| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574 |
- """
- Augmenters that have identical outputs to well-known PIL functions.
- The ``like`` in ``pillike`` indicates that the augmenters in this module
- have identical outputs and mostly identical inputs to corresponding PIL
- functions, but do not *have to* wrap these functions internally. They may
- use internally different (e.g. faster) techniques to produce these outputs.
- Some of the augmenters in this module may also exist in other modules
- under similar name. These other augmenters may currently have the same
- outputs as the corresponding PIL functions, but that is not guaranteed
- for the future. Use the augmenters in this module if identical outputs
- to PIL are required.
- List of augmenters:
- * :class:`Solarize`
- * :class:`Posterize`
- * :class:`Equalize`
- * :class:`Autocontrast`
- * :class:`EnhanceColor`
- * :class:`EnhanceContrast`
- * :class:`EnhanceBrightness`
- * :class:`EnhanceSharpness`
- * :class:`FilterBlur`
- * :class:`FilterSmooth`
- * :class:`FilterSmoothMore`
- * :class:`FilterEdgeEnhance`
- * :class:`FilterEdgeEnhanceMore`
- * :class:`FilterFindEdges`
- * :class:`FilterContour`
- * :class:`FilterEmboss`
- * :class:`FilterSharpen`
- * :class:`FilterDetail`
- * :class:`Affine`
- Standard usage of these augmenters follows roughly the schema::
- import numpy as np
- import imgaug.augmenters as iaa
- aug = iaa.pillike.Affine(translate_px={"x": (-5, 5)})
- image = np.full((32, 32, 3), 255, dtype=np.uint8)
- images_aug = aug(images=[image, image, image])
- Added in 0.4.0.
- """
- from __future__ import print_function, division, absolute_import
- import six.moves as sm
- import numpy as np
- import cv2
- import PIL.Image
- import PIL.ImageOps
- import PIL.ImageEnhance
- import PIL.ImageFilter
- import imgaug as ia
- from imgaug.imgaug import _normalize_cv2_input_arr_
- from . import meta
- from . import arithmetic
- from . import color as colorlib
- from . import contrast as contrastlib
- from . import geometric
- from . import size as sizelib
- from .. import parameters as iap
- # TODO some of the augmenters in this module broke on numpy arrays as
- # image inputs (as opposed to lists of arrays) without any test failing
- # add appropriate tests for that
- _EQUALIZE_USE_PIL_BELOW = 64*64 # H*W
- # Added in 0.4.0.
- def _ensure_valid_shape(image, func_name):
- is_hw1 = image.ndim == 3 and image.shape[-1] == 1
- if is_hw1:
- image = image[:, :, 0]
- assert (
- image.ndim == 2
- or (image.ndim == 3 and image.shape[-1] in [3, 4])
- ), (
- "Can apply %s only to images of "
- "shape (H, W) or (H, W, 1) or (H, W, 3) or (H, W, 4). "
- "Got shape %s." % (func_name, image.shape,))
- return image, is_hw1
- def solarize_(image, threshold=128):
- """Invert all array components above a threshold in-place.
- This function has identical outputs to ``PIL.ImageOps.solarize``.
- It does however work in-place.
- Added in 0.4.0.
- **Supported dtypes**:
- See ``~imgaug.augmenters.arithmetic.invert_(min_value=None and max_value=None)``.
- Parameters
- ----------
- image : ndarray
- Image array of shape ``(H,W,[C])``.
- The array *might* be modified in-place.
- threshold : int, optional
- A threshold to use in order to invert only numbers above or below
- the threshold.
- Returns
- -------
- ndarray
- Inverted image.
- This *can* be the same array as input in `image`, modified in-place.
- """
- return arithmetic.invert_(image, threshold=threshold)
- def solarize(image, threshold=128):
- """Invert all array components above a threshold.
- This function has identical outputs to ``PIL.ImageOps.solarize``.
- Added in 0.4.0.
- **Supported dtypes**:
- See ``~imgaug.augmenters.arithmetic.invert_(min_value=None and max_value=None)``.
- Parameters
- ----------
- image : ndarray
- Image array of shape ``(H,W,[C])``.
- threshold : int, optional
- A threshold to use in order to invert only numbers above or below
- the threshold.
- Returns
- -------
- ndarray
- Inverted image.
- """
- return arithmetic.invert(image, threshold=threshold)
- def posterize_(image, bits):
- """Reduce the number of bits for each color channel in-place.
- This function has identical outputs to ``PIL.ImageOps.posterize``.
- It does however work in-place.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.color.quantize_uniform_to_n_bits_`.
- Parameters
- ----------
- image : ndarray
- Image array of shape ``(H,W,[C])``.
- bits : int
- The number of bits to keep per component.
- Values in the interval ``[1, 8]`` are valid.
- Returns
- -------
- ndarray
- Posterized image.
- This *can* be the same array as input in `image`, modified in-place.
- """
- return colorlib.posterize(image, bits)
- def posterize(image, bits):
- """Reduce the number of bits for each color channel.
- This function has identical outputs to ``PIL.ImageOps.posterize``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.color.quantize_uniform_to_n_bits`.
- Parameters
- ----------
- image : ndarray
- Image array of shape ``(H,W,[C])``.
- bits : int
- The number of bits to keep per component.
- Values in the interval ``[1, 8]`` are valid.
- Returns
- -------
- ndarray
- Posterized image.
- """
- return colorlib.posterize(image, bits)
- def equalize(image, mask=None):
- """Equalize the image histogram.
- See :func:`~imgaug.augmenters.pillike.equalize_` for details.
- This function is identical in inputs and outputs to
- ``PIL.ImageOps.equalize``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.equalize_`.
- Parameters
- ----------
- image : ndarray
- ``uint8`` ``(H,W,[C])`` image to equalize.
- mask : None or ndarray, optional
- An optional mask. If given, only the pixels selected by the mask are
- included in the analysis.
- Returns
- -------
- ndarray
- Equalized image.
- """
- # internally used method works in-place by default and hence needs a copy
- size = image.size
- if size == 0:
- return np.copy(image)
- if size >= _EQUALIZE_USE_PIL_BELOW:
- image = np.copy(image)
- return equalize_(image, mask)
- def equalize_(image, mask=None):
- """Equalize the image histogram in-place.
- This function applies a non-linear mapping to the input image, in order
- to create a uniform distribution of grayscale values in the output image.
- This function has identical outputs to ``PIL.ImageOps.equalize``.
- It does however work in-place.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- ``uint8`` ``(H,W,[C])`` image to equalize.
- mask : None or ndarray, optional
- An optional mask. If given, only the pixels selected by the mask are
- included in the analysis.
- Returns
- -------
- ndarray
- Equalized image. *Might* have been modified in-place.
- """
- nb_channels = 1 if image.ndim == 2 else image.shape[-1]
- if nb_channels not in [1, 3]:
- result = [equalize_(image[:, :, c])
- for c in np.arange(nb_channels)]
- return np.stack(result, axis=-1)
- assert image.dtype.name == "uint8", (
- "Expected image of dtype uint8, got dtype %s." % (image.dtype.name,))
- if mask is not None:
- assert mask.ndim == 2, (
- "Expected 2-dimensional mask, got shape %s." % (mask.shape,))
- assert mask.dtype.name == "uint8", (
- "Expected mask of dtype uint8, got dtype %s." % (mask.dtype.name,))
- size = image.size
- if size == 0:
- return image
- if nb_channels == 3 and size < _EQUALIZE_USE_PIL_BELOW:
- return _equalize_pil_(image, mask)
- return _equalize_no_pil_(image, mask)
- # note that this is supposed to be a non-PIL reimplementation of PIL's
- # equalize, which produces slightly different results from cv2.equalizeHist()
- # Added in 0.4.0.
- def _equalize_no_pil_(image, mask=None):
- nb_channels = 1 if image.ndim == 2 else image.shape[-1]
- # TODO remove the first axis, no longer needed
- lut = np.empty((1, 256, nb_channels), dtype=np.int32)
- for c_idx in range(nb_channels):
- if image.ndim == 2:
- image_c = image[:, :, np.newaxis]
- else:
- image_c = image[:, :, c_idx:c_idx+1]
- histo = cv2.calcHist(
- [_normalize_cv2_input_arr_(image_c)], [0], mask, [256], [0, 256])
- if len(histo.nonzero()[0]) <= 1:
- lut[0, :, c_idx] = np.arange(256).astype(np.int32)
- continue
- step = np.sum(histo[:-1]) // 255
- if not step:
- lut[0, :, c_idx] = np.arange(256).astype(np.int32)
- continue
- n = step // 2
- cumsum = np.cumsum(histo)
- lut[0, 0, c_idx] = n
- lut[0, 1:, c_idx] = n + cumsum[0:-1]
- lut[0, :, c_idx] //= int(step)
- lut = np.clip(lut, None, 255, out=lut).astype(np.uint8)
- image = ia.apply_lut_(image, lut)
- return image
- # Added in 0.4.0.
- def _equalize_pil_(image, mask=None):
- if mask is not None:
- mask = PIL.Image.fromarray(mask).convert("L")
- # don't return np.asarray(...) directly as its results are read-only
- image[...] = np.asarray(
- PIL.ImageOps.equalize(
- PIL.Image.fromarray(image),
- mask=mask
- )
- )
- return image
- def autocontrast(image, cutoff=0, ignore=None):
- """Maximize (normalize) image contrast.
- This function calculates a histogram of the input image, removes
- **cutoff** percent of the lightest and darkest pixels from the histogram,
- and remaps the image so that the darkest pixel becomes black (``0``), and
- the lightest becomes white (``255``).
- This function has identical outputs to ``PIL.ImageOps.autocontrast``.
- The speed is almost identical.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image for which to enhance the contrast.
- cutoff : number
- How many percent to cut off at the low and high end of the
- histogram. E.g. ``20`` will cut off the lowest and highest ``20%``
- of values. Expected value range is ``[0, 100]``.
- ignore : None or int or iterable of int
- Intensity values to ignore, i.e. to treat as background. If ``None``,
- no pixels will be ignored. Otherwise exactly the given intensity
- value(s) will be ignored.
- Returns
- -------
- ndarray
- Contrast-enhanced image.
- """
- assert image.dtype.name == "uint8", (
- "Can apply autocontrast only to uint8 images, got dtype %s." % (
- image.dtype.name,))
- if 0 in image.shape:
- return np.copy(image)
- standard_channels = (image.ndim == 2 or image.shape[2] == 3)
- if cutoff and standard_channels:
- return _autocontrast_pil(image, cutoff, ignore)
- return _autocontrast_no_pil(image, cutoff, ignore)
- # Added in 0.4.0.
- def _autocontrast_pil(image, cutoff, ignore):
- # don't return np.asarray(...) as its results are read-only
- return np.array(
- PIL.ImageOps.autocontrast(
- PIL.Image.fromarray(image),
- cutoff=cutoff, ignore=ignore
- )
- )
- # This function is only faster than the corresponding PIL function if no
- # cutoff is used.
- # C901 is "<functionname> is too complex"
- # Added in 0.4.0.
- def _autocontrast_no_pil(image, cutoff, ignore): # noqa: C901
- # pylint: disable=invalid-name
- if ignore is not None and not ia.is_iterable(ignore):
- ignore = [ignore]
- result = np.empty_like(image)
- if result.ndim == 2:
- result = result[..., np.newaxis]
- nb_channels = image.shape[2] if image.ndim >= 3 else 1
- for c_idx in sm.xrange(nb_channels):
- # using [0] instead of [int(c_idx)] allows this to work with >4
- # channels
- if image.ndim == 2:
- image_c = image[:, :, np.newaxis]
- else:
- image_c = image[:, :, c_idx:c_idx+1]
- h = cv2.calcHist(
- [_normalize_cv2_input_arr_(image_c)], [0], None, [256], [0, 256])
- if ignore is not None:
- h[ignore] = 0
- if cutoff:
- cs = np.cumsum(h)
- n = cs[-1]
- cut = n * cutoff // 100
- # remove cutoff% pixels from the low end
- lo_cut = cut - cs
- lo_cut_nz = np.nonzero(lo_cut <= 0.0)[0]
- if len(lo_cut_nz) == 0:
- lo = 255
- else:
- lo = lo_cut_nz[0]
- if lo > 0:
- h[:lo] = 0
- h[lo] = lo_cut[lo]
- # remove cutoff% samples from the hi end
- cs_rev = np.cumsum(h[::-1])
- hi_cut = cs_rev - cut
- hi_cut_nz = np.nonzero(hi_cut > 0.0)[0]
- if len(hi_cut_nz) == 0:
- hi = -1
- else:
- hi = 255 - hi_cut_nz[0]
- h[hi+1:] = 0
- if hi > -1:
- h[hi] = hi_cut[255-hi]
- # find lowest/highest samples after preprocessing
- for lo, lo_val in enumerate(h):
- if lo_val:
- break
- for hi in range(255, -1, -1):
- if h[hi]:
- break
- if hi <= lo:
- # don't bother
- lut = np.arange(256)
- else:
- scale = 255.0 / (hi - lo)
- offset = -lo * scale
- ix = np.arange(256).astype(np.float64) * scale + offset
- ix = np.clip(ix, 0, 255).astype(np.uint8)
- lut = ix
- lut = np.array(lut, dtype=np.uint8)
- # Vectorized implementation of above block.
- # This is overall slower.
- # h_nz = np.nonzero(h)[0]
- # if len(h_nz) <= 1:
- # lut = np.arange(256).astype(np.uint8)
- # else:
- # lo = h_nz[0]
- # hi = h_nz[-1]
- #
- # scale = 255.0 / (hi - lo)
- # offset = -lo * scale
- # ix = np.arange(256).astype(np.float64) * scale + offset
- # ix = np.clip(ix, 0, 255).astype(np.uint8)
- # lut = ix
- # TODO change to a single call instead of one per channel
- image_c_aug = ia.apply_lut(image_c, lut)
- result[:, :, c_idx:c_idx+1] = image_c_aug
- if image.ndim == 2:
- return result[..., 0]
- return result
- # Added in 0.4.0.
- def _apply_enhance_func(image, cls, factor):
- assert image.dtype.name == "uint8", (
- "Can apply PIL image enhancement only to uint8 images, "
- "got dtype %s." % (image.dtype.name,))
- if 0 in image.shape:
- return np.copy(image)
- image, is_hw1 = _ensure_valid_shape(
- image, "imgaug.augmenters.pillike.enhance_*()")
- # don't return np.asarray(...) as its results are read-only
- result = np.array(
- cls(
- PIL.Image.fromarray(image)
- ).enhance(factor)
- )
- if is_hw1:
- result = result[:, :, np.newaxis]
- return result
- def enhance_color(image, factor):
- """Change the strength of colors in an image.
- This function has identical outputs to
- ``PIL.ImageEnhance.Color``.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- factor : number
- Colorfulness of the output image. Values close to ``0.0`` lead
- to grayscale images, values above ``1.0`` increase the strength of
- colors. Sane values are roughly in ``[0.0, 3.0]``.
- Returns
- -------
- ndarray
- Color-modified image.
- """
- return _apply_enhance_func(image, PIL.ImageEnhance.Color, factor)
- def enhance_contrast(image, factor):
- """Change the contrast of an image.
- This function has identical outputs to
- ``PIL.ImageEnhance.Contrast``.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- factor : number
- Strength of contrast in the image. Values below ``1.0`` decrease the
- contrast, leading to a gray image around ``0.0``. Values
- above ``1.0`` increase the contrast. Sane values are roughly in
- ``[0.5, 1.5]``.
- Returns
- -------
- ndarray
- Contrast-modified image.
- """
- return _apply_enhance_func(image, PIL.ImageEnhance.Contrast, factor)
- def enhance_brightness(image, factor):
- """Change the brightness of images.
- This function has identical outputs to
- ``PIL.ImageEnhance.Brightness``.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- factor : number
- Brightness of the image. Values below ``1.0`` decrease the brightness,
- leading to a black image around ``0.0``. Values above ``1.0`` increase
- the brightness. Sane values are roughly in ``[0.5, 1.5]``.
- Returns
- -------
- ndarray
- Brightness-modified image.
- """
- return _apply_enhance_func(image, PIL.ImageEnhance.Brightness, factor)
- def enhance_sharpness(image, factor):
- """Change the sharpness of an image.
- This function has identical outputs to
- ``PIL.ImageEnhance.Sharpness``.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- factor : number
- Sharpness of the image. Values below ``1.0`` decrease the sharpness,
- values above ``1.0`` increase it. Sane values are roughly in
- ``[0.0, 2.0]``.
- Returns
- -------
- ndarray
- Sharpness-modified image.
- """
- return _apply_enhance_func(image, PIL.ImageEnhance.Sharpness, factor)
- # Added in 0.4.0.
- def _filter_by_kernel(image, kernel):
- assert image.dtype.name == "uint8", (
- "Can apply PIL filters only to uint8 images, "
- "got dtype %s." % (image.dtype.name,))
- if 0 in image.shape:
- return np.copy(image)
- image, is_hw1 = _ensure_valid_shape(
- image, "imgaug.augmenters.pillike.filter_*()")
- image_pil = PIL.Image.fromarray(image)
- image_filtered = image_pil.filter(kernel)
- # don't return np.asarray(...) as its results are read-only
- result = np.array(image_filtered)
- if is_hw1:
- result = result[:, :, np.newaxis]
- return result
- def filter_blur(image):
- """Apply a blur filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.BLUR`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Blurred image.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.BLUR)
- def filter_smooth(image):
- """Apply a smoothness filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.SMOOTH`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Smoothened image.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.SMOOTH)
- def filter_smooth_more(image):
- """Apply a strong smoothness filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.SMOOTH_MORE`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Smoothened image.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.SMOOTH_MORE)
- def filter_edge_enhance(image):
- """Apply an edge enhancement filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.EDGE_ENHANCE`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Image with enhanced edges.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.EDGE_ENHANCE)
- def filter_edge_enhance_more(image):
- """Apply a stronger edge enhancement filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.EDGE_ENHANCE_MORE``
- kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Smoothened image.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.EDGE_ENHANCE_MORE)
- def filter_find_edges(image):
- """Apply an edge detection filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.FIND_EDGES`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Image with detected edges.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.FIND_EDGES)
- def filter_contour(image):
- """Apply a contour filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.CONTOUR`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Image with pronounced contours.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.CONTOUR)
- def filter_emboss(image):
- """Apply an emboss filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.EMBOSS`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Embossed image.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.EMBOSS)
- def filter_sharpen(image):
- """Apply a sharpening filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.SHARPEN`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Sharpened image.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.SHARPEN)
- def filter_detail(image):
- """Apply a detail enhancement filter kernel to the image.
- This is the same as using PIL's ``PIL.ImageFilter.DETAIL`` kernel.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify.
- Returns
- -------
- ndarray
- Image with enhanced details.
- """
- return _filter_by_kernel(image, PIL.ImageFilter.DETAIL)
- # TODO unify this with the matrix generation for Affine,
- # there is probably no need to keep these separate
- # Added in 0.4.0.
- def _create_affine_matrix(scale_x=1.0, scale_y=1.0,
- translate_x_px=0, translate_y_px=0,
- rotate_deg=0,
- shear_x_deg=0, shear_y_deg=0,
- center_px=(0, 0)):
- scale_x = max(scale_x, 0.0001)
- scale_y = max(scale_y, 0.0001)
- rotate_rad, shear_x_rad, shear_y_rad = np.deg2rad([rotate_deg,
- shear_x_deg,
- shear_y_deg])
- rotate_rad = (-1) * rotate_rad
- matrix_centerize = np.array([
- [1, 0, (-1) * center_px[0]],
- [0, 1, (-1) * center_px[1]],
- [0, 0, 1]
- ], dtype=np.float32)
- matrix_scale = np.array([
- [scale_x, 0, 0],
- [0, scale_y, 0],
- [0, 0, 1]
- ], dtype=np.float32)
- matrix_translate = np.array([
- [1, 0, translate_x_px],
- [0, 1, translate_y_px],
- [0, 0, 1]
- ], dtype=np.float32)
- matrix_shear = np.array([
- [1, np.tanh(shear_x_rad), 0],
- [np.tanh(shear_y_rad), 1, 0],
- [0, 0, 1]
- ], dtype=np.float32)
- matrix_rotate = np.array([
- [np.cos(rotate_rad), np.sin(rotate_rad), 0],
- [-np.sin(rotate_rad), np.cos(rotate_rad), 0],
- [0, 0, 1]
- ], dtype=np.float32)
- matrix_decenterize = np.array([
- [1, 0, center_px[0]],
- [0, 1, center_px[1]],
- [0, 0, 1]
- ], dtype=np.float32)
- matrix = np.array([
- [1, 0, 0],
- [0, 1, 0],
- [0, 0, 1]
- ], dtype=np.float32)
- for other_matrix in [matrix_centerize,
- matrix_rotate, matrix_shear,
- matrix_scale, matrix_translate,
- matrix_decenterize]:
- matrix = np.matmul(other_matrix, matrix)
- matrix = np.linalg.inv(matrix)
- return matrix
- def warp_affine(image,
- scale_x=1.0, scale_y=1.0,
- translate_x_px=0, translate_y_px=0,
- rotate_deg=0,
- shear_x_deg=0, shear_y_deg=0,
- fillcolor=None,
- center=(0.5, 0.5)):
- """Apply an affine transformation to an image.
- This function has identical outputs to
- ``PIL.Image.transform`` with ``method=PIL.Image.AFFINE``.
- Added in 0.4.0.
- **Supported dtypes**:
- * ``uint8``: yes; fully tested
- * ``uint16``: no
- * ``uint32``: no
- * ``uint64``: no
- * ``int8``: no
- * ``int16``: no
- * ``int32``: no
- * ``int64``: no
- * ``float16``: no
- * ``float32``: no
- * ``float64``: no
- * ``float128``: no
- * ``bool``: no
- Parameters
- ----------
- image : ndarray
- The image to modify. Expected to be ``uint8`` with shape ``(H,W)``
- or ``(H,W,C)`` with ``C`` being ``3`` or ``4``.
- scale_x : number, optional
- Affine scale factor along the x-axis, where ``1.0`` denotes an
- identity transform and ``2.0`` is a strong zoom-in effect.
- scale_y : number, optional
- Affine scale factor along the y-axis, where ``1.0`` denotes an
- identity transform and ``2.0`` is a strong zoom-in effect.
- translate_x_px : number, optional
- Affine translation along the x-axis in pixels.
- Positive values translate the image towards the right.
- translate_y_px : number, optional
- Affine translation along the y-axis in pixels.
- Positive values translate the image towards the bottom.
- rotate_deg : number, optional
- Affine rotation in degrees *around the top left* of the image.
- shear_x_deg : number, optional
- Affine shearing in degrees along the x-axis with center point
- being the top-left of the image.
- shear_y_deg : number, optional
- Affine shearing in degrees along the y-axis with center point
- being the top-left of the image.
- fillcolor : None or int or tuple of int, optional
- Color tuple or intensity value to use when filling up newly
- created pixels. ``None`` fills with zeros. ``int`` will only fill
- the ``0`` th channel with that intensity value and all other channels
- with ``0`` (this is the default behaviour of PIL, use a tuple to
- fill all channels).
- center : tuple of number, optional
- Center xy-coordinate of the affine transformation, given as *relative*
- values, i.e. ``(0.0, 0.0)`` sets the transformation center to the
- top-left image corner, ``(1.0, 0.0)`` sets it to the the top-right
- image corner and ``(0.5, 0.5)`` sets it to the image center.
- The transformation center is relevant e.g. for rotations ("rotate
- around this center point"). PIL uses the image top-left corner
- as the transformation center if no centerization is included in the
- affine transformation matrix.
- Returns
- -------
- ndarray
- Image after affine transformation.
- """
- assert image.dtype.name == "uint8", (
- "Can apply PIL affine transformation only to uint8 images, "
- "got dtype %s." % (image.dtype.name,))
- if 0 in image.shape:
- return np.copy(image)
- fillcolor = fillcolor if fillcolor is not None else 0
- if ia.is_iterable(fillcolor):
- # make sure that iterable fillcolor contains only ints
- # otherwise we get a deprecation warning in py3.8
- fillcolor = tuple(map(int, fillcolor))
- image, is_hw1 = _ensure_valid_shape(
- image, "imgaug.augmenters.pillike.warp_affine()")
- image_pil = PIL.Image.fromarray(image)
- height, width = image.shape[0:2]
- center_px = (width * center[0], height * center[1])
- matrix = _create_affine_matrix(scale_x=scale_x,
- scale_y=scale_y,
- translate_x_px=translate_x_px,
- translate_y_px=translate_y_px,
- rotate_deg=rotate_deg,
- shear_x_deg=shear_x_deg,
- shear_y_deg=shear_y_deg,
- center_px=center_px)
- matrix = matrix[:2, :].flat
- # don't return np.asarray(...) as its results are read-only
- result = np.array(
- image_pil.transform(image_pil.size, PIL.Image.AFFINE, matrix,
- fillcolor=fillcolor)
- )
- if is_hw1:
- result = result[:, :, np.newaxis]
- return result
- # we don't use pil_solarize() here. but instead just subclass Invert,
- # which is easier and comes down to the same
- class Solarize(arithmetic.Invert):
- """Augmenter with identical outputs to PIL's ``solarize()`` function.
- This augmenter inverts all pixel values above a threshold.
- The outputs are identical to PIL's ``solarize()``.
- Added in 0.4.0.
- **Supported dtypes**:
- See ``~imgaug.augmenters.arithmetic.invert_(min_value=None and max_value=None)``.
- Parameters
- ----------
- p : float or imgaug.parameters.StochasticParameter, optional
- See :class:`~imgaug.augmenters.arithmetic.Invert`.
- threshold : None or number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
- See :class:`~imgaug.augmenters.arithmetic.Invert`.
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.Solarize(0.5, threshold=(32, 128))
- Invert the colors in ``50`` percent of all images for pixels with a
- value between ``32`` and ``128`` or more. The threshold is sampled once
- per image. The thresholding operation happens per channel.
- """
- def __init__(self, p=1.0, threshold=128,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(Solarize, self).__init__(
- p=p, per_channel=False,
- min_value=None, max_value=None,
- threshold=threshold, invert_above_threshold=True,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class Posterize(colorlib.Posterize):
- """Augmenter with identical outputs to PIL's ``posterize()`` function.
- This augmenter quantizes each array component to ``N`` bits.
- This class is currently an alias for
- :class:`~imgaug.augmenters.color.Posterize`, which again is an alias
- for :class:`~imgaug.augmenters.color.UniformColorQuantizationToNBits`,
- i.e. all three classes are right now guarantueed to have the same
- outputs as PIL's function.
- Added in 0.4.0.
- **Supported dtypes**:
- See :class:`~imgaug.augmenters.color.Posterize`.
- """
- class Equalize(meta.Augmenter):
- """Equalize the image histogram.
- This augmenter has identical outputs to ``PIL.ImageOps.equalize``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.equalize_`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.Equalize()
- Equalize the histograms of all input images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(Equalize, self).__init__(
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- # Added in 0.4.0.
- def _augment_batch_(self, batch, random_state, parents, hooks):
- # pylint: disable=no-self-use
- if batch.images is not None:
- for image in batch.images:
- image[...] = equalize_(image)
- return batch
- # Added in 0.4.0.
- def get_parameters(self):
- """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
- return []
- class Autocontrast(contrastlib._ContrastFuncWrapper):
- """Adjust contrast by cutting off ``p%`` of lowest/highest histogram values.
- This augmenter has identical outputs to ``PIL.ImageOps.autocontrast``.
- See :func:`~imgaug.augmenters.pillike.autocontrast` for more details.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.autocontrast`.
- Parameters
- ----------
- cutoff : int or tuple of int or list of int or imgaug.parameters.StochasticParameter, optional
- Percentage of values to cut off from the low and high end of each
- image's histogram, before stretching it to ``[0, 255]``.
- * If ``int``: The value will be used for all images.
- * If ``tuple`` ``(a, b)``: A value will be uniformly sampled from
- the discrete interval ``[a..b]`` per image.
- * If ``list``: A random value will be sampled from the list
- per image.
- * If ``StochasticParameter``: A value will be sampled from that
- parameter per image.
- per_channel : bool or float, optional
- Whether to use the same value for all channels (``False``) or to
- sample a new value for each channel (``True``). If this value is a
- float ``p``, then for ``p`` percent of all images `per_channel` will
- be treated as ``True``, otherwise as ``False``.
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.Autocontrast()
- Modify the contrast of images by cutting off the ``0`` to ``20%`` lowest
- and highest values from the histogram, then stretching it to full length.
- >>> aug = iaa.pillike.Autocontrast((10, 20), per_channel=True)
- Modify the contrast of images by cutting off the ``10`` to ``20%`` lowest
- and highest values from the histogram, then stretching it to full length.
- The cutoff value is sampled per *channel* instead of per *image*.
- """
- # pylint: disable=protected-access
- # Added in 0.4.0.
- def __init__(self, cutoff=(0, 20), per_channel=False,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- params1d = [
- iap.handle_discrete_param(
- cutoff, "cutoff", value_range=(0, 49), tuple_to_uniform=True,
- list_to_choice=True)
- ]
- func = autocontrast
- super(Autocontrast, self).__init__(
- func, params1d, per_channel,
- dtypes_allowed=["uint8"],
- dtypes_disallowed=["uint16", "uint32", "uint64",
- "int8", "int16", "int32", "int64",
- "float16", "float32", "float64",
- "float16", "float32", "float64", "float96",
- "float128", "float256", "bool"],
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- # Added in 0.4.0.
- class _EnhanceBase(meta.Augmenter):
- # Added in 0.4.0.
- def __init__(self, func, factor, factor_value_range,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(_EnhanceBase, self).__init__(
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- self.func = func
- self.factor = iap.handle_continuous_param(
- factor, "factor", value_range=factor_value_range,
- tuple_to_uniform=True, list_to_choice=True)
- # Added in 0.4.0.
- def _augment_batch_(self, batch, random_state, parents, hooks):
- if batch.images is None:
- return batch
- factors = self._draw_samples(len(batch.images), random_state)
- for image, factor in zip(batch.images, factors):
- image[...] = self.func(image, factor)
- return batch
- # Added in 0.4.0.
- def _draw_samples(self, nb_rows, random_state):
- return self.factor.draw_samples((nb_rows,), random_state=random_state)
- # Added in 0.4.0.
- def get_parameters(self):
- """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
- return [self.factor]
- class EnhanceColor(_EnhanceBase):
- """Convert images to grayscale.
- This augmenter has identical outputs to ``PIL.ImageEnhance.Color``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.enhance_color`.
- Parameters
- ----------
- factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
- Colorfulness of the output image. Values close to ``0.0`` lead
- to grayscale images, values above ``1.0`` increase the strength of
- colors. Sane values are roughly in ``[0.0, 3.0]``.
- * If ``number``: The value will be used for all images.
- * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
- image from the interval ``[a, b)``.
- * If ``list``: A random value will be picked from the list per
- image.
- * If ``StochasticParameter``: Per batch of size ``N``, the
- parameter will be queried once to return ``(N,)`` samples.
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.EnhanceColor()
- Create an augmenter to remove a random fraction of color from
- input images.
- """
- # Added in 0.4.0.
- def __init__(self, factor=(0.0, 3.0),
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(EnhanceColor, self).__init__(
- func=enhance_color,
- factor=factor,
- factor_value_range=(0.0, None),
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class EnhanceContrast(_EnhanceBase):
- """Change the contrast of images.
- This augmenter has identical outputs to ``PIL.ImageEnhance.Contrast``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.enhance_contrast`.
- Parameters
- ----------
- factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
- Strength of contrast in the image. Values below ``1.0`` decrease the
- contrast, leading to a gray image around ``0.0``. Values
- above ``1.0`` increase the contrast. Sane values are roughly in
- ``[0.5, 1.5]``.
- * If ``number``: The value will be used for all images.
- * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
- image from the interval ``[a, b)``.
- * If ``list``: A random value will be picked from the list per
- image.
- * If ``StochasticParameter``: Per batch of size ``N``, the
- parameter will be queried once to return ``(N,)`` samples.
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.EnhanceContrast()
- Create an augmenter that worsens the contrast of an image by a random
- factor.
- """
- # Added in 0.4.0.
- def __init__(self, factor=(0.5, 1.5),
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(EnhanceContrast, self).__init__(
- func=enhance_contrast,
- factor=factor,
- factor_value_range=(0.0, None),
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class EnhanceBrightness(_EnhanceBase):
- """Change the brightness of images.
- This augmenter has identical outputs to
- ``PIL.ImageEnhance.Brightness``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.enhance_brightness`.
- Parameters
- ----------
- factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
- Brightness of the image. Values below ``1.0`` decrease the brightness,
- leading to a black image around ``0.0``. Values above ``1.0`` increase
- the brightness. Sane values are roughly in ``[0.5, 1.5]``.
- * If ``number``: The value will be used for all images.
- * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
- image from the interval ``[a, b)``.
- * If ``list``: A random value will be picked from the list per
- image.
- * If ``StochasticParameter``: Per batch of size ``N``, the
- parameter will be queried once to return ``(N,)`` samples.
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.EnhanceBrightness()
- Create an augmenter that worsens the brightness of an image by a random
- factor.
- """
- # Added in 0.4.0.
- def __init__(self, factor=(0.5, 1.5),
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(EnhanceBrightness, self).__init__(
- func=enhance_brightness,
- factor=factor,
- factor_value_range=(0.0, None),
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class EnhanceSharpness(_EnhanceBase):
- """Change the sharpness of images.
- This augmenter has identical outputs to
- ``PIL.ImageEnhance.Sharpness``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.enhance_sharpness`.
- Parameters
- ----------
- factor : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
- Sharpness of the image. Values below ``1.0`` decrease the sharpness,
- values above ``1.0`` increase it. Sane values are roughly in
- ``[0.0, 2.0]``.
- * If ``number``: The value will be used for all images.
- * If ``tuple`` ``(a, b)``: A value will be uniformly sampled per
- image from the interval ``[a, b)``.
- * If ``list``: A random value will be picked from the list per
- image.
- * If ``StochasticParameter``: Per batch of size ``N``, the
- parameter will be queried once to return ``(N,)`` samples.
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.EnhanceSharpness()
- Create an augmenter that randomly decreases or increases the sharpness
- of an image.
- """
- # Added in 0.4.0.
- def __init__(self, factor=(0.0, 2.0),
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(EnhanceSharpness, self).__init__(
- func=enhance_sharpness,
- factor=factor,
- factor_value_range=(0.0, None),
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- # Added in 0.4.0.
- class _FilterBase(meta.Augmenter):
- # Added in 0.4.0.
- def __init__(self, func,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(_FilterBase, self).__init__(
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- self.func = func
- # Added in 0.4.0.
- def _augment_batch_(self, batch, random_state, parents, hooks):
- if batch.images is not None:
- for image in batch.images:
- image[...] = self.func(image)
- return batch
- # Added in 0.4.0.
- def get_parameters(self):
- """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
- return []
- class FilterBlur(_FilterBase):
- """Apply a blur filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.BLUR``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_blur`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterBlur()
- Create an augmenter that applies a blur filter kernel to images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterBlur, self).__init__(
- func=filter_blur,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterSmooth(_FilterBase):
- """Apply a smoothening filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.SMOOTH``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_smooth`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterSmooth()
- Create an augmenter that applies a smoothening filter kernel to images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterSmooth, self).__init__(
- func=filter_smooth,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterSmoothMore(_FilterBase):
- """Apply a strong smoothening filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.BLUR``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_smooth_more`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterSmoothMore()
- Create an augmenter that applies a strong smoothening filter kernel to
- images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterSmoothMore, self).__init__(
- func=filter_smooth_more,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterEdgeEnhance(_FilterBase):
- """Apply an edge enhance filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel
- ``PIL.ImageFilter.EDGE_ENHANCE``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_edge_enhance`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterEdgeEnhance()
- Create an augmenter that applies a edge enhancement filter kernel to
- images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterEdgeEnhance, self).__init__(
- func=filter_edge_enhance,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterEdgeEnhanceMore(_FilterBase):
- """Apply a strong edge enhancement filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel
- ``PIL.ImageFilter.EDGE_ENHANCE_MORE``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_edge_enhance_more`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterEdgeEnhanceMore()
- Create an augmenter that applies a strong edge enhancement filter kernel
- to images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterEdgeEnhanceMore, self).__init__(
- func=filter_edge_enhance_more,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterFindEdges(_FilterBase):
- """Apply a edge detection kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel
- ``PIL.ImageFilter.FIND_EDGES``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_find_edges`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterFindEdges()
- Create an augmenter that applies an edge detection filter kernel to images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterFindEdges, self).__init__(
- func=filter_find_edges,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterContour(_FilterBase):
- """Apply a contour detection filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.CONTOUR``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_contour`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterContour()
- Create an augmenter that applies a contour detection filter kernel to
- images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterContour, self).__init__(
- func=filter_contour,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterEmboss(_FilterBase):
- """Apply an emboss filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.EMBOSS``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_emboss`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterEmboss()
- Create an augmenter that applies an emboss filter kernel to images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterEmboss, self).__init__(
- func=filter_emboss,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterSharpen(_FilterBase):
- """Apply a sharpening filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.SHARPEN``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_sharpen`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterSharpen()
- Create an augmenter that applies a sharpening filter kernel to images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterSharpen, self).__init__(
- func=filter_sharpen,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class FilterDetail(_FilterBase):
- """Apply a detail enhancement filter kernel to images.
- This augmenter has identical outputs to
- calling ``PIL.Image.filter`` with kernel ``PIL.ImageFilter.DETAIL``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.filter_detail`.
- Parameters
- ----------
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.FilterDetail()
- Create an augmenter that applies a detail enhancement filter kernel to
- images.
- """
- # Added in 0.4.0.
- def __init__(self,
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(FilterDetail, self).__init__(
- func=filter_detail,
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- class Affine(geometric.Affine):
- """Apply PIL-like affine transformations to images.
- This augmenter has identical outputs to
- ``PIL.Image.transform`` with parameter ``method=PIL.Image.AFFINE``.
- .. warning::
- This augmenter can currently only transform image-data.
- Batches containing heatmaps, segmentation maps and
- coordinate-based augmentables will be rejected with an error.
- Use :class:`~imgaug.augmenters.geometric.Affine` if you have to
- transform such inputs.
- .. note::
- This augmenter uses the image center as the transformation center.
- This has to be explicitly enforced in PIL using corresponding
- translation matrices. Without such translation, PIL uses the image
- top left corner as the transformation center. To mirror that
- behaviour, use ``center=(0.0, 0.0)``.
- Added in 0.4.0.
- **Supported dtypes**:
- See :func:`~imgaug.augmenters.pillike.warp_affine`.
- Parameters
- ----------
- 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
- See :class:`~imgaug.augmenters.geometric.Affine`.
- 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
- See :class:`~imgaug.augmenters.geometric.Affine`.
- 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
- See :class:`~imgaug.augmenters.geometric.Affine`.
- rotate : number or tuple of number or list of number or imgaug.parameters.StochasticParameter, optional
- See :class:`~imgaug.augmenters.geometric.Affine`.
- 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
- See :class:`~imgaug.augmenters.geometric.Affine`.
- fillcolor : number or tuple of number or list of number or imgaug.ALL or imgaug.parameters.StochasticParameter, optional
- See parameter ``cval`` in :class:`~imgaug.augmenters.geometric.Affine`.
- 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
- The center point of the affine transformation, given as relative
- xy-coordinates.
- Set this to ``(0.0, 0.0)`` or ``left-top`` to use the top left image
- corner as the transformation center.
- Set this to ``(0.5, 0.5)`` or ``center-center`` to use the image
- center as the transformation center.
- See also paramerer ``position`` in
- :class:`~imgaug.augmenters.size.PadToFixedSize` for details
- about valid datatypes of this parameter.
- 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
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- name : None or str, optional
- See :func:`~imgaug.augmenters.meta.Augmenter.__init__`.
- 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
- Old name for parameter `seed`.
- Its usage will not yet cause a deprecation warning,
- but it is still recommended to use `seed` now.
- Outdated since 0.4.0.
- deterministic : bool, optional
- Deprecated since 0.4.0.
- See method ``to_deterministic()`` for an alternative and for
- details about what the "deterministic mode" actually does.
- Examples
- --------
- >>> import imgaug.augmenters as iaa
- >>> aug = iaa.pillike.Affine(scale={"x": (0.8, 1.2), "y": (0.5, 1.5)})
- Create an augmenter that applies affine scaling (zoom in/out) to images.
- Along the x-axis they are scaled to 80-120% of their size, along
- the y-axis to 50-150% (both values randomly and uniformly chosen per
- image).
- >>> aug = iaa.pillike.Affine(translate_px={"x": 0, "y": [-10, 10]},
- >>> fillcolor=128)
- Create an augmenter that translates images along the y-axis by either
- ``-10px`` or ``10px``. Newly created pixels are always filled with
- the value ``128`` (along all channels).
- >>> aug = iaa.pillike.Affine(rotate=(-20, 20), fillcolor=(0, 256))
- Rotate an image by ``-20`` to ``20`` degress and fill up all newly
- created pixels with a random RGB color.
- See the similar augmenter :class:`~imgaug.augmenters.geometric.Affine`
- for more examples.
- """
- # Added in 0.4.0.
- def __init__(self, scale=1.0, translate_percent=None, translate_px=None,
- rotate=0.0, shear=0.0, fillcolor=0, center=(0.5, 0.5),
- seed=None, name=None,
- random_state="deprecated", deterministic="deprecated"):
- super(Affine, self).__init__(
- scale=scale,
- translate_percent=translate_percent,
- translate_px=translate_px,
- rotate=rotate,
- shear=shear,
- order=1,
- cval=fillcolor,
- mode="constant",
- fit_output=False,
- backend="auto",
- seed=seed, name=name,
- random_state=random_state, deterministic=deterministic)
- # TODO move that func to iap
- self.center = sizelib._handle_position_parameter(center)
- # Added in 0.4.0.
- def _augment_batch_(self, batch, random_state, parents, hooks):
- cols = batch.get_column_names()
- assert len(cols) == 0 or (len(cols) == 1 and "images" in cols), (
- "pillike.Affine can currently only process image data. Got a "
- "batch containing: %s. Use imgaug.augmenters.geometric.Affine for "
- "batches containing non-image data." % (", ".join(cols),))
- return super(Affine, self)._augment_batch_(
- batch, random_state, parents, hooks)
- # Added in 0.4.0.
- def _augment_images_by_samples(self, images, samples,
- image_shapes=None,
- return_matrices=False):
- assert return_matrices is False, (
- "Got unexpectedly return_matrices=True. pillike.Affine does not "
- "yet produce that output.")
- for i, image in enumerate(images):
- image_shape = (image.shape if image_shapes is None
- else image_shapes[i])
- params = samples.get_affine_parameters(
- i, arr_shape=image_shape, image_shape=image_shape)
- image[...] = warp_affine(
- image,
- scale_x=params["scale_x"],
- scale_y=params["scale_y"],
- translate_x_px=params["translate_x_px"],
- translate_y_px=params["translate_y_px"],
- rotate_deg=params["rotate_deg"],
- shear_x_deg=params["shear_x_deg"],
- shear_y_deg=params["shear_y_deg"],
- fillcolor=tuple(samples.cval[i]),
- center=(samples.center_x[i], samples.center_y[i])
- )
- return images
- # Added in 0.4.0.
- def _draw_samples(self, nb_samples, random_state):
- # standard affine samples
- samples = super(Affine, self)._draw_samples(nb_samples,
- random_state)
- # add samples for 'center' parameter, which is not yet a part of
- # Affine
- if isinstance(self.center, tuple):
- xx = self.center[0].draw_samples(nb_samples,
- random_state=random_state)
- yy = self.center[1].draw_samples(nb_samples,
- random_state=random_state)
- else:
- xy = self.center.draw_samples((nb_samples, 2),
- random_state=random_state)
- xx = xy[:, 0]
- yy = xy[:, 1]
- samples.center_x = xx
- samples.center_y = yy
- return samples
- # Added in 0.4.0.
- def get_parameters(self):
- """See :func:`~imgaug.augmenters.meta.Augmenter.get_parameters`."""
- return [
- self.scale, self.translate, self.rotate, self.shear, self.cval,
- self.center]
|