blend.py 159 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854
  1. """
  2. Augmenters that blend two images with each other.
  3. List of augmenters:
  4. * :class:`BlendAlpha`
  5. * :class:`BlendAlphaMask`
  6. * :class:`BlendAlphaElementwise`
  7. * :class:`BlendAlphaSimplexNoise`
  8. * :class:`BlendAlphaFrequencyNoise`
  9. * :class:`BlendAlphaSomeColors`
  10. * :class:`BlendAlphaHorizontalLinearGradient`
  11. * :class:`BlendAlphaVerticalLinearGradient`
  12. * :class:`BlendAlphaSegMapClassIds`
  13. * :class:`BlendAlphaBoundingBoxes`
  14. * :class:`BlendAlphaRegularGrid`
  15. * :class:`BlendAlphaCheckerboard`
  16. """
  17. from __future__ import print_function, division, absolute_import
  18. from abc import ABCMeta, abstractmethod
  19. import numpy as np
  20. import six
  21. import cv2
  22. import imgaug as ia
  23. from imgaug.imgaug import _normalize_cv2_input_arr_
  24. from . import meta
  25. from .. import parameters as iap
  26. from .. import dtypes as iadt
  27. from .. import random as iarandom
  28. from ..augmentables import utils as augm_utils
  29. def _split_1d_array_to_list(arr, sizes):
  30. result = []
  31. i = 0
  32. for size in sizes:
  33. result.append(arr[i:i+size])
  34. i += size
  35. return result
  36. def blend_alpha(image_fg, image_bg, alpha, eps=1e-2):
  37. """
  38. Blend two images using an alpha blending.
  39. In alpha blending, the two images are naively mixed using a multiplier.
  40. Let ``A`` be the foreground image and ``B`` the background image and
  41. ``a`` is the alpha value. Each pixel intensity is then computed as
  42. ``a * A_ij + (1-a) * B_ij``.
  43. **Supported dtypes**:
  44. * ``uint8``: yes; fully tested
  45. * ``uint16``: yes; fully tested
  46. * ``uint32``: yes; fully tested
  47. * ``uint64``: yes; fully tested (1)
  48. * ``int8``: yes; fully tested
  49. * ``int16``: yes; fully tested
  50. * ``int32``: yes; fully tested
  51. * ``int64``: yes; fully tested (1)
  52. * ``float16``: yes; fully tested
  53. * ``float32``: yes; fully tested
  54. * ``float64``: yes; fully tested (1)
  55. * ``float128``: no (2)
  56. * ``bool``: yes; fully tested (2)
  57. - (1) Tests show that these dtypes work, but a conversion to
  58. ``float128`` happens, which only has 96 bits of size instead of
  59. true 128 bits and hence not twice as much resolution. It is
  60. possible that these dtypes result in inaccuracies, though the
  61. tests did not indicate that.
  62. - (2) Not available due to the input dtype having to be increased to
  63. an equivalent float dtype with two times the input resolution.
  64. - (3) Mapped internally to ``float16``.
  65. Parameters
  66. ----------
  67. image_fg : (H,W,[C]) ndarray
  68. Foreground image. Shape and dtype kind must match the one of the
  69. background image.
  70. image_bg : (H,W,[C]) ndarray
  71. Background image. Shape and dtype kind must match the one of the
  72. foreground image.
  73. alpha : number or iterable of number or ndarray
  74. The blending factor, between ``0.0`` and ``1.0``. Can be interpreted
  75. as the opacity of the foreground image. Values around ``1.0`` result
  76. in only the foreground image being visible. Values around ``0.0``
  77. result in only the background image being visible. Multiple alphas
  78. may be provided. In these cases, there must be exactly one alpha per
  79. channel in the foreground/background image. Alternatively, for
  80. ``(H,W,C)`` images, either one ``(H,W)`` array or an ``(H,W,C)``
  81. array of alphas may be provided, denoting the elementwise alpha value.
  82. eps : number, optional
  83. Controls when an alpha is to be interpreted as exactly ``1.0`` or
  84. exactly ``0.0``, resulting in only the foreground/background being
  85. visible and skipping the actual computation.
  86. Returns
  87. -------
  88. image_blend : (H,W,C) ndarray
  89. Blend of foreground and background image.
  90. """
  91. assert image_fg.shape == image_bg.shape, (
  92. "Expected foreground and background images to have the same shape. "
  93. "Got %s and %s." % (image_fg.shape, image_bg.shape))
  94. assert image_fg.dtype.kind == image_bg.dtype.kind, (
  95. "Expected foreground and background images to have the same dtype "
  96. "kind. Got %s and %s." % (image_fg.dtype.kind, image_bg.dtype.kind))
  97. # TODO switch to gate_dtypes()
  98. assert image_fg.dtype.name not in ["float128"], (
  99. "Foreground image was float128, but blend_alpha() cannot handle that "
  100. "dtype.")
  101. assert image_bg.dtype.name not in ["float128"], (
  102. "Background image was float128, but blend_alpha() cannot handle that "
  103. "dtype.")
  104. input_was_2d = (image_fg.ndim == 2)
  105. if input_was_2d:
  106. image_fg = image_fg[..., np.newaxis]
  107. image_bg = image_bg[..., np.newaxis]
  108. input_was_bool = False
  109. if image_fg.dtype.kind == "b":
  110. input_was_bool = True
  111. # use float32 instead of float16 here because it seems to be faster
  112. image_fg = image_fg.astype(np.float32)
  113. image_bg = image_bg.astype(np.float32)
  114. alpha = np.array(alpha, dtype=np.float64)
  115. if alpha.size == 1:
  116. pass
  117. else:
  118. if alpha.ndim == 2:
  119. assert alpha.shape == image_fg.shape[0:2], (
  120. "'alpha' given as an array must match the height and width "
  121. "of the foreground and background image. Got shape %s vs "
  122. "foreground/background shape %s." % (
  123. alpha.shape, image_fg.shape))
  124. alpha = alpha.reshape((alpha.shape[0], alpha.shape[1], 1))
  125. elif alpha.ndim == 3:
  126. assert (
  127. alpha.shape == image_fg.shape
  128. or alpha.shape == image_fg.shape[0:2] + (1,)), (
  129. "'alpha' given as an array must match the height and "
  130. "width of the foreground and background image. Got "
  131. "shape %s vs foreground/background shape %s." % (
  132. alpha.shape, image_fg.shape))
  133. else:
  134. alpha = alpha.reshape((1, 1, -1))
  135. if alpha.shape[2] != image_fg.shape[2]:
  136. alpha = np.tile(alpha, (1, 1, image_fg.shape[2]))
  137. if not input_was_bool:
  138. if np.all(alpha >= 1.0 - eps):
  139. if input_was_2d:
  140. image_fg = image_fg[..., 0]
  141. return np.copy(image_fg)
  142. if np.all(alpha <= eps):
  143. if input_was_2d:
  144. image_bg = image_bg[..., 0]
  145. return np.copy(image_bg)
  146. # for efficiency reaons, only test one value of alpha here, even if alpha
  147. # is much larger
  148. if alpha.size > 0:
  149. assert 0 <= alpha.item(0) <= 1.0, (
  150. "Expected 'alpha' value(s) to be in the interval [0.0, 1.0]. "
  151. "Got min %.4f and max %.4f." % (np.min(alpha), np.max(alpha)))
  152. dt_images = iadt.get_minimal_dtype([image_fg, image_bg])
  153. # doing the below itemsize increase only for non-float images led to
  154. # inaccuracies for large float values
  155. # we also use a minimum of 4 bytes (=float32), as float32 tends to be
  156. # faster than float16
  157. isize = dt_images.itemsize * 2
  158. isize = max(isize, 4)
  159. dt_blend = np.dtype("f%d" % (isize,))
  160. if alpha.dtype.name != dt_blend.name:
  161. alpha = alpha.astype(dt_blend)
  162. if image_fg.dtype.name != dt_blend.name:
  163. image_fg = image_fg.astype(dt_blend)
  164. if image_bg.dtype.name != dt_blend.name:
  165. image_bg = image_bg.astype(dt_blend)
  166. # the following is equivalent to
  167. # image_blend = alpha * image_fg + (1 - alpha) * image_bg
  168. # but supposedly faster
  169. image_blend = image_bg + alpha * (image_fg - image_bg)
  170. if input_was_bool:
  171. image_blend = image_blend > 0.5
  172. else:
  173. # skip clip, because alpha is expected to be in range [0.0, 1.0] and
  174. # both images must have same dtype dont skip round, because otherwise
  175. # it is very unlikely to hit the image's max possible value
  176. image_blend = iadt.restore_dtypes_(
  177. image_blend, dt_images, clip=False, round=True)
  178. if input_was_2d:
  179. return image_blend[:, :, 0]
  180. return image_blend
  181. # Added in 0.4.0.
  182. def _generate_branch_outputs(augmenter, batch, hooks, parents):
  183. parents_extended = parents + [augmenter]
  184. # Note here that the propagation hook removes columns in the batch
  185. # and re-adds them afterwards. So the batch should not be copied
  186. # after the `with` statement.
  187. outputs_fg = batch
  188. if augmenter.foreground is not None:
  189. outputs_fg = outputs_fg.deepcopy()
  190. with outputs_fg.propagation_hooks_ctx(augmenter, hooks, parents):
  191. if augmenter.foreground is not None:
  192. outputs_fg = augmenter.foreground.augment_batch_(
  193. outputs_fg,
  194. parents=parents_extended,
  195. hooks=hooks
  196. )
  197. outputs_bg = batch
  198. if augmenter.background is not None:
  199. outputs_bg = outputs_bg.deepcopy()
  200. with outputs_bg.propagation_hooks_ctx(augmenter, hooks, parents):
  201. outputs_bg = augmenter.background.augment_batch_(
  202. outputs_bg,
  203. parents=parents_extended,
  204. hooks=hooks
  205. )
  206. return outputs_fg, outputs_bg
  207. # Added in 0.4.0.
  208. def _to_deterministic(augmenter):
  209. aug = augmenter.copy()
  210. aug.foreground = (
  211. aug.foreground.to_deterministic()
  212. if aug.foreground is not None
  213. else None)
  214. aug.background = (
  215. aug.background.to_deterministic()
  216. if aug.background is not None
  217. else None)
  218. aug.deterministic = True
  219. aug.random_state = augmenter.random_state.derive_rng_()
  220. return aug
  221. class BlendAlpha(meta.Augmenter):
  222. """
  223. Alpha-blend two image sources using an alpha/opacity value.
  224. The two image sources can be imagined as branches.
  225. If a source is not given, it is automatically the same as the input.
  226. Let ``FG`` be the foreground branch and ``BG`` be the background branch.
  227. Then the result images are defined as ``factor * FG + (1-factor) * BG``,
  228. where ``factor`` is an overlay factor.
  229. .. note::
  230. It is not recommended to use ``BlendAlpha`` with augmenters
  231. that change the geometry of images (e.g. horizontal flips, affine
  232. transformations) if you *also* want to augment coordinates (e.g.
  233. keypoints, polygons, ...), as it is unclear which of the two
  234. coordinate results (foreground or background branch) should be used
  235. as the coordinates after augmentation.
  236. Currently, if ``factor >= 0.5`` (per image), the results of the
  237. foreground branch are used as the new coordinates, otherwise the
  238. results of the background branch.
  239. Added in 0.4.0. (Before that named `Alpha`.)
  240. **Supported dtypes**:
  241. See :func:`~imgaug.augmenters.blend.blend_alpha`.
  242. Parameters
  243. ----------
  244. factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  245. Opacity of the results of the foreground branch. Values close to
  246. ``0.0`` mean that the results from the background branch (see
  247. parameter `background`) make up most of the final image.
  248. * If float, then that value will be used for all images.
  249. * If tuple ``(a, b)``, then a random value from the interval
  250. ``[a, b]`` will be sampled per image.
  251. * If a list, then a random value will be picked from that list per
  252. image.
  253. * If ``StochasticParameter``, then that parameter will be used to
  254. sample a value per image.
  255. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  256. Augmenter(s) that make up the foreground branch.
  257. High alpha values will show this branch's results.
  258. * If ``None``, then the input images will be reused as the output
  259. of the foreground branch.
  260. * If ``Augmenter``, then that augmenter will be used as the branch.
  261. * If iterable of ``Augmenter``, then that iterable will be
  262. converted into a ``Sequential`` and used as the augmenter.
  263. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  264. Augmenter(s) that make up the background branch.
  265. Low alpha values will show this branch's results.
  266. * If ``None``, then the input images will be reused as the output
  267. of the background branch.
  268. * If ``Augmenter``, then that augmenter will be used as the branch.
  269. * If iterable of ``Augmenter``, then that iterable will be
  270. converted into a ``Sequential`` and used as the augmenter.
  271. per_channel : bool or float or imgaug.parameters.StochasticParameter, optional
  272. Whether to use the same factor for all channels (``False``)
  273. or to sample a new value for each channel (``True``).
  274. If this value is a float ``p``, then for ``p`` percent of all images
  275. `per_channel` will be treated as True, otherwise as False.
  276. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  277. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  278. name : None or str, optional
  279. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  280. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  281. Old name for parameter `seed`.
  282. Its usage will not yet cause a deprecation warning,
  283. but it is still recommended to use `seed` now.
  284. Outdated since 0.4.0.
  285. deterministic : bool, optional
  286. Deprecated since 0.4.0.
  287. See method ``to_deterministic()`` for an alternative and for
  288. details about what the "deterministic mode" actually does.
  289. Examples
  290. --------
  291. >>> import imgaug.augmenters as iaa
  292. >>> aug = iaa.BlendAlpha(0.5, iaa.Grayscale(1.0))
  293. Convert each image to pure grayscale and alpha-blend the result with the
  294. original image using an alpha of ``50%``, thereby removing about ``50%`` of
  295. all color. This is equivalent to ``iaa.Grayscale(0.5)``.
  296. >>> aug = iaa.BlendAlpha((0.0, 1.0), iaa.Grayscale(1.0))
  297. Same as in the previous example, but the alpha factor is sampled uniformly
  298. from the interval ``[0.0, 1.0]`` once per image, thereby removing a random
  299. fraction of all colors. This is equivalent to
  300. ``iaa.Grayscale((0.0, 1.0))``.
  301. >>> aug = iaa.BlendAlpha(
  302. >>> (0.0, 1.0),
  303. >>> iaa.Affine(rotate=(-20, 20)),
  304. >>> per_channel=0.5)
  305. First, rotate each image by a random degree sampled uniformly from the
  306. interval ``[-20, 20]``. Then, alpha-blend that new image with the original
  307. one using a random factor sampled uniformly from the interval
  308. ``[0.0, 1.0]``. For ``50%`` of all images, the blending happens
  309. channel-wise and the factor is sampled independently per channel
  310. (``per_channel=0.5``). As a result, e.g. the red channel may look visibly
  311. rotated (factor near ``1.0``), while the green and blue channels may not
  312. look rotated (factors near ``0.0``).
  313. >>> aug = iaa.BlendAlpha(
  314. >>> (0.0, 1.0),
  315. >>> foreground=iaa.Add(100),
  316. >>> background=iaa.Multiply(0.2))
  317. Apply two branches of augmenters -- ``A`` and ``B`` -- *independently*
  318. to input images and alpha-blend the results of these branches using a
  319. factor ``f``. Branch ``A`` increases image pixel intensities by ``100``
  320. and ``B`` multiplies the pixel intensities by ``0.2``. ``f`` is sampled
  321. uniformly from the interval ``[0.0, 1.0]`` per image. The resulting images
  322. contain a bit of ``A`` and a bit of ``B``.
  323. >>> aug = iaa.BlendAlpha([0.25, 0.75], iaa.MedianBlur(13))
  324. Apply median blur to each image and alpha-blend the result with the
  325. original image using an alpha factor of either exactly ``0.25`` or
  326. exactly ``0.75`` (sampled once per image).
  327. """
  328. # Added in 0.4.0.
  329. def __init__(self, factor=(0.0, 1.0), foreground=None, background=None,
  330. per_channel=False,
  331. seed=None, name=None,
  332. random_state="deprecated", deterministic="deprecated"):
  333. super(BlendAlpha, self).__init__(
  334. seed=seed, name=name,
  335. random_state=random_state, deterministic=deterministic)
  336. self.factor = iap.handle_continuous_param(
  337. factor, "factor", value_range=(0, 1.0), tuple_to_uniform=True,
  338. list_to_choice=True)
  339. assert foreground is not None or background is not None, (
  340. "Expected 'foreground' and/or 'background' to not be None (i.e. "
  341. "at least one Augmenter), but got two None values.")
  342. self.foreground = meta.handle_children_list(
  343. foreground, self.name, "foreground", default=None)
  344. self.background = meta.handle_children_list(
  345. background, self.name, "background", default=None)
  346. self.per_channel = iap.handle_probability_param(per_channel,
  347. "per_channel")
  348. self.epsilon = 1e-2
  349. # Added in 0.4.0.
  350. def _augment_batch_(self, batch, random_state, parents, hooks):
  351. batch_fg, batch_bg = _generate_branch_outputs(
  352. self, batch, hooks, parents)
  353. columns = batch.columns
  354. shapes = batch.get_rowwise_shapes()
  355. nb_images = len(shapes)
  356. nb_channels_max = max([shape[2] if len(shape) > 2 else 1
  357. for shape in shapes])
  358. rngs = random_state.duplicate(2)
  359. per_channel = self.per_channel.draw_samples(nb_images,
  360. random_state=rngs[0])
  361. alphas = self.factor.draw_samples((nb_images, nb_channels_max),
  362. random_state=rngs[1])
  363. for i, shape in enumerate(shapes):
  364. if per_channel[i] > 0.5:
  365. nb_channels = shape[2] if len(shape) > 2 else 1
  366. alphas_i = alphas[i, 0:nb_channels]
  367. else:
  368. # We catch here the case of alphas[i] being empty, which can
  369. # happen if all images have 0 channels.
  370. # In that case the alpha value doesn't matter as the image
  371. # contains zero values anyways.
  372. alphas_i = alphas[i, 0] if alphas[i].size > 0 else 0
  373. # compute alpha for non-image data -- average() also works with
  374. # scalars
  375. alphas_i_avg = np.average(alphas_i)
  376. use_fg_branch = alphas_i_avg >= 0.5
  377. # blend images
  378. if batch.images is not None:
  379. batch.images[i] = blend_alpha(batch_fg.images[i],
  380. batch_bg.images[i],
  381. alphas_i, eps=self.epsilon)
  382. # blend non-images
  383. # TODO Use gradual blending for heatmaps here (as for images)?
  384. # Heatmaps are probably the only augmentable where this makes
  385. # sense.
  386. for column in columns:
  387. if column.name != "images":
  388. batch_use = (batch_fg if use_fg_branch
  389. else batch_bg)
  390. column.value[i] = getattr(batch_use, column.attr_name)[i]
  391. return batch
  392. # Added in 0.4.0.
  393. def _to_deterministic(self):
  394. return _to_deterministic(self)
  395. # Added in 0.4.0.
  396. def get_parameters(self):
  397. """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
  398. return [self.factor, self.per_channel]
  399. # Added in 0.4.0.
  400. def get_children_lists(self):
  401. """See :func:`~imgaug.augmenters.meta.Augmenter.get_children_lists`."""
  402. return [lst for lst in [self.foreground, self.background]
  403. if lst is not None]
  404. # Added in 0.4.0.
  405. def __str__(self):
  406. pattern = (
  407. "%s("
  408. "factor=%s, per_channel=%s, name=%s, "
  409. "foreground=%s, background=%s, "
  410. "deterministic=%s"
  411. ")"
  412. )
  413. return pattern % (
  414. self.__class__.__name__, self.factor, self.per_channel, self.name,
  415. self.foreground, self.background, self.deterministic)
  416. # tested indirectly via BlendAlphaElementwise for historic reasons
  417. class BlendAlphaMask(meta.Augmenter):
  418. """
  419. Alpha-blend two image sources using non-binary masks generated per image.
  420. This augmenter queries for each image a mask generator to generate
  421. a ``(H,W)`` or ``(H,W,C)`` channelwise mask ``[0.0, 1.0]``, where
  422. ``H`` is the image height and ``W`` the width.
  423. The mask will then be used to alpha-blend pixel- and possibly channel-wise
  424. between a foreground branch of augmenters and a background branch.
  425. (Both branches default to the identity operation if not provided.)
  426. See also :class:`~imgaug.augmenters.blend.BlendAlpha`.
  427. .. note::
  428. It is not recommended to use ``BlendAlphaMask`` with augmenters
  429. that change the geometry of images (e.g. horizontal flips, affine
  430. transformations) if you *also* want to augment coordinates (e.g.
  431. keypoints, polygons, ...), as it is unclear which of the two
  432. coordinate results (foreground or background branch) should be used
  433. as the final output coordinates after augmentation.
  434. Currently, for keypoints the results of the
  435. foreground and background branch will be mixed. That means that for
  436. each coordinate the augmented result will be picked from the
  437. foreground or background branch based on the average alpha mask value
  438. at the corresponding spatial location.
  439. For bounding boxes, line strings and polygons, either all objects
  440. (on an image) of the foreground or all of the background branch will
  441. be used, based on the average over the whole alpha mask.
  442. Added in 0.4.0.
  443. **Supported dtypes**:
  444. See :func:`~imgaug.augmenters.blend.blend_alpha`.
  445. Parameters
  446. ----------
  447. mask_generator : IBatchwiseMaskGenerator
  448. A generator that will be queried per image to generate a mask.
  449. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  450. Augmenter(s) that make up the foreground branch.
  451. High alpha values will show this branch's results.
  452. * If ``None``, then the input images will be reused as the output
  453. of the foreground branch (i.e. identity function).
  454. * If ``Augmenter``, then that augmenter will be used as the branch.
  455. * If iterable of ``Augmenter``, then that iterable will be
  456. converted into a ``Sequential`` and used as the augmenter.
  457. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  458. Augmenter(s) that make up the background branch.
  459. Low alpha values will show this branch's results.
  460. * If ``None``, then the input images will be reused as the output
  461. of the background branch (i.e. identity function).
  462. * If ``Augmenter``, then that augmenter will be used as the branch.
  463. * If iterable of ``Augmenter``, then that iterable will be
  464. converted into a ``Sequential`` and used as the augmenter.
  465. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  466. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  467. name : None or str, optional
  468. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  469. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  470. Old name for parameter `seed`.
  471. Its usage will not yet cause a deprecation warning,
  472. but it is still recommended to use `seed` now.
  473. Outdated since 0.4.0.
  474. deterministic : bool, optional
  475. Deprecated since 0.4.0.
  476. See method ``to_deterministic()`` for an alternative and for
  477. details about what the "deterministic mode" actually does.
  478. Examples
  479. --------
  480. >>> import imgaug.augmenters as iaa
  481. >>> aug = iaa.BlendAlphaMask(
  482. >>> iaa.InvertMaskGen(0.5, iaa.VerticalLinearGradientMaskGen()),
  483. >>> iaa.Sequential([
  484. >>> iaa.Clouds(),
  485. >>> iaa.WithChannels([1, 2], iaa.Multiply(0.5))
  486. >>> ])
  487. >>> )
  488. Create an augmenter that sometimes adds clouds at the bottom and sometimes
  489. at the top of the image.
  490. """
  491. # Currently the mode is only used for keypoint augmentation.
  492. # either or: use all keypoints from fg or all from bg branch (based
  493. # on average of the whole mask).
  494. # pointwise: decide for each point whether to use the fg or bg
  495. # branch's keypoint (based on the average mask value at the point's
  496. # xy-location).
  497. _MODE_EITHER_OR = "either-or"
  498. _MODE_POINTWISE = "pointwise"
  499. _MODES = [_MODE_POINTWISE, _MODE_EITHER_OR]
  500. # Added in 0.4.0.
  501. def __init__(self, mask_generator,
  502. foreground=None, background=None,
  503. seed=None, name=None,
  504. random_state="deprecated", deterministic="deprecated"):
  505. super(BlendAlphaMask, self).__init__(
  506. seed=seed, name=name,
  507. random_state=random_state, deterministic=deterministic)
  508. self.mask_generator = mask_generator
  509. assert foreground is not None or background is not None, (
  510. "Expected 'foreground' and/or 'background' to not be None (i.e. "
  511. "at least one Augmenter), but got two None values.")
  512. self.foreground = meta.handle_children_list(
  513. foreground, self.name, "foreground", default=None)
  514. self.background = meta.handle_children_list(
  515. background, self.name, "background", default=None)
  516. # this controls how keypoints and polygons are augmented
  517. # Non-keypoints currently uses an either-or approach.
  518. # Using pointwise augmentation is problematic for polygons and line
  519. # strings, because the order of the points may have changed (e.g.
  520. # from clockwise to counter-clockwise). For polygons, it is also
  521. # overall more likely that some child-augmenter added/deleted points
  522. # and we would need a polygon recoverer.
  523. # Overall it seems to be the better approach to use all polygons
  524. # from one branch or the other, which guarantuees their validity.
  525. # TODO decide the either-or not based on the whole average mask
  526. # value but on the average mask value within the polygon's area?
  527. self._coord_modes = {
  528. "keypoints": self._MODE_POINTWISE,
  529. "polygons": self._MODE_EITHER_OR,
  530. "line_strings": self._MODE_EITHER_OR,
  531. "bounding_boxes": self._MODE_EITHER_OR
  532. }
  533. self.epsilon = 1e-2
  534. # Added in 0.4.0.
  535. def _augment_batch_(self, batch, random_state, parents, hooks):
  536. batch_fg, batch_bg = _generate_branch_outputs(
  537. self, batch, hooks, parents)
  538. masks = self.mask_generator.draw_masks(batch, random_state)
  539. for i, mask in enumerate(masks):
  540. if batch.images is not None:
  541. batch.images[i] = blend_alpha(batch_fg.images[i],
  542. batch_bg.images[i],
  543. mask, eps=self.epsilon)
  544. if batch.heatmaps is not None:
  545. arr = batch.heatmaps[i].arr_0to1
  546. arr_height, arr_width = arr.shape[0:2]
  547. mask_binarized = self._binarize_mask(mask,
  548. arr_height, arr_width)
  549. batch.heatmaps[i].arr_0to1 = blend_alpha(
  550. batch_fg.heatmaps[i].arr_0to1,
  551. batch_bg.heatmaps[i].arr_0to1,
  552. mask_binarized, eps=self.epsilon)
  553. if batch.segmentation_maps is not None:
  554. arr = batch.segmentation_maps[i].arr
  555. arr_height, arr_width = arr.shape[0:2]
  556. mask_binarized = self._binarize_mask(mask,
  557. arr_height, arr_width)
  558. batch.segmentation_maps[i].arr = blend_alpha(
  559. batch_fg.segmentation_maps[i].arr,
  560. batch_bg.segmentation_maps[i].arr,
  561. mask_binarized, eps=self.epsilon)
  562. for augm_attr_name in ["keypoints", "bounding_boxes", "polygons",
  563. "line_strings"]:
  564. augm_value = getattr(batch, augm_attr_name)
  565. if augm_value is not None:
  566. augm_value[i] = self._blend_coordinates(
  567. augm_value[i],
  568. getattr(batch_fg, augm_attr_name)[i],
  569. getattr(batch_bg, augm_attr_name)[i],
  570. mask,
  571. self._coord_modes[augm_attr_name]
  572. )
  573. return batch
  574. # Added in 0.4.0.
  575. @classmethod
  576. def _binarize_mask(cls, mask, arr_height, arr_width):
  577. # Average over channels, resize to heatmap/segmap array size
  578. # (+clip for cubic interpolation). We can use none-NN interpolation
  579. # for segmaps here as this is just the mask and not the segmap
  580. # array.
  581. mask_3d = np.atleast_3d(mask)
  582. # masks with zero-sized axes crash in np.average() and cannot be
  583. # upscaled in imresize_single_image()
  584. if mask.size == 0:
  585. mask_rs = np.zeros((arr_height, arr_width),
  586. dtype=np.float32)
  587. else:
  588. mask_avg = (
  589. np.average(mask_3d, axis=2) if mask_3d.shape[2] > 0 else 1.0)
  590. mask_rs = ia.imresize_single_image(mask_avg,
  591. (arr_height, arr_width))
  592. mask_arr = iadt.clip_(mask_rs, 0, 1.0)
  593. mask_arr_binarized = (mask_arr >= 0.5)
  594. return mask_arr_binarized
  595. # Added in 0.4.0.
  596. @classmethod
  597. def _blend_coordinates(cls, cbaoi, cbaoi_fg, cbaoi_bg, mask_image,
  598. mode):
  599. coords = augm_utils.convert_cbaois_to_kpsois(cbaoi)
  600. coords_fg = augm_utils.convert_cbaois_to_kpsois(cbaoi_fg)
  601. coords_bg = augm_utils.convert_cbaois_to_kpsois(cbaoi_bg)
  602. coords = coords.to_xy_array()
  603. coords_fg = coords_fg.to_xy_array()
  604. coords_bg = coords_bg.to_xy_array()
  605. assert coords.shape == coords_fg.shape == coords_bg.shape, (
  606. "Expected number of coordinates to not be changed by foreground "
  607. "or background branch in BlendAlphaMask. But input coordinates "
  608. "of shape %s were changed to %s (foreground) and %s "
  609. "(background). Make sure to not use any augmenters that affect "
  610. "the existence of coordinates." % (
  611. coords.shape, coords_fg.shape, coords_bg.shape))
  612. h_img, w_img = mask_image.shape[0:2]
  613. if mode == cls._MODE_POINTWISE:
  614. # Augment pointwise, i.e. check for each point and its
  615. # xy-location the average mask value and pick based on that
  616. # either the point from the foreground or background branch.
  617. assert len(coords_fg) == len(coords_bg), (
  618. "Got different numbers of coordinates before/after "
  619. "augmentation in BlendAlphaMask. The number of "
  620. "coordinates is currently not allowed to change for this "
  621. "augmenter. Input contained %d coordinates, foreground "
  622. "branch %d, backround branch %d." % (
  623. len(coords), len(coords_fg), len(coords_bg)))
  624. coords_aug = []
  625. subgen = zip(coords, coords_fg, coords_bg)
  626. for coord, coord_fg, coord_bg in subgen:
  627. x_int = int(np.round(coord[0]))
  628. y_int = int(np.round(coord[1]))
  629. if 0 <= y_int < h_img and 0 <= x_int < w_img:
  630. alphas_i = mask_image[y_int, x_int, ...]
  631. alpha = (
  632. np.average(alphas_i) if alphas_i.size > 0 else 1.0)
  633. if alpha > 0.5:
  634. coords_aug.append(coord_fg)
  635. else:
  636. coords_aug.append(coord_bg)
  637. else:
  638. coords_aug.append((x_int, y_int))
  639. else:
  640. # Augment with an either-or approach over all points, i.e.
  641. # based on the average of the whole mask, either all points
  642. # from the foreground or all points from the background branch
  643. # are used.
  644. # Note that we ensured above that _keypoint_mode must be
  645. # _MODE_EITHER_OR if it wasn't _MODE_POINTWISE.
  646. mask_image_avg = (
  647. np.average(mask_image) if mask_image.size > 0 else 1.0)
  648. if mask_image_avg > 0.5:
  649. coords_aug = coords_fg
  650. else:
  651. coords_aug = coords_bg
  652. kpsoi_aug = ia.KeypointsOnImage.from_xy_array(
  653. coords_aug, shape=cbaoi.shape)
  654. return augm_utils.invert_convert_cbaois_to_kpsois_(cbaoi, kpsoi_aug)
  655. # Added in 0.4.0.
  656. def _to_deterministic(self):
  657. return _to_deterministic(self)
  658. # Added in 0.4.0.
  659. def get_parameters(self):
  660. """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
  661. return [self.mask_generator]
  662. # Added in 0.4.0.
  663. def get_children_lists(self):
  664. """See :func:`~imgaug.augmenters.meta.Augmenter.get_children_lists`."""
  665. return [lst for lst in [self.foreground, self.background]
  666. if lst is not None]
  667. # Added in 0.4.0.
  668. def __str__(self):
  669. pattern = (
  670. "%s("
  671. "mask_generator=%s, name=%s, foreground=%s, background=%s, "
  672. "deterministic=%s"
  673. ")"
  674. )
  675. return pattern % (
  676. self.__class__.__name__, self.mask_generator, self.name,
  677. self.foreground, self.background, self.deterministic)
  678. # FIXME the output of the third example makes it look like per_channel isn't
  679. # working
  680. class BlendAlphaElementwise(BlendAlphaMask):
  681. """
  682. Alpha-blend two image sources using alpha/opacity values sampled per pixel.
  683. This is the same as :class:`BlendAlpha`, except that the opacity factor is
  684. sampled once per *pixel* instead of once per *image* (or a few times per
  685. image, if ``BlendAlpha.per_channel`` is set to ``True``).
  686. See :class:`BlendAlpha` for more details.
  687. This class is a wrapper around
  688. :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  689. .. note::
  690. Avoid using augmenters as children that affect pixel locations (e.g.
  691. horizontal flips). See
  692. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  693. Added in 0.4.0. (Before that named `AlphaElementwise`.)
  694. **Supported dtypes**:
  695. See :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  696. Parameters
  697. ----------
  698. factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  699. Opacity of the results of the foreground branch. Values close to
  700. ``0.0`` mean that the results from the background branch (see
  701. parameter `background`) make up most of the final image.
  702. * If float, then that value will be used for all images.
  703. * If tuple ``(a, b)``, then a random value from the interval
  704. ``[a, b]`` will be sampled per image.
  705. * If a list, then a random value will be picked from that list per
  706. image.
  707. * If ``StochasticParameter``, then that parameter will be used to
  708. sample a value per image.
  709. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  710. Augmenter(s) that make up the foreground branch.
  711. High alpha values will show this branch's results.
  712. * If ``None``, then the input images will be reused as the output
  713. of the foreground branch.
  714. * If ``Augmenter``, then that augmenter will be used as the branch.
  715. * If iterable of ``Augmenter``, then that iterable will be
  716. converted into a ``Sequential`` and used as the augmenter.
  717. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  718. Augmenter(s) that make up the background branch.
  719. Low alpha values will show this branch's results.
  720. * If ``None``, then the input images will be reused as the output
  721. of the background branch.
  722. * If ``Augmenter``, then that augmenter will be used as the branch.
  723. * If iterable of ``Augmenter``, then that iterable will be
  724. converted into a ``Sequential`` and used as the augmenter.
  725. per_channel : bool or float, optional
  726. Whether to use the same factor for all channels (``False``)
  727. or to sample a new value for each channel (``True``).
  728. If this value is a float ``p``, then for ``p`` percent of all images
  729. `per_channel` will be treated as True, otherwise as False.
  730. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  731. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  732. name : None or str, optional
  733. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  734. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  735. Old name for parameter `seed`.
  736. Its usage will not yet cause a deprecation warning,
  737. but it is still recommended to use `seed` now.
  738. Outdated since 0.4.0.
  739. deterministic : bool, optional
  740. Deprecated since 0.4.0.
  741. See method ``to_deterministic()`` for an alternative and for
  742. details about what the "deterministic mode" actually does.
  743. Examples
  744. --------
  745. >>> import imgaug.augmenters as iaa
  746. >>> aug = iaa.BlendAlphaElementwise(0.5, iaa.Grayscale(1.0))
  747. Convert each image to pure grayscale and alpha-blend the result with the
  748. original image using an alpha of ``50%`` for all pixels, thereby removing
  749. about ``50%`` of all color. This is equivalent to ``iaa.Grayscale(0.5)``.
  750. This is also equivalent to ``iaa.BlendAlpha(0.5, iaa.Grayscale(1.0))``, as
  751. the opacity has a fixed value of ``0.5`` and is hence identical for all
  752. pixels.
  753. >>> aug = iaa.BlendAlphaElementwise((0, 1.0), iaa.AddToHue(100))
  754. Same as in the previous example, but here with hue-shift instead
  755. of grayscaling and additionally the alpha factor is sampled uniformly
  756. from the interval ``[0.0, 1.0]`` once per pixel, thereby shifting the
  757. hue by a random fraction for each pixel.
  758. >>> aug = iaa.BlendAlphaElementwise(
  759. >>> (0.0, 1.0),
  760. >>> iaa.Affine(rotate=(-20, 20)),
  761. >>> per_channel=0.5)
  762. First, rotate each image by a random degree sampled uniformly from the
  763. interval ``[-20, 20]``. Then, alpha-blend that new image with the original
  764. one using a random factor sampled uniformly from the interval
  765. ``[0.0, 1.0]`` per pixel. For ``50%`` of all images, the blending happens
  766. channel-wise and the factor is sampled independently per pixel *and*
  767. channel (``per_channel=0.5``). As a result, e.g. the red channel may look
  768. visibly rotated (factor near ``1.0``), while the green and blue channels
  769. may not look rotated (factors near ``0.0``).
  770. >>> aug = iaa.BlendAlphaElementwise(
  771. >>> (0.0, 1.0),
  772. >>> foreground=iaa.Add(100),
  773. >>> background=iaa.Multiply(0.2))
  774. Apply two branches of augmenters -- ``A`` and ``B`` -- *independently*
  775. to input images and alpha-blend the results of these branches using a
  776. factor ``f``. Branch ``A`` increases image pixel intensities by ``100``
  777. and ``B`` multiplies the pixel intensities by ``0.2``. ``f`` is sampled
  778. uniformly from the interval ``[0.0, 1.0]`` per pixel. The resulting images
  779. contain a bit of ``A`` and a bit of ``B``.
  780. >>> aug = iaa.BlendAlphaElementwise([0.25, 0.75], iaa.MedianBlur(13))
  781. Apply median blur to each image and alpha-blend the result with the
  782. original image using an alpha factor of either exactly ``0.25`` or
  783. exactly ``0.75`` (sampled once per pixel).
  784. """
  785. # Added in 0.4.0.
  786. def __init__(self, factor=(0.0, 1.0), foreground=None, background=None,
  787. per_channel=False,
  788. seed=None, name=None,
  789. random_state="deprecated", deterministic="deprecated"):
  790. factor = iap.handle_continuous_param(
  791. factor, "factor", value_range=(0, 1.0), tuple_to_uniform=True,
  792. list_to_choice=True)
  793. mask_gen = StochasticParameterMaskGen(factor, per_channel)
  794. super(BlendAlphaElementwise, self).__init__(
  795. mask_gen, foreground, background,
  796. seed=seed, name=name,
  797. random_state=random_state, deterministic=deterministic)
  798. # Added in 0.4.0.
  799. @property
  800. def factor(self):
  801. return self.mask_generator.parameter
  802. class BlendAlphaSimplexNoise(BlendAlphaElementwise):
  803. """Alpha-blend two image sources using simplex noise alpha masks.
  804. The alpha masks are sampled using a simplex noise method, roughly creating
  805. connected blobs of 1s surrounded by 0s. If nearest neighbour
  806. upsampling is used, these blobs can be rectangular with sharp edges.
  807. Added in 0.4.0. (Before that named `SimplexNoiseAlpha`.)
  808. **Supported dtypes**:
  809. See :class:`~imgaug.augmenters.blend.BlendAlphaElementwise`.
  810. Parameters
  811. ----------
  812. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  813. Augmenter(s) that make up the foreground branch.
  814. High alpha values will show this branch's results.
  815. * If ``None``, then the input images will be reused as the output
  816. of the foreground branch.
  817. * If ``Augmenter``, then that augmenter will be used as the branch.
  818. * If iterable of ``Augmenter``, then that iterable will be
  819. converted into a ``Sequential`` and used as the augmenter.
  820. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  821. Augmenter(s) that make up the background branch.
  822. Low alpha values will show this branch's results.
  823. * If ``None``, then the input images will be reused as the output
  824. of the background branch.
  825. * If ``Augmenter``, then that augmenter will be used as the branch.
  826. * If iterable of ``Augmenter``, then that iterable will be
  827. converted into a ``Sequential`` and used as the augmenter.
  828. per_channel : bool or float, optional
  829. Whether to use the same factor for all channels (``False``)
  830. or to sample a new value for each channel (``True``).
  831. If this value is a float ``p``, then for ``p`` percent of all images
  832. `per_channel` will be treated as ``True``, otherwise as ``False``.
  833. size_px_max : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  834. The simplex noise is always generated in a low resolution environment.
  835. This parameter defines the maximum size of that environment (in
  836. pixels). The environment is initialized at the same size as the input
  837. image and then downscaled, so that no side exceeds `size_px_max`
  838. (aspect ratio is kept).
  839. * If int, then that number will be used as the size for all
  840. iterations.
  841. * If tuple of two ``int`` s ``(a, b)``, then a value will be
  842. sampled per iteration from the discrete interval ``[a..b]``.
  843. * If a list of ``int`` s, then a value will be picked per iteration
  844. at random from that list.
  845. * If a ``StochasticParameter``, then a value will be sampled from
  846. that parameter per iteration.
  847. upscale_method : None or imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
  848. After generating the noise maps in low resolution environments, they
  849. have to be upscaled to the input image size. This parameter controls
  850. the upscaling method.
  851. * If ``None``, then either ``nearest`` or ``linear`` or ``cubic``
  852. is picked. Most weight is put on ``linear``, followed by
  853. ``cubic``.
  854. * If ``imgaug.ALL``, then either ``nearest`` or ``linear`` or
  855. ``area`` or ``cubic`` is picked per iteration (all same
  856. probability).
  857. * If a string, then that value will be used as the method (must be
  858. ``nearest`` or ``linear`` or ``area`` or ``cubic``).
  859. * If list of string, then a random value will be picked from that
  860. list per iteration.
  861. * If ``StochasticParameter``, then a random value will be sampled
  862. from that parameter per iteration.
  863. iterations : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  864. How often to repeat the simplex noise generation process per image.
  865. * If ``int``, then that number will be used as the iterations for
  866. all images.
  867. * If tuple of two ``int`` s ``(a, b)``, then a value will be
  868. sampled per image from the discrete interval ``[a..b]``.
  869. * If a list of ``int`` s, then a value will be picked per image at
  870. random from that list.
  871. * If a ``StochasticParameter``, then a value will be sampled from
  872. that parameter per image.
  873. aggregation_method : imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
  874. The noise maps (from each iteration) are combined to one noise map
  875. using an aggregation process. This parameter defines the method used
  876. for that process. Valid methods are ``min``, ``max`` or ``avg``,
  877. where ``min`` combines the noise maps by taking the (elementwise)
  878. minimum over all iteration's results, ``max`` the (elementwise)
  879. maximum and ``avg`` the (elementwise) average.
  880. * If ``imgaug.ALL``, then a random value will be picked per image
  881. from the valid ones.
  882. * If a string, then that value will always be used as the method.
  883. * If a list of string, then a random value will be picked from
  884. that list per image.
  885. * If a ``StochasticParameter``, then a random value will be
  886. sampled from that paramter per image.
  887. sigmoid : bool or number, optional
  888. Whether to apply a sigmoid function to the final noise maps, resulting
  889. in maps that have more extreme values (close to 0.0 or 1.0).
  890. * If ``bool``, then a sigmoid will always (``True``) or never
  891. (``False``) be applied.
  892. * If a number ``p`` with ``0<=p<=1``, then a sigmoid will be
  893. applied to ``p`` percent of all final noise maps.
  894. sigmoid_thresh : None or number or tuple of number or imgaug.parameters.StochasticParameter, optional
  895. Threshold of the sigmoid, when applied. Thresholds above zero
  896. (e.g. ``5.0``) will move the saddle point towards the right, leading
  897. to more values close to 0.0.
  898. * If ``None``, then ``Normal(0, 5.0)`` will be used.
  899. * If number, then that threshold will be used for all images.
  900. * If tuple of two numbers ``(a, b)``, then a random value will
  901. be sampled per image from the interval ``[a, b]``.
  902. * If ``StochasticParameter``, then a random value will be sampled
  903. from that parameter per image.
  904. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  905. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  906. name : None or str, optional
  907. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  908. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  909. Old name for parameter `seed`.
  910. Its usage will not yet cause a deprecation warning,
  911. but it is still recommended to use `seed` now.
  912. Outdated since 0.4.0.
  913. deterministic : bool, optional
  914. Deprecated since 0.4.0.
  915. See method ``to_deterministic()`` for an alternative and for
  916. details about what the "deterministic mode" actually does.
  917. Examples
  918. --------
  919. >>> import imgaug.augmenters as iaa
  920. >>> aug = iaa.BlendAlphaSimplexNoise(iaa.EdgeDetect(1.0))
  921. Detect per image all edges, mark them in a black and white image and
  922. then alpha-blend the result with the original image using simplex noise
  923. masks.
  924. >>> aug = iaa.BlendAlphaSimplexNoise(
  925. >>> iaa.EdgeDetect(1.0),
  926. >>> upscale_method="nearest")
  927. Same as in the previous example, but using only nearest neighbour
  928. upscaling to scale the simplex noise masks to the final image sizes, i.e.
  929. no nearest linear upsampling is used. This leads to rectangles with sharp
  930. edges.
  931. >>> aug = iaa.BlendAlphaSimplexNoise(
  932. >>> iaa.EdgeDetect(1.0),
  933. >>> upscale_method="linear")
  934. Same as in the previous example, but using only linear upscaling to
  935. scale the simplex noise masks to the final image sizes, i.e. no nearest
  936. neighbour upsampling is used. This leads to rectangles with smooth edges.
  937. >>> aug = iaa.BlendAlphaSimplexNoise(
  938. >>> iaa.EdgeDetect(1.0),
  939. >>> sigmoid_thresh=iap.Normal(10.0, 5.0))
  940. Same as in the first example, but using a threshold for the sigmoid
  941. function that is further to the right. This is more conservative, i.e.
  942. the generated noise masks will be mostly black (values around ``0.0``),
  943. which means that most of the original images (parameter/branch
  944. `background`) will be kept, rather than using the results of the
  945. augmentation (parameter/branch `foreground`).
  946. """
  947. # Added in 0.4.0.
  948. def __init__(self, foreground=None, background=None, per_channel=False,
  949. size_px_max=(2, 16), upscale_method=None,
  950. iterations=(1, 3), aggregation_method="max",
  951. sigmoid=True, sigmoid_thresh=None,
  952. seed=None, name=None,
  953. random_state="deprecated", deterministic="deprecated"):
  954. upscale_method_default = iap.Choice(["nearest", "linear", "cubic"],
  955. p=[0.05, 0.6, 0.35])
  956. sigmoid_thresh_default = iap.Normal(0.0, 5.0)
  957. noise = iap.SimplexNoise(
  958. size_px_max=size_px_max,
  959. upscale_method=(upscale_method
  960. if upscale_method is not None
  961. else upscale_method_default)
  962. )
  963. if iterations != 1:
  964. noise = iap.IterativeNoiseAggregator(
  965. noise,
  966. iterations=iterations,
  967. aggregation_method=aggregation_method
  968. )
  969. use_sigmoid = (
  970. sigmoid is True
  971. or (ia.is_single_number(sigmoid) and sigmoid >= 0.01))
  972. if use_sigmoid:
  973. noise = iap.Sigmoid.create_for_noise(
  974. noise,
  975. threshold=(sigmoid_thresh
  976. if sigmoid_thresh is not None
  977. else sigmoid_thresh_default),
  978. activated=sigmoid
  979. )
  980. super(BlendAlphaSimplexNoise, self).__init__(
  981. factor=noise, foreground=foreground, background=background,
  982. per_channel=per_channel,
  983. seed=seed, name=name,
  984. random_state=random_state, deterministic=deterministic)
  985. class BlendAlphaFrequencyNoise(BlendAlphaElementwise):
  986. """Alpha-blend two image sources using frequency noise masks.
  987. The alpha masks are sampled using frequency noise of varying scales,
  988. which can sometimes create large connected blobs of ``1`` s surrounded
  989. by ``0`` s and other times results in smaller patterns. If nearest
  990. neighbour upsampling is used, these blobs can be rectangular with sharp
  991. edges.
  992. Added in 0.4.0. (Before that named `FrequencyNoiseAlpha`.)
  993. **Supported dtypes**:
  994. See :class:`~imgaug.augmenters.blend.BlendAlphaElementwise`.
  995. Parameters
  996. ----------
  997. exponent : number or tuple of number of list of number or imgaug.parameters.StochasticParameter, optional
  998. Exponent to use when scaling in the frequency domain.
  999. Sane values are in the range ``-4`` (large blobs) to ``4`` (small
  1000. patterns). To generate cloud-like structures, use roughly ``-2``.
  1001. * If number, then that number will be used as the exponent for all
  1002. iterations.
  1003. * If tuple of two numbers ``(a, b)``, then a value will be sampled
  1004. per iteration from the interval ``[a, b]``.
  1005. * If a list of numbers, then a value will be picked per iteration
  1006. at random from that list.
  1007. * If a ``StochasticParameter``, then a value will be sampled from
  1008. that parameter per iteration.
  1009. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1010. Augmenter(s) that make up the foreground branch.
  1011. High alpha values will show this branch's results.
  1012. * If ``None``, then the input images will be reused as the output
  1013. of the foreground branch.
  1014. * If ``Augmenter``, then that augmenter will be used as the branch.
  1015. * If iterable of ``Augmenter``, then that iterable will be
  1016. converted into a ``Sequential`` and used as the augmenter.
  1017. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1018. Augmenter(s) that make up the background branch.
  1019. Low alpha values will show this branch's results.
  1020. * If ``None``, then the input images will be reused as the output
  1021. of the background branch.
  1022. * If ``Augmenter``, then that augmenter will be used as the branch.
  1023. * If iterable of ``Augmenter``, then that iterable will be
  1024. converted into a ``Sequential`` and used as the augmenter.
  1025. per_channel : bool or float, optional
  1026. Whether to use the same factor for all channels (``False``)
  1027. or to sample a new value for each channel (``True``).
  1028. If this value is a float ``p``, then for ``p`` percent of all images
  1029. `per_channel` will be treated as ``True``, otherwise as ``False``.
  1030. size_px_max : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  1031. The noise is generated in a low resolution environment.
  1032. This parameter defines the maximum size of that environment (in
  1033. pixels). The environment is initialized at the same size as the input
  1034. image and then downscaled, so that no side exceeds `size_px_max`
  1035. (aspect ratio is kept).
  1036. * If ``int``, then that number will be used as the size for all
  1037. iterations.
  1038. * If tuple of two ``int`` s ``(a, b)``, then a value will be
  1039. sampled per iteration from the discrete interval ``[a..b]``.
  1040. * If a list of ``int`` s, then a value will be picked per
  1041. iteration at random from that list.
  1042. * If a ``StochasticParameter``, then a value will be sampled from
  1043. that parameter per iteration.
  1044. upscale_method : None or imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
  1045. After generating the noise maps in low resolution environments, they
  1046. have to be upscaled to the input image size. This parameter controls
  1047. the upscaling method.
  1048. * If ``None``, then either ``nearest`` or ``linear`` or ``cubic``
  1049. is picked. Most weight is put on ``linear``, followed by
  1050. ``cubic``.
  1051. * If ``imgaug.ALL``, then either ``nearest`` or ``linear`` or
  1052. ``area`` or ``cubic`` is picked per iteration (all same
  1053. probability).
  1054. * If string, then that value will be used as the method (must be
  1055. ``nearest`` or ``linear`` or ``area`` or ``cubic``).
  1056. * If list of string, then a random value will be picked from that
  1057. list per iteration.
  1058. * If ``StochasticParameter``, then a random value will be sampled
  1059. from that parameter per iteration.
  1060. iterations : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  1061. How often to repeat the simplex noise generation process per
  1062. image.
  1063. * If ``int``, then that number will be used as the iterations for
  1064. all images.
  1065. * If tuple of two ``int`` s ``(a, b)``, then a value will be
  1066. sampled per image from the discrete interval ``[a..b]``.
  1067. * If a list of ``int`` s, then a value will be picked per image at
  1068. random from that list.
  1069. * If a ``StochasticParameter``, then a value will be sampled from
  1070. that parameter per image.
  1071. aggregation_method : imgaug.ALL or str or list of str or imgaug.parameters.StochasticParameter, optional
  1072. The noise maps (from each iteration) are combined to one noise map
  1073. using an aggregation process. This parameter defines the method used
  1074. for that process. Valid methods are ``min``, ``max`` or ``avg``,
  1075. where 'min' combines the noise maps by taking the (elementwise) minimum
  1076. over all iteration's results, ``max`` the (elementwise) maximum and
  1077. ``avg`` the (elementwise) average.
  1078. * If ``imgaug.ALL``, then a random value will be picked per image
  1079. from the valid ones.
  1080. * If a string, then that value will always be used as the method.
  1081. * If a list of string, then a random value will be picked from
  1082. that list per image.
  1083. * If a ``StochasticParameter``, then a random value will be sampled
  1084. from that parameter per image.
  1085. sigmoid : bool or number, optional
  1086. Whether to apply a sigmoid function to the final noise maps, resulting
  1087. in maps that have more extreme values (close to ``0.0`` or ``1.0``).
  1088. * If ``bool``, then a sigmoid will always (``True``) or never
  1089. (``False``) be applied.
  1090. * If a number ``p`` with ``0<=p<=1``, then a sigmoid will be applied to
  1091. ``p`` percent of all final noise maps.
  1092. sigmoid_thresh : None or number or tuple of number or imgaug.parameters.StochasticParameter, optional
  1093. Threshold of the sigmoid, when applied. Thresholds above zero
  1094. (e.g. ``5.0``) will move the saddle point towards the right, leading to
  1095. more values close to ``0.0``.
  1096. * If ``None``, then ``Normal(0, 5.0)`` will be used.
  1097. * If number, then that threshold will be used for all images.
  1098. * If tuple of two numbers ``(a, b)``, then a random value will
  1099. be sampled per image from the range ``[a, b]``.
  1100. * If ``StochasticParameter``, then a random value will be sampled
  1101. from that parameter per image.
  1102. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1103. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1104. name : None or str, optional
  1105. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1106. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1107. Old name for parameter `seed`.
  1108. Its usage will not yet cause a deprecation warning,
  1109. but it is still recommended to use `seed` now.
  1110. Outdated since 0.4.0.
  1111. deterministic : bool, optional
  1112. Deprecated since 0.4.0.
  1113. See method ``to_deterministic()`` for an alternative and for
  1114. details about what the "deterministic mode" actually does.
  1115. Examples
  1116. --------
  1117. >>> import imgaug.augmenters as iaa
  1118. >>> aug = iaa.BlendAlphaFrequencyNoise(foreground=iaa.EdgeDetect(1.0))
  1119. Detect per image all edges, mark them in a black and white image and
  1120. then alpha-blend the result with the original image using frequency noise
  1121. masks.
  1122. >>> aug = iaa.BlendAlphaFrequencyNoise(
  1123. >>> foreground=iaa.EdgeDetect(1.0),
  1124. >>> upscale_method="nearest")
  1125. Same as the first example, but using only linear upscaling to
  1126. scale the frequency noise masks to the final image sizes, i.e. no nearest
  1127. neighbour upsampling is used. This results in smooth edges.
  1128. >>> aug = iaa.BlendAlphaFrequencyNoise(
  1129. >>> foreground=iaa.EdgeDetect(1.0),
  1130. >>> upscale_method="linear")
  1131. Same as the first example, but using only linear upscaling to
  1132. scale the frequency noise masks to the final image sizes, i.e. no nearest
  1133. neighbour upsampling is used. This results in smooth edges.
  1134. >>> aug = iaa.BlendAlphaFrequencyNoise(
  1135. >>> foreground=iaa.EdgeDetect(1.0),
  1136. >>> upscale_method="linear",
  1137. >>> exponent=-2,
  1138. >>> sigmoid=False)
  1139. Same as in the previous example, but with the exponent set to a constant
  1140. ``-2`` and the sigmoid deactivated, resulting in cloud-like patterns
  1141. without sharp edges.
  1142. >>> aug = iaa.BlendAlphaFrequencyNoise(
  1143. >>> foreground=iaa.EdgeDetect(1.0),
  1144. >>> sigmoid_thresh=iap.Normal(10.0, 5.0))
  1145. Same as the first example, but using a threshold for the sigmoid function
  1146. that is further to the right. This is more conservative, i.e. the generated
  1147. noise masks will be mostly black (values around ``0.0``), which means that
  1148. most of the original images (parameter/branch `background`) will be kept,
  1149. rather than using the results of the augmentation (parameter/branch
  1150. `foreground`).
  1151. """
  1152. # Added in 0.4.0.
  1153. def __init__(self, exponent=(-4, 4), foreground=None, background=None,
  1154. per_channel=False, size_px_max=(4, 16), upscale_method=None,
  1155. iterations=(1, 3), aggregation_method=["avg", "max"],
  1156. sigmoid=0.5, sigmoid_thresh=None,
  1157. seed=None, name=None,
  1158. random_state="deprecated", deterministic="deprecated"):
  1159. # pylint: disable=dangerous-default-value
  1160. upscale_method_default = iap.Choice(["nearest", "linear", "cubic"],
  1161. p=[0.05, 0.6, 0.35])
  1162. sigmoid_thresh_default = iap.Normal(0.0, 5.0)
  1163. noise = iap.FrequencyNoise(
  1164. exponent=exponent,
  1165. size_px_max=size_px_max,
  1166. upscale_method=(upscale_method
  1167. if upscale_method is not None
  1168. else upscale_method_default)
  1169. )
  1170. if iterations != 1:
  1171. noise = iap.IterativeNoiseAggregator(
  1172. noise,
  1173. iterations=iterations,
  1174. aggregation_method=aggregation_method
  1175. )
  1176. use_sigmoid = (
  1177. sigmoid is True
  1178. or (ia.is_single_number(sigmoid) and sigmoid >= 0.01))
  1179. if use_sigmoid:
  1180. noise = iap.Sigmoid.create_for_noise(
  1181. noise,
  1182. threshold=(sigmoid_thresh
  1183. if sigmoid_thresh is not None
  1184. else sigmoid_thresh_default),
  1185. activated=sigmoid
  1186. )
  1187. super(BlendAlphaFrequencyNoise, self).__init__(
  1188. factor=noise, foreground=foreground, background=background,
  1189. per_channel=per_channel,
  1190. seed=seed, name=name,
  1191. random_state=random_state, deterministic=deterministic)
  1192. class BlendAlphaSomeColors(BlendAlphaMask):
  1193. """Blend images from two branches using colorwise masks.
  1194. This class generates masks that "mark" a few colors and replace the
  1195. pixels within these colors with the results of the foreground branch.
  1196. The remaining pixels are replaced with the results of the background
  1197. branch (usually the identity function). That allows to e.g. selectively
  1198. grayscale a few colors, while keeping other colors unchanged.
  1199. This class is a thin wrapper around
  1200. :class:`~imgaug.augmenters.blend.BlendAlphaMask` together with
  1201. :class:`~imgaug.augmenters.blend.SomeColorsMaskGen`.
  1202. .. note::
  1203. The underlying mask generator will produce an ``AssertionError`` for
  1204. batches that contain no images.
  1205. .. note::
  1206. Avoid using augmenters as children that affect pixel locations (e.g.
  1207. horizontal flips). See
  1208. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  1209. Added in 0.4.0.
  1210. **Supported dtypes**:
  1211. See :func:`~imgaug.augmenters.color.change_colorspaces_`.
  1212. Parameters
  1213. ----------
  1214. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1215. Augmenter(s) that make up the foreground branch.
  1216. High alpha values will show this branch's results.
  1217. * If ``None``, then the input images will be reused as the output
  1218. of the foreground branch.
  1219. * If ``Augmenter``, then that augmenter will be used as the branch.
  1220. * If iterable of ``Augmenter``, then that iterable will be
  1221. converted into a ``Sequential`` and used as the augmenter.
  1222. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1223. Augmenter(s) that make up the background branch.
  1224. Low alpha values will show this branch's results.
  1225. * If ``None``, then the input images will be reused as the output
  1226. of the background branch.
  1227. * If ``Augmenter``, then that augmenter will be used as the branch.
  1228. * If iterable of ``Augmenter``, then that iterable will be
  1229. converted into a ``Sequential`` and used as the augmenter.
  1230. nb_bins : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  1231. See :class:`~imgaug.augmenters.blend.SomeColorsMaskGen`.
  1232. smoothness : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1233. See :class:`~imgaug.augmenters.blend.SomeColorsMaskGen`.
  1234. alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1235. See :class:`~imgaug.augmenters.blend.SomeColorsMaskGen`.
  1236. rotation_deg : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1237. See :class:`~imgaug.augmenters.blend.SomeColorsMaskGen`.
  1238. from_colorspace : str, optional
  1239. See :class:`~imgaug.augmenters.blend.SomeColorsMaskGen`.
  1240. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1241. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1242. name : None or str, optional
  1243. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1244. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1245. Old name for parameter `seed`.
  1246. Its usage will not yet cause a deprecation warning,
  1247. but it is still recommended to use `seed` now.
  1248. Outdated since 0.4.0.
  1249. deterministic : bool, optional
  1250. Deprecated since 0.4.0.
  1251. See method ``to_deterministic()`` for an alternative and for
  1252. details about what the "deterministic mode" actually does.
  1253. Examples
  1254. --------
  1255. >>> import imgaug.augmenters as iaa
  1256. >>> aug = iaa.BlendAlphaSomeColors(iaa.Grayscale(1.0))
  1257. Create an augmenter that turns randomly removes some colors in images by
  1258. grayscaling them.
  1259. >>> aug = iaa.BlendAlphaSomeColors(iaa.TotalDropout(1.0))
  1260. Create an augmenter that removes some colors in images by replacing them
  1261. with black pixels.
  1262. >>> aug = iaa.BlendAlphaSomeColors(
  1263. >>> iaa.MultiplySaturation(0.5), iaa.MultiplySaturation(1.5))
  1264. Create an augmenter that desaturates some colors and increases the
  1265. saturation of the remaining ones.
  1266. >>> aug = iaa.BlendAlphaSomeColors(
  1267. >>> iaa.AveragePooling(7), alpha=[0.0, 1.0], smoothness=0.0)
  1268. Create an augmenter that applies average pooling to some colors.
  1269. Each color tune is either selected (alpha of ``1.0``) or not
  1270. selected (``0.0``). There is no gradual change between similar colors.
  1271. >>> aug = iaa.BlendAlphaSomeColors(
  1272. >>> iaa.AveragePooling(7), nb_bins=2, smoothness=0.0)
  1273. Create an augmenter that applies average pooling to some colors.
  1274. Choose on average half of all colors in images for the blending operation.
  1275. >>> aug = iaa.BlendAlphaSomeColors(
  1276. >>> iaa.AveragePooling(7), from_colorspace="BGR")
  1277. Create an augmenter that applies average pooling to some colors with
  1278. input images being in BGR colorspace.
  1279. """
  1280. # Added in 0.4.0.
  1281. def __init__(self, foreground=None, background=None,
  1282. nb_bins=(5, 15), smoothness=(0.1, 0.3),
  1283. alpha=[0.0, 1.0], rotation_deg=(0, 360),
  1284. from_colorspace="RGB",
  1285. seed=None, name=None,
  1286. random_state="deprecated", deterministic="deprecated"):
  1287. # pylint: disable=dangerous-default-value
  1288. super(BlendAlphaSomeColors, self).__init__(
  1289. SomeColorsMaskGen(
  1290. nb_bins=nb_bins,
  1291. smoothness=smoothness,
  1292. alpha=alpha,
  1293. rotation_deg=rotation_deg,
  1294. from_colorspace=from_colorspace
  1295. ),
  1296. foreground=foreground,
  1297. background=background,
  1298. seed=seed, name=name,
  1299. random_state=random_state, deterministic=deterministic)
  1300. class BlendAlphaHorizontalLinearGradient(BlendAlphaMask):
  1301. """Blend images from two branches along a horizontal linear gradient.
  1302. This class generates a horizontal linear gradient mask (i.e. usually a
  1303. mask with low values on the left and high values on the right) and
  1304. alphas-blends between foreground and background branch using that
  1305. mask.
  1306. This class is a thin wrapper around
  1307. :class:`~imgaug.augmenters.blend.BlendAlphaMask` together with
  1308. :class:`~imgaug.augmenters.blend.HorizontalLinearGradientMaskGen`.
  1309. .. note::
  1310. Avoid using augmenters as children that affect pixel locations (e.g.
  1311. horizontal flips). See
  1312. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  1313. Added in 0.4.0.
  1314. **Supported dtypes**:
  1315. See :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  1316. Parameters
  1317. ----------
  1318. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1319. Augmenter(s) that make up the foreground branch.
  1320. High alpha values will show this branch's results.
  1321. * If ``None``, then the input images will be reused as the output
  1322. of the foreground branch.
  1323. * If ``Augmenter``, then that augmenter will be used as the branch.
  1324. * If iterable of ``Augmenter``, then that iterable will be
  1325. converted into a ``Sequential`` and used as the augmenter.
  1326. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1327. Augmenter(s) that make up the background branch.
  1328. Low alpha values will show this branch's results.
  1329. * If ``None``, then the input images will be reused as the output
  1330. of the background branch.
  1331. * If ``Augmenter``, then that augmenter will be used as the branch.
  1332. * If iterable of ``Augmenter``, then that iterable will be
  1333. converted into a ``Sequential`` and used as the augmenter.
  1334. min_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1335. See :class:`~imgaug.augmenters.blend.HorizontalLinearGradientMaskGen`.
  1336. max_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1337. See :class:`~imgaug.augmenters.blend.HorizontalLinearGradientMaskGen`.
  1338. start_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1339. See :class:`~imgaug.augmenters.blend.HorizontalLinearGradientMaskGen`.
  1340. end_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1341. See :class:`~imgaug.augmenters.blend.HorizontalLinearGradientMaskGen`.
  1342. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1343. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1344. name : None or str, optional
  1345. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1346. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1347. Old name for parameter `seed`.
  1348. Its usage will not yet cause a deprecation warning,
  1349. but it is still recommended to use `seed` now.
  1350. Outdated since 0.4.0.
  1351. deterministic : bool, optional
  1352. Deprecated since 0.4.0.
  1353. See method ``to_deterministic()`` for an alternative and for
  1354. details about what the "deterministic mode" actually does.
  1355. Examples
  1356. --------
  1357. >>> import imgaug.augmenters as iaa
  1358. >>> aug = iaa.BlendAlphaHorizontalLinearGradient(iaa.AddToHue((-100, 100)))
  1359. Create an augmenter that randomizes the hue towards the right of the
  1360. image.
  1361. >>> aug = iaa.BlendAlphaHorizontalLinearGradient(
  1362. >>> iaa.TotalDropout(1.0),
  1363. >>> min_value=0.2, max_value=0.8)
  1364. Create an augmenter that replaces pixels towards the right with darker
  1365. and darker values. However it always keeps at least
  1366. 20% (``1.0 - max_value``) of the original pixel value on the far right
  1367. and always replaces at least 20% on the far left (``min_value=0.2``).
  1368. >>> aug = iaa.BlendAlphaHorizontalLinearGradient(
  1369. >>> iaa.AveragePooling(11),
  1370. >>> start_at=(0.0, 1.0), end_at=(0.0, 1.0))
  1371. Create an augmenter that blends with an average-pooled image according
  1372. to a horizontal gradient that starts at a random x-coordinate and reaches
  1373. its maximum at another random x-coordinate. Due to that randomness,
  1374. the gradient may increase towards the left or right.
  1375. """
  1376. # Added in 0.4.0.
  1377. def __init__(self, foreground=None, background=None,
  1378. min_value=(0.0, 0.2), max_value=(0.8, 1.0),
  1379. start_at=(0.0, 0.2), end_at=(0.8, 1.0),
  1380. seed=None, name=None,
  1381. random_state="deprecated", deterministic="deprecated"):
  1382. super(BlendAlphaHorizontalLinearGradient, self).__init__(
  1383. HorizontalLinearGradientMaskGen(
  1384. min_value=min_value,
  1385. max_value=max_value,
  1386. start_at=start_at,
  1387. end_at=end_at
  1388. ),
  1389. foreground=foreground,
  1390. background=background,
  1391. seed=seed, name=name,
  1392. random_state=random_state, deterministic=deterministic)
  1393. class BlendAlphaVerticalLinearGradient(BlendAlphaMask):
  1394. """Blend images from two branches along a vertical linear gradient.
  1395. This class generates a vertical linear gradient mask (i.e. usually a
  1396. mask with low values on the left and high values on the right) and
  1397. alphas-blends between foreground and background branch using that
  1398. mask.
  1399. This class is a thin wrapper around
  1400. :class:`~imgaug.augmenters.blend.BlendAlphaMask` together with
  1401. :class:`~imgaug.augmenters.blend.VerticalLinearGradientMaskGen`.
  1402. .. note::
  1403. Avoid using augmenters as children that affect pixel locations (e.g.
  1404. horizontal flips). See
  1405. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  1406. Added in 0.4.0.
  1407. **Supported dtypes**:
  1408. See :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  1409. Parameters
  1410. ----------
  1411. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1412. Augmenter(s) that make up the foreground branch.
  1413. High alpha values will show this branch's results.
  1414. * If ``None``, then the input images will be reused as the output
  1415. of the foreground branch.
  1416. * If ``Augmenter``, then that augmenter will be used as the branch.
  1417. * If iterable of ``Augmenter``, then that iterable will be
  1418. converted into a ``Sequential`` and used as the augmenter.
  1419. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1420. Augmenter(s) that make up the background branch.
  1421. Low alpha values will show this branch's results.
  1422. * If ``None``, then the input images will be reused as the output
  1423. of the background branch.
  1424. * If ``Augmenter``, then that augmenter will be used as the branch.
  1425. * If iterable of ``Augmenter``, then that iterable will be
  1426. converted into a ``Sequential`` and used as the augmenter.
  1427. min_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1428. See :class:`~imgaug.augmenters.blend.VerticalLinearGradientMaskGen`.
  1429. max_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1430. See :class:`~imgaug.augmenters.blend.VerticalLinearGradientMaskGen`.
  1431. start_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1432. See :class:`~imgaug.augmenters.blend.VerticalLinearGradientMaskGen`.
  1433. end_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1434. See :class:`~imgaug.augmenters.blend.VerticalLinearGradientMaskGen`.
  1435. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1436. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1437. name : None or str, optional
  1438. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1439. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1440. Old name for parameter `seed`.
  1441. Its usage will not yet cause a deprecation warning,
  1442. but it is still recommended to use `seed` now.
  1443. Outdated since 0.4.0.
  1444. deterministic : bool, optional
  1445. Deprecated since 0.4.0.
  1446. See method ``to_deterministic()`` for an alternative and for
  1447. details about what the "deterministic mode" actually does.
  1448. Examples
  1449. --------
  1450. >>> import imgaug.augmenters as iaa
  1451. >>> aug = iaa.BlendAlphaVerticalLinearGradient(iaa.AddToHue((-100, 100)))
  1452. Create an augmenter that randomizes the hue towards the bottom of the
  1453. image.
  1454. >>> aug = iaa.BlendAlphaVerticalLinearGradient(
  1455. >>> iaa.TotalDropout(1.0),
  1456. >>> min_value=0.2, max_value=0.8)
  1457. Create an augmenter that replaces pixels towards the bottom with darker
  1458. and darker values. However it always keeps at least
  1459. 20% (``1.0 - max_value``) of the original pixel value on the far bottom
  1460. and always replaces at least 20% on the far top (``min_value=0.2``).
  1461. >>> aug = iaa.BlendAlphaVerticalLinearGradient(
  1462. >>> iaa.AveragePooling(11),
  1463. >>> start_at=(0.0, 1.0), end_at=(0.0, 1.0))
  1464. Create an augmenter that blends with an average-pooled image according
  1465. to a vertical gradient that starts at a random y-coordinate and reaches
  1466. its maximum at another random y-coordinate. Due to that randomness,
  1467. the gradient may increase towards the bottom or top.
  1468. >>> aug = iaa.BlendAlphaVerticalLinearGradient(
  1469. >>> iaa.Clouds(),
  1470. >>> start_at=(0.15, 0.35), end_at=0.0)
  1471. Create an augmenter that draws clouds in roughly the top quarter of the
  1472. image.
  1473. """
  1474. # Added in 0.4.0.
  1475. def __init__(self, foreground=None, background=None,
  1476. min_value=(0.0, 0.2), max_value=(0.8, 1.0),
  1477. start_at=(0.0, 0.2), end_at=(0.8, 1.0),
  1478. seed=None, name=None,
  1479. random_state="deprecated", deterministic="deprecated"):
  1480. super(BlendAlphaVerticalLinearGradient, self).__init__(
  1481. VerticalLinearGradientMaskGen(
  1482. min_value=min_value,
  1483. max_value=max_value,
  1484. start_at=start_at,
  1485. end_at=end_at
  1486. ),
  1487. foreground=foreground,
  1488. background=background,
  1489. seed=seed, name=name,
  1490. random_state=random_state, deterministic=deterministic)
  1491. class BlendAlphaRegularGrid(BlendAlphaMask):
  1492. """Blend images from two branches according to a regular grid.
  1493. This class generates for each image a mask that splits the image into a
  1494. grid-like pattern of ``H`` rows and ``W`` columns. Each cell is then
  1495. filled with an alpha value, sampled randomly per cell.
  1496. The difference to :class:`AlphaBlendCheckerboard` is that this class
  1497. samples random alpha values per grid cell, while in the checkerboard the
  1498. alpha values follow a fixed pattern.
  1499. This class is a thin wrapper around
  1500. :class:`~imgaug.augmenters.blend.BlendAlphaMask` together with
  1501. :class:`~imgaug.augmenters.blend.RegularGridMaskGen`.
  1502. .. note::
  1503. Avoid using augmenters as children that affect pixel locations (e.g.
  1504. horizontal flips). See
  1505. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  1506. Added in 0.4.0.
  1507. **Supported dtypes**:
  1508. See :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  1509. Parameters
  1510. ----------
  1511. nb_rows : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  1512. Number of rows of the checkerboard.
  1513. See :class:`~imgaug.augmenters.blend.CheckerboardMaskGen` for details.
  1514. nb_cols : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  1515. Number of columns of the checkerboard. Analogous to `nb_rows`.
  1516. See :class:`~imgaug.augmenters.blend.CheckerboardMaskGen` for details.
  1517. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1518. Augmenter(s) that make up the foreground branch.
  1519. High alpha values will show this branch's results.
  1520. * If ``None``, then the input images will be reused as the output
  1521. of the foreground branch.
  1522. * If ``Augmenter``, then that augmenter will be used as the branch.
  1523. * If iterable of ``Augmenter``, then that iterable will be
  1524. converted into a ``Sequential`` and used as the augmenter.
  1525. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1526. Augmenter(s) that make up the background branch.
  1527. Low alpha values will show this branch's results.
  1528. * If ``None``, then the input images will be reused as the output
  1529. of the background branch.
  1530. * If ``Augmenter``, then that augmenter will be used as the branch.
  1531. * If iterable of ``Augmenter``, then that iterable will be
  1532. converted into a ``Sequential`` and used as the augmenter.
  1533. alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1534. Alpha value of each cell.
  1535. * If ``number``: Exactly that value will be used for all images.
  1536. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  1537. per image from the interval ``[a, b]``.
  1538. * If ``list``: A random value will be picked per image from that list.
  1539. * If ``StochasticParameter``: That parameter will be queried once
  1540. per batch for ``(N,)`` values -- one per image.
  1541. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1542. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1543. name : None or str, optional
  1544. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1545. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1546. Old name for parameter `seed`.
  1547. Its usage will not yet cause a deprecation warning,
  1548. but it is still recommended to use `seed` now.
  1549. Outdated since 0.4.0.
  1550. deterministic : bool, optional
  1551. Deprecated since 0.4.0.
  1552. See method ``to_deterministic()`` for an alternative and for
  1553. details about what the "deterministic mode" actually does.
  1554. Examples
  1555. --------
  1556. >>> import imgaug.augmenters as iaa
  1557. >>> aug = iaa.BlendAlphaRegularGrid(nb_rows=(4, 6), nb_cols=(1, 4),
  1558. >>> foreground=iaa.Multiply(0.0))
  1559. Create an augmenter that places a ``HxW`` grid on each image, where
  1560. ``H`` (rows) is randomly and uniformly sampled from the interval ``[4, 6]``
  1561. and ``W`` is analogously sampled from the interval ``[1, 4]``. Roughly
  1562. half of the cells in the grid are filled with ``0.0``, the remaining ones
  1563. are unaltered. Which cells exactly are "dropped" is randomly decided
  1564. per image. The resulting effect is similar to
  1565. :class:`~imgaug.augmenters.arithmetic.CoarseDropout`.
  1566. >>> aug = iaa.BlendAlphaRegularGrid(nb_rows=2, nb_cols=2,
  1567. >>> foreground=iaa.Multiply(0.0),
  1568. >>> background=iaa.AveragePooling(8),
  1569. >>> alpha=[0.0, 0.0, 1.0])
  1570. Create an augmenter that always placed ``2x2`` cells on each image
  1571. and sets about ``1/3`` of them to zero (foreground branch) and
  1572. the remaining ``2/3`` to a pixelated version (background branch).
  1573. """
  1574. # Added in 0.4.0.
  1575. def __init__(self, nb_rows, nb_cols,
  1576. foreground=None, background=None,
  1577. alpha=[0.0, 1.0],
  1578. seed=None, name=None,
  1579. random_state="deprecated", deterministic="deprecated"):
  1580. # pylint: disable=dangerous-default-value
  1581. super(BlendAlphaRegularGrid, self).__init__(
  1582. RegularGridMaskGen(
  1583. nb_rows=nb_rows,
  1584. nb_cols=nb_cols,
  1585. alpha=alpha
  1586. ),
  1587. foreground=foreground,
  1588. background=background,
  1589. seed=seed, name=name,
  1590. random_state=random_state, deterministic=deterministic)
  1591. class BlendAlphaCheckerboard(BlendAlphaMask):
  1592. """Blend images from two branches according to a checkerboard pattern.
  1593. This class generates for each image a mask following a checkboard layout of
  1594. ``H`` rows and ``W`` columns. Each cell is then filled with either
  1595. ``1.0`` or ``0.0``. The cell at the top-left is always ``1.0``. Its right
  1596. and bottom neighbour cells are ``0.0``. The 4-neighbours of any cell always
  1597. have a value opposite to the cell's value (``0.0`` vs. ``1.0``).
  1598. This class is a thin wrapper around
  1599. :class:`~imgaug.augmenters.blend.BlendAlphaMask` together with
  1600. :class:`~imgaug.augmenters.blend.CheckerboardMaskGen`.
  1601. .. note::
  1602. Avoid using augmenters as children that affect pixel locations (e.g.
  1603. horizontal flips). See
  1604. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  1605. Added in 0.4.0.
  1606. **Supported dtypes**:
  1607. See :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  1608. Parameters
  1609. ----------
  1610. nb_rows : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  1611. Number of rows of the checkerboard.
  1612. See :class:`~imgaug.augmenters.blend.CheckerboardMaskGen` for details.
  1613. nb_cols : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  1614. Number of columns of the checkerboard. Analogous to `nb_rows`.
  1615. See :class:`~imgaug.augmenters.blend.CheckerboardMaskGen` for details.
  1616. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1617. Augmenter(s) that make up the foreground branch.
  1618. High alpha values will show this branch's results.
  1619. * If ``None``, then the input images will be reused as the output
  1620. of the foreground branch.
  1621. * If ``Augmenter``, then that augmenter will be used as the branch.
  1622. * If iterable of ``Augmenter``, then that iterable will be
  1623. converted into a ``Sequential`` and used as the augmenter.
  1624. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1625. Augmenter(s) that make up the background branch.
  1626. Low alpha values will show this branch's results.
  1627. * If ``None``, then the input images will be reused as the output
  1628. of the background branch.
  1629. * If ``Augmenter``, then that augmenter will be used as the branch.
  1630. * If iterable of ``Augmenter``, then that iterable will be
  1631. converted into a ``Sequential`` and used as the augmenter.
  1632. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1633. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1634. name : None or str, optional
  1635. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1636. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1637. Old name for parameter `seed`.
  1638. Its usage will not yet cause a deprecation warning,
  1639. but it is still recommended to use `seed` now.
  1640. Outdated since 0.4.0.
  1641. deterministic : bool, optional
  1642. Deprecated since 0.4.0.
  1643. See method ``to_deterministic()`` for an alternative and for
  1644. details about what the "deterministic mode" actually does.
  1645. Examples
  1646. --------
  1647. >>> import imgaug.augmenters as iaa
  1648. >>> aug = iaa.BlendAlphaCheckerboard(nb_rows=2, nb_cols=(1, 4),
  1649. >>> foreground=iaa.AddToHue((-100, 100)))
  1650. Create an augmenter that places a ``HxW`` grid on each image, where
  1651. ``H`` (rows) is always ``2`` and ``W`` is randomly and uniformly sampled
  1652. from the interval ``[1, 4]``. For half of the cells in the grid the hue
  1653. is randomly modified, the other half of the cells is unaltered.
  1654. """
  1655. # Added in 0.4.0.
  1656. def __init__(self, nb_rows, nb_cols,
  1657. foreground=None, background=None,
  1658. seed=None, name=None,
  1659. random_state="deprecated", deterministic="deprecated"):
  1660. super(BlendAlphaCheckerboard, self).__init__(
  1661. CheckerboardMaskGen(
  1662. nb_rows=nb_rows,
  1663. nb_cols=nb_cols
  1664. ),
  1665. foreground=foreground,
  1666. background=background,
  1667. seed=seed, name=name,
  1668. random_state=random_state, deterministic=deterministic)
  1669. class BlendAlphaSegMapClassIds(BlendAlphaMask):
  1670. """Blend images from two branches based on segmentation map ids.
  1671. This class generates masks that are ``1.0`` at pixel locations covered
  1672. by specific classes in segmentation maps.
  1673. This class is a thin wrapper around
  1674. :class:`~imgaug.augmenters.blend.BlendAlphaMask` together with
  1675. :class:`~imgaug.augmenters.blend.SegMapClassIdsMaskGen`.
  1676. .. note::
  1677. Avoid using augmenters as children that affect pixel locations (e.g.
  1678. horizontal flips). See
  1679. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  1680. .. note::
  1681. Segmentation maps can have multiple channels. If that is the case
  1682. then for each position ``(x, y)`` it is sufficient that any class id
  1683. in any channel matches one of the desired class ids.
  1684. .. note::
  1685. This class will produce an ``AssertionError`` if there are no
  1686. segmentation maps in a batch.
  1687. Added in 0.4.0.
  1688. **Supported dtypes**:
  1689. See :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  1690. Parameters
  1691. ----------
  1692. class_ids : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  1693. See :class:`~imgaug.augmenters.blend.SegMapClassIdsMaskGen`.
  1694. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1695. Augmenter(s) that make up the foreground branch.
  1696. High alpha values will show this branch's results.
  1697. * If ``None``, then the input images will be reused as the output
  1698. of the foreground branch.
  1699. * If ``Augmenter``, then that augmenter will be used as the branch.
  1700. * If iterable of ``Augmenter``, then that iterable will be
  1701. converted into a ``Sequential`` and used as the augmenter.
  1702. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1703. Augmenter(s) that make up the background branch.
  1704. Low alpha values will show this branch's results.
  1705. * If ``None``, then the input images will be reused as the output
  1706. of the background branch.
  1707. * If ``Augmenter``, then that augmenter will be used as the branch.
  1708. * If iterable of ``Augmenter``, then that iterable will be
  1709. converted into a ``Sequential`` and used as the augmenter.
  1710. nb_sample_classes : None or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  1711. See :class:`~imgaug.augmenters.blend.SegMapClassIdsMaskGen`.
  1712. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1713. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1714. name : None or str, optional
  1715. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1716. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1717. Old name for parameter `seed`.
  1718. Its usage will not yet cause a deprecation warning,
  1719. but it is still recommended to use `seed` now.
  1720. Outdated since 0.4.0.
  1721. deterministic : bool, optional
  1722. Deprecated since 0.4.0.
  1723. See method ``to_deterministic()`` for an alternative and for
  1724. details about what the "deterministic mode" actually does.
  1725. Examples
  1726. --------
  1727. >>> import imgaug.augmenters as iaa
  1728. >>> aug = iaa.BlendAlphaSegMapClassIds(
  1729. >>> [1, 3],
  1730. >>> foreground=iaa.AddToHue((-100, 100)))
  1731. Create an augmenter that randomizes the hue wherever the segmentation maps
  1732. contain the classes ``1`` or ``3``.
  1733. >>> aug = iaa.BlendAlphaSegMapClassIds(
  1734. >>> [1, 2, 3, 4],
  1735. >>> nb_sample_classes=2,
  1736. >>> foreground=iaa.GaussianBlur(3.0))
  1737. Create an augmenter that randomly picks ``2`` classes from the
  1738. list ``[1, 2, 3, 4]`` and blurs the image content wherever these classes
  1739. appear in the segmentation map. Note that as the sampling of class ids
  1740. happens *with replacement*, it is not guaranteed to sample two *unique*
  1741. class ids.
  1742. >>> aug = iaa.Sometimes(0.2,
  1743. >>> iaa.BlendAlphaSegMapClassIds(
  1744. >>> 2,
  1745. >>> background=iaa.TotalDropout(1.0)))
  1746. Create an augmenter that zeros for roughly every fifth image all
  1747. image pixels that do *not* belong to class id ``2`` (note that the
  1748. `background` branch was used, not the `foreground` branch).
  1749. Example use case: Human body landmark detection where both the
  1750. landmarks/keypoints and the body segmentation map are known. Train the
  1751. model to detect landmarks and sometimes remove all non-body information
  1752. to force the model to become more independent of the background.
  1753. """
  1754. # Added in 0.4.0.
  1755. def __init__(self,
  1756. class_ids,
  1757. foreground=None, background=None,
  1758. nb_sample_classes=None,
  1759. seed=None, name=None,
  1760. random_state="deprecated", deterministic="deprecated"):
  1761. super(BlendAlphaSegMapClassIds, self).__init__(
  1762. SegMapClassIdsMaskGen(
  1763. class_ids=class_ids,
  1764. nb_sample_classes=nb_sample_classes
  1765. ),
  1766. foreground=foreground,
  1767. background=background,
  1768. seed=seed, name=name,
  1769. random_state=random_state, deterministic=deterministic)
  1770. class BlendAlphaBoundingBoxes(BlendAlphaMask):
  1771. """Blend images from two branches based on areas enclosed in bounding boxes.
  1772. This class generates masks that are ``1.0`` within bounding boxes of given
  1773. labels. A mask pixel will be set to ``1.0`` if *at least* one bounding box
  1774. covers the area and has one of the requested labels.
  1775. This class is a thin wrapper around
  1776. :class:`~imgaug.augmenters.blend.BlendAlphaMask` together with
  1777. :class:`~imgaug.augmenters.blend.BoundingBoxesMaskGen`.
  1778. .. note::
  1779. Avoid using augmenters as children that affect pixel locations (e.g.
  1780. horizontal flips). See
  1781. :class:`~imgaug.augmenters.blend.BlendAlphaMask` for details.
  1782. .. note::
  1783. This class will produce an ``AssertionError`` if there are no
  1784. bounding boxes in a batch.
  1785. Added in 0.4.0.
  1786. **Supported dtypes**:
  1787. See :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  1788. Parameters
  1789. ----------
  1790. labels : None or str or list of str or imgaug.parameters.StochasticParameter
  1791. See :class:`~imgaug.augmenters.blend.BoundingBoxesMaskGen`.
  1792. foreground : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1793. Augmenter(s) that make up the foreground branch.
  1794. High alpha values will show this branch's results.
  1795. * If ``None``, then the input images will be reused as the output
  1796. of the foreground branch.
  1797. * If ``Augmenter``, then that augmenter will be used as the branch.
  1798. * If iterable of ``Augmenter``, then that iterable will be
  1799. converted into a ``Sequential`` and used as the augmenter.
  1800. background : None or imgaug.augmenters.meta.Augmenter or iterable of imgaug.augmenters.meta.Augmenter, optional
  1801. Augmenter(s) that make up the background branch.
  1802. Low alpha values will show this branch's results.
  1803. * If ``None``, then the input images will be reused as the output
  1804. of the background branch.
  1805. * If ``Augmenter``, then that augmenter will be used as the branch.
  1806. * If iterable of ``Augmenter``, then that iterable will be
  1807. converted into a ``Sequential`` and used as the augmenter.
  1808. nb_sample_labels : None or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  1809. See :class:`~imgaug.augmenters.blend.BoundingBoxesMaskGen`.
  1810. seed : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1811. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1812. name : None or str, optional
  1813. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1814. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1815. Old name for parameter `seed`.
  1816. Its usage will not yet cause a deprecation warning,
  1817. but it is still recommended to use `seed` now.
  1818. Outdated since 0.4.0.
  1819. deterministic : bool, optional
  1820. Deprecated since 0.4.0.
  1821. See method ``to_deterministic()`` for an alternative and for
  1822. details about what the "deterministic mode" actually does.
  1823. Examples
  1824. --------
  1825. >>> import imgaug.augmenters as iaa
  1826. >>> aug = iaa.BlendAlphaBoundingBoxes("person",
  1827. >>> foreground=iaa.Grayscale(1.0))
  1828. Create an augmenter that removes color within bounding boxes having the
  1829. label ``person``.
  1830. >>> aug = iaa.BlendAlphaBoundingBoxes(["person", "car"],
  1831. >>> foreground=iaa.AddToHue((-255, 255)))
  1832. Create an augmenter that randomizes the hue within bounding boxes that
  1833. have the label ``person`` or ``car``.
  1834. >>> aug = iaa.BlendAlphaBoundingBoxes(["person", "car"],
  1835. >>> foreground=iaa.AddToHue((-255, 255)),
  1836. >>> nb_sample_labels=1)
  1837. Create an augmenter that randomizes the hue within bounding boxes that
  1838. have either the label ``person`` or ``car``. Only one label is picked per
  1839. image. Note that the sampling happens with replacement, so if
  1840. ``nb_sample_classes`` would be ``>1``, it could still lead to only one
  1841. *unique* label being sampled.
  1842. >>> aug = iaa.BlendAlphaBoundingBoxes(None,
  1843. >>> background=iaa.Multiply(0.0))
  1844. Create an augmenter that zeros all pixels (``Multiply(0.0)``)
  1845. that are *not* (``background`` branch) within bounding boxes of
  1846. *any* (``None``) label. In other words, all pixels outside of bounding
  1847. boxes become black.
  1848. Note that we don't use ``TotalDropout`` here, because by default it will
  1849. also remove all coordinate-based augmentables, which will break the
  1850. blending of such inputs.
  1851. """
  1852. # Added in 0.4.0.
  1853. def __init__(self,
  1854. labels,
  1855. foreground=None, background=None,
  1856. nb_sample_labels=None,
  1857. seed=None, name=None,
  1858. random_state="deprecated", deterministic="deprecated"):
  1859. super(BlendAlphaBoundingBoxes, self).__init__(
  1860. BoundingBoxesMaskGen(
  1861. labels=labels,
  1862. nb_sample_labels=nb_sample_labels
  1863. ),
  1864. foreground=foreground,
  1865. background=background,
  1866. seed=seed, name=name,
  1867. random_state=random_state, deterministic=deterministic)
  1868. @six.add_metaclass(ABCMeta)
  1869. class IBatchwiseMaskGenerator(object):
  1870. """Interface for classes generating masks for batches.
  1871. Child classes are supposed to receive a batch and generate an iterable
  1872. of masks, one per row (i.e. image), matching the row shape (i.e. image
  1873. shape). This is used in :class:`~imgaug.augmenters.blend.BlendAlphaMask`.
  1874. Added in 0.4.0.
  1875. """
  1876. # Added in 0.4.0.
  1877. def draw_masks(self, batch, random_state=None):
  1878. """Generate a mask with given shape.
  1879. Parameters
  1880. ----------
  1881. batch : imgaug.augmentables.batches._BatchInAugmentation
  1882. Shape of the mask to sample.
  1883. random_state : None or int or imgaug.random.RNG or numpy.random.Generator or numpy.random.BitGenerator or numpy.random.SeedSequence or numpy.random.RandomState, optional
  1884. A seed or random number generator to use during the sampling
  1885. process. If ``None``, the global RNG will be used.
  1886. See also :func:`~imgaug.augmenters.meta.Augmenter.__init__`
  1887. for a similar parameter with more details.
  1888. Returns
  1889. -------
  1890. iterable of ndarray
  1891. Masks, one per row in the batch.
  1892. Each mask must be a ``float32`` array in interval ``[0.0, 1.0]``.
  1893. It must either have the same shape as the row (i.e. the image)
  1894. or shape ``(H, W)`` if all channels are supposed to have the
  1895. same mask.
  1896. """
  1897. class StochasticParameterMaskGen(IBatchwiseMaskGenerator):
  1898. """Mask generator that queries stochastic parameters for mask values.
  1899. This class receives batches for which to generate masks, iterates over
  1900. the batch rows (i.e. images) and generates one mask per row.
  1901. For a row with shape ``(H, W, C)`` (= image shape), it generates
  1902. either a ``(H, W)`` mask (if ``per_channel`` is false-like) or a
  1903. ``(H, W, C)`` mask (if ``per_channel`` is true-like).
  1904. The ``per_channel`` is sampled per batch for each row/image.
  1905. Added in 0.4.0.
  1906. Parameters
  1907. ----------
  1908. parameter : imgaug.parameters.StochasticParameter
  1909. Stochastic parameter to draw mask samples from.
  1910. Expected to return values in interval ``[0.0, 1.0]`` (not all
  1911. stochastic parameters do that) and must be able to handle sampling
  1912. shapes ``(H, W)`` and ``(H, W, C)`` (all stochastic parameters should
  1913. do that).
  1914. per_channel : bool or float or imgaug.parameters.StochasticParameter, optional
  1915. Whether to use the same mask for all channels (``False``)
  1916. or to sample a new mask for each channel (``True``).
  1917. If this value is a float ``p``, then for ``p`` percent of all rows
  1918. (i.e. images) `per_channel` will be treated as ``True``, otherwise
  1919. as ``False``.
  1920. """
  1921. # Added in 0.4.0.
  1922. def __init__(self, parameter, per_channel):
  1923. super(StochasticParameterMaskGen, self).__init__()
  1924. self.parameter = parameter
  1925. self.per_channel = iap.handle_probability_param(per_channel,
  1926. "per_channel")
  1927. # Added in 0.4.0.
  1928. def draw_masks(self, batch, random_state=None):
  1929. """
  1930. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  1931. """
  1932. shapes = batch.get_rowwise_shapes()
  1933. random_state = iarandom.RNG(random_state)
  1934. per_channel = self.per_channel.draw_samples((len(shapes),),
  1935. random_state=random_state)
  1936. return [self._draw_mask(shape, random_state, per_channel_i)
  1937. for shape, per_channel_i
  1938. in zip(shapes, per_channel)]
  1939. # Added in 0.4.0.
  1940. def _draw_mask(self, shape, random_state, per_channel):
  1941. if len(shape) == 2 or per_channel >= 0.5:
  1942. mask = self.parameter.draw_samples(shape,
  1943. random_state=random_state)
  1944. else:
  1945. # TODO When this was wrongly sampled directly as (H,W,C) no
  1946. # test for AlphaElementwise ended up failing. That should not
  1947. # happen.
  1948. # We are guarantueed here to have (H, W, C) as shape (H, W) is
  1949. # handled by the above block.
  1950. # As the mask is not channelwise, we will just return (H, W)
  1951. # instead of (H, W, C).
  1952. mask = self.parameter.draw_samples(shape[0:2],
  1953. random_state=random_state)
  1954. # mask has no elements if height or width in shape is 0
  1955. if mask.size > 0:
  1956. assert 0 <= mask.item(0) <= 1.0, (
  1957. "Expected 'parameter' samples to be in the interval "
  1958. "[0.0, 1.0]. Got min %.4f and max %.4f." % (
  1959. np.min(mask), np.max(mask),))
  1960. return mask
  1961. class SomeColorsMaskGen(IBatchwiseMaskGenerator):
  1962. """Generator that produces masks based on some similar colors in images.
  1963. This class receives batches for which to generate masks, iterates over
  1964. the batch rows (i.e. images) and generates one mask per row.
  1965. The mask contains high alpha values for some colors, while other colors
  1966. get low mask values. Which colors are chosen is random. How wide or
  1967. narrow the selection is (e.g. very specific blue tone or all blue-ish
  1968. colors) is determined by the hyperparameters.
  1969. The color selection method performs roughly the following steps:
  1970. 1. Split the full color range of the hue in ``HSV`` into ``nb_bins``
  1971. bins (i.e. ``256/nb_bins`` different possible hue tones).
  1972. 2. Shift the bins by ``rotation_deg`` degrees. (This way, the ``0th``
  1973. bin does not always start at exactly ``0deg`` of hue.)
  1974. 3. Sample ``alpha`` values for each bin.
  1975. 4. Repeat the ``nb_bins`` bins until there are ``256`` bins.
  1976. 5. Smoothen the alpha values of neighbouring bins using a gaussian
  1977. kernel. The kernel's ``sigma`` is derived from ``smoothness``.
  1978. 6. Associate all hue values in the image with the corresponding bin's
  1979. alpha value. This results in the alpha mask.
  1980. .. note::
  1981. This mask generator will produce an ``AssertionError`` for batches
  1982. that contain no images.
  1983. Added in 0.4.0.
  1984. **Supported dtypes**:
  1985. See :func:`~imgaug.augmenters.color.change_colorspaces_`.
  1986. Parameters
  1987. ----------
  1988. nb_bins : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  1989. Number of bins. For ``B`` bins, each bin denotes roughly ``360/B``
  1990. degrees of colors in the hue channel. Lower values lead to a coarser
  1991. selection of colors. Expected value range is ``[2, 256]``.
  1992. * If ``int``: Exactly that value will be used for all images.
  1993. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  1994. per image from the discrete interval ``[a..b]``.
  1995. * If ``list``: A random value will be picked per image from that
  1996. list.
  1997. * If ``StochasticParameter``: That parameter will be queried once
  1998. per batch for ``(N,)`` values -- one per image.
  1999. smoothness : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2000. Strength of the 1D gaussian kernel applied to the sampled binwise
  2001. alpha values. Larger values will lead to more similar grayscaling of
  2002. neighbouring colors. Expected value range is ``[0.0, 1.0]``.
  2003. * If ``number``: Exactly that value will be used for all images.
  2004. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2005. per image from the interval ``[a, b]``.
  2006. * If ``list``: A random value will be picked per image from that
  2007. list.
  2008. * If ``StochasticParameter``: That parameter will be queried once
  2009. per batch for ``(N,)`` values -- one per image.
  2010. alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2011. Parameter to sample binwise alpha blending factors from. Expected
  2012. value range is ``[0.0, 1.0]``. Note that the alpha values will be
  2013. smoothed between neighbouring bins. Hence, it is usually a good idea
  2014. to set this so that the probability distribution peaks are around
  2015. ``0.0`` and ``1.0``, e.g. via a list ``[0.0, 1.0]`` or a ``Beta``
  2016. distribution.
  2017. It is not recommended to set this to a deterministic value, otherwise
  2018. all bins and hence all pixels in the generated mask will have the
  2019. same value.
  2020. * If ``number``: Exactly that value will be used for all bins.
  2021. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2022. per bin from the interval ``[a, b]``.
  2023. * If ``list``: A random value will be picked per bin from that list.
  2024. * If ``StochasticParameter``: That parameter will be queried once
  2025. per batch for ``(N*B,)`` values -- one per image and bin.
  2026. rotation_deg : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2027. Rotiational shift of each bin as a fraction of ``360`` degrees.
  2028. E.g. ``0.0`` will not shift any bins, while a value of ``0.5`` will
  2029. shift by around ``180`` degrees. This shift is mainly used so that
  2030. the ``0th`` bin does not always start at ``0deg``. Expected value
  2031. range is ``[-360, 360]``. This parameter can usually be kept at the
  2032. default value.
  2033. * If ``number``: Exactly that value will be used for all images.
  2034. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2035. per image from the interval ``[a, b]``.
  2036. * If ``list``: A random value will be picked per image from that
  2037. list.
  2038. * If ``StochasticParameter``: That parameter will be queried once
  2039. per batch for ``(N,)`` values -- one per image.
  2040. from_colorspace : str, optional
  2041. The source colorspace (of the input images).
  2042. See :func:`~imgaug.augmenters.color.change_colorspace_`.
  2043. """
  2044. # Added in 0.4.0.
  2045. # TODO colorlib.CSPACE_RGB produces 'has no attribute' error?
  2046. def __init__(self, nb_bins=(5, 15), smoothness=(0.1, 0.3),
  2047. alpha=[0.0, 1.0], rotation_deg=(0, 360),
  2048. from_colorspace="RGB"):
  2049. # pylint: disable=dangerous-default-value
  2050. super(SomeColorsMaskGen, self).__init__()
  2051. self.nb_bins = iap.handle_discrete_param(
  2052. nb_bins, "nb_bins", value_range=(1, 256),
  2053. tuple_to_uniform=True, list_to_choice=True)
  2054. self.smoothness = iap.handle_continuous_param(
  2055. smoothness, "smoothness", value_range=(0.0, 1.0),
  2056. tuple_to_uniform=True, list_to_choice=True)
  2057. self.alpha = iap.handle_continuous_param(
  2058. alpha, "alpha", value_range=(0.0, 1.0),
  2059. tuple_to_uniform=True, list_to_choice=True)
  2060. self.rotation_deg = iap.handle_continuous_param(
  2061. rotation_deg, "rotation_deg", value_range=(-360, 360),
  2062. tuple_to_uniform=True, list_to_choice=True)
  2063. self.from_colorspace = from_colorspace
  2064. self.sigma_max = 10.0
  2065. # Added in 0.4.0.
  2066. def draw_masks(self, batch, random_state=None):
  2067. """
  2068. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  2069. """
  2070. assert batch.images is not None, (
  2071. "Can only generate masks for batches that contain images, but "
  2072. "got a batch without images.")
  2073. random_state = iarandom.RNG(random_state)
  2074. samples = self._draw_samples(batch, random_state=random_state)
  2075. return [self._draw_mask(image, i, samples)
  2076. for i, image
  2077. in enumerate(batch.images)]
  2078. # Added in 0.4.0.
  2079. def _draw_mask(self, image, image_idx, samples):
  2080. return self.generate_mask(
  2081. image,
  2082. samples[0][image_idx],
  2083. samples[1][image_idx] * self.sigma_max,
  2084. samples[2][image_idx],
  2085. self.from_colorspace)
  2086. # Added in 0.4.0.
  2087. def _draw_samples(self, batch, random_state):
  2088. nb_rows = batch.nb_rows
  2089. nb_bins = self.nb_bins.draw_samples((nb_rows,),
  2090. random_state=random_state)
  2091. smoothness = self.smoothness.draw_samples((nb_rows,),
  2092. random_state=random_state)
  2093. alpha = self.alpha.draw_samples((np.sum(nb_bins),),
  2094. random_state=random_state)
  2095. rotation_deg = self.rotation_deg.draw_samples(
  2096. (nb_rows,), random_state=random_state)
  2097. nb_bins = np.clip(nb_bins, 1, 256)
  2098. smoothness = np.clip(smoothness, 0.0, 1.0)
  2099. alpha = np.clip(alpha, 0.0, 1.0)
  2100. rotation_bins = np.mod(
  2101. np.round(rotation_deg * (256/360)).astype(np.int32),
  2102. 256)
  2103. binwise_alphas = _split_1d_array_to_list(alpha, nb_bins)
  2104. return binwise_alphas, smoothness, rotation_bins
  2105. @classmethod
  2106. def generate_mask(cls, image, binwise_alphas, sigma,
  2107. rotation_bins, from_colorspace):
  2108. """Generate a colorwise alpha mask for a single image.
  2109. Added in 0.4.0.
  2110. Parameters
  2111. ----------
  2112. image : ndarray
  2113. Image for which to generate the mask. Must have shape ``(H,W,3)``
  2114. in colorspace `from_colorspace`.
  2115. binwise_alphas : ndarray
  2116. Alpha values of shape ``(B,)`` with ``B`` in ``[1, 256]``
  2117. and values in interval ``[0.0, 1.0]``. Will be upscaled to
  2118. 256 bins by simple repetition. Each bin represents ``1/256`` th
  2119. of the hue.
  2120. sigma : float
  2121. Sigma of the 1D gaussian kernel applied to the upscaled binwise
  2122. alpha value array.
  2123. rotation_bins : int
  2124. By how much to rotate the 256 bin alpha array. The rotation is
  2125. given in number of bins.
  2126. from_colorspace : str
  2127. Colorspace of the input image. One of
  2128. ``imgaug.augmenters.color.CSPACE_*``.
  2129. Returns
  2130. -------
  2131. ndarray
  2132. ``float32`` mask array of shape ``(H, W)`` with values in
  2133. ``[0.0, 1.0]``
  2134. """
  2135. # import has to be deferred, otherwise python 2.7 fails
  2136. from . import color as colorlib
  2137. image_hsv = colorlib.change_colorspace_(
  2138. np.copy(image),
  2139. to_colorspace=colorlib.CSPACE_HSV,
  2140. from_colorspace=from_colorspace)
  2141. if 0 in image_hsv.shape[0:2]:
  2142. return np.zeros(image_hsv.shape[0:2], dtype=np.float32)
  2143. binwise_alphas = cls._upscale_to_256_alpha_bins(binwise_alphas)
  2144. binwise_alphas = cls._rotate_alpha_bins(binwise_alphas, rotation_bins)
  2145. binwise_alphas_smooth = cls._smoothen_alphas(binwise_alphas, sigma)
  2146. mask = cls._generate_pixelwise_alpha_mask(image_hsv,
  2147. binwise_alphas_smooth)
  2148. return mask
  2149. # Added in 0.4.0.
  2150. @classmethod
  2151. def _upscale_to_256_alpha_bins(cls, alphas):
  2152. # repeat alphas bins so that B sampled bins become 256 bins
  2153. nb_bins = len(alphas)
  2154. nb_repeats_per_bin = int(np.ceil(256/nb_bins))
  2155. alphas = np.repeat(alphas, (nb_repeats_per_bin,))
  2156. alphas = alphas[0:256]
  2157. return alphas
  2158. # Added in 0.4.0.
  2159. @classmethod
  2160. def _rotate_alpha_bins(cls, alphas, rotation_bins):
  2161. # e.g. for offset 2: abcdef -> cdefab
  2162. # note: offset here is expected to be in [0, 256]
  2163. if rotation_bins > 0:
  2164. alphas = np.roll(alphas, -rotation_bins)
  2165. return alphas
  2166. # Added in 0.4.0.
  2167. @classmethod
  2168. def _smoothen_alphas(cls, alphas, sigma):
  2169. if sigma <= 0.0+1e-2:
  2170. return alphas
  2171. ksize = max(int(sigma * 2.5), 3)
  2172. ksize_y, ksize_x = (1, ksize)
  2173. if ksize_x % 2 == 0:
  2174. ksize_x += 1
  2175. # we fake here cv2.BORDER_WRAP, because GaussianBlur does not
  2176. # support that mode, i.e. we want:
  2177. # cdefgh|abcdefgh|abcdefg
  2178. alphas = np.concatenate([
  2179. alphas[-ksize_x:],
  2180. alphas,
  2181. alphas[:ksize_x],
  2182. ])
  2183. alphas = cv2.GaussianBlur(
  2184. _normalize_cv2_input_arr_(alphas[np.newaxis, :]),
  2185. ksize=(ksize_x, ksize_y),
  2186. sigmaX=sigma, sigmaY=sigma,
  2187. borderType=cv2.BORDER_REPLICATE
  2188. )[0, :]
  2189. # revert fake BORDER_WRAP
  2190. alphas = alphas[ksize_x:-ksize_x]
  2191. return alphas
  2192. # Added in 0.4.0.
  2193. @classmethod
  2194. def _generate_pixelwise_alpha_mask(cls, image_hsv, hue_to_alpha):
  2195. hue = image_hsv[:, :, 0]
  2196. table = hue_to_alpha * 255
  2197. table = np.clip(np.round(table), 0, 255).astype(np.uint8)
  2198. mask = ia.apply_lut(hue, table)
  2199. return mask.astype(np.float32) / 255.0
  2200. # Added in 0.4.0.
  2201. class _LinearGradientMaskGen(IBatchwiseMaskGenerator):
  2202. # Added in 0.4.0.
  2203. def __init__(self, axis, min_value=0.0, max_value=1.0,
  2204. start_at=0.0, end_at=1.0):
  2205. self.axis = axis
  2206. self.min_value = iap.handle_continuous_param(
  2207. min_value, "min_value", value_range=(0.0, 1.0),
  2208. tuple_to_uniform=True, list_to_choice=True)
  2209. self.max_value = iap.handle_continuous_param(
  2210. max_value, "max_value", value_range=(0.0, 1.0),
  2211. tuple_to_uniform=True, list_to_choice=True)
  2212. self.start_at = iap.handle_continuous_param(
  2213. start_at, "start_at", value_range=(0.0, 1.0),
  2214. tuple_to_uniform=True, list_to_choice=True)
  2215. self.end_at = iap.handle_continuous_param(
  2216. end_at, "end_at", value_range=(0.0, 1.0),
  2217. tuple_to_uniform=True, list_to_choice=True)
  2218. def draw_masks(self, batch, random_state=None):
  2219. """
  2220. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  2221. Added in 0.4.0.
  2222. """
  2223. random_state = iarandom.RNG(random_state)
  2224. shapes = batch.get_rowwise_shapes()
  2225. samples = self._draw_samples(len(shapes), random_state=random_state)
  2226. return [self._draw_mask(shape, i, samples)
  2227. for i, shape
  2228. in enumerate(shapes)]
  2229. # Added in 0.4.0.
  2230. def _draw_mask(self, shape, image_idx, samples):
  2231. return self.generate_mask(
  2232. shape,
  2233. samples[0][image_idx],
  2234. samples[1][image_idx],
  2235. samples[2][image_idx],
  2236. samples[3][image_idx])
  2237. # Added in 0.4.0.
  2238. def _draw_samples(self, nb_rows, random_state):
  2239. min_value = self.min_value.draw_samples((nb_rows,),
  2240. random_state=random_state)
  2241. max_value = self.max_value.draw_samples((nb_rows,),
  2242. random_state=random_state)
  2243. start_at = self.start_at.draw_samples(
  2244. (nb_rows,), random_state=random_state)
  2245. end_at = self.end_at.draw_samples(
  2246. (nb_rows,), random_state=random_state)
  2247. return min_value, max_value, start_at, end_at
  2248. @classmethod
  2249. @abstractmethod
  2250. def generate_mask(cls, shape, min_value, max_value, start_at, end_at):
  2251. """Generate a horizontal gradient mask.
  2252. Added in 0.4.0.
  2253. Parameters
  2254. ----------
  2255. shape : tuple of int
  2256. Shape of the image. The mask will have the same height and
  2257. width.
  2258. min_value : number
  2259. Minimum value of the gradient in interval ``[0.0, 1.0]``.
  2260. max_value : number
  2261. Maximum value of the gradient in interval ``[0.0, 1.0]``.
  2262. start_at : number
  2263. Position on the x-axis where the linear gradient starts, given as
  2264. a fraction of the axis size. Interval is ``[0.0, 1.0]``.
  2265. end_at : number
  2266. Position on the x-axis where the linear gradient ends, given as
  2267. a fraction of the axis size. Interval is ``[0.0, 1.0]``.
  2268. Returns
  2269. -------
  2270. ndarray
  2271. ``float32`` mask array with same height and width as the image.
  2272. Values are in ``[0.0, 1.0]``.
  2273. """
  2274. # Added in 0.4.0.
  2275. @classmethod
  2276. def _generate_mask(cls, shape, axis, min_value, max_value, start_at,
  2277. end_at):
  2278. height, width = shape[0:2]
  2279. axis_size = shape[axis]
  2280. min_value = min(max(min_value, 0.0), 1.0)
  2281. max_value = min(max(max_value, 0.0), 1.0)
  2282. start_at_px = min(max(int(start_at * axis_size), 0), axis_size)
  2283. end_at_px = min(max(int(end_at * axis_size), 0), axis_size)
  2284. inverted = False
  2285. if end_at_px < start_at_px:
  2286. inverted = True
  2287. start_at_px, end_at_px = end_at_px, start_at_px
  2288. before_grad = np.full((start_at_px,), min_value,
  2289. dtype=np.float32)
  2290. grad = np.linspace(start=min_value,
  2291. stop=max_value,
  2292. num=end_at_px - start_at_px,
  2293. dtype=np.float32)
  2294. after_grad = np.full((axis_size - end_at_px,), max_value,
  2295. dtype=np.float32)
  2296. mask = np.concatenate((
  2297. before_grad,
  2298. grad,
  2299. after_grad
  2300. ), axis=0)
  2301. if inverted:
  2302. mask = 1.0 - mask
  2303. if axis == 0:
  2304. mask = mask[:, np.newaxis]
  2305. mask = np.tile(mask, (1, width))
  2306. else:
  2307. mask = mask[np.newaxis, :]
  2308. mask = np.tile(mask, (height, 1))
  2309. return mask
  2310. class HorizontalLinearGradientMaskGen(_LinearGradientMaskGen):
  2311. """Generator that produces horizontal linear gradient masks.
  2312. This class receives batches and produces for each row (i.e. image)
  2313. a horizontal linear gradient that matches the row's shape (i.e. image
  2314. shape). The gradient increases linearly from a minimum value to a
  2315. maximum value along the x-axis. The start and end points (i.e. where the
  2316. minimum value starts to increase and where it reaches the maximum)
  2317. may be defines as fractions of the width. E.g. for width ``100`` and
  2318. ``start=0.25``, ``end=0.75``, the gradient would have its minimum
  2319. in interval ``[0px, 25px]`` and its maximum in interval ``[75px, 100px]``.
  2320. Note that this has nothing to do with a *derivative* along the x-axis.
  2321. Added in 0.4.0.
  2322. Parameters
  2323. ----------
  2324. min_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2325. Minimum value that the mask will have up to the start point of the
  2326. linear gradient.
  2327. Note that `min_value` is allowed to be larger than `max_value`,
  2328. in which case the gradient will start at the (higher) `min_value`
  2329. and decrease towards the (lower) `max_value`.
  2330. * If ``number``: Exactly that value will be used for all images.
  2331. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2332. per image from the interval ``[a, b]``.
  2333. * If ``list``: A random value will be picked per image from that list.
  2334. * If ``StochasticParameter``: That parameter will be queried once
  2335. per batch for ``(N,)`` values -- one per image.
  2336. max_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2337. Maximum value that the mask will have at the end of the
  2338. linear gradient.
  2339. Datatypes are analogous to `min_value`.
  2340. start_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2341. Position on the x-axis where the linear gradient starts, given as a
  2342. fraction of the axis size. Interval is ``[0.0, 1.0]``, where ``0.0``
  2343. is at the left of the image.
  2344. If ``end_at < start_at`` the gradient will be inverted.
  2345. Datatypes are analogous to `min_value`.
  2346. end_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2347. Position on the x-axis where the linear gradient ends, given as a
  2348. fraction of the axis size. Interval is ``[0.0, 1.0]``, where ``0.0``
  2349. is at the right of the image.
  2350. Datatypes are analogous to `min_value`.
  2351. """
  2352. # Added in 0.4.0.
  2353. def __init__(self, min_value=(0.0, 0.2), max_value=(0.8, 1.0),
  2354. start_at=(0.0, 0.2), end_at=(0.8, 1.0)):
  2355. super(HorizontalLinearGradientMaskGen, self).__init__(
  2356. axis=1,
  2357. min_value=min_value,
  2358. max_value=max_value,
  2359. start_at=start_at,
  2360. end_at=end_at)
  2361. @classmethod
  2362. def generate_mask(cls, shape, min_value, max_value, start_at, end_at):
  2363. """Generate a linear horizontal gradient mask.
  2364. Added in 0.4.0.
  2365. Parameters
  2366. ----------
  2367. shape : tuple of int
  2368. Shape of the image. The mask will have the same height and
  2369. width.
  2370. min_value : number
  2371. Minimum value of the gradient in interval ``[0.0, 1.0]``.
  2372. max_value : number
  2373. Maximum value of the gradient in interval ``[0.0, 1.0]``.
  2374. start_at : number
  2375. Position on the x-axis where the linear gradient starts, given as
  2376. a fraction of the axis size. Interval is ``[0.0, 1.0]``.
  2377. end_at : number
  2378. Position on the x-axis where the linear gradient ends, given as
  2379. a fraction of the axis size. Interval is ``[0.0, 1.0]``.
  2380. Returns
  2381. -------
  2382. ndarray
  2383. ``float32`` mask array with same height and width as the image.
  2384. Values are in ``[0.0, 1.0]``.
  2385. """
  2386. return cls._generate_mask(
  2387. axis=1,
  2388. shape=shape,
  2389. min_value=min_value,
  2390. max_value=max_value,
  2391. start_at=start_at,
  2392. end_at=end_at)
  2393. class VerticalLinearGradientMaskGen(_LinearGradientMaskGen):
  2394. """Generator that produces vertical linear gradient masks.
  2395. See :class:`~imgaug.augmenters.blend.HorizontalLinearGradientMaskGen`
  2396. for details.
  2397. Added in 0.4.0.
  2398. Parameters
  2399. ----------
  2400. min_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2401. Minimum value that the mask will have up to the start point of the
  2402. linear gradient.
  2403. Note that `min_value` is allowed to be larger than `max_value`,
  2404. in which case the gradient will start at the (higher) `min_value`
  2405. and decrease towards the (lower) `max_value`.
  2406. * If ``number``: Exactly that value will be used for all images.
  2407. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2408. per image from the interval ``[a, b]``.
  2409. * If ``list``: A random value will be picked per image from that list.
  2410. * If ``StochasticParameter``: That parameter will be queried once
  2411. per batch for ``(N,)`` values -- one per image.
  2412. max_value : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2413. Maximum value that the mask will have at the end of the
  2414. linear gradient.
  2415. Datatypes are analogous to `min_value`.
  2416. start_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2417. Position on the y-axis where the linear gradient starts, given as a
  2418. fraction of the axis size. Interval is ``[0.0, 1.0]``, where ``0.0``
  2419. is at the top of the image.
  2420. If ``end_at < start_at`` the gradient will be inverted.
  2421. Datatypes are analogous to `min_value`.
  2422. end_at : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2423. Position on the x-axis where the linear gradient ends, given as a
  2424. fraction of the axis size. Interval is ``[0.0, 1.0]``, where ``1.0``
  2425. is at the bottom of the image.
  2426. Datatypes are analogous to `min_value`.
  2427. """
  2428. # Added in 0.4.0.
  2429. def __init__(self, min_value=(0.0, 0.2), max_value=(0.8, 1.0),
  2430. start_at=(0.0, 0.2), end_at=(0.8, 1.0)):
  2431. super(VerticalLinearGradientMaskGen, self).__init__(
  2432. axis=0,
  2433. min_value=min_value,
  2434. max_value=max_value,
  2435. start_at=start_at,
  2436. end_at=end_at)
  2437. @classmethod
  2438. def generate_mask(cls, shape, min_value, max_value, start_at, end_at):
  2439. """Generate a linear horizontal gradient mask.
  2440. Added in 0.4.0.
  2441. Parameters
  2442. ----------
  2443. shape : tuple of int
  2444. Shape of the image. The mask will have the same height and
  2445. width.
  2446. min_value : number
  2447. Minimum value of the gradient in interval ``[0.0, 1.0]``.
  2448. max_value : number
  2449. Maximum value of the gradient in interval ``[0.0, 1.0]``.
  2450. start_at : number
  2451. Position on the x-axis where the linear gradient starts, given as
  2452. a fraction of the axis size. Interval is ``[0.0, 1.0]``.
  2453. end_at : number
  2454. Position on the x-axis where the linear gradient ends, given as
  2455. a fraction of the axis size. Interval is ``[0.0, 1.0]``.
  2456. Returns
  2457. -------
  2458. ndarray
  2459. ``float32`` mask array with same height and width as the image.
  2460. Values are in ``[0.0, 1.0]``.
  2461. """
  2462. return cls._generate_mask(
  2463. axis=0,
  2464. shape=shape,
  2465. min_value=min_value,
  2466. max_value=max_value,
  2467. start_at=start_at,
  2468. end_at=end_at)
  2469. class RegularGridMaskGen(IBatchwiseMaskGenerator):
  2470. """Generate masks following a regular grid pattern.
  2471. This mask generator splits each image into a grid-like pattern of
  2472. ``H`` rows and ``W`` columns. Each cell is then filled with an alpha
  2473. value, sampled randomly per cell.
  2474. The difference to :class:`CheckerboardMaskGen` is that this mask generator
  2475. samples random alpha values per cell, while in the checkerboard the
  2476. alpha values follow a fixed pattern.
  2477. Added in 0.4.0.
  2478. Parameters
  2479. ----------
  2480. nb_rows : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  2481. Number of rows of the regular grid.
  2482. * If ``int``: Exactly that value will be used for all images.
  2483. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2484. per image from the discrete interval ``[a..b]``.
  2485. * If ``list``: A random value will be picked per image from that
  2486. list.
  2487. * If ``StochasticParameter``: That parameter will be queried once
  2488. per batch for ``(N,)`` values -- one per image.
  2489. nb_cols : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  2490. Number of columns of the checkerboard. Analogous to `nb_rows`.
  2491. alpha : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  2492. Alpha value of each cell.
  2493. * If ``number``: Exactly that value will be used for all images.
  2494. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2495. per image from the interval ``[a, b]``.
  2496. * If ``list``: A random value will be picked per image from that list.
  2497. * If ``StochasticParameter``: That parameter will be queried once
  2498. per batch for ``(N,)`` values -- one per image.
  2499. """
  2500. # Added in 0.4.0.
  2501. def __init__(self, nb_rows, nb_cols, alpha=[0.0, 1.0]):
  2502. # pylint: disable=dangerous-default-value
  2503. self.nb_rows = iap.handle_discrete_param(
  2504. nb_rows, "nb_rows", value_range=(1, None),
  2505. tuple_to_uniform=True, list_to_choice=True,
  2506. allow_floats=False)
  2507. self.nb_cols = iap.handle_discrete_param(
  2508. nb_cols, "nb_cols", value_range=(1, None),
  2509. tuple_to_uniform=True, list_to_choice=True,
  2510. allow_floats=False)
  2511. self.alpha = iap.handle_continuous_param(
  2512. alpha, "alpha", value_range=(0.0, 1.0),
  2513. tuple_to_uniform=True, list_to_choice=True)
  2514. def draw_masks(self, batch, random_state=None):
  2515. """
  2516. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  2517. Added in 0.4.0.
  2518. """
  2519. random_state = iarandom.RNG(random_state)
  2520. shapes = batch.get_rowwise_shapes()
  2521. nb_rows, nb_cols, alpha = self._draw_samples(len(shapes),
  2522. random_state=random_state)
  2523. return [self.generate_mask(shape, nb_rows_i, nb_cols_i, alpha_i)
  2524. for shape, nb_rows_i, nb_cols_i, alpha_i
  2525. in zip(shapes, nb_rows, nb_cols, alpha)]
  2526. # Added in 0.4.0.
  2527. def _draw_samples(self, nb_images, random_state):
  2528. nb_rows = self.nb_rows.draw_samples((nb_images,),
  2529. random_state=random_state)
  2530. nb_cols = self.nb_cols.draw_samples((nb_images,),
  2531. random_state=random_state)
  2532. nb_alphas_per_img = nb_rows * nb_cols
  2533. alpha_raw = self.alpha.draw_samples(
  2534. (np.sum(nb_alphas_per_img),),
  2535. random_state=random_state)
  2536. alpha = _split_1d_array_to_list(alpha_raw, nb_alphas_per_img)
  2537. return nb_rows, nb_cols, alpha
  2538. @classmethod
  2539. def generate_mask(cls, shape, nb_rows, nb_cols, alphas):
  2540. """Generate a mask following a checkerboard pattern.
  2541. Added in 0.4.0.
  2542. Parameters
  2543. ----------
  2544. shape : tuple of int
  2545. Height and width of the output mask.
  2546. nb_rows : int
  2547. Number of rows of the checkerboard pattern.
  2548. nb_cols : int
  2549. Number of columns of the checkerboard pattern.
  2550. alphas : ndarray
  2551. 1D or 2D array containing for each cell the alpha value, i.e.
  2552. ``nb_rows*nb_cols`` values.
  2553. Returns
  2554. -------
  2555. ndarray
  2556. ``float32`` mask array with same height and width as
  2557. ``segmap.shape``. Values are in ``[0.0, 1.0]``.
  2558. """
  2559. from . import size as sizelib
  2560. height, width = shape[0:2]
  2561. if 0 in (height, width):
  2562. return np.zeros((height, width), dtype=np.float32)
  2563. nb_rows = min(max(nb_rows, 1), height)
  2564. nb_cols = min(max(nb_cols, 1), width)
  2565. cell_height = int(height / nb_rows)
  2566. cell_width = int(width / nb_cols)
  2567. # If there are more alpha values than nb_rows*nb_cols we reduce the
  2568. # number of alpha values.
  2569. alphas = alphas.flat[0:nb_rows*nb_cols]
  2570. assert alphas.size == nb_rows*nb_cols, (
  2571. "Expected `alphas` to not contain less values than "
  2572. "`nb_rows * nb_cols` (both clipped to [1, height] and "
  2573. "[1, width] respectively). Got %d alpha values vs %d expected "
  2574. "values (nb_rows=%d, nb_cols=%d) for requested mask shape %s." % (
  2575. alphas.size, nb_rows * nb_cols, nb_rows, nb_cols,
  2576. (height, width)))
  2577. mask = alphas.astype(np.float32).reshape((nb_rows, nb_cols))
  2578. mask = np.repeat(mask, cell_height, axis=0)
  2579. mask = np.repeat(mask, cell_width, axis=1)
  2580. # if mask is too small, reflection pad it on all sides
  2581. missing_height = height - mask.shape[0]
  2582. missing_width = width - mask.shape[1]
  2583. top = int(np.floor(missing_height / 2))
  2584. bottom = int(np.ceil(missing_height / 2))
  2585. left = int(np.floor(missing_width / 2))
  2586. right = int(np.ceil(missing_width / 2))
  2587. mask = sizelib.pad(mask,
  2588. top=top, right=right, bottom=bottom, left=left,
  2589. mode="reflect")
  2590. return mask
  2591. class CheckerboardMaskGen(IBatchwiseMaskGenerator):
  2592. """Generate masks following a checkerboard-like pattern.
  2593. This mask generator splits each image into a regular grid of
  2594. ``H`` rows and ``W`` columns. Each cell is then filled with either
  2595. ``1.0`` or ``0.0``. The cell at the top-left is always ``1.0``. Its right
  2596. and bottom neighbour cells are ``0.0``. The 4-neighbours of any cell always
  2597. have a value opposite to the cell's value (``0.0`` vs. ``1.0``).
  2598. Added in 0.4.0.
  2599. Parameters
  2600. ----------
  2601. nb_rows : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  2602. Number of rows of the checkerboard.
  2603. * If ``int``: Exactly that value will be used for all images.
  2604. * If ``tuple`` ``(a, b)``: A random value will be uniformly sampled
  2605. per image from the discrete interval ``[a..b]``.
  2606. * If ``list``: A random value will be picked per image from that
  2607. list.
  2608. * If ``StochasticParameter``: That parameter will be queried once
  2609. per batch for ``(N,)`` values -- one per image.
  2610. nb_cols : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  2611. Number of columns of the checkerboard. Analogous to `nb_rows`.
  2612. """
  2613. def __init__(self, nb_rows, nb_cols):
  2614. self.grid = RegularGridMaskGen(nb_rows=nb_rows,
  2615. nb_cols=nb_cols,
  2616. alpha=1)
  2617. @property
  2618. def nb_rows(self):
  2619. """Get the number of rows of the checkerboard grid.
  2620. Added in 0.4.0.
  2621. Returns
  2622. -------
  2623. int
  2624. The number of rows.
  2625. """
  2626. return self.grid.nb_rows
  2627. @property
  2628. def nb_cols(self):
  2629. """Get the number of columns of the checkerboard grid.
  2630. Added in 0.4.0.
  2631. Returns
  2632. -------
  2633. int
  2634. The number of columns.
  2635. """
  2636. return self.grid.nb_cols
  2637. def draw_masks(self, batch, random_state=None):
  2638. """
  2639. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  2640. Added in 0.4.0.
  2641. """
  2642. # pylint: disable=protected-access
  2643. random_state = iarandom.RNG(random_state)
  2644. shapes = batch.get_rowwise_shapes()
  2645. nb_rows, nb_cols, _alpha = self.grid._draw_samples(
  2646. len(shapes), random_state=random_state)
  2647. return [self.generate_mask(shape, nb_rows_i, nb_cols_i)
  2648. for shape, nb_rows_i, nb_cols_i
  2649. in zip(shapes, nb_rows, nb_cols)]
  2650. @classmethod
  2651. def generate_mask(cls, shape, nb_rows, nb_cols):
  2652. """Generate a mask following a checkerboard pattern.
  2653. Added in 0.4.0.
  2654. Parameters
  2655. ----------
  2656. shape : tuple of int
  2657. Height and width of the output mask.
  2658. nb_rows : int
  2659. Number of rows of the checkerboard pattern.
  2660. nb_cols : int
  2661. Number of columns of the checkerboard pattern.
  2662. Returns
  2663. -------
  2664. ndarray
  2665. ``float32`` mask array with same height and width as
  2666. ``segmap.shape``. Values are in ``[0.0, 1.0]``.
  2667. """
  2668. height, width = shape[0:2]
  2669. if 0 in (height, width):
  2670. return np.zeros((height, width), dtype=np.float32)
  2671. nb_rows = min(max(nb_rows, 1), height)
  2672. nb_cols = min(max(nb_cols, 1), width)
  2673. alphas = np.full((nb_cols,), 1.0, dtype=np.float32)
  2674. alphas[::2] = 0.0
  2675. alphas = np.tile(alphas[np.newaxis, :], (nb_rows, 1))
  2676. alphas[::2, :] = 1.0 - alphas[::2, :]
  2677. return RegularGridMaskGen.generate_mask(shape, nb_rows, nb_cols, alphas)
  2678. class SegMapClassIdsMaskGen(IBatchwiseMaskGenerator):
  2679. """Generator that produces masks highlighting segmentation map classes.
  2680. This class produces for each segmentation map in a batch a mask in which
  2681. the locations of a set of provided classes are highlighted (i.e. ``1.0``).
  2682. The classes may be provided as a fixed list of class ids or a stochastic
  2683. parameter from which class ids will be sampled.
  2684. The produced masks are initially of the same height and width as the
  2685. segmentation map arrays and later upscaled to the image height and width.
  2686. .. note::
  2687. Segmentation maps can have multiple channels. If that is the case
  2688. then for each position ``(x, y)`` it is sufficient that any class id
  2689. in any channel matches one of the desired class ids.
  2690. .. note::
  2691. This class will produce an ``AssertionError`` if there are no
  2692. segmentation maps in a batch.
  2693. Added in 0.4.0.
  2694. Parameters
  2695. ----------
  2696. class_ids : int or tuple of int or list of int or imgaug.parameters.StochasticParameter
  2697. Segmentation map classes to mark in the produced mask.
  2698. If `nb_sample_classes` is ``None`` then this is expected to be either
  2699. a single ``int`` (always mark this one class id) or a ``list`` of
  2700. ``int`` s (always mark these class ids).
  2701. If `nb_sample_classes` is set, then this parameter will be treated
  2702. as a stochastic parameter with the following valid types:
  2703. * If ``int``: Exactly that class id will be used for all
  2704. segmentation maps.
  2705. * If ``tuple`` ``(a, b)``: ``N`` random values will be uniformly
  2706. sampled per segmentation map from the discrete interval
  2707. ``[a..b]`` and used as the class ids.
  2708. * If ``list``: ``N`` random values will be picked per segmentation
  2709. map from that list and used as the class ids.
  2710. * If ``StochasticParameter``: That parameter will be queried once
  2711. per batch for ``(sum(N),)`` values.
  2712. ``N`` denotes the number of classes to sample per segmentation
  2713. map (derived from `nb_sample_classes`) and ``sum(N)`` denotes the
  2714. sum of ``N`` s over all segmentation maps.
  2715. nb_sample_classes : None or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  2716. Number of class ids to sample (with replacement) per segmentation map.
  2717. As sampling happens with replacement, fewer *unique* class ids may be
  2718. sampled.
  2719. * If ``None``: `class_ids` is expected to be a fixed value of
  2720. class ids to be used for all segmentation maps.
  2721. * If ``int``: Exactly that many class ids will be sampled for all
  2722. segmentation maps.
  2723. * If ``tuple`` ``(a, b)``: A random value will be uniformly
  2724. sampled per segmentation map from the discrete interval
  2725. ``[a..b]``.
  2726. * If ``list`` or ``int``: A random value will be picked per
  2727. segmentation map from that list.
  2728. * If ``StochasticParameter``: That parameter will be queried once
  2729. per batch for ``(B,)`` values, where ``B`` is the number of
  2730. segmentation maps.
  2731. """
  2732. # Added in 0.4.0.
  2733. def __init__(self, class_ids, nb_sample_classes=None):
  2734. if nb_sample_classes is None:
  2735. if ia.is_single_integer(class_ids):
  2736. class_ids = [class_ids]
  2737. assert isinstance(class_ids, list), (
  2738. "Expected `class_ids` to be a single integer or a list of "
  2739. "integers if `nb_sample_classes` is None. Got type `%s`. "
  2740. "Set `nb_sample_classes` to e.g. an integer to enable "
  2741. "stochastic parameters for `class_ids`." % (
  2742. type(class_ids).__name__,))
  2743. self.class_ids = class_ids
  2744. self.nb_sample_classes = None
  2745. else:
  2746. self.class_ids = iap.handle_discrete_param(
  2747. class_ids, "class_ids", value_range=(0, None),
  2748. tuple_to_uniform=True, list_to_choice=True,
  2749. allow_floats=False)
  2750. self.nb_sample_classes = iap.handle_discrete_param(
  2751. nb_sample_classes, "nb_sample_classes", value_range=(0, None),
  2752. tuple_to_uniform=True, list_to_choice=True,
  2753. allow_floats=False)
  2754. def draw_masks(self, batch, random_state=None):
  2755. """
  2756. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  2757. Added in 0.4.0.
  2758. """
  2759. assert batch.segmentation_maps is not None, (
  2760. "Can only generate masks for batches that contain segmentation "
  2761. "maps, but got a batch without them.")
  2762. random_state = iarandom.RNG(random_state)
  2763. class_ids = self._draw_samples(batch.nb_rows,
  2764. random_state=random_state)
  2765. return [self.generate_mask(segmap, class_ids_i)
  2766. for segmap, class_ids_i
  2767. in zip(batch.segmentation_maps, class_ids)]
  2768. # Added in 0.4.0.
  2769. def _draw_samples(self, nb_rows, random_state):
  2770. nb_sample_classes = self.nb_sample_classes
  2771. if nb_sample_classes is None:
  2772. assert isinstance(self.class_ids, list), (
  2773. "Expected list got %s." % (type(self.class_ids).__name__,))
  2774. return [self.class_ids] * nb_rows
  2775. nb_sample_classes = nb_sample_classes.draw_samples(
  2776. (nb_rows,), random_state=random_state)
  2777. nb_sample_classes = np.clip(nb_sample_classes, 0, None)
  2778. class_ids_raw = self.class_ids.draw_samples(
  2779. (np.sum(nb_sample_classes),),
  2780. random_state=random_state)
  2781. class_ids = _split_1d_array_to_list(class_ids_raw, nb_sample_classes)
  2782. return class_ids
  2783. # TODO this could be simplified to something like:
  2784. # segmap.keep_only_classes(class_ids).draw_mask()
  2785. @classmethod
  2786. def generate_mask(cls, segmap, class_ids):
  2787. """Generate a mask of where the segmentation map has the given classes.
  2788. Added in 0.4.0.
  2789. Parameters
  2790. ----------
  2791. segmap : imgaug.augmentables.segmap.SegmentationMapsOnImage
  2792. The segmentation map for which to generate the mask.
  2793. class_ids : iterable of int
  2794. IDs of the classes to set to ``1.0``.
  2795. For an ``(x, y)`` position, it is enough that *any* channel
  2796. at the given location to have one of these class ids to be marked
  2797. as ``1.0``.
  2798. Returns
  2799. -------
  2800. ndarray
  2801. ``float32`` mask array with same height and width as
  2802. ``segmap.shape``. Values are in ``[0.0, 1.0]``.
  2803. """
  2804. mask = np.zeros(segmap.arr.shape[0:2], dtype=bool)
  2805. for class_id in class_ids:
  2806. # note that segmap has shape (H,W,C), so we max() along C
  2807. mask_i = np.any(segmap.arr == class_id, axis=2)
  2808. mask = np.logical_or(mask, mask_i)
  2809. mask = mask.astype(np.float32)
  2810. mask = ia.imresize_single_image(mask, segmap.shape[0:2])
  2811. return mask
  2812. class BoundingBoxesMaskGen(IBatchwiseMaskGenerator):
  2813. """Generator that produces masks highlighting bounding boxes.
  2814. This class produces for each row (i.e. image + bounding boxes) in a batch
  2815. a mask in which the inner areas of bounding box rectangles with given
  2816. labels are marked (i.e. set to ``1.0``). The labels may be provided as a
  2817. fixed list of strings or a stochastic parameter from which labels will be
  2818. sampled. If no labels are provided, all bounding boxes will be marked.
  2819. A pixel will be set to ``1.0`` if *at least* one bounding box at that
  2820. location has one of the requested labels, even if there is *also* one
  2821. bounding box at that location with a not requested label.
  2822. .. note::
  2823. This class will produce an ``AssertionError`` if there are no
  2824. bounding boxes in a batch.
  2825. Added in 0.4.0.
  2826. Parameters
  2827. ----------
  2828. labels : None or str or list of str or imgaug.parameters.StochasticParameter
  2829. Labels of bounding boxes to select for.
  2830. If `nb_sample_labels` is ``None`` then this is expected to be either
  2831. also ``None`` (select all BBs) or a single ``str`` (select BBs with
  2832. this one label) or a ``list`` of ``str`` s (always select BBs with
  2833. these labels).
  2834. If `nb_sample_labels` is set, then this parameter will be treated
  2835. as a stochastic parameter with the following valid types:
  2836. * If ``None``: Ignore the sampling count and always use all
  2837. bounding boxes.
  2838. * If ``str``: Exactly that label will be used for all
  2839. images.
  2840. * If ``list`` of ``str``: ``N`` random values will be picked per
  2841. image from that list and used as the labels.
  2842. * If ``StochasticParameter``: That parameter will be queried once
  2843. per batch for ``(sum(N),)`` values.
  2844. ``N`` denotes the number of labels to sample per segmentation
  2845. map (derived from `nb_sample_labels`) and ``sum(N)`` denotes the
  2846. sum of ``N`` s over all images.
  2847. nb_sample_labels : None or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  2848. Number of labels to sample (with replacement) per image.
  2849. As sampling happens with replacement, fewer *unique* labels may be
  2850. sampled.
  2851. * If ``None``: `labels` is expected to also be ``None`` or a fixed
  2852. value of labels to be used for all images.
  2853. * If ``int``: Exactly that many labels will be sampled for all
  2854. images.
  2855. * If ``tuple`` ``(a, b)``: A random value will be uniformly
  2856. sampled per image from the discrete interval ``[a..b]``.
  2857. * If ``list``: A random value will be picked per image from
  2858. that list.
  2859. * If ``StochasticParameter``: That parameter will be queried once
  2860. per batch for ``(B,)`` values, where ``B`` is the number of
  2861. images.
  2862. """
  2863. # Added in 0.4.0.
  2864. def __init__(self, labels=None, nb_sample_labels=None):
  2865. if labels is None:
  2866. self.labels = None
  2867. self.nb_sample_labels = None
  2868. elif nb_sample_labels is None:
  2869. if ia.is_string(labels):
  2870. labels = [labels]
  2871. assert isinstance(labels, list), (
  2872. "Expected `labels` a single string or a list of "
  2873. "strings if `nb_sample_labels` is None. Got type `%s`. "
  2874. "Set `nb_sample_labels` to e.g. an integer to enable "
  2875. "stochastic parameters for `labels`." % (
  2876. type(labels).__name__,))
  2877. self.labels = labels
  2878. self.nb_sample_labels = None
  2879. else:
  2880. self.labels = iap.handle_categorical_string_param(labels, "labels")
  2881. self.nb_sample_labels = iap.handle_discrete_param(
  2882. nb_sample_labels, "nb_sample_labels", value_range=(0, None),
  2883. tuple_to_uniform=True, list_to_choice=True,
  2884. allow_floats=False)
  2885. def draw_masks(self, batch, random_state=None):
  2886. """
  2887. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  2888. Added in 0.4.0.
  2889. """
  2890. assert batch.bounding_boxes is not None, (
  2891. "Can only generate masks for batches that contain bounding boxes, "
  2892. "but got a batch without them.")
  2893. random_state = iarandom.RNG(random_state)
  2894. if self.labels is None:
  2895. return [self.generate_mask(bbsoi, None)
  2896. for bbsoi in batch.bounding_boxes]
  2897. labels = self._draw_samples(batch.nb_rows, random_state=random_state)
  2898. return [self.generate_mask(bbsoi, labels_i)
  2899. for bbsoi, labels_i
  2900. in zip(batch.bounding_boxes, labels)]
  2901. # Added in 0.4.0.
  2902. def _draw_samples(self, nb_rows, random_state):
  2903. nb_sample_labels = self.nb_sample_labels
  2904. if nb_sample_labels is None:
  2905. assert isinstance(self.labels, list), (
  2906. "Expected list got %s." % (type(self.labels).__name__,))
  2907. return [self.labels] * nb_rows
  2908. nb_sample_labels = nb_sample_labels.draw_samples(
  2909. (nb_rows,), random_state=random_state)
  2910. nb_sample_labels = np.clip(nb_sample_labels, 0, None)
  2911. labels_raw = self.labels.draw_samples(
  2912. (np.sum(nb_sample_labels),),
  2913. random_state=random_state)
  2914. labels = _split_1d_array_to_list(labels_raw, nb_sample_labels)
  2915. return labels
  2916. # TODO this could be simplified to something like
  2917. # bbsoi.only_labels(labels).draw_mask()
  2918. @classmethod
  2919. def generate_mask(cls, bbsoi, labels):
  2920. """Generate a mask of the areas of bounding boxes with given labels.
  2921. Added in 0.4.0.
  2922. Parameters
  2923. ----------
  2924. bbsoi : imgaug.augmentables.bbs.BoundingBoxesOnImage
  2925. The bounding boxes for which to generate the mask.
  2926. labels : None or iterable of str
  2927. Labels of the bounding boxes to set to ``1.0``.
  2928. For an ``(x, y)`` position, it is enough that *any* bounding box
  2929. at the given location has one of the labels.
  2930. If this is ``None``, all bounding boxes will be marked.
  2931. Returns
  2932. -------
  2933. ndarray
  2934. ``float32`` mask array with same height and width as
  2935. ``segmap.shape``. Values are in ``[0.0, 1.0]``.
  2936. """
  2937. labels = set(labels) if labels is not None else None
  2938. height, width = bbsoi.shape[0:2]
  2939. mask = np.zeros((height, width), dtype=np.float32)
  2940. for bb in bbsoi:
  2941. if labels is None or bb.label in labels:
  2942. x1 = min(max(int(bb.x1), 0), width)
  2943. y1 = min(max(int(bb.y1), 0), height)
  2944. x2 = min(max(int(bb.x2), 0), width)
  2945. y2 = min(max(int(bb.y2), 0), height)
  2946. if x1 < x2 and y1 < y2:
  2947. mask[y1:y2, x1:x2] = 1.0
  2948. return mask
  2949. class InvertMaskGen(IBatchwiseMaskGenerator):
  2950. """Generator that inverts the outputs of other mask generators.
  2951. This class receives batches and calls for each row (i.e. image)
  2952. a child mask generator to produce a mask. That mask is then inverted
  2953. for ``p%`` of all rows, i.e. converted to ``1.0 - mask``.
  2954. Added in 0.4.0.
  2955. Parameters
  2956. ----------
  2957. p : bool or float or imgaug.parameters.StochasticParameter, optional
  2958. Probability of inverting each mask produced by the other mask
  2959. generator.
  2960. child : IBatchwiseMaskGenerator
  2961. The other mask generator to invert.
  2962. """
  2963. # Added in 0.4.0.
  2964. def __init__(self, p, child):
  2965. self.p = iap.handle_probability_param(p, "p")
  2966. self.child = child
  2967. def draw_masks(self, batch, random_state=None):
  2968. """
  2969. See :func:`~imgaug.augmenters.blend.IBatchwiseMaskGenerator.draw_masks`.
  2970. Added in 0.4.0.
  2971. """
  2972. random_state = iarandom.RNG(random_state)
  2973. masks = self.child.draw_masks(batch, random_state=random_state)
  2974. p = self.p.draw_samples(len(masks), random_state=random_state)
  2975. for mask, p_i in zip(masks, p):
  2976. if p_i >= 0.5:
  2977. mask[...] = 1.0 - mask
  2978. return masks
  2979. @ia.deprecated(alt_func="Alpha",
  2980. comment="Alpha is deprecated. "
  2981. "Use BlendAlpha instead. "
  2982. "The order of parameters is the same. "
  2983. "Parameter 'first' was renamed to 'foreground'. "
  2984. "Parameter 'second' was renamed to 'background'.")
  2985. def Alpha(factor=0, first=None, second=None, per_channel=False,
  2986. seed=None, name=None,
  2987. random_state="deprecated", deterministic="deprecated"):
  2988. """See :class:`BlendAlpha`.
  2989. Deprecated since 0.4.0.
  2990. """
  2991. # pylint: disable=invalid-name
  2992. return BlendAlpha(
  2993. factor=factor,
  2994. foreground=first,
  2995. background=second,
  2996. per_channel=per_channel,
  2997. seed=seed, name=name,
  2998. random_state=random_state, deterministic=deterministic)
  2999. @ia.deprecated(alt_func="AlphaElementwise",
  3000. comment="AlphaElementwise is deprecated. "
  3001. "Use BlendAlphaElementwise instead. "
  3002. "The order of parameters is the same. "
  3003. "Parameter 'first' was renamed to 'foreground'. "
  3004. "Parameter 'second' was renamed to 'background'.")
  3005. def AlphaElementwise(factor=0, first=None, second=None, per_channel=False,
  3006. seed=None, name=None,
  3007. random_state="deprecated", deterministic="deprecated"):
  3008. """See :class:`BlendAlphaElementwise`.
  3009. Deprecated since 0.4.0.
  3010. """
  3011. # pylint: disable=invalid-name
  3012. return BlendAlphaElementwise(
  3013. factor=factor,
  3014. foreground=first,
  3015. background=second,
  3016. per_channel=per_channel,
  3017. seed=seed, name=name,
  3018. random_state=random_state, deterministic=deterministic)
  3019. @ia.deprecated(alt_func="BlendAlphaSimplexNoise",
  3020. comment="SimplexNoiseAlpha is deprecated. "
  3021. "Use BlendAlphaSimplexNoise instead. "
  3022. "The order of parameters is the same. "
  3023. "Parameter 'first' was renamed to 'foreground'. "
  3024. "Parameter 'second' was renamed to 'background'.")
  3025. def SimplexNoiseAlpha(first=None, second=None, per_channel=False,
  3026. size_px_max=(2, 16), upscale_method=None,
  3027. iterations=(1, 3), aggregation_method="max",
  3028. sigmoid=True, sigmoid_thresh=None,
  3029. seed=None, name=None,
  3030. random_state="deprecated", deterministic="deprecated"):
  3031. """See :class:`BlendAlphaSimplexNoise`.
  3032. Deprecated since 0.4.0.
  3033. """
  3034. # pylint: disable=invalid-name
  3035. return BlendAlphaSimplexNoise(
  3036. foreground=first,
  3037. background=second,
  3038. per_channel=per_channel,
  3039. size_px_max=size_px_max,
  3040. upscale_method=upscale_method,
  3041. iterations=iterations,
  3042. aggregation_method=aggregation_method,
  3043. sigmoid=sigmoid,
  3044. sigmoid_thresh=sigmoid_thresh,
  3045. seed=seed, name=name,
  3046. random_state=random_state, deterministic=deterministic)
  3047. @ia.deprecated(alt_func="BlendAlphaFrequencyNoise",
  3048. comment="FrequencyNoiseAlpha is deprecated. "
  3049. "Use BlendAlphaFrequencyNoise instead. "
  3050. "The order of parameters is the same. "
  3051. "Parameter 'first' was renamed to 'foreground'. "
  3052. "Parameter 'second' was renamed to 'background'.")
  3053. def FrequencyNoiseAlpha(exponent=(-4, 4), first=None, second=None,
  3054. per_channel=False, size_px_max=(4, 16),
  3055. upscale_method=None,
  3056. iterations=(1, 3), aggregation_method=["avg", "max"],
  3057. sigmoid=0.5, sigmoid_thresh=None,
  3058. seed=None, name=None,
  3059. random_state="deprecated", deterministic="deprecated"):
  3060. """See :class:`BlendAlphaFrequencyNoise`.
  3061. Deprecated since 0.4.0.
  3062. """
  3063. # pylint: disable=invalid-name, dangerous-default-value
  3064. return BlendAlphaFrequencyNoise(
  3065. exponent=exponent,
  3066. foreground=first,
  3067. background=second,
  3068. per_channel=per_channel,
  3069. size_px_max=size_px_max,
  3070. upscale_method=upscale_method,
  3071. iterations=iterations,
  3072. aggregation_method=aggregation_method,
  3073. sigmoid=sigmoid,
  3074. sigmoid_thresh=sigmoid_thresh,
  3075. seed=seed, name=name,
  3076. random_state=random_state, deterministic=deterministic)