imgproc.hpp 235 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946
  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. // Third party copyrights are property of their respective owners.
  16. //
  17. // Redistribution and use in source and binary forms, with or without modification,
  18. // are permitted provided that the following conditions are met:
  19. //
  20. // * Redistribution's of source code must retain the above copyright notice,
  21. // this list of conditions and the following disclaimer.
  22. //
  23. // * Redistribution's in binary form must reproduce the above copyright notice,
  24. // this list of conditions and the following disclaimer in the documentation
  25. // and/or other materials provided with the distribution.
  26. //
  27. // * The name of the copyright holders may not be used to endorse or promote products
  28. // derived from this software without specific prior written permission.
  29. //
  30. // This software is provided by the copyright holders and contributors "as is" and
  31. // any express or implied warranties, including, but not limited to, the implied
  32. // warranties of merchantability and fitness for a particular purpose are disclaimed.
  33. // In no event shall the Intel Corporation or contributors be liable for any direct,
  34. // indirect, incidental, special, exemplary, or consequential damages
  35. // (including, but not limited to, procurement of substitute goods or services;
  36. // loss of use, data, or profits; or business interruption) however caused
  37. // and on any theory of liability, whether in contract, strict liability,
  38. // or tort (including negligence or otherwise) arising in any way out of
  39. // the use of this software, even if advised of the possibility of such damage.
  40. //
  41. //M*/
  42. #ifndef OPENCV_IMGPROC_HPP
  43. #define OPENCV_IMGPROC_HPP
  44. #include "opencv2/core.hpp"
  45. /**
  46. @defgroup imgproc Image Processing
  47. This module includes image-processing functions.
  48. @{
  49. @defgroup imgproc_filter Image Filtering
  50. Functions and classes described in this section are used to perform various linear or non-linear
  51. filtering operations on 2D images (represented as Mat's). It means that for each pixel location
  52. \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to
  53. compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of
  54. morphological operations, it is the minimum or maximum values, and so on. The computed response is
  55. stored in the destination image at the same location \f$(x,y)\f$. It means that the output image
  56. will be of the same size as the input image. Normally, the functions support multi-channel arrays,
  57. in which case every channel is processed independently. Therefore, the output image will also have
  58. the same number of channels as the input one.
  59. Another common feature of the functions and classes described in this section is that, unlike
  60. simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For
  61. example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when
  62. processing the left-most pixels in each row, you need pixels to the left of them, that is, outside
  63. of the image. You can let these pixels be the same as the left-most image pixels ("replicated
  64. border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant
  65. border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method.
  66. For details, see #BorderTypes
  67. @anchor filter_depths
  68. ### Depth combinations
  69. Input depth (src.depth()) | Output depth (ddepth)
  70. --------------------------|----------------------
  71. CV_8U | -1/CV_16S/CV_32F/CV_64F
  72. CV_16U/CV_16S | -1/CV_32F/CV_64F
  73. CV_32F | -1/CV_32F/CV_64F
  74. CV_64F | -1/CV_64F
  75. @note when ddepth=-1, the output image will have the same depth as the source.
  76. @defgroup imgproc_transform Geometric Image Transformations
  77. The functions in this section perform various geometrical transformations of 2D images. They do not
  78. change the image content but deform the pixel grid and map this deformed grid to the destination
  79. image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from
  80. destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the
  81. functions compute coordinates of the corresponding "donor" pixel in the source image and copy the
  82. pixel value:
  83. \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f]
  84. In case when you specify the forward mapping \f$\left<g_x, g_y\right>: \texttt{src} \rightarrow
  85. \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping
  86. \f$\left<f_x, f_y\right>: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula.
  87. The actual implementations of the geometrical transformations, from the most generic remap and to
  88. the simplest and the fastest resize, need to solve two main problems with the above formula:
  89. - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the
  90. previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both
  91. of them may fall outside of the image. In this case, an extrapolation method needs to be used.
  92. OpenCV provides the same selection of extrapolation methods as in the filtering functions. In
  93. addition, it provides the method #BORDER_TRANSPARENT. This means that the corresponding pixels in
  94. the destination image will not be modified at all.
  95. - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point
  96. numbers. This means that \f$\left<f_x, f_y\right>\f$ can be either an affine or perspective
  97. transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional
  98. coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the
  99. nearest integer coordinates and the corresponding pixel can be used. This is called a
  100. nearest-neighbor interpolation. However, a better result can be achieved by using more
  101. sophisticated [interpolation methods](http://en.wikipedia.org/wiki/Multivariate_interpolation) ,
  102. where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y),
  103. f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the
  104. interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See
  105. resize for details.
  106. @note The geometrical transformations do not work with `CV_8S` or `CV_32S` images.
  107. @defgroup imgproc_misc Miscellaneous Image Transformations
  108. @defgroup imgproc_draw Drawing Functions
  109. Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be
  110. rendered with antialiasing (implemented only for 8-bit images for now). All the functions include
  111. the parameter color that uses an RGB value (that may be constructed with the Scalar constructor )
  112. for color images and brightness for grayscale images. For color images, the channel ordering is
  113. normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a
  114. color using the Scalar constructor, it should look like:
  115. \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f]
  116. If you are using your own image rendering and I/O functions, you can use any channel ordering. The
  117. drawing functions process each channel independently and do not depend on the channel order or even
  118. on the used color space. The whole image can be converted from BGR to RGB or to a different color
  119. space using cvtColor .
  120. If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also,
  121. many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means
  122. that the coordinates can be passed as fixed-point numbers encoded as integers. The number of
  123. fractional bits is specified by the shift parameter and the real point coordinates are calculated as
  124. \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is
  125. especially effective when rendering antialiased shapes.
  126. @note The functions do not support alpha-transparency when the target image is 4-channel. In this
  127. case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint
  128. semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main
  129. image.
  130. @defgroup imgproc_color_conversions Color Space Conversions
  131. @defgroup imgproc_colormap ColorMaps in OpenCV
  132. The human perception isn't built for observing fine changes in grayscale images. Human eyes are more
  133. sensitive to observing changes between colors, so you often need to recolor your grayscale images to
  134. get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your
  135. computer vision application.
  136. In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample
  137. code reads the path to an image from command line, applies a Jet colormap on it and shows the
  138. result:
  139. @include snippets/imgproc_applyColorMap.cpp
  140. @see #ColormapTypes
  141. @defgroup imgproc_subdiv2d Planar Subdivision
  142. The Subdiv2D class described in this section is used to perform various planar subdivision on
  143. a set of 2D points (represented as vector of Point2f). OpenCV subdivides a plane into triangles
  144. using the Delaunay's algorithm, which corresponds to the dual graph of the Voronoi diagram.
  145. In the figure below, the Delaunay's triangulation is marked with black lines and the Voronoi
  146. diagram with red lines.
  147. ![Delaunay triangulation (black) and Voronoi (red)](pics/delaunay_voronoi.png)
  148. The subdivisions can be used for the 3D piece-wise transformation of a plane, morphing, fast
  149. location of points on the plane, building special graphs (such as NNG,RNG), and so forth.
  150. @defgroup imgproc_hist Histograms
  151. @defgroup imgproc_shape Structural Analysis and Shape Descriptors
  152. @defgroup imgproc_motion Motion Analysis and Object Tracking
  153. @defgroup imgproc_feature Feature Detection
  154. @defgroup imgproc_object Object Detection
  155. @defgroup imgproc_c C API
  156. @defgroup imgproc_hal Hardware Acceleration Layer
  157. @{
  158. @defgroup imgproc_hal_functions Functions
  159. @defgroup imgproc_hal_interface Interface
  160. @}
  161. @}
  162. */
  163. namespace cv
  164. {
  165. /** @addtogroup imgproc
  166. @{
  167. */
  168. //! @addtogroup imgproc_filter
  169. //! @{
  170. //! type of morphological operation
  171. enum MorphTypes{
  172. MORPH_ERODE = 0, //!< see #erode
  173. MORPH_DILATE = 1, //!< see #dilate
  174. MORPH_OPEN = 2, //!< an opening operation
  175. //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f]
  176. MORPH_CLOSE = 3, //!< a closing operation
  177. //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f]
  178. MORPH_GRADIENT = 4, //!< a morphological gradient
  179. //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f]
  180. MORPH_TOPHAT = 5, //!< "top hat"
  181. //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f]
  182. MORPH_BLACKHAT = 6, //!< "black hat"
  183. //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f]
  184. MORPH_HITMISS = 7 //!< "hit or miss"
  185. //!< .- Only supported for CV_8UC1 binary images. A tutorial can be found in the documentation
  186. };
  187. //! shape of the structuring element
  188. enum MorphShapes {
  189. MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f]
  190. MORPH_CROSS = 1, //!< a cross-shaped structuring element:
  191. //!< \f[E_{ij} = \begin{cases} 1 & \texttt{if } {i=\texttt{anchor.y } {or } {j=\texttt{anchor.x}}} \\0 & \texttt{otherwise} \end{cases}\f]
  192. MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed
  193. //!< into the rectangle Rect(0, 0, esize.width, 0.esize.height)
  194. };
  195. //! @} imgproc_filter
  196. //! @addtogroup imgproc_transform
  197. //! @{
  198. //! interpolation algorithm
  199. enum InterpolationFlags{
  200. /** nearest neighbor interpolation */
  201. INTER_NEAREST = 0,
  202. /** bilinear interpolation */
  203. INTER_LINEAR = 1,
  204. /** bicubic interpolation */
  205. INTER_CUBIC = 2,
  206. /** resampling using pixel area relation. It may be a preferred method for image decimation, as
  207. it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST
  208. method. */
  209. INTER_AREA = 3,
  210. /** Lanczos interpolation over 8x8 neighborhood */
  211. INTER_LANCZOS4 = 4,
  212. /** Bit exact bilinear interpolation */
  213. INTER_LINEAR_EXACT = 5,
  214. /** Bit exact nearest neighbor interpolation. This will produce same results as
  215. the nearest neighbor method in PIL, scikit-image or Matlab. */
  216. INTER_NEAREST_EXACT = 6,
  217. /** mask for interpolation codes */
  218. INTER_MAX = 7,
  219. /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the
  220. source image, they are set to zero */
  221. WARP_FILL_OUTLIERS = 8,
  222. /** flag, inverse transformation
  223. For example, #linearPolar or #logPolar transforms:
  224. - flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$
  225. - flag is set: \f$dst(x,y) = src( \rho , \phi )\f$
  226. */
  227. WARP_INVERSE_MAP = 16
  228. };
  229. /** \brief Specify the polar mapping mode
  230. @sa warpPolar
  231. */
  232. enum WarpPolarMode
  233. {
  234. WARP_POLAR_LINEAR = 0, ///< Remaps an image to/from polar space.
  235. WARP_POLAR_LOG = 256 ///< Remaps an image to/from semilog-polar space.
  236. };
  237. enum InterpolationMasks {
  238. INTER_BITS = 5,
  239. INTER_BITS2 = INTER_BITS * 2,
  240. INTER_TAB_SIZE = 1 << INTER_BITS,
  241. INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE
  242. };
  243. //! @} imgproc_transform
  244. //! @addtogroup imgproc_misc
  245. //! @{
  246. //! Distance types for Distance Transform and M-estimators
  247. //! @see distanceTransform, fitLine
  248. enum DistanceTypes {
  249. DIST_USER = -1, //!< User defined distance
  250. DIST_L1 = 1, //!< distance = |x1-x2| + |y1-y2|
  251. DIST_L2 = 2, //!< the simple euclidean distance
  252. DIST_C = 3, //!< distance = max(|x1-x2|,|y1-y2|)
  253. DIST_L12 = 4, //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1))
  254. DIST_FAIR = 5, //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998
  255. DIST_WELSCH = 6, //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846
  256. DIST_HUBER = 7 //!< distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345
  257. };
  258. //! Mask size for distance transform
  259. enum DistanceTransformMasks {
  260. DIST_MASK_3 = 3, //!< mask=3
  261. DIST_MASK_5 = 5, //!< mask=5
  262. DIST_MASK_PRECISE = 0 //!<
  263. };
  264. //! type of the threshold operation
  265. //! ![threshold types](pics/threshold.png)
  266. enum ThresholdTypes {
  267. THRESH_BINARY = 0, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{maxval}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f]
  268. THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f]
  269. THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f]
  270. THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f]
  271. THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f]
  272. THRESH_MASK = 7,
  273. THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value
  274. THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value
  275. };
  276. //! adaptive threshold algorithm
  277. //! @see adaptiveThreshold
  278. enum AdaptiveThresholdTypes {
  279. /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times
  280. \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */
  281. ADAPTIVE_THRESH_MEAN_C = 0,
  282. /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian
  283. window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$
  284. minus C . The default sigma (standard deviation) is used for the specified blockSize . See
  285. #getGaussianKernel*/
  286. ADAPTIVE_THRESH_GAUSSIAN_C = 1
  287. };
  288. //! cv::undistort mode
  289. enum UndistortTypes {
  290. PROJ_SPHERICAL_ORTHO = 0,
  291. PROJ_SPHERICAL_EQRECT = 1
  292. };
  293. //! class of the pixel in GrabCut algorithm
  294. enum GrabCutClasses {
  295. GC_BGD = 0, //!< an obvious background pixels
  296. GC_FGD = 1, //!< an obvious foreground (object) pixel
  297. GC_PR_BGD = 2, //!< a possible background pixel
  298. GC_PR_FGD = 3 //!< a possible foreground pixel
  299. };
  300. //! GrabCut algorithm flags
  301. enum GrabCutModes {
  302. /** The function initializes the state and the mask using the provided rectangle. After that it
  303. runs iterCount iterations of the algorithm. */
  304. GC_INIT_WITH_RECT = 0,
  305. /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT
  306. and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are
  307. automatically initialized with GC_BGD .*/
  308. GC_INIT_WITH_MASK = 1,
  309. /** The value means that the algorithm should just resume. */
  310. GC_EVAL = 2,
  311. /** The value means that the algorithm should just run the grabCut algorithm (a single iteration) with the fixed model */
  312. GC_EVAL_FREEZE_MODEL = 3
  313. };
  314. //! distanceTransform algorithm flags
  315. enum DistanceTransformLabelTypes {
  316. /** each connected component of zeros in src (as well as all the non-zero pixels closest to the
  317. connected component) will be assigned the same label */
  318. DIST_LABEL_CCOMP = 0,
  319. /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */
  320. DIST_LABEL_PIXEL = 1
  321. };
  322. //! floodfill algorithm flags
  323. enum FloodFillFlags {
  324. /** If set, the difference between the current pixel and seed pixel is considered. Otherwise,
  325. the difference between neighbor pixels is considered (that is, the range is floating). */
  326. FLOODFILL_FIXED_RANGE = 1 << 16,
  327. /** If set, the function does not change the image ( newVal is ignored), and only fills the
  328. mask with the value specified in bits 8-16 of flags as described above. This option only make
  329. sense in function variants that have the mask parameter. */
  330. FLOODFILL_MASK_ONLY = 1 << 17
  331. };
  332. //! @} imgproc_misc
  333. //! @addtogroup imgproc_shape
  334. //! @{
  335. //! connected components statistics
  336. enum ConnectedComponentsTypes {
  337. CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding
  338. //!< box in the horizontal direction.
  339. CC_STAT_TOP = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding
  340. //!< box in the vertical direction.
  341. CC_STAT_WIDTH = 2, //!< The horizontal size of the bounding box
  342. CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box
  343. CC_STAT_AREA = 4, //!< The total area (in pixels) of the connected component
  344. #ifndef CV_DOXYGEN
  345. CC_STAT_MAX = 5 //!< Max enumeration value. Used internally only for memory allocation
  346. #endif
  347. };
  348. //! connected components algorithm
  349. enum ConnectedComponentsAlgorithmsTypes {
  350. CCL_WU = 0, //!< SAUF @cite Wu2009 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity
  351. CCL_DEFAULT = -1, //!< BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity
  352. CCL_GRANA = 1 //!< BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity
  353. };
  354. //! mode of the contour retrieval algorithm
  355. enum RetrievalModes {
  356. /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for
  357. all the contours. */
  358. RETR_EXTERNAL = 0,
  359. /** retrieves all of the contours without establishing any hierarchical relationships. */
  360. RETR_LIST = 1,
  361. /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top
  362. level, there are external boundaries of the components. At the second level, there are
  363. boundaries of the holes. If there is another contour inside a hole of a connected component, it
  364. is still put at the top level. */
  365. RETR_CCOMP = 2,
  366. /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/
  367. RETR_TREE = 3,
  368. RETR_FLOODFILL = 4 //!<
  369. };
  370. //! the contour approximation algorithm
  371. enum ContourApproximationModes {
  372. /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and
  373. (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is,
  374. max(abs(x1-x2),abs(y2-y1))==1. */
  375. CHAIN_APPROX_NONE = 1,
  376. /** compresses horizontal, vertical, and diagonal segments and leaves only their end points.
  377. For example, an up-right rectangular contour is encoded with 4 points. */
  378. CHAIN_APPROX_SIMPLE = 2,
  379. /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */
  380. CHAIN_APPROX_TC89_L1 = 3,
  381. /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */
  382. CHAIN_APPROX_TC89_KCOS = 4
  383. };
  384. /** @brief Shape matching methods
  385. \f$A\f$ denotes object1,\f$B\f$ denotes object2
  386. \f$\begin{array}{l} m^A_i = \mathrm{sign} (h^A_i) \cdot \log{h^A_i} \\ m^B_i = \mathrm{sign} (h^B_i) \cdot \log{h^B_i} \end{array}\f$
  387. and \f$h^A_i, h^B_i\f$ are the Hu moments of \f$A\f$ and \f$B\f$ , respectively.
  388. */
  389. enum ShapeMatchModes {
  390. CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f]
  391. CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f]
  392. CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f]
  393. };
  394. //! @} imgproc_shape
  395. //! @addtogroup imgproc_feature
  396. //! @{
  397. //! Variants of a Hough transform
  398. enum HoughModes {
  399. /** classical or standard Hough transform. Every line is represented by two floating-point
  400. numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line,
  401. and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must
  402. be (the created sequence will be) of CV_32FC2 type */
  403. HOUGH_STANDARD = 0,
  404. /** probabilistic Hough transform (more efficient in case if the picture contains a few long
  405. linear segments). It returns line segments rather than the whole line. Each segment is
  406. represented by starting and ending points, and the matrix must be (the created sequence will
  407. be) of the CV_32SC4 type. */
  408. HOUGH_PROBABILISTIC = 1,
  409. /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as
  410. HOUGH_STANDARD. */
  411. HOUGH_MULTI_SCALE = 2,
  412. HOUGH_GRADIENT = 3 //!< basically *21HT*, described in @cite Yuen90
  413. };
  414. //! Variants of Line Segment %Detector
  415. enum LineSegmentDetectorModes {
  416. LSD_REFINE_NONE = 0, //!< No refinement applied
  417. LSD_REFINE_STD = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations.
  418. LSD_REFINE_ADV = 2 //!< Advanced refinement. Number of false alarms is calculated, lines are
  419. //!< refined through increase of precision, decrement in size, etc.
  420. };
  421. //! @} imgproc_feature
  422. /** Histogram comparison methods
  423. @ingroup imgproc_hist
  424. */
  425. enum HistCompMethods {
  426. /** Correlation
  427. \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f]
  428. where
  429. \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f]
  430. and \f$N\f$ is a total number of histogram bins. */
  431. HISTCMP_CORREL = 0,
  432. /** Chi-Square
  433. \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */
  434. HISTCMP_CHISQR = 1,
  435. /** Intersection
  436. \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] */
  437. HISTCMP_INTERSECT = 2,
  438. /** Bhattacharyya distance
  439. (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.)
  440. \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */
  441. HISTCMP_BHATTACHARYYA = 3,
  442. HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA
  443. /** Alternative Chi-Square
  444. \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f]
  445. This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */
  446. HISTCMP_CHISQR_ALT = 4,
  447. /** Kullback-Leibler divergence
  448. \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */
  449. HISTCMP_KL_DIV = 5
  450. };
  451. /** the color conversion codes
  452. @see @ref imgproc_color_conversions
  453. @ingroup imgproc_color_conversions
  454. */
  455. enum ColorConversionCodes {
  456. COLOR_BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image
  457. COLOR_RGB2RGBA = COLOR_BGR2BGRA,
  458. COLOR_BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image
  459. COLOR_RGBA2RGB = COLOR_BGRA2BGR,
  460. COLOR_BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel)
  461. COLOR_RGB2BGRA = COLOR_BGR2RGBA,
  462. COLOR_RGBA2BGR = 3,
  463. COLOR_BGRA2RGB = COLOR_RGBA2BGR,
  464. COLOR_BGR2RGB = 4,
  465. COLOR_RGB2BGR = COLOR_BGR2RGB,
  466. COLOR_BGRA2RGBA = 5,
  467. COLOR_RGBA2BGRA = COLOR_BGRA2RGBA,
  468. COLOR_BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions"
  469. COLOR_RGB2GRAY = 7,
  470. COLOR_GRAY2BGR = 8,
  471. COLOR_GRAY2RGB = COLOR_GRAY2BGR,
  472. COLOR_GRAY2BGRA = 9,
  473. COLOR_GRAY2RGBA = COLOR_GRAY2BGRA,
  474. COLOR_BGRA2GRAY = 10,
  475. COLOR_RGBA2GRAY = 11,
  476. COLOR_BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images)
  477. COLOR_RGB2BGR565 = 13,
  478. COLOR_BGR5652BGR = 14,
  479. COLOR_BGR5652RGB = 15,
  480. COLOR_BGRA2BGR565 = 16,
  481. COLOR_RGBA2BGR565 = 17,
  482. COLOR_BGR5652BGRA = 18,
  483. COLOR_BGR5652RGBA = 19,
  484. COLOR_GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images)
  485. COLOR_BGR5652GRAY = 21,
  486. COLOR_BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images)
  487. COLOR_RGB2BGR555 = 23,
  488. COLOR_BGR5552BGR = 24,
  489. COLOR_BGR5552RGB = 25,
  490. COLOR_BGRA2BGR555 = 26,
  491. COLOR_RGBA2BGR555 = 27,
  492. COLOR_BGR5552BGRA = 28,
  493. COLOR_BGR5552RGBA = 29,
  494. COLOR_GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images)
  495. COLOR_BGR5552GRAY = 31,
  496. COLOR_BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions"
  497. COLOR_RGB2XYZ = 33,
  498. COLOR_XYZ2BGR = 34,
  499. COLOR_XYZ2RGB = 35,
  500. COLOR_BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions"
  501. COLOR_RGB2YCrCb = 37,
  502. COLOR_YCrCb2BGR = 38,
  503. COLOR_YCrCb2RGB = 39,
  504. COLOR_BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value), @ref color_convert_rgb_hsv "color conversions"
  505. COLOR_RGB2HSV = 41,
  506. COLOR_BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions"
  507. COLOR_RGB2Lab = 45,
  508. COLOR_BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions"
  509. COLOR_RGB2Luv = 51,
  510. COLOR_BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation), @ref color_convert_rgb_hls "color conversions"
  511. COLOR_RGB2HLS = 53,
  512. COLOR_HSV2BGR = 54, //!< backward conversions to RGB/BGR
  513. COLOR_HSV2RGB = 55,
  514. COLOR_Lab2BGR = 56,
  515. COLOR_Lab2RGB = 57,
  516. COLOR_Luv2BGR = 58,
  517. COLOR_Luv2RGB = 59,
  518. COLOR_HLS2BGR = 60,
  519. COLOR_HLS2RGB = 61,
  520. COLOR_BGR2HSV_FULL = 66,
  521. COLOR_RGB2HSV_FULL = 67,
  522. COLOR_BGR2HLS_FULL = 68,
  523. COLOR_RGB2HLS_FULL = 69,
  524. COLOR_HSV2BGR_FULL = 70,
  525. COLOR_HSV2RGB_FULL = 71,
  526. COLOR_HLS2BGR_FULL = 72,
  527. COLOR_HLS2RGB_FULL = 73,
  528. COLOR_LBGR2Lab = 74,
  529. COLOR_LRGB2Lab = 75,
  530. COLOR_LBGR2Luv = 76,
  531. COLOR_LRGB2Luv = 77,
  532. COLOR_Lab2LBGR = 78,
  533. COLOR_Lab2LRGB = 79,
  534. COLOR_Luv2LBGR = 80,
  535. COLOR_Luv2LRGB = 81,
  536. COLOR_BGR2YUV = 82, //!< convert between RGB/BGR and YUV
  537. COLOR_RGB2YUV = 83,
  538. COLOR_YUV2BGR = 84,
  539. COLOR_YUV2RGB = 85,
  540. //! YUV 4:2:0 family to RGB
  541. COLOR_YUV2RGB_NV12 = 90,
  542. COLOR_YUV2BGR_NV12 = 91,
  543. COLOR_YUV2RGB_NV21 = 92,
  544. COLOR_YUV2BGR_NV21 = 93,
  545. COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21,
  546. COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21,
  547. COLOR_YUV2RGBA_NV12 = 94,
  548. COLOR_YUV2BGRA_NV12 = 95,
  549. COLOR_YUV2RGBA_NV21 = 96,
  550. COLOR_YUV2BGRA_NV21 = 97,
  551. COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21,
  552. COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21,
  553. COLOR_YUV2RGB_YV12 = 98,
  554. COLOR_YUV2BGR_YV12 = 99,
  555. COLOR_YUV2RGB_IYUV = 100,
  556. COLOR_YUV2BGR_IYUV = 101,
  557. COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV,
  558. COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV,
  559. COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12,
  560. COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12,
  561. COLOR_YUV2RGBA_YV12 = 102,
  562. COLOR_YUV2BGRA_YV12 = 103,
  563. COLOR_YUV2RGBA_IYUV = 104,
  564. COLOR_YUV2BGRA_IYUV = 105,
  565. COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV,
  566. COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV,
  567. COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12,
  568. COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12,
  569. COLOR_YUV2GRAY_420 = 106,
  570. COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420,
  571. COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420,
  572. COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420,
  573. COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420,
  574. COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420,
  575. COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420,
  576. COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420,
  577. //! YUV 4:2:2 family to RGB
  578. COLOR_YUV2RGB_UYVY = 107,
  579. COLOR_YUV2BGR_UYVY = 108,
  580. //COLOR_YUV2RGB_VYUY = 109,
  581. //COLOR_YUV2BGR_VYUY = 110,
  582. COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY,
  583. COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY,
  584. COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY,
  585. COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY,
  586. COLOR_YUV2RGBA_UYVY = 111,
  587. COLOR_YUV2BGRA_UYVY = 112,
  588. //COLOR_YUV2RGBA_VYUY = 113,
  589. //COLOR_YUV2BGRA_VYUY = 114,
  590. COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY,
  591. COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY,
  592. COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY,
  593. COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY,
  594. COLOR_YUV2RGB_YUY2 = 115,
  595. COLOR_YUV2BGR_YUY2 = 116,
  596. COLOR_YUV2RGB_YVYU = 117,
  597. COLOR_YUV2BGR_YVYU = 118,
  598. COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2,
  599. COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2,
  600. COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2,
  601. COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2,
  602. COLOR_YUV2RGBA_YUY2 = 119,
  603. COLOR_YUV2BGRA_YUY2 = 120,
  604. COLOR_YUV2RGBA_YVYU = 121,
  605. COLOR_YUV2BGRA_YVYU = 122,
  606. COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2,
  607. COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2,
  608. COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2,
  609. COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2,
  610. COLOR_YUV2GRAY_UYVY = 123,
  611. COLOR_YUV2GRAY_YUY2 = 124,
  612. //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY,
  613. COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY,
  614. COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY,
  615. COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2,
  616. COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2,
  617. COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2,
  618. //! alpha premultiplication
  619. COLOR_RGBA2mRGBA = 125,
  620. COLOR_mRGBA2RGBA = 126,
  621. //! RGB to YUV 4:2:0 family
  622. COLOR_RGB2YUV_I420 = 127,
  623. COLOR_BGR2YUV_I420 = 128,
  624. COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420,
  625. COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420,
  626. COLOR_RGBA2YUV_I420 = 129,
  627. COLOR_BGRA2YUV_I420 = 130,
  628. COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420,
  629. COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420,
  630. COLOR_RGB2YUV_YV12 = 131,
  631. COLOR_BGR2YUV_YV12 = 132,
  632. COLOR_RGBA2YUV_YV12 = 133,
  633. COLOR_BGRA2YUV_YV12 = 134,
  634. //! Demosaicing
  635. COLOR_BayerBG2BGR = 46,
  636. COLOR_BayerGB2BGR = 47,
  637. COLOR_BayerRG2BGR = 48,
  638. COLOR_BayerGR2BGR = 49,
  639. COLOR_BayerBG2RGB = COLOR_BayerRG2BGR,
  640. COLOR_BayerGB2RGB = COLOR_BayerGR2BGR,
  641. COLOR_BayerRG2RGB = COLOR_BayerBG2BGR,
  642. COLOR_BayerGR2RGB = COLOR_BayerGB2BGR,
  643. COLOR_BayerBG2GRAY = 86,
  644. COLOR_BayerGB2GRAY = 87,
  645. COLOR_BayerRG2GRAY = 88,
  646. COLOR_BayerGR2GRAY = 89,
  647. //! Demosaicing using Variable Number of Gradients
  648. COLOR_BayerBG2BGR_VNG = 62,
  649. COLOR_BayerGB2BGR_VNG = 63,
  650. COLOR_BayerRG2BGR_VNG = 64,
  651. COLOR_BayerGR2BGR_VNG = 65,
  652. COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG,
  653. COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG,
  654. COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG,
  655. COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG,
  656. //! Edge-Aware Demosaicing
  657. COLOR_BayerBG2BGR_EA = 135,
  658. COLOR_BayerGB2BGR_EA = 136,
  659. COLOR_BayerRG2BGR_EA = 137,
  660. COLOR_BayerGR2BGR_EA = 138,
  661. COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA,
  662. COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA,
  663. COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA,
  664. COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA,
  665. //! Demosaicing with alpha channel
  666. COLOR_BayerBG2BGRA = 139,
  667. COLOR_BayerGB2BGRA = 140,
  668. COLOR_BayerRG2BGRA = 141,
  669. COLOR_BayerGR2BGRA = 142,
  670. COLOR_BayerBG2RGBA = COLOR_BayerRG2BGRA,
  671. COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA,
  672. COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA,
  673. COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA,
  674. COLOR_COLORCVT_MAX = 143
  675. };
  676. //! @addtogroup imgproc_shape
  677. //! @{
  678. //! types of intersection between rectangles
  679. enum RectanglesIntersectTypes {
  680. INTERSECT_NONE = 0, //!< No intersection
  681. INTERSECT_PARTIAL = 1, //!< There is a partial intersection
  682. INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other
  683. };
  684. /** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform
  685. */
  686. class CV_EXPORTS_W GeneralizedHough : public Algorithm
  687. {
  688. public:
  689. //! set template to search
  690. CV_WRAP virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0;
  691. CV_WRAP virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0;
  692. //! find template on image
  693. CV_WRAP virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0;
  694. CV_WRAP virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0;
  695. //! Canny low threshold.
  696. CV_WRAP virtual void setCannyLowThresh(int cannyLowThresh) = 0;
  697. CV_WRAP virtual int getCannyLowThresh() const = 0;
  698. //! Canny high threshold.
  699. CV_WRAP virtual void setCannyHighThresh(int cannyHighThresh) = 0;
  700. CV_WRAP virtual int getCannyHighThresh() const = 0;
  701. //! Minimum distance between the centers of the detected objects.
  702. CV_WRAP virtual void setMinDist(double minDist) = 0;
  703. CV_WRAP virtual double getMinDist() const = 0;
  704. //! Inverse ratio of the accumulator resolution to the image resolution.
  705. CV_WRAP virtual void setDp(double dp) = 0;
  706. CV_WRAP virtual double getDp() const = 0;
  707. //! Maximal size of inner buffers.
  708. CV_WRAP virtual void setMaxBufferSize(int maxBufferSize) = 0;
  709. CV_WRAP virtual int getMaxBufferSize() const = 0;
  710. };
  711. /** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform
  712. Detects position only without translation and rotation @cite Ballard1981 .
  713. */
  714. class CV_EXPORTS_W GeneralizedHoughBallard : public GeneralizedHough
  715. {
  716. public:
  717. //! R-Table levels.
  718. CV_WRAP virtual void setLevels(int levels) = 0;
  719. CV_WRAP virtual int getLevels() const = 0;
  720. //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected.
  721. CV_WRAP virtual void setVotesThreshold(int votesThreshold) = 0;
  722. CV_WRAP virtual int getVotesThreshold() const = 0;
  723. };
  724. /** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform
  725. Detects position, translation and rotation @cite Guil1999 .
  726. */
  727. class CV_EXPORTS_W GeneralizedHoughGuil : public GeneralizedHough
  728. {
  729. public:
  730. //! Angle difference in degrees between two points in feature.
  731. CV_WRAP virtual void setXi(double xi) = 0;
  732. CV_WRAP virtual double getXi() const = 0;
  733. //! Feature table levels.
  734. CV_WRAP virtual void setLevels(int levels) = 0;
  735. CV_WRAP virtual int getLevels() const = 0;
  736. //! Maximal difference between angles that treated as equal.
  737. CV_WRAP virtual void setAngleEpsilon(double angleEpsilon) = 0;
  738. CV_WRAP virtual double getAngleEpsilon() const = 0;
  739. //! Minimal rotation angle to detect in degrees.
  740. CV_WRAP virtual void setMinAngle(double minAngle) = 0;
  741. CV_WRAP virtual double getMinAngle() const = 0;
  742. //! Maximal rotation angle to detect in degrees.
  743. CV_WRAP virtual void setMaxAngle(double maxAngle) = 0;
  744. CV_WRAP virtual double getMaxAngle() const = 0;
  745. //! Angle step in degrees.
  746. CV_WRAP virtual void setAngleStep(double angleStep) = 0;
  747. CV_WRAP virtual double getAngleStep() const = 0;
  748. //! Angle votes threshold.
  749. CV_WRAP virtual void setAngleThresh(int angleThresh) = 0;
  750. CV_WRAP virtual int getAngleThresh() const = 0;
  751. //! Minimal scale to detect.
  752. CV_WRAP virtual void setMinScale(double minScale) = 0;
  753. CV_WRAP virtual double getMinScale() const = 0;
  754. //! Maximal scale to detect.
  755. CV_WRAP virtual void setMaxScale(double maxScale) = 0;
  756. CV_WRAP virtual double getMaxScale() const = 0;
  757. //! Scale step.
  758. CV_WRAP virtual void setScaleStep(double scaleStep) = 0;
  759. CV_WRAP virtual double getScaleStep() const = 0;
  760. //! Scale votes threshold.
  761. CV_WRAP virtual void setScaleThresh(int scaleThresh) = 0;
  762. CV_WRAP virtual int getScaleThresh() const = 0;
  763. //! Position votes threshold.
  764. CV_WRAP virtual void setPosThresh(int posThresh) = 0;
  765. CV_WRAP virtual int getPosThresh() const = 0;
  766. };
  767. //! @} imgproc_shape
  768. //! @addtogroup imgproc_hist
  769. //! @{
  770. /** @brief Base class for Contrast Limited Adaptive Histogram Equalization.
  771. */
  772. class CV_EXPORTS_W CLAHE : public Algorithm
  773. {
  774. public:
  775. /** @brief Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization.
  776. @param src Source image of type CV_8UC1 or CV_16UC1.
  777. @param dst Destination image.
  778. */
  779. CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0;
  780. /** @brief Sets threshold for contrast limiting.
  781. @param clipLimit threshold value.
  782. */
  783. CV_WRAP virtual void setClipLimit(double clipLimit) = 0;
  784. //! Returns threshold value for contrast limiting.
  785. CV_WRAP virtual double getClipLimit() const = 0;
  786. /** @brief Sets size of grid for histogram equalization. Input image will be divided into
  787. equally sized rectangular tiles.
  788. @param tileGridSize defines the number of tiles in row and column.
  789. */
  790. CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0;
  791. //!@brief Returns Size defines the number of tiles in row and column.
  792. CV_WRAP virtual Size getTilesGridSize() const = 0;
  793. CV_WRAP virtual void collectGarbage() = 0;
  794. };
  795. //! @} imgproc_hist
  796. //! @addtogroup imgproc_subdiv2d
  797. //! @{
  798. class CV_EXPORTS_W Subdiv2D
  799. {
  800. public:
  801. /** Subdiv2D point location cases */
  802. enum { PTLOC_ERROR = -2, //!< Point location error
  803. PTLOC_OUTSIDE_RECT = -1, //!< Point outside the subdivision bounding rect
  804. PTLOC_INSIDE = 0, //!< Point inside some facet
  805. PTLOC_VERTEX = 1, //!< Point coincides with one of the subdivision vertices
  806. PTLOC_ON_EDGE = 2 //!< Point on some edge
  807. };
  808. /** Subdiv2D edge type navigation (see: getEdge()) */
  809. enum { NEXT_AROUND_ORG = 0x00,
  810. NEXT_AROUND_DST = 0x22,
  811. PREV_AROUND_ORG = 0x11,
  812. PREV_AROUND_DST = 0x33,
  813. NEXT_AROUND_LEFT = 0x13,
  814. NEXT_AROUND_RIGHT = 0x31,
  815. PREV_AROUND_LEFT = 0x20,
  816. PREV_AROUND_RIGHT = 0x02
  817. };
  818. /** creates an empty Subdiv2D object.
  819. To create a new empty Delaunay subdivision you need to use the #initDelaunay function.
  820. */
  821. CV_WRAP Subdiv2D();
  822. /** @overload
  823. @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision.
  824. The function creates an empty Delaunay subdivision where 2D points can be added using the function
  825. insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime
  826. error is raised.
  827. */
  828. CV_WRAP Subdiv2D(Rect rect);
  829. /** @brief Creates a new empty Delaunay subdivision
  830. @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision.
  831. */
  832. CV_WRAP void initDelaunay(Rect rect);
  833. /** @brief Insert a single point into a Delaunay triangulation.
  834. @param pt Point to insert.
  835. The function inserts a single point into a subdivision and modifies the subdivision topology
  836. appropriately. If a point with the same coordinates exists already, no new point is added.
  837. @returns the ID of the point.
  838. @note If the point is outside of the triangulation specified rect a runtime error is raised.
  839. */
  840. CV_WRAP int insert(Point2f pt);
  841. /** @brief Insert multiple points into a Delaunay triangulation.
  842. @param ptvec Points to insert.
  843. The function inserts a vector of points into a subdivision and modifies the subdivision topology
  844. appropriately.
  845. */
  846. CV_WRAP void insert(const std::vector<Point2f>& ptvec);
  847. /** @brief Returns the location of a point within a Delaunay triangulation.
  848. @param pt Point to locate.
  849. @param edge Output edge that the point belongs to or is located to the right of it.
  850. @param vertex Optional output vertex the input point coincides with.
  851. The function locates the input point within the subdivision and gives one of the triangle edges
  852. or vertices.
  853. @returns an integer which specify one of the following five cases for point location:
  854. - The point falls into some facet. The function returns #PTLOC_INSIDE and edge will contain one of
  855. edges of the facet.
  856. - The point falls onto the edge. The function returns #PTLOC_ON_EDGE and edge will contain this edge.
  857. - The point coincides with one of the subdivision vertices. The function returns #PTLOC_VERTEX and
  858. vertex will contain a pointer to the vertex.
  859. - The point is outside the subdivision reference rectangle. The function returns #PTLOC_OUTSIDE_RECT
  860. and no pointers are filled.
  861. - One of input arguments is invalid. A runtime error is raised or, if silent or "parent" error
  862. processing mode is selected, #PTLOC_ERROR is returned.
  863. */
  864. CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex);
  865. /** @brief Finds the subdivision vertex closest to the given point.
  866. @param pt Input point.
  867. @param nearestPt Output subdivision vertex point.
  868. The function is another function that locates the input point within the subdivision. It finds the
  869. subdivision vertex that is the closest to the input point. It is not necessarily one of vertices
  870. of the facet containing the input point, though the facet (located using locate() ) is used as a
  871. starting point.
  872. @returns vertex ID.
  873. */
  874. CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0);
  875. /** @brief Returns a list of all edges.
  876. @param edgeList Output vector.
  877. The function gives each edge as a 4 numbers vector, where each two are one of the edge
  878. vertices. i.e. org_x = v[0], org_y = v[1], dst_x = v[2], dst_y = v[3].
  879. */
  880. CV_WRAP void getEdgeList(CV_OUT std::vector<Vec4f>& edgeList) const;
  881. /** @brief Returns a list of the leading edge ID connected to each triangle.
  882. @param leadingEdgeList Output vector.
  883. The function gives one edge ID for each triangle.
  884. */
  885. CV_WRAP void getLeadingEdgeList(CV_OUT std::vector<int>& leadingEdgeList) const;
  886. /** @brief Returns a list of all triangles.
  887. @param triangleList Output vector.
  888. The function gives each triangle as a 6 numbers vector, where each two are one of the triangle
  889. vertices. i.e. p1_x = v[0], p1_y = v[1], p2_x = v[2], p2_y = v[3], p3_x = v[4], p3_y = v[5].
  890. */
  891. CV_WRAP void getTriangleList(CV_OUT std::vector<Vec6f>& triangleList) const;
  892. /** @brief Returns a list of all Voronoi facets.
  893. @param idx Vector of vertices IDs to consider. For all vertices you can pass empty vector.
  894. @param facetList Output vector of the Voronoi facets.
  895. @param facetCenters Output vector of the Voronoi facets center points.
  896. */
  897. CV_WRAP void getVoronoiFacetList(const std::vector<int>& idx, CV_OUT std::vector<std::vector<Point2f> >& facetList,
  898. CV_OUT std::vector<Point2f>& facetCenters);
  899. /** @brief Returns vertex location from vertex ID.
  900. @param vertex vertex ID.
  901. @param firstEdge Optional. The first edge ID which is connected to the vertex.
  902. @returns vertex (x,y)
  903. */
  904. CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const;
  905. /** @brief Returns one of the edges related to the given edge.
  906. @param edge Subdivision edge ID.
  907. @param nextEdgeType Parameter specifying which of the related edges to return.
  908. The following values are possible:
  909. - NEXT_AROUND_ORG next around the edge origin ( eOnext on the picture below if e is the input edge)
  910. - NEXT_AROUND_DST next around the edge vertex ( eDnext )
  911. - PREV_AROUND_ORG previous around the edge origin (reversed eRnext )
  912. - PREV_AROUND_DST previous around the edge destination (reversed eLnext )
  913. - NEXT_AROUND_LEFT next around the left facet ( eLnext )
  914. - NEXT_AROUND_RIGHT next around the right facet ( eRnext )
  915. - PREV_AROUND_LEFT previous around the left facet (reversed eOnext )
  916. - PREV_AROUND_RIGHT previous around the right facet (reversed eDnext )
  917. ![sample output](pics/quadedge.png)
  918. @returns edge ID related to the input edge.
  919. */
  920. CV_WRAP int getEdge( int edge, int nextEdgeType ) const;
  921. /** @brief Returns next edge around the edge origin.
  922. @param edge Subdivision edge ID.
  923. @returns an integer which is next edge ID around the edge origin: eOnext on the
  924. picture above if e is the input edge).
  925. */
  926. CV_WRAP int nextEdge(int edge) const;
  927. /** @brief Returns another edge of the same quad-edge.
  928. @param edge Subdivision edge ID.
  929. @param rotate Parameter specifying which of the edges of the same quad-edge as the input
  930. one to return. The following values are possible:
  931. - 0 - the input edge ( e on the picture below if e is the input edge)
  932. - 1 - the rotated edge ( eRot )
  933. - 2 - the reversed edge (reversed e (in green))
  934. - 3 - the reversed rotated edge (reversed eRot (in green))
  935. @returns one of the edges ID of the same quad-edge as the input edge.
  936. */
  937. CV_WRAP int rotateEdge(int edge, int rotate) const;
  938. CV_WRAP int symEdge(int edge) const;
  939. /** @brief Returns the edge origin.
  940. @param edge Subdivision edge ID.
  941. @param orgpt Output vertex location.
  942. @returns vertex ID.
  943. */
  944. CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const;
  945. /** @brief Returns the edge destination.
  946. @param edge Subdivision edge ID.
  947. @param dstpt Output vertex location.
  948. @returns vertex ID.
  949. */
  950. CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const;
  951. protected:
  952. int newEdge();
  953. void deleteEdge(int edge);
  954. int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0);
  955. void deletePoint(int vtx);
  956. void setEdgePoints( int edge, int orgPt, int dstPt );
  957. void splice( int edgeA, int edgeB );
  958. int connectEdges( int edgeA, int edgeB );
  959. void swapEdges( int edge );
  960. int isRightOf(Point2f pt, int edge) const;
  961. void calcVoronoi();
  962. void clearVoronoi();
  963. void checkSubdiv() const;
  964. struct CV_EXPORTS Vertex
  965. {
  966. Vertex();
  967. Vertex(Point2f pt, bool _isvirtual, int _firstEdge=0);
  968. bool isvirtual() const;
  969. bool isfree() const;
  970. int firstEdge;
  971. int type;
  972. Point2f pt;
  973. };
  974. struct CV_EXPORTS QuadEdge
  975. {
  976. QuadEdge();
  977. QuadEdge(int edgeidx);
  978. bool isfree() const;
  979. int next[4];
  980. int pt[4];
  981. };
  982. //! All of the vertices
  983. std::vector<Vertex> vtx;
  984. //! All of the edges
  985. std::vector<QuadEdge> qedges;
  986. int freeQEdge;
  987. int freePoint;
  988. bool validGeometry;
  989. int recentEdge;
  990. //! Top left corner of the bounding rect
  991. Point2f topLeft;
  992. //! Bottom right corner of the bounding rect
  993. Point2f bottomRight;
  994. };
  995. //! @} imgproc_subdiv2d
  996. //! @addtogroup imgproc_feature
  997. //! @{
  998. /** @brief Line segment detector class
  999. following the algorithm described at @cite Rafael12 .
  1000. @note Implementation has been removed due original code license conflict
  1001. */
  1002. class CV_EXPORTS_W LineSegmentDetector : public Algorithm
  1003. {
  1004. public:
  1005. /** @brief Finds lines in the input image.
  1006. This is the output of the default parameters of the algorithm on the above shown image.
  1007. ![image](pics/building_lsd.png)
  1008. @param _image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use:
  1009. `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);`
  1010. @param _lines A vector of Vec4i or Vec4f elements specifying the beginning and ending point of a line. Where
  1011. Vec4i/Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly
  1012. oriented depending on the gradient.
  1013. @param width Vector of widths of the regions, where the lines are found. E.g. Width of line.
  1014. @param prec Vector of precisions with which the lines are found.
  1015. @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The
  1016. bigger the value, logarithmically better the detection.
  1017. - -1 corresponds to 10 mean false alarms
  1018. - 0 corresponds to 1 mean false alarm
  1019. - 1 corresponds to 0.1 mean false alarms
  1020. This vector will be calculated only when the objects type is #LSD_REFINE_ADV.
  1021. */
  1022. CV_WRAP virtual void detect(InputArray _image, OutputArray _lines,
  1023. OutputArray width = noArray(), OutputArray prec = noArray(),
  1024. OutputArray nfa = noArray()) = 0;
  1025. /** @brief Draws the line segments on a given image.
  1026. @param _image The image, where the lines will be drawn. Should be bigger or equal to the image,
  1027. where the lines were found.
  1028. @param lines A vector of the lines that needed to be drawn.
  1029. */
  1030. CV_WRAP virtual void drawSegments(InputOutputArray _image, InputArray lines) = 0;
  1031. /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels.
  1032. @param size The size of the image, where lines1 and lines2 were found.
  1033. @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color.
  1034. @param lines2 The second group of lines. They visualized in red color.
  1035. @param _image Optional image, where the lines will be drawn. The image should be color(3-channel)
  1036. in order for lines1 and lines2 to be drawn in the above mentioned colors.
  1037. */
  1038. CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray _image = noArray()) = 0;
  1039. virtual ~LineSegmentDetector() { }
  1040. };
  1041. /** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it.
  1042. The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want
  1043. to edit those, as to tailor it for their own application.
  1044. @param _refine The way found lines will be refined, see #LineSegmentDetectorModes
  1045. @param _scale The scale of the image that will be used to find the lines. Range (0..1].
  1046. @param _sigma_scale Sigma for Gaussian filter. It is computed as sigma = _sigma_scale/_scale.
  1047. @param _quant Bound to the quantization error on the gradient norm.
  1048. @param _ang_th Gradient angle tolerance in degrees.
  1049. @param _log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advance refinement
  1050. is chosen.
  1051. @param _density_th Minimal density of aligned region points in the enclosing rectangle.
  1052. @param _n_bins Number of bins in pseudo-ordering of gradient modulus.
  1053. @note Implementation has been removed due original code license conflict
  1054. */
  1055. CV_EXPORTS_W Ptr<LineSegmentDetector> createLineSegmentDetector(
  1056. int _refine = LSD_REFINE_STD, double _scale = 0.8,
  1057. double _sigma_scale = 0.6, double _quant = 2.0, double _ang_th = 22.5,
  1058. double _log_eps = 0, double _density_th = 0.7, int _n_bins = 1024);
  1059. //! @} imgproc_feature
  1060. //! @addtogroup imgproc_filter
  1061. //! @{
  1062. /** @brief Returns Gaussian filter coefficients.
  1063. The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter
  1064. coefficients:
  1065. \f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f]
  1066. where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$.
  1067. Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize
  1068. smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly.
  1069. You may also use the higher-level GaussianBlur.
  1070. @param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive.
  1071. @param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as
  1072. `sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`.
  1073. @param ktype Type of filter coefficients. It can be CV_32F or CV_64F .
  1074. @sa sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur
  1075. */
  1076. CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F );
  1077. /** @brief Returns filter coefficients for computing spatial image derivatives.
  1078. The function computes and returns the filter coefficients for spatial image derivatives. When
  1079. `ksize=CV_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel
  1080. kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to
  1081. @param kx Output matrix of row filter coefficients. It has the type ktype .
  1082. @param ky Output matrix of column filter coefficients. It has the type ktype .
  1083. @param dx Derivative order in respect of x.
  1084. @param dy Derivative order in respect of y.
  1085. @param ksize Aperture size. It can be CV_SCHARR, 1, 3, 5, or 7.
  1086. @param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not.
  1087. Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are
  1088. going to filter floating-point images, you are likely to use the normalized kernels. But if you
  1089. compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve
  1090. all the fractional bits, you may want to set normalize=false .
  1091. @param ktype Type of filter coefficients. It can be CV_32f or CV_64F .
  1092. */
  1093. CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky,
  1094. int dx, int dy, int ksize,
  1095. bool normalize = false, int ktype = CV_32F );
  1096. /** @brief Returns Gabor filter coefficients.
  1097. For more details about gabor filter equations and parameters, see: [Gabor
  1098. Filter](http://en.wikipedia.org/wiki/Gabor_filter).
  1099. @param ksize Size of the filter returned.
  1100. @param sigma Standard deviation of the gaussian envelope.
  1101. @param theta Orientation of the normal to the parallel stripes of a Gabor function.
  1102. @param lambd Wavelength of the sinusoidal factor.
  1103. @param gamma Spatial aspect ratio.
  1104. @param psi Phase offset.
  1105. @param ktype Type of filter coefficients. It can be CV_32F or CV_64F .
  1106. */
  1107. CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd,
  1108. double gamma, double psi = CV_PI*0.5, int ktype = CV_64F );
  1109. //! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation.
  1110. static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); }
  1111. /** @brief Returns a structuring element of the specified size and shape for morphological operations.
  1112. The function constructs and returns the structuring element that can be further passed to #erode,
  1113. #dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as
  1114. the structuring element.
  1115. @param shape Element shape that could be one of #MorphShapes
  1116. @param ksize Size of the structuring element.
  1117. @param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the
  1118. anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor
  1119. position. In other cases the anchor just regulates how much the result of the morphological
  1120. operation is shifted.
  1121. */
  1122. CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1));
  1123. /** @example samples/cpp/tutorial_code/ImgProc/Smoothing/Smoothing.cpp
  1124. Sample code for simple filters
  1125. ![Sample screenshot](Smoothing_Tutorial_Result_Median_Filter.jpg)
  1126. Check @ref tutorial_gausian_median_blur_bilateral_filter "the corresponding tutorial" for more details
  1127. */
  1128. /** @brief Blurs an image using the median filter.
  1129. The function smoothes an image using the median filter with the \f$\texttt{ksize} \times
  1130. \texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently.
  1131. In-place operation is supported.
  1132. @note The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes
  1133. @param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be
  1134. CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U.
  1135. @param dst destination array of the same size and type as src.
  1136. @param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ...
  1137. @sa bilateralFilter, blur, boxFilter, GaussianBlur
  1138. */
  1139. CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize );
  1140. /** @brief Blurs an image using a Gaussian filter.
  1141. The function convolves the source image with the specified Gaussian kernel. In-place filtering is
  1142. supported.
  1143. @param src input image; the image can have any number of channels, which are processed
  1144. independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
  1145. @param dst output image of the same size and type as src.
  1146. @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be
  1147. positive and odd. Or, they can be zero's and then they are computed from sigma.
  1148. @param sigmaX Gaussian kernel standard deviation in X direction.
  1149. @param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be
  1150. equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height,
  1151. respectively (see #getGaussianKernel for details); to fully control the result regardless of
  1152. possible future modifications of all this semantics, it is recommended to specify all of ksize,
  1153. sigmaX, and sigmaY.
  1154. @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1155. @sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur
  1156. */
  1157. CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize,
  1158. double sigmaX, double sigmaY = 0,
  1159. int borderType = BORDER_DEFAULT );
  1160. /** @brief Applies the bilateral filter to an image.
  1161. The function applies bilateral filtering to the input image, as described in
  1162. http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html
  1163. bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is
  1164. very slow compared to most filters.
  1165. _Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\<
  1166. 10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very
  1167. strong effect, making the image look "cartoonish".
  1168. _Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time
  1169. applications, and perhaps d=9 for offline applications that need heavy noise filtering.
  1170. This filter does not work inplace.
  1171. @param src Source 8-bit or floating-point, 1-channel or 3-channel image.
  1172. @param dst Destination image of the same size and type as src .
  1173. @param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive,
  1174. it is computed from sigmaSpace.
  1175. @param sigmaColor Filter sigma in the color space. A larger value of the parameter means that
  1176. farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting
  1177. in larger areas of semi-equal color.
  1178. @param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that
  1179. farther pixels will influence each other as long as their colors are close enough (see sigmaColor
  1180. ). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is
  1181. proportional to sigmaSpace.
  1182. @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes
  1183. */
  1184. CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d,
  1185. double sigmaColor, double sigmaSpace,
  1186. int borderType = BORDER_DEFAULT );
  1187. /** @brief Blurs an image using the box filter.
  1188. The function smooths an image using the kernel:
  1189. \f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f]
  1190. where
  1191. \f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\f]
  1192. Unnormalized box filter is useful for computing various integral characteristics over each pixel
  1193. neighborhood, such as covariance matrices of image derivatives (used in dense optical flow
  1194. algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral.
  1195. @param src input image.
  1196. @param dst output image of the same size and type as src.
  1197. @param ddepth the output image depth (-1 to use src.depth()).
  1198. @param ksize blurring kernel size.
  1199. @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel
  1200. center.
  1201. @param normalize flag, specifying whether the kernel is normalized by its area or not.
  1202. @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
  1203. @sa blur, bilateralFilter, GaussianBlur, medianBlur, integral
  1204. */
  1205. CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth,
  1206. Size ksize, Point anchor = Point(-1,-1),
  1207. bool normalize = true,
  1208. int borderType = BORDER_DEFAULT );
  1209. /** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter.
  1210. For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring
  1211. pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$.
  1212. The unnormalized square box filter can be useful in computing local image statistics such as the the local
  1213. variance and standard deviation around the neighborhood of a pixel.
  1214. @param src input image
  1215. @param dst output image of the same size and type as _src
  1216. @param ddepth the output image depth (-1 to use src.depth())
  1217. @param ksize kernel size
  1218. @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel
  1219. center.
  1220. @param normalize flag, specifying whether the kernel is to be normalized by it's area or not.
  1221. @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
  1222. @sa boxFilter
  1223. */
  1224. CV_EXPORTS_W void sqrBoxFilter( InputArray src, OutputArray dst, int ddepth,
  1225. Size ksize, Point anchor = Point(-1, -1),
  1226. bool normalize = true,
  1227. int borderType = BORDER_DEFAULT );
  1228. /** @brief Blurs an image using the normalized box filter.
  1229. The function smooths an image using the kernel:
  1230. \f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f]
  1231. The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), ksize,
  1232. anchor, true, borderType)`.
  1233. @param src input image; it can have any number of channels, which are processed independently, but
  1234. the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
  1235. @param dst output image of the same size and type as src.
  1236. @param ksize blurring kernel size.
  1237. @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel
  1238. center.
  1239. @param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported.
  1240. @sa boxFilter, bilateralFilter, GaussianBlur, medianBlur
  1241. */
  1242. CV_EXPORTS_W void blur( InputArray src, OutputArray dst,
  1243. Size ksize, Point anchor = Point(-1,-1),
  1244. int borderType = BORDER_DEFAULT );
  1245. /** @brief Convolves an image with the kernel.
  1246. The function applies an arbitrary linear filter to an image. In-place operation is supported. When
  1247. the aperture is partially outside the image, the function interpolates outlier pixel values
  1248. according to the specified border mode.
  1249. The function does actually compute correlation, not the convolution:
  1250. \f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f]
  1251. That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip
  1252. the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows -
  1253. anchor.y - 1)`.
  1254. The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or
  1255. larger) and the direct algorithm for small kernels.
  1256. @param src input image.
  1257. @param dst output image of the same size and the same number of channels as src.
  1258. @param ddepth desired depth of the destination image, see @ref filter_depths "combinations"
  1259. @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point
  1260. matrix; if you want to apply different kernels to different channels, split the image into
  1261. separate color planes using split and process them individually.
  1262. @param anchor anchor of the kernel that indicates the relative position of a filtered point within
  1263. the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor
  1264. is at the kernel center.
  1265. @param delta optional value added to the filtered pixels before storing them in dst.
  1266. @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1267. @sa sepFilter2D, dft, matchTemplate
  1268. */
  1269. CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth,
  1270. InputArray kernel, Point anchor = Point(-1,-1),
  1271. double delta = 0, int borderType = BORDER_DEFAULT );
  1272. /** @brief Applies a separable linear filter to an image.
  1273. The function applies a separable linear filter to the image. That is, first, every row of src is
  1274. filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D
  1275. kernel kernelY. The final result shifted by delta is stored in dst .
  1276. @param src Source image.
  1277. @param dst Destination image of the same size and the same number of channels as src .
  1278. @param ddepth Destination image depth, see @ref filter_depths "combinations"
  1279. @param kernelX Coefficients for filtering each row.
  1280. @param kernelY Coefficients for filtering each column.
  1281. @param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor
  1282. is at the kernel center.
  1283. @param delta Value added to the filtered results before storing them.
  1284. @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1285. @sa filter2D, Sobel, GaussianBlur, boxFilter, blur
  1286. */
  1287. CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth,
  1288. InputArray kernelX, InputArray kernelY,
  1289. Point anchor = Point(-1,-1),
  1290. double delta = 0, int borderType = BORDER_DEFAULT );
  1291. /** @example samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp
  1292. Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector
  1293. ![Sample screenshot](Sobel_Derivatives_Tutorial_Result.jpg)
  1294. Check @ref tutorial_sobel_derivatives "the corresponding tutorial" for more details
  1295. */
  1296. /** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator.
  1297. In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to
  1298. calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$
  1299. kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first
  1300. or the second x- or y- derivatives.
  1301. There is also the special value `ksize = #CV_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr
  1302. filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is
  1303. \f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f]
  1304. for the x-derivative, or transposed for the y-derivative.
  1305. The function calculates an image derivative by convolving the image with the appropriate kernel:
  1306. \f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f]
  1307. The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less
  1308. resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3)
  1309. or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first
  1310. case corresponds to a kernel of:
  1311. \f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f]
  1312. The second case corresponds to a kernel of:
  1313. \f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f]
  1314. @param src input image.
  1315. @param dst output image of the same size and the same number of channels as src .
  1316. @param ddepth output image depth, see @ref filter_depths "combinations"; in the case of
  1317. 8-bit input images it will result in truncated derivatives.
  1318. @param dx order of the derivative x.
  1319. @param dy order of the derivative y.
  1320. @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7.
  1321. @param scale optional scale factor for the computed derivative values; by default, no scaling is
  1322. applied (see #getDerivKernels for details).
  1323. @param delta optional delta value that is added to the results prior to storing them in dst.
  1324. @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1325. @sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar
  1326. */
  1327. CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth,
  1328. int dx, int dy, int ksize = 3,
  1329. double scale = 1, double delta = 0,
  1330. int borderType = BORDER_DEFAULT );
  1331. /** @brief Calculates the first order image derivative in both x and y using a Sobel operator
  1332. Equivalent to calling:
  1333. @code
  1334. Sobel( src, dx, CV_16SC1, 1, 0, 3 );
  1335. Sobel( src, dy, CV_16SC1, 0, 1, 3 );
  1336. @endcode
  1337. @param src input image.
  1338. @param dx output image with first-order derivative in x.
  1339. @param dy output image with first-order derivative in y.
  1340. @param ksize size of Sobel kernel. It must be 3.
  1341. @param borderType pixel extrapolation method, see #BorderTypes.
  1342. Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported.
  1343. @sa Sobel
  1344. */
  1345. CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx,
  1346. OutputArray dy, int ksize = 3,
  1347. int borderType = BORDER_DEFAULT );
  1348. /** @brief Calculates the first x- or y- image derivative using Scharr operator.
  1349. The function computes the first x- or y- spatial image derivative using the Scharr operator. The
  1350. call
  1351. \f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f]
  1352. is equivalent to
  1353. \f[\texttt{Sobel(src, dst, ddepth, dx, dy, CV_SCHARR, scale, delta, borderType)} .\f]
  1354. @param src input image.
  1355. @param dst output image of the same size and the same number of channels as src.
  1356. @param ddepth output image depth, see @ref filter_depths "combinations"
  1357. @param dx order of the derivative x.
  1358. @param dy order of the derivative y.
  1359. @param scale optional scale factor for the computed derivative values; by default, no scaling is
  1360. applied (see #getDerivKernels for details).
  1361. @param delta optional delta value that is added to the results prior to storing them in dst.
  1362. @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1363. @sa cartToPolar
  1364. */
  1365. CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth,
  1366. int dx, int dy, double scale = 1, double delta = 0,
  1367. int borderType = BORDER_DEFAULT );
  1368. /** @example samples/cpp/laplace.cpp
  1369. An example using Laplace transformations for edge detection
  1370. */
  1371. /** @brief Calculates the Laplacian of an image.
  1372. The function calculates the Laplacian of the source image by adding up the second x and y
  1373. derivatives calculated using the Sobel operator:
  1374. \f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f]
  1375. This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image
  1376. with the following \f$3 \times 3\f$ aperture:
  1377. \f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f]
  1378. @param src Source image.
  1379. @param dst Destination image of the same size and the same number of channels as src .
  1380. @param ddepth Desired depth of the destination image.
  1381. @param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for
  1382. details. The size must be positive and odd.
  1383. @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is
  1384. applied. See #getDerivKernels for details.
  1385. @param delta Optional delta value that is added to the results prior to storing them in dst .
  1386. @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1387. @sa Sobel, Scharr
  1388. */
  1389. CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth,
  1390. int ksize = 1, double scale = 1, double delta = 0,
  1391. int borderType = BORDER_DEFAULT );
  1392. //! @} imgproc_filter
  1393. //! @addtogroup imgproc_feature
  1394. //! @{
  1395. /** @example samples/cpp/edge.cpp
  1396. This program demonstrates usage of the Canny edge detector
  1397. Check @ref tutorial_canny_detector "the corresponding tutorial" for more details
  1398. */
  1399. /** @brief Finds edges in an image using the Canny algorithm @cite Canny86 .
  1400. The function finds edges in the input image and marks them in the output map edges using the
  1401. Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The
  1402. largest value is used to find initial segments of strong edges. See
  1403. <http://en.wikipedia.org/wiki/Canny_edge_detector>
  1404. @param image 8-bit input image.
  1405. @param edges output edge map; single channels 8-bit image, which has the same size as image .
  1406. @param threshold1 first threshold for the hysteresis procedure.
  1407. @param threshold2 second threshold for the hysteresis procedure.
  1408. @param apertureSize aperture size for the Sobel operator.
  1409. @param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm
  1410. \f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude (
  1411. L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough (
  1412. L2gradient=false ).
  1413. */
  1414. CV_EXPORTS_W void Canny( InputArray image, OutputArray edges,
  1415. double threshold1, double threshold2,
  1416. int apertureSize = 3, bool L2gradient = false );
  1417. /** \overload
  1418. Finds edges in an image using the Canny algorithm with custom image gradient.
  1419. @param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3).
  1420. @param dy 16-bit y derivative of input image (same type as dx).
  1421. @param edges output edge map; single channels 8-bit image, which has the same size as image .
  1422. @param threshold1 first threshold for the hysteresis procedure.
  1423. @param threshold2 second threshold for the hysteresis procedure.
  1424. @param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm
  1425. \f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude (
  1426. L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough (
  1427. L2gradient=false ).
  1428. */
  1429. CV_EXPORTS_W void Canny( InputArray dx, InputArray dy,
  1430. OutputArray edges,
  1431. double threshold1, double threshold2,
  1432. bool L2gradient = false );
  1433. /** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection.
  1434. The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal
  1435. eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms
  1436. of the formulae in the cornerEigenValsAndVecs description.
  1437. @param src Input single-channel 8-bit or floating-point image.
  1438. @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as
  1439. src .
  1440. @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ).
  1441. @param ksize Aperture parameter for the Sobel operator.
  1442. @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
  1443. */
  1444. CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst,
  1445. int blockSize, int ksize = 3,
  1446. int borderType = BORDER_DEFAULT );
  1447. /** @brief Harris corner detector.
  1448. The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and
  1449. cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance
  1450. matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it
  1451. computes the following characteristic:
  1452. \f[\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f]
  1453. Corners in the image can be found as the local maxima of this response map.
  1454. @param src Input single-channel 8-bit or floating-point image.
  1455. @param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same
  1456. size as src .
  1457. @param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ).
  1458. @param ksize Aperture parameter for the Sobel operator.
  1459. @param k Harris detector free parameter. See the formula above.
  1460. @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
  1461. */
  1462. CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize,
  1463. int ksize, double k,
  1464. int borderType = BORDER_DEFAULT );
  1465. /** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection.
  1466. For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize
  1467. neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as:
  1468. \f[M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f]
  1469. where the derivatives are computed using the Sobel operator.
  1470. After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as
  1471. \f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where
  1472. - \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$
  1473. - \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$
  1474. - \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$
  1475. The output of the function can be used for robust edge or corner detection.
  1476. @param src Input single-channel 8-bit or floating-point image.
  1477. @param dst Image to store the results. It has the same size as src and the type CV_32FC(6) .
  1478. @param blockSize Neighborhood size (see details below).
  1479. @param ksize Aperture parameter for the Sobel operator.
  1480. @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
  1481. @sa cornerMinEigenVal, cornerHarris, preCornerDetect
  1482. */
  1483. CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst,
  1484. int blockSize, int ksize,
  1485. int borderType = BORDER_DEFAULT );
  1486. /** @brief Calculates a feature map for corner detection.
  1487. The function calculates the complex spatial derivative-based function of the source image
  1488. \f[\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\f]
  1489. where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image
  1490. derivatives, and \f$D_{xy}\f$ is the mixed derivative.
  1491. The corners can be found as local maximums of the functions, as shown below:
  1492. @code
  1493. Mat corners, dilated_corners;
  1494. preCornerDetect(image, corners, 3);
  1495. // dilation with 3x3 rectangular structuring element
  1496. dilate(corners, dilated_corners, Mat(), 1);
  1497. Mat corner_mask = corners == dilated_corners;
  1498. @endcode
  1499. @param src Source single-channel 8-bit of floating-point image.
  1500. @param dst Output image that has the type CV_32F and the same size as src .
  1501. @param ksize %Aperture size of the Sobel .
  1502. @param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported.
  1503. */
  1504. CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize,
  1505. int borderType = BORDER_DEFAULT );
  1506. /** @brief Refines the corner locations.
  1507. The function iterates to find the sub-pixel accurate location of corners or radial saddle
  1508. points as described in @cite forstner1987fast, and as shown on the figure below.
  1509. ![image](pics/cornersubpix.png)
  1510. Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$
  1511. to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$
  1512. subject to image and measurement noise. Consider the expression:
  1513. \f[\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\f]
  1514. where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The
  1515. value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up
  1516. with \f$\epsilon_i\f$ set to zero:
  1517. \f[\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) \cdot q - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\f]
  1518. where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first
  1519. gradient term \f$G\f$ and the second gradient term \f$b\f$ gives:
  1520. \f[q = G^{-1} \cdot b\f]
  1521. The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates
  1522. until the center stays within a set threshold.
  1523. @param image Input single-channel, 8-bit or float image.
  1524. @param corners Initial coordinates of the input corners and refined coordinates provided for
  1525. output.
  1526. @param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) ,
  1527. then a \f$(5*2+1) \times (5*2+1) = 11 \times 11\f$ search window is used.
  1528. @param zeroZone Half of the size of the dead region in the middle of the search zone over which
  1529. the summation in the formula below is not done. It is used sometimes to avoid possible
  1530. singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such
  1531. a size.
  1532. @param criteria Criteria for termination of the iterative process of corner refinement. That is,
  1533. the process of corner position refinement stops either after criteria.maxCount iterations or when
  1534. the corner position moves by less than criteria.epsilon on some iteration.
  1535. */
  1536. CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners,
  1537. Size winSize, Size zeroZone,
  1538. TermCriteria criteria );
  1539. /** @brief Determines strong corners on an image.
  1540. The function finds the most prominent corners in the image or in the specified image region, as
  1541. described in @cite Shi94
  1542. - Function calculates the corner quality measure at every source image pixel using the
  1543. #cornerMinEigenVal or #cornerHarris .
  1544. - Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are
  1545. retained).
  1546. - The corners with the minimal eigenvalue less than
  1547. \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected.
  1548. - The remaining corners are sorted by the quality measure in the descending order.
  1549. - Function throws away each corner for which there is a stronger corner at a distance less than
  1550. maxDistance.
  1551. The function can be used to initialize a point-based tracker of an object.
  1552. @note If the function is called with different values A and B of the parameter qualityLevel , and
  1553. A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector
  1554. with qualityLevel=B .
  1555. @param image Input 8-bit or floating-point 32-bit, single-channel image.
  1556. @param corners Output vector of detected corners.
  1557. @param maxCorners Maximum number of corners to return. If there are more corners than are found,
  1558. the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set
  1559. and all detected corners are returned.
  1560. @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The
  1561. parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue
  1562. (see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the
  1563. quality measure less than the product are rejected. For example, if the best corner has the
  1564. quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure
  1565. less than 15 are rejected.
  1566. @param minDistance Minimum possible Euclidean distance between the returned corners.
  1567. @param mask Optional region of interest. If the image is not empty (it needs to have the type
  1568. CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected.
  1569. @param blockSize Size of an average block for computing a derivative covariation matrix over each
  1570. pixel neighborhood. See cornerEigenValsAndVecs .
  1571. @param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris)
  1572. or #cornerMinEigenVal.
  1573. @param k Free parameter of the Harris detector.
  1574. @sa cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform,
  1575. */
  1576. CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners,
  1577. int maxCorners, double qualityLevel, double minDistance,
  1578. InputArray mask = noArray(), int blockSize = 3,
  1579. bool useHarrisDetector = false, double k = 0.04 );
  1580. CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners,
  1581. int maxCorners, double qualityLevel, double minDistance,
  1582. InputArray mask, int blockSize,
  1583. int gradientSize, bool useHarrisDetector = false,
  1584. double k = 0.04 );
  1585. /** @example samples/cpp/tutorial_code/ImgTrans/houghlines.cpp
  1586. An example using the Hough line detector
  1587. ![Sample input image](Hough_Lines_Tutorial_Original_Image.jpg) ![Output image](Hough_Lines_Tutorial_Result.jpg)
  1588. */
  1589. /** @brief Finds lines in a binary image using the standard Hough transform.
  1590. The function implements the standard or standard multi-scale Hough transform algorithm for line
  1591. detection. See <http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough
  1592. transform.
  1593. @param image 8-bit, single-channel binary source image. The image may be modified by the function.
  1594. @param lines Output vector of lines. Each line is represented by a 2 or 3 element vector
  1595. \f$(\rho, \theta)\f$ or \f$(\rho, \theta, \textrm{votes})\f$ . \f$\rho\f$ is the distance from the coordinate origin \f$(0,0)\f$ (top-left corner of
  1596. the image). \f$\theta\f$ is the line rotation angle in radians (
  1597. \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ).
  1598. \f$\textrm{votes}\f$ is the value of accumulator.
  1599. @param rho Distance resolution of the accumulator in pixels.
  1600. @param theta Angle resolution of the accumulator in radians.
  1601. @param threshold Accumulator threshold parameter. Only those lines are returned that get enough
  1602. votes ( \f$>\texttt{threshold}\f$ ).
  1603. @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho .
  1604. The coarse accumulator distance resolution is rho and the accurate accumulator resolution is
  1605. rho/srn . If both srn=0 and stn=0 , the classical Hough transform is used. Otherwise, both these
  1606. parameters should be positive.
  1607. @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta.
  1608. @param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines.
  1609. Must fall between 0 and max_theta.
  1610. @param max_theta For standard and multi-scale Hough transform, maximum angle to check for lines.
  1611. Must fall between min_theta and CV_PI.
  1612. */
  1613. CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines,
  1614. double rho, double theta, int threshold,
  1615. double srn = 0, double stn = 0,
  1616. double min_theta = 0, double max_theta = CV_PI );
  1617. /** @brief Finds line segments in a binary image using the probabilistic Hough transform.
  1618. The function implements the probabilistic Hough transform algorithm for line detection, described
  1619. in @cite Matas00
  1620. See the line detection example below:
  1621. @include snippets/imgproc_HoughLinesP.cpp
  1622. This is a sample picture the function parameters have been tuned for:
  1623. ![image](pics/building.jpg)
  1624. And this is the output of the above program in case of the probabilistic Hough transform:
  1625. ![image](pics/houghp.png)
  1626. @param image 8-bit, single-channel binary source image. The image may be modified by the function.
  1627. @param lines Output vector of lines. Each line is represented by a 4-element vector
  1628. \f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected
  1629. line segment.
  1630. @param rho Distance resolution of the accumulator in pixels.
  1631. @param theta Angle resolution of the accumulator in radians.
  1632. @param threshold Accumulator threshold parameter. Only those lines are returned that get enough
  1633. votes ( \f$>\texttt{threshold}\f$ ).
  1634. @param minLineLength Minimum line length. Line segments shorter than that are rejected.
  1635. @param maxLineGap Maximum allowed gap between points on the same line to link them.
  1636. @sa LineSegmentDetector
  1637. */
  1638. CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines,
  1639. double rho, double theta, int threshold,
  1640. double minLineLength = 0, double maxLineGap = 0 );
  1641. /** @brief Finds lines in a set of points using the standard Hough transform.
  1642. The function finds lines in a set of points using a modification of the Hough transform.
  1643. @include snippets/imgproc_HoughLinesPointSet.cpp
  1644. @param _point Input vector of points. Each vector must be encoded as a Point vector \f$(x,y)\f$. Type must be CV_32FC2 or CV_32SC2.
  1645. @param _lines Output vector of found lines. Each vector is encoded as a vector<Vec3d> \f$(votes, rho, theta)\f$.
  1646. The larger the value of 'votes', the higher the reliability of the Hough line.
  1647. @param lines_max Max count of hough lines.
  1648. @param threshold Accumulator threshold parameter. Only those lines are returned that get enough
  1649. votes ( \f$>\texttt{threshold}\f$ )
  1650. @param min_rho Minimum Distance value of the accumulator in pixels.
  1651. @param max_rho Maximum Distance value of the accumulator in pixels.
  1652. @param rho_step Distance resolution of the accumulator in pixels.
  1653. @param min_theta Minimum angle value of the accumulator in radians.
  1654. @param max_theta Maximum angle value of the accumulator in radians.
  1655. @param theta_step Angle resolution of the accumulator in radians.
  1656. */
  1657. CV_EXPORTS_W void HoughLinesPointSet( InputArray _point, OutputArray _lines, int lines_max, int threshold,
  1658. double min_rho, double max_rho, double rho_step,
  1659. double min_theta, double max_theta, double theta_step );
  1660. /** @example samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp
  1661. An example using the Hough circle detector
  1662. */
  1663. /** @brief Finds circles in a grayscale image using the Hough transform.
  1664. The function finds circles in a grayscale image using a modification of the Hough transform.
  1665. Example: :
  1666. @include snippets/imgproc_HoughLinesCircles.cpp
  1667. @note Usually the function detects the centers of circles well. However, it may fail to find correct
  1668. radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if
  1669. you know it. Or, you may set maxRadius to a negative number to return centers only without radius
  1670. search, and find the correct radius using an additional procedure.
  1671. @param image 8-bit, single-channel, grayscale input image.
  1672. @param circles Output vector of found circles. Each vector is encoded as 3 or 4 element
  1673. floating-point vector \f$(x, y, radius)\f$ or \f$(x, y, radius, votes)\f$ .
  1674. @param method Detection method, see #HoughModes. Currently, the only implemented method is #HOUGH_GRADIENT
  1675. @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if
  1676. dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has
  1677. half as big width and height.
  1678. @param minDist Minimum distance between the centers of the detected circles. If the parameter is
  1679. too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is
  1680. too large, some circles may be missed.
  1681. @param param1 First method-specific parameter. In case of #HOUGH_GRADIENT , it is the higher
  1682. threshold of the two passed to the Canny edge detector (the lower one is twice smaller).
  1683. @param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT , it is the
  1684. accumulator threshold for the circle centers at the detection stage. The smaller it is, the more
  1685. false circles may be detected. Circles, corresponding to the larger accumulator values, will be
  1686. returned first.
  1687. @param minRadius Minimum circle radius.
  1688. @param maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, returns
  1689. centers without finding the radius.
  1690. @sa fitEllipse, minEnclosingCircle
  1691. */
  1692. CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles,
  1693. int method, double dp, double minDist,
  1694. double param1 = 100, double param2 = 100,
  1695. int minRadius = 0, int maxRadius = 0 );
  1696. //! @} imgproc_feature
  1697. //! @addtogroup imgproc_filter
  1698. //! @{
  1699. /** @example samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp
  1700. Advanced morphology Transformations sample code
  1701. ![Sample screenshot](Morphology_2_Tutorial_Result.jpg)
  1702. Check @ref tutorial_opening_closing_hats "the corresponding tutorial" for more details
  1703. */
  1704. /** @brief Erodes an image by using a specific structuring element.
  1705. The function erodes the source image using the specified structuring element that determines the
  1706. shape of a pixel neighborhood over which the minimum is taken:
  1707. \f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f]
  1708. The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In
  1709. case of multi-channel images, each channel is processed independently.
  1710. @param src input image; the number of channels can be arbitrary, but the depth should be one of
  1711. CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
  1712. @param dst output image of the same size and type as src.
  1713. @param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular
  1714. structuring element is used. Kernel can be created using #getStructuringElement.
  1715. @param anchor position of the anchor within the element; default value (-1, -1) means that the
  1716. anchor is at the element center.
  1717. @param iterations number of times erosion is applied.
  1718. @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1719. @param borderValue border value in case of a constant border
  1720. @sa dilate, morphologyEx, getStructuringElement
  1721. */
  1722. CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel,
  1723. Point anchor = Point(-1,-1), int iterations = 1,
  1724. int borderType = BORDER_CONSTANT,
  1725. const Scalar& borderValue = morphologyDefaultBorderValue() );
  1726. /** @example samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp
  1727. Erosion and Dilation sample code
  1728. ![Sample Screenshot-Erosion](Morphology_1_Tutorial_Erosion_Result.jpg)![Sample Screenshot-Dilation](Morphology_1_Tutorial_Dilation_Result.jpg)
  1729. Check @ref tutorial_erosion_dilatation "the corresponding tutorial" for more details
  1730. */
  1731. /** @brief Dilates an image by using a specific structuring element.
  1732. The function dilates the source image using the specified structuring element that determines the
  1733. shape of a pixel neighborhood over which the maximum is taken:
  1734. \f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f]
  1735. The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In
  1736. case of multi-channel images, each channel is processed independently.
  1737. @param src input image; the number of channels can be arbitrary, but the depth should be one of
  1738. CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
  1739. @param dst output image of the same size and type as src.
  1740. @param kernel structuring element used for dilation; if elemenat=Mat(), a 3 x 3 rectangular
  1741. structuring element is used. Kernel can be created using #getStructuringElement
  1742. @param anchor position of the anchor within the element; default value (-1, -1) means that the
  1743. anchor is at the element center.
  1744. @param iterations number of times dilation is applied.
  1745. @param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported.
  1746. @param borderValue border value in case of a constant border
  1747. @sa erode, morphologyEx, getStructuringElement
  1748. */
  1749. CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel,
  1750. Point anchor = Point(-1,-1), int iterations = 1,
  1751. int borderType = BORDER_CONSTANT,
  1752. const Scalar& borderValue = morphologyDefaultBorderValue() );
  1753. /** @brief Performs advanced morphological transformations.
  1754. The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as
  1755. basic operations.
  1756. Any of the operations can be done in-place. In case of multi-channel images, each channel is
  1757. processed independently.
  1758. @param src Source image. The number of channels can be arbitrary. The depth should be one of
  1759. CV_8U, CV_16U, CV_16S, CV_32F or CV_64F.
  1760. @param dst Destination image of the same size and type as source image.
  1761. @param op Type of a morphological operation, see #MorphTypes
  1762. @param kernel Structuring element. It can be created using #getStructuringElement.
  1763. @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the
  1764. kernel center.
  1765. @param iterations Number of times erosion and dilation are applied.
  1766. @param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported.
  1767. @param borderValue Border value in case of a constant border. The default value has a special
  1768. meaning.
  1769. @sa dilate, erode, getStructuringElement
  1770. @note The number of iterations is the number of times erosion or dilatation operation will be applied.
  1771. For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply
  1772. successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate).
  1773. */
  1774. CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst,
  1775. int op, InputArray kernel,
  1776. Point anchor = Point(-1,-1), int iterations = 1,
  1777. int borderType = BORDER_CONSTANT,
  1778. const Scalar& borderValue = morphologyDefaultBorderValue() );
  1779. //! @} imgproc_filter
  1780. //! @addtogroup imgproc_transform
  1781. //! @{
  1782. /** @brief Resizes an image.
  1783. The function resize resizes the image src down to or up to the specified size. Note that the
  1784. initial dst type or size are not taken into account. Instead, the size and type are derived from
  1785. the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst,
  1786. you may call the function as follows:
  1787. @code
  1788. // explicitly specify dsize=dst.size(); fx and fy will be computed from that.
  1789. resize(src, dst, dst.size(), 0, 0, interpolation);
  1790. @endcode
  1791. If you want to decimate the image by factor of 2 in each direction, you can call the function this
  1792. way:
  1793. @code
  1794. // specify fx and fy and let the function compute the destination image size.
  1795. resize(src, dst, Size(), 0.5, 0.5, interpolation);
  1796. @endcode
  1797. To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to
  1798. enlarge an image, it will generally look best with c#INTER_CUBIC (slow) or #INTER_LINEAR
  1799. (faster but still looks OK).
  1800. @param src input image.
  1801. @param dst output image; it has the size dsize (when it is non-zero) or the size computed from
  1802. src.size(), fx, and fy; the type of dst is the same as of src.
  1803. @param dsize output image size; if it equals zero, it is computed as:
  1804. \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f]
  1805. Either dsize or both fx and fy must be non-zero.
  1806. @param fx scale factor along the horizontal axis; when it equals 0, it is computed as
  1807. \f[\texttt{(double)dsize.width/src.cols}\f]
  1808. @param fy scale factor along the vertical axis; when it equals 0, it is computed as
  1809. \f[\texttt{(double)dsize.height/src.rows}\f]
  1810. @param interpolation interpolation method, see #InterpolationFlags
  1811. @sa warpAffine, warpPerspective, remap
  1812. */
  1813. CV_EXPORTS_W void resize( InputArray src, OutputArray dst,
  1814. Size dsize, double fx = 0, double fy = 0,
  1815. int interpolation = INTER_LINEAR );
  1816. /** @brief Applies an affine transformation to an image.
  1817. The function warpAffine transforms the source image using the specified matrix:
  1818. \f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f]
  1819. when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted
  1820. with #invertAffineTransform and then put in the formula above instead of M. The function cannot
  1821. operate in-place.
  1822. @param src input image.
  1823. @param dst output image that has the size dsize and the same type as src .
  1824. @param M \f$2\times 3\f$ transformation matrix.
  1825. @param dsize size of the output image.
  1826. @param flags combination of interpolation methods (see #InterpolationFlags) and the optional
  1827. flag #WARP_INVERSE_MAP that means that M is the inverse transformation (
  1828. \f$\texttt{dst}\rightarrow\texttt{src}\f$ ).
  1829. @param borderMode pixel extrapolation method (see #BorderTypes); when
  1830. borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to
  1831. the "outliers" in the source image are not modified by the function.
  1832. @param borderValue value used in case of a constant border; by default, it is 0.
  1833. @sa warpPerspective, resize, remap, getRectSubPix, transform
  1834. */
  1835. CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst,
  1836. InputArray M, Size dsize,
  1837. int flags = INTER_LINEAR,
  1838. int borderMode = BORDER_CONSTANT,
  1839. const Scalar& borderValue = Scalar());
  1840. /** @example samples/cpp/warpPerspective_demo.cpp
  1841. An example program shows using cv::getPerspectiveTransform and cv::warpPerspective for image warping
  1842. */
  1843. /** @brief Applies a perspective transformation to an image.
  1844. The function warpPerspective transforms the source image using the specified matrix:
  1845. \f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} ,
  1846. \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f]
  1847. when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert
  1848. and then put in the formula above instead of M. The function cannot operate in-place.
  1849. @param src input image.
  1850. @param dst output image that has the size dsize and the same type as src .
  1851. @param M \f$3\times 3\f$ transformation matrix.
  1852. @param dsize size of the output image.
  1853. @param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the
  1854. optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation (
  1855. \f$\texttt{dst}\rightarrow\texttt{src}\f$ ).
  1856. @param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE).
  1857. @param borderValue value used in case of a constant border; by default, it equals 0.
  1858. @sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform
  1859. */
  1860. CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst,
  1861. InputArray M, Size dsize,
  1862. int flags = INTER_LINEAR,
  1863. int borderMode = BORDER_CONSTANT,
  1864. const Scalar& borderValue = Scalar());
  1865. /** @brief Applies a generic geometrical transformation to an image.
  1866. The function remap transforms the source image using the specified map:
  1867. \f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f]
  1868. where values of pixels with non-integer coordinates are computed using one of available
  1869. interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps
  1870. in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in
  1871. \f$map_1\f$, or fixed-point maps created by using convertMaps. The reason you might want to
  1872. convert from floating to fixed-point representations of a map is that they can yield much faster
  1873. (\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x),
  1874. cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients.
  1875. This function cannot operate in-place.
  1876. @param src Source image.
  1877. @param dst Destination image. It has the same size as map1 and the same type as src .
  1878. @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 ,
  1879. CV_32FC1, or CV_32FC2. See convertMaps for details on converting a floating point
  1880. representation to fixed-point for speed.
  1881. @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map
  1882. if map1 is (x,y) points), respectively.
  1883. @param interpolation Interpolation method (see #InterpolationFlags). The method #INTER_AREA is
  1884. not supported by this function.
  1885. @param borderMode Pixel extrapolation method (see #BorderTypes). When
  1886. borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that
  1887. corresponds to the "outliers" in the source image are not modified by the function.
  1888. @param borderValue Value used in case of a constant border. By default, it is 0.
  1889. @note
  1890. Due to current implementation limitations the size of an input and output images should be less than 32767x32767.
  1891. */
  1892. CV_EXPORTS_W void remap( InputArray src, OutputArray dst,
  1893. InputArray map1, InputArray map2,
  1894. int interpolation, int borderMode = BORDER_CONSTANT,
  1895. const Scalar& borderValue = Scalar());
  1896. /** @brief Converts image transformation maps from one representation to another.
  1897. The function converts a pair of maps for remap from one representation to another. The following
  1898. options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are
  1899. supported:
  1900. - \f$\texttt{(CV_32FC1, CV_32FC1)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. This is the
  1901. most frequently used conversion operation, in which the original floating-point maps (see remap )
  1902. are converted to a more compact and much faster fixed-point representation. The first output array
  1903. contains the rounded coordinates and the second array (created only when nninterpolation=false )
  1904. contains indices in the interpolation tables.
  1905. - \f$\texttt{(CV_32FC2)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. The same as above but
  1906. the original maps are stored in one 2-channel matrix.
  1907. - Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same
  1908. as the originals.
  1909. @param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 .
  1910. @param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix),
  1911. respectively.
  1912. @param dstmap1 The first output map that has the type dstmap1type and the same size as src .
  1913. @param dstmap2 The second output map.
  1914. @param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or
  1915. CV_32FC2 .
  1916. @param nninterpolation Flag indicating whether the fixed-point maps are used for the
  1917. nearest-neighbor or for a more complex interpolation.
  1918. @sa remap, undistort, initUndistortRectifyMap
  1919. */
  1920. CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2,
  1921. OutputArray dstmap1, OutputArray dstmap2,
  1922. int dstmap1type, bool nninterpolation = false );
  1923. /** @brief Calculates an affine matrix of 2D rotation.
  1924. The function calculates the following matrix:
  1925. \f[\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\f]
  1926. where
  1927. \f[\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f]
  1928. The transformation maps the rotation center to itself. If this is not the target, adjust the shift.
  1929. @param center Center of the rotation in the source image.
  1930. @param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the
  1931. coordinate origin is assumed to be the top-left corner).
  1932. @param scale Isotropic scale factor.
  1933. @sa getAffineTransform, warpAffine, transform
  1934. */
  1935. CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale );
  1936. //! returns 3x3 perspective transformation for the corresponding 4 point pairs.
  1937. CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] );
  1938. /** @brief Calculates an affine transform from three pairs of the corresponding points.
  1939. The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that:
  1940. \f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f]
  1941. where
  1942. \f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f]
  1943. @param src Coordinates of triangle vertices in the source image.
  1944. @param dst Coordinates of the corresponding triangle vertices in the destination image.
  1945. @sa warpAffine, transform
  1946. */
  1947. CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] );
  1948. /** @brief Inverts an affine transformation.
  1949. The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M:
  1950. \f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f]
  1951. The result is also a \f$2 \times 3\f$ matrix of the same type as M.
  1952. @param M Original affine transformation.
  1953. @param iM Output reverse affine transformation.
  1954. */
  1955. CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM );
  1956. /** @brief Calculates a perspective transform from four pairs of the corresponding points.
  1957. The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that:
  1958. \f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f]
  1959. where
  1960. \f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f]
  1961. @param src Coordinates of quadrangle vertices in the source image.
  1962. @param dst Coordinates of the corresponding quadrangle vertices in the destination image.
  1963. @sa findHomography, warpPerspective, perspectiveTransform
  1964. */
  1965. CV_EXPORTS_W Mat getPerspectiveTransform( InputArray src, InputArray dst );
  1966. CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst );
  1967. /** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy.
  1968. The function getRectSubPix extracts pixels from src:
  1969. \f[patch(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f]
  1970. where the values of the pixels at non-integer coordinates are retrieved using bilinear
  1971. interpolation. Every channel of multi-channel images is processed independently. Also
  1972. the image should be a single channel or three channel image. While the center of the
  1973. rectangle must be inside the image, parts of the rectangle may be outside.
  1974. @param image Source image.
  1975. @param patchSize Size of the extracted patch.
  1976. @param center Floating point coordinates of the center of the extracted rectangle within the
  1977. source image. The center must be inside the image.
  1978. @param patch Extracted patch that has the size patchSize and the same number of channels as src .
  1979. @param patchType Depth of the extracted pixels. By default, they have the same depth as src .
  1980. @sa warpAffine, warpPerspective
  1981. */
  1982. CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize,
  1983. Point2f center, OutputArray patch, int patchType = -1 );
  1984. /** @example samples/cpp/polar_transforms.cpp
  1985. An example using the cv::linearPolar and cv::logPolar operations
  1986. */
  1987. /** @brief Remaps an image to semilog-polar coordinates space.
  1988. @deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags+WARP_POLAR_LOG);
  1989. @internal
  1990. Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image d)"):
  1991. \f[\begin{array}{l}
  1992. dst( \rho , \phi ) = src(x,y) \\
  1993. dst.size() \leftarrow src.size()
  1994. \end{array}\f]
  1995. where
  1996. \f[\begin{array}{l}
  1997. I = (dx,dy) = (x - center.x,y - center.y) \\
  1998. \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\
  1999. \phi = Kangle \cdot \texttt{angle} (I) \\
  2000. \end{array}\f]
  2001. and
  2002. \f[\begin{array}{l}
  2003. M = src.cols / log_e(maxRadius) \\
  2004. Kangle = src.rows / 2\Pi \\
  2005. \end{array}\f]
  2006. The function emulates the human "foveal" vision and can be used for fast scale and
  2007. rotation-invariant template matching, for object tracking and so forth.
  2008. @param src Source image
  2009. @param dst Destination image. It will have same size and type as src.
  2010. @param center The transformation center; where the output precision is maximal
  2011. @param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too.
  2012. @param flags A combination of interpolation methods, see #InterpolationFlags
  2013. @note
  2014. - The function can not operate in-place.
  2015. - To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees.
  2016. @sa cv::linearPolar
  2017. @endinternal
  2018. */
  2019. CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst,
  2020. Point2f center, double M, int flags );
  2021. /** @brief Remaps an image to polar coordinates space.
  2022. @deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags)
  2023. @internal
  2024. Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image c)"):
  2025. \f[\begin{array}{l}
  2026. dst( \rho , \phi ) = src(x,y) \\
  2027. dst.size() \leftarrow src.size()
  2028. \end{array}\f]
  2029. where
  2030. \f[\begin{array}{l}
  2031. I = (dx,dy) = (x - center.x,y - center.y) \\
  2032. \rho = Kmag \cdot \texttt{magnitude} (I) ,\\
  2033. \phi = angle \cdot \texttt{angle} (I)
  2034. \end{array}\f]
  2035. and
  2036. \f[\begin{array}{l}
  2037. Kx = src.cols / maxRadius \\
  2038. Ky = src.rows / 2\Pi
  2039. \end{array}\f]
  2040. @param src Source image
  2041. @param dst Destination image. It will have same size and type as src.
  2042. @param center The transformation center;
  2043. @param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too.
  2044. @param flags A combination of interpolation methods, see #InterpolationFlags
  2045. @note
  2046. - The function can not operate in-place.
  2047. - To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees.
  2048. @sa cv::logPolar
  2049. @endinternal
  2050. */
  2051. CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst,
  2052. Point2f center, double maxRadius, int flags );
  2053. /** \brief Remaps an image to polar or semilog-polar coordinates space
  2054. @anchor polar_remaps_reference_image
  2055. ![Polar remaps reference](pics/polar_remap_doc.png)
  2056. Transform the source image using the following transformation:
  2057. \f[
  2058. dst(\rho , \phi ) = src(x,y)
  2059. \f]
  2060. where
  2061. \f[
  2062. \begin{array}{l}
  2063. \vec{I} = (x - center.x, \;y - center.y) \\
  2064. \phi = Kangle \cdot \texttt{angle} (\vec{I}) \\
  2065. \rho = \left\{\begin{matrix}
  2066. Klin \cdot \texttt{magnitude} (\vec{I}) & default \\
  2067. Klog \cdot log_e(\texttt{magnitude} (\vec{I})) & if \; semilog \\
  2068. \end{matrix}\right.
  2069. \end{array}
  2070. \f]
  2071. and
  2072. \f[
  2073. \begin{array}{l}
  2074. Kangle = dsize.height / 2\Pi \\
  2075. Klin = dsize.width / maxRadius \\
  2076. Klog = dsize.width / log_e(maxRadius) \\
  2077. \end{array}
  2078. \f]
  2079. \par Linear vs semilog mapping
  2080. Polar mapping can be linear or semi-log. Add one of #WarpPolarMode to `flags` to specify the polar mapping mode.
  2081. Linear is the default mode.
  2082. The semilog mapping emulates the human "foveal" vision that permit very high acuity on the line of sight (central vision)
  2083. in contrast to peripheral vision where acuity is minor.
  2084. \par Option on `dsize`:
  2085. - if both values in `dsize <=0 ` (default),
  2086. the destination image will have (almost) same area of source bounding circle:
  2087. \f[\begin{array}{l}
  2088. dsize.area \leftarrow (maxRadius^2 \cdot \Pi) \\
  2089. dsize.width = \texttt{cvRound}(maxRadius) \\
  2090. dsize.height = \texttt{cvRound}(maxRadius \cdot \Pi) \\
  2091. \end{array}\f]
  2092. - if only `dsize.height <= 0`,
  2093. the destination image area will be proportional to the bounding circle area but scaled by `Kx * Kx`:
  2094. \f[\begin{array}{l}
  2095. dsize.height = \texttt{cvRound}(dsize.width \cdot \Pi) \\
  2096. \end{array}
  2097. \f]
  2098. - if both values in `dsize > 0 `,
  2099. the destination image will have the given size therefore the area of the bounding circle will be scaled to `dsize`.
  2100. \par Reverse mapping
  2101. You can get reverse mapping adding #WARP_INVERSE_MAP to `flags`
  2102. \snippet polar_transforms.cpp InverseMap
  2103. In addiction, to calculate the original coordinate from a polar mapped coordinate \f$(rho, phi)->(x, y)\f$:
  2104. \snippet polar_transforms.cpp InverseCoordinate
  2105. @param src Source image.
  2106. @param dst Destination image. It will have same type as src.
  2107. @param dsize The destination image size (see description for valid options).
  2108. @param center The transformation center.
  2109. @param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too.
  2110. @param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode.
  2111. - Add #WARP_POLAR_LINEAR to select linear polar mapping (default)
  2112. - Add #WARP_POLAR_LOG to select semilog polar mapping
  2113. - Add #WARP_INVERSE_MAP for reverse mapping.
  2114. @note
  2115. - The function can not operate in-place.
  2116. - To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees.
  2117. - This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767.
  2118. @sa cv::remap
  2119. */
  2120. CV_EXPORTS_W void warpPolar(InputArray src, OutputArray dst, Size dsize,
  2121. Point2f center, double maxRadius, int flags);
  2122. //! @} imgproc_transform
  2123. //! @addtogroup imgproc_misc
  2124. //! @{
  2125. /** @overload */
  2126. CV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth = -1 );
  2127. /** @overload */
  2128. CV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum,
  2129. OutputArray sqsum, int sdepth = -1, int sqdepth = -1 );
  2130. /** @brief Calculates the integral of an image.
  2131. The function calculates one or more integral images for the source image as follows:
  2132. \f[\texttt{sum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)\f]
  2133. \f[\texttt{sqsum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)^2\f]
  2134. \f[\texttt{tilted} (X,Y) = \sum _{y<Y,abs(x-X+1) \leq Y-y-1} \texttt{image} (x,y)\f]
  2135. Using these integral images, you can calculate sum, mean, and standard deviation over a specific
  2136. up-right or rotated rectangular region of the image in a constant time, for example:
  2137. \f[\sum _{x_1 \leq x < x_2, \, y_1 \leq y < y_2} \texttt{image} (x,y) = \texttt{sum} (x_2,y_2)- \texttt{sum} (x_1,y_2)- \texttt{sum} (x_2,y_1)+ \texttt{sum} (x_1,y_1)\f]
  2138. It makes possible to do a fast blurring or fast block correlation with a variable window size, for
  2139. example. In case of multi-channel images, sums for each channel are accumulated independently.
  2140. As a practical example, the next figure shows the calculation of the integral of a straight
  2141. rectangle Rect(3,3,3,2) and of a tilted rectangle Rect(5,1,2,3) . The selected pixels in the
  2142. original image are shown, as well as the relative pixels in the integral images sum and tilted .
  2143. ![integral calculation example](pics/integral.png)
  2144. @param src input image as \f$W \times H\f$, 8-bit or floating-point (32f or 64f).
  2145. @param sum integral image as \f$(W+1)\times (H+1)\f$ , 32-bit integer or floating-point (32f or 64f).
  2146. @param sqsum integral image for squared pixel values; it is \f$(W+1)\times (H+1)\f$, double-precision
  2147. floating-point (64f) array.
  2148. @param tilted integral for the image rotated by 45 degrees; it is \f$(W+1)\times (H+1)\f$ array with
  2149. the same data type as sum.
  2150. @param sdepth desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or
  2151. CV_64F.
  2152. @param sqdepth desired depth of the integral image of squared pixel values, CV_32F or CV_64F.
  2153. */
  2154. CV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum,
  2155. OutputArray sqsum, OutputArray tilted,
  2156. int sdepth = -1, int sqdepth = -1 );
  2157. //! @} imgproc_misc
  2158. //! @addtogroup imgproc_motion
  2159. //! @{
  2160. /** @brief Adds an image to the accumulator image.
  2161. The function adds src or some of its elements to dst :
  2162. \f[\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f]
  2163. The function supports multi-channel images. Each channel is processed independently.
  2164. The function cv::accumulate can be used, for example, to collect statistics of a scene background
  2165. viewed by a still camera and for the further foreground-background segmentation.
  2166. @param src Input image of type CV_8UC(n), CV_16UC(n), CV_32FC(n) or CV_64FC(n), where n is a positive integer.
  2167. @param dst %Accumulator image with the same number of channels as input image, and a depth of CV_32F or CV_64F.
  2168. @param mask Optional operation mask.
  2169. @sa accumulateSquare, accumulateProduct, accumulateWeighted
  2170. */
  2171. CV_EXPORTS_W void accumulate( InputArray src, InputOutputArray dst,
  2172. InputArray mask = noArray() );
  2173. /** @brief Adds the square of a source image to the accumulator image.
  2174. The function adds the input image src or its selected region, raised to a power of 2, to the
  2175. accumulator dst :
  2176. \f[\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y)^2 \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f]
  2177. The function supports multi-channel images. Each channel is processed independently.
  2178. @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
  2179. @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit
  2180. floating-point.
  2181. @param mask Optional operation mask.
  2182. @sa accumulateSquare, accumulateProduct, accumulateWeighted
  2183. */
  2184. CV_EXPORTS_W void accumulateSquare( InputArray src, InputOutputArray dst,
  2185. InputArray mask = noArray() );
  2186. /** @brief Adds the per-element product of two input images to the accumulator image.
  2187. The function adds the product of two images or their selected regions to the accumulator dst :
  2188. \f[\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src1} (x,y) \cdot \texttt{src2} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f]
  2189. The function supports multi-channel images. Each channel is processed independently.
  2190. @param src1 First input image, 1- or 3-channel, 8-bit or 32-bit floating point.
  2191. @param src2 Second input image of the same type and the same size as src1 .
  2192. @param dst %Accumulator image with the same number of channels as input images, 32-bit or 64-bit
  2193. floating-point.
  2194. @param mask Optional operation mask.
  2195. @sa accumulate, accumulateSquare, accumulateWeighted
  2196. */
  2197. CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2,
  2198. InputOutputArray dst, InputArray mask=noArray() );
  2199. /** @brief Updates a running average.
  2200. The function calculates the weighted sum of the input image src and the accumulator dst so that dst
  2201. becomes a running average of a frame sequence:
  2202. \f[\texttt{dst} (x,y) \leftarrow (1- \texttt{alpha} ) \cdot \texttt{dst} (x,y) + \texttt{alpha} \cdot \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f]
  2203. That is, alpha regulates the update speed (how fast the accumulator "forgets" about earlier images).
  2204. The function supports multi-channel images. Each channel is processed independently.
  2205. @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point.
  2206. @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit
  2207. floating-point.
  2208. @param alpha Weight of the input image.
  2209. @param mask Optional operation mask.
  2210. @sa accumulate, accumulateSquare, accumulateProduct
  2211. */
  2212. CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst,
  2213. double alpha, InputArray mask = noArray() );
  2214. /** @brief The function is used to detect translational shifts that occur between two images.
  2215. The operation takes advantage of the Fourier shift theorem for detecting the translational shift in
  2216. the frequency domain. It can be used for fast image registration as well as motion estimation. For
  2217. more information please see <http://en.wikipedia.org/wiki/Phase_correlation>
  2218. Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed
  2219. with getOptimalDFTSize.
  2220. The function performs the following equations:
  2221. - First it applies a Hanning window (see <http://en.wikipedia.org/wiki/Hann_function>) to each
  2222. image to remove possible edge effects. This window is cached until the array size changes to speed
  2223. up processing time.
  2224. - Next it computes the forward DFTs of each source array:
  2225. \f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f]
  2226. where \f$\mathcal{F}\f$ is the forward DFT.
  2227. - It then computes the cross-power spectrum of each frequency domain array:
  2228. \f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f]
  2229. - Next the cross-correlation is converted back into the time domain via the inverse DFT:
  2230. \f[r = \mathcal{F}^{-1}\{R\}\f]
  2231. - Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to
  2232. achieve sub-pixel accuracy.
  2233. \f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f]
  2234. - If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5
  2235. centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single
  2236. peak) and will be smaller when there are multiple peaks.
  2237. @param src1 Source floating point array (CV_32FC1 or CV_64FC1)
  2238. @param src2 Source floating point array (CV_32FC1 or CV_64FC1)
  2239. @param window Floating point array with windowing coefficients to reduce edge effects (optional).
  2240. @param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional).
  2241. @returns detected phase shift (sub-pixel) between the two arrays.
  2242. @sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow
  2243. */
  2244. CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2,
  2245. InputArray window = noArray(), CV_OUT double* response = 0);
  2246. /** @brief This function computes a Hanning window coefficients in two dimensions.
  2247. See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function)
  2248. for more information.
  2249. An example is shown below:
  2250. @code
  2251. // create hanning window of size 100x100 and type CV_32F
  2252. Mat hann;
  2253. createHanningWindow(hann, Size(100, 100), CV_32F);
  2254. @endcode
  2255. @param dst Destination array to place Hann coefficients in
  2256. @param winSize The window size specifications (both width and height must be > 1)
  2257. @param type Created array type
  2258. */
  2259. CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type);
  2260. //! @} imgproc_motion
  2261. //! @addtogroup imgproc_misc
  2262. //! @{
  2263. /** @brief Applies a fixed-level threshold to each array element.
  2264. The function applies fixed-level thresholding to a multiple-channel array. The function is typically
  2265. used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for
  2266. this purpose) or for removing a noise, that is, filtering out pixels with too small or too large
  2267. values. There are several types of thresholding supported by the function. They are determined by
  2268. type parameter.
  2269. Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the
  2270. above values. In these cases, the function determines the optimal threshold value using the Otsu's
  2271. or Triangle algorithm and uses it instead of the specified thresh.
  2272. @note Currently, the Otsu's and Triangle methods are implemented only for 8-bit single-channel images.
  2273. @param src input array (multiple-channel, 8-bit or 32-bit floating point).
  2274. @param dst output array of the same size and type and the same number of channels as src.
  2275. @param thresh threshold value.
  2276. @param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding
  2277. types.
  2278. @param type thresholding type (see #ThresholdTypes).
  2279. @return the computed threshold value if Otsu's or Triangle methods used.
  2280. @sa adaptiveThreshold, findContours, compare, min, max
  2281. */
  2282. CV_EXPORTS_W double threshold( InputArray src, OutputArray dst,
  2283. double thresh, double maxval, int type );
  2284. /** @brief Applies an adaptive threshold to an array.
  2285. The function transforms a grayscale image to a binary image according to the formulae:
  2286. - **THRESH_BINARY**
  2287. \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f]
  2288. - **THRESH_BINARY_INV**
  2289. \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f]
  2290. where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter).
  2291. The function can process the image in-place.
  2292. @param src Source 8-bit single-channel image.
  2293. @param dst Destination image of the same size and the same type as src.
  2294. @param maxValue Non-zero value assigned to the pixels for which the condition is satisfied
  2295. @param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes.
  2296. The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries.
  2297. @param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV,
  2298. see #ThresholdTypes.
  2299. @param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the
  2300. pixel: 3, 5, 7, and so on.
  2301. @param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it
  2302. is positive but may be zero or negative as well.
  2303. @sa threshold, blur, GaussianBlur
  2304. */
  2305. CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst,
  2306. double maxValue, int adaptiveMethod,
  2307. int thresholdType, int blockSize, double C );
  2308. //! @} imgproc_misc
  2309. //! @addtogroup imgproc_filter
  2310. //! @{
  2311. /** @example samples/cpp/tutorial_code/ImgProc/Pyramids/Pyramids.cpp
  2312. An example using pyrDown and pyrUp functions
  2313. */
  2314. /** @brief Blurs an image and downsamples it.
  2315. By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in
  2316. any case, the following conditions should be satisfied:
  2317. \f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f]
  2318. The function performs the downsampling step of the Gaussian pyramid construction. First, it
  2319. convolves the source image with the kernel:
  2320. \f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f]
  2321. Then, it downsamples the image by rejecting even rows and columns.
  2322. @param src input image.
  2323. @param dst output image; it has the specified size and the same type as src.
  2324. @param dstsize size of the output image.
  2325. @param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported)
  2326. */
  2327. CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst,
  2328. const Size& dstsize = Size(), int borderType = BORDER_DEFAULT );
  2329. /** @brief Upsamples an image and then blurs it.
  2330. By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any
  2331. case, the following conditions should be satisfied:
  2332. \f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\f]
  2333. The function performs the upsampling step of the Gaussian pyramid construction, though it can
  2334. actually be used to construct the Laplacian pyramid. First, it upsamples the source image by
  2335. injecting even zero rows and columns and then convolves the result with the same kernel as in
  2336. pyrDown multiplied by 4.
  2337. @param src input image.
  2338. @param dst output image. It has the specified size and the same type as src .
  2339. @param dstsize size of the output image.
  2340. @param borderType Pixel extrapolation method, see #BorderTypes (only #BORDER_DEFAULT is supported)
  2341. */
  2342. CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst,
  2343. const Size& dstsize = Size(), int borderType = BORDER_DEFAULT );
  2344. /** @brief Constructs the Gaussian pyramid for an image.
  2345. The function constructs a vector of images and builds the Gaussian pyramid by recursively applying
  2346. pyrDown to the previously built pyramid layers, starting from `dst[0]==src`.
  2347. @param src Source image. Check pyrDown for the list of supported types.
  2348. @param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the
  2349. same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on.
  2350. @param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative.
  2351. @param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported)
  2352. */
  2353. CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst,
  2354. int maxlevel, int borderType = BORDER_DEFAULT );
  2355. //! @} imgproc_filter
  2356. //! @addtogroup imgproc_transform
  2357. //! @{
  2358. /** @brief Transforms an image to compensate for lens distortion.
  2359. The function transforms an image to compensate radial and tangential lens distortion.
  2360. The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap
  2361. (with bilinear interpolation). See the former function for details of the transformation being
  2362. performed.
  2363. Those pixels in the destination image, for which there is no correspondent pixels in the source
  2364. image, are filled with zeros (black color).
  2365. A particular subset of the source image that will be visible in the corrected image can be regulated
  2366. by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate
  2367. newCameraMatrix depending on your requirements.
  2368. The camera matrix and the distortion parameters can be determined using #calibrateCamera. If
  2369. the resolution of images is different from the resolution used at the calibration stage, \f$f_x,
  2370. f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain
  2371. the same.
  2372. @param src Input (distorted) image.
  2373. @param dst Output (corrected) image that has the same size and type as src .
  2374. @param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  2375. @param distCoeffs Input vector of distortion coefficients
  2376. \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$
  2377. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  2378. @param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as
  2379. cameraMatrix but you may additionally scale and shift the result by using a different matrix.
  2380. */
  2381. CV_EXPORTS_W void undistort( InputArray src, OutputArray dst,
  2382. InputArray cameraMatrix,
  2383. InputArray distCoeffs,
  2384. InputArray newCameraMatrix = noArray() );
  2385. /** @brief Computes the undistortion and rectification transformation map.
  2386. The function computes the joint undistortion and rectification transformation and represents the
  2387. result in the form of maps for remap. The undistorted image looks like original, as if it is
  2388. captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a
  2389. monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by
  2390. #getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera,
  2391. newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify .
  2392. Also, this new camera is oriented differently in the coordinate space, according to R. That, for
  2393. example, helps to align two heads of a stereo camera so that the epipolar lines on both images
  2394. become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera).
  2395. The function actually builds the maps for the inverse mapping algorithm that is used by remap. That
  2396. is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function
  2397. computes the corresponding coordinates in the source image (that is, in the original image from
  2398. camera). The following process is applied:
  2399. \f[
  2400. \begin{array}{l}
  2401. x \leftarrow (u - {c'}_x)/{f'}_x \\
  2402. y \leftarrow (v - {c'}_y)/{f'}_y \\
  2403. {[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\
  2404. x' \leftarrow X/W \\
  2405. y' \leftarrow Y/W \\
  2406. r^2 \leftarrow x'^2 + y'^2 \\
  2407. 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}
  2408. + 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\
  2409. 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}
  2410. + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\
  2411. s\vecthree{x'''}{y'''}{1} =
  2412. \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)}
  2413. {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)}
  2414. {0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\
  2415. map_x(u,v) \leftarrow x''' f_x + c_x \\
  2416. map_y(u,v) \leftarrow y''' f_y + c_y
  2417. \end{array}
  2418. \f]
  2419. 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$
  2420. are the distortion coefficients.
  2421. In case of a stereo camera, this function is called twice: once for each camera head, after
  2422. stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera
  2423. was not calibrated, it is still possible to compute the rectification transformations directly from
  2424. the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes
  2425. homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D
  2426. space. R can be computed from H as
  2427. \f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f]
  2428. where cameraMatrix can be chosen arbitrarily.
  2429. @param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  2430. @param distCoeffs Input vector of distortion coefficients
  2431. \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$
  2432. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  2433. @param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 ,
  2434. computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation
  2435. is assumed. In cvInitUndistortMap R assumed to be an identity matrix.
  2436. @param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$.
  2437. @param size Undistorted image size.
  2438. @param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps
  2439. @param map1 The first output map.
  2440. @param map2 The second output map.
  2441. */
  2442. CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs,
  2443. InputArray R, InputArray newCameraMatrix,
  2444. Size size, int m1type, OutputArray map1, OutputArray map2 );
  2445. //! initializes maps for #remap for wide-angle
  2446. CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs,
  2447. Size imageSize, int destImageWidth,
  2448. int m1type, OutputArray map1, OutputArray map2,
  2449. int projType = PROJ_SPHERICAL_EQRECT, double alpha = 0);
  2450. /** @brief Returns the default new camera matrix.
  2451. The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when
  2452. centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true).
  2453. In the latter case, the new camera matrix will be:
  2454. \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]
  2455. where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively.
  2456. By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not
  2457. move the principal point. However, when you work with stereo, it is important to move the principal
  2458. points in both views to the same y-coordinate (which is required by most of stereo correspondence
  2459. algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for
  2460. each view where the principal points are located at the center.
  2461. @param cameraMatrix Input camera matrix.
  2462. @param imgsize Camera view image size in pixels.
  2463. @param centerPrincipalPoint Location of the principal point in the new camera matrix. The
  2464. parameter indicates whether this location should be at the image center or not.
  2465. */
  2466. CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize = Size(),
  2467. bool centerPrincipalPoint = false );
  2468. /** @brief Computes the ideal point coordinates from the observed point coordinates.
  2469. The function is similar to #undistort and #initUndistortRectifyMap but it operates on a
  2470. sparse set of points instead of a raster image. Also the function performs a reverse transformation
  2471. to projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a
  2472. planar object, it does, up to a translation vector, if the proper R is specified.
  2473. For each observed point coordinate \f$(u, v)\f$ the function computes:
  2474. \f[
  2475. \begin{array}{l}
  2476. x^{"} \leftarrow (u - c_x)/f_x \\
  2477. y^{"} \leftarrow (v - c_y)/f_y \\
  2478. (x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\
  2479. {[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\
  2480. x \leftarrow X/W \\
  2481. y \leftarrow Y/W \\
  2482. \text{only performed if P is specified:} \\
  2483. u' \leftarrow x {f'}_x + {c'}_x \\
  2484. v' \leftarrow y {f'}_y + {c'}_y
  2485. \end{array}
  2486. \f]
  2487. where *undistort* is an approximate iterative algorithm that estimates the normalized original
  2488. point coordinates out of the normalized distorted point coordinates ("normalized" means that the
  2489. coordinates do not depend on the camera matrix).
  2490. The function can be used for both a stereo camera head or a monocular camera (when R is empty).
  2491. @param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or
  2492. vector\<Point2f\> ).
  2493. @param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\<Point2f\> ) after undistortion and reverse perspective
  2494. transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates.
  2495. @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ .
  2496. @param distCoeffs Input vector of distortion coefficients
  2497. \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$
  2498. of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed.
  2499. @param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by
  2500. #stereoRectify can be passed here. If the matrix is empty, the identity transformation is used.
  2501. @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
  2502. #stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used.
  2503. */
  2504. CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst,
  2505. InputArray cameraMatrix, InputArray distCoeffs,
  2506. InputArray R = noArray(), InputArray P = noArray() );
  2507. /** @overload
  2508. @note Default version of #undistortPoints does 5 iterations to compute undistorted points.
  2509. */
  2510. CV_EXPORTS_AS(undistortPointsIter) void undistortPoints( InputArray src, OutputArray dst,
  2511. InputArray cameraMatrix, InputArray distCoeffs,
  2512. InputArray R, InputArray P, TermCriteria criteria );
  2513. //! @} imgproc_transform
  2514. //! @addtogroup imgproc_hist
  2515. //! @{
  2516. /** @example samples/cpp/demhist.cpp
  2517. An example for creating histograms of an image
  2518. */
  2519. /** @brief Calculates a histogram of a set of arrays.
  2520. The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used
  2521. to increment a histogram bin are taken from the corresponding input arrays at the same location. The
  2522. sample below shows how to compute a 2D Hue-Saturation histogram for a color image. :
  2523. @include snippets/imgproc_calcHist.cpp
  2524. @param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same
  2525. size. Each of them can have an arbitrary number of channels.
  2526. @param nimages Number of source images.
  2527. @param channels List of the dims channels used to compute the histogram. The first array channels
  2528. are numerated from 0 to images[0].channels()-1 , the second array channels are counted from
  2529. images[0].channels() to images[0].channels() + images[1].channels()-1, and so on.
  2530. @param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size
  2531. as images[i] . The non-zero mask elements mark the array elements counted in the histogram.
  2532. @param hist Output histogram, which is a dense or sparse dims -dimensional array.
  2533. @param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS
  2534. (equal to 32 in the current OpenCV version).
  2535. @param histSize Array of histogram sizes in each dimension.
  2536. @param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the
  2537. histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower
  2538. (inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary
  2539. \f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a
  2540. uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform (
  2541. uniform=false ), then each of ranges[i] contains histSize[i]+1 elements:
  2542. \f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$
  2543. . The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not
  2544. counted in the histogram.
  2545. @param uniform Flag indicating whether the histogram is uniform or not (see above).
  2546. @param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning
  2547. when it is allocated. This feature enables you to compute a single histogram from several sets of
  2548. arrays, or to update the histogram in time.
  2549. */
  2550. CV_EXPORTS void calcHist( const Mat* images, int nimages,
  2551. const int* channels, InputArray mask,
  2552. OutputArray hist, int dims, const int* histSize,
  2553. const float** ranges, bool uniform = true, bool accumulate = false );
  2554. /** @overload
  2555. this variant uses %SparseMat for output
  2556. */
  2557. CV_EXPORTS void calcHist( const Mat* images, int nimages,
  2558. const int* channels, InputArray mask,
  2559. SparseMat& hist, int dims,
  2560. const int* histSize, const float** ranges,
  2561. bool uniform = true, bool accumulate = false );
  2562. /** @overload */
  2563. CV_EXPORTS_W void calcHist( InputArrayOfArrays images,
  2564. const std::vector<int>& channels,
  2565. InputArray mask, OutputArray hist,
  2566. const std::vector<int>& histSize,
  2567. const std::vector<float>& ranges,
  2568. bool accumulate = false );
  2569. /** @brief Calculates the back projection of a histogram.
  2570. The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to
  2571. #calcHist , at each location (x, y) the function collects the values from the selected channels
  2572. in the input images and finds the corresponding histogram bin. But instead of incrementing it, the
  2573. function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of
  2574. statistics, the function computes probability of each element value in respect with the empirical
  2575. probability distribution represented by the histogram. See how, for example, you can find and track
  2576. a bright-colored object in a scene:
  2577. - Before tracking, show the object to the camera so that it covers almost the whole frame.
  2578. Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant
  2579. colors in the object.
  2580. - When tracking, calculate a back projection of a hue plane of each input video frame using that
  2581. pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make
  2582. sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels.
  2583. - Find connected components in the resulting picture and choose, for example, the largest
  2584. component.
  2585. This is an approximate algorithm of the CamShift color object tracker.
  2586. @param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same
  2587. size. Each of them can have an arbitrary number of channels.
  2588. @param nimages Number of source images.
  2589. @param channels The list of channels used to compute the back projection. The number of channels
  2590. must match the histogram dimensionality. The first array channels are numerated from 0 to
  2591. images[0].channels()-1 , the second array channels are counted from images[0].channels() to
  2592. images[0].channels() + images[1].channels()-1, and so on.
  2593. @param hist Input histogram that can be dense or sparse.
  2594. @param backProject Destination back projection array that is a single-channel array of the same
  2595. size and depth as images[0] .
  2596. @param ranges Array of arrays of the histogram bin boundaries in each dimension. See #calcHist .
  2597. @param scale Optional scale factor for the output back projection.
  2598. @param uniform Flag indicating whether the histogram is uniform or not (see above).
  2599. @sa calcHist, compareHist
  2600. */
  2601. CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
  2602. const int* channels, InputArray hist,
  2603. OutputArray backProject, const float** ranges,
  2604. double scale = 1, bool uniform = true );
  2605. /** @overload */
  2606. CV_EXPORTS void calcBackProject( const Mat* images, int nimages,
  2607. const int* channels, const SparseMat& hist,
  2608. OutputArray backProject, const float** ranges,
  2609. double scale = 1, bool uniform = true );
  2610. /** @overload */
  2611. CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector<int>& channels,
  2612. InputArray hist, OutputArray dst,
  2613. const std::vector<float>& ranges,
  2614. double scale );
  2615. /** @brief Compares two histograms.
  2616. The function cv::compareHist compares two dense or two sparse histograms using the specified method.
  2617. The function returns \f$d(H_1, H_2)\f$ .
  2618. While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable
  2619. for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling
  2620. problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms
  2621. or more general sparse configurations of weighted points, consider using the #EMD function.
  2622. @param H1 First compared histogram.
  2623. @param H2 Second compared histogram of the same size as H1 .
  2624. @param method Comparison method, see #HistCompMethods
  2625. */
  2626. CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method );
  2627. /** @overload */
  2628. CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method );
  2629. /** @brief Equalizes the histogram of a grayscale image.
  2630. The function equalizes the histogram of the input image using the following algorithm:
  2631. - Calculate the histogram \f$H\f$ for src .
  2632. - Normalize the histogram so that the sum of histogram bins is 255.
  2633. - Compute the integral of the histogram:
  2634. \f[H'_i = \sum _{0 \le j < i} H(j)\f]
  2635. - Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$
  2636. The algorithm normalizes the brightness and increases the contrast of the image.
  2637. @param src Source 8-bit single channel image.
  2638. @param dst Destination image of the same size and type as src .
  2639. */
  2640. CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst );
  2641. /** @brief Creates a smart pointer to a cv::CLAHE class and initializes it.
  2642. @param clipLimit Threshold for contrast limiting.
  2643. @param tileGridSize Size of grid for histogram equalization. Input image will be divided into
  2644. equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column.
  2645. */
  2646. CV_EXPORTS_W Ptr<CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8));
  2647. /** @brief Computes the "minimal work" distance between two weighted point configurations.
  2648. The function computes the earth mover distance and/or a lower boundary of the distance between the
  2649. two weighted point configurations. One of the applications described in @cite RubnerSept98,
  2650. @cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation
  2651. problem that is solved using some modification of a simplex algorithm, thus the complexity is
  2652. exponential in the worst case, though, on average it is much faster. In the case of a real metric
  2653. the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used
  2654. to determine roughly whether the two signatures are far enough so that they cannot relate to the
  2655. same object.
  2656. @param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix.
  2657. Each row stores the point weight followed by the point coordinates. The matrix is allowed to have
  2658. a single column (weights only) if the user-defined cost matrix is used. The weights must be
  2659. non-negative and have at least one non-zero value.
  2660. @param signature2 Second signature of the same format as signature1 , though the number of rows
  2661. may be different. The total weights may be different. In this case an extra "dummy" point is added
  2662. to either signature1 or signature2. The weights must be non-negative and have at least one non-zero
  2663. value.
  2664. @param distType Used metric. See #DistanceTypes.
  2665. @param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix
  2666. is used, lower boundary lowerBound cannot be calculated because it needs a metric function.
  2667. @param lowerBound Optional input/output parameter: lower boundary of a distance between the two
  2668. signatures that is a distance between mass centers. The lower boundary may not be calculated if
  2669. the user-defined cost matrix is used, the total weights of point configurations are not equal, or
  2670. if the signatures consist of weights only (the signature matrices have a single column). You
  2671. **must** initialize \*lowerBound . If the calculated distance between mass centers is greater or
  2672. equal to \*lowerBound (it means that the signatures are far enough), the function does not
  2673. calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on
  2674. return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound
  2675. should be set to 0.
  2676. @param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is
  2677. a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 .
  2678. */
  2679. CV_EXPORTS float EMD( InputArray signature1, InputArray signature2,
  2680. int distType, InputArray cost=noArray(),
  2681. float* lowerBound = 0, OutputArray flow = noArray() );
  2682. CV_EXPORTS_AS(EMD) float wrapperEMD( InputArray signature1, InputArray signature2,
  2683. int distType, InputArray cost=noArray(),
  2684. CV_IN_OUT Ptr<float> lowerBound = Ptr<float>(), OutputArray flow = noArray() );
  2685. //! @} imgproc_hist
  2686. /** @example samples/cpp/watershed.cpp
  2687. An example using the watershed algorithm
  2688. */
  2689. /** @brief Performs a marker-based image segmentation using the watershed algorithm.
  2690. The function implements one of the variants of watershed, non-parametric marker-based segmentation
  2691. algorithm, described in @cite Meyer92 .
  2692. Before passing the image to the function, you have to roughly outline the desired regions in the
  2693. image markers with positive (\>0) indices. So, every region is represented as one or more connected
  2694. components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary
  2695. mask using #findContours and #drawContours (see the watershed.cpp demo). The markers are "seeds" of
  2696. the future image regions. All the other pixels in markers , whose relation to the outlined regions
  2697. is not known and should be defined by the algorithm, should be set to 0's. In the function output,
  2698. each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the
  2699. regions.
  2700. @note Any two neighbor connected components are not necessarily separated by a watershed boundary
  2701. (-1's pixels); for example, they can touch each other in the initial marker image passed to the
  2702. function.
  2703. @param image Input 8-bit 3-channel image.
  2704. @param markers Input/output 32-bit single-channel image (map) of markers. It should have the same
  2705. size as image .
  2706. @sa findContours
  2707. @ingroup imgproc_misc
  2708. */
  2709. CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers );
  2710. //! @addtogroup imgproc_filter
  2711. //! @{
  2712. /** @brief Performs initial step of meanshift segmentation of an image.
  2713. The function implements the filtering stage of meanshift segmentation, that is, the output of the
  2714. function is the filtered "posterized" image with color gradients and fine-grain texture flattened.
  2715. At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes
  2716. meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is
  2717. considered:
  2718. \f[(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\f]
  2719. where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively
  2720. (though, the algorithm does not depend on the color space used, so any 3-component color space can
  2721. be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector
  2722. (R',G',B') are found and they act as the neighborhood center on the next iteration:
  2723. \f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f]
  2724. After the iterations over, the color components of the initial pixel (that is, the pixel from where
  2725. the iterations started) are set to the final value (average color at the last iteration):
  2726. \f[I(X,Y) <- (R*,G*,B*)\f]
  2727. When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is
  2728. run on the smallest layer first. After that, the results are propagated to the larger layer and the
  2729. iterations are run again only on those pixels where the layer colors differ by more than sr from the
  2730. lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the
  2731. results will be actually different from the ones obtained by running the meanshift procedure on the
  2732. whole original image (i.e. when maxLevel==0).
  2733. @param src The source 8-bit, 3-channel image.
  2734. @param dst The destination image of the same format and the same size as the source.
  2735. @param sp The spatial window radius.
  2736. @param sr The color window radius.
  2737. @param maxLevel Maximum level of the pyramid for the segmentation.
  2738. @param termcrit Termination criteria: when to stop meanshift iterations.
  2739. */
  2740. CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst,
  2741. double sp, double sr, int maxLevel = 1,
  2742. TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) );
  2743. //! @}
  2744. //! @addtogroup imgproc_misc
  2745. //! @{
  2746. /** @example samples/cpp/grabcut.cpp
  2747. An example using the GrabCut algorithm
  2748. ![Sample Screenshot](grabcut_output1.jpg)
  2749. */
  2750. /** @brief Runs the GrabCut algorithm.
  2751. The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut).
  2752. @param img Input 8-bit 3-channel image.
  2753. @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when
  2754. mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses.
  2755. @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as
  2756. "obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT .
  2757. @param bgdModel Temporary array for the background model. Do not modify it while you are
  2758. processing the same image.
  2759. @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are
  2760. processing the same image.
  2761. @param iterCount Number of iterations the algorithm should make before returning the result. Note
  2762. that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or
  2763. mode==GC_EVAL .
  2764. @param mode Operation mode that could be one of the #GrabCutModes
  2765. */
  2766. CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect,
  2767. InputOutputArray bgdModel, InputOutputArray fgdModel,
  2768. int iterCount, int mode = GC_EVAL );
  2769. /** @example samples/cpp/distrans.cpp
  2770. An example on using the distance transform
  2771. */
  2772. /** @brief Calculates the distance to the closest zero pixel for each pixel of the source image.
  2773. The function cv::distanceTransform calculates the approximate or precise distance from every binary
  2774. image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero.
  2775. When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the
  2776. algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library.
  2777. In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function
  2778. finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical,
  2779. diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall
  2780. distance is calculated as a sum of these basic distances. Since the distance function should be
  2781. symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all
  2782. the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the
  2783. same cost (denoted as `c`). For the #DIST_C and #DIST_L1 types, the distance is calculated
  2784. precisely, whereas for #DIST_L2 (Euclidean distance) the distance can be calculated only with a
  2785. relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV
  2786. uses the values suggested in the original paper:
  2787. - DIST_L1: `a = 1, b = 2`
  2788. - DIST_L2:
  2789. - `3 x 3`: `a=0.955, b=1.3693`
  2790. - `5 x 5`: `a=1, b=1.4, c=2.1969`
  2791. - DIST_C: `a = 1, b = 1`
  2792. Typically, for a fast, coarse distance estimation #DIST_L2, a \f$3\times 3\f$ mask is used. For a
  2793. more accurate distance estimation #DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used.
  2794. Note that both the precise and the approximate algorithms are linear on the number of pixels.
  2795. This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$
  2796. but also identifies the nearest connected component consisting of zero pixels
  2797. (labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the
  2798. component/pixel is stored in `labels(x, y)`. When labelType==#DIST_LABEL_CCOMP, the function
  2799. automatically finds connected components of zero pixels in the input image and marks them with
  2800. distinct labels. When labelType==#DIST_LABEL_CCOMP, the function scans through the input image and
  2801. marks all the zero pixels with distinct labels.
  2802. In this mode, the complexity is still linear. That is, the function provides a very fast way to
  2803. compute the Voronoi diagram for a binary image. Currently, the second variant can use only the
  2804. approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported
  2805. yet.
  2806. @param src 8-bit, single-channel (binary) source image.
  2807. @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point,
  2808. single-channel image of the same size as src.
  2809. @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type
  2810. CV_32SC1 and the same size as src.
  2811. @param distanceType Type of distance, see #DistanceTypes
  2812. @param maskSize Size of the distance transform mask, see #DistanceTransformMasks.
  2813. #DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type,
  2814. the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times
  2815. 5\f$ or any larger aperture.
  2816. @param labelType Type of the label array to build, see #DistanceTransformLabelTypes.
  2817. */
  2818. CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst,
  2819. OutputArray labels, int distanceType, int maskSize,
  2820. int labelType = DIST_LABEL_CCOMP );
  2821. /** @overload
  2822. @param src 8-bit, single-channel (binary) source image.
  2823. @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point,
  2824. single-channel image of the same size as src .
  2825. @param distanceType Type of distance, see #DistanceTypes
  2826. @param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the
  2827. #DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives
  2828. the same result as \f$5\times 5\f$ or any larger aperture.
  2829. @param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for
  2830. the first variant of the function and distanceType == #DIST_L1.
  2831. */
  2832. CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst,
  2833. int distanceType, int maskSize, int dstType=CV_32F);
  2834. /** @example samples/cpp/ffilldemo.cpp
  2835. An example using the FloodFill technique
  2836. */
  2837. /** @overload
  2838. variant without `mask` parameter
  2839. */
  2840. CV_EXPORTS int floodFill( InputOutputArray image,
  2841. Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0,
  2842. Scalar loDiff = Scalar(), Scalar upDiff = Scalar(),
  2843. int flags = 4 );
  2844. /** @brief Fills a connected component with the given color.
  2845. The function cv::floodFill fills a connected component starting from the seed point with the specified
  2846. color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The
  2847. pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if:
  2848. - in case of a grayscale image and floating range
  2849. \f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f]
  2850. - in case of a grayscale image and fixed range
  2851. \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f]
  2852. - in case of a color image and floating range
  2853. \f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f]
  2854. \f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f]
  2855. and
  2856. \f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f]
  2857. - in case of a color image and fixed range
  2858. \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f]
  2859. \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f]
  2860. and
  2861. \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f]
  2862. where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the
  2863. component. That is, to be added to the connected component, a color/brightness of the pixel should
  2864. be close enough to:
  2865. - Color/brightness of one of its neighbors that already belong to the connected component in case
  2866. of a floating range.
  2867. - Color/brightness of the seed point in case of a fixed range.
  2868. Use these functions to either mark a connected component with the specified color in-place, or build
  2869. a mask and then extract the contour, or copy the region to another image, and so on.
  2870. @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the
  2871. function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See
  2872. the details below.
  2873. @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels
  2874. taller than image. Since this is both an input and output parameter, you must take responsibility
  2875. of initializing it. Flood-filling cannot go across non-zero pixels in the input mask. For example,
  2876. an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the
  2877. mask corresponding to filled pixels in the image are set to 1 or to the a value specified in flags
  2878. as described below. Additionally, the function fills the border of the mask with ones to simplify
  2879. internal processing. It is therefore possible to use the same mask in multiple calls to the function
  2880. to make sure the filled areas do not overlap.
  2881. @param seedPoint Starting point.
  2882. @param newVal New value of the repainted domain pixels.
  2883. @param loDiff Maximal lower brightness/color difference between the currently observed pixel and
  2884. one of its neighbors belonging to the component, or a seed pixel being added to the component.
  2885. @param upDiff Maximal upper brightness/color difference between the currently observed pixel and
  2886. one of its neighbors belonging to the component, or a seed pixel being added to the component.
  2887. @param rect Optional output parameter set by the function to the minimum bounding rectangle of the
  2888. repainted domain.
  2889. @param flags Operation flags. The first 8 bits contain a connectivity value. The default value of
  2890. 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A
  2891. connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner)
  2892. will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill
  2893. the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest
  2894. neighbours and fill the mask with a value of 255. The following additional options occupy higher
  2895. bits and therefore may be further combined with the connectivity and mask fill values using
  2896. bit-wise or (|), see #FloodFillFlags.
  2897. @note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the
  2898. pixel \f$(x+1, y+1)\f$ in the mask .
  2899. @sa findContours
  2900. */
  2901. CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask,
  2902. Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0,
  2903. Scalar loDiff = Scalar(), Scalar upDiff = Scalar(),
  2904. int flags = 4 );
  2905. //! Performs linear blending of two images:
  2906. //! \f[ \texttt{dst}(i,j) = \texttt{weights1}(i,j)*\texttt{src1}(i,j) + \texttt{weights2}(i,j)*\texttt{src2}(i,j) \f]
  2907. //! @param src1 It has a type of CV_8UC(n) or CV_32FC(n), where n is a positive integer.
  2908. //! @param src2 It has the same type and size as src1.
  2909. //! @param weights1 It has a type of CV_32FC1 and the same size with src1.
  2910. //! @param weights2 It has a type of CV_32FC1 and the same size with src1.
  2911. //! @param dst It is created if it does not have the same size and type with src1.
  2912. CV_EXPORTS void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst);
  2913. //! @} imgproc_misc
  2914. //! @addtogroup imgproc_color_conversions
  2915. //! @{
  2916. /** @brief Converts an image from one color space to another.
  2917. The function converts an input image from one color space to another. In case of a transformation
  2918. to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note
  2919. that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the
  2920. bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue
  2921. component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and
  2922. sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.
  2923. The conventional ranges for R, G, and B channel values are:
  2924. - 0 to 255 for CV_8U images
  2925. - 0 to 65535 for CV_16U images
  2926. - 0 to 1 for CV_32F images
  2927. In case of linear transformations, the range does not matter. But in case of a non-linear
  2928. transformation, an input RGB image should be normalized to the proper value range to get the correct
  2929. results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a
  2930. 32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will
  2931. have the 0..255 value range instead of 0..1 assumed by the function. So, before calling #cvtColor ,
  2932. you need first to scale the image down:
  2933. @code
  2934. img *= 1./255;
  2935. cvtColor(img, img, COLOR_BGR2Luv);
  2936. @endcode
  2937. If you use #cvtColor with 8-bit images, the conversion will have some information lost. For many
  2938. applications, this will not be noticeable but it is recommended to use 32-bit images in applications
  2939. that need the full range of colors or that convert an image before an operation and then convert
  2940. back.
  2941. If conversion adds the alpha channel, its value will set to the maximum of corresponding channel
  2942. range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F.
  2943. @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision
  2944. floating-point.
  2945. @param dst output image of the same size and depth as src.
  2946. @param code color space conversion code (see #ColorConversionCodes).
  2947. @param dstCn number of channels in the destination image; if the parameter is 0, the number of the
  2948. channels is derived automatically from src and code.
  2949. @see @ref imgproc_color_conversions
  2950. */
  2951. CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0 );
  2952. /** @brief Converts an image from one color space to another where the source image is
  2953. stored in two planes.
  2954. This function only supports YUV420 to RGB conversion as of now.
  2955. @param src1: 8-bit image (#CV_8U) of the Y plane.
  2956. @param src2: image containing interleaved U/V plane.
  2957. @param dst: output image.
  2958. @param code: Specifies the type of conversion. It can take any of the following values:
  2959. - #COLOR_YUV2BGR_NV12
  2960. - #COLOR_YUV2RGB_NV12
  2961. - #COLOR_YUV2BGRA_NV12
  2962. - #COLOR_YUV2RGBA_NV12
  2963. - #COLOR_YUV2BGR_NV21
  2964. - #COLOR_YUV2RGB_NV21
  2965. - #COLOR_YUV2BGRA_NV21
  2966. - #COLOR_YUV2RGBA_NV21
  2967. */
  2968. CV_EXPORTS_W void cvtColorTwoPlane( InputArray src1, InputArray src2, OutputArray dst, int code );
  2969. /** @brief main function for all demosaicing processes
  2970. @param src input image: 8-bit unsigned or 16-bit unsigned.
  2971. @param dst output image of the same size and depth as src.
  2972. @param code Color space conversion code (see the description below).
  2973. @param dstCn number of channels in the destination image; if the parameter is 0, the number of the
  2974. channels is derived automatically from src and code.
  2975. The function can do the following transformations:
  2976. - Demosaicing using bilinear interpolation
  2977. #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR
  2978. #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY
  2979. - Demosaicing using Variable Number of Gradients.
  2980. #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG
  2981. - Edge-Aware Demosaicing.
  2982. #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA
  2983. - Demosaicing with alpha channel
  2984. #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA
  2985. @sa cvtColor
  2986. */
  2987. CV_EXPORTS_W void demosaicing(InputArray src, OutputArray dst, int code, int dstCn = 0);
  2988. //! @} imgproc_color_conversions
  2989. //! @addtogroup imgproc_shape
  2990. //! @{
  2991. /** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape.
  2992. The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The
  2993. results are returned in the structure cv::Moments.
  2994. @param array Raster image (single-channel, 8-bit or floating-point 2D array) or an array (
  2995. \f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f ).
  2996. @param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is
  2997. used for images only.
  2998. @returns moments.
  2999. @note Only applicable to contour moments calculations from Python bindings: Note that the numpy
  3000. type for the input array should be either np.int32 or np.float32.
  3001. @sa contourArea, arcLength
  3002. */
  3003. CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false );
  3004. /** @brief Calculates seven Hu invariants.
  3005. The function calculates seven Hu invariants (introduced in @cite Hu62; see also
  3006. <http://en.wikipedia.org/wiki/Image_moment>) defined as:
  3007. \f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f]
  3008. where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ .
  3009. These values are proved to be invariants to the image scale, rotation, and reflection except the
  3010. seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of
  3011. infinite image resolution. In case of raster images, the computed Hu invariants for the original and
  3012. transformed images are a bit different.
  3013. @param moments Input moments computed with moments .
  3014. @param hu Output Hu invariants.
  3015. @sa matchShapes
  3016. */
  3017. CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] );
  3018. /** @overload */
  3019. CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu );
  3020. //! @} imgproc_shape
  3021. //! @addtogroup imgproc_object
  3022. //! @{
  3023. //! type of the template matching operation
  3024. enum TemplateMatchModes {
  3025. TM_SQDIFF = 0, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f]
  3026. TM_SQDIFF_NORMED = 1, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f]
  3027. TM_CCORR = 2, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f]
  3028. TM_CCORR_NORMED = 3, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f]
  3029. TM_CCOEFF = 4, //!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f]
  3030. //!< where
  3031. //!< \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f]
  3032. TM_CCOEFF_NORMED = 5 //!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }\f]
  3033. };
  3034. /** @example samples/cpp/tutorial_code/Histograms_Matching/MatchTemplate_Demo.cpp
  3035. An example using Template Matching algorithm
  3036. */
  3037. /** @brief Compares a template against overlapped image regions.
  3038. The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against
  3039. templ using the specified method and stores the comparison results in result . Here are the formulae
  3040. for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ template, \f$R\f$ result ). The summation
  3041. is done over template and/or the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$
  3042. After the function finishes the comparison, the best matches can be found as global minimums (when
  3043. #TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the
  3044. #minMaxLoc function. In case of a color image, template summation in the numerator and each sum in
  3045. the denominator is done over all of the channels and separate mean values are used for each channel.
  3046. That is, the function can take a color template and a color image. The result will still be a
  3047. single-channel image, which is easier to analyze.
  3048. @param image Image where the search is running. It must be 8-bit or 32-bit floating-point.
  3049. @param templ Searched template. It must be not greater than the source image and have the same
  3050. data type.
  3051. @param result Map of comparison results. It must be single-channel 32-bit floating-point. If image
  3052. is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ .
  3053. @param method Parameter specifying the comparison method, see #TemplateMatchModes
  3054. @param mask Mask of searched template. It must have the same datatype and size with templ. It is
  3055. not set by default. Currently, only the #TM_SQDIFF and #TM_CCORR_NORMED methods are supported.
  3056. */
  3057. CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ,
  3058. OutputArray result, int method, InputArray mask = noArray() );
  3059. //! @}
  3060. //! @addtogroup imgproc_shape
  3061. //! @{
  3062. /** @example samples/cpp/connected_components.cpp
  3063. This program demonstrates connected components and use of the trackbar
  3064. */
  3065. /** @brief computes the connected components labeled image of boolean image
  3066. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0
  3067. represents the background label. ltype specifies the output label image type, an important
  3068. consideration based on the total number of labels or alternatively the total number of pixels in
  3069. the source image. ccltype specifies the connected components labeling algorithm to use, currently
  3070. Grana (BBDT) and Wu's (SAUF) @cite Wu2009 algorithms are supported, see the #ConnectedComponentsAlgorithmsTypes
  3071. for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not.
  3072. This function uses parallel version of both Grana and Wu's algorithms if at least one allowed
  3073. parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs.
  3074. @param image the 8-bit single-channel image to be labeled
  3075. @param labels destination labeled image
  3076. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
  3077. @param ltype output image label type. Currently CV_32S and CV_16U are supported.
  3078. @param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes).
  3079. */
  3080. CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels,
  3081. int connectivity, int ltype, int ccltype);
  3082. /** @overload
  3083. @param image the 8-bit single-channel image to be labeled
  3084. @param labels destination labeled image
  3085. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
  3086. @param ltype output image label type. Currently CV_32S and CV_16U are supported.
  3087. */
  3088. CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels,
  3089. int connectivity = 8, int ltype = CV_32S);
  3090. /** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label
  3091. image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0
  3092. represents the background label. ltype specifies the output label image type, an important
  3093. consideration based on the total number of labels or alternatively the total number of pixels in
  3094. the source image. ccltype specifies the connected components labeling algorithm to use, currently
  3095. Grana's (BBDT) and Wu's (SAUF) @cite Wu2009 algorithms are supported, see the #ConnectedComponentsAlgorithmsTypes
  3096. for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not.
  3097. This function uses parallel version of both Grana and Wu's algorithms (statistics included) if at least one allowed
  3098. parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs.
  3099. @param image the 8-bit single-channel image to be labeled
  3100. @param labels destination labeled image
  3101. @param stats statistics output for each label, including the background label.
  3102. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
  3103. #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S.
  3104. @param centroids centroid output for each label, including the background label. Centroids are
  3105. accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
  3106. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
  3107. @param ltype output image label type. Currently CV_32S and CV_16U are supported.
  3108. @param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes).
  3109. */
  3110. CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels,
  3111. OutputArray stats, OutputArray centroids,
  3112. int connectivity, int ltype, int ccltype);
  3113. /** @overload
  3114. @param image the 8-bit single-channel image to be labeled
  3115. @param labels destination labeled image
  3116. @param stats statistics output for each label, including the background label.
  3117. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of
  3118. #ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S.
  3119. @param centroids centroid output for each label, including the background label. Centroids are
  3120. accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F.
  3121. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively
  3122. @param ltype output image label type. Currently CV_32S and CV_16U are supported.
  3123. */
  3124. CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels,
  3125. OutputArray stats, OutputArray centroids,
  3126. int connectivity = 8, int ltype = CV_32S);
  3127. /** @brief Finds contours in a binary image.
  3128. The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours
  3129. are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the
  3130. OpenCV sample directory.
  3131. @note Since opencv 3.2 source image is not modified by this function.
  3132. @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero
  3133. pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold ,
  3134. #adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one.
  3135. If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1).
  3136. @param contours Detected contours. Each contour is stored as a vector of points (e.g.
  3137. std::vector<std::vector<cv::Point> >).
  3138. @param hierarchy Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has
  3139. as many elements as the number of contours. For each i-th contour contours[i], the elements
  3140. hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices
  3141. in contours of the next and previous contours at the same hierarchical level, the first child
  3142. contour and the parent contour, respectively. If for the contour i there are no next, previous,
  3143. parent, or nested contours, the corresponding elements of hierarchy[i] will be negative.
  3144. @param mode Contour retrieval mode, see #RetrievalModes
  3145. @param method Contour approximation method, see #ContourApproximationModes
  3146. @param offset Optional offset by which every contour point is shifted. This is useful if the
  3147. contours are extracted from the image ROI and then they should be analyzed in the whole image
  3148. context.
  3149. */
  3150. CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours,
  3151. OutputArray hierarchy, int mode,
  3152. int method, Point offset = Point());
  3153. /** @overload */
  3154. CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours,
  3155. int mode, int method, Point offset = Point());
  3156. /** @example samples/cpp/squares.cpp
  3157. A program using pyramid scaling, Canny, contours and contour simplification to find
  3158. squares in a list of images (pic1-6.png). Returns sequence of squares detected on the image.
  3159. */
  3160. /** @example samples/tapi/squares.cpp
  3161. A program using pyramid scaling, Canny, contours and contour simplification to find
  3162. squares in the input image.
  3163. */
  3164. /** @brief Approximates a polygonal curve(s) with the specified precision.
  3165. The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less
  3166. vertices so that the distance between them is less or equal to the specified precision. It uses the
  3167. Douglas-Peucker algorithm <http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm>
  3168. @param curve Input vector of a 2D point stored in std::vector or Mat
  3169. @param approxCurve Result of the approximation. The type should match the type of the input curve.
  3170. @param epsilon Parameter specifying the approximation accuracy. This is the maximum distance
  3171. between the original curve and its approximation.
  3172. @param closed If true, the approximated curve is closed (its first and last vertices are
  3173. connected). Otherwise, it is not closed.
  3174. */
  3175. CV_EXPORTS_W void approxPolyDP( InputArray curve,
  3176. OutputArray approxCurve,
  3177. double epsilon, bool closed );
  3178. /** @brief Calculates a contour perimeter or a curve length.
  3179. The function computes a curve length or a closed contour perimeter.
  3180. @param curve Input vector of 2D points, stored in std::vector or Mat.
  3181. @param closed Flag indicating whether the curve is closed or not.
  3182. */
  3183. CV_EXPORTS_W double arcLength( InputArray curve, bool closed );
  3184. /** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image.
  3185. The function calculates and returns the minimal up-right bounding rectangle for the specified point set or
  3186. non-zero pixels of gray-scale image.
  3187. @param array Input gray-scale image or 2D point set, stored in std::vector or Mat.
  3188. */
  3189. CV_EXPORTS_W Rect boundingRect( InputArray array );
  3190. /** @brief Calculates a contour area.
  3191. The function computes a contour area. Similarly to moments , the area is computed using the Green
  3192. formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using
  3193. #drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong
  3194. results for contours with self-intersections.
  3195. Example:
  3196. @code
  3197. vector<Point> contour;
  3198. contour.push_back(Point2f(0, 0));
  3199. contour.push_back(Point2f(10, 0));
  3200. contour.push_back(Point2f(10, 10));
  3201. contour.push_back(Point2f(5, 4));
  3202. double area0 = contourArea(contour);
  3203. vector<Point> approx;
  3204. approxPolyDP(contour, approx, 5, true);
  3205. double area1 = contourArea(approx);
  3206. cout << "area0 =" << area0 << endl <<
  3207. "area1 =" << area1 << endl <<
  3208. "approx poly vertices" << approx.size() << endl;
  3209. @endcode
  3210. @param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat.
  3211. @param oriented Oriented area flag. If it is true, the function returns a signed area value,
  3212. depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can
  3213. determine orientation of a contour by taking the sign of an area. By default, the parameter is
  3214. false, which means that the absolute value is returned.
  3215. */
  3216. CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false );
  3217. /** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set.
  3218. The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a
  3219. specified point set. Developer should keep in mind that the returned RotatedRect can contain negative
  3220. indices when data is close to the containing Mat element boundary.
  3221. @param points Input vector of 2D points, stored in std::vector\<\> or Mat
  3222. */
  3223. CV_EXPORTS_W RotatedRect minAreaRect( InputArray points );
  3224. /** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle.
  3225. The function finds the four vertices of a rotated rectangle. This function is useful to draw the
  3226. rectangle. In C++, instead of using this function, you can directly use RotatedRect::points method. Please
  3227. visit the @ref tutorial_bounding_rotated_ellipses "tutorial on Creating Bounding rotated boxes and ellipses for contours" for more information.
  3228. @param box The input rotated rectangle. It may be the output of
  3229. @param points The output array of four vertices of rectangles.
  3230. */
  3231. CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points);
  3232. /** @brief Finds a circle of the minimum area enclosing a 2D point set.
  3233. The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm.
  3234. @param points Input vector of 2D points, stored in std::vector\<\> or Mat
  3235. @param center Output center of the circle.
  3236. @param radius Output radius of the circle.
  3237. */
  3238. CV_EXPORTS_W void minEnclosingCircle( InputArray points,
  3239. CV_OUT Point2f& center, CV_OUT float& radius );
  3240. /** @example samples/cpp/minarea.cpp
  3241. */
  3242. /** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area.
  3243. The function finds a triangle of minimum area enclosing the given set of 2D points and returns its
  3244. area. The output for a given 2D point set is shown in the image below. 2D points are depicted in
  3245. *red* and the enclosing triangle in *yellow*.
  3246. ![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png)
  3247. The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's
  3248. @cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal
  3249. enclosing triangle of a 2D convex polygon with n vertices. Since the #minEnclosingTriangle function
  3250. takes a 2D point set as input an additional preprocessing step of computing the convex hull of the
  3251. 2D point set is required. The complexity of the #convexHull function is \f$O(n log(n))\f$ which is higher
  3252. than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$.
  3253. @param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat
  3254. @param triangle Output vector of three 2D points defining the vertices of the triangle. The depth
  3255. of the OutputArray must be CV_32F.
  3256. */
  3257. CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle );
  3258. /** @brief Compares two shapes.
  3259. The function compares two shapes. All three implemented methods use the Hu invariants (see #HuMoments)
  3260. @param contour1 First contour or grayscale image.
  3261. @param contour2 Second contour or grayscale image.
  3262. @param method Comparison method, see #ShapeMatchModes
  3263. @param parameter Method-specific parameter (not supported now).
  3264. */
  3265. CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2,
  3266. int method, double parameter );
  3267. /** @example samples/cpp/convexhull.cpp
  3268. An example using the convexHull functionality
  3269. */
  3270. /** @brief Finds the convex hull of a point set.
  3271. The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82
  3272. that has *O(N logN)* complexity in the current implementation.
  3273. @param points Input 2D point set, stored in std::vector or Mat.
  3274. @param hull Output convex hull. It is either an integer vector of indices or vector of points. In
  3275. the first case, the hull elements are 0-based indices of the convex hull points in the original
  3276. array (since the set of convex hull points is a subset of the original point set). In the second
  3277. case, hull elements are the convex hull points themselves.
  3278. @param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise.
  3279. Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing
  3280. to the right, and its Y axis pointing upwards.
  3281. @param returnPoints Operation flag. In case of a matrix, when the flag is true, the function
  3282. returns convex hull points. Otherwise, it returns indices of the convex hull points. When the
  3283. output array is std::vector, the flag is ignored, and the output depends on the type of the
  3284. vector: std::vector\<int\> implies returnPoints=false, std::vector\<Point\> implies
  3285. returnPoints=true.
  3286. @note `points` and `hull` should be different arrays, inplace processing isn't supported.
  3287. Check @ref tutorial_hull "the corresponding tutorial" for more details.
  3288. useful links:
  3289. https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/
  3290. */
  3291. CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull,
  3292. bool clockwise = false, bool returnPoints = true );
  3293. /** @brief Finds the convexity defects of a contour.
  3294. The figure below displays convexity defects of a hand contour:
  3295. ![image](pics/defects.png)
  3296. @param contour Input contour.
  3297. @param convexhull Convex hull obtained using convexHull that should contain indices of the contour
  3298. points that make the hull.
  3299. @param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java
  3300. interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i):
  3301. (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices
  3302. in the original contour of the convexity defect beginning, end and the farthest point, and
  3303. fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the
  3304. farthest contour point and the hull. That is, to get the floating-point value of the depth will be
  3305. fixpt_depth/256.0.
  3306. */
  3307. CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects );
  3308. /** @brief Tests a contour convexity.
  3309. The function tests whether the input contour is convex or not. The contour must be simple, that is,
  3310. without self-intersections. Otherwise, the function output is undefined.
  3311. @param contour Input vector of 2D points, stored in std::vector\<\> or Mat
  3312. */
  3313. CV_EXPORTS_W bool isContourConvex( InputArray contour );
  3314. /** @example samples/cpp/intersectExample.cpp
  3315. Examples of how intersectConvexConvex works
  3316. */
  3317. /** @brief Finds intersection of two convex polygons
  3318. @param _p1 First polygon
  3319. @param _p2 Second polygon
  3320. @param _p12 Output polygon describing the intersecting area
  3321. @param handleNested When true, an intersection is found if one of the polygons is fully enclosed in the other.
  3322. When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge
  3323. of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested.
  3324. @returns Absolute value of area of intersecting polygon
  3325. @note intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't.
  3326. */
  3327. CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2,
  3328. OutputArray _p12, bool handleNested = true );
  3329. /** @example samples/cpp/fitellipse.cpp
  3330. An example using the fitEllipse technique
  3331. */
  3332. /** @brief Fits an ellipse around a set of 2D points.
  3333. The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of
  3334. all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95
  3335. is used. Developer should keep in mind that it is possible that the returned
  3336. ellipse/rotatedRect data contains negative indices, due to the data points being close to the
  3337. border of the containing Mat element.
  3338. @param points Input 2D point set, stored in std::vector\<\> or Mat
  3339. */
  3340. CV_EXPORTS_W RotatedRect fitEllipse( InputArray points );
  3341. /** @brief Fits an ellipse around a set of 2D points.
  3342. The function calculates the ellipse that fits a set of 2D points.
  3343. It returns the rotated rectangle in which the ellipse is inscribed.
  3344. The Approximate Mean Square (AMS) proposed by @cite Taubin1991 is used.
  3345. For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$,
  3346. which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$.
  3347. However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$,
  3348. the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines,
  3349. quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits.
  3350. If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used.
  3351. The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves
  3352. by imposing the condition that \f$ A^T ( D_x^T D_x + D_y^T D_y) A = 1 \f$ where
  3353. the matrices \f$ Dx \f$ and \f$ Dy \f$ are the partial derivatives of the design matrix \f$ D \f$ with
  3354. respect to x and y. The matrices are formed row by row applying the following to
  3355. each of the points in the set:
  3356. \f{align*}{
  3357. D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} &
  3358. D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} &
  3359. D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\}
  3360. \f}
  3361. The AMS method minimizes the cost function
  3362. \f{equation*}{
  3363. \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T }
  3364. \f}
  3365. The minimum cost is found by solving the generalized eigenvalue problem.
  3366. \f{equation*}{
  3367. D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A
  3368. \f}
  3369. @param points Input 2D point set, stored in std::vector\<\> or Mat
  3370. */
  3371. CV_EXPORTS_W RotatedRect fitEllipseAMS( InputArray points );
  3372. /** @brief Fits an ellipse around a set of 2D points.
  3373. The function calculates the ellipse that fits a set of 2D points.
  3374. It returns the rotated rectangle in which the ellipse is inscribed.
  3375. The Direct least square (Direct) method by @cite Fitzgibbon1999 is used.
  3376. For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$,
  3377. which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$.
  3378. However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$,
  3379. the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines,
  3380. quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits.
  3381. The Direct method confines the fit to ellipses by ensuring that \f$ 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \f$.
  3382. The condition imposed is that \f$ 4 A_{xx} A_{yy}- A_{xy}^2=1 \f$ which satisfies the inequality
  3383. and as the coefficients can be arbitrarily scaled is not overly restrictive.
  3384. \f{equation*}{
  3385. \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix}
  3386. 0 & 0 & 2 & 0 & 0 & 0 \\
  3387. 0 & -1 & 0 & 0 & 0 & 0 \\
  3388. 2 & 0 & 0 & 0 & 0 & 0 \\
  3389. 0 & 0 & 0 & 0 & 0 & 0 \\
  3390. 0 & 0 & 0 & 0 & 0 & 0 \\
  3391. 0 & 0 & 0 & 0 & 0 & 0
  3392. \end{matrix} \right)
  3393. \f}
  3394. The minimum cost is found by solving the generalized eigenvalue problem.
  3395. \f{equation*}{
  3396. D^T D A = \lambda \left( C\right) A
  3397. \f}
  3398. The system produces only one positive eigenvalue \f$ \lambda\f$ which is chosen as the solution
  3399. with its eigenvector \f$\mathbf{u}\f$. These are used to find the coefficients
  3400. \f{equation*}{
  3401. A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u}
  3402. \f}
  3403. The scaling factor guarantees that \f$A^T C A =1\f$.
  3404. @param points Input 2D point set, stored in std::vector\<\> or Mat
  3405. */
  3406. CV_EXPORTS_W RotatedRect fitEllipseDirect( InputArray points );
  3407. /** @brief Fits a line to a 2D or 3D point set.
  3408. The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where
  3409. \f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one
  3410. of the following:
  3411. - DIST_L2
  3412. \f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f]
  3413. - DIST_L1
  3414. \f[\rho (r) = r\f]
  3415. - DIST_L12
  3416. \f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f]
  3417. - DIST_FAIR
  3418. \f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f]
  3419. - DIST_WELSCH
  3420. \f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f]
  3421. - DIST_HUBER
  3422. \f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f]
  3423. The algorithm is based on the M-estimator ( <http://en.wikipedia.org/wiki/M-estimator> ) technique
  3424. that iteratively fits the line using the weighted least-squares algorithm. After each iteration the
  3425. weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ .
  3426. @param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat.
  3427. @param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements
  3428. (like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and
  3429. (x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like
  3430. Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line
  3431. and (x0, y0, z0) is a point on the line.
  3432. @param distType Distance used by the M-estimator, see #DistanceTypes
  3433. @param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value
  3434. is chosen.
  3435. @param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line).
  3436. @param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps.
  3437. */
  3438. CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType,
  3439. double param, double reps, double aeps );
  3440. /** @brief Performs a point-in-contour test.
  3441. The function determines whether the point is inside a contour, outside, or lies on an edge (or
  3442. coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge)
  3443. value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively.
  3444. Otherwise, the return value is a signed distance between the point and the nearest contour edge.
  3445. See below a sample output of the function where each image pixel is tested against the contour:
  3446. ![sample output](pics/pointpolygon.png)
  3447. @param contour Input contour.
  3448. @param pt Point tested against the contour.
  3449. @param measureDist If true, the function estimates the signed distance from the point to the
  3450. nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not.
  3451. */
  3452. CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist );
  3453. /** @brief Finds out if there is any intersection between two rotated rectangles.
  3454. If there is then the vertices of the intersecting region are returned as well.
  3455. Below are some examples of intersection configurations. The hatched pattern indicates the
  3456. intersecting region and the red vertices are returned by the function.
  3457. ![intersection examples](pics/intersection.png)
  3458. @param rect1 First rectangle
  3459. @param rect2 Second rectangle
  3460. @param intersectingRegion The output array of the vertices of the intersecting region. It returns
  3461. at most 8 vertices. Stored as std::vector\<cv::Point2f\> or cv::Mat as Mx1 of type CV_32FC2.
  3462. @returns One of #RectanglesIntersectTypes
  3463. */
  3464. CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion );
  3465. /** @brief Creates a smart pointer to a cv::GeneralizedHoughBallard class and initializes it.
  3466. */
  3467. CV_EXPORTS_W Ptr<GeneralizedHoughBallard> createGeneralizedHoughBallard();
  3468. /** @brief Creates a smart pointer to a cv::GeneralizedHoughGuil class and initializes it.
  3469. */
  3470. CV_EXPORTS_W Ptr<GeneralizedHoughGuil> createGeneralizedHoughGuil();
  3471. //! @} imgproc_shape
  3472. //! @addtogroup imgproc_colormap
  3473. //! @{
  3474. //! GNU Octave/MATLAB equivalent colormaps
  3475. enum ColormapTypes
  3476. {
  3477. COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg)
  3478. COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg)
  3479. COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg)
  3480. COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg)
  3481. COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg)
  3482. COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg)
  3483. COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg)
  3484. COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg)
  3485. COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg)
  3486. COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg)
  3487. COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg)
  3488. COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg)
  3489. COLORMAP_PARULA = 12, //!< ![parula](pics/colormaps/colorscale_parula.jpg)
  3490. COLORMAP_MAGMA = 13, //!< ![magma](pics/colormaps/colorscale_magma.jpg)
  3491. COLORMAP_INFERNO = 14, //!< ![inferno](pics/colormaps/colorscale_inferno.jpg)
  3492. COLORMAP_PLASMA = 15, //!< ![plasma](pics/colormaps/colorscale_plasma.jpg)
  3493. COLORMAP_VIRIDIS = 16, //!< ![viridis](pics/colormaps/colorscale_viridis.jpg)
  3494. COLORMAP_CIVIDIS = 17, //!< ![cividis](pics/colormaps/colorscale_cividis.jpg)
  3495. COLORMAP_TWILIGHT = 18, //!< ![twilight](pics/colormaps/colorscale_twilight.jpg)
  3496. COLORMAP_TWILIGHT_SHIFTED = 19, //!< ![twilight shifted](pics/colormaps/colorscale_twilight_shifted.jpg)
  3497. COLORMAP_TURBO = 20, //!< ![turbo](pics/colormaps/colorscale_turbo.jpg)
  3498. COLORMAP_DEEPGREEN = 21 //!< ![deepgreen](pics/colormaps/colorscale_deepgreen.jpg)
  3499. };
  3500. /** @example samples/cpp/falsecolor.cpp
  3501. An example using applyColorMap function
  3502. */
  3503. /** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image.
  3504. @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3.
  3505. @param dst The result is the colormapped source image. Note: Mat::create is called on dst.
  3506. @param colormap The colormap to apply, see #ColormapTypes
  3507. */
  3508. CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap);
  3509. /** @brief Applies a user colormap on a given image.
  3510. @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3.
  3511. @param dst The result is the colormapped source image. Note: Mat::create is called on dst.
  3512. @param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256
  3513. */
  3514. CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, InputArray userColor);
  3515. //! @} imgproc_colormap
  3516. //! @addtogroup imgproc_draw
  3517. //! @{
  3518. /** OpenCV color channel order is BGR[A] */
  3519. #define CV_RGB(r, g, b) cv::Scalar((b), (g), (r), 0)
  3520. /** @brief Draws a line segment connecting two points.
  3521. The function line draws the line segment between pt1 and pt2 points in the image. The line is
  3522. clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected
  3523. or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased
  3524. lines are drawn using Gaussian filtering.
  3525. @param img Image.
  3526. @param pt1 First point of the line segment.
  3527. @param pt2 Second point of the line segment.
  3528. @param color Line color.
  3529. @param thickness Line thickness.
  3530. @param lineType Type of the line. See #LineTypes.
  3531. @param shift Number of fractional bits in the point coordinates.
  3532. */
  3533. CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color,
  3534. int thickness = 1, int lineType = LINE_8, int shift = 0);
  3535. /** @brief Draws a arrow segment pointing from the first point to the second one.
  3536. The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line.
  3537. @param img Image.
  3538. @param pt1 The point the arrow starts from.
  3539. @param pt2 The point the arrow points to.
  3540. @param color Line color.
  3541. @param thickness Line thickness.
  3542. @param line_type Type of the line. See #LineTypes
  3543. @param shift Number of fractional bits in the point coordinates.
  3544. @param tipLength The length of the arrow tip in relation to the arrow length
  3545. */
  3546. CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color,
  3547. int thickness=1, int line_type=8, int shift=0, double tipLength=0.1);
  3548. /** @brief Draws a simple, thick, or filled up-right rectangle.
  3549. The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners
  3550. are pt1 and pt2.
  3551. @param img Image.
  3552. @param pt1 Vertex of the rectangle.
  3553. @param pt2 Vertex of the rectangle opposite to pt1 .
  3554. @param color Rectangle color or brightness (grayscale image).
  3555. @param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED,
  3556. mean that the function has to draw a filled rectangle.
  3557. @param lineType Type of the line. See #LineTypes
  3558. @param shift Number of fractional bits in the point coordinates.
  3559. */
  3560. CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2,
  3561. const Scalar& color, int thickness = 1,
  3562. int lineType = LINE_8, int shift = 0);
  3563. /** @overload
  3564. use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and
  3565. r.br()-Point(1,1)` are opposite corners
  3566. */
  3567. CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec,
  3568. const Scalar& color, int thickness = 1,
  3569. int lineType = LINE_8, int shift = 0);
  3570. /** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp
  3571. An example using drawing functions
  3572. */
  3573. /** @brief Draws a circle.
  3574. The function cv::circle draws a simple or filled circle with a given center and radius.
  3575. @param img Image where the circle is drawn.
  3576. @param center Center of the circle.
  3577. @param radius Radius of the circle.
  3578. @param color Circle color.
  3579. @param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED,
  3580. mean that a filled circle is to be drawn.
  3581. @param lineType Type of the circle boundary. See #LineTypes
  3582. @param shift Number of fractional bits in the coordinates of the center and in the radius value.
  3583. */
  3584. CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius,
  3585. const Scalar& color, int thickness = 1,
  3586. int lineType = LINE_8, int shift = 0);
  3587. /** @brief Draws a simple or thick elliptic arc or fills an ellipse sector.
  3588. The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic
  3589. arc, or a filled ellipse sector. The drawing code uses general parametric form.
  3590. A piecewise-linear curve is used to approximate the elliptic arc
  3591. boundary. If you need more control of the ellipse rendering, you can retrieve the curve using
  3592. #ellipse2Poly and then render it with #polylines or fill it with #fillPoly. If you use the first
  3593. variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and
  3594. `endAngle=360`. If `startAngle` is greater than `endAngle`, they are swapped. The figure below explains
  3595. the meaning of the parameters to draw the blue arc.
  3596. ![Parameters of Elliptic Arc](pics/ellipse.svg)
  3597. @param img Image.
  3598. @param center Center of the ellipse.
  3599. @param axes Half of the size of the ellipse main axes.
  3600. @param angle Ellipse rotation angle in degrees.
  3601. @param startAngle Starting angle of the elliptic arc in degrees.
  3602. @param endAngle Ending angle of the elliptic arc in degrees.
  3603. @param color Ellipse color.
  3604. @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that
  3605. a filled ellipse sector is to be drawn.
  3606. @param lineType Type of the ellipse boundary. See #LineTypes
  3607. @param shift Number of fractional bits in the coordinates of the center and values of axes.
  3608. */
  3609. CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes,
  3610. double angle, double startAngle, double endAngle,
  3611. const Scalar& color, int thickness = 1,
  3612. int lineType = LINE_8, int shift = 0);
  3613. /** @overload
  3614. @param img Image.
  3615. @param box Alternative ellipse representation via RotatedRect. This means that the function draws
  3616. an ellipse inscribed in the rotated rectangle.
  3617. @param color Ellipse color.
  3618. @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that
  3619. a filled ellipse sector is to be drawn.
  3620. @param lineType Type of the ellipse boundary. See #LineTypes
  3621. */
  3622. CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color,
  3623. int thickness = 1, int lineType = LINE_8);
  3624. /* ----------------------------------------------------------------------------------------- */
  3625. /* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */
  3626. /* ----------------------------------------------------------------------------------------- */
  3627. //! Possible set of marker types used for the cv::drawMarker function
  3628. enum MarkerTypes
  3629. {
  3630. MARKER_CROSS = 0, //!< A crosshair marker shape
  3631. MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape
  3632. MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross
  3633. MARKER_DIAMOND = 3, //!< A diamond marker shape
  3634. MARKER_SQUARE = 4, //!< A square marker shape
  3635. MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape
  3636. MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape
  3637. };
  3638. /** @brief Draws a marker on a predefined position in an image.
  3639. The function cv::drawMarker draws a marker on a given position in the image. For the moment several
  3640. marker types are supported, see #MarkerTypes for more information.
  3641. @param img Image.
  3642. @param position The point where the crosshair is positioned.
  3643. @param color Line color.
  3644. @param markerType The specific type of marker you want to use, see #MarkerTypes
  3645. @param thickness Line thickness.
  3646. @param line_type Type of the line, See #LineTypes
  3647. @param markerSize The length of the marker axis [default = 20 pixels]
  3648. */
  3649. CV_EXPORTS_W void drawMarker(CV_IN_OUT Mat& img, Point position, const Scalar& color,
  3650. int markerType = MARKER_CROSS, int markerSize=20, int thickness=1,
  3651. int line_type=8);
  3652. /* ----------------------------------------------------------------------------------------- */
  3653. /* END OF MARKER SECTION */
  3654. /* ----------------------------------------------------------------------------------------- */
  3655. /** @overload */
  3656. CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts,
  3657. const Scalar& color, int lineType = LINE_8,
  3658. int shift = 0);
  3659. /** @brief Fills a convex polygon.
  3660. The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the
  3661. function #fillPoly . It can fill not only convex polygons but any monotonic polygon without
  3662. self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line)
  3663. twice at the most (though, its top-most and/or the bottom edge could be horizontal).
  3664. @param img Image.
  3665. @param points Polygon vertices.
  3666. @param color Polygon color.
  3667. @param lineType Type of the polygon boundaries. See #LineTypes
  3668. @param shift Number of fractional bits in the vertex coordinates.
  3669. */
  3670. CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points,
  3671. const Scalar& color, int lineType = LINE_8,
  3672. int shift = 0);
  3673. /** @overload */
  3674. CV_EXPORTS void fillPoly(Mat& img, const Point** pts,
  3675. const int* npts, int ncontours,
  3676. const Scalar& color, int lineType = LINE_8, int shift = 0,
  3677. Point offset = Point() );
  3678. /** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_1.cpp
  3679. An example using drawing functions
  3680. Check @ref tutorial_random_generator_and_text "the corresponding tutorial" for more details
  3681. */
  3682. /** @brief Fills the area bounded by one or more polygons.
  3683. The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill
  3684. complex areas, for example, areas with holes, contours with self-intersections (some of their
  3685. parts), and so forth.
  3686. @param img Image.
  3687. @param pts Array of polygons where each polygon is represented as an array of points.
  3688. @param color Polygon color.
  3689. @param lineType Type of the polygon boundaries. See #LineTypes
  3690. @param shift Number of fractional bits in the vertex coordinates.
  3691. @param offset Optional offset of all points of the contours.
  3692. */
  3693. CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts,
  3694. const Scalar& color, int lineType = LINE_8, int shift = 0,
  3695. Point offset = Point() );
  3696. /** @overload */
  3697. CV_EXPORTS void polylines(Mat& img, const Point* const* pts, const int* npts,
  3698. int ncontours, bool isClosed, const Scalar& color,
  3699. int thickness = 1, int lineType = LINE_8, int shift = 0 );
  3700. /** @brief Draws several polygonal curves.
  3701. @param img Image.
  3702. @param pts Array of polygonal curves.
  3703. @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed,
  3704. the function draws a line from the last vertex of each curve to its first vertex.
  3705. @param color Polyline color.
  3706. @param thickness Thickness of the polyline edges.
  3707. @param lineType Type of the line segments. See #LineTypes
  3708. @param shift Number of fractional bits in the vertex coordinates.
  3709. The function cv::polylines draws one or more polygonal curves.
  3710. */
  3711. CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts,
  3712. bool isClosed, const Scalar& color,
  3713. int thickness = 1, int lineType = LINE_8, int shift = 0 );
  3714. /** @example samples/cpp/contours2.cpp
  3715. An example program illustrates the use of cv::findContours and cv::drawContours
  3716. \image html WindowsQtContoursOutput.png "Screenshot of the program"
  3717. */
  3718. /** @example samples/cpp/segment_objects.cpp
  3719. An example using drawContours to clean up a background segmentation result
  3720. */
  3721. /** @brief Draws contours outlines or filled contours.
  3722. The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area
  3723. bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve
  3724. connected components from the binary image and label them: :
  3725. @include snippets/imgproc_drawContours.cpp
  3726. @param image Destination image.
  3727. @param contours All the input contours. Each contour is stored as a point vector.
  3728. @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn.
  3729. @param color Color of the contours.
  3730. @param thickness Thickness of lines the contours are drawn with. If it is negative (for example,
  3731. thickness=#FILLED ), the contour interiors are drawn.
  3732. @param lineType Line connectivity. See #LineTypes
  3733. @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only
  3734. some of the contours (see maxLevel ).
  3735. @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn.
  3736. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function
  3737. draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This
  3738. parameter is only taken into account when there is hierarchy available.
  3739. @param offset Optional contour shift parameter. Shift all the drawn contours by the specified
  3740. \f$\texttt{offset}=(dx,dy)\f$ .
  3741. @note When thickness=#FILLED, the function is designed to handle connected components with holes correctly
  3742. even when no hierarchy date is provided. This is done by analyzing all the outlines together
  3743. using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved
  3744. contours. In order to solve this problem, you need to call #drawContours separately for each sub-group
  3745. of contours, or iterate over the collection using contourIdx parameter.
  3746. */
  3747. CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours,
  3748. int contourIdx, const Scalar& color,
  3749. int thickness = 1, int lineType = LINE_8,
  3750. InputArray hierarchy = noArray(),
  3751. int maxLevel = INT_MAX, Point offset = Point() );
  3752. /** @brief Clips the line against the image rectangle.
  3753. The function cv::clipLine calculates a part of the line segment that is entirely within the specified
  3754. rectangle. it returns false if the line segment is completely outside the rectangle. Otherwise,
  3755. it returns true .
  3756. @param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) .
  3757. @param pt1 First line point.
  3758. @param pt2 Second line point.
  3759. */
  3760. CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2);
  3761. /** @overload
  3762. @param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) .
  3763. @param pt1 First line point.
  3764. @param pt2 Second line point.
  3765. */
  3766. CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2);
  3767. /** @overload
  3768. @param imgRect Image rectangle.
  3769. @param pt1 First line point.
  3770. @param pt2 Second line point.
  3771. */
  3772. CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2);
  3773. /** @brief Approximates an elliptic arc with a polyline.
  3774. The function ellipse2Poly computes the vertices of a polyline that approximates the specified
  3775. elliptic arc. It is used by #ellipse. If `arcStart` is greater than `arcEnd`, they are swapped.
  3776. @param center Center of the arc.
  3777. @param axes Half of the size of the ellipse main axes. See #ellipse for details.
  3778. @param angle Rotation angle of the ellipse in degrees. See #ellipse for details.
  3779. @param arcStart Starting angle of the elliptic arc in degrees.
  3780. @param arcEnd Ending angle of the elliptic arc in degrees.
  3781. @param delta Angle between the subsequent polyline vertices. It defines the approximation
  3782. accuracy.
  3783. @param pts Output vector of polyline vertices.
  3784. */
  3785. CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle,
  3786. int arcStart, int arcEnd, int delta,
  3787. CV_OUT std::vector<Point>& pts );
  3788. /** @overload
  3789. @param center Center of the arc.
  3790. @param axes Half of the size of the ellipse main axes. See #ellipse for details.
  3791. @param angle Rotation angle of the ellipse in degrees. See #ellipse for details.
  3792. @param arcStart Starting angle of the elliptic arc in degrees.
  3793. @param arcEnd Ending angle of the elliptic arc in degrees.
  3794. @param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy.
  3795. @param pts Output vector of polyline vertices.
  3796. */
  3797. CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle,
  3798. int arcStart, int arcEnd, int delta,
  3799. CV_OUT std::vector<Point2d>& pts);
  3800. /** @brief Draws a text string.
  3801. The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered
  3802. using the specified font are replaced by question marks. See #getTextSize for a text rendering code
  3803. example.
  3804. @param img Image.
  3805. @param text Text string to be drawn.
  3806. @param org Bottom-left corner of the text string in the image.
  3807. @param fontFace Font type, see #HersheyFonts.
  3808. @param fontScale Font scale factor that is multiplied by the font-specific base size.
  3809. @param color Text color.
  3810. @param thickness Thickness of the lines used to draw a text.
  3811. @param lineType Line type. See #LineTypes
  3812. @param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise,
  3813. it is at the top-left corner.
  3814. */
  3815. CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org,
  3816. int fontFace, double fontScale, Scalar color,
  3817. int thickness = 1, int lineType = LINE_8,
  3818. bool bottomLeftOrigin = false );
  3819. /** @brief Calculates the width and height of a text string.
  3820. The function cv::getTextSize calculates and returns the size of a box that contains the specified text.
  3821. That is, the following code renders some text, the tight box surrounding it, and the baseline: :
  3822. @code
  3823. String text = "Funny text inside the box";
  3824. int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX;
  3825. double fontScale = 2;
  3826. int thickness = 3;
  3827. Mat img(600, 800, CV_8UC3, Scalar::all(0));
  3828. int baseline=0;
  3829. Size textSize = getTextSize(text, fontFace,
  3830. fontScale, thickness, &baseline);
  3831. baseline += thickness;
  3832. // center the text
  3833. Point textOrg((img.cols - textSize.width)/2,
  3834. (img.rows + textSize.height)/2);
  3835. // draw the box
  3836. rectangle(img, textOrg + Point(0, baseline),
  3837. textOrg + Point(textSize.width, -textSize.height),
  3838. Scalar(0,0,255));
  3839. // ... and the baseline first
  3840. line(img, textOrg + Point(0, thickness),
  3841. textOrg + Point(textSize.width, thickness),
  3842. Scalar(0, 0, 255));
  3843. // then put the text itself
  3844. putText(img, text, textOrg, fontFace, fontScale,
  3845. Scalar::all(255), thickness, 8);
  3846. @endcode
  3847. @param text Input text string.
  3848. @param fontFace Font to use, see #HersheyFonts.
  3849. @param fontScale Font scale factor that is multiplied by the font-specific base size.
  3850. @param thickness Thickness of lines used to render the text. See #putText for details.
  3851. @param[out] baseLine y-coordinate of the baseline relative to the bottom-most text
  3852. point.
  3853. @return The size of a box that contains the specified text.
  3854. @see putText
  3855. */
  3856. CV_EXPORTS_W Size getTextSize(const String& text, int fontFace,
  3857. double fontScale, int thickness,
  3858. CV_OUT int* baseLine);
  3859. /** @brief Calculates the font-specific size to use to achieve a given height in pixels.
  3860. @param fontFace Font to use, see cv::HersheyFonts.
  3861. @param pixelHeight Pixel height to compute the fontScale for
  3862. @param thickness Thickness of lines used to render the text.See putText for details.
  3863. @return The fontSize to use for cv::putText
  3864. @see cv::putText
  3865. */
  3866. CV_EXPORTS_W double getFontScaleFromHeight(const int fontFace,
  3867. const int pixelHeight,
  3868. const int thickness = 1);
  3869. /** @brief Line iterator
  3870. The class is used to iterate over all the pixels on the raster line
  3871. segment connecting two specified points.
  3872. The class LineIterator is used to get each pixel of a raster line. It
  3873. can be treated as versatile implementation of the Bresenham algorithm
  3874. where you can stop at each pixel and do some extra processing, for
  3875. example, grab pixel values along the line or draw a line with an effect
  3876. (for example, with XOR operation).
  3877. The number of pixels along the line is stored in LineIterator::count.
  3878. The method LineIterator::pos returns the current position in the image:
  3879. @code{.cpp}
  3880. // grabs pixels along the line (pt1, pt2)
  3881. // from 8-bit 3-channel image to the buffer
  3882. LineIterator it(img, pt1, pt2, 8);
  3883. LineIterator it2 = it;
  3884. vector<Vec3b> buf(it.count);
  3885. for(int i = 0; i < it.count; i++, ++it)
  3886. buf[i] = *(const Vec3b*)*it;
  3887. // alternative way of iterating through the line
  3888. for(int i = 0; i < it2.count; i++, ++it2)
  3889. {
  3890. Vec3b val = img.at<Vec3b>(it2.pos());
  3891. CV_Assert(buf[i] == val);
  3892. }
  3893. @endcode
  3894. */
  3895. class CV_EXPORTS LineIterator
  3896. {
  3897. public:
  3898. /** @brief initializes the iterator
  3899. creates iterators for the line connecting pt1 and pt2
  3900. the line will be clipped on the image boundaries
  3901. the line is 8-connected or 4-connected
  3902. If leftToRight=true, then the iteration is always done
  3903. from the left-most point to the right most,
  3904. not to depend on the ordering of pt1 and pt2 parameters
  3905. */
  3906. LineIterator( const Mat& img, Point pt1, Point pt2,
  3907. int connectivity = 8, bool leftToRight = false );
  3908. /** @brief returns pointer to the current pixel
  3909. */
  3910. uchar* operator *();
  3911. /** @brief prefix increment operator (++it). shifts iterator to the next pixel
  3912. */
  3913. LineIterator& operator ++();
  3914. /** @brief postfix increment operator (it++). shifts iterator to the next pixel
  3915. */
  3916. LineIterator operator ++(int);
  3917. /** @brief returns coordinates of the current pixel
  3918. */
  3919. Point pos() const;
  3920. uchar* ptr;
  3921. const uchar* ptr0;
  3922. int step, elemSize;
  3923. int err, count;
  3924. int minusDelta, plusDelta;
  3925. int minusStep, plusStep;
  3926. };
  3927. //! @cond IGNORED
  3928. // === LineIterator implementation ===
  3929. inline
  3930. uchar* LineIterator::operator *()
  3931. {
  3932. return ptr;
  3933. }
  3934. inline
  3935. LineIterator& LineIterator::operator ++()
  3936. {
  3937. int mask = err < 0 ? -1 : 0;
  3938. err += minusDelta + (plusDelta & mask);
  3939. ptr += minusStep + (plusStep & mask);
  3940. return *this;
  3941. }
  3942. inline
  3943. LineIterator LineIterator::operator ++(int)
  3944. {
  3945. LineIterator it = *this;
  3946. ++(*this);
  3947. return it;
  3948. }
  3949. inline
  3950. Point LineIterator::pos() const
  3951. {
  3952. Point p;
  3953. p.y = (int)((ptr - ptr0)/step);
  3954. p.x = (int)(((ptr - ptr0) - p.y*step)/elemSize);
  3955. return p;
  3956. }
  3957. //! @endcond
  3958. //! @} imgproc_draw
  3959. //! @} imgproc
  3960. } // cv
  3961. #ifndef DISABLE_OPENCV_24_COMPATIBILITY
  3962. #include "opencv2/imgproc/imgproc_c.h"
  3963. #endif
  3964. #endif