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

adjust_brightness() adds the factor.

adjust_brightness_accumulative() multiplies by it.

Contrast

adjust_contrast() multiplies by the factor.

adjust_contrast_with_mean_subtraction() blends with the mean gray level.

Saturation

adjust_saturation() scales the HSV saturation.

adjust_saturation_with_gray_subtraction() blends with the gray image.

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) returns src1 * alpha + src2 * beta + gamma for two tensors of one shape, without clamping.

_images/add_weighted.png
Convention:

A tensor coefficient must broadcast to the shape of src1 without 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 unless B equals W or 1, and then it weights columns. Use (B, 1, 1, 1) for one weight per image.

Parameters:
  • src1 (Tensor) – tensor of any shape.

  • alpha (Union[float, Tensor]) – weight of src1, a number or a tensor.

  • src2 (Tensor) – tensor with the shape of src1.

  • beta (Union[float, Tensor]) – weight of src2, a number or a tensor.

  • gamma (Union[float, Tensor]) – value added to the sum, a number or a tensor.

Return type:

Tensor

Returns:

Weighted sum with the shape of src1.

See also

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) adds factor to every value of an image in \([0, 1]\); 0 leaves it unchanged. PIL multiplies instead, which is adjust_brightness_accumulative().

_images/adjust_brightness.png
Parameters:
  • image (Tensor) – image with shape (*, H, W).

  • factor (Union[float, Tensor]) – value to add, a float or a tensor with shape (B,) for one value per image.

  • clip_output (bool, optional) – clamp the result to \([0, 1]\). Default: True

Return type:

Tensor

Returns:

Adjusted image with the shape of image.

Note

See a working example here.

See also

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.Brightness does.

out = adjust_brightness_accumulative(image, factor) multiplies an image in \([0, 1]\) by factor: 0 gives black, 1 leaves it unchanged and a larger factor brightens it.

Parameters:
  • image (Tensor) – image with shape (*, H, W).

  • factor (Union[float, Tensor]) – multiplier, a float or a tensor with shape (B,) for one value per image.

  • clip_output (bool, optional) – clamp the result to \([0, 1]\). Default: True

Return type:

Tensor

Returns:

Adjusted image with the shape of image.

See also

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]\) by factor: 0 gives black and 1 leaves it unchanged. To blend with the mean gray level instead, as PIL does, use adjust_contrast_with_mean_subtraction().

_images/adjust_contrast.png
Convention:

Multiplicative, as in Szeliski’s book and OpenCV’s convertScaleAbs(alpha=factor).

Parameters:
  • image (Tensor) – image with shape (*, H, W).

  • factor (Union[float, Tensor]) – non-negative multiplier, a float or a tensor with shape (B,) for one value per image.

  • clip_output (bool, optional) – clamp the result to \([0, 1]\). Default: True

Return type:

Tensor

Returns:

Adjusted image with the shape of image.

Note

See a working example here.

Note

The non-negativity check on factor reads a CPU value during the call and raises AsyncCheckError, a RuntimeError. A tensor on CUDA, or on MPS from torch 2.13, is checked with torch._assert_async instead and raises RuntimeError by the next synchronization; on CUDA that is a device-side assert.

See also

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) returns factor * image + (1 - factor) * mean, clamped to \([0, 1]\), for an image in \([0, 1]\). mean is the mean of the image’s grayscale for 3 channels and of all its values otherwise; 0 gives a uniform image and 1 the input.

Parameters:
  • image (Tensor) – image with shape (*, C, H, W).

  • factor (Union[float, Tensor]) – weight of the image, a float or a tensor with shape (B,) for one value per image.

Return type:

Tensor

Returns:

Adjusted image with the shape of image.

See also

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 ** gamma to an image.

out = adjust_gamma(input, gamma, gain) takes an image in \([0, 1]\) and clamps the result to \([0, 1]\); gamma > 1 darkens the shadows and gamma < 1 lightens them.

_images/adjust_gamma.png
Convention:

For 0 < gamma < 1 the derivative of input ** gamma at a black pixel (input == 0) is infinite; the gradient there is 0 instead. A graph captured by torch.jit.trace keeps the plain power, whose gradient there is not finite.

Parameters:
  • input (Tensor) – image with shape (*, H, W).

  • gamma (Union[float, Tensor]) – non-negative exponent, a float or a tensor with shape (B,) for one value per image.

  • gain (Union[float, Tensor], optional) – non-negative multiplier, a float or a tensor with shape (B,). Default: 1.0

Return type:

Tensor

Returns:

Adjusted image with the shape of input.

Note

See a working example here.

Note

The non-negativity check on gamma/gain reads a CPU value during the call and raises AsyncCheckError, a RuntimeError. A tensor on CUDA, or on MPS from torch 2.13, is checked with torch._assert_async instead and raises RuntimeError by the next synchronization; on CUDA that is a device-side assert.

See also

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]\) by factor radians and returns RGB.

_images/adjust_hue.png
Convention:
  • factor is any angle in radians, taken modulo \(2\pi\): factor and factor + 2π agree, ±π gives the complementary colors, and a positive angle turns red towards green.

  • torchvision’s adjust_hue takes a fraction of a turn in \([-0.5, 0.5]\): its hue_factor is factor / (2 * pi) for factor in \([-\pi, \pi]\).

Parameters:
  • image (Tensor) – RGB image with shape (*, 3, H, W).

  • factor (Union[float, Tensor]) – hue shift in radians, a number or a tensor with shape (B,) for one value per image.

Return type:

Tensor

Returns:

Adjusted image with shape (*, 3, H, W).

Note

See a working example here.

See also

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) adds factor radians 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, use adjust_hue().

Parameters:
  • image (Tensor) – HSV image with shape (*, 3, H, W), hue in radians.

  • factor (Union[float, Tensor]) – angle in radians, a number or a tensor with shape (B,) for one value per image.

Return type:

Tensor

Returns:

HSV image with shape (*, 3, H, W).

See also

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]\) by factor, clamps it to \([0, 1]\) and returns RGB. 0 gives gray pixels equal to max(R, G, B), not the gray level; for PIL’s blend with the gray level, use adjust_saturation_with_gray_subtraction().

_images/adjust_saturation.png
Parameters:
  • image (Tensor) – RGB image with shape (*, 3, H, W).

  • factor (Union[float, Tensor]) – saturation multiplier, a float or a tensor with shape (B,) for one value per image.

Return type:

Tensor

Returns:

Adjusted image with shape (*, 3, H, W).

Note

See a working example here.

See also

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 by factor, clamps it to \([0, 1]\) and leaves hue and value as they are. For an RGB image, use adjust_saturation().

Parameters:
  • image (Tensor) – HSV image with shape (*, 3, H, W).

  • factor (Union[float, Tensor]) – saturation multiplier, a float or a tensor with shape (B,) for one value per image.

Return type:

Tensor

Returns:

HSV image with shape (*, 3, H, W).

See also

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) returns factor * image + (1 - factor) * gray for a (*, 3, H, W) RGB image in \([0, 1]\), clamped to \([0, 1]\): 0 gives the gray image and 1 the input. A single-channel image is returned unchanged.

Parameters:
  • image (Tensor) – RGB image with shape (*, 3, H, W), or gray image with shape (*, 1, H, W).

  • factor (Union[float, Tensor]) – weight of the image, a float or a tensor with shape (B,) for one value per image.

Return type:

Tensor

Returns:

Adjusted image with the shape of image.

See also

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 at cutoff. With inv=True it returns one minus that curve.

Reference:
[1]: Gustav J. Braun, “Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions”,

http://markfairchild.org/PDFs/PAP07.pdf

Parameters:
  • image (Tensor) – image with shape (*, H, W).

  • cutoff (float, optional) – input value at which the curve equals 0.5. Default: 0.5

  • gain (float, optional) – steepness of the curve. Default: 10

  • inv (bool, optional) – return one minus the curve. Default: False

Return type:

Tensor

Returns:

Adjusted image with the shape of image.

See also

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) returns gain * log2(1 + image) for an image in \([0, 1]\), or gain * (2 ** image - 1) with inv=True.

Reference:

[1]: http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf

Parameters:
  • image (Tensor) – image with shape (*, H, W).

  • gain (float, optional) – multiplier of the curve. Default: 1

  • inv (bool, optional) – use the exponential curve. Default: False

  • clip_output (bool, optional) – clamp the result to \([0, 1]\). Default: True

Return type:

Tensor

Returns:

Adjusted image with the shape of image.

See also

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) returns max_val - image.

_images/invert.png
Parameters:
  • image (Tensor) – tensor of any shape.

  • max_val (Optional[Tensor], optional) – tensor the image is subtracted from, broadcastable to image. The default is 1, so for a uint8 image pass torch.tensor(255). Default: None

Return type:

Tensor

Returns:

Inverted tensor with the shape of image.

See also

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 bits of the 8 bits of each color level, as PIL’s ImageOps.posterize does.

out = posterize(input, bits) quantizes an image in \([0, 1]\) to its bits highest bits per value: bits=8 returns the input and bits=0 gives black.

_images/posterize.png
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, so k / 255 reads level k even 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, where B is the product of the leading dimensions of input.

Return type:

Tensor

Returns:

Image with the shape of input.

Raises:
  • AssertionError – if a bits tensor does not match the leading dimensions of input.

  • AsyncCheckError – if bits is outside [0, 8]; it is a ValueError and a RuntimeError. A bits tensor on CUDA, or on MPS from torch 2.13, is checked with torch._assert_async instead and raises RuntimeError by the next synchronization.

See also

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.Sharpness does.

out = sharpness(input, factor) blends a (*, C, H, W) image in \([0, 1]\) with a copy smoothed by a 3x3 kernel: 0 returns the smoothed image, 1 the input, and a factor above 1 sharpens. The result is clamped to \([0, 1]\).

_images/sharpness.png
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, where B is the product of the leading dimensions of input. A (1,) tensor applies to every image. Negative factors are accepted and extrapolate past the smoothed image.

Return type:

Tensor

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: draws factor at 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 raise ShapeError. The three shifts must share the same shape.

Parameters:
  • image (Tensor) – RGB image with shape (B, 3, H, W).

  • r_shift (Tensor) – red shift with shape (B,), or (1,) for all images.

  • g_shift (Tensor) – green shift with shape (B,), or (1,) for all images.

  • b_shift (Tensor) – blue shift with shape (B,), or (1,) for all images.

Return type:

Tensor

Returns:

Shifted image with shape (B, 3, H, W).

See also

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 above thresholds by 1 - value. Without additions it equals PIL’s ImageOps.solarize.

_images/solarize.png
Convention:

additions is added to the whole image and the sum clamped to \([0, 1]\) before the comparison, so it can move a pixel across the threshold: with thresholds=0.5 and additions=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.5

  • additions (Union[Tensor, float, None], optional) – amount in \([-0.5, 0.5]\), endpoints included, with the shapes of thresholds. None adds nothing. Default: None

Return type:

Tensor

Returns:

The solarized image with shape (*, C, H, W).

Note

The range check on additions reads a float or a CPU tensor during the call and raises AsyncCheckError, a RuntimeError, whatever the device of the image. A tensor on CUDA, or on MPS from torch 2.13, is checked with torch._assert_async instead and raises RuntimeError by the next synchronization; on CUDA that is a device-side assert.

See also

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.threshold does.

out = threshold(input, thresh, maxval, type) compares each element with thresh and maps it to maxval, 0, thresh or itself, as the ThresholdType type says. It takes tensors for thresh and maxval.

Convention:
  • The comparison is strict: an element passes when input > thresh.

  • thresh and maxval broadcast over input and move to its device. maxval is converted to the dtype of input, and so is thresh for a floating-point input.

  • On an integer input thresh is not cast: as in OpenCV, an element passes when it is greater than floor(thresh). A thresh below the dtype’s range passes every element and one at or above its maximum passes none. THRESH_TRUNC then writes floor(thresh), or the dtype’s minimum for a thresh below its range.

Parameters:
  • input (Tensor) – tensor with shape (*, H, W).

  • thresh (Union[float, Tensor]) – level, a number or a tensor that broadcasts to input.

  • maxval (Union[float, Tensor], optional) – value written by the binary modes, a number or a tensor. The default 255.0 turns a \([0, 1]\) image into 0 and 255; pass 1.0 to keep its range. Default: 255.0

  • type (Union[int, ThresholdType], optional) – a ThresholdType member or its value. Default: ThresholdType.THRESH_BINARY

Return type:

Tensor

Returns:

Thresholded tensor with the shape, dtype and device of input.

Raises:

See also

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, and out = adjust(image) is adjust_brightness() with it and clip_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

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, and out = adjust(image) is adjust_brightness_accumulative() with it and clip_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

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, and out = adjust(image) is adjust_contrast() with it and clip_output=True.

Convention:
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

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, and out = adjust(image) is adjust_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

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, and out = adjust(image) is adjust_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

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, and out = adjust(image) is adjust_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

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, and out = adjust(image) is adjust_hue() with it.

Convention:
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

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, and out = adjust(image) is adjust_gamma() with them.

Convention:
Parameters:
  • gamma (Union[float, Tensor]) – non-negative exponent, a float or a tensor with shape (B,).

  • gain (Union[float, Tensor], optional) – non-negative multiplier, a float or a tensor with shape (B,). Default: 1.0

Shape:
  • Input: (*, H, W)

  • Output: (*, H, W)

See also

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, and out = adjust(image) is adjust_sigmoid() with them.

Reference:
[1]: Gustav J. Braun, “Image Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions”,

http://markfairchild.org/PDFs/PAP07.pdf

Parameters:
  • cutoff (float, optional) – input value at which the curve equals 0.5. Default: 0.5

  • gain (float, optional) – steepness of the curve. Default: 10

  • inv (bool, optional) – return one minus the curve. Default: False

Shape:
  • Input: (*, H, W)

  • Output: (*, H, W)

See also

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, and out = adjust(image) is adjust_log() with them.

Reference:

[1]: http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf

Parameters:
  • gain (float, optional) – multiplier of the curve. Default: 1

  • inv (bool, optional) – use the exponential curve. Default: False

  • clip_output (bool, optional) – clamp the result to \([0, 1]\). Default: True

Shape:
  • Input: (*, H, W)

  • Output: (*, H, W)

See also

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 and out = op(src1, src2) is add_weighted() with them. A tensor coefficient is stored as a non-persistent buffer, or as a parameter if it is an nn.Parameter.

Convention:
Parameters:
  • alpha (Union[float, Tensor]) – weight of src1, a number or a tensor.

  • beta (Union[float, Tensor]) – weight of src2, a number or a tensor.

  • gamma (Union[float, Tensor]) – value added to the sum, a number or a tensor.

Shape:
  • Input1: tensor of any shape.

  • Input2: tensor with the shape of Input1.

  • Output: same shape as Input1.

See also

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) stores factor and out = op(input) returns input * factor. A tensor factor is stored as a non-persistent buffer, so .to() moves it, and an nn.Parameter stays 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, a float or a 0-d tensor. An int raises TypeError.

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) stores max_val as a buffer, or as a parameter if it is an nn.Parameter, and out = op(image) is invert() with it.

Parameters:

max_val (Optional[Tensor], optional) – tensor the image is subtracted from, broadcastable to the input. The default is 1, so for a uint8 image pass torch.tensor(255). Default: None

Shape:
  • Input: any shape

  • Output: same as the input

See also

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 and out = op(input) is threshold() with them.

Convention:
  • See the convention block of threshold(); thresh and maxval are numbers here, not tensors.

Parameters:
  • thresh (float) – level, a number.

  • maxval (float, optional) – value written by the binary modes, a number. The default 255.0 turns a \([0, 1]\) image into 0 and 255; pass 1.0 to keep its range. Default: 255.0

  • type (Union[int, ThresholdType], optional) – a ThresholdType member or its value. Default: ThresholdType.THRESH_BINARY

See also

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. Writing x for an element, t for thresh and m for maxval:

  • THRESH_BINARY (0): m where x > t, else 0.

  • THRESH_BINARY_INV (1): 0 where x > t, else m.

  • THRESH_TRUNC (2): t where x > t, else x.

  • THRESH_TOZERO (3): x where x > t, else 0.

  • THRESH_TOZERO_INV (4): 0 where x > t, else x.

  • THRESH_OTSU (8): reserved; threshold() raises NotImplementedError for it, also when it is OR-ed into another mode.

See also