2D intensity transforms#
Transforms that change pixel values but keep every pixel where it is, so masks, boxes and keypoints pass through
unchanged. With default arguments, 24 of the 37 transforms on this page clamp their output to [0, 1]. These 13
do not: the four blurs, RandomGaussianNoise, RandomSaltAndPepperNoise, RandomGrayscale, RandomInvert,
RandomChannelShuffle, RandomChannelDropout, RandomRain, Normalize and Denormalize.
ColorJiggle and ColorJitter both jitter brightness, contrast, saturation and hue; ColorJitter uses
torchvision’s formulas. RandomEqualize equalizes whole channels, RandomClahe local tiles.
- class kornia.augmentation.ColorJiggle(brightness=0.0, contrast=0.0, saturation=0.0, hue=0.0, same_on_batch=False, p=1.0, keepdim=False, order=None)[source]#
Jiggle color with Kornia’s additive-brightness and HSV formulas.
output = ColorJiggle(brightness, contrast, saturation, hue)(input)applies a sampled order of enabled color steps. UseColorJitterwhen reproducing torchvision’s multiplicative and grayscale-blend formulas.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation. Default:1.0brightness (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The brightness factor to apply. Default:0.0contrast (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The contrast factor to apply. Default:0.0saturation (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The saturation factor to apply. Default:0.0hue (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The hue factor to apply. Default:0.0same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:Falseorder (
Optional[Sequence[int]], optional) – a fixed application order, as indices into (brightness, contrast, saturation, hue); a subset applies only those, and a repeated index raisesValueError.None(the default) draws a random order on every call. A fixed order makes the transformtorch.compilefullgraph-safe for RGB inputs. The parameter generator still draws anorderentry into_params, and with a fixed order that entry is ignored, including on replay. Default:None
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the steps use kornia’s own primitives: brightness is additive (the drawn factor is re-based to
factor - 1forkornia.enhance.adjust_brightness(), asRandomBrightnessdoes), contrast scales the raw values (kornia.enhance.adjust_contrast()), saturation scales the HSV saturation (kornia.enhance.adjust_saturation()) and hue shifts by turns of the hue circle (kornia.enhance.adjust_hue()).ColorJitteruses torchvision’s blend formulas for the first three instead, so the two classes give different outputs for the same factors.with matching effective bounds and the default CPU sampler, this class and
ColorJitterdraw the same factors and the sameorderfrom the same seed. The drawnorderis shared by the whole batch; without a fixedorderargument, anordertensor passed as a forward keyword or in replayedparamsreplaces it.brightnessis bounded to[0, 2]in both argument forms:(0.0, 3.0)and the scalar1.5, whose implied range reaches2.5, raise at construction, whereColorJitteraccepts either.a step is skipped when every drawn factor in the batch is neutral, so
ColorJiggle(0, 0, 0, 0)is the identity for an input in[0, 1]. The channel count only has to suit the steps that run: saturation and hue need three channels; a brightness- or contrast-only configuration accepts any. The input and final RGB result are clamped even when every step is neutral.
Note
This function internally uses
kornia.enhance.adjust_brightness(),kornia.enhance.adjust_contrast().kornia.enhance.adjust_saturation(),kornia.enhance.adjust_hue().See also
ColorJitter: torchvision-compatible alternative with different brightness, contrast and saturation.RandomBrightness: applies only the additive brightness step.RandomHue: applies only an HSV hue rotation.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.ones(1, 3, 3, 3) >>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.) >>> aug(inputs) tensor([[[[0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993]], [[0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993]], [[0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.ColorJitter(brightness=0.0, contrast=0.0, saturation=0.0, hue=0.0, same_on_batch=False, p=1.0, keepdim=False, order=None)[source]#
Randomly adjust brightness, contrast, saturation and hue using torchvision-compatible formulas.
output = ColorJitter(brightness, contrast, saturation, hue)(input)applies four sampled adjustments in a sampled or fixed order using torchvision’s formulas. Brightness multiplies the image by a factor, contrast blends it with its grayscale mean, saturation blends it with its grayscale, and hue uses torchvision’sadjust_hueshift. Use this class to porttorchvision.transforms.ColorJittercode; it is not actively maintained, so preferColorJigglefor new code.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
brightness (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The brightness factor to apply. Default:0.0contrast (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The contrast factor to apply. Default:0.0saturation (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The saturation factor to apply. Default:0.0hue (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The hue factor to apply. Default:0.0same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation. Default:1.0keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:Falseorder (
Optional[Sequence[int]], optional) – a fixed application order, as indices into (brightness, contrast, saturation, hue); a subset applies only those, and a repeated index raisesValueError.None(the default) draws a random order on every call. A fixed order makes the transformtorch.compilefullgraph-safe for RGB inputs. The parameter generator still draws anorderentry into_params, and with a fixed order that entry is ignored, including on replay. Default:None
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.see
ColorJigglefor how the two classes relate. This class takes the brightness factor as drawn, a multiplier whose identity is1, and a scalarbrightnessabove1draws from[0, 1 + brightness], as torchvision does.a step is skipped when every factor in the batch equals its neutral value –
1for brightness, contrast and saturation,0for hue – so a skipped step accepts any channel count. Otherwise the step runs on the whole batch, and the brightness, contrast and (three-channel) saturation steps clamp the whole batch into[0, 1]. A fixedorderwithout index0skips the brightness step.
Note
This function internally uses
kornia.enhance.adjust_brightness_accumulative(),kornia.enhance.adjust_contrast_with_mean_subtraction(),kornia.enhance.adjust_saturation_with_gray_subtraction(),kornia.enhance.adjust_hue().See also
ColorJiggle: Kornia’s alternative with additive brightness and raw-value contrast.RandomBrightness: applies Kornia’s additive brightness alone.RandomSaturation: applies HSV saturation scaling alone.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.ones(1, 3, 3, 3) >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.) >>> aug(inputs) tensor([[[[0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993]], [[0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993]], [[0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993], [0.9993, 0.9993, 0.9993]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomAutoContrast(clip_output=None, same_on_batch=False, p=1.0, keepdim=False)[source]#
Rescale each selected image channel from its own minimum to maximum.
output = RandomAutoContrast()(input)maps each selected channel into[0, 1]from its observed extrema.See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation. Default:1.0clip_output (
Optional[bool], optional) – deprecated since 0.9.1 and ignored; passing it emits aDeprecationWarning, and it will be removed in a future release.kornia.enhance.normalize_min_max()already maps each sample’s channels onto[0, 1]. See #4436. Default:Nonesame_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the output is
kornia.enhance.normalize_min_max()of the input: each channel of each sample is rescaled by its own minimum and maximum as(x - min) / (max - min + 1e-6). This is a rescale, not a clamp, so an input outside[0, 1]is mapped into range rather than clipped, and a constant channel comes back as zeros. Empty batches preserve their shape, dtype and device.
See also
RandomContrast: applies a sampled multiplicative factor instead of input-dependent rescaling.Normalize: applies supplied channel statistics instead of observed extrema.
- class kornia.augmentation.RandomBoxBlur(kernel_size=(3, 3), border_type='reflect', normalized=True, same_on_batch=False, p=0.5, keepdim=False)[source]#
Blur images with a box filter, applied per sample with probability
p(default 0.5).output = RandomBoxBlur(kernel_size, ...)(input)replaces every pixel in each selected image of shape(B, C, H, W)with a rectangular-window mean.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
kernel_size (
Tuple[int,int], optional) – the blurring kernel size. Default:(3, 3)border_type (
Union[int,str,BorderType], optional) – the padding mode to be applied before convolving. The expected modes are:constant,reflect,replicateorcircular, given as a case-insensitive string, aBorderTypemember or its integer value (CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3). Default:"reflect"normalized (
bool, optional) – selects the implementation ofkornia.filters.box_blur():Truecomputes the blur as two 1D passes (separable=True),Falseas one 2D pass. The kernel is L1-normalized either way, so both return the mean of each window, never its sum, and differ only by float rounding. Default:Truesame_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].kernel_sizeis(kH, kW): rows, then columns, as inkornia.filters.box_blur(). An even entry is accepted and shifts the image half a pixel toward the top-left – for an even extentk, outputiaverages inputsi - k // 2 + 1toi + k // 2– whereRandomGaussianBlurraises.the output is not clamped. At the default
border_type="reflect"every output value is a mean of input values and stays between the input’s extremes, up to the rounding of the kernel weights;border_type="constant"pads with zeros, which pulls a border pixel toward0.
Note
The padding sets a minimum image size: at
border_type="reflect"each spatial axis must be longer thank // 2for a kernel extentkalong it, and at"circular"at least that long; a smaller image raises aValueErrornaming the class, the kernel and the input shape."constant"and"replicate"run down to a single pixel.Note
This function internally uses
kornia.filters.box_blur().See also
RandomGaussianBlur: uses Gaussian rather than uniform filter weights.
Examples
>>> img = torch.ones(1, 1, 24, 24) >>> out = RandomBoxBlur((7, 7))(img) >>> out.shape torch.Size([1, 1, 24, 24])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomBoxBlur((7, 7), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomBrightness(brightness=(1.0, 1.0), clip_output=True, same_on_batch=False, p=1.0, keepdim=False)[source]#
Shift brightness by an additive random offset.
output = RandomBrightness(brightness)(input)computesinput + (factor - 1)for each selected image using a sampled brightness factor, with clamping enabled by default. UseColorJitterfor torchvision-compatible multiplicative brightness,input * factor.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
brightness (
Tuple[float,float], optional) – the brightness factor to apply Default:(1.0, 1.0)clip_output (
bool, optional) – if true clip output Default:Truesame_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation. Default:1.0keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
with
clip_output=True, input values are clamped into[0, 1]before the operation as well as afterwards. Withclip_output=False, the arithmetic is range-independent: neither input nor output is clamped.brightnessis centered on1.0: the drawn factor is re-based tofactor - 1before it reacheskornia.enhance.adjust_brightness(), whose own identity is0.0, so the same number passed straight to the primitive means something else.at the default
clip_output=Truethe result is clamped into[0, 1]; withclip_output=Falsethe raw sum is returned.
Note
This function internally uses
kornia.enhance.adjust_brightness()See also
RandomContrast: scales values instead of adding an offset.ColorJiggle: combines this additive brightness step with color adjustments.ColorJitter: uses torchvision-compatible multiplicative brightness.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.rand(1, 3, 3, 3) >>> aug = RandomBrightness(brightness = (0.5,2.),p=1.) >>> aug(inputs) tensor([[[[0.0505, 0.3225, 0.0000], [0.0000, 0.0000, 0.1883], [0.0443, 0.4507, 0.0099]], [[0.1866, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000], [0.0728, 0.2519, 0.3543]], [[0.0000, 0.0000, 0.2359], [0.4694, 0.0000, 0.4284], [0.0000, 0.1072, 0.5070]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomBrightness((0.8,1.2), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomChannelDropout(num_drop_channels=1, fill_value=0.0, same_on_batch=False, p=0.5, keepdim=False)[source]#
Set random channels to
fill_value(channel dropout) per sample with probabilityp(default 0.5).output = RandomChannelDropout(num_drop_channels, fill_value, ...)(input)replaces selected channels of each selected image(B, C, H, W)with a constant.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
num_drop_channels (
int, optional) – Number of channels to drop randomly. Default is 1. Default:1fill_value (
float, optional) – Value to fill the dropped channels with. Default is 0.0. Default:0.0same_on_batch (
bool, optional) – Apply the same transformation across the batch. Defaults to False. Default:Falsep (
float, optional) – Probability of applying the transformation to each sample. Defaults to 0.5. Default:0.5keepdim (
bool, optional) – Whether to keep the output shape the same as inputTrueor broadcast it to the batch formFalse. Defaults to False. Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(C, H, W)or(B, C, H, W)
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the channels named by the drawn
channel_idxare overwritten with the literalfill_value, anintorfloatin[0, 1]checked at construction. Every other channel is left exactly as it came in, so the input’s value range is carried through.num_drop_channelsis checked against the input’s channel count on the forward pass.fill_valueis held in a non-persistent buffer, so.to(...)moves and casts it whilestate_dict()gains no key for it. A float64 image is filled with the numberfill_valueitself rather than the buffer’s float32 rounding of it, unless the buffer has been changed since construction.
Note
- If num_drop_channels is set to 1, it means that for each image in the batch,
we will randomly choose one channel to drop.
- If num_drop_channels is set to 2, it means that for each image in the batch,
we will randomly choose two channels to drop.
- If num_drop_channels is set to 3, it means that for each image in the batch,
we will randomly choose three channels to drop (all image).
See also
RandomChannelShuffle: permutes channels instead of replacing them.RandomGrayscale: computes grayscale instead of removing channels.
Examples
>>> rng = torch.manual_seed(1) >>> img = torch.ones(1, 3, 3, 3) >>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0) >>> aug(img) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomChannelDropout(num_drop_channels=1, fill_value=0.0, p=1.0) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomChannelShuffle(same_on_batch=False, p=0.5, keepdim=False)[source]#
Randomly permute the channels of images, applied per sample with probability
p(default 0.5).output = RandomChannelShuffle(...)(input)reorders the channels of every selected image(B, C, H, W)without changing its values.
Note
Unlike torchvision’s
RandomChannelPermutation, which permutes the channels of every image, this class permutes the channels of each sample with probabilityp, 0.5 by default; withsame_on_batch=Trueone draw decides for the whole batch. Passp=1.0to permute every sample.See the Convention block on
IntensityAugmentationBase2D.- Parameters:
same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as inputTrueor broadcast it to the batch formFalse. Default:False
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the drawn
channelsindex the source, not the destination: output channelcof samplebis input channelchannels[b][c].the permutation is drawn independently per sample;
same_on_batch=Trueshares one permutation across the batch.values are only reordered, never recomputed, so the input’s value range is carried through.
See also
RandomChannelDropout: replaces channels instead of permuting them.
Examples
>>> rng = torch.manual_seed(0) >>> img = torch.arange(1*2*2*2.).view(1,2,2,2) >>> RandomChannelShuffle()(img) tensor([[[[4., 5.], [6., 7.]], [[0., 1.], [2., 3.]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomChannelShuffle(p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomClahe(clip_limit=(40.0, 40.0), grid_size=(8, 8), slow_and_differentiable=False, same_on_batch=False, p=0.5, keepdim=False)[source]#
Equalize local contrast with CLAHE, applied per sample with probability
p(default 0.5).output = RandomClahe(clip_limit, grid_size, ...)(input)equalizes each selected image through local tiles. It accepts(B, C, H, W)images and clamps the selected inputs and outputs to[0, 1]. UseRandomEqualizefor one global histogram per channel.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
clip_limit (
tuple[float,float], optional) – the(low, high)range the per-sample contrast-limiting threshold is drawn from. A value is drawn for each image, or once and shared across the batch whensame_on_batch=True. Unlikekornia.enhance.equalize_clahe()’s scalar argument of the same name this must be a two-element tuple – a scalar raises aValueErrorat construction – and(0.0, 0.0)disables clipping. A negative bound is not rejected and behaves like0.0. Default:(40.0, 40.0)grid_size (
tuple[int,int], optional) – number of tiles to be cropped in each direction (GH, GW). Default:(8, 8)slow_and_differentiable (
bool, optional) – selects the implementation. At the defaultFalsethe fast path breaks the autograd graph – the output hasrequires_grad=Falseand nograd_fn, which no other 2D intensity augmentation does – so set it toTrueto keep the class differentiable. Default:Falsesame_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the wrapper clamps before calling
kornia.enhance.equalize_clahe(); the functional API retains its strict range check.grid_sizetiles the two axes independently, and a grid that does not divide the image pads it, sogrid_size=(3, 3)works on a10 x 10image. Each axis must be larger than its grid size, so a grid as large as the image, or larger, raises aValueErrornaming the smallest image it admits.
Note
This function internally uses
kornia.enhance.equalize_clahe().See also
RandomEqualize: equalizes each whole channel rather than local tiles.
Examples
>>> img = torch.rand(1, 10, 20) >>> aug = RandomClahe() >>> res = aug(img) >>> res.shape torch.Size([1, 1, 10, 20])
>>> img = torch.rand(2, 3, 10, 20) >>> aug = RandomClahe() >>> res = aug(img) >>> res.shape torch.Size([2, 3, 10, 20])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomClahe(p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomContrast(contrast=(1.0, 1.0), clip_output=True, same_on_batch=False, p=1.0, keepdim=False)[source]#
Scale pixel values by a random contrast factor.
output = RandomContrast(contrast)(input)computesinput * factorfor each selected image using a sampled contrast factor, with clamping enabled by default. UseColorJitterfor torchvision-compatible contrast, which blends the image with its grayscale mean,factor * input + (1 - factor) * mean.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
contrast (
Tuple[float,float], optional) – the contrast factor to apply. Default:(1.0, 1.0)clip_output (
bool, optional) – if true clip output. Default:Truesame_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation. Default:1.0keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
with
clip_output=True, input values are clamped into[0, 1]before the operation as well as afterwards. Withclip_output=False, the arithmetic is range-independent: neither input nor output is clamped.the drawn factor reaches
kornia.enhance.adjust_contrast()unchanged – it is not re-based the wayRandomBrightnessre-bases its own – so1.0is the identity: for any input withclip_output=False, and for an input in[0, 1]at the default.at the default
clip_output=Truethe result is clamped into[0, 1]; withclip_output=Falsethe raw product is returned.
Note
This function internally uses
kornia.enhance.adjust_contrast()See also
RandomBrightness: adds an offset instead of scaling values.ColorJiggle: combines this raw-value scaling with color adjustments.ColorJitter: blends with the grayscale mean as torchvision does.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.rand(1, 3, 3, 3) >>> aug = RandomContrast(contrast = (0.5, 2.), p = 1.) >>> aug(inputs) tensor([[[[0.2750, 0.4258, 0.0490], [0.0732, 0.1704, 0.3514], [0.2716, 0.4969, 0.2525]], [[0.3505, 0.1934, 0.2227], [0.0124, 0.0936, 0.1629], [0.2874, 0.3867, 0.4434]], [[0.0893, 0.1564, 0.3778], [0.5072, 0.2201, 0.4845], [0.2325, 0.3064, 0.5281]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomContrast((0.8,1.2), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomEqualize(same_on_batch=False, p=0.5, keepdim=False)[source]#
Equalize the histogram of each image channel, applied per sample with probability
p(default 0.5).output = RandomEqualize(...)(input)equalizes every selected channel of an image(B, C, H, W)after clamping it to[0, 1]. UseRandomClaheto equalize local tiles with contrast limiting.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – Probability of applying the transformation to each sample. Default:0.5same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the wrapper clamps before calling
kornia.enhance.equalize(); the functional API retains its strict range check.
Note
This function internally uses
kornia.enhance.equalize().See also
RandomEqualize3D: equalizes volume intensities.RandomClahe: uses local contrast-limited histogram equalization.
Examples
>>> rng = torch.manual_seed(0) >>> input = torch.rand(1, 1, 5, 5) >>> equalize = RandomEqualize(p=1.) >>> equalize(input) tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074], [0.6341, 0.4901, 0.8964, 0.4556, 0.6323], [0.3489, 0.4017, 0.0223, 0.1689, 0.2939], [0.5185, 0.6977, 0.8000, 0.1610, 0.2823], [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomEqualize(p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomDissolving(step_range=(100, 500), version='1.5', p=0.5, keepdim=False, **kwargs)[source]#
Dissolve images with a Stable Diffusion model, applied to the whole batch with probability
p(default 0.5).output = RandomDissolving(step_range, version, ...)(input)applies one sampled reverse-diffusion step to the selected batch of images. It needs the optionaldiffusersdependency and a compatible Stable Diffusion model.See the Convention block on
IntensityAugmentationBase2D.Based on [SZZ+24], the dissolving transformation is essentially applying one-step reverse diffusion. Our implementation currently supports the HuggingFace implementations of SD 1.4, SD 1.5 and SD XL; once
diffusersis importable, any otherversionraisesNotImplementedErrorwith the unsupported value and the supported versions (without it, construction fails on the optional-dependency prompt before the version is looked at).SD 1.4
SD 1.5
SD XL
SD XL example image pending — see #4601.
- Parameters:
p (
float, optional) – probability of applying the transformation, drawn once for the whole batch. Default:0.5version (
str, optional) – the version of the stable diffusion model. Options:"1.4","1.5","xl". Default:"1.5"step_range (
Tuple[float,float], optional) – the step range of the diffusion model steps. Higher the step, stronger the dissolving effects. Default:(100, 500)keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False**kwargs (
Any) – additional arguments for .from_pretrained for HF StableDiffusionPipeline.
- Shape:
Input:
(C, H, W)or(B, C, H, W).Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the clamped input is encoded by the Stable Diffusion VAE; its decoded result is also clamped.
Note
The transform is delegated to
kornia.filters.StableDiffusionDissolving, which the constructor builds: instantiating this class needs the optionaldiffuserspackage and, on a cold cache, downloads a Stable Diffusion checkpoint at that point – thefrom_pretrainedcall is in that class’s own constructor, not on the first forward.See also
RandomErasing: removes a rectangle without a diffusion model.StableDiffusionDissolving: the model itself, with a step you choose and an input it does not clamp.
- class kornia.augmentation.RandomGamma(gamma=(1.0, 1.0), gain=(1.0, 1.0), same_on_batch=False, p=1.0, keepdim=False)[source]#
Apply a random gamma power law to unit-range images.
output = RandomGamma(gamma, gain)(input)raises pixels in selected images to a sampled gamma and multiplies them by sampled gain.The formula is torchvision’s
adjust_gammafor a float image:clamp(gain * input ** gamma, 0, 1).
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation. Default:1.0gamma (
Tuple[float,float], optional) – the gamma factor to apply. Default:(1.0, 1.0)gain (
Tuple[float,float], optional) – the gain factor to apply. Default:(1.0, 1.0)same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the clamp is not optional: unlike
RandomBrightnessandRandomContrastthis class has noclip_output.gammaandgainmust be non-negative. Neither is checked at construction: the check is inkornia.enhance.adjust_gamma(), so a negative value raises aRuntimeErroron the forward pass. It is not run for an MPS image, where a negative value goes through the same formula unchecked.
Note
This function internally uses
kornia.enhance.adjust_gamma()See also
RandomBrightness: applies an additive linear adjustment.RandomContrast: applies a multiplicative linear adjustment.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.rand(1, 3, 3, 3) >>> aug = RandomGamma((0.5,2.),(1.5,1.5),p=1.) >>> aug(inputs) tensor([[[[1.0000, 1.0000, 0.3912], [0.4883, 0.7801, 1.0000], [1.0000, 1.0000, 0.9702]], [[1.0000, 0.8368, 0.9048], [0.1824, 0.5597, 0.7609], [1.0000, 1.0000, 1.0000]], [[0.5452, 0.7441, 1.0000], [1.0000, 0.8990, 1.0000], [0.9267, 1.0000, 1.0000]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomGamma((0.8,1.2), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomGaussianBlur(kernel_size, sigma, border_type='reflect', separable=True, same_on_batch=False, p=0.5, keepdim=False)[source]#
Blur images with a Gaussian kernel of random sigma, applied per sample with probability
p(default 0.5).output = RandomGaussianBlur(kernel_size, sigma, ...)(input)convolves each selected(B, C, H, W)image with separable Gaussian weights.The standard deviation is sampled for each instance.
Note
Unlike torchvision’s
GaussianBlur, which blurs every image, this class blurs each sample with probabilityp, 0.5 by default; withsame_on_batch=Trueone draw decides for the whole batch. Passp=1.0to blur every sample.See the Convention block on
IntensityAugmentationBase2D.- Parameters:
kernel_size (
Union[Tuple[int,int],int]) – the size of the kernel.sigma (
Union[Tuple[float,float],Tensor]) – the range for the standard deviation of the kernel.border_type (
str, optional) – the padding mode to be applied before convolving. The expected modes are:constant,reflect,replicateorcircular. Default:"reflect"separable (
bool, optional) – run as composition of two 1d-convolutions. Default:Truesame_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].kernel_sizeis(kH, kW): rows, then columns, as inkornia.filters.gaussian_blur2d(). An even entry is not rounded up: the forward pass raises that function’s odd-size error.sigmais drawn once per sample, as a single scalar used for both axes, and a drawn0raises on the forward pass. Both axes get that sigma even when a rectangularkernel_sizegives them different supports, and a support short enough to truncate the Gaussian narrows the blur along its axis.the defaults
separable=Trueandborder_type="reflect"are the function’s own defaults.the output is not clamped. At the default
border_type="reflect"every output value is a weighted mean of input values and stays between the input’s extremes, up to the rounding of the kernel weights;border_type="constant"pads with zeros, which pulls a border pixel toward0.
Note
The padding sets a minimum image size: at
border_type="reflect"each spatial axis must be longer than the kernel’s radius along it, and at"circular"at least that long; a smaller image raises aValueErrornaming the class, the kernel and the input shape."constant"and"replicate"run down to a single pixel.Note
This function internally uses
kornia.filters.gaussian_blur2d().See also
RandomBoxBlur: uses uniform box-filter weights.RandomMedianBlur: uses the median rather than a weighted average.RandomMotionBlur: uses a directional motion kernel.
Examples
>>> rng = torch.manual_seed(0) >>> input = torch.rand(1, 1, 5, 5) >>> blur = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.) >>> blur(input) tensor([[[[0.5941, 0.5833, 0.5022, 0.4384, 0.3934], [0.5310, 0.4964, 0.4113, 0.3637, 0.3472], [0.4991, 0.4997, 0.4312, 0.3620, 0.3081], [0.6082, 0.5667, 0.4954, 0.3825, 0.3508], [0.7042, 0.6849, 0.6275, 0.4753, 0.4105]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomGaussianBlur((3, 3), (0.1, 2.0), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomGaussianIllumination(gain=(0.01, 0.15), center=(0.1, 0.9), sigma=(0.2, 1.0), sign=(-1.0, 1.0), p=0.5, same_on_batch=False, keepdim=False)[source]#
Add a random Gaussian-shaped illumination pattern, applied per sample with probability
p(default 0.5).output = RandomGaussianIllumination(gain, center, sigma, ...)(input)adds a sampled Gaussian field to each selected(B, C, H, W)image and clamps it to[0, 1].
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
gain (
Union[float,Tuple[float,float],None], optional) – Range for the gain factor (intensity) applied to the generated illumination. Default:(0.01, 0.15)center (
Union[float,Tuple[float,float],None], optional) – The center coordinates of the Gaussian distribution are expressed as a Default:(0.1, 0.9)dimensions (percentage of the spatial) – math:(H, W).
sigma (
Union[float,Tuple[float,float],None], optional) – The sigma values (standard deviation) of the Gaussian distribution are expressed as a Default:(0.2, 1.0)dimensions – math:(H, W).
sign (
Union[float,Tuple[float,float],None], optional) – Range for the sign of the Gaussian distribution. If only one sign is needed, Default:(-1.0, 1.0)float. (insert only as a tuple or)
p (
float, optional) – Probability of applying the transformation to each sample. Default:0.5same_on_batch (
bool, optional) – If True, apply the same transformation across the entire batch. Default is False. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the class adds the drawn field
_params["gradient"]to the image and clamps the sum into[0, 1], so the output stays inside that range even when the input does not.signis drawn per sample, from(-1.0, 1.0)by default, and only whether the draw is negative is used: it decides whether that sample’s gradient darkens or brightens, so one batch can hold both a darkened and a brightened image. A point range such assign=1.0brightens every sample.sigmais a fraction of the axis length, not an absolute width: the generator draws it and multiplies by the image’s width and height before building the kernel, so the samesigmais a narrower kernel on a smaller image. Every admittedsigmagives a finite kernel,0included.centeris a fraction of the axis length too, and the peak sits at the pixel-center positioncenter * L - 0.5without rounding to a whole pixel:center=0.5is the middle of any axis,0and1are the outer edges of the first and last pixel. Atsigma=0the field is an impulse on the pixel nearest that position, split between two pixels when it falls halfway.
Note
The generated random numbers are not reproducible across different devices and dtypes. By default, the parameters will be generated on CPU. This can be changed by calling
self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64).See also
RandomLinearIllumination: uses a linear rather than Gaussian-shaped field.RandomGaussianNoise: adds unstructured noise rather than an illumination field.
Examples
>>> rng = torch.manual_seed(1) >>> input = torch.ones(1, 3, 3, 3) * 0.5 >>> aug = RandomGaussianIllumination(gain=0.5, p=1.) >>> aug(input) tensor([[[[0.8675, 1.0000, 0.6834], [0.7891, 0.9075, 0.6246], [0.6229, 0.7113, 0.5000]], [[0.8675, 1.0000, 0.6834], [0.7891, 0.9075, 0.6246], [0.6229, 0.7113, 0.5000]], [[0.8675, 1.0000, 0.6834], [0.7891, 0.9075, 0.6246], [0.6229, 0.7113, 0.5000]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomGaussianIllumination(p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomGaussianNoise(mean=0.0, std=1.0, same_on_batch=False, p=0.5, keepdim=False)[source]#
Add sampled Gaussian noise without clipping the result, per sample with probability
p(default 0.5).output = RandomGaussianNoise(mean, std)(input)adds a sampled noise field to each selected image; withsame_on_batch=True, the field is shared across the batch.
Note
Unlike torchvision’s
GaussianNoise, which adds noise to every image, this class adds noise to each sample with probabilityp, 0.5 by default; withsame_on_batch=Trueone draw decides for the whole batch. Passp=1.0to add noise to every sample.See the Convention block on
IntensityAugmentationBase2D.- Parameters:
mean (
float, optional) – The mean of the gaussian distribution. Default:0.0std (
float, optional) – The standard deviation of the gaussian distribution. Default:1.0same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the noise is additive and recorded in full: the output is the input plus
_params["gaussian_noise"], someanoffsets the image rather than naming the mean the output should have.nothing is clamped, so an input already inside
[0, 1]can leave it in either direction.
See also
RandomSaltAndPepperNoise: replaces a sparse set of pixels with salt or pepper values.RandomGaussianIllumination: adds a smooth spatial illumination field instead of noise.
Examples
>>> rng = torch.manual_seed(0) >>> img = torch.ones(1, 1, 2, 2) >>> RandomGaussianNoise(mean=0., std=1., p=1.)(img) tensor([[[[ 2.5410, 0.7066], [-1.1788, 1.5684]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomGaussianNoise(mean=0., std=1., p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomGrayscale(rgb_weights=None, same_on_batch=False, p=0.1, keepdim=False)[source]#
Convert images to grayscale (channel count kept), applied per sample with probability
p(default 0.1).output = RandomGrayscale(...)(input)turns selected images(B, C, H, W)into grayscale values while retaining their channel count: RGB uses luminance weights and other channel counts default to equal weights.
See the Convention block on
IntensityAugmentationBase2D.Works for multispectral imagery too (e.g. satellite data with 4-13+ bands): for a non-RGB channel count the grayscale is the weighted average across all channels, broadcast back to the input channel count. This makes the augmentation usable outside the 3-channel RGB regime.
- Parameters:
rgb_weights (
Optional[Tensor], optional) – Per-channel weights applied when reducing to grayscale — one weight per input channel (three, for the usual RGB case). IfNone, RGB inputs use the standard luminance weights and multispectral inputs weight every band equally. Weights are applied as given and are not normalized, so weights that do not sum to one rescale the output. Default:Nonep (
float, optional) – probability of applying the transformation to each sample. Default:0.1same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the channel count is preserved: the single weighted average is broadcast back over the input’s channels, so every output channel of a sample carries the same value.
a three-channel input uses the RGB luminance weights by default; any other channel count defaults to an equal weight per channel, which makes the output the plain mean over channels.
rgb_weightsreplaces those defaults.the result is not clamped; its range follows the weighted channel reduction and the supplied
rgb_weights.
Note
For 3-channel RGB inputs this uses
kornia.color.rgb_to_grayscale(); multispectral inputs use a weighted channel average.See also
RandomChannelDropout: removes selected channels instead of computing grayscale.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.randn((1, 3, 3, 3)) >>> aug = RandomGrayscale(p=1.0) >>> aug(inputs) tensor([[[[-1.1344, -0.1330, 0.1517], [-0.0791, 0.6711, -0.1413], [-0.1717, -0.9023, 0.0819]], [[-1.1344, -0.1330, 0.1517], [-0.0791, 0.6711, -0.1413], [-0.1717, -0.9023, 0.0819]], [[-1.1344, -0.1330, 0.1517], [-0.0791, 0.6711, -0.1413], [-0.1717, -0.9023, 0.0819]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomGrayscale(p=1.0) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomHue(hue=(0.0, 0.0), same_on_batch=False, p=1.0, keepdim=False)[source]#
Rotate the hue of a three-channel image by a random number of turns.
output = RandomHue(hue)(input)samples an HSV hue rotation for each selected image.The shift is in turns of the hue circle, the unit of torchvision’s
adjust_huehue_factor, so a torchvision hue range carries over unchanged.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
hue (
Tuple[float,float], optional) – the hue shift, in turns of the hue circle, restricted to the closed[-0.5, 0.5]. Ifhueis a single numberxthe shift is sampled from[-x, x], andxabove0.5raises; a tuple gives the range directly, and one outside the bound raises as well. Default:(0.0, 0.0)same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation. Default:1.0keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the input must have three channels: the shift is computed in HSV, and any other channel count raises a
ValueErroron the forward pass.the drawn shift is in turns of the hue circle, and the class multiplies it by
2 * pibefore callingkornia.enhance.adjust_hue(), which takes radians. Passing the same number straight to that primitive shifts the hue by a different amount.the HSV hue shift preserves the clamped input pixel’s largest and smallest channel, up to rounding.
Note
This function internally uses
kornia.enhance.adjust_hue()See also
RandomSaturation: scales HSV saturation without rotating hue.ColorJiggle: combines hue rotation with other Kornia color adjustments.ColorJitter: combines hue rotation with torchvision-compatible color adjustments.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.rand(1, 3, 3, 3) >>> aug = RandomHue(hue = (-0.5,0.5),p=1.) >>> aug(inputs) tensor([[[[0.3993, 0.2823, 0.6816], [0.6117, 0.2090, 0.4081], [0.4693, 0.5529, 0.9527]], [[0.1610, 0.5962, 0.4971], [0.9152, 0.3971, 0.8742], [0.4194, 0.6771, 0.7162]], [[0.6323, 0.7682, 0.0885], [0.0223, 0.1689, 0.2939], [0.5185, 0.8964, 0.4556]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomHue((-0.2,0.2), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomInvert(max_val=1.0, same_on_batch=False, p=0.5, keepdim=False)[source]#
Invert image values as
max_val - x, applied per sample with probabilityp(default 0.5).output = RandomInvert(max_val, ...)(input)subtracts selected image values from a chosen maximum.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
max_val (
Union[float,Tensor], optional) – The expected maximum value in the input tensor. The shape has to according to the input tensor shape, or at least has to work with broadcasting. Default:1.0same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the output is
max_val - input, with no clamp, so an input outside[0, max_val]comes back outside it rather than clipped.max_valdescribes the input’s maximum, so it has to be set to match an input that is not in[0, 1].
Note
This function internally uses
kornia.enhance.invert().See also
RandomSolarize: inverts only values above a sampled threshold.
Examples
>>> rng = torch.manual_seed(0) >>> img = torch.rand(1, 1, 5, 5) >>> inv = RandomInvert() >>> inv(img) tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074], [0.6341, 0.4901, 0.8964, 0.4556, 0.6323], [0.3489, 0.4017, 0.0223, 0.1689, 0.2939], [0.5185, 0.6977, 0.8000, 0.1610, 0.2823], [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomInvert(p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomJPEG(jpeg_quality=50.0, same_on_batch=False, p=1.0, keepdim=False)[source]#
Simulate differentiable JPEG coding for RGB images.
output = RandomJPEG(jpeg_quality, ...)(input)simulates JPEG coding for selected RGB images of shape(B, 3, H, W).
See the Convention block on
IntensityAugmentationBase2D.kornia.color.ycbcr_to_rgb()hard-clamps the decoded RGB values to[0, 1]. The codec’s final soft-clipping call uses bounds[0, 255]and leaves those RGB values unchanged. The input must have three channels: the codec works in YCbCr, and any other channel count raises aShapeError.- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.
- Parameters:
jpeg_quality (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – The range of compression rates to be applied. Default:50.0p (
float, optional) – probability of applying the transformation. Default:1.0same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
Note
This function internally uses
kornia.enhance.jpeg_codec_differentiable().See also
RandomGaussianBlur: smooths with a filter rather than JPEG coding artifacts.
Examples
>>> import torch >>> rng = torch.manual_seed(0) >>> images = 0.1904 * torch.ones(2, 3, 32, 32) >>> aug = RandomJPEG(jpeg_quality=(1.0, 50.0), p=1.) >>> images_jpeg = aug(images)
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> images = 0.1904 * torch.ones(2, 3, 32, 32) >>> aug = RandomJPEG(jpeg_quality=20.0, p=1.) # Samples a JPEG quality from the range [30.0, 70.0] >>> (aug(images) == aug(images, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomLinearCornerIllumination(gain=(0.01, 0.2), sign=(-1.0, 1.0), p=0.5, same_on_batch=False, keepdim=False)[source]#
Brighten or darken by a linear ramp from a corner, applied per sample with probability
p(default 0.5).output = RandomLinearCornerIllumination(...)(input)adds a sampled ramp from one corner to selected images(B, C, H, W)and clamps them to[0, 1].
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
gain (
Union[float,Tuple[float,float],None], optional) – Range for the gain factor (intensity) applied to the generated illumination. Default:(0.01, 0.2)sign (
Union[float,Tuple[float,float],None], optional) – Range for the sign of the distribution. If only one sign is needed, Default:(-1.0, 1.0)float. (insert only as a tuple or)
p (
float, optional) – Probability of applying the transformation to each sample. Default:0.5same_on_batch (
bool, optional) – If True, apply the same transformation across the entire batch. Default is False. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the class adds the drawn field
_params["gradient"]to the image and clamps the sum into[0, 1], so the output stays inside that range even when the input does not.signis drawn per sample, from(-1.0, 1.0)by default, and only whether the draw is negative is used: it decides whether that sample’s gradient darkens or brightens, so one batch can hold both a darkened and a brightened image. A point range such assign=1.0brightens every sample. The corner where the gradient is strongest is drawn separately, per sample.
Note
The generated random numbers are not reproducible across different devices and dtypes. By default, the parameters will be generated on CPU. This can be changed by calling
self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64).See also
RandomLinearIllumination: starts the linear illumination ramp from an edge.
Examples
>>> rng = torch.manual_seed(1) >>> input = torch.ones(1, 3, 3, 3) * 0.5 >>> aug = RandomLinearCornerIllumination(gain=0.25, p=1.) >>> aug(input) tensor([[[[0.3750, 0.4375, 0.5000], [0.3125, 0.3750, 0.4375], [0.2500, 0.3125, 0.3750]], [[0.3750, 0.4375, 0.5000], [0.3125, 0.3750, 0.4375], [0.2500, 0.3125, 0.3750]], [[0.3750, 0.4375, 0.5000], [0.3125, 0.3750, 0.4375], [0.2500, 0.3125, 0.3750]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomLinearCornerIllumination(p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomLinearIllumination(gain=(0.01, 0.2), sign=(-1.0, 1.0), p=0.5, same_on_batch=False, keepdim=False)[source]#
Brighten or darken by a linear ramp from an edge, applied per sample with probability
p(default 0.5).output = RandomLinearIllumination(...)(input)adds a sampled edge-to-edge ramp to selected images(B, C, H, W)and clamps them to[0, 1].
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
gain (
Union[float,Tuple[float,float],None], optional) – Range for the gain factor (intensity) applied to the generated illumination. Default:(0.01, 0.2)sign (
Union[float,Tuple[float,float],None], optional) – Range for the sign of the distribution. If only one sign is needed, Default:(-1.0, 1.0)float. (insert only as a tuple or)
p (
float, optional) – Probability of applying the transformation to each sample. Default:0.5same_on_batch (
bool, optional) – If True, apply the same transformation across the entire batch. Default is False. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the class adds the drawn field
_params["gradient"]to the image and clamps the sum into[0, 1], so the output stays inside that range even when the input does not.signis drawn per sample, from(-1.0, 1.0)by default, and only whether the draw is negative is used: it decides whether that sample’s gradient darkens or brightens, so one batch can hold both a darkened and a brightened image. A point range such assign=1.0brightens every sample. The edge where the gradient is strongest is drawn separately, per sample.
Note
The generated random numbers are not reproducible across different devices and dtypes. By default, the parameters will be generated on CPU. This can be changed by calling
self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64).See also
RandomGaussianIllumination: adds a smooth Gaussian-shaped illumination field.RandomLinearCornerIllumination: starts its ramp from a corner.
Examples
>>> rng = torch.manual_seed(1) >>> input = torch.ones(1, 3, 3, 3) * 0.5 >>> aug = RandomLinearIllumination(gain=0.25, p=1.) >>> aug(input) tensor([[[[0.2500, 0.2500, 0.2500], [0.3750, 0.3750, 0.3750], [0.5000, 0.5000, 0.5000]], [[0.2500, 0.2500, 0.2500], [0.3750, 0.3750, 0.3750], [0.5000, 0.5000, 0.5000]], [[0.2500, 0.2500, 0.2500], [0.3750, 0.3750, 0.3750], [0.5000, 0.5000, 0.5000]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomLinearIllumination(p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomMedianBlur(kernel_size=(3, 3), same_on_batch=False, p=0.5, keepdim=False)[source]#
Blur images with a median filter, applied per sample with probability
p(default 0.5).output = RandomMedianBlur(kernel_size, ...)(input)replaces pixels in selected(B, C, H, W)images by local medians.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
kernel_size (
Tuple[int,int], optional) – the blurring kernel size. Default:(3, 3)same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].kernel_sizeis(kH, kW): rows, then columns, as inkornia.filters.median_blur(). An even entry is rejected at construction with that function’s odd-size error.the output is not clamped. The window is reflect-padded by
kornia.filters.median_blur()by default under every implementation it selects – theF.conv2dwindow extraction and the selection network it uses instead for a 3x3 or 5x5 inference pass alike.this class has no
border_typeand inheritskornia.filters.median_blur()’s defaultborder_type="reflect"; likeRandomBoxBlurandRandomGaussianBlur, it raises aValueErrornaming the class and the shape once a spatial axis is no longer than half the kernel’s extent along it.
Note
This function internally uses
kornia.filters.median_blur().See also
RandomGaussianBlur: uses a weighted average rather than the median.
Examples
>>> img = torch.ones(1, 1, 4, 4) >>> out = RandomMedianBlur((3, 3), p = 1)(img) >>> out.shape torch.Size([1, 1, 4, 4]) >>> out tensor([[[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomMedianBlur((7, 7), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomMotionBlur(kernel_size, angle, direction, border_type=BorderType.CONSTANT.name, resample=Resample.NEAREST.name, same_on_batch=False, p=0.5, keepdim=False)[source]#
Blur images with a random motion-blur kernel, applied per sample with probability
p(default 0.5).output = RandomMotionBlur(kernel_size, angle, direction, ...)(input)convolves selected(B, C, H, W)images with a sampled directional kernel.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation to each sample. Default:0.5kernel_size (
Union[int,Tuple[int,int],List[int]]) – motion kernel size (odd and positive). If int, the kernel will have a fixed size. If Tuple[int, int] or a two-element list, it will randomly generate one odd value from the closed range for the whole batch.angle (
Union[Tensor,float,Tuple[float,float]]) – angle of the motion blur in degrees (anti-clockwise rotation). If float, it will generate the value from (-angle, angle).direction (
Union[Tensor,float,Tuple[float,float]]) – forward/backward direction of the motion blur. Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle), while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur. If float, it will generate the value from (-direction, direction). If Tuple[int, int], it will randomly generate the value from the range.border_type (
Union[int,str,BorderType], optional) – the padding mode to be applied before convolving. CONSTANT = 0, REFLECT = 1, REPLICATE = 2, CIRCULAR = 3. Default:BorderType.CONSTANT.nameresample (
Union[str,int,Resample], optional) – the interpolation mode. Default:Resample.NEAREST.namesame_on_batch (
bool, optional) – apply the same angle and direction across the batch. The kernel size is always shared. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].a positive
angleturns the blur line counter-clockwise as the image is displayed, as inkornia.filters.motion_blur()andkornia.filters.get_motion_kernel2d().directionre-weights the kernel along that line before it is rotated:0spreads the weight evenly, and-1and+1pile it at opposite ends. The rotation then resamples the kernel withresample:"nearest"can drop or duplicate taps, so the line’s length and end weights change withangle, and"bilinear"or"bicubic"also spread weight off the line.the default
resample="nearest"is the function’s own default. The defaultborder_type="constant"is not: the class zero-pads by its own default, whilekornia.filters.motion_blur()defaults to"reflect". Passborder_type="reflect"to match the function.a ranged
kernel_sizeis drawn once per call and repeated into_params["ksize_factor"]with shape(B,), so every sample uses that size even withsame_on_batch=False; angle and direction are drawn per sample unlesssame_on_batch=True. A tuple range draws each odd size inside it with equal probability, bounds included, so(3, 20)draws3, 5, ..., 19. A range that holds no odd size is rounded up out of the requested range, so(4, 4)draws5; a reversed one such as(20, 3)raises at construction, and a drawn size below3raises on the forward pass.the output is not clamped. At the default
border_type="constant"the padding is zeros, so a border pixel is pulled toward0. Withborder_type="reflect"the result stays between the input’s extremes, up to rounding, atresample="nearest"or"bilinear"; a"bicubic"rotation gives the kernel negative weights, and the result can overshoot both extremes.an image smaller than the kernel is accepted, down to
1 x 1, at the defaultborder_type="constant"and at"replicate"."reflect"needs each spatial axis longer than the kernel radius along it, and"circular"at least that long; below that both raise aValueErrornaming the class, the drawn kernel and the input shape, asRandomBoxBlurandRandomGaussianBlurdo.
Note
This function accepts another transformation torch.Tensor (
(B, 3, 3)), then the applied transformation will be merged int to the input transformation torch.Tensor and returned.Please set
resampleto'bilinear'if more meaningful gradients wanted.Note
This function internally uses
kornia.filters.motion_blur().See also
RandomMotionBlur3D: applies a directional kernel to volumes.RandomGaussianBlur: applies isotropic Gaussian smoothing.RandomBoxBlur: applies uniform, non-directional smoothing.
Examples
>>> rng = torch.manual_seed(0) >>> input = torch.ones(1, 1, 5, 5) >>> motion_blur = RandomMotionBlur(3, 35., 0.5, p=1.) >>> motion_blur(input) tensor([[[[0.5773, 1.0000, 1.0000, 1.0000, 0.7561], [0.5773, 1.0000, 1.0000, 1.0000, 0.7561], [0.5773, 1.0000, 1.0000, 1.0000, 0.7561], [0.5773, 1.0000, 1.0000, 1.0000, 0.7561], [0.5773, 1.0000, 1.0000, 1.0000, 0.7561]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomMotionBlur(3, 35., 0.5, p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomPlanckianJitter(mode='blackbody', select_from=None, same_on_batch=False, p=0.5, keepdim=False)[source]#
Shift the illuminant color (Planckian jitter), applied per sample with probability
p(default 0.5).output = RandomPlanckianJitter(...)(input)changes the illumination of selected RGB images(B, 3, H, W)along its color-temperature model.
See the Convention block on
IntensityAugmentationBase2D.This is physics based color augmentation, that creates realistic variations in chromaticity, this can simulate the illumination changes in the scene.
See [ZBTvdW22] for more details.
- Parameters:
mode (
str, optional) – ‘blackbody’ or ‘CIED’. Default:"blackbody"select_from (
Union[int,List[int],None], optional) – choose a list of jitters to apply from. blackbody range [0-24], CIED range [0-22]. The entries index the table like a Python sequence: one past the end raises at construction, and a negative one counts from the end. Default:Nonesame_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the red and blue channels are scaled by the selected row of the illuminant table and the green channel is not scaled. Both input and output are clamped into
[0, 1], including green.modeselects the illuminant lookup table, held in the persistent bufferpl, andselect_fromnarrows that table to the listed rows. The input must have three channels.
Warning
pl’s shape depends onmode, so astate_dictsaved by an instance built with one mode does not load into an instance built with the other. Tracked in #4428.See also
ColorJiggle: samples general color adjustments instead of illuminant coefficients.
Examples
To apply planckian jitter based on mode
>>> rng = torch.manual_seed(0) >>> input = torch.rand(1, 3, 2, 2) >>> aug = RandomPlanckianJitter(mode='CIED', p=1.0) >>> aug(input) tensor([[[[0.6543, 1.0000], [0.1167, 0.1741]], [[0.3074, 0.6341], [0.4901, 0.8964]], [[0.2358, 0.3272], [0.1806, 0.2079]]]])
To apply planckian jitter on image(s) from list of interested jitters
>>> rng = torch.manual_seed(0) >>> input = torch.rand(2, 3, 2, 2) >>> aug = RandomPlanckianJitter(mode='blackbody', select_from=[23, 24, 1, 2], p=1.0) >>> aug(input) tensor([[[[0.3736, 0.5784], [0.0666, 0.0994]], [[0.3074, 0.6341], [0.4901, 0.8964]], [[0.6789, 0.9421], [0.5199, 0.5986]]], [[[0.0331, 0.2501], [0.4353, 0.7679]], [[0.6977, 0.8000], [0.1610, 0.2823]], [[0.2676, 0.3593], [0.1559, 0.3432]]]])
- class kornia.augmentation.RandomPlasmaBrightness(roughness=(0.1, 0.7), intensity=(0.0, 1.0), same_on_batch=False, p=0.5, keepdim=False)[source]#
Shift brightness by a diamond-square fractal map, applied per sample with probability
p(default 0.5).output = RandomPlasmaBrightness(roughness, intensity, ...)(input)adds a sampled fractal field to each selected image(B, C, H, W)and clamps it to[0, 1].
See the Convention block on
IntensityAugmentationBase2D.This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals. See: [NCR+22] for more details.
Note
This function internally uses
kornia.contrib.diamond_square().- Parameters:
roughness (
Tuple[float,float], optional) – value to scale during the recursion in the generation of the fractal map. Default:(0.1, 0.7)intensity (
Tuple[float,float], optional) – value that scales the intensity values of the generated maps. Default:(0.0, 1.0)same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the sampled fractal map is recorded as
_params["plasma"], so a forward replayed withparams=reproduces the first output bitwise.the result is clamped into
[0, 1], so the output stays inside that range even when the input does not.a one-pixel spatial axis is accepted, down to a
1 x 1image.
See also
RandomGaussianIllumination: uses a smooth Gaussian field instead of a fractal field.RandomLinearIllumination: uses a linear illumination ramp.
Examples
>>> rng = torch.manual_seed(0) >>> img = torch.ones(1, 1, 3, 4) >>> RandomPlasmaBrightness(roughness=(0.1, 0.7), p=1.)(img) tensor([[[[0.3677, 0.5169, 0.4346, 0.6906], [0.7740, 0.7483, 0.7752, 0.9332], [1.0000, 0.9797, 0.9848, 1.0000]]]])
- class kornia.augmentation.RandomPlasmaContrast(roughness=(0.1, 0.7), same_on_batch=False, p=0.5, keepdim=False)[source]#
Scale contrast by a diamond-square fractal map, applied per sample with probability
p(default 0.5).output = RandomPlasmaContrast(roughness, ...)(input)scales contrast locally with a sampled fractal field on selected(B, C, H, W)images.
See the Convention block on
IntensityAugmentationBase2D.This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals. See: [NCR+22] for more details.
Note
This function internally uses
kornia.contrib.diamond_square().- Parameters:
roughness (
Tuple[float,float], optional) – value to scale during the recursion in the generation of the fractal map. Default:(0.1, 0.7)same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the sampled fractal map is recorded as
_params["plasma"], so a forward replayed withparams=reproduces the first output bitwise.the result is clamped into
[0, 1], so the output stays inside that range even when the input does not.a one-pixel spatial axis is accepted, down to a
1 x 1image.
See also
RandomPlasmaBrightness: offsets brightness with a fractal map.RandomPlasmaShadow: uses a fractal map to darken selected areas.
Examples
>>> rng = torch.manual_seed(0) >>> img = torch.ones(1, 1, 3, 4) >>> RandomPlasmaContrast(roughness=(0.1, 0.7), p=1.)(img) tensor([[[[1.0000, 1.0000, 0.6770, 0.8711], [1.0000, 1.0000, 1.0000, 1.0000], [1.0000, 1.0000, 1.0000, 1.0000]]]])
- class kornia.augmentation.RandomPlasmaShadow(roughness=(0.1, 0.7), shade_intensity=(-1.0, 0.0), shade_quantity=(0.0, 1.0), same_on_batch=False, p=0.5, keepdim=False)[source]#
Add shadows from a diamond-square fractal map, applied per sample with probability
p(default 0.5).output = RandomPlasmaShadow(roughness, shade_intensity, ...)(input)darkens areas chosen by a sampled fractal field in selected(B, C, H, W)images.
See the Convention block on
IntensityAugmentationBase2D.This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals. See: [NCR+22] for more details.
Note
This function internally uses
kornia.contrib.diamond_square().- Parameters:
roughness (
Tuple[float,float], optional) – value to scale during the recursion in the generation of the fractal map. Default:(0.1, 0.7)shade_intensity (
Tuple[float,float], optional) – value that scales the intensity values of the generated maps. Default:(-1.0, 0.0)shade_quantity (
Tuple[float,float], optional) – value to select the pixels to mask. Default:(0.0, 1.0)same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the sampled fractal map is recorded as
_params["plasma"]with a single channel,(B, 1, H, W): one shade mask is applied to every channel of a sample. A forward replayed withparams=reproduces the first output bitwise.the result is clamped into
[0, 1], so the output stays inside that range even when the input does not.a one-pixel spatial axis is accepted, down to a
1 x 1image.
See also
RandomPlasmaBrightness: offsets brightness with a fractal map.RandomPlasmaContrast: scales contrast with a fractal map.
Examples
>>> rng = torch.manual_seed(0) >>> img = torch.ones(1, 1, 3, 4) >>> RandomPlasmaShadow(roughness=(0.1, 0.7), p=1.)(img) tensor([[[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]]])
- class kornia.augmentation.RandomPosterize(bits=3, same_on_batch=False, p=0.5, keepdim=False)[source]#
Posterize images to a random number of bits, applied per sample with probability
p(default 0.5).output = RandomPosterize(bits, ...)(input)reduces the retained bit depth of selected images.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation to each sample. Default:0.5bits (
Union[float,Tuple[float,float],Tensor], optional) – number of high bits to keep, in[0, 8], in which 0 gives a black image and 8 gives the original. A range of whole numbers is closed and uniform: every integer from the lower to the upper bound is drawn with the same probability. A non-integral argument is accepted; the drawn factor is rounded to an integer, half to even, so2.5gives2and3.5gives4. If int x, bits will be generated from (x, 8) then convert to int. If tuple (x, y), bits will be generated from (x, y) then convert to int. Default:3same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.bits=(k, k)withk < 8leaves at most2 ** kdistinct values, so0gives a constant image; the reduction is auint8round trip insidekornia.enhance.posterize(). A sample that draws8returns the clamped input, without the round trip.the round trip is a step function: the output still has
requires_grad=True, but its gradient with respect to the input is identically0belowbits=8, and follows the input clamp at8.an
intargument is the lower bound of the sampled range[x, 8]– the opposite reading fromRandomSharpness, whose scalar argument is an upper bound.
Note
This function internally uses
kornia.enhance.posterize().See also
RandomSolarize: thresholds values rather than reducing their bit depth.
Examples
>>> rng = torch.manual_seed(0) >>> input = torch.rand(1, 1, 5, 5) >>> posterize = RandomPosterize(3., p=1.) >>> posterize(input) tensor([[[[0.4863, 0.7529, 0.0784, 0.1255, 0.2980], [0.6275, 0.4863, 0.8941, 0.4549, 0.6275], [0.3451, 0.3922, 0.0157, 0.1569, 0.2824], [0.5176, 0.6902, 0.8000, 0.1569, 0.2667], [0.6745, 0.9098, 0.3922, 0.8627, 0.4078]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomPosterize(3., p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomRain(number_of_drops=(1000, 2000), drop_height=(5, 20), drop_width=(-5, 5), same_on_batch=False, p=0.5, keepdim=False)[source]#
Draw random rain-drop streaks on images, applied per sample with probability
p(default 0.5).output = RandomRain(...)(input)draws sampled streaks over selected one- or three-channel images(B, C, H, W).See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation to each sample. Default:0.5number_of_drops (
tuple[int,int], optional) – number of drops per image Default:(1000, 2000)drop_height (
tuple[int,int], optional) – Height of the drop in the image (same for each drop in one image). Sampled values must be greater than zero and strictly smaller than the input image height. Default:(5, 20)drop_width (
tuple[int,int], optional) – Width of the drop in the image (same for each drop in one image). The absolute sampled value must be strictly smaller than the input image width. Default:(-5, 5)
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the input must have one or three channels; any other channel count raises on the forward pass.
drop_heightruns down rows anddrop_widthalong columns: both name image axes, not drop-local ones, and a negativedrop_widthslants the drop the other way across the columns. Their absolute values give the number of pixels covered on each nonzero axis; a zero width makes a vertical line one pixel wide.a drop is written as the fixed value
200 / 255, not as a function of the image, so the rain is darker than every pixel above200 / 255that it falls on, inside[0, 1]or not. Every other pixel is carried through unclamped.both sizes must be strictly smaller than the image on their own axis, checked on the forward pass, where the image shape is known; a
drop_heightbelow1raises there too.every start position that keeps the whole drop inside the image is equally likely.
the three integer ranges are closed and uniform, so the default
drop_height=(5, 20)reaches20and the defaultdrop_width=(-5, 5)reaches both ends. With the defaults an image 20 pixels tall, or 5 pixels wide, therefore raises on some draws. A range that is reversed, fractional or non-finite raisesValueErrorat construction.
See also
RandomSnow: creates a snow effect rather than rain streaks.
Examples
>>> rng = torch.manual_seed(0) >>> input = torch.rand(1, 1, 5, 5) >>> rain = RandomRain(p=1,drop_height=(1,2),drop_width=(1,2),number_of_drops=(1,1)) >>> rain(input) tensor([[[[0.4963, 0.7843, 0.0885, 0.1320, 0.3074], [0.6341, 0.7843, 0.8964, 0.4556, 0.6323], [0.3489, 0.4017, 0.0223, 0.1689, 0.2939], [0.5185, 0.6977, 0.8000, 0.1610, 0.2823], [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
- class kornia.augmentation.RandomRGBShift(r_shift_limit=0.5, g_shift_limit=0.5, b_shift_limit=0.5, same_on_batch=False, p=0.5, keepdim=False)[source]#
Shift each RGB channel by a random offset, applied per sample with probability
p(default 0.5).output = RandomRGBShift(r_shift_limit, g_shift_limit, b_shift_limit, ...)(input)offsets the channels of selected RGB images(B, 3, H, W)separately and clamps their output to[0, 1]. UseRandomBrightnessfor one shared additive offset.See the Convention block on
IntensityAugmentationBase2D.- Parameters:
r_shift_limit (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – shift range for the red channel. A non-negative numberlimitsamples from[-limit, limit]; a(low, high)pair samples from[low, high]. Default:0.5g_shift_limit (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – shift range for the green channel, in the same form asr_shift_limit. Default:0.5b_shift_limit (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – shift range for the blue channel, in the same form asr_shift_limit. Default:0.5same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsep (
float, optional) – probability of applying the transformation to each sample. Default:0.5keepdim (
bool, optional) – whether to keep the output shape the same as inputTrueor broadcast it to the batch formFalse. Default:False
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the input must have exactly three channels, which
kornia.enhance.shift_rgb()checks; any other channel count raises anImageError. The class draws three named shifts per sample –_params["r_shift"],["g_shift"]and["b_shift"], each of shape(B,)– adds each to its channel, and the sum is clamped into[0, 1]bykornia.enhance.shift_rgb().a number
*_shift_limitis a non-negative half-width: that channel’s shift is sampled from[-limit, limit], so a limit of0adds nothing to the channel, though the clamp still applies. A negative limit raises aValueErrorat construction.a
(low, high)pair, as inalbumentations.RGBShift, is the sampling range itself. It must be finite withlow <= high, otherwise it raises aValueErrorat construction.
See also
RandomBrightness: offsets all channels equally instead of each RGB channel separately.ColorJiggle: combines RGB color adjustments with HSV operations.
Examples
>>> import torch >>> rng = torch.manual_seed(0) >>> inp = torch.rand(1, 3, 5, 5) >>> aug = RandomRGBShift(0, 0, 0) >>> ((inp == aug(inp)).double()).all() tensor(True)
>>> rng = torch.manual_seed(0) >>> inp = torch.rand(1, 3, 5, 5) >>> inp tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074], [0.6341, 0.4901, 0.8964, 0.4556, 0.6323], [0.3489, 0.4017, 0.0223, 0.1689, 0.2939], [0.5185, 0.6977, 0.8000, 0.1610, 0.2823], [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]], [[0.5529, 0.9527, 0.0362, 0.1852, 0.3734], [0.3051, 0.9320, 0.1759, 0.2698, 0.1507], [0.0317, 0.2081, 0.9298, 0.7231, 0.7423], [0.5263, 0.2437, 0.5846, 0.0332, 0.1387], [0.2422, 0.8155, 0.7932, 0.2783, 0.4820]], [[0.8198, 0.9971, 0.6984, 0.5675, 0.8352], [0.2056, 0.5932, 0.1123, 0.1535, 0.2417], [0.7262, 0.7011, 0.2038, 0.6511, 0.7745], [0.4369, 0.5191, 0.6159, 0.8102, 0.9801], [0.1147, 0.3168, 0.6965, 0.9143, 0.9351]]]]) >>> aug = RandomRGBShift(p=1.) >>> aug(inp) tensor([[[[0.9374, 1.0000, 0.5297, 0.5732, 0.7486], [1.0000, 0.9313, 1.0000, 0.8968, 1.0000], [0.7901, 0.8429, 0.4635, 0.6100, 0.7351], [0.9597, 1.0000, 1.0000, 0.6022, 0.7234], [1.0000, 1.0000, 0.8383, 1.0000, 0.8606]], [[0.6524, 1.0000, 0.1357, 0.2847, 0.4729], [0.4046, 1.0000, 0.2754, 0.3693, 0.2502], [0.1312, 0.3076, 1.0000, 0.8226, 0.8418], [0.6258, 0.3432, 0.6841, 0.1327, 0.2382], [0.3417, 0.9150, 0.8927, 0.3778, 0.5815]], [[0.3850, 0.5623, 0.2636, 0.1328, 0.4005], [0.0000, 0.1584, 0.0000, 0.0000, 0.0000], [0.2914, 0.2663, 0.0000, 0.2163, 0.3397], [0.0021, 0.0843, 0.1811, 0.3754, 0.5453], [0.0000, 0.0000, 0.2617, 0.4795, 0.5003]]]])
- class kornia.augmentation.RandomSaltAndPepperNoise(amount=(0.01, 0.06), salt_vs_pepper=(0.4, 0.6), p=0.5, same_on_batch=False, keepdim=False)[source]#
Add salt-and-pepper noise to images, applied per sample with probability
p(default 0.5).output = RandomSaltAndPepperNoise(amount, salt_vs_pepper, ...)(input)rewrites sampled pixels of selected one- or three-channel images(B, C, H, W)to zero or one.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
amount (
Union[float,Tuple[float,float],None], optional) – A float or a tuple representing the range for the amount of noise to apply. Default:(0.01, 0.06)salt_vs_pepper (
Union[float,Tuple[float,float],None], optional) – A float or a tuple representing the range for the ratio of Salt to Pepper noise. Default:(0.4, 0.6)p (
float, optional) – The probability of applying the transformation to each sample. Default is 0.5. Default:0.5same_on_batch (
bool, optional) – If True, apply the same transformation across the entire batch. Default is False. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].amountis a per-pixel rewrite probability: a chosen pixel is rewritten in every channel.salt_vs_pepperis the probability that a rewritten pixel becomes salt rather than pepper, and the poles are the literals1.0and0.0whatever the input’s range is – on an image scaled to[0, 2]the salt is darker than every pixel above1.the input must have one or three channels; any other channel count raises.
the pixels the masks do not name are carried through unchanged and unclamped.
Note
The amount parameter controls the intensity of the noise, while salt_vs_pepper controls the ratio of Salt to Pepper noise.
The values for amount and salt_vs_pepper should be between 0 and 1. The recommended value for salt_vs_pepper is 0.5, and for amount, values less than 0.2 are recommended.
If amount and salt_vs_pepper are floats (unique values), the transformation is applied with these exact values, rather than randomly sampling from the specified range. However, the masks are still generated randomly using these exact parameters.
See also
RandomGaussianNoise: adds a dense continuous noise field.
Examples
>>> rng = torch.manual_seed(5) >>> inputs = torch.rand(1, 3, 3, 3) >>> aug = RandomSaltAndPepperNoise(amount=0.5, salt_vs_pepper=0.5, p=1.) >>> aug(inputs) tensor([[[[1.0000, 0.0000, 0.0000], [1.0000, 1.0000, 0.1166], [0.1644, 0.7379, 0.0000]], [[1.0000, 0.0000, 0.0000], [1.0000, 1.0000, 0.7150], [0.5793, 0.9809, 0.0000]], [[1.0000, 0.0000, 0.0000], [1.0000, 1.0000, 0.7850], [0.9752, 0.0903, 0.0000]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomSaltAndPepperNoise(amount=0.05, salt_vs_pepper=0.5, p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomSaturation(saturation=(1.0, 1.0), same_on_batch=False, p=1.0, keepdim=False)[source]#
Scale the HSV saturation of a three-channel image by a random factor.
output = RandomSaturation(saturation)(input)scales only the HSV saturation of each selected image by a sampled factor. UseColorJitterfor torchvision-compatible saturation, which blends the image with its grayscale,factor * input + (1 - factor) * gray.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation. Default:1.0saturation (
Tuple[float,float], optional) – the saturation factor to apply. Default:(1.0, 1.0)same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the input must have three channels: the scaling is defined on the HSV saturation, and any other channel count raises a
ValueErroron the forward pass.the drawn factor reaches
kornia.enhance.adjust_saturation()unchanged, and1.0is the identity, up to rounding, for a pixel in[0, 1].the HSV saturation is also clamped into
[0, 1]before converting back to RGB.
Note
This function internally uses
kornia.enhance.adjust_saturation()See also
RandomHue: rotates hue instead of scaling saturation.ColorJiggle: combines HSV saturation scaling with Kornia color adjustments.ColorJitter: uses torchvision-compatible grayscale-blend saturation.
Examples
>>> rng = torch.manual_seed(0) >>> inputs = torch.rand(1, 3, 3, 3) >>> aug = RandomSaturation(saturation = (0.5,2.),p=1.) >>> aug(inputs) tensor([[[[0.5569, 0.7682, 0.3529], [0.4811, 0.3474, 0.7411], [0.5028, 0.8964, 0.6772]], [[0.6323, 0.5358, 0.5265], [0.4203, 0.2706, 0.5525], [0.5185, 0.7863, 0.8681]], [[0.3711, 0.4989, 0.6816], [0.9152, 0.3971, 0.8742], [0.4636, 0.7060, 0.9527]]]])
To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.rand(1, 3, 32, 32) >>> aug = RandomSaturation((0.8,1.2), p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomSharpness(sharpness=0.5, same_on_batch=False, p=0.5, keepdim=False)[source]#
Blend each sample with a
3 x 3smoothed copy by a random factor, with probabilityp(default 0.5).output = RandomSharpness(sharpness, ...)(input)blends each selected(B, C, H, W)image with its local smooth version.A drawn factor above
1sharpens and a factor below1blurs; the defaultsharpness=0.5draws from[0, 0.5]and therefore only ever blurs.
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation to each sample. Default:0.5sharpness (
Union[Tensor,float,Tuple[float,float]], optional) – the blend factor between the blurred image and the input. Ifsharpnessis a single non-negative numberx, the factor is sampled from[0, x]; a tuple gives the range directly. Default:0.5same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the factor blends between the fully blurred image at
0and the input at1, and values above1sharpen. The one-pixel border is copied from the input at every factor, so it is never blurred or sharpened, although the final clamp into[0, 1]applies to it as to the rest.a scalar argument is the upper bound of
[0, x], so the defaultsharpness=0.5never reaches the identity and only blurs.
Note
The smoothing kernel is a fixed
3 x 3convolved with no padding, so both spatial sides must be at least3pixels; a smaller image raises aValueErrornaming the class and the input shape.Note
This function internally uses
kornia.enhance.sharpness().See also
RandomBoxBlur: smooths rather than blends an image with its smoothed copy.
Examples
>>> rng = torch.manual_seed(0) >>> input = torch.rand(1, 1, 5, 5) >>> sharpness = RandomSharpness(1., p=1.) >>> sharpness(input) tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074], [0.6341, 0.4810, 0.7367, 0.4177, 0.6323], [0.3489, 0.4428, 0.1562, 0.2443, 0.2939], [0.5185, 0.6462, 0.7050, 0.2288, 0.2823], [0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomSharpness(1., p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
- class kornia.augmentation.RandomSnow(snow_coefficient=(0.5, 0.5), brightness=(2, 2), same_on_batch=False, p=1.0, keepdim=False)[source]#
Create an HLS snow effect on selected RGB images.
output = RandomSnow(snow_coefficient, brightness, ...)(input)brightens pixels of selected(B, 3, H, W)images according to a sampled snow threshold.See the Convention block on
IntensityAugmentationBase2D.- Parameters:
snow_coefficient (
Tuple[float,float], optional) – A tuple of floats (lower and upper bound) between 0 and 1 that control Default:(0.5, 0.5)image (the amount of snow to add to the)
snow. (brightness of the)
brightness (
Tuple[float,float], optional) – A tuple of floats (lower and upper bound) of1or greater that controls the Default:(2, 2)snow.
same_on_batch (
bool, optional) – If True, apply the same transformation to each image in a batch. Default: False.p (
float, optional) – Probability of applying the transformation. Default: 1.0.keepdim (
bool, optional) – Keep the output torch.Tensor with the same shape as input. Default: False.
- Shape:
Input:
(C, H, W)or(B, C, H, W)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the input must have three channels: the effect is computed in HLS, and any other channel count raises on the forward pass.
snow_coefficientis checked against[0, 1]at construction, wherebrightnessmust be1or greater.a pixel whose lightness is below
snow_coefficienthas its lightness scaled bybrightness; it becomes white once that lightness reaches1.
See also
RandomRain: creates rain streaks rather than an HLS snow effect.
Examples
>>> inputs = torch.rand(2, 3, 4, 4) >>> snow = kornia.augmentation.RandomSnow(p=1.0, snow_coefficient=(0.1, 0.6), brightness=(1.0, 5.0)) >>> output = snow(inputs) >>> output.shape torch.Size([2, 3, 4, 4])
- class kornia.augmentation.RandomSolarize(thresholds=0.1, additions=0.1, same_on_batch=False, p=0.5, keepdim=False)[source]#
Solarize images at a random threshold and addition, applied per sample with probability
p(default 0.5).output = RandomSolarize(thresholds, additions, ...)(input)offsets then inverts selected image values above a sampled threshold, after clamping the selected input to[0, 1].
See the Convention block on
IntensityAugmentationBase2D.- Parameters:
p (
float, optional) – probability of applying the transformation to each sample. Default:0.5thresholds (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – If float x, threshold will be generated from (0.5 - x, 0.5 + x). If tuple (x, y), threshold will be generated from (x, y). Default:0.1additions (
Union[Tensor,float,Tuple[float,float],List[float]], optional) – If float x, addition will be generated from (-x, x). If tuple (x, y), addition will be generated from (x, y). Default:0.1same_on_batch (
bool, optional) – apply the same transformation across the batch. Default:Falsekeepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Shape:
Input:
(C, H, W)or(B, C, H, W), Optional:(B, 3, 3)Output:
(B, C, H, W)
- Convention:
input values are clamped into
[0, 1]before the operation, and the result is clamped into the same range. This applies only to samples selected by the probability gate.the addition comes first: the drawn
additionsvalue is added to the whole image and the sum is clamped into[0, 1], and only then is everything at or above the drawnthresholdsreplaced by1 - value.the scalar forms are centered, not absolute: a scalar
thresholdsis a half-width around0.5and a scalaradditionsa half-width around0, so the class defaults center onkornia.enhance.solarize()’s own default threshold rather than equalling it.an explicit
additionsrange is checked against the closed[-0.5, 0.5]at construction, so a range that reaches an endpoint is applied rather than rejected.
Note
This function internally uses
kornia.enhance.solarize().See also
RandomInvert: inverts every pixel rather than values above a threshold.RandomPosterize: reduces bit depth rather than applying a threshold.
Examples
>>> rng = torch.manual_seed(0) >>> input = torch.rand(1, 1, 5, 5) >>> solarize = RandomSolarize(0.1, 0.1, p=1.) >>> solarize(input) tensor([[[[0.4132, 0.1412, 0.1790, 0.2226, 0.3980], [0.2754, 0.4194, 0.0130, 0.4538, 0.2771], [0.4394, 0.4923, 0.1129, 0.2594, 0.3844], [0.3909, 0.2118, 0.1094, 0.2516, 0.3728], [0.2278, 0.0000, 0.4876, 0.0353, 0.5100]]]])
- To apply the exact augmenation again, you may take the advantage of the previous parameter state:
>>> input = torch.randn(1, 3, 32, 32) >>> aug = RandomSolarize(0.1, 0.1, p=1.) >>> (aug(input) == aug(input, params=aug._params)).all() tensor(True)
Normalization#
Deterministic normalization operators, shape-agnostic for 2D and 3D tensors.
- class kornia.augmentation.Denormalize(mean, std, p=1.0, keepdim=False)[source]#
Restore image channels with supplied mean and standard deviation.
output = Denormalize(mean, std)(input)returnsinput * std + mean.See the Convention block on
IntensityAugmentationBase2D.\[\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}\]Where mean is \((M_1, \ldots, M_n)\) and std \((S_1, \ldots, S_n)\) for n channels,
- Parameters:
mean (
Union[Tensor,Tuple[float],List[float],float]) – Mean for each channel.std (
Union[Tensor,Tuple[float],List[float],float]) – Standard deviations for each channel.p (
float, optional) – probability of applying the transformation. Default:1.0keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Returns:
Denormalised tensor with same size as input
(*, C, H, W).
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].the
meanandstdforms, the batch-widepgate and the storage inflagsare those ofNormalize.this class inverts
Normalizebuilt with the samemeanand nonzerostd, up to floating-point rounding, when both transforms apply and their intermediate values remain finite.the result is not clamped: it is
input * std + meanwhatever range the input is in.
Note
This function internally uses
kornia.enhance.denormalize().See also
Normalize: subtracts mean and divides by standard deviation.RandomAutoContrast: derives a rescaling from each image’s extrema.
Examples
>>> norm = Denormalize(mean=torch.zeros(1, 4), std=torch.ones(1, 4)) >>> x = torch.rand(1, 4, 3, 3) >>> out = norm(x) >>> out.shape torch.Size([1, 4, 3, 3])
- class kornia.augmentation.Normalize(mean, std, p=1.0, keepdim=False)[source]#
Normalize image channels with supplied mean and standard deviation.
output = Normalize(mean, std)(input)returns(input - mean) / std.See the Convention block on
IntensityAugmentationBase2D.\[\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}\]Where mean is \((M_1, \ldots, M_n)\) and std \((S_1, \ldots, S_n)\) for n channels,
- Parameters:
mean (
Tensor|tuple[float,...] |list[float] |float) – Mean for each channel.std (
Tensor|tuple[float,...] |list[float] |float) – Standard deviations for each channel.p (
float, optional) – probability of applying the transformation. Default:1.0keepdim (
bool, optional) – whether to keep the output shape the same as input (True) or broadcast it to the batch form (False). Default:False
- Returns:
Normalised tensor with same size as input
(*, C, H, W).
- Convention:
this operation is range-independent: it does not clamp the input into
[0, 1].meanandstdaccept a float, a per-channel sequence or tensor, or a per-sample(B, C)tensor; a length that is neither1nor the channel count raises.pgates the whole batch rather than each sample: the constructor hard-codessame_on_batch=Trueand takes nosame_on_batchargument.the statistics live in
flagsrather than in a buffer:state_dict()is empty andModule.to(...)does not move them; they are cast to the input’s device and dtype on each call. A float64 input uses ameanorstdgiven as numbers exactly, rather than the float32 rounding held inflags, unless that entry has been changed since construction.Denormalizebuilt with the samemeanand nonzerostdinverts this class, up to floating-point rounding, when both transforms apply and their intermediate values remain finite.the result is not clamped: moving an image out of
[0, 1]is what this class is for.
Note
This function internally uses
kornia.enhance.normalize().See also
Denormalize: reverses this operation when both use the same statistics and apply.RandomAutoContrast: derives a rescaling from each image rather than supplied statistics.
Examples
>>> norm = Normalize(mean=torch.zeros(4), std=torch.ones(4)) >>> x = torch.rand(1, 4, 3, 3) >>> out = norm(x) >>> out.shape torch.Size([1, 4, 3, 3])