Adjustment#
Hue and saturation adjustments and shift_rgb() take RGB channels at axis -3. Functions
whose name ends in _raw take HSV instead; their RGB counterparts perform that conversion.
The other functions accept any channel count. sharpness() filters neighboring pixels and
adjust_contrast_with_mean_subtraction() subtracts an image mean, so their output also
depends on the rest of the image.
Three adjustments have two definitions, and the second of each pair matches PIL’s ImageEnhance:
Adjustment |
Direct |
Matches PIL |
|---|---|---|
Brightness |
|
|
Contrast |
|
|
Saturation |
|
|
The brightness, contrast, gamma, logarithmic and sigmoid adjustments,
adjust_brightness_accumulative(), adjust_contrast_with_mean_subtraction(),
adjust_saturation_with_gray_subtraction(), posterize(), solarize(),
sharpness() and shift_rgb() expect a floating-point image in [0, 1] and raise
TypeCheckError (a TypeError) for an integer image; convert
8-bit data with image.float() / 255 first. adjust_hue(), adjust_saturation(),
add_weighted() and invert() (with max_val) also accept integer input.
Functions#
- kornia.enhance.add_weighted(src1, alpha, src2, beta, gamma)[source]#
Blend two tensors as a weighted sum.
out = add_weighted(src1, alpha, src2, beta, gamma)returnssrc1 * alpha + src2 * beta + gammafor two tensors of one shape, without clamping.
- Convention:
A tensor coefficient must broadcast to the shape of
src1without enlarging it: a 0-d scalar,(C, 1, 1)or a per-image(B, 1, 1, 1)weight. A(B,)weight lines up with the width axis, not the batch: it raises unlessBequalsWor 1, and then it weights columns. Use(B, 1, 1, 1)for one weight per image.
- Parameters:
- Return type:
- Returns:
Weighted sum with the shape of
src1.
See also
AddWeighted: the module form.
Example
>>> input1 = torch.rand(1, 1, 5, 5) >>> input2 = torch.rand(1, 1, 5, 5) >>> output = add_weighted(input1, 0.5, input2, 0.5, 1.0) >>> output.shape torch.Size([1, 1, 5, 5])
- kornia.enhance.adjust_brightness(image, factor, clip_output=True)[source]#
Adjust the brightness of an image by adding a factor to its values.
out = adjust_brightness(image, factor)addsfactorto every value of an image in \([0, 1]\);0leaves it unchanged. PIL multiplies instead, which isadjust_brightness_accumulative().
- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
image.
Note
See a working example here.
See also
adjust_brightness_accumulative(): multiplies instead of adding.adjust_gamma(): a power curve, which maps \([0, 1]\) onto itself atgain=1.shift_rgb(): adds a different shift to each color channel.AdjustBrightness: the module form.
Example
>>> x = torch.ones(1, 1, 2, 2) >>> adjust_brightness(x, 1.) tensor([[[[1., 1.], [1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.tensor([0.25, 0.50]) >>> adjust_brightness(x, y).shape torch.Size([2, 5, 3, 3])
- kornia.enhance.adjust_brightness_accumulative(image, factor, clip_output=True)[source]#
Multiply an image by a factor to brighten or darken it, as PIL’s
ImageEnhance.Brightnessdoes.out = adjust_brightness_accumulative(image, factor)multiplies an image in \([0, 1]\) byfactor:0gives black,1leaves it unchanged and a larger factor brightens it.- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
image.
See also
adjust_brightness(): adds the factor.adjust_contrast(): the same product, but a negative factor raises.AdjustBrightnessAccumulative: the module form.
Example
>>> x = torch.ones(1, 1, 2, 2) >>> adjust_brightness_accumulative(x, 1.) tensor([[[[1., 1.], [1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.tensor([0.25, 0.50]) >>> adjust_brightness_accumulative(x, y).shape torch.Size([2, 5, 3, 3])
- kornia.enhance.adjust_contrast(image, factor, clip_output=True)[source]#
Adjust the contrast of an image by multiplying its values by a factor.
out = adjust_contrast(image, factor)multiplies an image in \([0, 1]\) byfactor:0gives black and1leaves it unchanged. To blend with the mean gray level instead, as PIL does, useadjust_contrast_with_mean_subtraction().
- Convention:
Multiplicative, as in Szeliski’s book and OpenCV’s
convertScaleAbs(alpha=factor).
- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
image.
Note
See a working example here.
Note
The non-negativity check on
factorreads a CPU value during the call and raisesAsyncCheckError, aRuntimeError. A tensor on CUDA, or on MPS from torch 2.13, is checked withtorch._assert_asyncinstead and raisesRuntimeErrorby the next synchronization; on CUDA that is a device-side assert.See also
adjust_contrast_with_mean_subtraction(): blends with the mean gray level instead of scaling.adjust_brightness_accumulative(): the same product, with a negative factor accepted.adjust_gamma(): a power curve, which maps \([0, 1]\) onto itself atgain=1.AdjustContrast: the module form.
Example
>>> import torch >>> x = torch.ones(1, 1, 2, 2) >>> adjust_contrast(x, 0.5) tensor([[[[0.5000, 0.5000], [0.5000, 0.5000]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.tensor([0.65, 0.50]) >>> adjust_contrast(x, y).shape torch.Size([2, 5, 3, 3])
- kornia.enhance.adjust_contrast_with_mean_subtraction(image, factor)[source]#
Adjust the contrast of an image by blending it with its mean gray level, as PIL does.
out = adjust_contrast_with_mean_subtraction(image, factor)returnsfactor * image + (1 - factor) * mean, clamped to \([0, 1]\), for an image in \([0, 1]\).meanis the mean of the image’s grayscale for 3 channels and of all its values otherwise;0gives a uniform image and1the input.- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
image.
See also
adjust_contrast(): multiplies the values, so the mean moves with them.adjust_gamma(): a power curve, which maps \([0, 1]\) onto itself atgain=1.AdjustContrastWithMeanSubtraction: the module form.
Example
>>> import torch >>> x = torch.ones(1, 1, 2, 2) >>> adjust_contrast_with_mean_subtraction(x, 0.5) tensor([[[[1., 1.], [1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.tensor([0.65, 0.50]) >>> adjust_contrast_with_mean_subtraction(x, y).shape torch.Size([2, 5, 3, 3])
- kornia.enhance.adjust_gamma(input, gamma, gain=1.0)[source]#
Apply gamma correction
gain * input ** gammato an image.out = adjust_gamma(input, gamma, gain)takes an image in \([0, 1]\) and clamps the result to \([0, 1]\);gamma > 1darkens the shadows andgamma < 1lightens them.
- Convention:
For
0 < gamma < 1the derivative ofinput ** gammaat a black pixel (input == 0) is infinite; the gradient there is 0 instead. A graph captured bytorch.jit.tracekeeps the plain power, whose gradient there is not finite.
- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
input.
Note
See a working example here.
Note
The non-negativity check on
gamma/gainreads a CPU value during the call and raisesAsyncCheckError, aRuntimeError. A tensor on CUDA, or on MPS from torch 2.13, is checked withtorch._assert_asyncinstead and raisesRuntimeErrorby the next synchronization; on CUDA that is a device-side assert.See also
AdjustGamma: the module form.adjust_sigmoid(): an S-shaped curve around a cutoff.adjust_log(): a logarithmic curve.
Example
>>> x = torch.ones(1, 1, 2, 2) >>> adjust_gamma(x, 1.0, 2.0) tensor([[[[1., 1.], [1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y1 = torch.ones(2) * 1.0 >>> y2 = torch.ones(2) * 2.0 >>> adjust_gamma(x, y1, y2).shape torch.Size([2, 5, 3, 3])
- kornia.enhance.adjust_hue(image, factor)[source]#
Shift the hue of an RGB image by an angle in radians.
out = adjust_hue(image, factor)rotates the hue of a(*, 3, H, W)RGB image in \([0, 1]\) byfactorradians and returns RGB.
- Convention:
factoris any angle in radians, taken modulo \(2\pi\):factorandfactor + 2πagree,±πgives the complementary colors, and a positive angle turns red towards green.torchvision’s
adjust_huetakes a fraction of a turn in \([-0.5, 0.5]\): itshue_factorisfactor / (2 * pi)forfactorin \([-\pi, \pi]\).
- Parameters:
- Return type:
- Returns:
Adjusted image with shape
(*, 3, H, W).
Note
See a working example here.
See also
adjust_hue_raw(): the same shift on an HSV image.AdjustHue: the module form.
Example
>>> x = torch.ones(1, 3, 2, 2) >>> adjust_hue(x, 3.141516).shape torch.Size([1, 3, 2, 2])
>>> x = torch.ones(2, 3, 3, 3) >>> y = torch.ones(2) * 3.141516 >>> adjust_hue(x, y).shape torch.Size([2, 3, 3, 3])
- kornia.enhance.adjust_hue_raw(image, factor)[source]#
Shift the hue channel of an HSV image by an angle in radians, wrapping it into [0, 2π).
out = adjust_hue_raw(image, factor)addsfactorradians to channel 0 (hue) of a(*, 3, H, W)HSV image and wraps the sum into \([0, 2\pi)\), leaving saturation and value as they are. For an RGB image, useadjust_hue().- Parameters:
- Return type:
- Returns:
HSV image with shape
(*, 3, H, W).
See also
adjust_hue(): the same shift on an RGB image.adjust_saturation_raw(): scales the saturation of an HSV image.rgb_to_hsv(): makes the HSV image this takes, with hue in radians.
- kornia.enhance.adjust_saturation(image, factor)[source]#
Adjust the saturation of an RGB image by scaling its HSV saturation channel.
out = adjust_saturation(image, factor)multiplies the HSV saturation of a(*, 3, H, W)RGB image in \([0, 1]\) byfactor, clamps it to \([0, 1]\) and returns RGB.0gives gray pixels equal to max(R, G, B), not the gray level; for PIL’s blend with the gray level, useadjust_saturation_with_gray_subtraction().
- Parameters:
- Return type:
- Returns:
Adjusted image with shape
(*, 3, H, W).
Note
See a working example here.
See also
adjust_saturation_with_gray_subtraction(): blends with the gray image instead of scaling the HSV saturation.adjust_saturation_raw(): the same scaling on an HSV image.AdjustSaturation: the module form.
Example
>>> x = torch.ones(1, 3, 3, 3) >>> adjust_saturation(x, 2.).shape torch.Size([1, 3, 3, 3])
>>> x = torch.ones(2, 3, 3, 3) >>> y = torch.tensor([1., 2.]) >>> adjust_saturation(x, y).shape torch.Size([2, 3, 3, 3])
- kornia.enhance.adjust_saturation_raw(image, factor)[source]#
Scale the saturation channel of an HSV image by a factor and clamp it to [0, 1].
out = adjust_saturation_raw(image, factor)multiplies channel 1 (saturation) of a(*, 3, H, W)HSV image byfactor, clamps it to \([0, 1]\) and leaves hue and value as they are. For an RGB image, useadjust_saturation().- Parameters:
- Return type:
- Returns:
HSV image with shape
(*, 3, H, W).
See also
adjust_saturation(): the same scaling on an RGB image.adjust_hue_raw(): shifts the hue of an HSV image.
- kornia.enhance.adjust_saturation_with_gray_subtraction(image, factor)[source]#
Adjust the saturation of an RGB image by blending it with its grayscale version, as PIL does.
out = adjust_saturation_with_gray_subtraction(image, factor)returnsfactor * image + (1 - factor) * grayfor a(*, 3, H, W)RGB image in \([0, 1]\), clamped to \([0, 1]\):0gives the gray image and1the input. A single-channel image is returned unchanged.- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
image.
See also
adjust_saturation(): scales HSV saturation, so0gives max(R, G, B) instead of the gray level.AdjustSaturationWithGraySubtraction: the module form.
Example
>>> x = torch.ones(1, 3, 3, 3) >>> adjust_saturation_with_gray_subtraction(x, 2.).shape torch.Size([1, 3, 3, 3])
>>> x = torch.ones(2, 3, 3, 3) >>> y = torch.tensor([1., 2.]) >>> adjust_saturation_with_gray_subtraction(x, y).shape torch.Size([2, 3, 3, 3])
- kornia.enhance.adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False)[source]#
Apply sigmoid correction around a cutoff to an image.
out = adjust_sigmoid(image, cutoff, gain, inv)maps an image in \([0, 1]\) through the curve \(1 / (1 + e^{\text{gain}\,(\text{cutoff} - x)})\), which equals 0.5 atcutoff. Withinv=Trueit returns one minus that curve.- Reference:
- [1]: Gustav J. Braun, “Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions”,
- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
image.
See also
AdjustSigmoid: the module form.adjust_gamma(): a power curve.adjust_log(): a logarithmic curve.
Example
>>> x = torch.ones(1, 1, 2, 2) >>> adjust_sigmoid(x, gain=0) tensor([[[[0.5000, 0.5000], [0.5000, 0.5000]]]])
- kornia.enhance.adjust_log(image, gain=1, inv=False, clip_output=True)[source]#
Apply logarithmic correction to an image, or exponential correction with
inv.out = adjust_log(image, gain, inv, clip_output)returnsgain * log2(1 + image)for an image in \([0, 1]\), orgain * (2 ** image - 1)withinv=True.- Parameters:
- Return type:
- Returns:
Adjusted image with the shape of
image.
See also
AdjustLog: the module form.adjust_gamma(): a power curve.adjust_sigmoid(): an S-shaped curve around a cutoff.
Example
>>> x = torch.zeros(1, 1, 2, 2) >>> adjust_log(x, inv=True) tensor([[[[0., 0.], [0., 0.]]]])
- kornia.enhance.invert(image, max_val=None)[source]#
Invert an image by subtracting it from its maximum value.
out = invert(image, max_val)returnsmax_val - image.
- Parameters:
- Return type:
- Returns:
Inverted tensor with the shape of
image.
See also
Invert: the module form.solarize(): inverts only the pixels at or above a threshold.RandomInvert: inverts at random per image.
Example
>>> img = torch.rand(1, 2, 4, 4) >>> invert(img).shape torch.Size([1, 2, 4, 4])
>>> img = 255. * torch.rand(1, 2, 3, 4, 4) >>> invert(img, torch.as_tensor(255.)).shape torch.Size([1, 2, 3, 4, 4])
>>> img = torch.rand(1, 3, 4, 4) >>> invert(img, torch.as_tensor([[[[1.]]]])).shape torch.Size([1, 3, 4, 4])
- kornia.enhance.posterize(input, bits)[source]#
Keep only the highest
bitsof the 8 bits of each color level, as PIL’sImageOps.posterizedoes.out = posterize(input, bits)quantizes an image in \([0, 1]\) to itsbitshighest bits per value:bits=8returns the input andbits=0gives black.
- Convention:
Each value is read at its 8-bit level
(x * 255).long(), with the 255 raised by four float32 epsilons, relative, in float32 and float64, sok / 255reads levelkeven when its division was rounded a unit low, as dividing by 255 on CUDA does.The gradient is zero, except for
bits=8, which returns the input.Empty leading dimensions are supported; channels and spatial dimensions must be non-empty.
- Parameters:
input (
Tensor) – image with shape(*, C, H, W).bits (
Union[int,Tensor]) – number of high bits to keep, in[0, 8]. An integer or a one-element tensor applies to the whole batch. A tensor with shape(B,)gives one value per image, one with shape(B, C)one per channel, and a longer prefix of(B, C, H, W)element-wise values, whereBis the product of the leading dimensions ofinput.
- Return type:
- Returns:
Image with the shape of
input.- Raises:
AssertionError – if a
bitstensor does not match the leading dimensions ofinput.AsyncCheckError – if
bitsis outside[0, 8]; it is aValueErrorand aRuntimeError. Abitstensor on CUDA, or on MPS from torch 2.13, is checked withtorch._assert_asyncinstead and raisesRuntimeErrorby the next synchronization.
See also
RandomPosterize: drawsbitsat random per image.solarize(): inverts pixels above a threshold instead.
Example
>>> x = torch.rand(1, 6, 3, 3) >>> out = posterize(x, bits=8) >>> torch.testing.assert_close(x, out)
>>> x = torch.rand(2, 6, 3, 3) >>> bits = torch.tensor([4, 2]) >>> posterize(x, bits).shape torch.Size([2, 6, 3, 3])
- kornia.enhance.sharpness(input, factor)[source]#
Blend an image with a smoothed copy to sharpen or blur it, as PIL’s
ImageEnhance.Sharpnessdoes.out = sharpness(input, factor)blends a(*, C, H, W)image in \([0, 1]\) with a copy smoothed by a 3x3 kernel:0returns the smoothed image,1the input, and a factor above1sharpens. The result is clamped to \([0, 1]\).
- Convention:
The smoothing kernel is \(\tfrac{1}{13}[[1, 1, 1], [1, 5, 1], [1, 1, 1]]\), and the one-pixel border keeps the input’s values.
Empty leading dimensions are supported; channels must be non-empty and both spatial dimensions at least 3 pixels.
- Parameters:
input (
Tensor) – image with shape(*, C, H, W).factor (
Union[float,Tensor]) – blend weight of the input against the smoothed copy. A float or a 0-d tensor applies to the whole batch, and a tensor with shape(B,)gives one value per image, whereBis the product of the leading dimensions ofinput. A(1,)tensor applies to every image. Negative factors are accepted and extrapolate past the smoothed image.
- Return type:
- Returns:
Sharpened image with the shape of
input.
See also
unsharp_mask(): adds back the detail a Gaussian blur removes, with a fixed gain and no clamp.RandomSharpness: drawsfactorat random per image.
Example
>>> x = torch.rand(1, 1, 5, 5) >>> sharpness(x, 0.5).shape torch.Size([1, 1, 5, 5])
- kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)[source]#
Add a shift to each color channel of an RGB image.
out = shift_rgb(image, r_shift, g_shift, b_shift)adds the red, green and blue shifts to the channels of an RGB image(B, 3, H, W)in \([0, 1]\) and clamps the result to \([0, 1]\).- Convention:
Ranks below three or a channel count other than three raise
ImageError. Other ranks that pass the color check but are not four raiseShapeError. The three shifts must share the same shape.
- Parameters:
- Return type:
- Returns:
Shifted image with shape
(B, 3, H, W).
See also
adjust_brightness(): adds one factor to every channel.
Example
>>> image = torch.zeros(1, 3, 2, 2) >>> shift_rgb(image, torch.tensor([0.2]), torch.tensor([0.0]), torch.tensor([-0.1]))[0, :, 0, 0] tensor([0.2000, 0.0000, 0.0000])
- kornia.enhance.solarize(input, thresholds=0.5, additions=None)[source]#
Invert the pixels at or above a threshold, optionally after adding an amount to every pixel.
out = solarize(input, thresholds, additions)replaces every value of an image in \([0, 1]\) that is at or abovethresholdsby1 - value. Withoutadditionsit equals PIL’sImageOps.solarize.
- Convention:
additionsis added to the whole image and the sum clamped to \([0, 1]\) before the comparison, so it can move a pixel across the threshold: withthresholds=0.5andadditions=0.2,[0.1, 0.4, 0.6, 0.9]comes back as[0.3, 0.4, 0.2, 0.0].
- Parameters:
input (
Tensor) – image with shape(*, C, H, W).thresholds (
Union[float,Tensor], optional) – threshold in \([0, 1]\), a float or a tensor. One value, as a float or a one-element tensor, applies to the whole batch, and a tensor with shape(B,)gives one value per image. Default:0.5additions (
Union[Tensor,float,None], optional) – amount in \([-0.5, 0.5]\), endpoints included, with the shapes ofthresholds.Noneadds nothing. Default:None
- Return type:
- Returns:
The solarized image with shape
(*, C, H, W).
Note
The range check on
additionsreads a float or a CPU tensor during the call and raisesAsyncCheckError, aRuntimeError, whatever the device of the image. A tensor on CUDA, or on MPS from torch 2.13, is checked withtorch._assert_asyncinstead and raisesRuntimeErrorby the next synchronization; on CUDA that is a device-side assert.See also
RandomSolarize: drawsthresholdsandadditionsat random per image.posterize(): reduces the bit depth instead of inverting.invert(): inverts every pixel.
Example
>>> x = torch.rand(1, 4, 3, 3) >>> out = solarize(x, thresholds=0.5, additions=0.) >>> out.shape torch.Size([1, 4, 3, 3])
>>> x = torch.rand(2, 4, 3, 3) >>> thresholds = torch.tensor([0.8, 0.5]) >>> additions = torch.tensor([-0.25, 0.25]) >>> solarize(x, thresholds, additions).shape torch.Size([2, 4, 3, 3])
- kornia.enhance.threshold(input, thresh, maxval=255.0, type=ThresholdType.THRESH_BINARY)[source]#
Threshold every element at a fixed level, as
cv2.thresholddoes.out = threshold(input, thresh, maxval, type)compares each element withthreshand maps it tomaxval,0,threshor itself, as theThresholdTypetypesays. It takes tensors forthreshandmaxval.- Convention:
The comparison is strict: an element passes when
input > thresh.threshandmaxvalbroadcast overinputand move to its device.maxvalis converted to the dtype ofinput, and so isthreshfor a floating-point input.On an integer input
threshis not cast: as in OpenCV, an element passes when it is greater thanfloor(thresh). Athreshbelow the dtype’s range passes every element and one at or above its maximum passes none.THRESH_TRUNCthen writesfloor(thresh), or the dtype’s minimum for athreshbelow its range.
- Parameters:
input (
Tensor) – tensor with shape(*, H, W).thresh (
Union[float,Tensor]) – level, a number or a tensor that broadcasts toinput.maxval (
Union[float,Tensor], optional) – value written by the binary modes, a number or a tensor. The default255.0turns a \([0, 1]\) image into 0 and 255; pass1.0to keep its range. Default:255.0type (
Union[int,ThresholdType], optional) – aThresholdTypemember or its value. Default:ThresholdType.THRESH_BINARY
- Return type:
- Returns:
Thresholded tensor with the shape, dtype and device of
input.- Raises:
NotImplementedError – if
THRESH_OTSUis passed.BaseError – if
typeis not a supported mode.
See also
Threshold: the module form.otsu_threshold(): finds the level itself with Otsu’s method.
Example
>>> x = torch.tensor([[0.2, 0.8]]) >>> threshold(x, 0.5, 1.0) tensor([[0., 1.]]) >>> threshold(x, 0.5, 1.0, ThresholdType.THRESH_TRUNC) tensor([[0.2000, 0.5000]])
Modules#
- class kornia.enhance.AdjustBrightness(brightness_factor)[source]#
Adjust the brightness of an image by adding a stored factor (module form).
adjust = AdjustBrightness(brightness_factor)stores the factor, andout = adjust(image)isadjust_brightness()with it andclip_output=True.- Parameters:
brightness_factor (
Union[float,Tensor]) – value to add, a float or a tensor with shape(B,).
- Shape:
Input:
(*, H, W)Output:
(*, H, W)
See also
adjust_brightness(): the one-call form, withclip_output.AdjustBrightnessAccumulative: multiplies instead of adding.
Example
>>> x = torch.ones(1, 1, 3, 3) >>> AdjustBrightness(1.)(x) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.ones(2) >>> AdjustBrightness(y)(x).shape torch.Size([2, 5, 3, 3])
- class kornia.enhance.AdjustBrightnessAccumulative(brightness_factor)[source]#
Multiply an image by a stored factor to brighten or darken it (module form).
adjust = AdjustBrightnessAccumulative(brightness_factor)stores the factor, andout = adjust(image)isadjust_brightness_accumulative()with it andclip_output=True.- Parameters:
brightness_factor (
Union[float,Tensor]) – multiplier, a float or a tensor with shape(B,).
- Shape:
Input:
(*, H, W)Output:
(*, H, W)
See also
adjust_brightness_accumulative(): the one-call form, withclip_output.AdjustBrightness: adds the factor instead.
Example
>>> x = torch.ones(1, 1, 3, 3) >>> AdjustBrightnessAccumulative(1.)(x) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.ones(2) >>> AdjustBrightnessAccumulative(y)(x).shape torch.Size([2, 5, 3, 3])
- class kornia.enhance.AdjustContrast(contrast_factor)[source]#
Adjust the contrast of an image by multiplying its values by a stored factor (module form).
adjust = AdjustContrast(contrast_factor)stores the factor, andout = adjust(image)isadjust_contrast()with it andclip_output=True.- Convention:
See the convention block of
adjust_contrast().
- Parameters:
contrast_factor (
Union[float,Tensor]) – non-negative multiplier, a float or a tensor with shape(B,).
- Shape:
Input:
(*, H, W)Output:
(*, H, W)
See also
adjust_contrast(): the one-call form, withclip_output.AdjustContrastWithMeanSubtraction: blends with the mean gray level instead of scaling.
Example
>>> x = torch.ones(1, 1, 3, 3) >>> AdjustContrast(0.5)(x) tensor([[[[0.5000, 0.5000, 0.5000], [0.5000, 0.5000, 0.5000], [0.5000, 0.5000, 0.5000]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.ones(2) >>> AdjustContrast(y)(x).shape torch.Size([2, 5, 3, 3])
- class kornia.enhance.AdjustContrastWithMeanSubtraction(contrast_factor)[source]#
Adjust the contrast of an image by blending it with its mean gray level (module form).
adjust = AdjustContrastWithMeanSubtraction(contrast_factor)stores the factor, andout = adjust(image)isadjust_contrast_with_mean_subtraction()with it.- Parameters:
contrast_factor (
Union[float,Tensor]) – weight of the image, a float or a tensor with shape(B,).
- Shape:
Input:
(*, C, H, W)Output:
(*, C, H, W)
See also
adjust_contrast_with_mean_subtraction(): the one-call form.AdjustContrast: multiplies the values instead.
Example
>>> x = torch.ones(1, 1, 3, 3) >>> AdjustContrastWithMeanSubtraction(0.5)(x) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y = torch.ones(2) >>> AdjustContrastWithMeanSubtraction(y)(x).shape torch.Size([2, 5, 3, 3])
- class kornia.enhance.AdjustSaturation(saturation_factor)[source]#
Adjust the saturation of an RGB image by scaling its HSV saturation (module form).
adjust = AdjustSaturation(saturation_factor)stores the factor, andout = adjust(image)isadjust_saturation()with it.- Parameters:
saturation_factor (
Union[float,Tensor]) – saturation multiplier, a float or a tensor with shape(B,).
- Shape:
Input:
(*, 3, H, W)Output:
(*, 3, H, W)
See also
adjust_saturation(): the one-call form.AdjustSaturationWithGraySubtraction: blends with the gray image instead of scaling the HSV saturation.
Example
>>> x = torch.ones(1, 3, 3, 3) >>> AdjustSaturation(2.)(x) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
>>> x = torch.ones(2, 3, 3, 3) >>> y = torch.ones(2) >>> out = AdjustSaturation(y)(x) >>> torch.nn.functional.mse_loss(x, out) tensor(0.)
- class kornia.enhance.AdjustSaturationWithGraySubtraction(saturation_factor)[source]#
Adjust the saturation of an RGB image by blending it with its grayscale version (module form).
adjust = AdjustSaturationWithGraySubtraction(saturation_factor)stores the factor, andout = adjust(image)isadjust_saturation_with_gray_subtraction()with it.- Parameters:
saturation_factor (
Union[float,Tensor]) – weight of the image, a float or a tensor with shape(B,).
- Shape:
Input:
(*, 3, H, W)or(*, 1, H, W)Output: same as the input
See also
adjust_saturation_with_gray_subtraction(): the one-call form.AdjustSaturation: scales the HSV saturation instead.
Example
>>> x = torch.ones(1, 3, 3, 3) >>> AdjustSaturationWithGraySubtraction(2.)(x) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
>>> x = torch.ones(2, 3, 3, 3) >>> y = torch.ones(2) >>> out = AdjustSaturationWithGraySubtraction(y)(x) >>> torch.nn.functional.mse_loss(x, out) tensor(0.)
- class kornia.enhance.AdjustHue(hue_factor)[source]#
Shift the hue of an RGB image by an angle in radians (module form).
adjust = AdjustHue(hue_factor)stores the angle, andout = adjust(image)isadjust_hue()with it.- Convention:
See the convention block of
adjust_hue().
- Parameters:
hue_factor (
Union[float,Tensor]) – hue shift in radians, a number or a tensor with shape(B,).
- Shape:
Input:
(*, 3, H, W)Output:
(*, 3, H, W)
See also
adjust_hue(): the one-call form.
Example
>>> x = torch.ones(1, 3, 3, 3) >>> AdjustHue(3.141516)(x) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
>>> x = torch.ones(2, 3, 3, 3) >>> y = torch.ones(2) * 3.141516 >>> AdjustHue(y)(x).shape torch.Size([2, 3, 3, 3])
- class kornia.enhance.AdjustGamma(gamma, gain=1.0)[source]#
Apply gamma correction with a stored exponent and gain (module form).
adjust = AdjustGamma(gamma, gain)stores both, andout = adjust(image)isadjust_gamma()with them.- Convention:
See the convention block of
adjust_gamma().
- Parameters:
- Shape:
Input:
(*, H, W)Output:
(*, H, W)
See also
adjust_gamma(): the one-call form.
Example
>>> x = torch.ones(1, 1, 3, 3) >>> AdjustGamma(1.0, 2.0)(x) tensor([[[[1., 1., 1.], [1., 1., 1.], [1., 1., 1.]]]])
>>> x = torch.ones(2, 5, 3, 3) >>> y1 = torch.ones(2) * 1.0 >>> y2 = torch.ones(2) * 2.0 >>> AdjustGamma(y1, y2)(x).shape torch.Size([2, 5, 3, 3])
- class kornia.enhance.AdjustSigmoid(cutoff=0.5, gain=10, inv=False)[source]#
Apply sigmoid correction with a stored cutoff and gain (module form).
adjust = AdjustSigmoid(cutoff, gain, inv)stores its arguments, andout = adjust(image)isadjust_sigmoid()with them.- Reference:
- [1]: Gustav J. Braun, “Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions”,
- Parameters:
- Shape:
Input:
(*, H, W)Output:
(*, H, W)
See also
adjust_sigmoid(): the one-call form.
Example
>>> x = torch.ones(1, 1, 2, 2) >>> AdjustSigmoid(gain=0)(x) tensor([[[[0.5000, 0.5000], [0.5000, 0.5000]]]])
- class kornia.enhance.AdjustLog(gain=1, inv=False, clip_output=True)[source]#
Apply logarithmic correction with a stored gain (module form).
adjust = AdjustLog(gain, inv, clip_output)stores its arguments, andout = adjust(image)isadjust_log()with them.- Parameters:
- Shape:
Input:
(*, H, W)Output:
(*, H, W)
See also
adjust_log(): the one-call form.
Example
>>> x = torch.zeros(1, 1, 2, 2) >>> AdjustLog(inv=True)(x) tensor([[[[0., 0.], [0., 0.]]]])
- class kornia.enhance.AddWeighted(alpha, beta, gamma)[source]#
Blend two tensors as a weighted sum (module form).
op = AddWeighted(alpha, beta, gamma)stores the coefficients andout = op(src1, src2)isadd_weighted()with them. A tensor coefficient is stored as a non-persistent buffer, or as a parameter if it is annn.Parameter.- Convention:
See the convention block of
add_weighted().
- Parameters:
- Shape:
Input1: tensor of any shape.
Input2: tensor with the shape of Input1.
Output: same shape as Input1.
See also
add_weighted(): the one-call form.
Example
>>> input1 = torch.rand(1, 1, 5, 5) >>> input2 = torch.rand(1, 1, 5, 5) >>> output = AddWeighted(0.5, 0.5, 1.0)(input1, input2) >>> output.shape torch.Size([1, 1, 5, 5])
- class kornia.enhance.Rescale(factor)[source]#
Multiply the input by a constant factor.
op = Rescale(factor)storesfactorandout = op(input)returnsinput * factor. A tensor factor is stored as a non-persistent buffer, so.to()moves it, and annn.Parameterstays a parameter that optimizers and checkpoints include.- Convention:
A float factor is applied as a Python number: a float64 input keeps its precision and an integer input promotes to the default float dtype.
- Parameters:
factor (
Union[float,Tensor]) – scaling factor, afloator a 0-d tensor. AnintraisesTypeError.
- Shape:
Input: any shape.
Output: same shape as the input.
See also
Rescale: resizes an image by a factor instead of multiplying its values.adjust_contrast(): multiplies an image by a factor and clamps it to \([0, 1]\).
Example
>>> Rescale(0.5)(torch.ones(1, 1, 2, 2)) tensor([[[[0.5000, 0.5000], [0.5000, 0.5000]]]])
- class kornia.enhance.Invert(max_val=None)[source]#
Invert an image by subtracting it from a stored maximum value (module form).
op = Invert(max_val)storesmax_valas a buffer, or as a parameter if it is annn.Parameter, andout = op(image)isinvert()with it.- Parameters:
max_val (
Optional[Tensor], optional) – tensor the image is subtracted from, broadcastable to the input. The default is1, so for auint8image passtorch.tensor(255). Default:None
- Shape:
Input: any shape
Output: same as the input
See also
invert(): the one-call form.
Example
>>> img = torch.rand(1, 2, 4, 4) >>> Invert()(img).shape torch.Size([1, 2, 4, 4])
>>> img = 255. * torch.rand(1, 2, 3, 4, 4) >>> Invert(torch.as_tensor(255.))(img).shape torch.Size([1, 2, 3, 4, 4])
>>> img = torch.rand(1, 3, 4, 4) >>> Invert(torch.as_tensor([[[[1.]]]]))(img).shape torch.Size([1, 3, 4, 4])
- class kornia.enhance.Threshold(thresh, maxval=255.0, type=ThresholdType.THRESH_BINARY)[source]#
Threshold every element at a fixed level (module form).
op = Threshold(thresh, maxval, type)stores the three values as plain numbers andout = op(input)isthreshold()with them.- Convention:
See the convention block of
threshold();threshandmaxvalare numbers here, not tensors.
- Parameters:
thresh (
float) – level, a number.maxval (
float, optional) – value written by the binary modes, a number. The default255.0turns a \([0, 1]\) image into 0 and 255; pass1.0to keep its range. Default:255.0type (
Union[int,ThresholdType], optional) – aThresholdTypemember or its value. Default:ThresholdType.THRESH_BINARY
See also
threshold(): the one-call form.
Example
>>> Threshold(0.5, 1.0)(torch.tensor([[0.2, 0.8]])) tensor([[0., 1.]])
- class kornia.enhance.ThresholdType(value)[source]#
Select how
threshold()maps each element, with OpenCV’s values for the fixed modes.Pass a member, or its integer value, as
type. Writingxfor an element,tforthreshandmformaxval:THRESH_BINARY(0):mwherex > t, else0.THRESH_BINARY_INV(1):0wherex > t, elsem.THRESH_TRUNC(2):twherex > t, elsex.THRESH_TOZERO(3):xwherex > t, else0.THRESH_TOZERO_INV(4):0wherex > t, elsex.THRESH_OTSU(8): reserved;threshold()raisesNotImplementedErrorfor it, also when it is OR-ed into another mode.
See also
threshold(): applies a mode.Threshold: the module form.