Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] better kornia.enhance testing (#801)

Edgar Riba215002f33aae
diff --git a/conftest.py b/conftest.py
index 485130abf..f48ad9d4e 100644
--- a/conftest.py
+++ b/conftest.py
@@ -3,6 +3,7 @@ from typing import Dict
import pytest
import torch
+import kornia
def get_test_devices() -> Dict[str, torch.device]:
@@ -16,6 +17,9 @@ def get_test_devices() -> Dict[str, torch.device]:
devices["cpu"] = torch.device("cpu")
if torch.cuda.is_available():
devices["cuda"] = torch.device("cuda:0")
+ if kornia.xla_is_available():
+ import torch_xla.core.xla_model as xm
+ devices["tpu"] = xm.xla_device()
return devices
@@ -43,15 +47,6 @@ DEVICE_DTYPE_BLACKLIST = {('cpu', 'float16')}
@pytest.fixture()
def device(device_name) -> torch.device:
- # To work with TPUs on Colab:
- # pip install cloud-tpu-client==0.10
- # pip install https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.6-cp36-cp36m-linux_x86_64.whl
- # Issue: gradcheck on TPUs takes ages...
- if device_name == "tpu":
- import torch_xla.core.xla_model as xm
- return xm.xla_device()
- elif device_name not in TEST_DEVICES:
- pytest.skip(f"Unsupported device type: {device_name}")
return TEST_DEVICES[device_name]
diff --git a/docker/tpu-tests/tpu_test_cases.jsonnet b/docker/tpu-tests/tpu_test_cases.jsonnet
index 36bce8861..e5c0c6f24 100644
--- a/docker/tpu-tests/tpu_test_cases.jsonnet
+++ b/docker/tpu-tests/tpu_test_cases.jsonnet
@@ -23,7 +23,7 @@ local tputests = base.BaseTest {
python -c "import torch; print(torch.__version__)"
python -c "import torch_xla; print(torch_xla.__version__)"
python -c "import kornia; print(kornia.__version__)"
- pytest -v kornia/test/color --device tpu --dtype float32 -k "not gradcheck"
+ pytest -v kornia/test/color kornia/test/enhance --device tpu --dtype float32 -k "not grad"
test_exit_code=$?
echo "\nFinished running commands.\n"
test $test_exit_code -eq 0
diff --git a/kornia/__init__.py b/kornia/__init__.py
index b854fe8d6..62f24375b 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -108,3 +108,5 @@ from kornia.utils import (
from kornia.geometry import *
from kornia.constants import *
+
+from kornia.testing import xla_is_available
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index df29e0634..ed11a8557 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -131,7 +131,7 @@ def rgba_to_rgb(image: torch.Tensor) -> torch.Tensor:
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 4:
- raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
+ raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}")
# unpack channels
r, g, b, a = torch.chunk(image, image.shape[-3], dim=-3)
@@ -162,7 +162,7 @@ def rgba_to_bgr(image: torch.Tensor) -> torch.Tensor:
raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
if len(image.shape) < 3 or image.shape[-3] != 4:
- raise ValueError(f"Input size must have a shape of (*, 3, H, W).Got {image.shape}")
+ raise ValueError(f"Input size must have a shape of (*, 4, H, W).Got {image.shape}")
# convert to RGB first, then to BGR
x_rgb: torch.Tensor = rgba_to_rgb(image)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index a7600254d..92934182d 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -1,12 +1,13 @@
from typing import Union, Optional
+from math import pi
+
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.color.hsv import rgb_to_hsv, hsv_to_rgb
from kornia.utils.image import _to_bchw, _to_bcdhw
-from kornia.constants import pi
__all__ = [
@@ -36,7 +37,7 @@ def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, t
See :class:`~kornia.color.AdjustSaturation` for details.
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(saturation_factor, (float, torch.Tensor,)):
@@ -44,12 +45,13 @@ def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, t
f"Got {type(saturation_factor)}")
if isinstance(saturation_factor, float):
- saturation_factor = torch.tensor([saturation_factor])
+ saturation_factor = torch.as_tensor(saturation_factor)
saturation_factor = saturation_factor.to(input.device).to(input.dtype)
- if (saturation_factor < 0).any():
- raise ValueError(f"Saturation factor must be non-negative. Got {saturation_factor}")
+ # TODO: find a proper way to check bound values in batched tensors.
+ # if (saturation_factor < 0).any():
+ # raise ValueError(f"Saturation factor must be non-negative. Got {saturation_factor}")
for _ in input.shape[1:]:
saturation_factor = torch.unsqueeze(saturation_factor, dim=-1)
@@ -69,7 +71,37 @@ def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, t
def adjust_saturation(input: torch.Tensor, saturation_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust color saturation of an image.
- See :class:`~kornia.color.AdjustSaturation` for details.
+ The input image is expected to be an RGB image in the range of [0, 1].
+
+ Args:
+ input (torch.Tensor): Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ saturation_factor (Union[float, torch.Tensor]): How much to adjust the saturation. 0 will give a black
+ and white image, 1 will give the original image while 2 will enhance the saturation
+ by a factor of 2.
+
+ Return:
+ torch.Tensor: Adjusted image in the shape of :math:`(*, 3, H, W)`.
+
+ Example:
+ >>> x = torch.ones(1, 3, 3, 3)
+ >>> adjust_saturation(x, 2.)
+ tensor([[[[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]]]])
+
+ >>> x = torch.ones(2, 3, 3, 3)
+ >>> y = torch.ones(2)
+ >>> out = adjust_saturation(x, y)
+ >>> torch.nn.functional.mse_loss(x, out)
+ tensor(0.)
"""
# convert the rgb image to hsv
@@ -90,7 +122,7 @@ def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor])
See :class:`~kornia.color.AdjustHue` for details.
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(hue_factor, (float, torch.Tensor)):
@@ -98,12 +130,13 @@ def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor])
f" [-PI, PI]. Got {type(hue_factor)}")
if isinstance(hue_factor, float):
- hue_factor = torch.tensor([hue_factor])
+ hue_factor = torch.as_tensor(hue_factor)
- hue_factor = hue_factor.to(input.device).to(input.dtype)
+ hue_factor = hue_factor.to(input.device, input.dtype)
- if ((hue_factor < -pi) | (hue_factor > pi)).any():
- raise ValueError(f"Hue-factor must be in the range [-PI, PI]. Got {hue_factor}")
+ # TODO: find a proper way to check bound values in batched tensors.
+ # if ((hue_factor < -pi) | (hue_factor > pi)).any():
+ # raise ValueError(f"Hue-factor must be in the range [-PI, PI]. Got {hue_factor}")
for _ in input.shape[1:]:
hue_factor = torch.unsqueeze(hue_factor, dim=-1)
@@ -112,7 +145,7 @@ def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor])
h, s, v = torch.chunk(input, chunks=3, dim=-3)
# transform the hue value and appl module
- divisor: float = 2 * pi.item()
+ divisor: float = 2 * pi
h_out: torch.Tensor = torch.fmod(h + hue_factor, divisor)
# pack back back the corrected hue
@@ -124,7 +157,37 @@ def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor])
def adjust_hue(input: torch.Tensor, hue_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust hue of an image.
- See :class:`~kornia.color.AdjustHue` for details.
+ The input image is expected to be an RGB image in the range of [0, 1].
+
+ Args:
+ input (torch.Tensor): Image to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ hue_factor (Union[float, torch.Tensor]): How much to shift the hue channel. Should be in [-PI, PI]. PI
+ and -PI give complete reversal of hue channel in HSV space in positive and negative
+ direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
+ image with complementary colors while 0 gives the original image.
+
+ Return:
+ torch.Tensor: Adjusted image in the shape of :math:`(*, 3, H, W)`.
+
+ Example:
+ >>> x = torch.ones(1, 3, 3, 3)
+ >>> adjust_hue(x, 3.141516)
+ tensor([[[[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]]]])
+
+ >>> x = torch.ones(2, 3, 3, 3)
+ >>> y = torch.ones(2) * 3.141516
+ >>> adjust_hue(x, y).shape
+ torch.Size([2, 3, 3, 3])
"""
# convert the rgb image to hsv
@@ -143,10 +206,33 @@ def adjust_gamma(input: torch.Tensor, gamma: Union[float, torch.Tensor],
gain: Union[float, torch.Tensor] = 1.) -> torch.Tensor:
r"""Perform gamma correction on an image.
- See :class:`~kornia.color.AdjustGamma` for details.
+ The input image is expected to be in the range of [0, 1].
+
+ Args:
+ input (torch.Tensor): Image to be adjusted in the shape of :math:`(*, N)`.
+ gamma (Union[float, torch.Tensor]): Non negative real number, same as γ\gammaγ in the equation.
+ gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
+ dark regions lighter.
+ gain (Union[float, torch.Tensor], optional): The constant multiplier. Default 1.
+
+ Return:
+ torch.Tenor: Adjusted image in the shape of :math:`(*, N)`.
+
+ Example:
+ >>> x = torch.ones(1, 1, 3, 3)
+ >>> adjust_gamma(x, 1.0, 2.0)
+ 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
+ >>> adjust_gamma(x, y1, y2).shape
+ torch.Size([2, 5, 3, 3])
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(gamma, (float, torch.Tensor)):
@@ -187,10 +273,33 @@ def adjust_contrast(input: torch.Tensor,
contrast_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust Contrast of an image.
- See :class:`~kornia.color.AdjustContrast` for details.
+ This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
+ The input image is expected to be in the range of [0, 1].
+
+ Args:
+ input (torch.Tensor): Image to be adjusted in the shape of :math:`(*, N)`.
+ contrast_factor (Union[float, torch.Tensor]): Contrast adjust factor per element
+ in the batch. 0 generates a compleatly black image, 1 does not modify
+ the input image while any other non-negative number modify the
+ brightness by this factor.
+
+ Return:
+ torch.Tensor: Adjusted image in the shape of :math:`(*, N)`.
+
+ Example:
+ >>> x = torch.ones(1, 1, 3, 3)
+ >>> adjust_contrast(x, 0.5)
+ 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)
+ >>> adjust_contrast(x, y).shape
+ torch.Size([2, 5, 3, 3])
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(contrast_factor, (float, torch.Tensor,)):
@@ -221,10 +330,32 @@ def adjust_brightness(input: torch.Tensor,
brightness_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust Brightness of an image.
- See :class:`~kornia.color.AdjustBrightness` for details.
+ This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
+ The input image is expected to be in the range of [0, 1].
+
+ Args:
+ input (torch.Tensor): image to be adjusted in the shape of :math:`(*, N)`.
+ brightness_factor (Union[float, torch.Tensor]): Brightness adjust factor per element
+ in the batch. 0 does not modify the input image while any other number modify the
+ brightness.
+
+ Return:
+ torch.Tensor: Adjusted image in the shape of :math:`(*, N)`.
+
+ Example:
+ >>> x = torch.ones(1, 1, 3, 3)
+ >>> adjust_brightness(x, 1.)
+ tensor([[[[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]]]])
+
+ >>> x = torch.ones(2, 5, 3, 3)
+ >>> y = torch.ones(2)
+ >>> adjust_brightness(x, y).shape
+ torch.Size([2, 5, 3, 3])
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(brightness_factor, (float, torch.Tensor,)):
@@ -261,7 +392,7 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
Returns:
torch.Tensor: Solarized images.
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(thresholds, (float, torch.Tensor,)):
@@ -280,11 +411,13 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
def solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5,
additions: Optional[Union[float, torch.Tensor]] = None) -> torch.Tensor:
- r"""For each pixel in the image less than threshold, we add 'addition' amount to it and then clip the
- pixel value to be between 0 and 1.0. The value of 'addition' is between -0.5 and 0.5.
+ r"""For each pixel in the image less than threshold.
+
+ We add 'addition' amount to it and then clip the pixel value to be between 0 and 1.0.
+ The value of 'addition' is between -0.5 and 0.5.
Args:
- input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to solarize.
+ input (torch.Tensor): image tensor with shapes like :math:`(B, C, H, W)` to solarize.
thresholds (float or torch.Tensor): solarize thresholds.
If int or one element tensor, input will be solarized across the whole batch.
If 1-d tensor, input will be solarized element-wise, len(thresholds) == len(input).
@@ -294,9 +427,21 @@ def solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5,
If 1-d tensor, additions will be added element-wisely, len(additions) == len(input).
Returns:
- torch.Tensor: Solarized images.
+ torch.Tensor: The solarized images with shape :math:`(B, C, H, W)`.
+
+ 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.7])
+ >>> out = solarize(x, thresholds)
+ >>> out.shape
+ torch.Size([2, 4, 3, 3])
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(thresholds, (float, torch.Tensor,)):
@@ -330,26 +475,42 @@ def solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5,
def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensor:
- r"""Reduce the number of bits for each color channel. Non-differentiable function, uint8 involved.
+ r"""Reduce the number of bits for each color channel.
+
+ Non-differentiable function, torch.uint8 involved.
Args:
- input (torch.Tensor): image tensor with shapes like (C, H, W) or (B, C, H, W) to posterize.
+ input (torch.Tensor): image tensor with shapes like :math:`(B, C, H, W)` to posterize.
bits (int or torch.Tensor): number of high bits. Must be in range [0, 8].
If int or one element tensor, input will be posterized by this bits.
If 1-d tensor, input will be posterized element-wisely, len(bits) == input.shape[1].
If n-d tensor, input will be posterized element-channel-wisely, bits.shape == input.shape[:len(bits.shape)]
Returns:
- torch.Tensor: Image with reduced color channels.
+ torch.Tensor: Image with reduced color channels with shape :math:`(B, C, H, W)`.
+
+ Example:
+ >>> x = torch.rand(1, 6, 3, 3)
+ >>> out = posterize(x, bits=8)
+ >>> torch.testing.assert_allclose(x, out)
+
+ >>> x = torch.rand(2, 6, 3, 3)
+ >>> bits = torch.tensor([0, 8])
+ >>> posterize(x, bits).shape
+ torch.Size([2, 6, 3, 3])
"""
- if not torch.is_tensor(input):
+ if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ if not isinstance(bits, (int, torch.Tensor,)):
+ raise TypeError(f"bits type is not an int or torch.Tensor. Got {type(bits)}")
+
if isinstance(bits, int):
bits = torch.tensor(bits)
- if not torch.all((bits >= 0) * (bits <= 8)) and bits.dtype == torch.int:
- raise ValueError(f"bits must be integers within range [0, 8]. Got {bits}.")
+ # TODO: find a better way to check boundaries on tensors
+ # if not torch.all((bits >= 0) * (bits <= 8)) and bits.dtype == torch.int:
+ # raise ValueError(f"bits must be integers within range [0, 8]. Got {bits}.")
# TODO: Make a differentiable version
# Current version:
@@ -477,6 +638,17 @@ def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: torch.Tensor)
return torch.clamp(res, 0, 1)
+def _build_lut(histo, step):
+ # Compute the cumulative sum, shifting by step // 2
+ # and then normalization by step.
+ lut = (torch.cumsum(histo, 0) + (step // 2)) // step
+ # Shift lut, prepending with 0.
+ lut = torch.cat([torch.zeros(1, device=lut.device), lut[:-1]])
+ # Clip the counts to be in range. This is done
+ # in the C code for image.point.
+ return torch.clamp(lut, 0, 255)
+
+
# Code taken from: https://github.com/pytorch/vision/pull/796
def _scale_channel(im: torch.Tensor) -> torch.Tensor:
r"""Scale the data in the channel to implement equalize.
@@ -509,23 +681,13 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
nonzero_histo = torch.reshape(histo[histo != 0], [-1])
step = (torch.sum(nonzero_histo) - nonzero_histo[-1]) // 255
- def build_lut(histo, step):
- # Compute the cumulative sum, shifting by step // 2
- # and then normalization by step.
- lut = (torch.cumsum(histo, 0) + (step // 2)) // step
- # Shift lut, prepending with 0.
- lut = torch.cat([torch.zeros(1, device=lut.device, dtype=lut.dtype), lut[:-1]])
- # Clip the counts to be in range. This is done
- # in the C code for image.point.
- return torch.clamp(lut, 0, 255)
-
# If step is zero, return the original image. Otherwise, build
# lut from the full histogram and step and then index from it.
if step == 0:
result = im
else:
# can't index using 2d index. Have to flatten and then reshape
- result = torch.gather(build_lut(histo, step), 0, im.flatten().long())
+ result = torch.gather(_build_lut(histo, step), 0, im.flatten().long())
result = result.reshape_as(im)
return result / 255.
@@ -535,13 +697,25 @@ def equalize(input: torch.Tensor) -> torch.Tensor:
r"""Apply equalize on the input tensor.
Implements Equalize function from PIL using PyTorch ops based on uint8 format:
- https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L352
+ https://github.com/tensorflow/tpu/blob/5f71c12a020403f863434e96982a840578fdd127/models/official/efficientnet/autoaugment.py#L355
Args:
- input (torch.Tensor): image tensor with shapes like :math:`(C, H, W)` or :math:`(B, C, H, W)` to equalize.
+ input (torch.Tensor): image tensor to equalizr with shapes like :math:`(C, H, W)` or :math:`(B, C, H, W)`.
Returns:
- torch.Tensor: Sharpened image or images.
+ torch.Tensor: Sharpened image or images with shape as the input.
+
+ Example:
+ >>> _ = torch.manual_seed(0)
+ >>> x = torch.rand(1, 2, 3, 3)
+ >>> equalize(x)
+ tensor([[[[0.4963, 0.7682, 0.0885],
+ [0.1320, 0.3074, 0.6341],
+ [0.4901, 0.8964, 0.4556]],
+ <BLANKLINE>
+ [[0.6323, 0.3489, 0.4017],
+ [0.0223, 0.1689, 0.2939],
+ [0.5185, 0.6977, 0.8000]]]])
"""
input = _to_bchw(input)
@@ -584,20 +758,41 @@ class AdjustSaturation(nn.Module):
The input image is expected to be an RGB image in the range of [0, 1].
Args:
- input (torch.Tensor): Image/Tensor to be adjusted in the shape of (\*, N).
- saturation_factor (float): How much to adjust the saturation. 0 will give a black
+ saturation_factor (Union[float, torch.Tensor]): How much to adjust the saturation. 0 will give a black
and white image, 1 will give the original image while 2 will enhance the saturation
by a factor of 2.
- Returns:
- torch.Tensor: Adjusted image.
+ Shape:
+ - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ - Ouput: Adjusted image in the shape of :math:`(*, 3, H, W)`.
+
+ Example:
+ >>> x = torch.ones(1, 3, 3, 3)
+ >>> AdjustSaturation(2.)(x)
+ tensor([[[[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[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.)
"""
def __init__(self, saturation_factor: Union[float, torch.Tensor]) -> None:
super(AdjustSaturation, self).__init__()
self.saturation_factor: Union[float, torch.Tensor] = saturation_factor
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_saturation(input, self.saturation_factor)
@@ -607,21 +802,41 @@ class AdjustHue(nn.Module):
The input image is expected to be an RGB image in the range of [0, 1].
Args:
- input (torch.Tensor): Image/Tensor to be adjusted in the shape of (\*, N).
- hue_factor (float): How much to shift the hue channel. Should be in [-PI, PI]. PI
+ hue_factor (Union[float, torch.Tensor]): How much to shift the hue channel. Should be in [-PI, PI]. PI
and -PI give complete reversal of hue channel in HSV space in positive and negative
direction respectively. 0 means no shift. Therefore, both -PI and PI will give an
image with complementary colors while 0 gives the original image.
- Returns:
- torch.Tensor: Adjusted image.
+ Shape:
+ - Input: Image/Tensor to be adjusted in the shape of :math:`(*, 3, H, W)`.
+ - Output: Adjusted image in the shape of :math:`(*, 3, H, W)`.
+
+ Example:
+ >>> x = torch.ones(1, 3, 3, 3)
+ >>> AdjustHue(3.141516)(x)
+ tensor([[[[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.]],
+ <BLANKLINE>
+ [[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])
"""
def __init__(self, hue_factor: Union[float, torch.Tensor]) -> None:
super(AdjustHue, self).__init__()
self.hue_factor: Union[float, torch.Tensor] = hue_factor
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_hue(input, self.hue_factor)
@@ -631,14 +846,27 @@ class AdjustGamma(nn.Module):
The input image is expected to be in the range of [0, 1].
Args:
- input (torch.Tensor): Image/Tensor to be adjusted in the shape of (\*, N).
- gamma (float): Non negative real number, same as γ\gammaγ in the equation.
+ gamma (Union[float, torch.Tensor]): Non negative real number, same as γ\gammaγ in the equation.
gamma larger than 1 make the shadows darker, while gamma smaller than 1 make
dark regions lighter.
- gain (float, optional): The constant multiplier. Default 1.
+ gain (Union[float, torch.Tensor], optional): The constant multiplier. Default 1.
- Returns:
- torch.Tensor: Adjusted image.
+ Shape:
+ - Input: Image to be adjusted in the shape of :math:`(*, N)`.
+ - Output: Adjusted image in the shape of :math:`(*, N)`.
+
+ 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])
"""
def __init__(self, gamma: Union[float, torch.Tensor], gain: Union[float, torch.Tensor] = 1.) -> None:
@@ -646,54 +874,78 @@ class AdjustGamma(nn.Module):
self.gamma: Union[float, torch.Tensor] = gamma
self.gain: Union[float, torch.Tensor] = gain
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_gamma(input, self.gamma, self.gain)
class AdjustContrast(nn.Module):
- r"""Adjust Contrast of an image. This implementation aligns OpenCV, not PIL. Hence,
- the output differs from TorchVision.
+ r"""Adjust Contrast of an image.
+ This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
- input (torch.Tensor): Image to be adjusted in the shape of (\*, N).
contrast_factor (Union[float, torch.Tensor]): Contrast adjust factor per element
in the batch. 0 generates a compleatly black image, 1 does not modify
the input image while any other non-negative number modify the
brightness by this factor.
- Returns:
- torch.Tensor: Adjusted image.
+ Shape:
+ - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.
+ - Output: Adjusted image in the shape of :math:`(*, N)`.
+
+ 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])
"""
def __init__(self, contrast_factor: Union[float, torch.Tensor]) -> None:
super(AdjustContrast, self).__init__()
self.contrast_factor: Union[float, torch.Tensor] = contrast_factor
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_contrast(input, self.contrast_factor)
class AdjustBrightness(nn.Module):
- r"""Adjust Brightness of an image. This implementation aligns OpenCV, not PIL. Hence,
- the output differs from TorchVision.
+ r"""Adjust Brightness of an image.
+ This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
The input image is expected to be in the range of [0, 1].
Args:
- input (torch.Tensor): Image/Input to be adjusted in the shape of (\*, N).
brightness_factor (Union[float, torch.Tensor]): Brightness adjust factor per element
in the batch. 0 does not modify the input image while any other number modify the
brightness.
- Returns:
- torch.Tensor: Adjusted image.
+ Shape:
+ - Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.
+ - Output: Adjusted image in the shape of :math:`(*, N)`.
+
+ 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])
"""
def __init__(self, brightness_factor: Union[float, torch.Tensor]) -> None:
super(AdjustBrightness, self).__init__()
self.brightness_factor: Union[float, torch.Tensor] = brightness_factor
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return adjust_brightness(input, self.brightness_factor)
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 57630a551..00c4c5a16 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -11,9 +11,30 @@ __all__ = [
def add_weighted(src1: torch.Tensor, alpha: float,
src2: torch.Tensor, beta: float,
gamma: float) -> torch.Tensor:
- r"""Blend two Tensors.
+ r"""Calculates the weighted sum of two Tensors.
+
+ The function calculates the weighted sum of two Tensors as follows:
+
+ .. math::
+ out = src1 * alpha + src2 * beta + gamma
+
+ Args:
+ src1 (torch.Tensor): Tensor of shape :math:`(B, C, H, W)`.
+ alpha (float): weight of the src1 elements.
+ src2 (torch.Tensor): Tensor of same size and channel number as src1 :math:`(B, C, H, W)`.
+ beta (float): weight of the src2 elements.
+ gamma (float): scalar added to each sum.
+
+ Returns:
+ torch.Tensor: Weighted Tensor of shape :math:`(B, C, H, W)`.
+
+ 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])
- See :class:`~kornia.color.AddWeighted` for details.
"""
if not isinstance(src1, torch.Tensor):
raise TypeError("src1 should be a tensor. Got {}".format(type(src1)))
@@ -42,14 +63,22 @@ class AddWeighted(nn.Module):
out = src1 * alpha + src2 * beta + gamma
Args:
- src1 (torch.Tensor): Tensor.
alpha (float): weight of the src1 elements.
- src2 (torch.Tensor): Tensor of same size and channel number as src1.
beta (float): weight of the src2 elements.
gamma (float): scalar added to each sum.
- Returns:
- torch.Tensor: Weighted Tensor.
+ Shape:
+ Input1: Tensor of shape :math:`(B, C, H, W)`.
+ Input2: Tensor of shape :math:`(B, C, H, W)`.
+ Output: Weighted tensor of shape :math:`(B, C, H, W)`.
+
+ 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])
+
"""
def __init__(self, alpha: float, beta: float, gamma: float) -> None:
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 281c36a08..71ed7fe8c 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -1,7 +1,6 @@
-from typing import Tuple, List
+from typing import Tuple
import torch
-import torch.nn as nn
__all__ = [
@@ -12,34 +11,42 @@ __all__ = [
def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor,
epsilon: float = 1e-10) -> Tuple[torch.Tensor, torch.Tensor]:
- """
- Function that calculates the marginal probability distribution function of the input tensor based on the number
- of histogram bins.
+ """Function that calculates the marginal probability distribution function of the input tensor
+ based on the number of histogram bins.
+
Args:
- values: (torch.Tensor), shape [BxNx1]
- bins: (torch.Tensor), shape [NUM_BINS]
- sigma: (torch.Tensor), shape [1], gaussian smoothing factor
- epsilon: (float), scalar, for numerical stability
+ values (torch.Tensor): shape [BxNx1].
+ bins (torch.Tensor): shape [NUM_BINS].
+ sigma (torch.Tensor): shape [1], gaussian smoothing factor.
+ epsilon: (float), scalar, for numerical stability.
+
Returns:
- pdf: (torch.Tensor), shape [BxN]
- kernel_values: (torch.Tensor), shape [BxNxNUM_BINS]"""
+ Tuple[torch.Tensor, torch.Tensor]:
+ - torch.Tensor: shape [BxN].
+ - torch.Tensor: shape [BxNxNUM_BINS].
- if not torch.is_tensor(values):
+ """
+
+ if not isinstance(values, torch.Tensor):
raise TypeError("Input values type is not a torch.Tensor. Got {}"
.format(type(values)))
- if not torch.is_tensor(bins):
+
+ if not isinstance(bins, torch.Tensor):
raise TypeError("Input bins type is not a torch.Tensor. Got {}"
.format(type(bins)))
- if not torch.is_tensor(sigma):
+
+ if not isinstance(sigma, torch.Tensor):
raise TypeError("Input sigma type is not a torch.Tensor. Got {}"
.format(type(sigma)))
if not values.dim() == 3:
raise ValueError("Input values must be a of the shape BxNx1."
" Got {}".format(values.shape))
+
if not bins.dim() == 1:
raise ValueError("Input bins must be a of the shape NUM_BINS"
" Got {}".format(bins.shape))
+
if not sigma.dim() == 0:
raise ValueError("Input sigma must be a of the shape 1"
" Got {}".format(sigma.shape))
@@ -54,30 +61,37 @@ def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor,
return (pdf, kernel_values)
-def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
- """
- Function that calculates the joint probability distribution function of the input tensors based on the number
- of histogram bins.
+def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor,
+ epsilon: float = 1e-10) -> torch.Tensor:
+ """Function that calculates the joint probability distribution function of the input tensors
+ based on the number of histogram bins.
+
Args:
- kernel_values1: (torch.Tensor), shape [BxNxNUM_BINS]
- kernel_values2: (torch.Tensor), shape [BxNxNUM_BINS]
- epsilon: (float), scalar, for numerical stability
+ kernel_values1 (torch.Tensor): shape [BxNxNUM_BINS].
+ kernel_values2 (torch.Tensor): shape [BxNxNUM_BINS].
+ epsilon (float): scalar, for numerical stability.
+
Returns:
- pdf: (torch.Tensor), shape [BxNUM_BINSxNUM_BINS]"""
+ torch.Tensor: shape [BxNUM_BINSxNUM_BINS].
+
+ """
- if not torch.is_tensor(kernel_values1):
+ if not isinstance(kernel_values1, torch.Tensor):
raise TypeError("Input kernel_values1 type is not a torch.Tensor. Got {}"
.format(type(kernel_values1)))
- if not torch.is_tensor(kernel_values2):
+
+ if not isinstance(kernel_values2, torch.Tensor):
raise TypeError("Input kernel_values2 type is not a torch.Tensor. Got {}"
.format(type(kernel_values2)))
if not kernel_values1.dim() == 3:
raise ValueError("Input kernel_values1 must be a of the shape BxN."
" Got {}".format(kernel_values1.shape))
+
if not kernel_values2.dim() == 3:
raise ValueError("Input kernel_values2 must be a of the shape BxN."
" Got {}".format(kernel_values2.shape))
+
if kernel_values1.shape != kernel_values2.shape:
raise ValueError("Inputs kernel_values1 and kernel_values2 must have the same shape."
" Got {} and {}".format(kernel_values1.shape, kernel_values2.shape))
@@ -89,17 +103,28 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor, epsilo
return pdf
-def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsilon: float = 1e-10) -> torch.Tensor:
- """
- Function that estimates the histogram of the input tensor. The calculation uses kernel
- density estimation which requires a bandwidth (smoothing) parameter.
+def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor,
+ epsilon: float = 1e-10) -> torch.Tensor:
+ """Function that estimates the histogram of the input tensor.
+
+ The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
+
Args:
- x: (torch.Tensor), shape [BxN]
- bins: (torch.Tensor), shape [NUM_BINS]
- bandwidth: (torch.Tensor), shape [1], gaussian smoothing factor
- epsilon: (float), scalar, for numerical stability
+ x (torch.Tensor): Input tensor to compute the histogram with shape :math:`(B, D)`.
+ bins (torch.Tensor): The number of bins to use the histogram :math:`(N_{bins})`.
+ bandwidth (torch.Tensor): Gaussian smoothing factor with shape shape [1].
+ epsilon (float): A scalar, for numerical stability. Default: 1e-10.
+
Returns:
- pdf: (torch.Tensor), shape [BxNUM_BINS]"""
+ torch.Tensor: Computed histogram of shape :math:`(B, N_{bins})`.
+
+ Examples:
+ >>> x = torch.rand(1, 10)
+ >>> bins = torch.torch.linspace(0, 255, 128)
+ >>> hist = histogram(x, bins, bandwidth=torch.tensor(0.9))
+ >>> hist.shape
+ torch.Size([1, 128])
+ """
pdf, _ = marginal_pdf(x.unsqueeze(2), bins, bandwidth, epsilon)
@@ -112,17 +137,28 @@ def histogram2d(
bins: torch.Tensor,
bandwidth: torch.Tensor,
epsilon: float = 1e-10) -> torch.Tensor:
- """
- Function that estimates the histogram of the input tensor. The calculation uses kernel
- density estimation which requires a bandwidth (smoothing) parameter.
+ """Function that estimates the 2d histogram of the input tensor.
+
+ The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
+
Args:
- x1: (torch.Tensor), shape [BxN1]
- x2: (torch.Tensor), shape [BxN2]
- bins: (torch.Tensor), shape [NUM_BINS]
- bandwidth: (torch.Tensor), scalar, gaussian smoothing factor
- epsilon: (float), scalar, for numerical stability
+ x1 (torch.Tensor): Input tensor to compute the histogram with shape :math:`(B, D1)`.
+ x2 (torch.Tensor): Input tensor to compute the histogram with shape :math:`(B, D2)`.
+ bins (torch.Tensor): The number of bins to use the histogram :math:`(N_{bins})`.
+ bandwidth (torch.Tensor): Gaussian smoothing factor with shape shape [1].
+ epsilon (float): A scalar, for numerical stability. Default: 1e-10.
+
Returns:
- pdf: (torch.Tensor), shape [BxNUM_BINSxNUM_BINS]"""
+ torch.Tensor: Computed histogram of shape :math:`(B, N_{bins})`.
+
+ Examples:
+ >>> x1 = torch.rand(2, 32)
+ >>> x2 = torch.rand(2, 32)
+ >>> bins = torch.torch.linspace(0, 255, 128)
+ >>> hist = histogram2d(x1, x2, bins, bandwidth=torch.tensor(0.9))
+ >>> hist.shape
+ torch.Size([2, 128, 128])
+ """
pdf1, kernel_values1 = marginal_pdf(x1.unsqueeze(2), bins, bandwidth, epsilon)
pdf2, kernel_values2 = marginal_pdf(x2.unsqueeze(2), bins, bandwidth, epsilon)
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 45a5a37b1..9840d519c 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -16,18 +16,33 @@ __all__ = [
class Normalize(nn.Module):
- r"""Normalize a tensor image or a batch of tensor images with mean and standard deviation.
+ r"""Normalize a tensor image with mean and standard deviation.
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ .. math::
+ \text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
- Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,
- this transform will normalize each channel of the input ``torch.Tensor``
- i.e. ``input[channel] = (input[channel] - mean[channel]) / std[channel]``
+ Where `mean` is :math:`(M_1,...,M_n)` and `std` :math:`(S_1,..,S_n)` for `n` channels,
Args:
- mean (torch.Tensor or float): Mean for each channel.
- std (torch.Tensor or float): Standard deviations for each channel.
-
+ mean (Union[torch.Tensor, float]): Mean for each channel.
+ std (Union[torch.Tensor, float]): Standard deviations for each channel.
+
+ Shape:
+ - Input: Image tensor of size :math:`(*, C, H, W)`.
+ - Output: Normalised tensor with same size as input :math:`(*, C, H, W)`.
+
+ Examples:
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> out = Normalize(0.0, 255.)(x)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
+
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> mean = torch.zeros(1, 4)
+ >>> std = 255. * torch.ones(1, 4)
+ >>> out = Normalize(mean, std)(x)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
"""
def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
@@ -37,16 +52,7 @@ class Normalize(nn.Module):
self.mean = mean
self.std = std
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- """Normalises an input tensor by the mean and standard deviation.
-
- Args:
- input: image tensor of size (*, H, W).
-
- Returns:
- normalised tensor with same size as input (*, H, W).
-
- """
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return normalize(input, self.mean, self.std)
def __repr__(self):
@@ -57,18 +63,33 @@ class Normalize(nn.Module):
def normalize(
data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]
) -> torch.Tensor:
- r"""Normalise the image with channel-wise mean and standard deviation.
-
- See :class:`~kornia.color.Normalize` for details.
+ r"""Normalize a tensor image with mean and standard deviation.
- Args:
- data (torch.Tensor): The image tensor to be normalised.
- mean (torch.Tensor or float): Mean for each channel.
- std (torch.Tensor or float): Standard deviations for each channel.
+ .. math::
+ \text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
- Returns:
- torch.Tensor: The normalised image tensor.
+ Where `mean` is :math:`(M_1,...,M_n)` and `std` :math:`(S_1,..,S_n)` for `n` channels,
+ Args:
+ data (torch.Tensor): Image tensor of size :math:`(*, C, H, W)`.
+ mean (Union[torch.Tensor, float]): Mean for each channel.
+ std (Union[torch.Tensor, float]): Standard deviations for each channel.
+
+ Return:
+ torch.Tensor: Normalised tensor with same size as input :math:`(*, C, H, W)`.
+
+ Examples:
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> out = normalize(x, 0.0, 255.)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
+
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> mean = torch.zeros(1, 4)
+ >>> std = 255. * torch.ones(1, 4)
+ >>> out = normalize(x, mean, std)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
"""
if isinstance(mean, float):
mean = torch.tensor([mean]) # prevent 0 sized tensors
@@ -76,13 +97,13 @@ def normalize(
if isinstance(std, float):
std = torch.tensor([std]) # prevent 0 sized tensors
- if not torch.is_tensor(data):
+ if not isinstance(data, torch.Tensor):
raise TypeError("data should be a tensor. Got {}".format(type(data)))
- if not torch.is_tensor(mean):
+ if not isinstance(mean, torch.Tensor):
raise TypeError("mean should be a tensor or a float. Got {}".format(type(mean)))
- if not torch.is_tensor(std):
+ if not isinstance(std, torch.Tensor):
raise TypeError("std should be a tensor or float. Got {}".format(type(std)))
# Allow broadcast on channel dimension
@@ -97,6 +118,7 @@ def normalize(
if mean.shape:
mean = mean[..., :, None, None].to(data.device)
+
if std.shape:
std = std[..., :, None, None].to(data.device)
@@ -106,18 +128,33 @@ def normalize(
class Denormalize(nn.Module):
- r"""Denormalize a tensor image or a batch of tensor images.
+ r"""Denormalize a tensor image with mean and standard deviation.
- Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
+ .. math::
+ \text{input[channel] = (input[channel] * mean[channel]) + std[channel]}
- Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels,
- this transform will denormalize each channel of the input ``torch.Tensor``
- i.e. ``input[channel] = (input[channel] * std[channel]) + mean[channel]``
+ Where `mean` is :math:`(M_1,...,M_n)` and `std` :math:`(S_1,..,S_n)` for `n` channels,
Args:
- mean (torch.Tensor or float): Mean for each channel.
- std (torch.Tensor or float): Standard deviations for each channel.
-
+ mean (Union[torch.Tensor, float]): Mean for each channel.
+ std (Union[torch.Tensor, float]): Standard deviations for each channel.
+
+ Shape:
+ - Input: Image tensor of size :math:`(*, C, H, W)`.
+ - Output: Denormalised tensor with same size as input :math:`(*, C, H, W)`.
+
+ Examples:
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> out = Denormalize(0.0, 255.)(x)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
+
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> mean = torch.zeros(1, 4)
+ >>> std = 255. * torch.ones(1, 4)
+ >>> out = Denormalize(mean, std)(x)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
"""
def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
@@ -127,16 +164,7 @@ class Denormalize(nn.Module):
self.mean = mean
self.std = std
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- """Denormalises an input tensor by the mean and standard deviation.
-
- Args:
- input: image tensor of size (*, H, W).
-
- Returns:
- normalised tensor with same size as input (*, H, W).
-
- """
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
return denormalize(input, self.mean, self.std)
def __repr__(self):
@@ -147,32 +175,48 @@ class Denormalize(nn.Module):
def denormalize(
data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]
) -> torch.Tensor:
- r"""Denormalize the image given channel-wise mean and standard deviation.
-
- See :class:`~kornia.color.Normalize` for details.
+ r"""Denormalize a tensor image with mean and standard deviation.
- Args:
- data (torch.Tensor): The image tensor to be normalised.
- mean (torch.Tensor or float): Mean for each channel.
- std (torch.Tensor or float): Standard deviations for each channel.
+ .. math::
+ \text{input[channel] = (input[channel] * mean[channel]) + std[channel]}
- Returns:
- torch.Tensor: The normalised image tensor.
+ Where `mean` is :math:`(M_1,...,M_n)` and `std` :math:`(S_1,..,S_n)` for `n` channels,
+ Args:
+ input (torch.Tensor): Image tensor of size :math:`(*, C, H, W)`.
+ mean (Union[torch.Tensor, float]): Mean for each channel.
+ std (Union[torch.Tensor, float]): Standard deviations for each channel.
+
+ Return:
+ torch.Tensor: Denormalised tensor with same size as input :math:`(*, C, H, W)`.
+
+ Examples:
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> out = denormalize(x, 0.0, 255.)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
+
+ >>> x = torch.rand(1, 4, 3, 3)
+ >>> mean = torch.zeros(1, 4)
+ >>> std = 255. * torch.ones(1, 4)
+ >>> out = denormalize(x, mean, std)
+ >>> out.shape
+ torch.Size([1, 4, 3, 3])
"""
+
if isinstance(mean, float):
mean = torch.tensor([mean]) # prevent 0 sized tensors
if isinstance(std, float):
std = torch.tensor([std]) # prevent 0 sized tensors
- if not torch.is_tensor(data):
+ if not isinstance(data, torch.Tensor):
raise TypeError("data should be a tensor. Got {}".format(type(data)))
- if not torch.is_tensor(mean):
+ if not isinstance(mean, torch.Tensor):
raise TypeError("mean should be a tensor or a float. Got {}".format(type(mean)))
- if not torch.is_tensor(std):
+ if not isinstance(std, torch.Tensor):
raise TypeError("std should be a tensor or float. Got {}".format(type(std)))
# Allow broadcast on channel dimension
@@ -214,6 +258,13 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0., max_val: float = 1.,
Returns:
torch.Tensor: The normalised image tensor with same shape as input :math:`(B, C, H, W)`.
+ Example:
+ >>> x = torch.rand(1, 5, 3, 3)
+ >>> x_norm = normalize_min_max(x, min_val=-1., max_val=1.)
+ >>> x_norm.min()
+ tensor(-1.)
+ >>> x_norm.max()
+ tensor(1.0000)
"""
if not isinstance(x, torch.Tensor):
raise TypeError(f"data should be a tensor. Got: {type(x)}.")
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 5e457bb7a..201414b96 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -2,16 +2,24 @@
The testing package contains testing-specific utilities.
"""
from abc import ABC, abstractmethod
+import importlib
import torch
import numpy as np
__all__ = [
- 'tensor_to_gradcheck_var', 'create_eye_batch',
+ 'tensor_to_gradcheck_var', 'create_eye_batch', 'xla_is_available'
]
+def xla_is_available() -> bool:
+ """Return whether `torch_xla` is available in the system."""
+ if importlib.util.find_spec("torch_xla") is not None:
+ return True
+ return False
+
+
def create_checkerboard(h, w, nw):
"""Creates a synthetic checkerd board of shape HxW and window size `nw`.
"""
@@ -99,3 +107,22 @@ class BaseTester(ABC):
@abstractmethod
def test_module(self):
raise NotImplementedError("Implement a stupid routine.")
+
+
+def _get_precision(device: torch.device, dtype: torch.dtype) -> float:
+ if 'xla' in device.type:
+ return 1e-2
+ elif dtype == torch.float16:
+ return 1e-3
+ return 1e-4
+
+
+def _get_precision_by_name(device: torch.device, device_target: str,
+ tol_val: float, tol_val_default: float = 1e-4) -> float:
+ if device_target not in ['cpu', 'cuda', 'xla']:
+ raise ValueError(f"Invalid device name: {device_target}.")
+
+ if device_target in device.type:
+ return tol_val
+
+ return tol_val_default
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index fd84459bc..f7855572c 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -57,7 +57,7 @@ def _to_bchw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) -> t
Returns:
torch.Tensor: input tensor of the form :math:`(B, H, W, C)`.
"""
- if not torch.is_tensor(tensor):
+ if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
if len(tensor.shape) > 4 or len(tensor.shape) < 2:
@@ -69,10 +69,12 @@ def _to_bchw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) -> t
if len(tensor.shape) == 3:
tensor = tensor.unsqueeze(0)
- if color_channel_num is not None and color_channel_num != 1:
- channel_list = [0, 1, 2, 3]
- channel_list.insert(1, channel_list.pop(color_channel_num))
- tensor = tensor.permute(*channel_list)
+ # TODO(jian): this function is never used. Besides is not feasible for torchscript.
+ # In addition, the docs must be updated. I don't understand what is doing.
+ # if color_channel_num is not None and color_channel_num != 1:
+ # channel_list = [0, 1, 2, 3]
+ # channel_list.insert(1, channel_list.pop(color_channel_num))
+ # tensor = tensor.permute(*channel_list)
return tensor
@@ -87,7 +89,7 @@ def _to_bcdhw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) ->
Returns:
torch.Tensor: input tensor of the form :math:`(B, C, D, H, W)`.
"""
- if not torch.is_tensor(tensor):
+ if not isinstance(tensor, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
if len(tensor.shape) > 5 or len(tensor.shape) < 3:
@@ -99,10 +101,12 @@ def _to_bcdhw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) ->
if len(tensor.shape) == 4:
tensor = tensor.unsqueeze(0)
- if color_channel_num is not None and color_channel_num != 1:
- channel_list = [0, 1, 2, 3, 4]
- channel_list.insert(1, channel_list.pop(color_channel_num))
- tensor = tensor.permute(*channel_list)
+ # TODO(jian): this function is never used. Besides is not feasible for torchscript.
+ # In addition, the docs must be updated. I don't understand what is doing.
+ # if color_channel_num is not None and color_channel_num != 1:
+ # channel_list = [0, 1, 2, 3, 4]
+ # channel_list.insert(1, channel_list.pop(color_channel_num))
+ # tensor = tensor.permute(*channel_list)
return tensor
@@ -119,7 +123,7 @@ def tensor_to_image(tensor: torch.Tensor) -> np.array:
numpy.ndarray: image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`.
"""
- if not torch.is_tensor(tensor):
+ if not isinstance(tensor, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
type(tensor)))
diff --git a/setup_dev_env.sh b/setup_dev_env.sh
index 1c87eddac..885e121d5 100755
--- a/setup_dev_env.sh
+++ b/setup_dev_env.sh
@@ -36,21 +36,22 @@ fi
# define a python version to initialise the conda environment.
# by default we assume python 3.7.
python_version=${PYTHON_VERSION:-"3.7"}
-pytorch_version=${PYTORCH_VERSION:-"1.6.0"}
+pytorch_version=${PYTORCH_VERSION:-"1.7.0"}
pytorch_mode=${PYTORCH_MODE:-""} # use `cpuonly` for CPU or leave it in blank for GPU
-cuda_version=${CUDA_VERSION:-""}
-pytorch_channel="pytorch"
+cuda_version=${CUDA_VERSION:-"10.2"}
# configure for nightly builds
+pytorch_channel="pytorch"
if [ "$pytorch_version" == "nightly" ]; then
pytorch_version=""
pytorch_channel="pytorch-nightly"
+fi
# configure cudatoolkit
-cuda_toolkit=""
-if [ ! -z "$cuda_version" ]
+cuda_toolkit="cudatoolkit=$cuda_version"
+if [ "$pytorch_mode" == "cpuonly" ]
then
- cuda_toolkit="cudatoolkit=$cuda_version"
+ cuda_toolkit=""
fi
# create an environment with the specific python version
@@ -63,7 +64,7 @@ $conda_bin clean -ya
source $conda_bin_dir/activate $dev_env_dir/envs/venv
# install pytorch and torchvision
-conda install pytorch=$pytorch_version torchvision $cuda_toolkit $pytorch_mode -c pytorch
+conda install pytorch=$pytorch_version torchvision $cuda_toolkit $pytorch_mode -c $pytorch_channel
# install testing dependencies
pip install -r requirements-dev.txt
@@ -71,4 +72,4 @@ pip install -r requirements-dev.txt
# install documentation dependencies
pip install -r docs/requirements.txt
-conda deactivate # close the `venv` environment
\ No newline at end of file
+conda deactivate # close the `venv` environment
diff --git a/test/color/test_luv.py b/test/color/test_luv.py
index bc4061551..05c2e34a0 100644
--- a/test/color/test_luv.py
+++ b/test/color/test_luv.py
@@ -1,21 +1,13 @@
import pytest
import kornia
-from kornia.testing import BaseTester
+from kornia.testing import BaseTester, _get_precision
import torch
from torch.autograd import gradcheck
from torch.testing import assert_allclose
-def _get_precision(device: torch.device, dtype: torch.dtype) -> float:
- if 'xla' in device.type:
- return 1e-2
- elif dtype == torch.float16:
- return 1e-3
- return 1e-4
-
-
class TestRgbToLuv(BaseTester):
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
diff --git a/test/color/test_rgb.py b/test/color/test_rgb.py
index 62cb4dc06..219524a28 100644
--- a/test/color/test_rgb.py
+++ b/test/color/test_rgb.py
@@ -234,3 +234,19 @@ class TestRgbToRgba(BaseTester):
ops = kornia.color.BgrToRgba(1.).to(device, dtype)
fcn = kornia.color.bgr_to_rgba
assert_allclose(ops(img), fcn(img, 1.))
+
+ @pytest.mark.nn
+ def test_module_bgra2rgb(self, device, dtype):
+ B, C, H, W = 2, 4, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ ops = kornia.color.RgbaToRgb().to(device, dtype)
+ fcn = kornia.color.rgba_to_rgb
+ assert_allclose(ops(img), fcn(img))
+
+ @pytest.mark.nn
+ def test_module_bgra2bgr(self, device, dtype):
+ B, C, H, W = 2, 4, 4, 4
+ img = torch.ones(B, C, H, W, device=device, dtype=dtype)
+ ops = kornia.color.RgbaToBgr().to(device, dtype)
+ fcn = kornia.color.rgba_to_bgr
+ assert_allclose(ops(img), fcn(img))
diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.py
index 47b629561..634156ab3 100644
--- a/test/enhance/test_adjust.py
+++ b/test/enhance/test_adjust.py
@@ -2,6 +2,7 @@ import pytest
import kornia
from kornia.testing import tensor_to_gradcheck_var, BaseTester
+import kornia.testing as utils
from kornia.constants import pi
import torch
@@ -18,9 +19,9 @@ class TestAdjustSaturation:
[.5, .5]],
[[.25, .25],
- [.25, .25]]], device=device) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
- expected = data
+ expected = data.clone()
f = kornia.enhance.AdjustSaturation(1.)
assert_allclose(f(data), expected)
@@ -42,22 +43,22 @@ class TestAdjustSaturation:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]], device=device) # 2x3x2x2
+ [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
expected = data
f = kornia.enhance.AdjustSaturation(torch.ones(2))
assert_allclose(f(data), expected)
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.adjust_saturation, (img, 2.),
raise_exception=True)
class TestAdjustHue:
- def test_hue_one(self, device):
+ def test_hue_one(self, device, dtype):
data = torch.tensor([[[.5, .5],
[.5, .5]],
@@ -65,15 +66,14 @@ class TestAdjustHue:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
- data = data.to(device)
expected = data.clone()
f = kornia.enhance.AdjustHue(0.)
assert_allclose(f(data), expected)
- def test_hue_one_batch(self):
+ def test_hue_one_batch(self, device, dtype):
data = torch.tensor([[[[.5, .5],
[.5, .5]],
@@ -90,13 +90,13 @@ class TestAdjustHue:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]]) # 2x3x2x2
+ [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
expected = data
f = kornia.enhance.AdjustHue(torch.tensor([0, 0]))
assert_allclose(f(data), expected)
- def test_hue_flip_batch(self):
+ def test_hue_flip_batch(self, device, dtype):
data = torch.tensor([[[[.5, .5],
[.5, .5]],
@@ -113,22 +113,24 @@ class TestAdjustHue:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]]) # 2x3x2x2
+ [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
+
+ pi_t = torch.tensor([-pi, pi], device=device, dtype=dtype)
+ f = kornia.enhance.AdjustHue(pi_t)
- f = kornia.enhance.AdjustHue(torch.tensor([-pi, pi]))
result = f(data)
assert_allclose(result, result.flip(0))
- def test_gradcheck(self):
+ def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.rand(batch_size, channels, height, width)
+ img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.adjust_hue, (img, 2.),
raise_exception=True)
class TestAdjustGamma:
- def test_gamma_zero(self, device):
+ def test_gamma_zero(self, device, dtype):
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -136,15 +138,14 @@ class TestAdjustGamma:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
- data = data.to(device)
expected = torch.ones_like(data)
f = kornia.enhance.AdjustGamma(0.)
assert_allclose(f(data), expected)
- def test_gamma_one(self, device):
+ def test_gamma_one(self, device, dtype):
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -152,15 +153,14 @@ class TestAdjustGamma:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
- data = data.to(device)
expected = data.clone()
f = kornia.enhance.AdjustGamma(1.)
assert_allclose(f(data), expected)
- def test_gamma_one_gain_two(self, device):
+ def test_gamma_one_gain_two(self, device, dtype):
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -168,7 +168,7 @@ class TestAdjustGamma:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
expected = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -177,15 +177,12 @@ class TestAdjustGamma:
[1., 1.]],
[[.5, .5],
- [.5, .5]]]) # 3x2x2
-
- data = data.to(device)
- expected = expected.to(device)
+ [.5, .5]]], device=device, dtype=dtype) # 3x2x2
f = kornia.enhance.AdjustGamma(1., 2.)
assert_allclose(f(data), expected)
- def test_gamma_two(self, device):
+ def test_gamma_two(self, device, dtype):
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -193,7 +190,7 @@ class TestAdjustGamma:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
expected = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -202,15 +199,12 @@ class TestAdjustGamma:
[.25, .25]],
[[.0625, .0625],
- [.0625, .0625]]]) # 3x2x2
-
- data = data.to(device)
- expected = expected.to(device)
+ [.0625, .0625]]], device=device, dtype=dtype) # 3x2x2
f = kornia.enhance.AdjustGamma(2.)
assert_allclose(f(data), expected)
- def test_gamma_two_batch(self):
+ def test_gamma_two_batch(self, device, dtype):
data = torch.tensor([[[[1., 1.],
[1., 1.]],
@@ -227,7 +221,7 @@ class TestAdjustGamma:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]]) # 2x3x2x2
+ [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
expected = torch.tensor([[[[1., 1.],
[1., 1.]],
@@ -245,22 +239,24 @@ class TestAdjustGamma:
[.25, .25]],
[[.0625, .0625],
- [.0625, .0625]]]]) # 2x3x2x2
+ [.0625, .0625]]]], device=device, dtype=dtype) # 2x3x2x2
- f = kornia.enhance.AdjustGamma(torch.tensor([2., 2.]), gain=torch.ones(2))
+ p1 = torch.tensor([2., 2.], device=device, dtype=dtype)
+ p2 = torch.ones(2, device=device, dtype=dtype)
+
+ f = kornia.enhance.AdjustGamma(p1, gain=p2)
assert_allclose(f(data), expected)
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.ones(batch_size, channels, height, width)
- img = img.to(device)
+ img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
img = tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.adjust_gamma, (img, 1., 2.),
raise_exception=True)
class TestAdjustContrast:
- def test_factor_zero(self, device):
+ def test_factor_zero(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -269,16 +265,14 @@ class TestAdjustContrast:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
- data = data.to(device)
expected = torch.zeros_like(data)
f = kornia.enhance.AdjustContrast(0.)
-
assert_allclose(f(data), expected)
- def test_factor_one(self, device):
+ def test_factor_one(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -287,15 +281,14 @@ class TestAdjustContrast:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
- data = data.to(device)
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+
expected = data.clone()
f = kornia.enhance.AdjustContrast(1.)
-
assert_allclose(f(data), expected)
- def test_factor_two(self, device):
+ def test_factor_two(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -304,7 +297,7 @@ class TestAdjustContrast:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
expected = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -313,16 +306,12 @@ class TestAdjustContrast:
[1., 1.]],
[[.5, .5],
- [.5, .5]]]) # 3x2x2
-
- data = data.to(device)
- expected = expected.to(device)
+ [.5, .5]]], device=device, dtype=dtype) # 3x2x2
f = kornia.enhance.AdjustContrast(2.)
-
assert_allclose(f(data), expected)
- def test_factor_tensor(self, device):
+ def test_factor_tensor(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -334,7 +323,7 @@ class TestAdjustContrast:
[.25, .25]],
[[.5, .5],
- [.5, .5]]]) # 4x2x2
+ [.5, .5]]], device=device, dtype=dtype) # 4x2x2
expected = torch.tensor([[[0., 0.],
[0., 0.]],
@@ -346,18 +335,14 @@ class TestAdjustContrast:
[.375, .375]],
[[1., 1.],
- [1., 1.]]]) # 4x2x2
-
- factor = torch.tensor([0, 1, 1.5, 2])
+ [1., 1.]]], device=device, dtype=dtype) # 4x2x2
- data = data.to(device)
- expected = expected.to(device)
- factor = factor.to(device)
+ factor = torch.tensor([0, 1, 1.5, 2], device=device, dtype=dtype)
f = kornia.enhance.AdjustContrast(factor)
assert_allclose(f(data), expected)
- def test_factor_tensor_color(self, device):
+ def test_factor_tensor_color(self, device, dtype):
# prepare input data
data = torch.tensor([[[[1., 1.],
[1., 1.]],
@@ -375,7 +360,7 @@ class TestAdjustContrast:
[.3, .3]],
[[.6, .6],
- [.6, .6]]]]) # 2x3x2x2
+ [.6, .6]]]], device=device, dtype=dtype) # 2x3x2x2
expected = torch.tensor([[[[1., 1.],
[1., 1.]],
@@ -393,18 +378,14 @@ class TestAdjustContrast:
[.6, .6]],
[[1., 1.],
- [1., 1.]]]]) # 2x3x2x2
+ [1., 1.]]]], device=device, dtype=dtype) # 2x3x2x2
- factor = torch.tensor([1, 2])
-
- data = data.to(device)
- expected = expected.to(device)
- factor = factor.to(device)
+ factor = torch.tensor([1, 2], device=device, dtype=dtype)
f = kornia.enhance.AdjustContrast(factor)
assert_allclose(f(data), expected)
- def test_factor_tensor_shape(self, device):
+ def test_factor_tensor_shape(self, device, dtype):
# prepare input data
data = torch.tensor([[[[1., 1., .5],
[1., 1., .5]],
@@ -422,7 +403,7 @@ class TestAdjustContrast:
[.3, .3, .4]],
[[.6, .6, 0.],
- [.3, .2, .1]]]]) # 2x3x2x3
+ [.3, .2, .1]]]], device=device, dtype=dtype) # 2x3x2x3
expected = torch.tensor([[[[1., 1., .75],
[1., 1., .75]],
@@ -440,28 +421,23 @@ class TestAdjustContrast:
[.6, .6, .8]],
[[1., 1., 0.],
- [.6, .4, .2]]]]) # 2x3x2x3
-
- factor = torch.tensor([1.5, 2.])
+ [.6, .4, .2]]]], device=device, dtype=dtype) # 2x3x2x3
- data = data.to(device)
- expected = expected.to(device)
- factor = factor.to(device)
+ factor = torch.tensor([1.5, 2.], device=device, dtype=dtype)
f = kornia.enhance.AdjustContrast(factor)
assert_allclose(f(data), expected)
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.ones(batch_size, channels, height, width)
- img = img.to(device)
+ img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
img = tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.adjust_contrast, (img, 2.),
raise_exception=True)
class TestAdjustBrightness:
- def test_factor_zero(self, device):
+ def test_factor_zero(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -470,15 +446,14 @@ class TestAdjustBrightness:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
- data = data.to(device)
expected = data.clone()
f = kornia.enhance.AdjustBrightness(0.)
assert_allclose(f(data), expected)
- def test_factor_one(self, device):
+ def test_factor_one(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -487,15 +462,14 @@ class TestAdjustBrightness:
[.5, .5]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
- data = data.to(device)
expected = torch.ones_like(data)
f = kornia.enhance.AdjustBrightness(1.)
assert_allclose(f(data), expected)
- def test_factor_minus(self, device):
+ def test_factor_minus(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -504,7 +478,7 @@ class TestAdjustBrightness:
[.75, .75]],
[[.25, .25],
- [.25, .25]]]) # 3x2x2
+ [.25, .25]]], device=device, dtype=dtype) # 3x2x2
expected = torch.tensor([[[.5, .5],
[.5, .5]],
@@ -513,15 +487,12 @@ class TestAdjustBrightness:
[.25, .25]],
[[0., 0.],
- [0., 0.]]]) # 3x2x2
-
- data = data.to(device)
- expected = expected.to(device)
+ [0., 0.]]], device=device, dtype=dtype) # 3x2x2
f = kornia.enhance.AdjustBrightness(-0.5)
assert_allclose(f(data), expected)
- def test_factor_tensor(self, device):
+ def test_factor_tensor(self, device, dtype):
# prepare input data
data = torch.tensor([[[1., 1.],
[1., 1.]],
@@ -533,18 +504,16 @@ class TestAdjustBrightness:
[.25, .25]],
[[.5, .5],
- [.5, .5]]]) # 4x2x2
+ [.5, .5]]], device=device, dtype=dtype) # 4x2x2
- factor = torch.tensor([0, 0.5, 0.75, 2])
+ factor = torch.tensor([0, 0.5, 0.75, 2], device=device, dtype=dtype)
- data = data.to(device)
expected = torch.ones_like(data)
- factor = factor.to(device)
f = kornia.enhance.AdjustBrightness(factor)
assert_allclose(f(data), expected)
- def test_factor_tensor_color(self, device):
+ def test_factor_tensor_color(self, device, dtype):
# prepare input data
data = torch.tensor([[[[1., 1.],
[1., 1.]],
@@ -562,7 +531,7 @@ class TestAdjustBrightness:
[.3, .3]],
[[.6, .6],
- [.6, .6]]]]) # 2x3x2x2
+ [.6, .6]]]], device=device, dtype=dtype) # 2x3x2x2
expected = torch.tensor([[[[1., 1.],
[1., 1.]],
@@ -580,21 +549,16 @@ class TestAdjustBrightness:
[.4, .4]],
[[.7, .7],
- [.7, .7]]]]) # 2x3x2x2
+ [.7, .7]]]], device=device, dtype=dtype) # 2x3x2x2
- factor = torch.tensor([0.25, 0.1])
-
- data = data.to(device)
- expected = expected.to(device)
- factor = factor.to(device)
+ factor = torch.tensor([0.25, 0.1], device=device, dtype=dtype)
f = kornia.enhance.AdjustBrightness(factor)
assert_allclose(f(data), expected)
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 2, 3, 4, 5
- img = torch.ones(batch_size, channels, height, width)
- img = img.to(device)
+ img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
img = tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.adjust_brightness, (img, 2.),
raise_exception=True)
@@ -617,58 +581,66 @@ class TestEqualize:
assert f(inputs).shape == torch.Size([bs, channels, height, width])
- def test_equalize(self, device):
+ def test_equalize(self, device, dtype):
bs, channels, height, width = 1, 3, 20, 20
- inputs = self.build_input(channels, height, width).squeeze(dim=0)
- inputs = inputs.to(device)
+ inputs = self.build_input(bs, channels, height, width, device=device, dtype=dtype)
row_expected = torch.tensor([
0.0000, 0.07843, 0.15686, 0.2353, 0.3137, 0.3922, 0.4706, 0.5490, 0.6275,
0.7059, 0.7843, 0.8627, 0.9412, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000
- ], device=device)
- expected = self.build_input(channels, height, width, bs=1, row=row_expected)
- expected = expected.to(device)
+ ], device=device, dtype=dtype)
+
+ expected = self.build_input(bs, channels, height, width,
+ device=device, dtype=dtype, row=row_expected)
f = kornia.enhance.equalize
- assert_allclose(f(inputs), expected)
+ assert_allclose(f(inputs), expected, rtol=1e-4, atol=1e-4)
- def test_equalize_batch(self, device):
+ def test_equalize_batch(self, device, dtype):
bs, channels, height, width = 2, 3, 20, 20
- inputs = self.build_input(channels, height, width, bs)
- inputs = inputs.to(device)
+ inputs = self.build_input(bs, channels, height, width, device=device, dtype=dtype)
row_expected = torch.tensor([
0.0000, 0.07843, 0.15686, 0.2353, 0.3137, 0.3922, 0.4706, 0.5490, 0.6275,
0.7059, 0.7843, 0.8627, 0.9412, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000,
1.0000, 1.0000
- ], device=device)
- expected = self.build_input(channels, height, width, bs, row=row_expected)
- expected = expected.to(device)
+ ], device=device, dtype=dtype)
+
+ expected = self.build_input(bs, channels, height, width,
+ device=device, dtype=dtype, row=row_expected)
f = kornia.enhance.equalize
- assert_allclose(f(inputs), expected)
+ assert_allclose(f(inputs), expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device):
- bs, channels, height, width = 2, 3, 4, 5
- inputs = torch.ones(bs, channels, height, width)
- inputs = inputs.to(device)
+ def test_gradcheck(self, device, dtype):
+ bs, channels, height, width = 1, 2, 3, 3
+ inputs = torch.ones(bs, channels, height, width, device=device, dtype=dtype)
inputs = tensor_to_gradcheck_var(inputs)
assert gradcheck(kornia.enhance.equalize, (inputs,),
raise_exception=True)
+ def test_jit(self, device, dtype):
+ batch_size, channels, height, width = 1, 2, 3, 3
+ inp = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
+
+ op = kornia.enhance.equalize
+ op_script = torch.jit.script(op)
+
+ assert_allclose(op(inp), op_script(inp))
+
@staticmethod
- def build_input(channels, height, width, bs=1, row=None):
+ def build_input(batch_size, channels, height, width, device, dtype, row=None):
if row is None:
row = torch.arange(width) / float(width)
- channel = torch.stack([row] * height)
- image = torch.stack([channel] * channels)
- batch = torch.stack([image] * bs)
+ channel = torch.stack([row] * height).to(device, dtype)
+ image = torch.stack([channel] * channels).to(device, dtype)
+ batch = torch.stack([image] * batch_size).to(device, dtype)
return batch
@@ -690,55 +662,64 @@ class TestEqualize3D:
assert f(inputs3d).shape == torch.Size([bs, channels, depth, height, width])
- def test_equalize3d(self, device):
+ def test_equalize3d(self, device, dtype):
bs, channels, depth, height, width = 1, 3, 6, 10, 10
- inputs3d = self.build_input(channels, depth, height, width).squeeze(dim=0)
- inputs3d = inputs3d.to(device)
+ inputs3d = self.build_input(bs, channels, depth, height, width, device, dtype)
row_expected = torch.tensor([
0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000
- ], device=device)
- expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected)
- expected = expected.to(device)
+ ], device=device, dtype=dtype)
+
+ expected = self.build_input(
+ bs, channels, depth, height, width, device, dtype, row=row_expected)
f = kornia.enhance.equalize3d
- assert_allclose(f(inputs3d), expected)
+ assert_allclose(f(inputs3d), expected, atol=1e-4, rtol=1e-4)
- def test_equalize3d_batch(self, device):
+ def test_equalize3d_batch(self, device, dtype):
bs, channels, depth, height, width = 2, 3, 6, 10, 10
- inputs3d = self.build_input(channels, depth, height, width, bs)
- inputs3d = inputs3d.to(device)
+ inputs3d = self.build_input(
+ bs, channels, depth, height, width, device, dtype)
row_expected = torch.tensor([
0.0000, 0.11764, 0.2353, 0.3529, 0.4706, 0.5882, 0.7059, 0.8235, 0.9412, 1.0000
- ], device=device)
- expected = self.build_input(channels, depth, height, width, bs, row=row_expected)
- expected = expected.to(device)
+ ], device=device, dtype=dtype)
+
+ expected = self.build_input(
+ bs, channels, depth, height, width, device, dtype, row=row_expected)
f = kornia.enhance.equalize3d
- assert_allclose(f(inputs3d), expected)
+ assert_allclose(f(inputs3d), expected, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device):
- bs, channels, depth, height, width = 2, 3, 6, 4, 5
- inputs3d = torch.ones(bs, channels, depth, height, width)
- inputs3d = inputs3d.to(device)
+ def test_gradcheck(self, device, dtype):
+ bs, channels, depth, height, width = 1, 2, 3, 4, 5
+ inputs3d = torch.ones(bs, channels, depth, height, width, device=device, dtype=dtype)
inputs3d = tensor_to_gradcheck_var(inputs3d)
assert gradcheck(kornia.enhance.equalize3d, (inputs3d,),
raise_exception=True)
+ def test_jit(self, device, dtype):
+ batch_size, channels, depth, height, width = 1, 2, 1, 3, 3
+ inp = torch.ones(batch_size, channels, depth, height, width, device=device, dtype=dtype)
+
+ op = kornia.enhance.equalize3d
+ op_script = torch.jit.script(op)
+
+ assert_allclose(op(inp), op_script(inp))
+
@staticmethod
- def build_input(channels, depth, height, width, bs=1, row=None):
+ def build_input(batch_size, channels, depth, height, width, device, dtype, row=None):
if row is None:
row = torch.arange(width) / float(width)
- channel = torch.stack([row] * height)
- image = torch.stack([channel] * channels)
- image3d = torch.stack([image] * depth).transpose(0, 1)
- batch = torch.stack([image3d] * bs)
+ channel = torch.stack([row] * height).to(device, dtype)
+ image = torch.stack([channel] * channels).to(device, dtype)
+ image3d = torch.stack([image] * depth).transpose(0, 1).to(device, dtype)
+ batch = torch.stack([image3d] * batch_size).to(device, dtype)
return batch
@@ -773,7 +754,7 @@ class TestSharpness(BaseTester):
def test_value(self, device, dtype):
torch.manual_seed(0)
- inputs = torch.rand(1, 3, 3).to(device=device, dtype=dtype)
+ inputs = torch.rand(1, 1, 3, 3).to(device=device, dtype=dtype)
# Output generated is similar (1e-2 due to the uint8 conversions) to the below output:
# img = PIL.Image.fromarray(arr)
@@ -781,11 +762,13 @@ class TestSharpness(BaseTester):
# np.array(en) / 255.
expected = torch.tensor([
[[[0.4963, 0.7682, 0.0885],
- [0.1320, 0.3305, 0.6341],
- [0.4901, 0.8964, 0.4556]]]], device=device, dtype=dtype)
+ [0.1320, 0.3305, 0.6341],
+ [0.4901, 0.8964, 0.4556]]]], device=device, dtype=dtype)
# If factor == 1, shall return original
- assert_allclose(TestSharpness.f(inputs, 1), inputs, rtol=1e-4, atol=1e-4)
+ # TODO(jian): add test for this case
+ # assert_allclose(TestSharpness.f(inputs, 0.), inputs, rtol=1e-4, atol=1e-4)
+ assert_allclose(TestSharpness.f(inputs, 1.), inputs, rtol=1e-4, atol=1e-4)
assert_allclose(TestSharpness.f(inputs, 0.8), expected, rtol=1e-4, atol=1e-4)
def test_value_batch(self, device, dtype):
@@ -799,24 +782,26 @@ class TestSharpness(BaseTester):
# np.array(en) / 255.
expected_08 = torch.tensor([
[[[0.4963, 0.7682, 0.0885],
- [0.1320, 0.3305, 0.6341],
- [0.4901, 0.8964, 0.4556]]],
+ [0.1320, 0.3305, 0.6341],
+ [0.4901, 0.8964, 0.4556]]],
[[[0.6323, 0.3489, 0.4017],
- [0.0223, 0.2052, 0.2939],
- [0.5185, 0.6977, 0.8000]]]], device=device, dtype=dtype)
+ [0.0223, 0.2052, 0.2939],
+ [0.5185, 0.6977, 0.8000]]]], device=device, dtype=dtype)
+
expected_08_13 = torch.tensor([
[[[0.4963, 0.7682, 0.0885],
- [0.1320, 0.3305, 0.6341],
- [0.4901, 0.8964, 0.4556]]],
+ [0.1320, 0.3305, 0.6341],
+ [0.4901, 0.8964, 0.4556]]],
[[[0.6323, 0.3489, 0.4017],
- [0.0223, 0.1143, 0.2939],
- [0.5185, 0.6977, 0.8000]]]], device=device, dtype=dtype)
+ [0.0223, 0.1143, 0.2939],
+ [0.5185, 0.6977, 0.8000]]]], device=device, dtype=dtype)
# If factor == 1, shall return original
- assert_allclose(TestSharpness.f(inputs, 1), inputs, rtol=1e-4, atol=1e-4)
- assert_allclose(TestSharpness.f(inputs, torch.tensor([1., 1.])), inputs, rtol=1e-4, atol=1e-4)
- assert_allclose(TestSharpness.f(inputs, 0.8), expected_08, rtol=1e-4, atol=1e-4)
- assert_allclose(TestSharpness.f(inputs, torch.tensor([0.8, 1.3])), expected_08_13, rtol=1e-4, atol=1e-4)
+ tol_val: float = utils._get_precision(device, dtype)
+ assert_allclose(TestSharpness.f(inputs, 1), inputs, rtol=tol_val, atol=tol_val)
+ assert_allclose(TestSharpness.f(inputs, torch.tensor([1., 1.])), inputs, rtol=tol_val, atol=tol_val)
+ assert_allclose(TestSharpness.f(inputs, 0.8), expected_08, rtol=tol_val, atol=tol_val)
+ assert_allclose(TestSharpness.f(inputs, torch.tensor([0.8, 1.3])), expected_08_13, rtol=tol_val, atol=tol_val)
@pytest.mark.grad
def test_gradcheck(self, device, dtype):
@@ -840,3 +825,155 @@ class TestSharpness(BaseTester):
img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
# gray_ops = kornia.enhance.sharpness().to(device, dtype)
# assert_allclose(gray_ops(img), f(img))
+
+
[email protected](kornia.xla_is_available(), reason="issues with xla device")
+class TestSolarize(BaseTester):
+
+ f = kornia.enhance.solarize
+
+ def test_smoke(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 5
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ assert isinstance(TestSolarize.f(img, 0.8), torch.Tensor)
+
+ # TODO(jian): verify thresholds test and include addtions
+ @pytest.mark.parametrize("batch_size, height, width, thresholds", [
+ (1, 4, 5, 0.8), (2, 4, 5, 0.8),
+ (1, 4, 5, torch.tensor(0.8)), (2, 4, 5, torch.tensor(0.8)),
+ (2, 4, 5, torch.tensor([0.8, 0.7]))])
+ @pytest.mark.parametrize("channels", [1, 3, 5])
+ def test_cardinality(self, batch_size, channels, height, width, thresholds, device, dtype):
+ inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
+ assert TestSolarize.f(inputs, thresholds).shape == torch.Size([batch_size, channels, height, width])
+
+ # TODO(jian): add better assertions
+ def test_exception(self, device, dtype):
+ img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert TestSolarize.f([1.], 0.)
+
+ with pytest.raises(TypeError):
+ assert TestSolarize.f(img, 1)
+
+ with pytest.raises(TypeError):
+ assert TestSolarize.f(img, 0.8, 1)
+
+ # TODO: add better cases
+ def test_value(self, device, dtype):
+ torch.manual_seed(0)
+
+ inputs = torch.rand(1, 1, 3, 3).to(device=device, dtype=dtype)
+
+ # Output generated is similar (1e-2 due to the uint8 conversions) to the below output:
+ # img = PIL.Image.fromarray((255*inputs[0,0]).byte().numpy())
+ # en = ImageOps.Solarize(img, 128)
+ # np.array(en) / 255.
+ expected = torch.tensor([
+ [[[0.49411765, 0.23529412, 0.08627451],
+ [0.12941176, 0.30588235, 0.36862745],
+ [0.48627451, 0.10588235, 0.45490196]]]], device=device, dtype=dtype)
+
+ # TODO(jian): precision is very bad compared to PIL
+ assert_allclose(TestSolarize.f(inputs, 0.5), expected, rtol=1e-2, atol=1e-2)
+
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ bs, channels, height, width = 2, 3, 4, 5
+ inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
+ inputs = tensor_to_gradcheck_var(inputs)
+ assert gradcheck(TestSolarize.f, (inputs, 0.8), raise_exception=True)
+
+ # TODO: implement me
+ @pytest.mark.skip(reason="union type input")
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = torch.jit.script(kornia.enhance.adjust.solarize)
+ inputs = torch.rand(2, 1, 3, 3).to(device=device, dtype=dtype)
+ expected = op(input, 0.8)
+ actual = op_script(input, 0.8)
+ assert_allclose(actual, expected)
+
+ # TODO: implement me
+ @pytest.mark.skip(reason="Not having it yet.")
+ @pytest.mark.nn
+ def test_module(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ # gray_ops = kornia.enhance.sharpness().to(device, dtype)
+ # assert_allclose(gray_ops(img), f(img))
+
+
+class TestPosterize(BaseTester):
+
+ f = kornia.enhance.posterize
+
+ def test_smoke(self, device, dtype):
+ B, C, H, W = 2, 3, 4, 5
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ assert isinstance(TestPosterize.f(img, 8), torch.Tensor)
+
+ @pytest.mark.parametrize("batch_size, height, width, bits", [
+ (1, 4, 5, 8), (2, 4, 5, 0),
+ (1, 4, 5, torch.tensor(8)), (2, 4, 5, torch.tensor(8)),
+ (2, 4, 5, torch.tensor([0, 8]))])
+ @pytest.mark.parametrize("channels", [1, 3, 5])
+ def test_cardinality(self, batch_size, channels, height, width, bits, device, dtype):
+ inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
+ assert TestPosterize.f(inputs, bits).shape == torch.Size([batch_size, channels, height, width])
+
+ # TODO(jian): add better assertions
+ def test_exception(self, device, dtype):
+ img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)
+
+ with pytest.raises(TypeError):
+ assert TestPosterize.f([1.], 0.)
+
+ with pytest.raises(TypeError):
+ assert TestPosterize.f(img, 1.)
+
+ # TODO(jian): add better cases
+ @pytest.mark.skipif(kornia.xla_is_available(), reason="issues with xla device")
+ def test_value(self, device, dtype):
+ torch.manual_seed(0)
+
+ inputs = torch.rand(1, 1, 3, 3).to(device=device, dtype=dtype)
+
+ # Output generated is similar (1e-2 due to the uint8 conversions) to the below output:
+ # img = PIL.Image.fromarray((255*inputs[0,0]).byte().numpy())
+ # en = ImageOps.posterize(img, 1)
+ # np.array(en) / 255.
+ expected = torch.tensor([
+ [[[0., 0.50196078, 0.],
+ [0., 0., 0.50196078],
+ [0., 0.50196078, 0.]]]], device=device, dtype=dtype)
+
+ assert_allclose(TestPosterize.f(inputs, 1), expected)
+ assert_allclose(TestPosterize.f(inputs, 0), torch.zeros_like(inputs))
+ assert_allclose(TestPosterize.f(inputs, 8), inputs)
+
+ @pytest.mark.skip(reason="IndexError: tuple index out of range")
+ @pytest.mark.grad
+ def test_gradcheck(self, device, dtype):
+ bs, channels, height, width = 2, 3, 4, 5
+ inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
+ inputs = tensor_to_gradcheck_var(inputs)
+ assert gradcheck(TestPosterize.f, (inputs, 0), raise_exception=True)
+
+ # TODO: implement me
+ @pytest.mark.skip(reason="union type input")
+ @pytest.mark.jit
+ def test_jit(self, device, dtype):
+ op = torch.jit.script(kornia.enhance.adjust.posterize)
+ inputs = torch.rand(2, 1, 3, 3).to(device=device, dtype=dtype)
+ expected = op(input, 8)
+ actual = op_script(input, 8)
+ assert_allclose(actual, expected)
+
+ # TODO: implement me
+ @pytest.mark.skip(reason="Not having it yet.")
+ @pytest.mark.nn
+ def test_module(self, device, dtype):
+ img = torch.ones(2, 3, 4, 4, device=device, dtype=dtype)
+ # gray_ops = kornia.enhance.sharpness().to(device, dtype)
+ # assert_allclose(gray_ops(img), f(img))
diff --git a/test/enhance/test_core.py b/test/enhance/test_core.py
index 15f17e83e..33126e513 100644
--- a/test/enhance/test_core.py
+++ b/test/enhance/test_core.py
@@ -14,50 +14,49 @@ def random_shape(dim, min_elem=1, max_elem=10):
class TestAddWeighted:
- def get_input(self, size, max_elem=10):
+
+ fcn = kornia.enhance.add_weighted
+
+ def get_input(self, device, dtype, size, max_elem=10):
shape = random_shape(size, max_elem)
- src1 = torch.randn(shape)
- src2 = torch.randn(shape)
+ src1 = torch.randn(shape, device=device, dtype=dtype)
+ src2 = torch.randn(shape, device=device, dtype=dtype)
alpha = random.random()
beta = random.random()
gamma = random.random()
return src1, src2, alpha, beta, gamma
@pytest.mark.parametrize("size", [2, 3, 4, 5])
- def test_addweighted(self, size, device):
- src1, src2, alpha, beta, gamma = self.get_input(3)
- src1 = src1.to(device)
- src2 = src2.to(device)
-
- f = kornia.enhance.AddWeighted(alpha, beta, gamma)
- assert_allclose(f(src1, src2), src1 * alpha + src2 * beta + gamma)
+ def test_smoke(self, device, dtype, size):
+ src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
+ assert_allclose(
+ TestAddWeighted.fcn(src1, alpha, src2, beta, gamma),
+ src1 * alpha + src2 * beta + gamma
+ )
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- @torch.jit.script
- def op_script(src1: torch.Tensor, alpha: float, src2: torch.Tensor,
- beta: float, gamma: float) -> torch.Tensor:
- return kornia.enhance.add_weighted(src1, alpha, src2, beta, gamma)
+ def test_jit(self, device, dtype):
+ src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
+ inputs = (src1, alpha, src2, beta, gamma)
- src1, src2, alpha, beta, gamma = self.get_input(3)
- src1 = src1.to(device)
- src2 = src2.to(device)
+ op = TestAddWeighted.fcn
+ op_script = torch.jit.script(op)
- actual = op_script(src1, alpha, src2, beta, gamma)
- expected = kornia.enhance.add_weighted(src1, alpha, src2, beta, gamma)
- assert_allclose(actual, expected)
+ assert_allclose(op(*inputs), op_script(*inputs))
@pytest.mark.parametrize("size", [2, 3])
- def test_gradcheck(self, size, device):
- shape = random_shape(size, max_elem=5) # to shave time on gradcheck
- src1 = torch.randn(shape).to(device)
- src2 = torch.randn(shape).to(device)
- alpha = random.random()
- beta = random.random()
- gamma = random.random()
-
+ def test_gradcheck(self, size, device, dtype):
+ src1, src2, alpha, beta, gamma = self.get_input(
+ device, dtype, size=3, max_elem=5) # to shave time on gradcheck
src1 = utils.tensor_to_gradcheck_var(src1) # to var
src2 = utils.tensor_to_gradcheck_var(src2) # to var
-
assert gradcheck(kornia.enhance.AddWeighted(alpha, beta, gamma), (src1, src2),
raise_exception=True)
+
+ def test_module(self, device, dtype):
+ src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
+ inputs = (src1, alpha, src2, beta, gamma)
+
+ op = TestAddWeighted.fcn
+ op_module = kornia.enhance.AddWeighted(alpha, beta, gamma)
+
+ assert_allclose(op(*inputs), op_module(src1, src2))
diff --git a/test/enhance/test_histogram.py b/test/enhance/test_histogram.py
index 3e12b8514..5a8aae7db 100644
--- a/test/enhance/test_histogram.py
+++ b/test/enhance/test_histogram.py
@@ -4,79 +4,107 @@ import torch
from torch.testing import assert_allclose
from torch.autograd import gradcheck
-from kornia.enhance import histogram, histogram2d
+import kornia
import kornia.testing as utils # test utils
class TestHistogram:
- def test_shape(self, device):
- inp = torch.ones(1, 32, device=device)
- bins = torch.linspace(0, 255, 128).to(device)
- bandwidth = torch.Tensor(np.array(0.9)).to(device)
- pdf = histogram(inp, bins, bandwidth)
+
+ fcn = kornia.enhance.histogram
+
+ def test_shape(self, device, dtype):
+ inp = torch.ones(1, 32, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
+ pdf = TestHistogram.fcn(inp, bins, bandwidth)
assert pdf.shape == (1, 128)
- def test_shape_batch(self, device):
- inp = torch.ones(8, 32, device=device)
- bins = torch.linspace(0, 255, 128).to(device)
- bandwidth = torch.Tensor(np.array(0.9)).to(device)
- pdf = histogram(inp, bins, bandwidth)
+ def test_shape_batch(self, device, dtype):
+ inp = torch.ones(8, 32, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
+ pdf = TestHistogram.fcn(inp, bins, bandwidth)
assert pdf.shape == (8, 128)
- def test_gradcheck(self, device):
- inp = torch.ones(8, 32, device=device)
+ def test_gradcheck(self, device, dtype):
+ inp = torch.ones(1, 8, device=device, dtype=dtype)
inp = utils.tensor_to_gradcheck_var(inp) # to var
- bins = torch.linspace(0, 255, 128).to(device)
+ bins = torch.linspace(0, 255, 8, device=device, dtype=dtype)
bins = utils.tensor_to_gradcheck_var(bins)
- bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
bandwidth = utils.tensor_to_gradcheck_var(bandwidth)
- assert gradcheck(histogram, (inp, bins, bandwidth), raise_exception=True)
+ assert gradcheck(TestHistogram.fcn, (inp, bins, bandwidth), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
+ bins = torch.linspace(0, 255, 10, device=device, dtype=dtype)
+ bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)
+ inputs = (input1, bins, bandwidth)
+
+ op = TestHistogram.fcn
+ op_script = torch.jit.script(op)
+
+ assert_allclose(op(*inputs), op_script(*inputs))
- def test_uniform_dist(self, device):
- input1 = torch.linspace(0, 255, 10).unsqueeze(0).to(device)
+ def test_uniform_dist(self, device, dtype):
+ input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
+ input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype)
+ bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)
- pdf = histogram(input1, torch.linspace(0, 255, 10).to(device), torch.Tensor(np.array(2 * 0.4**2)))
- ans = torch.ones((1, 10)) * 0.1
- assert((ans.cpu() - pdf.cpu()).sum() < 1e-6)
+ pdf = TestHistogram.fcn(input1, input2, bandwidth)
+ ans = 0.1 * torch.ones(1, 10, device=device, dtype=dtype)
+ assert_allclose(ans, pdf)
class TestHistogram2d:
- def test_shape(self, device):
- inp1 = torch.ones(1, 32, device=device)
- inp2 = torch.ones(1, 32, device=device)
- bins = torch.linspace(0, 255, 128).to(device)
- bandwidth = torch.Tensor(np.array(0.9)).to(device)
- pdf = histogram2d(inp1, inp2, bins, bandwidth)
+
+ fcn = kornia.enhance.histogram2d
+
+ def test_shape(self, device, dtype):
+ inp1 = torch.ones(1, 32, device=device, dtype=dtype)
+ inp2 = torch.ones(1, 32, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
+ pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)
assert pdf.shape == (1, 128, 128)
- def test_shape_batch(self, device):
- inp1 = torch.ones(8, 32, device=device)
- inp2 = torch.ones(8, 32, device=device)
- bins = torch.linspace(0, 255, 128).to(device)
- bandwidth = torch.Tensor(np.array(0.9)).to(device)
- pdf = histogram2d(inp1, inp2, bins, bandwidth)
+ def test_shape_batch(self, device, dtype):
+ inp1 = torch.ones(8, 32, device=device, dtype=dtype)
+ inp2 = torch.ones(8, 32, device=device, dtype=dtype)
+ bins = torch.linspace(0, 255, 128, device=device, dtype=dtype)
+ bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
+ pdf = TestHistogram2d.fcn(inp1, inp2, bins, bandwidth)
assert pdf.shape == (8, 128, 128)
- def test_gradcheck(self, device):
- inp1 = torch.ones(3, 16, device=device)
- inp2 = torch.ones(3, 16, device=device)
+ def test_gradcheck(self, device, dtype):
+ inp1 = torch.ones(1, 8, device=device, dtype=dtype)
+ inp2 = torch.ones(1, 8, device=device, dtype=dtype)
inp1 = utils.tensor_to_gradcheck_var(inp1) # to var
inp2 = utils.tensor_to_gradcheck_var(inp2) # to var
- bins = torch.linspace(0, 255, 64).to(device)
+ bins = torch.linspace(0, 255, 8, device=device, dtype=dtype)
bins = utils.tensor_to_gradcheck_var(bins)
- bandwidth = torch.Tensor(np.array(0.9)).to(device)
+ bandwidth = torch.tensor(0.9, device=device, dtype=dtype)
bandwidth = utils.tensor_to_gradcheck_var(bandwidth)
- assert gradcheck(histogram2d, (inp1, inp2, bins, bandwidth), raise_exception=True)
+ assert gradcheck(TestHistogram2d.fcn, (inp1, inp2, bins, bandwidth), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
+ input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
+ bins = torch.linspace(0, 255, 10, device=device, dtype=dtype)
+ bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)
+ inputs = (input1, input2, bins, bandwidth)
+
+ op = TestHistogram2d.fcn
+ op_script = torch.jit.script(op)
- def test_uniform_dist(self, device):
- input1 = torch.linspace(0, 255, 10).unsqueeze(0).to(device)
- input2 = torch.linspace(0, 255, 10).unsqueeze(0).to(device)
+ assert_allclose(op(*inputs), op_script(*inputs))
- joint_pdf = histogram2d(
- input1,
- input2,
- torch.linspace(0, 255, 10).to(device),
- torch.Tensor(np.array(2 * 0.4**2)))
+ def test_uniform_dist(self, device, dtype):
+ input1 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
+ input2 = torch.linspace(0, 255, 10, device=device, dtype=dtype).unsqueeze(0)
+ bins = torch.linspace(0, 255, 10, device=device, dtype=dtype)
+ bandwidth = torch.tensor(2 * 0.4 ** 2, device=device, dtype=dtype)
- ans = torch.eye(10).unsqueeze(0) * 0.1
- assert((ans.cpu() - joint_pdf.cpu()).sum() < 1e-6)
+ pdf = TestHistogram2d.fcn(input1, input2, bins, bandwidth)
+ ans = 0.1 * kornia.eye_like(10, pdf)
+ assert_allclose(ans, pdf)
diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.py
index 4f6ae7a69..54718aac2 100644
--- a/test/enhance/test_normalize.py
+++ b/test/enhance/test_normalize.py
@@ -10,33 +10,35 @@ from torch.testing import assert_allclose
class TestNormalize:
- def test_smoke(self):
+
+ def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
repr = "Normalize(mean=[0.5], std=[0.1])"
assert str(kornia.enhance.Normalize(mean, std)) == repr
- def test_normalize(self, device):
+ def test_normalize(self, device, dtype):
# prepare input data
- data = torch.ones(1, 2, 2).to(device)
- mean = torch.tensor([0.5]).to(device)
- std = torch.tensor([2.0]).to(device)
+ data = torch.ones(1, 2, 2, device=device, dtype=dtype)
+ mean = torch.tensor([0.5], device=device, dtype=dtype)
+ std = torch.tensor([2.0], device=device, dtype=dtype)
# expected output
- expected = torch.tensor([0.25]).repeat(1, 2, 2).view_as(data).to(device)
+ expected = torch.tensor([0.25],
+ device=device, dtype=dtype).repeat(1, 2, 2).view_as(data)
f = kornia.enhance.Normalize(mean, std)
assert_allclose(f(data), expected)
- def test_broadcast_normalize(self, device):
+ def test_broadcast_normalize(self, device, dtype):
# prepare input data
- data = torch.ones(2, 3, 1, 1).to(device)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
data += 2
- mean = torch.tensor([2.0]).to(device)
- std = torch.tensor([0.5]).to(device)
+ mean = torch.tensor([2.0], device=device, dtype=dtype)
+ std = torch.tensor([0.5], device=device, dtype=dtype)
# expected output
expected = torch.ones_like(data) + 1
@@ -44,13 +46,13 @@ class TestNormalize:
f = kornia.enhance.Normalize(mean, std)
assert_allclose(f(data), expected)
- def test_float_input(self, device):
+ def test_float_input(self, device, dtype):
- data = torch.ones(2, 3, 1, 1).to(device)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
data += 2
- mean = 2.0
- std = 0.5
+ mean: float = 2.0
+ std: float = 0.5
# expected output
expected = torch.ones_like(data) + 1
@@ -58,44 +60,38 @@ class TestNormalize:
f = kornia.enhance.Normalize(mean, std)
assert_allclose(f(data), expected)
- def test_batch_normalize(self, device):
+ def test_batch_normalize(self, device, dtype):
# prepare input data
- data = torch.ones(2, 3, 1, 1).to(device)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
data += 2
- mean = torch.tensor([0.5, 1.0, 2.0]).to(device).repeat(2, 1)
- std = torch.tensor([2.0, 2.0, 2.0]).to(device).repeat(2, 1)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
# expected output
- expected = torch.tensor([1.25, 1, 0.5]).to(device).repeat(2, 1, 1).view_as(data)
+ expected = torch.tensor([1.25, 1, 0.5], device=device, dtype=dtype).repeat(2, 1, 1).view_as(data)
f = kornia.enhance.Normalize(mean, std)
assert_allclose(f(data), expected)
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- @torch.jit.script
- def op_script(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:
- return kornia.normalize(data, mean, std)
-
- data = torch.ones(2, 3, 1, 1).to(device)
- data += 2
-
- mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1).to(device)
- std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1).to(device)
+ @pytest.mark.skip(reason="union type not supported")
+ def test_jit(self, device, dtype):
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ inputs = (data, mean, std)
- actual = op_script(data, mean, std)
- expected = kornia.normalize(data, mean, std)
- assert_allclose(actual, expected)
+ op = kornia.enhance.normalize
+ op_script = torch.jit.script(op)
- def test_gradcheck(self, device):
+ assert_allclose(op(*inputs), op_script(*inputs))
+ def test_gradcheck(self, device, dtype):
# prepare input data
- data = torch.ones(2, 3, 1, 1).to(device)
- data += 2
- mean = torch.tensor([0.5, 1.0, 2.0])
- std = torch.tensor([2.0, 2.0, 2.0])
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
data = utils.tensor_to_gradcheck_var(data) # to var
mean = utils.tensor_to_gradcheck_var(mean) # to var
@@ -103,46 +99,57 @@ class TestNormalize:
assert gradcheck(kornia.enhance.Normalize(mean, std), (data,), raise_exception=True)
- def test_single_value(self, device):
+ def test_single_value(self, device, dtype):
# prepare input data
- mean = torch.tensor(2).to(device)
- std = torch.tensor(3).to(device)
- data = torch.ones(2, 3, 256, 313).to(device)
+ mean = torch.tensor(2, device=device, dtype=dtype)
+ std = torch.tensor(3, device=device, dtype=dtype)
+ data = torch.ones(2, 3, 256, 313, device=device, dtype=dtype)
# expected output
expected = (data - mean) / std
assert_allclose(kornia.normalize(data, mean, std), expected)
+ def test_module(self, device, dtype):
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ inputs = (data, mean, std)
+
+ op = kornia.enhance.normalize
+ op_module = kornia.enhance.Normalize(mean, std)
+
+ assert_allclose(op(*inputs), op_module(data))
+
class TestDenormalize:
- def test_smoke(self):
+ def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
repr = "Denormalize(mean=[0.5], std=[0.1])"
assert str(kornia.enhance.Denormalize(mean, std)) == repr
- def test_denormalize(self):
+ def test_denormalize(self, device, dtype):
# prepare input data
- data = torch.ones(1, 2, 2)
+ data = torch.ones(1, 2, 2, device=device, dtype=dtype)
mean = torch.tensor([0.5])
std = torch.tensor([2.0])
# expected output
- expected = torch.tensor([2.5]).repeat(1, 2, 2).view_as(data)
+ expected = torch.tensor([2.5], device=device, dtype=dtype).repeat(1, 2, 2).view_as(data)
f = kornia.enhance.Denormalize(mean, std)
assert_allclose(f(data), expected)
- def test_broadcast_denormalize(self):
+ def test_broadcast_denormalize(self, device, dtype):
# prepare input data
- data = torch.ones(2, 3, 1, 1)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
data += 2
- mean = torch.tensor([2.0])
- std = torch.tensor([0.5])
+ mean = torch.tensor([2.0], device=device, dtype=dtype)
+ std = torch.tensor([0.5], device=device, dtype=dtype)
# expected output
expected = torch.ones_like(data) + 2.5
@@ -150,13 +157,13 @@ class TestDenormalize:
f = kornia.enhance.Denormalize(mean, std)
assert_allclose(f(data), expected)
- def test_float_input(self):
+ def test_float_input(self, device, dtype):
- data = torch.ones(2, 3, 1, 1)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
data += 2
- mean = 2.0
- std = 0.5
+ mean: float = 2.0
+ std: float = 0.5
# expected output
expected = torch.ones_like(data) + 2.5
@@ -164,61 +171,70 @@ class TestDenormalize:
f = kornia.enhance.Denormalize(mean, std)
assert_allclose(f(data), expected)
- def test_batch_denormalize(self):
+ def test_batch_denormalize(self, device, dtype):
# prepare input data
- data = torch.ones(2, 3, 1, 1)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
data += 2
- mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)
- std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
# expected output
- expected = torch.tensor([6.5, 7, 8]).repeat(2, 1, 1).view_as(data)
+ expected = torch.tensor([6.5, 7, 8], device=device, dtype=dtype).repeat(2, 1, 1).view_as(data)
f = kornia.enhance.Denormalize(mean, std)
assert_allclose(f(data), expected)
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self):
- @torch.jit.script
- def op_script(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torch.Tensor:
- return kornia.denormalize(data, mean, std)
-
- data = torch.ones(2, 3, 1, 1)
- data += 2
+ @pytest.mark.skip(reason="union type not supported")
+ def test_jit(self, device, dtype):
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ inputs = (data, mean, std)
- mean = torch.tensor([0.5, 1.0, 2.0]).repeat(2, 1)
- std = torch.tensor([2.0, 2.0, 2.0]).repeat(2, 1)
+ op = kornia.enhance.denormalize
+ op_script = torch.jit.script(op)
- actual = op_script(data, mean, std)
- expected = kornia.denormalize(data, mean, std)
- assert_allclose(actual, expected)
+ assert_allclose(op(*inputs), op_script(*inputs))
- def test_gradcheck(self):
+ def test_gradcheck(self, device, dtype):
# prepare input data
- data = torch.ones(2, 3, 1, 1)
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
data += 2
- mean = torch.tensor([0.5, 1.0, 2.0]).double()
- std = torch.tensor([2.0, 2.0, 2.0]).double()
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype)
data = utils.tensor_to_gradcheck_var(data) # to var
+ mean = utils.tensor_to_gradcheck_var(mean) # to var
+ std = utils.tensor_to_gradcheck_var(std) # to var
assert gradcheck(kornia.enhance.Denormalize(mean, std), (data,), raise_exception=True)
- def test_single_value(self):
+ def test_single_value(self, device, dtype):
# prepare input data
- mean = torch.tensor(2)
- std = torch.tensor(3)
- data = torch.ones(2, 3, 256, 313).float()
+ mean = torch.tensor(2, device=device, dtype=dtype)
+ std = torch.tensor(3, device=device, dtype=dtype)
+ data = torch.ones(2, 3, 256, 313, device=device, dtype=dtype)
# expected output
expected = (data * std) + mean
assert_allclose(kornia.denormalize(data, mean, std), expected)
+ def test_module(self, device, dtype):
+ data = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)
+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype).repeat(2, 1)
+ inputs = (data, mean, std)
+
+ op = kornia.enhance.denormalize
+ op_module = kornia.enhance.Denormalize(mean, std)
+
+ assert_allclose(op(*inputs), op_module(data))
+
class TestNormalizeMinMax(BaseTester):
def test_smoke(self, device, dtype):
@@ -251,8 +267,8 @@ class TestNormalizeMinMax(BaseTester):
def test_range(self, device, dtype, min_val, max_val):
x = torch.rand(1, 2, 4, 5, device=device, dtype=dtype)
out = kornia.normalize_min_max(x, min_val=min_val, max_val=max_val)
- assert_allclose(out.min(), min_val)
- assert_allclose(out.max(), max_val)
+ assert_allclose(out.min().item(), min_val)
+ assert_allclose(out.max().item(), max_val)
def test_values(self, device, dtype):
x = torch.tensor([[[
@@ -282,6 +298,7 @@ class TestNormalizeMinMax(BaseTester):
x = torch.ones(1, 1, 1, 1, device=device, dtype=torch.float64, requires_grad=True)
assert gradcheck(kornia.normalize_min_max, (x,), raise_exception=True)
+ @pytest.mark.skip(reason="not implemented yet")
@pytest.mark.nn
def test_module(self, device, dtype):
pass
diff --git a/test/enhance/test_zca.py b/test/enhance/test_zca.py
index 86e0e1015..872446ebb 100644
--- a/test/enhance/test_zca.py
+++ b/test/enhance/test_zca.py
@@ -4,7 +4,6 @@ import pytest
import kornia
import kornia.testing as utils # test utils
-
import torch
from torch.autograd import gradcheck
from torch.testing import assert_allclose
@@ -13,60 +12,67 @@ from torch.testing import assert_allclose
class TestZCA:
@pytest.mark.parametrize("unbiased", [True, False])
- def test_zca_unbiased(self, unbiased, device):
+ def test_zca_unbiased(self, unbiased, device, dtype):
data = torch.tensor([[0, 1],
[1, 0],
[-1, 0],
- [0, -1]], dtype=torch.float32).to(device)
+ [0, -1]], device=device, dtype=dtype)
if unbiased:
- expected = torch.sqrt(1.5 * torch.abs(data)) * torch.sign(data)
+ unbiased_val = 1.5
else:
- expected = torch.sqrt(2 * torch.abs(data)) * torch.sign(data)
+ unbiased_val = 2.0
- expected = expected.to(device)
+ expected = torch.sqrt(unbiased_val * torch.abs(data)) * torch.sign(data)
zca = kornia.enhance.ZCAWhitening(unbiased=unbiased).fit(data)
actual = zca(data)
- assert_allclose(actual, expected)
+ tol_val: float = utils._get_precision(device, dtype)
+ assert_allclose(actual, expected, rtol=tol_val, atol=tol_val)
@pytest.mark.parametrize("dim", [0, 1])
- def test_dim_args(self, dim, device):
+ def test_dim_args(self, dim, device, dtype):
+ if 'xla' in device.type:
+ pytest.skip("buggy with XLA devices.")
data = torch.tensor([[0, 1],
[1, 0],
[-1, 0],
- [0, -1]], dtype=torch.float32).to(device)
+ [0, -1]], device=device, dtype=dtype)
if dim == 1:
- expected = torch.tensor([[-0.35360718, 0.35360718],
- [0.35351562, -0.35351562],
- [-0.35353088, 0.35353088],
- [0.35353088, -0.35353088]], dtype=torch.float32)
+ expected = torch.tensor([
+ [-0.35360718, 0.35360718],
+ [0.35351562, -0.35351562],
+ [-0.35353088, 0.35353088],
+ [0.35353088, -0.35353088],
+ ], device=device, dtype=dtype)
elif dim == 0:
- expected = torch.tensor([[0., 1.2247448],
- [1.2247448, 0.],
- [-1.2247448, 0.],
- [0., -1.2247448]], dtype=torch.float32)
- expected = expected.to(device)
+ expected = torch.tensor([
+ [0., 1.2247448],
+ [1.2247448, 0.],
+ [-1.2247448, 0.],
+ [0., -1.2247448],
+ ], device=device, dtype=dtype)
zca = kornia.enhance.ZCAWhitening(dim=dim)
actual = zca(data, True)
- assert_allclose(actual, expected)
+ tol_val: float = utils._get_precision(device, dtype)
+ assert_allclose(actual, expected, rtol=tol_val, atol=tol_val)
@pytest.mark.parametrize("input_shape,eps", [((15, 2, 2, 2), 1e-6), ((10, 4), .1), ((20, 3, 2, 2), 1e-3)])
- def test_identity(self, input_shape, eps, device):
+ def test_identity(self, input_shape, eps, device, dtype):
"""
Assert that data can be recovered by the inverse transform
"""
- data = torch.randn(*input_shape, dtype=torch.float32).to(device)
+ data = torch.randn(*input_shape, device=device, dtype=dtype)
zca = kornia.enhance.ZCAWhitening(compute_inv=True, eps=eps).fit(data)
@@ -74,9 +80,10 @@ class TestZCA:
data_hat = zca.inverse_transform(data_w)
- assert_allclose(data, data_hat)
+ tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
+ assert_allclose(data, data_hat, rtol=tol_val, atol=tol_val)
- def test_grad_zca_individual_transforms(self, device):
+ def test_grad_zca_individual_transforms(self, device, dtype):
"""
Checks if the gradients of the transforms are correct w.r.t to the input data
@@ -87,7 +94,7 @@ class TestZCA:
[0, 1],
[-2, 0],
[0, -1]],
- dtype=torch.float32).to(device)
+ device=device, dtype=dtype)
data = utils.tensor_to_gradcheck_var(data)
@@ -104,13 +111,13 @@ class TestZCA:
assert gradcheck(zca_mu, (data,), raise_exception=True)
assert gradcheck(zca_T_inv, (data,), raise_exception=True)
- def test_grad_zca_with_fit(self, device):
+ def test_grad_zca_with_fit(self, device, dtype):
data = torch.tensor([[2, 0],
[0, 1],
[-2, 0],
[0, -1]],
- dtype=torch.float32).to(device)
+ device=device, dtype=dtype)
data = utils.tensor_to_gradcheck_var(data)
@@ -120,13 +127,13 @@ class TestZCA:
assert gradcheck(zca_fit, (data,), raise_exception=True)
- def test_grad_detach_zca(self, device):
+ def test_grad_detach_zca(self, device, dtype):
data = torch.tensor([[1, 0],
[0, 1],
[-2, 0],
[0, -1]],
- dtype=torch.float32).to(device)
+ device=device, dtype=dtype)
data = utils.tensor_to_gradcheck_var(data)
zca = kornia.enhance.ZCAWhitening()
@@ -136,45 +143,46 @@ class TestZCA:
assert gradcheck(zca,
(data,), raise_exception=True)
- def test_not_fitted(self, device):
+ def test_not_fitted(self, device, dtype):
with pytest.raises(RuntimeError):
- data = torch.rand(10, 2).to(device)
+ data = torch.rand(10, 2, device=device, dtype=dtype)
zca = kornia.enhance.ZCAWhitening()
zca(data)
- def test_not_fitted_inv(self, device):
+ def test_not_fitted_inv(self, device, dtype):
with pytest.raises(RuntimeError):
- data = torch.rand(10, 2).to(device)
+ data = torch.rand(10, 2, device=device, dtype=dtype)
zca = kornia.enhance.ZCAWhitening()
zca.inverse_transform(data)
def test_jit(self, device, dtype):
- data = torch.rand((10, 3, 1, 2)).to(device)
+ data = torch.rand(10, 3, 1, 2, device=device, dtype=dtype)
zca = kornia.enhance.ZCAWhitening().fit(data)
zca_jit = kornia.enhance.ZCAWhitening().fit(data)
zca_jit = torch.jit.script(zca_jit)
assert_allclose(zca_jit(data), zca(data))
@pytest.mark.parametrize("unbiased", [True, False])
- def test_zca_whiten_func_unbiased(self, unbiased, device):
+ def test_zca_whiten_func_unbiased(self, unbiased, device, dtype):
data = torch.tensor([[0, 1],
[1, 0],
[-1, 0],
- [0, -1]], dtype=torch.float32).to(device)
+ [0, -1]], device=device, dtype=dtype)
if unbiased:
- expected = torch.sqrt(1.5 * torch.abs(data)) * torch.sign(data)
+ unbiased_val = 1.5
else:
- expected = torch.sqrt(2 * torch.abs(data)) * torch.sign(data)
+ unbiased_val = 2.0
- expected = expected.to(device)
+ expected = torch.sqrt(unbiased_val * torch.abs(data)) * torch.sign(data)
actual = kornia.zca_whiten(data, unbiased=unbiased)
- assert_allclose(actual, expected)
+ tol_val: float = utils._get_precision(device, dtype)
+ assert_allclose(actual, expected, atol=tol_val, rtol=tol_val)