pillike.py 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574
  1. """
  2. Augmenters that have identical outputs to well-known PIL functions.
  3. The ``like`` in ``pillike`` indicates that the augmenters in this module
  4. have identical outputs and mostly identical inputs to corresponding PIL
  5. functions, but do not *have to* wrap these functions internally. They may
  6. use internally different (e.g. faster) techniques to produce these outputs.
  7. Some of the augmenters in this module may also exist in other modules
  8. under similar name. These other augmenters may currently have the same
  9. outputs as the corresponding PIL functions, but that is not guaranteed
  10. for the future. Use the augmenters in this module if identical outputs
  11. to PIL are required.
  12. List of augmenters:
  13. * :class:`Solarize`
  14. * :class:`Posterize`
  15. * :class:`Equalize`
  16. * :class:`Autocontrast`
  17. * :class:`EnhanceColor`
  18. * :class:`EnhanceContrast`
  19. * :class:`EnhanceBrightness`
  20. * :class:`EnhanceSharpness`
  21. * :class:`FilterBlur`
  22. * :class:`FilterSmooth`
  23. * :class:`FilterSmoothMore`
  24. * :class:`FilterEdgeEnhance`
  25. * :class:`FilterEdgeEnhanceMore`
  26. * :class:`FilterFindEdges`
  27. * :class:`FilterContour`
  28. * :class:`FilterEmboss`
  29. * :class:`FilterSharpen`
  30. * :class:`FilterDetail`
  31. * :class:`Affine`
  32. Standard usage of these augmenters follows roughly the schema::
  33. import numpy as np
  34. import imgaug.augmenters as iaa
  35. aug = iaa.pillike.Affine(translate_px={"x": (-5, 5)})
  36. image = np.full((32, 32, 3), 255, dtype=np.uint8)
  37. images_aug = aug(images=[image, image, image])
  38. Added in 0.4.0.
  39. """
  40. from __future__ import print_function, division, absolute_import
  41. import six.moves as sm
  42. import numpy as np
  43. import cv2
  44. import PIL.Image
  45. import PIL.ImageOps
  46. import PIL.ImageEnhance
  47. import PIL.ImageFilter
  48. import imgaug as ia
  49. from imgaug.imgaug import _normalize_cv2_input_arr_
  50. from . import meta
  51. from . import arithmetic
  52. from . import color as colorlib
  53. from . import contrast as contrastlib
  54. from . import geometric
  55. from . import size as sizelib
  56. from .. import parameters as iap
  57. # TODO some of the augmenters in this module broke on numpy arrays as
  58. # image inputs (as opposed to lists of arrays) without any test failing
  59. # add appropriate tests for that
  60. _EQUALIZE_USE_PIL_BELOW = 64*64 # H*W
  61. # Added in 0.4.0.
  62. def _ensure_valid_shape(image, func_name):
  63. is_hw1 = image.ndim == 3 and image.shape[-1] == 1
  64. if is_hw1:
  65. image = image[:, :, 0]
  66. assert (
  67. image.ndim == 2
  68. or (image.ndim == 3 and image.shape[-1] in [3, 4])
  69. ), (
  70. "Can apply %s only to images of "
  71. "shape (H, W) or (H, W, 1) or (H, W, 3) or (H, W, 4). "
  72. "Got shape %s." % (func_name, image.shape,))
  73. return image, is_hw1
  74. def solarize_(image, threshold=128):
  75. """Invert all array components above a threshold in-place.
  76. This function has identical outputs to ``PIL.ImageOps.solarize``.
  77. It does however work in-place.
  78. Added in 0.4.0.
  79. **Supported dtypes**:
  80. See ``~imgaug.augmenters.arithmetic.invert_(min_value=None and max_value=None)``.
  81. Parameters
  82. ----------
  83. image : ndarray
  84. Image array of shape ``(H,W,[C])``.
  85. The array *might* be modified in-place.
  86. threshold : int, optional
  87. A threshold to use in order to invert only numbers above or below
  88. the threshold.
  89. Returns
  90. -------
  91. ndarray
  92. Inverted image.
  93. This *can* be the same array as input in `image`, modified in-place.
  94. """
  95. return arithmetic.invert_(image, threshold=threshold)
  96. def solarize(image, threshold=128):
  97. """Invert all array components above a threshold.
  98. This function has identical outputs to ``PIL.ImageOps.solarize``.
  99. Added in 0.4.0.
  100. **Supported dtypes**:
  101. See ``~imgaug.augmenters.arithmetic.invert_(min_value=None and max_value=None)``.
  102. Parameters
  103. ----------
  104. image : ndarray
  105. Image array of shape ``(H,W,[C])``.
  106. threshold : int, optional
  107. A threshold to use in order to invert only numbers above or below
  108. the threshold.
  109. Returns
  110. -------
  111. ndarray
  112. Inverted image.
  113. """
  114. return arithmetic.invert(image, threshold=threshold)
  115. def posterize_(image, bits):
  116. """Reduce the number of bits for each color channel in-place.
  117. This function has identical outputs to ``PIL.ImageOps.posterize``.
  118. It does however work in-place.
  119. Added in 0.4.0.
  120. **Supported dtypes**:
  121. See :func:`~imgaug.augmenters.color.quantize_uniform_to_n_bits_`.
  122. Parameters
  123. ----------
  124. image : ndarray
  125. Image array of shape ``(H,W,[C])``.
  126. bits : int
  127. The number of bits to keep per component.
  128. Values in the interval ``[1, 8]`` are valid.
  129. Returns
  130. -------
  131. ndarray
  132. Posterized image.
  133. This *can* be the same array as input in `image`, modified in-place.
  134. """
  135. return colorlib.posterize(image, bits)
  136. def posterize(image, bits):
  137. """Reduce the number of bits for each color channel.
  138. This function has identical outputs to ``PIL.ImageOps.posterize``.
  139. Added in 0.4.0.
  140. **Supported dtypes**:
  141. See :func:`~imgaug.augmenters.color.quantize_uniform_to_n_bits`.
  142. Parameters
  143. ----------
  144. image : ndarray
  145. Image array of shape ``(H,W,[C])``.
  146. bits : int
  147. The number of bits to keep per component.
  148. Values in the interval ``[1, 8]`` are valid.
  149. Returns
  150. -------
  151. ndarray
  152. Posterized image.
  153. """
  154. return colorlib.posterize(image, bits)
  155. def equalize(image, mask=None):
  156. """Equalize the image histogram.
  157. See :func:`~imgaug.augmenters.pillike.equalize_` for details.
  158. This function is identical in inputs and outputs to
  159. ``PIL.ImageOps.equalize``.
  160. Added in 0.4.0.
  161. **Supported dtypes**:
  162. See :func:`~imgaug.augmenters.pillike.equalize_`.
  163. Parameters
  164. ----------
  165. image : ndarray
  166. ``uint8`` ``(H,W,[C])`` image to equalize.
  167. mask : None or ndarray, optional
  168. An optional mask. If given, only the pixels selected by the mask are
  169. included in the analysis.
  170. Returns
  171. -------
  172. ndarray
  173. Equalized image.
  174. """
  175. # internally used method works in-place by default and hence needs a copy
  176. size = image.size
  177. if size == 0:
  178. return np.copy(image)
  179. if size >= _EQUALIZE_USE_PIL_BELOW:
  180. image = np.copy(image)
  181. return equalize_(image, mask)
  182. def equalize_(image, mask=None):
  183. """Equalize the image histogram in-place.
  184. This function applies a non-linear mapping to the input image, in order
  185. to create a uniform distribution of grayscale values in the output image.
  186. This function has identical outputs to ``PIL.ImageOps.equalize``.
  187. It does however work in-place.
  188. Added in 0.4.0.
  189. **Supported dtypes**:
  190. * ``uint8``: yes; fully tested
  191. * ``uint16``: no
  192. * ``uint32``: no
  193. * ``uint64``: no
  194. * ``int8``: no
  195. * ``int16``: no
  196. * ``int32``: no
  197. * ``int64``: no
  198. * ``float16``: no
  199. * ``float32``: no
  200. * ``float64``: no
  201. * ``float128``: no
  202. * ``bool``: no
  203. Parameters
  204. ----------
  205. image : ndarray
  206. ``uint8`` ``(H,W,[C])`` image to equalize.
  207. mask : None or ndarray, optional
  208. An optional mask. If given, only the pixels selected by the mask are
  209. included in the analysis.
  210. Returns
  211. -------
  212. ndarray
  213. Equalized image. *Might* have been modified in-place.
  214. """
  215. nb_channels = 1 if image.ndim == 2 else image.shape[-1]
  216. if nb_channels not in [1, 3]:
  217. result = [equalize_(image[:, :, c])
  218. for c in np.arange(nb_channels)]
  219. return np.stack(result, axis=-1)
  220. assert image.dtype.name == "uint8", (
  221. "Expected image of dtype uint8, got dtype %s." % (image.dtype.name,))
  222. if mask is not None:
  223. assert mask.ndim == 2, (
  224. "Expected 2-dimensional mask, got shape %s." % (mask.shape,))
  225. assert mask.dtype.name == "uint8", (
  226. "Expected mask of dtype uint8, got dtype %s." % (mask.dtype.name,))
  227. size = image.size
  228. if size == 0:
  229. return image
  230. if nb_channels == 3 and size < _EQUALIZE_USE_PIL_BELOW:
  231. return _equalize_pil_(image, mask)
  232. return _equalize_no_pil_(image, mask)
  233. # note that this is supposed to be a non-PIL reimplementation of PIL's
  234. # equalize, which produces slightly different results from cv2.equalizeHist()
  235. # Added in 0.4.0.
  236. def _equalize_no_pil_(image, mask=None):
  237. nb_channels = 1 if image.ndim == 2 else image.shape[-1]
  238. # TODO remove the first axis, no longer needed
  239. lut = np.empty((1, 256, nb_channels), dtype=np.int32)
  240. for c_idx in range(nb_channels):
  241. if image.ndim == 2:
  242. image_c = image[:, :, np.newaxis]
  243. else:
  244. image_c = image[:, :, c_idx:c_idx+1]
  245. histo = cv2.calcHist(
  246. [_normalize_cv2_input_arr_(image_c)], [0], mask, [256], [0, 256])
  247. if len(histo.nonzero()[0]) <= 1:
  248. lut[0, :, c_idx] = np.arange(256).astype(np.int32)
  249. continue
  250. step = np.sum(histo[:-1]) // 255
  251. if not step:
  252. lut[0, :, c_idx] = np.arange(256).astype(np.int32)
  253. continue
  254. n = step // 2
  255. cumsum = np.cumsum(histo)
  256. lut[0, 0, c_idx] = n
  257. lut[0, 1:, c_idx] = n + cumsum[0:-1]
  258. lut[0, :, c_idx] //= int(step)
  259. lut = np.clip(lut, None, 255, out=lut).astype(np.uint8)
  260. image = ia.apply_lut_(image, lut)
  261. return image
  262. # Added in 0.4.0.
  263. def _equalize_pil_(image, mask=None):
  264. if mask is not None:
  265. mask = PIL.Image.fromarray(mask).convert("L")
  266. # don't return np.asarray(...) directly as its results are read-only
  267. image[...] = np.asarray(
  268. PIL.ImageOps.equalize(
  269. PIL.Image.fromarray(image),
  270. mask=mask
  271. )
  272. )
  273. return image
  274. def autocontrast(image, cutoff=0, ignore=None):
  275. """Maximize (normalize) image contrast.
  276. This function calculates a histogram of the input image, removes
  277. **cutoff** percent of the lightest and darkest pixels from the histogram,
  278. and remaps the image so that the darkest pixel becomes black (``0``), and
  279. the lightest becomes white (``255``).
  280. This function has identical outputs to ``PIL.ImageOps.autocontrast``.
  281. The speed is almost identical.
  282. Added in 0.4.0.
  283. **Supported dtypes**:
  284. * ``uint8``: yes; fully tested
  285. * ``uint16``: no
  286. * ``uint32``: no
  287. * ``uint64``: no
  288. * ``int8``: no
  289. * ``int16``: no
  290. * ``int32``: no
  291. * ``int64``: no
  292. * ``float16``: no
  293. * ``float32``: no
  294. * ``float64``: no
  295. * ``float128``: no
  296. * ``bool``: no
  297. Parameters
  298. ----------
  299. image : ndarray
  300. The image for which to enhance the contrast.
  301. cutoff : number
  302. How many percent to cut off at the low and high end of the
  303. histogram. E.g. ``20`` will cut off the lowest and highest ``20%``
  304. of values. Expected value range is ``[0, 100]``.
  305. ignore : None or int or iterable of int
  306. Intensity values to ignore, i.e. to treat as background. If ``None``,
  307. no pixels will be ignored. Otherwise exactly the given intensity
  308. value(s) will be ignored.
  309. Returns
  310. -------
  311. ndarray
  312. Contrast-enhanced image.
  313. """
  314. assert image.dtype.name == "uint8", (
  315. "Can apply autocontrast only to uint8 images, got dtype %s." % (
  316. image.dtype.name,))
  317. if 0 in image.shape:
  318. return np.copy(image)
  319. standard_channels = (image.ndim == 2 or image.shape[2] == 3)
  320. if cutoff and standard_channels:
  321. return _autocontrast_pil(image, cutoff, ignore)
  322. return _autocontrast_no_pil(image, cutoff, ignore)
  323. # Added in 0.4.0.
  324. def _autocontrast_pil(image, cutoff, ignore):
  325. # don't return np.asarray(...) as its results are read-only
  326. return np.array(
  327. PIL.ImageOps.autocontrast(
  328. PIL.Image.fromarray(image),
  329. cutoff=cutoff, ignore=ignore
  330. )
  331. )
  332. # This function is only faster than the corresponding PIL function if no
  333. # cutoff is used.
  334. # C901 is "<functionname> is too complex"
  335. # Added in 0.4.0.
  336. def _autocontrast_no_pil(image, cutoff, ignore): # noqa: C901
  337. # pylint: disable=invalid-name
  338. if ignore is not None and not ia.is_iterable(ignore):
  339. ignore = [ignore]
  340. result = np.empty_like(image)
  341. if result.ndim == 2:
  342. result = result[..., np.newaxis]
  343. nb_channels = image.shape[2] if image.ndim >= 3 else 1
  344. for c_idx in sm.xrange(nb_channels):
  345. # using [0] instead of [int(c_idx)] allows this to work with >4
  346. # channels
  347. if image.ndim == 2:
  348. image_c = image[:, :, np.newaxis]
  349. else:
  350. image_c = image[:, :, c_idx:c_idx+1]
  351. h = cv2.calcHist(
  352. [_normalize_cv2_input_arr_(image_c)], [0], None, [256], [0, 256])
  353. if ignore is not None:
  354. h[ignore] = 0
  355. if cutoff:
  356. cs = np.cumsum(h)
  357. n = cs[-1]
  358. cut = n * cutoff // 100
  359. # remove cutoff% pixels from the low end
  360. lo_cut = cut - cs
  361. lo_cut_nz = np.nonzero(lo_cut <= 0.0)[0]
  362. if len(lo_cut_nz) == 0:
  363. lo = 255
  364. else:
  365. lo = lo_cut_nz[0]
  366. if lo > 0:
  367. h[:lo] = 0
  368. h[lo] = lo_cut[lo]
  369. # remove cutoff% samples from the hi end
  370. cs_rev = np.cumsum(h[::-1])
  371. hi_cut = cs_rev - cut
  372. hi_cut_nz = np.nonzero(hi_cut > 0.0)[0]
  373. if len(hi_cut_nz) == 0:
  374. hi = -1
  375. else:
  376. hi = 255 - hi_cut_nz[0]
  377. h[hi+1:] = 0
  378. if hi > -1:
  379. h[hi] = hi_cut[255-hi]
  380. # find lowest/highest samples after preprocessing
  381. for lo, lo_val in enumerate(h):
  382. if lo_val:
  383. break
  384. for hi in range(255, -1, -1):
  385. if h[hi]:
  386. break
  387. if hi <= lo:
  388. # don't bother
  389. lut = np.arange(256)
  390. else:
  391. scale = 255.0 / (hi - lo)
  392. offset = -lo * scale
  393. ix = np.arange(256).astype(np.float64) * scale + offset
  394. ix = np.clip(ix, 0, 255).astype(np.uint8)
  395. lut = ix
  396. lut = np.array(lut, dtype=np.uint8)
  397. # Vectorized implementation of above block.
  398. # This is overall slower.
  399. # h_nz = np.nonzero(h)[0]
  400. # if len(h_nz) <= 1:
  401. # lut = np.arange(256).astype(np.uint8)
  402. # else:
  403. # lo = h_nz[0]
  404. # hi = h_nz[-1]
  405. #
  406. # scale = 255.0 / (hi - lo)
  407. # offset = -lo * scale
  408. # ix = np.arange(256).astype(np.float64) * scale + offset
  409. # ix = np.clip(ix, 0, 255).astype(np.uint8)
  410. # lut = ix
  411. # TODO change to a single call instead of one per channel
  412. image_c_aug = ia.apply_lut(image_c, lut)
  413. result[:, :, c_idx:c_idx+1] = image_c_aug
  414. if image.ndim == 2:
  415. return result[..., 0]
  416. return result
  417. # Added in 0.4.0.
  418. def _apply_enhance_func(image, cls, factor):
  419. assert image.dtype.name == "uint8", (
  420. "Can apply PIL image enhancement only to uint8 images, "
  421. "got dtype %s." % (image.dtype.name,))
  422. if 0 in image.shape:
  423. return np.copy(image)
  424. image, is_hw1 = _ensure_valid_shape(
  425. image, "imgaug.augmenters.pillike.enhance_*()")
  426. # don't return np.asarray(...) as its results are read-only
  427. result = np.array(
  428. cls(
  429. PIL.Image.fromarray(image)
  430. ).enhance(factor)
  431. )
  432. if is_hw1:
  433. result = result[:, :, np.newaxis]
  434. return result
  435. def enhance_color(image, factor):
  436. """Change the strength of colors in an image.
  437. This function has identical outputs to
  438. ``PIL.ImageEnhance.Color``.
  439. Added in 0.4.0.
  440. **Supported dtypes**:
  441. * ``uint8``: yes; fully tested
  442. * ``uint16``: no
  443. * ``uint32``: no
  444. * ``uint64``: no
  445. * ``int8``: no
  446. * ``int16``: no
  447. * ``int32``: no
  448. * ``int64``: no
  449. * ``float16``: no
  450. * ``float32``: no
  451. * ``float64``: no
  452. * ``float128``: no
  453. * ``bool``: no
  454. Parameters
  455. ----------
  456. image : ndarray
  457. The image to modify.
  458. factor : number
  459. Colorfulness of the output image. Values close to ``0.0`` lead
  460. to grayscale images, values above ``1.0`` increase the strength of
  461. colors. Sane values are roughly in ``[0.0, 3.0]``.
  462. Returns
  463. -------
  464. ndarray
  465. Color-modified image.
  466. """
  467. return _apply_enhance_func(image, PIL.ImageEnhance.Color, factor)
  468. def enhance_contrast(image, factor):
  469. """Change the contrast of an image.
  470. This function has identical outputs to
  471. ``PIL.ImageEnhance.Contrast``.
  472. Added in 0.4.0.
  473. **Supported dtypes**:
  474. * ``uint8``: yes; fully tested
  475. * ``uint16``: no
  476. * ``uint32``: no
  477. * ``uint64``: no
  478. * ``int8``: no
  479. * ``int16``: no
  480. * ``int32``: no
  481. * ``int64``: no
  482. * ``float16``: no
  483. * ``float32``: no
  484. * ``float64``: no
  485. * ``float128``: no
  486. * ``bool``: no
  487. Parameters
  488. ----------
  489. image : ndarray
  490. The image to modify.
  491. factor : number
  492. Strength of contrast in the image. Values below ``1.0`` decrease the
  493. contrast, leading to a gray image around ``0.0``. Values
  494. above ``1.0`` increase the contrast. Sane values are roughly in
  495. ``[0.5, 1.5]``.
  496. Returns
  497. -------
  498. ndarray
  499. Contrast-modified image.
  500. """
  501. return _apply_enhance_func(image, PIL.ImageEnhance.Contrast, factor)
  502. def enhance_brightness(image, factor):
  503. """Change the brightness of images.
  504. This function has identical outputs to
  505. ``PIL.ImageEnhance.Brightness``.
  506. Added in 0.4.0.
  507. **Supported dtypes**:
  508. * ``uint8``: yes; fully tested
  509. * ``uint16``: no
  510. * ``uint32``: no
  511. * ``uint64``: no
  512. * ``int8``: no
  513. * ``int16``: no
  514. * ``int32``: no
  515. * ``int64``: no
  516. * ``float16``: no
  517. * ``float32``: no
  518. * ``float64``: no
  519. * ``float128``: no
  520. * ``bool``: no
  521. Parameters
  522. ----------
  523. image : ndarray
  524. The image to modify.
  525. factor : number
  526. Brightness of the image. Values below ``1.0`` decrease the brightness,
  527. leading to a black image around ``0.0``. Values above ``1.0`` increase
  528. the brightness. Sane values are roughly in ``[0.5, 1.5]``.
  529. Returns
  530. -------
  531. ndarray
  532. Brightness-modified image.
  533. """
  534. return _apply_enhance_func(image, PIL.ImageEnhance.Brightness, factor)
  535. def enhance_sharpness(image, factor):
  536. """Change the sharpness of an image.
  537. This function has identical outputs to
  538. ``PIL.ImageEnhance.Sharpness``.
  539. Added in 0.4.0.
  540. **Supported dtypes**:
  541. * ``uint8``: yes; fully tested
  542. * ``uint16``: no
  543. * ``uint32``: no
  544. * ``uint64``: no
  545. * ``int8``: no
  546. * ``int16``: no
  547. * ``int32``: no
  548. * ``int64``: no
  549. * ``float16``: no
  550. * ``float32``: no
  551. * ``float64``: no
  552. * ``float128``: no
  553. * ``bool``: no
  554. Parameters
  555. ----------
  556. image : ndarray
  557. The image to modify.
  558. factor : number
  559. Sharpness of the image. Values below ``1.0`` decrease the sharpness,
  560. values above ``1.0`` increase it. Sane values are roughly in
  561. ``[0.0, 2.0]``.
  562. Returns
  563. -------
  564. ndarray
  565. Sharpness-modified image.
  566. """
  567. return _apply_enhance_func(image, PIL.ImageEnhance.Sharpness, factor)
  568. # Added in 0.4.0.
  569. def _filter_by_kernel(image, kernel):
  570. assert image.dtype.name == "uint8", (
  571. "Can apply PIL filters only to uint8 images, "
  572. "got dtype %s." % (image.dtype.name,))
  573. if 0 in image.shape:
  574. return np.copy(image)
  575. image, is_hw1 = _ensure_valid_shape(
  576. image, "imgaug.augmenters.pillike.filter_*()")
  577. image_pil = PIL.Image.fromarray(image)
  578. image_filtered = image_pil.filter(kernel)
  579. # don't return np.asarray(...) as its results are read-only
  580. result = np.array(image_filtered)
  581. if is_hw1:
  582. result = result[:, :, np.newaxis]
  583. return result
  584. def filter_blur(image):
  585. """Apply a blur filter kernel to the image.
  586. This is the same as using PIL's ``PIL.ImageFilter.BLUR`` kernel.
  587. Added in 0.4.0.
  588. **Supported dtypes**:
  589. * ``uint8``: yes; fully tested
  590. * ``uint16``: no
  591. * ``uint32``: no
  592. * ``uint64``: no
  593. * ``int8``: no
  594. * ``int16``: no
  595. * ``int32``: no
  596. * ``int64``: no
  597. * ``float16``: no
  598. * ``float32``: no
  599. * ``float64``: no
  600. * ``float128``: no
  601. * ``bool``: no
  602. Parameters
  603. ----------
  604. image : ndarray
  605. The image to modify.
  606. Returns
  607. -------
  608. ndarray
  609. Blurred image.
  610. """
  611. return _filter_by_kernel(image, PIL.ImageFilter.BLUR)
  612. def filter_smooth(image):
  613. """Apply a smoothness filter kernel to the image.
  614. This is the same as using PIL's ``PIL.ImageFilter.SMOOTH`` kernel.
  615. Added in 0.4.0.
  616. **Supported dtypes**:
  617. * ``uint8``: yes; fully tested
  618. * ``uint16``: no
  619. * ``uint32``: no
  620. * ``uint64``: no
  621. * ``int8``: no
  622. * ``int16``: no
  623. * ``int32``: no
  624. * ``int64``: no
  625. * ``float16``: no
  626. * ``float32``: no
  627. * ``float64``: no
  628. * ``float128``: no
  629. * ``bool``: no
  630. Parameters
  631. ----------
  632. image : ndarray
  633. The image to modify.
  634. Returns
  635. -------
  636. ndarray
  637. Smoothened image.
  638. """
  639. return _filter_by_kernel(image, PIL.ImageFilter.SMOOTH)
  640. def filter_smooth_more(image):
  641. """Apply a strong smoothness filter kernel to the image.
  642. This is the same as using PIL's ``PIL.ImageFilter.SMOOTH_MORE`` kernel.
  643. Added in 0.4.0.
  644. **Supported dtypes**:
  645. * ``uint8``: yes; fully tested
  646. * ``uint16``: no
  647. * ``uint32``: no
  648. * ``uint64``: no
  649. * ``int8``: no
  650. * ``int16``: no
  651. * ``int32``: no
  652. * ``int64``: no
  653. * ``float16``: no
  654. * ``float32``: no
  655. * ``float64``: no
  656. * ``float128``: no
  657. * ``bool``: no
  658. Parameters
  659. ----------
  660. image : ndarray
  661. The image to modify.
  662. Returns
  663. -------
  664. ndarray
  665. Smoothened image.
  666. """
  667. return _filter_by_kernel(image, PIL.ImageFilter.SMOOTH_MORE)
  668. def filter_edge_enhance(image):
  669. """Apply an edge enhancement filter kernel to the image.
  670. This is the same as using PIL's ``PIL.ImageFilter.EDGE_ENHANCE`` kernel.
  671. Added in 0.4.0.
  672. **Supported dtypes**:
  673. * ``uint8``: yes; fully tested
  674. * ``uint16``: no
  675. * ``uint32``: no
  676. * ``uint64``: no
  677. * ``int8``: no
  678. * ``int16``: no
  679. * ``int32``: no
  680. * ``int64``: no
  681. * ``float16``: no
  682. * ``float32``: no
  683. * ``float64``: no
  684. * ``float128``: no
  685. * ``bool``: no
  686. Parameters
  687. ----------
  688. image : ndarray
  689. The image to modify.
  690. Returns
  691. -------
  692. ndarray
  693. Image with enhanced edges.
  694. """
  695. return _filter_by_kernel(image, PIL.ImageFilter.EDGE_ENHANCE)
  696. def filter_edge_enhance_more(image):
  697. """Apply a stronger edge enhancement filter kernel to the image.
  698. This is the same as using PIL's ``PIL.ImageFilter.EDGE_ENHANCE_MORE``
  699. kernel.
  700. Added in 0.4.0.
  701. **Supported dtypes**:
  702. * ``uint8``: yes; fully tested
  703. * ``uint16``: no
  704. * ``uint32``: no
  705. * ``uint64``: no
  706. * ``int8``: no
  707. * ``int16``: no
  708. * ``int32``: no
  709. * ``int64``: no
  710. * ``float16``: no
  711. * ``float32``: no
  712. * ``float64``: no
  713. * ``float128``: no
  714. * ``bool``: no
  715. Parameters
  716. ----------
  717. image : ndarray
  718. The image to modify.
  719. Returns
  720. -------
  721. ndarray
  722. Smoothened image.
  723. """
  724. return _filter_by_kernel(image, PIL.ImageFilter.EDGE_ENHANCE_MORE)
  725. def filter_find_edges(image):
  726. """Apply an edge detection filter kernel to the image.
  727. This is the same as using PIL's ``PIL.ImageFilter.FIND_EDGES`` kernel.
  728. Added in 0.4.0.
  729. **Supported dtypes**:
  730. * ``uint8``: yes; fully tested
  731. * ``uint16``: no
  732. * ``uint32``: no
  733. * ``uint64``: no
  734. * ``int8``: no
  735. * ``int16``: no
  736. * ``int32``: no
  737. * ``int64``: no
  738. * ``float16``: no
  739. * ``float32``: no
  740. * ``float64``: no
  741. * ``float128``: no
  742. * ``bool``: no
  743. Parameters
  744. ----------
  745. image : ndarray
  746. The image to modify.
  747. Returns
  748. -------
  749. ndarray
  750. Image with detected edges.
  751. """
  752. return _filter_by_kernel(image, PIL.ImageFilter.FIND_EDGES)
  753. def filter_contour(image):
  754. """Apply a contour filter kernel to the image.
  755. This is the same as using PIL's ``PIL.ImageFilter.CONTOUR`` kernel.
  756. Added in 0.4.0.
  757. **Supported dtypes**:
  758. * ``uint8``: yes; fully tested
  759. * ``uint16``: no
  760. * ``uint32``: no
  761. * ``uint64``: no
  762. * ``int8``: no
  763. * ``int16``: no
  764. * ``int32``: no
  765. * ``int64``: no
  766. * ``float16``: no
  767. * ``float32``: no
  768. * ``float64``: no
  769. * ``float128``: no
  770. * ``bool``: no
  771. Parameters
  772. ----------
  773. image : ndarray
  774. The image to modify.
  775. Returns
  776. -------
  777. ndarray
  778. Image with pronounced contours.
  779. """
  780. return _filter_by_kernel(image, PIL.ImageFilter.CONTOUR)
  781. def filter_emboss(image):
  782. """Apply an emboss filter kernel to the image.
  783. This is the same as using PIL's ``PIL.ImageFilter.EMBOSS`` kernel.
  784. Added in 0.4.0.
  785. **Supported dtypes**:
  786. * ``uint8``: yes; fully tested
  787. * ``uint16``: no
  788. * ``uint32``: no
  789. * ``uint64``: no
  790. * ``int8``: no
  791. * ``int16``: no
  792. * ``int32``: no
  793. * ``int64``: no
  794. * ``float16``: no
  795. * ``float32``: no
  796. * ``float64``: no
  797. * ``float128``: no
  798. * ``bool``: no
  799. Parameters
  800. ----------
  801. image : ndarray
  802. The image to modify.
  803. Returns
  804. -------
  805. ndarray
  806. Embossed image.
  807. """
  808. return _filter_by_kernel(image, PIL.ImageFilter.EMBOSS)
  809. def filter_sharpen(image):
  810. """Apply a sharpening filter kernel to the image.
  811. This is the same as using PIL's ``PIL.ImageFilter.SHARPEN`` kernel.
  812. Added in 0.4.0.
  813. **Supported dtypes**:
  814. * ``uint8``: yes; fully tested
  815. * ``uint16``: no
  816. * ``uint32``: no
  817. * ``uint64``: no
  818. * ``int8``: no
  819. * ``int16``: no
  820. * ``int32``: no
  821. * ``int64``: no
  822. * ``float16``: no
  823. * ``float32``: no
  824. * ``float64``: no
  825. * ``float128``: no
  826. * ``bool``: no
  827. Parameters
  828. ----------
  829. image : ndarray
  830. The image to modify.
  831. Returns
  832. -------
  833. ndarray
  834. Sharpened image.
  835. """
  836. return _filter_by_kernel(image, PIL.ImageFilter.SHARPEN)
  837. def filter_detail(image):
  838. """Apply a detail enhancement filter kernel to the image.
  839. This is the same as using PIL's ``PIL.ImageFilter.DETAIL`` kernel.
  840. Added in 0.4.0.
  841. **Supported dtypes**:
  842. * ``uint8``: yes; fully tested
  843. * ``uint16``: no
  844. * ``uint32``: no
  845. * ``uint64``: no
  846. * ``int8``: no
  847. * ``int16``: no
  848. * ``int32``: no
  849. * ``int64``: no
  850. * ``float16``: no
  851. * ``float32``: no
  852. * ``float64``: no
  853. * ``float128``: no
  854. * ``bool``: no
  855. Parameters
  856. ----------
  857. image : ndarray
  858. The image to modify.
  859. Returns
  860. -------
  861. ndarray
  862. Image with enhanced details.
  863. """
  864. return _filter_by_kernel(image, PIL.ImageFilter.DETAIL)
  865. # TODO unify this with the matrix generation for Affine,
  866. # there is probably no need to keep these separate
  867. # Added in 0.4.0.
  868. def _create_affine_matrix(scale_x=1.0, scale_y=1.0,
  869. translate_x_px=0, translate_y_px=0,
  870. rotate_deg=0,
  871. shear_x_deg=0, shear_y_deg=0,
  872. center_px=(0, 0)):
  873. scale_x = max(scale_x, 0.0001)
  874. scale_y = max(scale_y, 0.0001)
  875. rotate_rad, shear_x_rad, shear_y_rad = np.deg2rad([rotate_deg,
  876. shear_x_deg,
  877. shear_y_deg])
  878. rotate_rad = (-1) * rotate_rad
  879. matrix_centerize = np.array([
  880. [1, 0, (-1) * center_px[0]],
  881. [0, 1, (-1) * center_px[1]],
  882. [0, 0, 1]
  883. ], dtype=np.float32)
  884. matrix_scale = np.array([
  885. [scale_x, 0, 0],
  886. [0, scale_y, 0],
  887. [0, 0, 1]
  888. ], dtype=np.float32)
  889. matrix_translate = np.array([
  890. [1, 0, translate_x_px],
  891. [0, 1, translate_y_px],
  892. [0, 0, 1]
  893. ], dtype=np.float32)
  894. matrix_shear = np.array([
  895. [1, np.tanh(shear_x_rad), 0],
  896. [np.tanh(shear_y_rad), 1, 0],
  897. [0, 0, 1]
  898. ], dtype=np.float32)
  899. matrix_rotate = np.array([
  900. [np.cos(rotate_rad), np.sin(rotate_rad), 0],
  901. [-np.sin(rotate_rad), np.cos(rotate_rad), 0],
  902. [0, 0, 1]
  903. ], dtype=np.float32)
  904. matrix_decenterize = np.array([
  905. [1, 0, center_px[0]],
  906. [0, 1, center_px[1]],
  907. [0, 0, 1]
  908. ], dtype=np.float32)
  909. matrix = np.array([
  910. [1, 0, 0],
  911. [0, 1, 0],
  912. [0, 0, 1]
  913. ], dtype=np.float32)
  914. for other_matrix in [matrix_centerize,
  915. matrix_rotate, matrix_shear,
  916. matrix_scale, matrix_translate,
  917. matrix_decenterize]:
  918. matrix = np.matmul(other_matrix, matrix)
  919. matrix = np.linalg.inv(matrix)
  920. return matrix
  921. def warp_affine(image,
  922. scale_x=1.0, scale_y=1.0,
  923. translate_x_px=0, translate_y_px=0,
  924. rotate_deg=0,
  925. shear_x_deg=0, shear_y_deg=0,
  926. fillcolor=None,
  927. center=(0.5, 0.5)):
  928. """Apply an affine transformation to an image.
  929. This function has identical outputs to
  930. ``PIL.Image.transform`` with ``method=PIL.Image.AFFINE``.
  931. Added in 0.4.0.
  932. **Supported dtypes**:
  933. * ``uint8``: yes; fully tested
  934. * ``uint16``: no
  935. * ``uint32``: no
  936. * ``uint64``: no
  937. * ``int8``: no
  938. * ``int16``: no
  939. * ``int32``: no
  940. * ``int64``: no
  941. * ``float16``: no
  942. * ``float32``: no
  943. * ``float64``: no
  944. * ``float128``: no
  945. * ``bool``: no
  946. Parameters
  947. ----------
  948. image : ndarray
  949. The image to modify. Expected to be ``uint8`` with shape ``(H,W)``
  950. or ``(H,W,C)`` with ``C`` being ``3`` or ``4``.
  951. scale_x : number, optional
  952. Affine scale factor along the x-axis, where ``1.0`` denotes an
  953. identity transform and ``2.0`` is a strong zoom-in effect.
  954. scale_y : number, optional
  955. Affine scale factor along the y-axis, where ``1.0`` denotes an
  956. identity transform and ``2.0`` is a strong zoom-in effect.
  957. translate_x_px : number, optional
  958. Affine translation along the x-axis in pixels.
  959. Positive values translate the image towards the right.
  960. translate_y_px : number, optional
  961. Affine translation along the y-axis in pixels.
  962. Positive values translate the image towards the bottom.
  963. rotate_deg : number, optional
  964. Affine rotation in degrees *around the top left* of the image.
  965. shear_x_deg : number, optional
  966. Affine shearing in degrees along the x-axis with center point
  967. being the top-left of the image.
  968. shear_y_deg : number, optional
  969. Affine shearing in degrees along the y-axis with center point
  970. being the top-left of the image.
  971. fillcolor : None or int or tuple of int, optional
  972. Color tuple or intensity value to use when filling up newly
  973. created pixels. ``None`` fills with zeros. ``int`` will only fill
  974. the ``0`` th channel with that intensity value and all other channels
  975. with ``0`` (this is the default behaviour of PIL, use a tuple to
  976. fill all channels).
  977. center : tuple of number, optional
  978. Center xy-coordinate of the affine transformation, given as *relative*
  979. values, i.e. ``(0.0, 0.0)`` sets the transformation center to the
  980. top-left image corner, ``(1.0, 0.0)`` sets it to the the top-right
  981. image corner and ``(0.5, 0.5)`` sets it to the image center.
  982. The transformation center is relevant e.g. for rotations ("rotate
  983. around this center point"). PIL uses the image top-left corner
  984. as the transformation center if no centerization is included in the
  985. affine transformation matrix.
  986. Returns
  987. -------
  988. ndarray
  989. Image after affine transformation.
  990. """
  991. assert image.dtype.name == "uint8", (
  992. "Can apply PIL affine transformation only to uint8 images, "
  993. "got dtype %s." % (image.dtype.name,))
  994. if 0 in image.shape:
  995. return np.copy(image)
  996. fillcolor = fillcolor if fillcolor is not None else 0
  997. if ia.is_iterable(fillcolor):
  998. # make sure that iterable fillcolor contains only ints
  999. # otherwise we get a deprecation warning in py3.8
  1000. fillcolor = tuple(map(int, fillcolor))
  1001. image, is_hw1 = _ensure_valid_shape(
  1002. image, "imgaug.augmenters.pillike.warp_affine()")
  1003. image_pil = PIL.Image.fromarray(image)
  1004. height, width = image.shape[0:2]
  1005. center_px = (width * center[0], height * center[1])
  1006. matrix = _create_affine_matrix(scale_x=scale_x,
  1007. scale_y=scale_y,
  1008. translate_x_px=translate_x_px,
  1009. translate_y_px=translate_y_px,
  1010. rotate_deg=rotate_deg,
  1011. shear_x_deg=shear_x_deg,
  1012. shear_y_deg=shear_y_deg,
  1013. center_px=center_px)
  1014. matrix = matrix[:2, :].flat
  1015. # don't return np.asarray(...) as its results are read-only
  1016. result = np.array(
  1017. image_pil.transform(image_pil.size, PIL.Image.AFFINE, matrix,
  1018. fillcolor=fillcolor)
  1019. )
  1020. if is_hw1:
  1021. result = result[:, :, np.newaxis]
  1022. return result
  1023. # we don't use pil_solarize() here. but instead just subclass Invert,
  1024. # which is easier and comes down to the same
  1025. class Solarize(arithmetic.Invert):
  1026. """Augmenter with identical outputs to PIL's ``solarize()`` function.
  1027. This augmenter inverts all pixel values above a threshold.
  1028. The outputs are identical to PIL's ``solarize()``.
  1029. Added in 0.4.0.
  1030. **Supported dtypes**:
  1031. See ``~imgaug.augmenters.arithmetic.invert_(min_value=None and max_value=None)``.
  1032. Parameters
  1033. ----------
  1034. p : float or imgaug.parameters.StochasticParameter, optional
  1035. See :class:`~imgaug.augmenters.arithmetic.Invert`.
  1036. threshold : None or number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1037. See :class:`~imgaug.augmenters.arithmetic.Invert`.
  1038. 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
  1039. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1040. name : None or str, optional
  1041. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1042. 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
  1043. Old name for parameter `seed`.
  1044. Its usage will not yet cause a deprecation warning,
  1045. but it is still recommended to use `seed` now.
  1046. Outdated since 0.4.0.
  1047. deterministic : bool, optional
  1048. Deprecated since 0.4.0.
  1049. See method ``to_deterministic()`` for an alternative and for
  1050. details about what the "deterministic mode" actually does.
  1051. Examples
  1052. --------
  1053. >>> import imgaug.augmenters as iaa
  1054. >>> aug = iaa.Solarize(0.5, threshold=(32, 128))
  1055. Invert the colors in ``50`` percent of all images for pixels with a
  1056. value between ``32`` and ``128`` or more. The threshold is sampled once
  1057. per image. The thresholding operation happens per channel.
  1058. """
  1059. def __init__(self, p=1.0, threshold=128,
  1060. seed=None, name=None,
  1061. random_state="deprecated", deterministic="deprecated"):
  1062. super(Solarize, self).__init__(
  1063. p=p, per_channel=False,
  1064. min_value=None, max_value=None,
  1065. threshold=threshold, invert_above_threshold=True,
  1066. seed=seed, name=name,
  1067. random_state=random_state, deterministic=deterministic)
  1068. class Posterize(colorlib.Posterize):
  1069. """Augmenter with identical outputs to PIL's ``posterize()`` function.
  1070. This augmenter quantizes each array component to ``N`` bits.
  1071. This class is currently an alias for
  1072. :class:`~imgaug.augmenters.color.Posterize`, which again is an alias
  1073. for :class:`~imgaug.augmenters.color.UniformColorQuantizationToNBits`,
  1074. i.e. all three classes are right now guarantueed to have the same
  1075. outputs as PIL's function.
  1076. Added in 0.4.0.
  1077. **Supported dtypes**:
  1078. See :class:`~imgaug.augmenters.color.Posterize`.
  1079. """
  1080. class Equalize(meta.Augmenter):
  1081. """Equalize the image histogram.
  1082. This augmenter has identical outputs to ``PIL.ImageOps.equalize``.
  1083. Added in 0.4.0.
  1084. **Supported dtypes**:
  1085. See :func:`~imgaug.augmenters.pillike.equalize_`.
  1086. Parameters
  1087. ----------
  1088. 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
  1089. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1090. name : None or str, optional
  1091. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1092. 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
  1093. Old name for parameter `seed`.
  1094. Its usage will not yet cause a deprecation warning,
  1095. but it is still recommended to use `seed` now.
  1096. Outdated since 0.4.0.
  1097. deterministic : bool, optional
  1098. Deprecated since 0.4.0.
  1099. See method ``to_deterministic()`` for an alternative and for
  1100. details about what the "deterministic mode" actually does.
  1101. Examples
  1102. --------
  1103. >>> import imgaug.augmenters as iaa
  1104. >>> aug = iaa.pillike.Equalize()
  1105. Equalize the histograms of all input images.
  1106. """
  1107. # Added in 0.4.0.
  1108. def __init__(self,
  1109. seed=None, name=None,
  1110. random_state="deprecated", deterministic="deprecated"):
  1111. super(Equalize, self).__init__(
  1112. seed=seed, name=name,
  1113. random_state=random_state, deterministic=deterministic)
  1114. # Added in 0.4.0.
  1115. def _augment_batch_(self, batch, random_state, parents, hooks):
  1116. # pylint: disable=no-self-use
  1117. if batch.images is not None:
  1118. for image in batch.images:
  1119. image[...] = equalize_(image)
  1120. return batch
  1121. # Added in 0.4.0.
  1122. def get_parameters(self):
  1123. """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
  1124. return []
  1125. class Autocontrast(contrastlib._ContrastFuncWrapper):
  1126. """Adjust contrast by cutting off ``p%`` of lowest/highest histogram values.
  1127. This augmenter has identical outputs to ``PIL.ImageOps.autocontrast``.
  1128. See :func:`~imgaug.augmenters.pillike.autocontrast` for more details.
  1129. Added in 0.4.0.
  1130. **Supported dtypes**:
  1131. See :func:`~imgaug.augmenters.pillike.autocontrast`.
  1132. Parameters
  1133. ----------
  1134. cutoff : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
  1135. Percentage of values to cut off from the low and high end of each
  1136. image's histogram, before stretching it to ``[0, 255]``.
  1137. * If ``int``: The value will be used for all images.
  1138. * If ``tuple`` ``(a, b)``: A value will be uniformly sampled from
  1139. the discrete interval ``[a..b]`` per image.
  1140. * If ``list``: A random value will be sampled from the list
  1141. per image.
  1142. * If ``StochasticParameter``: A value will be sampled from that
  1143. parameter per image.
  1144. per_channel : bool or float, optional
  1145. Whether to use the same value for all channels (``False``) or to
  1146. sample a new value for each channel (``True``). If this value is a
  1147. float ``p``, then for ``p`` percent of all images `per_channel` will
  1148. be treated as ``True``, otherwise as ``False``.
  1149. 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
  1150. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1151. name : None or str, optional
  1152. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1153. 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
  1154. Old name for parameter `seed`.
  1155. Its usage will not yet cause a deprecation warning,
  1156. but it is still recommended to use `seed` now.
  1157. Outdated since 0.4.0.
  1158. deterministic : bool, optional
  1159. Deprecated since 0.4.0.
  1160. See method ``to_deterministic()`` for an alternative and for
  1161. details about what the "deterministic mode" actually does.
  1162. Examples
  1163. --------
  1164. >>> import imgaug.augmenters as iaa
  1165. >>> aug = iaa.pillike.Autocontrast()
  1166. Modify the contrast of images by cutting off the ``0`` to ``20%`` lowest
  1167. and highest values from the histogram, then stretching it to full length.
  1168. >>> aug = iaa.pillike.Autocontrast((10, 20), per_channel=True)
  1169. Modify the contrast of images by cutting off the ``10`` to ``20%`` lowest
  1170. and highest values from the histogram, then stretching it to full length.
  1171. The cutoff value is sampled per *channel* instead of per *image*.
  1172. """
  1173. # pylint: disable=protected-access
  1174. # Added in 0.4.0.
  1175. def __init__(self, cutoff=(0, 20), per_channel=False,
  1176. seed=None, name=None,
  1177. random_state="deprecated", deterministic="deprecated"):
  1178. params1d = [
  1179. iap.handle_discrete_param(
  1180. cutoff, "cutoff", value_range=(0, 49), tuple_to_uniform=True,
  1181. list_to_choice=True)
  1182. ]
  1183. func = autocontrast
  1184. super(Autocontrast, self).__init__(
  1185. func, params1d, per_channel,
  1186. dtypes_allowed=["uint8"],
  1187. dtypes_disallowed=["uint16", "uint32", "uint64",
  1188. "int8", "int16", "int32", "int64",
  1189. "float16", "float32", "float64",
  1190. "float16", "float32", "float64", "float96",
  1191. "float128", "float256", "bool"],
  1192. seed=seed, name=name,
  1193. random_state=random_state, deterministic=deterministic)
  1194. # Added in 0.4.0.
  1195. class _EnhanceBase(meta.Augmenter):
  1196. # Added in 0.4.0.
  1197. def __init__(self, func, factor, factor_value_range,
  1198. seed=None, name=None,
  1199. random_state="deprecated", deterministic="deprecated"):
  1200. super(_EnhanceBase, self).__init__(
  1201. seed=seed, name=name,
  1202. random_state=random_state, deterministic=deterministic)
  1203. self.func = func
  1204. self.factor = iap.handle_continuous_param(
  1205. factor, "factor", value_range=factor_value_range,
  1206. tuple_to_uniform=True, list_to_choice=True)
  1207. # Added in 0.4.0.
  1208. def _augment_batch_(self, batch, random_state, parents, hooks):
  1209. if batch.images is None:
  1210. return batch
  1211. factors = self._draw_samples(len(batch.images), random_state)
  1212. for image, factor in zip(batch.images, factors):
  1213. image[...] = self.func(image, factor)
  1214. return batch
  1215. # Added in 0.4.0.
  1216. def _draw_samples(self, nb_rows, random_state):
  1217. return self.factor.draw_samples((nb_rows,), random_state=random_state)
  1218. # Added in 0.4.0.
  1219. def get_parameters(self):
  1220. """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
  1221. return [self.factor]
  1222. class EnhanceColor(_EnhanceBase):
  1223. """Convert images to grayscale.
  1224. This augmenter has identical outputs to ``PIL.ImageEnhance.Color``.
  1225. Added in 0.4.0.
  1226. **Supported dtypes**:
  1227. See :func:`~imgaug.augmenters.pillike.enhance_color`.
  1228. Parameters
  1229. ----------
  1230. factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1231. Colorfulness of the output image. Values close to ``0.0`` lead
  1232. to grayscale images, values above ``1.0`` increase the strength of
  1233. colors. Sane values are roughly in ``[0.0, 3.0]``.
  1234. * If ``number``: The value will be used for all images.
  1235. * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
  1236. image from the interval ``[a, b)``.
  1237. * If ``list``: A random value will be picked from the list per
  1238. image.
  1239. * If ``StochasticParameter``: Per batch of size ``N``, the
  1240. parameter will be queried once to return ``(N,)`` samples.
  1241. 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
  1242. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1243. name : None or str, optional
  1244. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1245. 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
  1246. Old name for parameter `seed`.
  1247. Its usage will not yet cause a deprecation warning,
  1248. but it is still recommended to use `seed` now.
  1249. Outdated since 0.4.0.
  1250. deterministic : bool, optional
  1251. Deprecated since 0.4.0.
  1252. See method ``to_deterministic()`` for an alternative and for
  1253. details about what the "deterministic mode" actually does.
  1254. Examples
  1255. --------
  1256. >>> import imgaug.augmenters as iaa
  1257. >>> aug = iaa.pillike.EnhanceColor()
  1258. Create an augmenter to remove a random fraction of color from
  1259. input images.
  1260. """
  1261. # Added in 0.4.0.
  1262. def __init__(self, factor=(0.0, 3.0),
  1263. seed=None, name=None,
  1264. random_state="deprecated", deterministic="deprecated"):
  1265. super(EnhanceColor, self).__init__(
  1266. func=enhance_color,
  1267. factor=factor,
  1268. factor_value_range=(0.0, None),
  1269. seed=seed, name=name,
  1270. random_state=random_state, deterministic=deterministic)
  1271. class EnhanceContrast(_EnhanceBase):
  1272. """Change the contrast of images.
  1273. This augmenter has identical outputs to ``PIL.ImageEnhance.Contrast``.
  1274. Added in 0.4.0.
  1275. **Supported dtypes**:
  1276. See :func:`~imgaug.augmenters.pillike.enhance_contrast`.
  1277. Parameters
  1278. ----------
  1279. factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1280. Strength of contrast in the image. Values below ``1.0`` decrease the
  1281. contrast, leading to a gray image around ``0.0``. Values
  1282. above ``1.0`` increase the contrast. Sane values are roughly in
  1283. ``[0.5, 1.5]``.
  1284. * If ``number``: The value will be used for all images.
  1285. * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
  1286. image from the interval ``[a, b)``.
  1287. * If ``list``: A random value will be picked from the list per
  1288. image.
  1289. * If ``StochasticParameter``: Per batch of size ``N``, the
  1290. parameter will be queried once to return ``(N,)`` samples.
  1291. 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
  1292. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1293. name : None or str, optional
  1294. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1295. 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
  1296. Old name for parameter `seed`.
  1297. Its usage will not yet cause a deprecation warning,
  1298. but it is still recommended to use `seed` now.
  1299. Outdated since 0.4.0.
  1300. deterministic : bool, optional
  1301. Deprecated since 0.4.0.
  1302. See method ``to_deterministic()`` for an alternative and for
  1303. details about what the "deterministic mode" actually does.
  1304. Examples
  1305. --------
  1306. >>> import imgaug.augmenters as iaa
  1307. >>> aug = iaa.pillike.EnhanceContrast()
  1308. Create an augmenter that worsens the contrast of an image by a random
  1309. factor.
  1310. """
  1311. # Added in 0.4.0.
  1312. def __init__(self, factor=(0.5, 1.5),
  1313. seed=None, name=None,
  1314. random_state="deprecated", deterministic="deprecated"):
  1315. super(EnhanceContrast, self).__init__(
  1316. func=enhance_contrast,
  1317. factor=factor,
  1318. factor_value_range=(0.0, None),
  1319. seed=seed, name=name,
  1320. random_state=random_state, deterministic=deterministic)
  1321. class EnhanceBrightness(_EnhanceBase):
  1322. """Change the brightness of images.
  1323. This augmenter has identical outputs to
  1324. ``PIL.ImageEnhance.Brightness``.
  1325. Added in 0.4.0.
  1326. **Supported dtypes**:
  1327. See :func:`~imgaug.augmenters.pillike.enhance_brightness`.
  1328. Parameters
  1329. ----------
  1330. factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1331. Brightness of the image. Values below ``1.0`` decrease the brightness,
  1332. leading to a black image around ``0.0``. Values above ``1.0`` increase
  1333. the brightness. Sane values are roughly in ``[0.5, 1.5]``.
  1334. * If ``number``: The value will be used for all images.
  1335. * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
  1336. image from the interval ``[a, b)``.
  1337. * If ``list``: A random value will be picked from the list per
  1338. image.
  1339. * If ``StochasticParameter``: Per batch of size ``N``, the
  1340. parameter will be queried once to return ``(N,)`` samples.
  1341. 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
  1342. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1343. name : None or str, optional
  1344. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1345. 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
  1346. Old name for parameter `seed`.
  1347. Its usage will not yet cause a deprecation warning,
  1348. but it is still recommended to use `seed` now.
  1349. Outdated since 0.4.0.
  1350. deterministic : bool, optional
  1351. Deprecated since 0.4.0.
  1352. See method ``to_deterministic()`` for an alternative and for
  1353. details about what the "deterministic mode" actually does.
  1354. Examples
  1355. --------
  1356. >>> import imgaug.augmenters as iaa
  1357. >>> aug = iaa.pillike.EnhanceBrightness()
  1358. Create an augmenter that worsens the brightness of an image by a random
  1359. factor.
  1360. """
  1361. # Added in 0.4.0.
  1362. def __init__(self, factor=(0.5, 1.5),
  1363. seed=None, name=None,
  1364. random_state="deprecated", deterministic="deprecated"):
  1365. super(EnhanceBrightness, self).__init__(
  1366. func=enhance_brightness,
  1367. factor=factor,
  1368. factor_value_range=(0.0, None),
  1369. seed=seed, name=name,
  1370. random_state=random_state, deterministic=deterministic)
  1371. class EnhanceSharpness(_EnhanceBase):
  1372. """Change the sharpness of images.
  1373. This augmenter has identical outputs to
  1374. ``PIL.ImageEnhance.Sharpness``.
  1375. Added in 0.4.0.
  1376. **Supported dtypes**:
  1377. See :func:`~imgaug.augmenters.pillike.enhance_sharpness`.
  1378. Parameters
  1379. ----------
  1380. factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1381. Sharpness of the image. Values below ``1.0`` decrease the sharpness,
  1382. values above ``1.0`` increase it. Sane values are roughly in
  1383. ``[0.0, 2.0]``.
  1384. * If ``number``: The value will be used for all images.
  1385. * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
  1386. image from the interval ``[a, b)``.
  1387. * If ``list``: A random value will be picked from the list per
  1388. image.
  1389. * If ``StochasticParameter``: Per batch of size ``N``, the
  1390. parameter will be queried once to return ``(N,)`` samples.
  1391. 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
  1392. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1393. name : None or str, optional
  1394. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1395. 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
  1396. Old name for parameter `seed`.
  1397. Its usage will not yet cause a deprecation warning,
  1398. but it is still recommended to use `seed` now.
  1399. Outdated since 0.4.0.
  1400. deterministic : bool, optional
  1401. Deprecated since 0.4.0.
  1402. See method ``to_deterministic()`` for an alternative and for
  1403. details about what the "deterministic mode" actually does.
  1404. Examples
  1405. --------
  1406. >>> import imgaug.augmenters as iaa
  1407. >>> aug = iaa.pillike.EnhanceSharpness()
  1408. Create an augmenter that randomly decreases or increases the sharpness
  1409. of an image.
  1410. """
  1411. # Added in 0.4.0.
  1412. def __init__(self, factor=(0.0, 2.0),
  1413. seed=None, name=None,
  1414. random_state="deprecated", deterministic="deprecated"):
  1415. super(EnhanceSharpness, self).__init__(
  1416. func=enhance_sharpness,
  1417. factor=factor,
  1418. factor_value_range=(0.0, None),
  1419. seed=seed, name=name,
  1420. random_state=random_state, deterministic=deterministic)
  1421. # Added in 0.4.0.
  1422. class _FilterBase(meta.Augmenter):
  1423. # Added in 0.4.0.
  1424. def __init__(self, func,
  1425. seed=None, name=None,
  1426. random_state="deprecated", deterministic="deprecated"):
  1427. super(_FilterBase, self).__init__(
  1428. seed=seed, name=name,
  1429. random_state=random_state, deterministic=deterministic)
  1430. self.func = func
  1431. # Added in 0.4.0.
  1432. def _augment_batch_(self, batch, random_state, parents, hooks):
  1433. if batch.images is not None:
  1434. for image in batch.images:
  1435. image[...] = self.func(image)
  1436. return batch
  1437. # Added in 0.4.0.
  1438. def get_parameters(self):
  1439. """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
  1440. return []
  1441. class FilterBlur(_FilterBase):
  1442. """Apply a blur filter kernel to images.
  1443. This augmenter has identical outputs to
  1444. calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.BLUR``.
  1445. Added in 0.4.0.
  1446. **Supported dtypes**:
  1447. See :func:`~imgaug.augmenters.pillike.filter_blur`.
  1448. Parameters
  1449. ----------
  1450. 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
  1451. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1452. name : None or str, optional
  1453. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1454. 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
  1455. Old name for parameter `seed`.
  1456. Its usage will not yet cause a deprecation warning,
  1457. but it is still recommended to use `seed` now.
  1458. Outdated since 0.4.0.
  1459. deterministic : bool, optional
  1460. Deprecated since 0.4.0.
  1461. See method ``to_deterministic()`` for an alternative and for
  1462. details about what the "deterministic mode" actually does.
  1463. Examples
  1464. --------
  1465. >>> import imgaug.augmenters as iaa
  1466. >>> aug = iaa.pillike.FilterBlur()
  1467. Create an augmenter that applies a blur filter kernel to images.
  1468. """
  1469. # Added in 0.4.0.
  1470. def __init__(self,
  1471. seed=None, name=None,
  1472. random_state="deprecated", deterministic="deprecated"):
  1473. super(FilterBlur, self).__init__(
  1474. func=filter_blur,
  1475. seed=seed, name=name,
  1476. random_state=random_state, deterministic=deterministic)
  1477. class FilterSmooth(_FilterBase):
  1478. """Apply a smoothening filter kernel to images.
  1479. This augmenter has identical outputs to
  1480. calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.SMOOTH``.
  1481. Added in 0.4.0.
  1482. **Supported dtypes**:
  1483. See :func:`~imgaug.augmenters.pillike.filter_smooth`.
  1484. Parameters
  1485. ----------
  1486. 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
  1487. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1488. name : None or str, optional
  1489. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1490. 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
  1491. Old name for parameter `seed`.
  1492. Its usage will not yet cause a deprecation warning,
  1493. but it is still recommended to use `seed` now.
  1494. Outdated since 0.4.0.
  1495. deterministic : bool, optional
  1496. Deprecated since 0.4.0.
  1497. See method ``to_deterministic()`` for an alternative and for
  1498. details about what the "deterministic mode" actually does.
  1499. Examples
  1500. --------
  1501. >>> import imgaug.augmenters as iaa
  1502. >>> aug = iaa.pillike.FilterSmooth()
  1503. Create an augmenter that applies a smoothening filter kernel to images.
  1504. """
  1505. # Added in 0.4.0.
  1506. def __init__(self,
  1507. seed=None, name=None,
  1508. random_state="deprecated", deterministic="deprecated"):
  1509. super(FilterSmooth, self).__init__(
  1510. func=filter_smooth,
  1511. seed=seed, name=name,
  1512. random_state=random_state, deterministic=deterministic)
  1513. class FilterSmoothMore(_FilterBase):
  1514. """Apply a strong smoothening filter kernel to images.
  1515. This augmenter has identical outputs to
  1516. calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.BLUR``.
  1517. Added in 0.4.0.
  1518. **Supported dtypes**:
  1519. See :func:`~imgaug.augmenters.pillike.filter_smooth_more`.
  1520. Parameters
  1521. ----------
  1522. 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
  1523. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1524. name : None or str, optional
  1525. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1526. 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
  1527. Old name for parameter `seed`.
  1528. Its usage will not yet cause a deprecation warning,
  1529. but it is still recommended to use `seed` now.
  1530. Outdated since 0.4.0.
  1531. deterministic : bool, optional
  1532. Deprecated since 0.4.0.
  1533. See method ``to_deterministic()`` for an alternative and for
  1534. details about what the "deterministic mode" actually does.
  1535. Examples
  1536. --------
  1537. >>> import imgaug.augmenters as iaa
  1538. >>> aug = iaa.pillike.FilterSmoothMore()
  1539. Create an augmenter that applies a strong smoothening filter kernel to
  1540. images.
  1541. """
  1542. # Added in 0.4.0.
  1543. def __init__(self,
  1544. seed=None, name=None,
  1545. random_state="deprecated", deterministic="deprecated"):
  1546. super(FilterSmoothMore, self).__init__(
  1547. func=filter_smooth_more,
  1548. seed=seed, name=name,
  1549. random_state=random_state, deterministic=deterministic)
  1550. class FilterEdgeEnhance(_FilterBase):
  1551. """Apply an edge enhance filter kernel to images.
  1552. This augmenter has identical outputs to
  1553. calling ``PIL.Image.filter`` with kernel
  1554. ``PIL.ImageFilter.EDGE_ENHANCE``.
  1555. Added in 0.4.0.
  1556. **Supported dtypes**:
  1557. See :func:`~imgaug.augmenters.pillike.filter_edge_enhance`.
  1558. Parameters
  1559. ----------
  1560. 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
  1561. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1562. name : None or str, optional
  1563. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1564. 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
  1565. Old name for parameter `seed`.
  1566. Its usage will not yet cause a deprecation warning,
  1567. but it is still recommended to use `seed` now.
  1568. Outdated since 0.4.0.
  1569. deterministic : bool, optional
  1570. Deprecated since 0.4.0.
  1571. See method ``to_deterministic()`` for an alternative and for
  1572. details about what the "deterministic mode" actually does.
  1573. Examples
  1574. --------
  1575. >>> import imgaug.augmenters as iaa
  1576. >>> aug = iaa.pillike.FilterEdgeEnhance()
  1577. Create an augmenter that applies a edge enhancement filter kernel to
  1578. images.
  1579. """
  1580. # Added in 0.4.0.
  1581. def __init__(self,
  1582. seed=None, name=None,
  1583. random_state="deprecated", deterministic="deprecated"):
  1584. super(FilterEdgeEnhance, self).__init__(
  1585. func=filter_edge_enhance,
  1586. seed=seed, name=name,
  1587. random_state=random_state, deterministic=deterministic)
  1588. class FilterEdgeEnhanceMore(_FilterBase):
  1589. """Apply a strong edge enhancement filter kernel to images.
  1590. This augmenter has identical outputs to
  1591. calling ``PIL.Image.filter`` with kernel
  1592. ``PIL.ImageFilter.EDGE_ENHANCE_MORE``.
  1593. Added in 0.4.0.
  1594. **Supported dtypes**:
  1595. See :func:`~imgaug.augmenters.pillike.filter_edge_enhance_more`.
  1596. Parameters
  1597. ----------
  1598. 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
  1599. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1600. name : None or str, optional
  1601. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1602. 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
  1603. Old name for parameter `seed`.
  1604. Its usage will not yet cause a deprecation warning,
  1605. but it is still recommended to use `seed` now.
  1606. Outdated since 0.4.0.
  1607. deterministic : bool, optional
  1608. Deprecated since 0.4.0.
  1609. See method ``to_deterministic()`` for an alternative and for
  1610. details about what the "deterministic mode" actually does.
  1611. Examples
  1612. --------
  1613. >>> import imgaug.augmenters as iaa
  1614. >>> aug = iaa.pillike.FilterEdgeEnhanceMore()
  1615. Create an augmenter that applies a strong edge enhancement filter kernel
  1616. to images.
  1617. """
  1618. # Added in 0.4.0.
  1619. def __init__(self,
  1620. seed=None, name=None,
  1621. random_state="deprecated", deterministic="deprecated"):
  1622. super(FilterEdgeEnhanceMore, self).__init__(
  1623. func=filter_edge_enhance_more,
  1624. seed=seed, name=name,
  1625. random_state=random_state, deterministic=deterministic)
  1626. class FilterFindEdges(_FilterBase):
  1627. """Apply a edge detection kernel to images.
  1628. This augmenter has identical outputs to
  1629. calling ``PIL.Image.filter`` with kernel
  1630. ``PIL.ImageFilter.FIND_EDGES``.
  1631. Added in 0.4.0.
  1632. **Supported dtypes**:
  1633. See :func:`~imgaug.augmenters.pillike.filter_find_edges`.
  1634. Parameters
  1635. ----------
  1636. 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
  1637. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1638. name : None or str, optional
  1639. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1640. 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
  1641. Old name for parameter `seed`.
  1642. Its usage will not yet cause a deprecation warning,
  1643. but it is still recommended to use `seed` now.
  1644. Outdated since 0.4.0.
  1645. deterministic : bool, optional
  1646. Deprecated since 0.4.0.
  1647. See method ``to_deterministic()`` for an alternative and for
  1648. details about what the "deterministic mode" actually does.
  1649. Examples
  1650. --------
  1651. >>> import imgaug.augmenters as iaa
  1652. >>> aug = iaa.pillike.FilterFindEdges()
  1653. Create an augmenter that applies an edge detection filter kernel to images.
  1654. """
  1655. # Added in 0.4.0.
  1656. def __init__(self,
  1657. seed=None, name=None,
  1658. random_state="deprecated", deterministic="deprecated"):
  1659. super(FilterFindEdges, self).__init__(
  1660. func=filter_find_edges,
  1661. seed=seed, name=name,
  1662. random_state=random_state, deterministic=deterministic)
  1663. class FilterContour(_FilterBase):
  1664. """Apply a contour detection filter kernel to images.
  1665. This augmenter has identical outputs to
  1666. calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.CONTOUR``.
  1667. Added in 0.4.0.
  1668. **Supported dtypes**:
  1669. See :func:`~imgaug.augmenters.pillike.filter_contour`.
  1670. Parameters
  1671. ----------
  1672. 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
  1673. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1674. name : None or str, optional
  1675. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1676. 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
  1677. Old name for parameter `seed`.
  1678. Its usage will not yet cause a deprecation warning,
  1679. but it is still recommended to use `seed` now.
  1680. Outdated since 0.4.0.
  1681. deterministic : bool, optional
  1682. Deprecated since 0.4.0.
  1683. See method ``to_deterministic()`` for an alternative and for
  1684. details about what the "deterministic mode" actually does.
  1685. Examples
  1686. --------
  1687. >>> import imgaug.augmenters as iaa
  1688. >>> aug = iaa.pillike.FilterContour()
  1689. Create an augmenter that applies a contour detection filter kernel to
  1690. images.
  1691. """
  1692. # Added in 0.4.0.
  1693. def __init__(self,
  1694. seed=None, name=None,
  1695. random_state="deprecated", deterministic="deprecated"):
  1696. super(FilterContour, self).__init__(
  1697. func=filter_contour,
  1698. seed=seed, name=name,
  1699. random_state=random_state, deterministic=deterministic)
  1700. class FilterEmboss(_FilterBase):
  1701. """Apply an emboss filter kernel to images.
  1702. This augmenter has identical outputs to
  1703. calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.EMBOSS``.
  1704. Added in 0.4.0.
  1705. **Supported dtypes**:
  1706. See :func:`~imgaug.augmenters.pillike.filter_emboss`.
  1707. Parameters
  1708. ----------
  1709. 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
  1710. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1711. name : None or str, optional
  1712. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1713. 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
  1714. Old name for parameter `seed`.
  1715. Its usage will not yet cause a deprecation warning,
  1716. but it is still recommended to use `seed` now.
  1717. Outdated since 0.4.0.
  1718. deterministic : bool, optional
  1719. Deprecated since 0.4.0.
  1720. See method ``to_deterministic()`` for an alternative and for
  1721. details about what the "deterministic mode" actually does.
  1722. Examples
  1723. --------
  1724. >>> import imgaug.augmenters as iaa
  1725. >>> aug = iaa.pillike.FilterEmboss()
  1726. Create an augmenter that applies an emboss filter kernel to images.
  1727. """
  1728. # Added in 0.4.0.
  1729. def __init__(self,
  1730. seed=None, name=None,
  1731. random_state="deprecated", deterministic="deprecated"):
  1732. super(FilterEmboss, self).__init__(
  1733. func=filter_emboss,
  1734. seed=seed, name=name,
  1735. random_state=random_state, deterministic=deterministic)
  1736. class FilterSharpen(_FilterBase):
  1737. """Apply a sharpening filter kernel to images.
  1738. This augmenter has identical outputs to
  1739. calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.SHARPEN``.
  1740. Added in 0.4.0.
  1741. **Supported dtypes**:
  1742. See :func:`~imgaug.augmenters.pillike.filter_sharpen`.
  1743. Parameters
  1744. ----------
  1745. 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
  1746. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1747. name : None or str, optional
  1748. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1749. 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
  1750. Old name for parameter `seed`.
  1751. Its usage will not yet cause a deprecation warning,
  1752. but it is still recommended to use `seed` now.
  1753. Outdated since 0.4.0.
  1754. deterministic : bool, optional
  1755. Deprecated since 0.4.0.
  1756. See method ``to_deterministic()`` for an alternative and for
  1757. details about what the "deterministic mode" actually does.
  1758. Examples
  1759. --------
  1760. >>> import imgaug.augmenters as iaa
  1761. >>> aug = iaa.pillike.FilterSharpen()
  1762. Create an augmenter that applies a sharpening filter kernel to images.
  1763. """
  1764. # Added in 0.4.0.
  1765. def __init__(self,
  1766. seed=None, name=None,
  1767. random_state="deprecated", deterministic="deprecated"):
  1768. super(FilterSharpen, self).__init__(
  1769. func=filter_sharpen,
  1770. seed=seed, name=name,
  1771. random_state=random_state, deterministic=deterministic)
  1772. class FilterDetail(_FilterBase):
  1773. """Apply a detail enhancement filter kernel to images.
  1774. This augmenter has identical outputs to
  1775. calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.DETAIL``.
  1776. Added in 0.4.0.
  1777. **Supported dtypes**:
  1778. See :func:`~imgaug.augmenters.pillike.filter_detail`.
  1779. Parameters
  1780. ----------
  1781. 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
  1782. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1783. name : None or str, optional
  1784. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1785. 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
  1786. Old name for parameter `seed`.
  1787. Its usage will not yet cause a deprecation warning,
  1788. but it is still recommended to use `seed` now.
  1789. Outdated since 0.4.0.
  1790. deterministic : bool, optional
  1791. Deprecated since 0.4.0.
  1792. See method ``to_deterministic()`` for an alternative and for
  1793. details about what the "deterministic mode" actually does.
  1794. Examples
  1795. --------
  1796. >>> import imgaug.augmenters as iaa
  1797. >>> aug = iaa.pillike.FilterDetail()
  1798. Create an augmenter that applies a detail enhancement filter kernel to
  1799. images.
  1800. """
  1801. # Added in 0.4.0.
  1802. def __init__(self,
  1803. seed=None, name=None,
  1804. random_state="deprecated", deterministic="deprecated"):
  1805. super(FilterDetail, self).__init__(
  1806. func=filter_detail,
  1807. seed=seed, name=name,
  1808. random_state=random_state, deterministic=deterministic)
  1809. class Affine(geometric.Affine):
  1810. """Apply PIL-like affine transformations to images.
  1811. This augmenter has identical outputs to
  1812. ``PIL.Image.transform`` with parameter ``method=PIL.Image.AFFINE``.
  1813. .. warning::
  1814. This augmenter can currently only transform image-data.
  1815. Batches containing heatmaps, segmentation maps and
  1816. coordinate-based augmentables will be rejected with an error.
  1817. Use :class:`~imgaug.augmenters.geometric.Affine` if you have to
  1818. transform such inputs.
  1819. .. note::
  1820. This augmenter uses the image center as the transformation center.
  1821. This has to be explicitly enforced in PIL using corresponding
  1822. translation matrices. Without such translation, PIL uses the image
  1823. top left corner as the transformation center. To mirror that
  1824. behaviour, use ``center=(0.0, 0.0)``.
  1825. Added in 0.4.0.
  1826. **Supported dtypes**:
  1827. See :func:`~imgaug.augmenters.pillike.warp_affine`.
  1828. Parameters
  1829. ----------
  1830. scale : number or tuple of number or list of number or imgaug.parameters.StochasticParameter or dict {"x": number/tuple/list/StochasticParameter, "y": number/tuple/list/StochasticParameter}, optional
  1831. See :class:`~imgaug.augmenters.geometric.Affine`.
  1832. translate_percent : None or number or tuple of number or list of number or imgaug.parameters.StochasticParameter or dict {"x": number/tuple/list/StochasticParameter, "y": number/tuple/list/StochasticParameter}, optional
  1833. See :class:`~imgaug.augmenters.geometric.Affine`.
  1834. translate_px : None or int or tuple of int or list of int or imgaug.parameters.StochasticParameter or dict {"x": int/tuple/list/StochasticParameter, "y": int/tuple/list/StochasticParameter}, optional
  1835. See :class:`~imgaug.augmenters.geometric.Affine`.
  1836. rotate : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
  1837. See :class:`~imgaug.augmenters.geometric.Affine`.
  1838. shear : number or tuple of number or list of number or imgaug.parameters.StochasticParameter or dict {"x": int/tuple/list/StochasticParameter, "y": int/tuple/list/StochasticParameter}, optional
  1839. See :class:`~imgaug.augmenters.geometric.Affine`.
  1840. fillcolor : number or tuple of number or list of number or imgaug.ALL or imgaug.parameters.StochasticParameter, optional
  1841. See parameter ``cval`` in :class:`~imgaug.augmenters.geometric.Affine`.
  1842. center : {'uniform', 'normal', 'center', 'left-top', 'left-center', 'left-bottom', 'center-top', 'center-center', 'center-bottom', 'right-top', 'right-center', 'right-bottom'} or tuple of float or StochasticParameter or tuple of StochasticParameter, optional
  1843. The center point of the affine transformation, given as relative
  1844. xy-coordinates.
  1845. Set this to ``(0.0, 0.0)`` or ``left-top`` to use the top left image
  1846. corner as the transformation center.
  1847. Set this to ``(0.5, 0.5)`` or ``center-center`` to use the image
  1848. center as the transformation center.
  1849. See also paramerer ``position`` in
  1850. :class:`~imgaug.augmenters.size.PadToFixedSize` for details
  1851. about valid datatypes of this parameter.
  1852. 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
  1853. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1854. name : None or str, optional
  1855. See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
  1856. 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
  1857. Old name for parameter `seed`.
  1858. Its usage will not yet cause a deprecation warning,
  1859. but it is still recommended to use `seed` now.
  1860. Outdated since 0.4.0.
  1861. deterministic : bool, optional
  1862. Deprecated since 0.4.0.
  1863. See method ``to_deterministic()`` for an alternative and for
  1864. details about what the "deterministic mode" actually does.
  1865. Examples
  1866. --------
  1867. >>> import imgaug.augmenters as iaa
  1868. >>> aug = iaa.pillike.Affine(scale={"x": (0.8, 1.2), "y": (0.5, 1.5)})
  1869. Create an augmenter that applies affine scaling (zoom in/out) to images.
  1870. Along the x-axis they are scaled to 80-120% of their size, along
  1871. the y-axis to 50-150% (both values randomly and uniformly chosen per
  1872. image).
  1873. >>> aug = iaa.pillike.Affine(translate_px={"x": 0, "y": [-10, 10]},
  1874. >>> fillcolor=128)
  1875. Create an augmenter that translates images along the y-axis by either
  1876. ``-10px`` or ``10px``. Newly created pixels are always filled with
  1877. the value ``128`` (along all channels).
  1878. >>> aug = iaa.pillike.Affine(rotate=(-20, 20), fillcolor=(0, 256))
  1879. Rotate an image by ``-20`` to ``20`` degress and fill up all newly
  1880. created pixels with a random RGB color.
  1881. See the similar augmenter :class:`~imgaug.augmenters.geometric.Affine`
  1882. for more examples.
  1883. """
  1884. # Added in 0.4.0.
  1885. def __init__(self, scale=1.0, translate_percent=None, translate_px=None,
  1886. rotate=0.0, shear=0.0, fillcolor=0, center=(0.5, 0.5),
  1887. seed=None, name=None,
  1888. random_state="deprecated", deterministic="deprecated"):
  1889. super(Affine, self).__init__(
  1890. scale=scale,
  1891. translate_percent=translate_percent,
  1892. translate_px=translate_px,
  1893. rotate=rotate,
  1894. shear=shear,
  1895. order=1,
  1896. cval=fillcolor,
  1897. mode="constant",
  1898. fit_output=False,
  1899. backend="auto",
  1900. seed=seed, name=name,
  1901. random_state=random_state, deterministic=deterministic)
  1902. # TODO move that func to iap
  1903. self.center = sizelib._handle_position_parameter(center)
  1904. # Added in 0.4.0.
  1905. def _augment_batch_(self, batch, random_state, parents, hooks):
  1906. cols = batch.get_column_names()
  1907. assert len(cols) == 0 or (len(cols) == 1 and "images" in cols), (
  1908. "pillike.Affine can currently only process image data. Got a "
  1909. "batch containing: %s. Use imgaug.augmenters.geometric.Affine for "
  1910. "batches containing non-image data." % (", ".join(cols),))
  1911. return super(Affine, self)._augment_batch_(
  1912. batch, random_state, parents, hooks)
  1913. # Added in 0.4.0.
  1914. def _augment_images_by_samples(self, images, samples,
  1915. image_shapes=None,
  1916. return_matrices=False):
  1917. assert return_matrices is False, (
  1918. "Got unexpectedly return_matrices=True. pillike.Affine does not "
  1919. "yet produce that output.")
  1920. for i, image in enumerate(images):
  1921. image_shape = (image.shape if image_shapes is None
  1922. else image_shapes[i])
  1923. params = samples.get_affine_parameters(
  1924. i, arr_shape=image_shape, image_shape=image_shape)
  1925. image[...] = warp_affine(
  1926. image,
  1927. scale_x=params["scale_x"],
  1928. scale_y=params["scale_y"],
  1929. translate_x_px=params["translate_x_px"],
  1930. translate_y_px=params["translate_y_px"],
  1931. rotate_deg=params["rotate_deg"],
  1932. shear_x_deg=params["shear_x_deg"],
  1933. shear_y_deg=params["shear_y_deg"],
  1934. fillcolor=tuple(samples.cval[i]),
  1935. center=(samples.center_x[i], samples.center_y[i])
  1936. )
  1937. return images
  1938. # Added in 0.4.0.
  1939. def _draw_samples(self, nb_samples, random_state):
  1940. # standard affine samples
  1941. samples = super(Affine, self)._draw_samples(nb_samples,
  1942. random_state)
  1943. # add samples for 'center' parameter, which is not yet a part of
  1944. # Affine
  1945. if isinstance(self.center, tuple):
  1946. xx = self.center[0].draw_samples(nb_samples,
  1947. random_state=random_state)
  1948. yy = self.center[1].draw_samples(nb_samples,
  1949. random_state=random_state)
  1950. else:
  1951. xy = self.center.draw_samples((nb_samples, 2),
  1952. random_state=random_state)
  1953. xx = xy[:, 0]
  1954. yy = xy[:, 1]
  1955. samples.center_x = xx
  1956. samples.center_y = yy
  1957. return samples
  1958. # Added in 0.4.0.
  1959. def get_parameters(self):
  1960. """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
  1961. return [
  1962. self.scale, self.translate, self.rotate, self.shear, self.cval,
  1963. self.center]