Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

define and apply YAPF formatting (#1039)

Jirka Boroveca080515cb6a5
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
index c7dccb825..d52dc44b1 100644
--- a/CONTRIBUTING.rst
+++ b/CONTRIBUTING.rst
@@ -158,12 +158,14 @@ This section provides general guidance for developing code for the project. The
- Format your code:
- We follow `PEP8 style guide <https://www.python.org/dev/peps/pep-0008>`_.
- - Use ``autopep`` to autoformat: https://pypi.org/project/autopep8/#id3 .
+ - Use ``yapf`` to autoformat: https://github.com/google/yapf
For doing so, just run the following from the repository root
.. code:: bash
- make autopep8
+ make yapf
+ # OR for specific folder/path
+ yapf kornia/jit -rip
- Changes to PEP8:
diff --git a/Makefile b/Makefile
index 7c6e31f1c..828593038 100644
--- a/Makefile
+++ b/Makefile
@@ -38,6 +38,9 @@ mypy: FORCE
autopep8: FORCE
autopep8 --in-place --aggressive --recursive kornia/ test/ examples/
+yapf: FORCE
+ yapf --in-place --parallel --recursive kornia/ test/ examples/
+
doctest:
pytest -v --doctest-modules kornia
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 731e5461e..e968ca5d3 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -65,14 +65,7 @@ from kornia.contrib import (
extract_tensor_patches,
max_blur_pool2d,
)
-from kornia.feature import (
- nms2d,
- harris_response,
- hessian_response,
- gftt_response,
- SIFTDescriptor,
- MKDDescriptor
-)
+from kornia.feature import (nms2d, harris_response, hessian_response, gftt_response, SIFTDescriptor, MKDDescriptor)
from kornia.filters import (
get_gaussian_kernel1d,
get_gaussian_erf_kernel1d,
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index eddfa080a..c7e3f58b6 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -1,7 +1,4 @@
-from .base import (
- AugmentationBase2D,
- AugmentationBase3D
-)
+from .base import (AugmentationBase2D, AugmentationBase3D)
from .augmentation import (
CenterCrop,
ColorJitter,
@@ -42,13 +39,8 @@ from .augmentation3d import (
RandomEqualize3D,
RandomPerspective3D,
)
-from .mix_augmentation import (
- RandomMixUp,
- RandomCutMix
-)
-from .container import (
- VideoSequential
-)
+from .mix_augmentation import (RandomMixUp, RandomCutMix)
+from .container import (VideoSequential)
__all__ = [
"AugmentationBase2D",
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 14f558030..0697bd68b 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -52,14 +52,10 @@ from kornia.enhance.normalize import normalize, denormalize
from kornia.enhance import Invert
from . import random_generator as rg
-from .utils import (
- _range_bound,
- _transform_input
-)
+from .utils import (_range_bound, _transform_input)
class RandomHorizontalFlip(GeometricAugmentationBase2D):
-
r"""Applies a random horizontal flip to a tensor image or a batch of tensor images with a given probability.
Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
@@ -106,20 +102,22 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
w: int = input.shape[-1]
- flip_mat: torch.Tensor = torch.tensor([[-1, 0, w - 1],
- [0, 1, 0],
- [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.repeat(input.size(0), 1, 1)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return hflip(input)
class RandomVerticalFlip(GeometricAugmentationBase2D):
-
r"""Applies a random vertical flip to a tensor image or a batch of tensor images with a given probability.
Args:
@@ -160,20 +158,22 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
h: int = input.shape[-2]
- flip_mat: torch.Tensor = torch.tensor([[1, 0, 0],
- [0, -1, h - 1],
- [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.repeat(input.size(0), 1, 1)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return vflip(input)
class ColorJitter(IntensityAugmentationBase2D):
-
r"""Applies a random transformation to the brightness, contrast, saturation and hue of a tensor image.
Args:
@@ -217,15 +217,18 @@ class ColorJitter(IntensityAugmentationBase2D):
"""
def __init__(
- self, brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
+ self,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.,
- return_transform: bool = False, same_on_batch: bool = False, p: float = 1.,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 1.,
keepdim: bool = False
) -> None:
- super(ColorJitter, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(ColorJitter,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([brightness, contrast, hue, saturation])
self.brightness = brightness
self.contrast = contrast
@@ -238,19 +241,24 @@ class ColorJitter(IntensityAugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
brightness: torch.Tensor = _range_bound(
- self.brightness, 'brightness', center=1., bounds=(0, 2), device=self._device, dtype=self._dtype)
+ self.brightness, 'brightness', center=1., bounds=(0, 2), device=self._device, dtype=self._dtype
+ )
contrast: torch.Tensor = _range_bound(
- self.contrast, 'contrast', center=1., device=self._device, dtype=self._dtype)
+ self.contrast, 'contrast', center=1., device=self._device, dtype=self._dtype
+ )
saturation: torch.Tensor = _range_bound(
- self.saturation, 'saturation', center=1., device=self._device, dtype=self._dtype)
- hue: torch.Tensor = _range_bound(
- self.hue, 'hue', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype)
+ self.saturation, 'saturation', center=1., device=self._device, dtype=self._dtype
+ )
+ hue: torch.Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype)
return rg.random_color_jitter_generator(
- batch_shape[0], brightness, contrast, saturation, hue, self.same_on_batch,
- self.device, self.dtype)
+ batch_shape[0], brightness, contrast, saturation, hue, self.same_on_batch, self.device, self.dtype
+ )
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transforms = [
lambda img: adjust_brightness(img, params['brightness_factor'] - 1),
@@ -306,16 +314,24 @@ class RandomGrayscale(IntensityAugmentationBase2D):
[-0.1717, -0.9023, 0.0819]]]])
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.1,
- keepdim: bool = False) -> None:
- super(RandomGrayscale, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ def __init__(
+ self,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.1,
+ keepdim: bool = False
+ ) -> None:
+ super(RandomGrayscale,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
# Make sure it returns (*, 3, H, W)
grayscale = torch.ones_like(input)
@@ -362,13 +378,17 @@ class RandomErasing(IntensityAugmentationBase2D):
# Note: Extra params, inplace=False in Torchvision.
def __init__(
- self, scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
- ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
- value: float = 0., return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
- keepdim: bool = False
+ self,
+ scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
+ value: float = 0.,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomErasing, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomErasing,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([scale, ratio])
self.scale = scale
self.ratio = ratio
@@ -382,11 +402,22 @@ class RandomErasing(IntensityAugmentationBase2D):
scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)
ratio = torch.as_tensor(self.ratio, device=self._device, dtype=self._dtype)
return rg.random_rectangles_params_generator(
- batch_shape[0], batch_shape[-2], batch_shape[-1], scale=scale, ratio=ratio,
- value=self.value, same_on_batch=self.same_on_batch, device=self.device, dtype=self.dtype)
+ batch_shape[0],
+ batch_shape[-2],
+ batch_shape[-1],
+ scale=scale,
+ ratio=ratio,
+ value=self.value,
+ same_on_batch=self.same_on_batch,
+ device=self.device,
+ dtype=self.dtype
+ )
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, c, h, w = input.size()
values = params['values'].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).repeat(1, *input.shape[1:]).to(input)
@@ -439,45 +470,53 @@ class RandomPerspective(GeometricAugmentationBase2D):
"""
def __init__(
- self, distortion_scale: Union[torch.Tensor, float] = 0.5,
+ self,
+ distortion_scale: Union[torch.Tensor, float] = 0.5,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 0.5, keepdim: bool = False
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomPerspective, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomPerspective,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([distortion_scale])
self.distortion_scale = distortion_scale
self.resample: Resample = Resample.get(resample)
self.align_corners = align_corners
self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
+ interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
)
def __repr__(self) -> str:
- repr = (f"distortion_scale={self.distortion_scale}, interpolation={self.resample.name}, "
- f"align_corners={self.align_corners}")
+ repr = (
+ f"distortion_scale={self.distortion_scale}, interpolation={self.resample.name}, "
+ f"align_corners={self.align_corners}"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
distortion_scale = torch.as_tensor(self.distortion_scale, device=self._device, dtype=self._dtype)
return rg.random_perspective_generator(
- batch_shape[0], batch_shape[-2], batch_shape[-1], distortion_scale, self.same_on_batch,
- self.device, self.dtype)
+ batch_shape[0], batch_shape[-2], batch_shape[-1], distortion_scale, self.same_on_batch, self.device,
+ self.dtype
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return get_perspective_transform(
- params['start_points'].to(input), params['end_points'].to(input))
+ return get_perspective_transform(params['start_points'].to(input), params['end_points'].to(input))
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return warp_perspective(
- input, transform, (height, width),
- mode=self.resample.name.lower(), align_corners=self.align_corners)
+ input, transform, (height, width), mode=self.resample.name.lower(), align_corners=self.align_corners
+ )
class RandomAffine(GeometricAugmentationBase2D):
@@ -545,16 +584,21 @@ class RandomAffine(GeometricAugmentationBase2D):
"""
def __init__(
- self, degrees: Union[torch.Tensor, float, Tuple[float, float]],
+ self,
+ degrees: Union[torch.Tensor, float, Tuple[float, float]],
translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False,
- padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name, p: float = 0.5, keepdim: bool = False
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomAffine, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomAffine,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([degrees, translate, scale, shear])
self.degrees = degrees
self.translate = translate
@@ -570,60 +614,92 @@ class RandomAffine(GeometricAugmentationBase2D):
)
def __repr__(self) -> str:
- repr = (f"degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}, "
- f"resample={self.resample.name}")
+ repr = (
+ f"degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}, "
+ f"resample={self.resample.name}"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- degrees = _range_bound(
- self.degrees, 'degrees', 0, (-360, 360), device=self._device, dtype=self._dtype)
+ degrees = _range_bound(self.degrees, 'degrees', 0, (-360, 360), device=self._device, dtype=self._dtype)
translate: Optional[torch.Tensor] = None
scale: Optional[torch.Tensor] = None
shear: Optional[torch.Tensor] = None
if self.translate is not None:
translate = _range_bound(
- self.translate, 'translate', bounds=(0, 1), check='singular', device=self._device, dtype=self._dtype)
+ self.translate, 'translate', bounds=(0, 1), check='singular', device=self._device, dtype=self._dtype
+ )
if self.scale is not None:
scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)
if len(scale) == 2:
scale = _range_bound(
- scale, 'scale', bounds=(0, float('inf')), check='singular', device=self._device, dtype=self._dtype)
+ scale, 'scale', bounds=(0, float('inf')), check='singular', device=self._device, dtype=self._dtype
+ )
elif len(scale) == 4:
- scale = torch.cat([
- _range_bound(scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular',
- device=self._device, dtype=self._dtype),
- _range_bound(scale[2:], 'scale_y', bounds=(0, float('inf')), check='singular',
- device=self._device, dtype=self._dtype)
- ])
+ scale = torch.cat(
+ [
+ _range_bound(
+ scale[:2],
+ 'scale_x',
+ bounds=(0, float('inf')),
+ check='singular',
+ device=self._device,
+ dtype=self._dtype
+ ),
+ _range_bound(
+ scale[2:],
+ 'scale_y',
+ bounds=(0, float('inf')),
+ check='singular',
+ device=self._device,
+ dtype=self._dtype
+ )
+ ]
+ )
else:
raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {scale}")
if self.shear is not None:
shear = torch.as_tensor(self.shear, device=self._device, dtype=self._dtype)
- shear = torch.stack([
- _range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360),
- device=self._device, dtype=self._dtype),
- torch.tensor([0, 0], device=self._device, dtype=self._dtype) if shear.dim() == 0 or len(shear) == 2
- else _range_bound(shear[2:], 'shear-y', 0, (-360, 360), device=self._device, dtype=self._dtype)
- ])
+ shear = torch.stack(
+ [
+ _range_bound(
+ shear if shear.dim() == 0 else shear[:2],
+ 'shear-x',
+ 0, (-360, 360),
+ device=self._device,
+ dtype=self._dtype
+ ),
+ torch.tensor([0, 0], device=self._device, dtype=self._dtype) if shear.dim() == 0 or len(shear) == 2
+ else _range_bound(shear[2:], 'shear-y', 0, (-360, 360), device=self._device, dtype=self._dtype)
+ ]
+ )
return rg.random_affine_generator(
- batch_shape[0], batch_shape[-2], batch_shape[-1], degrees, translate, scale, shear,
- self.same_on_batch, self.device, self.dtype)
+ batch_shape[0], batch_shape[-2], batch_shape[-1], degrees, translate, scale, shear, self.same_on_batch,
+ self.device, self.dtype
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return get_affine_matrix2d(
- params['translations'], params['center'], params['scale'], params['angle'],
- deg2rad(params['sx']), deg2rad(params['sy'])
+ params['translations'], params['center'], params['scale'], params['angle'], deg2rad(params['sx']),
+ deg2rad(params['sy'])
).type_as(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
_, _, height, width = input.shape
transform = cast(torch.Tensor, transform)
return warp_affine(
- input, transform[:, :2, :], (height, width), self.resample.name.lower(),
- align_corners=self.align_corners, padding_mode=self.padding_mode.name.lower())
+ input,
+ transform[:, :2, :], (height, width),
+ self.resample.name.lower(),
+ align_corners=self.align_corners,
+ padding_mode=self.padding_mode.name.lower()
+ )
class CenterCrop(GeometricAugmentationBase2D):
@@ -673,31 +749,29 @@ class CenterCrop(GeometricAugmentationBase2D):
"""
def __init__(
- self,
- size: Union[int, Tuple[int, int]],
- align_corners: bool = True,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False,
- p: float = 1.,
- keepdim: bool = False,
- cropping_mode: str = 'slice',
+ self,
+ size: Union[int, Tuple[int, int]],
+ align_corners: bool = True,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ p: float = 1.,
+ keepdim: bool = False,
+ cropping_mode: str = 'slice',
) -> None:
# same_on_batch is always True for CenterCrop
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
- super(CenterCrop, self).__init__(p=1., return_transform=return_transform, same_on_batch=True, p_batch=p,
- keepdim=keepdim)
+ super(CenterCrop,
+ self).__init__(p=1., return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1])
elif isinstance(size, int):
self.size = (size, size)
else:
- raise Exception(f"Invalid size type. Expected (int, tuple(int, int). "
- f"Got: {type(size)}.")
+ raise Exception(f"Invalid size type. Expected (int, tuple(int, int). " f"Got: {type(size)}.")
self.resample = Resample.get(resample)
self.align_corners = align_corners
self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
+ interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
)
self.cropping_mode = cropping_mode
@@ -706,23 +780,25 @@ class CenterCrop(GeometricAugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.center_crop_generator(
- batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
+ return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(
- params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform(params['src'].to(input), params['dst'].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
if self.cropping_mode == 'resample': # uses bilinear interpolation to crop
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(
- input, transform[:, :2, :], self.size, self.resample.name.lower(), 'zeros', self.align_corners)
- elif self.cropping_mode == 'slice': # uses advanced slicing to crop
+ input, transform[:, :2, :], self.size, self.resample.name.lower(), 'zeros', self.align_corners
+ )
+ elif self.cropping_mode == 'slice': # uses advanced slicing to crop
# TODO: implement as separated function `crop_and_resize_iterative`
B, C, _, _ = input.shape
H, W = self.size
@@ -738,20 +814,23 @@ class CenterCrop(GeometricAugmentationBase2D):
raise NotImplementedError(f"Not supported type: {self.cropping_mode}.")
def inverse_transform(
- self, input: torch.Tensor, transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None, **kwargs
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs
) -> torch.Tensor:
if self.cropping_mode != 'resample':
raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}.")
+ f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}."
+ )
if size is None:
size = self.size
mode = self.resample.name.lower() if "mode" not in kwargs else kwargs['mode']
align_corners = self.align_corners if "align_corners" not in kwargs else kwargs['align_corners']
padding_mode = 'zeros' if "padding_mode" not in kwargs else kwargs['padding_mode']
transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(
- input, transform[:, :2, :], size, mode, padding_mode, align_corners)
+ return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
class RandomRotation(GeometricAugmentationBase2D):
@@ -800,23 +879,27 @@ class RandomRotation(GeometricAugmentationBase2D):
[2.9055e-03, 9.9416e-01, 1.9825e+00, 2.3134e-02],
[2.5777e-05, 1.1640e-02, 9.9992e-01, 1.9392e+00]]]])
"""
+
# Note: Extra params, center=None, fill=0 in TorchVision
def __init__(
- self, degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
+ self,
+ degrees: Union[torch.Tensor, float, Tuple[float, float], List[float]],
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = True, p: float = 0.5,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = True,
+ p: float = 0.5,
keepdim: bool = False
) -> None:
- super(RandomRotation, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomRotation,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([degrees])
self.degrees = degrees
self.resample: Resample = Resample.get(resample)
self.align_corners = align_corners
self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
+ interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
)
def __repr__(self) -> str:
@@ -842,7 +925,10 @@ class RandomRotation(GeometricAugmentationBase2D):
return trans_mat
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return affine(input, transform[..., :2, :3], self.resample.name.lower(), 'zeros', self.align_corners)
@@ -920,7 +1006,8 @@ class RandomCrop(GeometricAugmentationBase2D):
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super(RandomCrop, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
+ )
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
@@ -929,19 +1016,25 @@ class RandomCrop(GeometricAugmentationBase2D):
self.resample: Resample = Resample.get(resample)
self.align_corners = align_corners
self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
+ interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
)
self.cropping_mode = cropping_mode
def __repr__(self) -> str:
- repr = (f"crop_size={self.size}, padding={self.padding}, fill={self.fill}, pad_if_needed={self.pad_if_needed}, "
- f"padding_mode={self.padding_mode}, resample={self.resample.name}")
+ repr = (
+ f"crop_size={self.size}, padding={self.padding}, fill={self.fill}, pad_if_needed={self.pad_if_needed}, "
+ f"padding_mode={self.padding_mode}, resample={self.resample.name}"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), self.size,
- same_on_batch=self.same_on_batch, device=self.device, dtype=self.dtype)
+ return rg.random_crop_generator(
+ batch_shape[0], (batch_shape[-2], batch_shape[-1]),
+ self.size,
+ same_on_batch=self.same_on_batch,
+ device=self.device,
+ dtype=self.dtype
+ )
def compute_padding(self, shape: torch.Size) -> List[int]:
assert len(shape) == 4, f"Expected BCHW. Got {shape}."
@@ -974,19 +1067,26 @@ class RandomCrop(GeometricAugmentationBase2D):
return input
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(
- params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform(params['src'].to(input), params['dst'].to(input))
return transform
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
if self.cropping_mode == 'resample': # uses bilinear interpolation to crop
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(
- input, transform, self.size, mode=self.resample.name.lower(),
- padding_mode='zeros', align_corners=self.align_corners)
- elif self.cropping_mode == 'slice': # uses advanced slicing to crop
+ input,
+ transform,
+ self.size,
+ mode=self.resample.name.lower(),
+ padding_mode='zeros',
+ align_corners=self.align_corners
+ )
+ elif self.cropping_mode == 'slice': # uses advanced slicing to crop
B, C, _, _ = input.shape
out = torch.empty(B, C, *self.size, device=input.device, dtype=input.dtype)
for i in range(B):
@@ -1000,37 +1100,46 @@ class RandomCrop(GeometricAugmentationBase2D):
raise NotImplementedError(f"Not supported type: {self.flags['mode']}.")
def inverse_transform(
- self, input: torch.Tensor, transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None, **kwargs
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs
) -> torch.Tensor:
if self.cropping_mode != 'resample':
raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}.")
+ f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}."
+ )
size = cast(Tuple[int, int], size)
mode = self.resample.name.lower() if "mode" not in kwargs else kwargs['mode']
align_corners = self.align_corners if "align_corners" not in kwargs else kwargs['align_corners']
padding_mode = 'zeros' if "padding_mode" not in kwargs else kwargs['padding_mode']
transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(
- input, transform[:, :2, :], size, mode, padding_mode, align_corners)
+ return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
def inverse(
- self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Dict[str, torch.Tensor]] = None, size: Optional[Tuple[int, int]] = None, **kwargs
+ self,
+ input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs
) -> torch.Tensor:
out = super().inverse(input, params, size, **kwargs)
if params is None:
params = self._params
if 'padding_size' in params:
padding_size = params['padding_size'].unique(dim=0).cpu().squeeze().numpy().tolist()
- padding_size = [- padding_size[0], - padding_size[1], - padding_size[2], - padding_size[3]]
+ padding_size = [-padding_size[0], -padding_size[1], -padding_size[2], -padding_size[3]]
else:
padding_size = [0, 0, 0, 0]
return self.precrop_padding(out, padding_size)
- def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Dict[str, torch.Tensor]] = None, return_transform: Optional[bool] = None
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ def forward(
+ self,
+ input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ return_transform: Optional[bool] = None
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if isinstance(input, (tuple, list)):
input_temp = _transform_input(input[0])
input_pad = self.compute_padding(input[0].shape)
@@ -1043,8 +1152,8 @@ class RandomCrop(GeometricAugmentationBase2D):
out = super().forward(_input, params, return_transform)
# Update the actual input size for inverse
- _padding_size = torch.tensor(
- tuple(input_pad), device=input_temp.device, dtype=torch.long).expand(input_temp.size(0), -1)
+ _padding_size = torch.tensor(tuple(input_pad), device=input_temp.device,
+ dtype=torch.long).expand(input_temp.size(0), -1)
self._params.update({"padding_size": _padding_size})
if not self._params['batch_prob'].all():
@@ -1120,7 +1229,8 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens all the time.
super(RandomResizedCrop, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
+ )
self._device, self._dtype = _extract_device_dtype([scale, ratio])
self.size = size
self.scale = scale
@@ -1141,27 +1251,40 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
scale = torch.as_tensor(self.scale, device=self._device, dtype=self._dtype)
ratio = torch.as_tensor(self.ratio, device=self._device, dtype=self._dtype)
target_size: torch.Tensor = rg.random_crop_size_generator(
- batch_shape[0], (batch_shape[-2], batch_shape[-1]), scale, ratio, self.same_on_batch,
- self.device, self.dtype)['size']
- return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), target_size,
- resize_to=self.size, same_on_batch=self.same_on_batch,
- device=self.device, dtype=self.dtype)
+ batch_shape[0], (batch_shape[-2], batch_shape[-1]), scale, ratio, self.same_on_batch, self.device,
+ self.dtype
+ )['size']
+ return rg.random_crop_generator(
+ batch_shape[0], (batch_shape[-2], batch_shape[-1]),
+ target_size,
+ resize_to=self.size,
+ same_on_batch=self.same_on_batch,
+ device=self.device,
+ dtype=self.dtype
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform(
- params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform(params['src'].to(input), params['dst'].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
if self.cropping_mode == 'resample': # uses bilinear interpolation to crop
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat(
- input, transform, self.size, mode=self.resample.name.lower(),
- padding_mode='zeros', align_corners=self.align_corners)
- elif self.cropping_mode == 'slice': # uses advanced slicing to crop
+ input,
+ transform,
+ self.size,
+ mode=self.resample.name.lower(),
+ padding_mode='zeros',
+ align_corners=self.align_corners
+ )
+ elif self.cropping_mode == 'slice': # uses advanced slicing to crop
B, C, _, _ = input.shape
out = torch.empty(B, C, *self.size, device=input.device, dtype=input.dtype)
for i in range(B):
@@ -1169,28 +1292,33 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
x2 = int(params['src'][i, 1, 0]) + 1
y1 = int(params['src'][i, 0, 1])
y2 = int(params['src'][i, 3, 1]) + 1
- out[i] = resize(input[i:i + 1, :, y1:y2, x1:x2],
- self.size,
- interpolation=(self.resample.name).lower(),
- align_corners=self.align_corners)
+ out[i] = resize(
+ input[i:i + 1, :, y1:y2, x1:x2],
+ self.size,
+ interpolation=(self.resample.name).lower(),
+ align_corners=self.align_corners
+ )
return out
else:
raise NotImplementedError(f"Not supported type: {self.cropping_mode}.")
def inverse_transform(
- self, input: torch.Tensor, transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None, **kwargs
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs
) -> torch.Tensor:
if self.cropping_mode != 'resample':
raise NotImplementedError(
- f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}.")
+ f"`inverse` is only applicable for resample cropping mode. Got {self.cropping_mode}."
+ )
size = cast(Tuple[int, int], size)
mode = self.resample.name.lower() if "mode" not in kwargs else kwargs['mode']
align_corners = self.align_corners if "align_corners" not in kwargs else kwargs['align_corners']
padding_mode = 'zeros' if "padding_mode" not in kwargs else kwargs['padding_mode']
transform = cast(torch.Tensor, transform)
- return crop_by_transform_mat(
- input, transform[:, :2, :], size, mode, padding_mode, align_corners)
+ return crop_by_transform_mat(input, transform[:, :2, :], size, mode, padding_mode, align_corners)
class Normalize(IntensityAugmentationBase2D):
@@ -1218,11 +1346,14 @@ class Normalize(IntensityAugmentationBase2D):
"""
def __init__(
- self, mean: torch.Tensor, std: torch.Tensor,
- return_transform: bool = False, p: float = 1., keepdim: bool = False
+ self,
+ mean: torch.Tensor,
+ std: torch.Tensor,
+ return_transform: bool = False,
+ p: float = 1.,
+ keepdim: bool = False
) -> None:
- super(Normalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True,
- keepdim=keepdim)
+ super(Normalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
self.mean = mean
self.std = std
@@ -1231,7 +1362,10 @@ class Normalize(IntensityAugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return normalize(input, self.mean, self.std)
@@ -1261,11 +1395,14 @@ class Denormalize(IntensityAugmentationBase2D):
"""
def __init__(
- self, mean: torch.Tensor, std: torch.Tensor,
- return_transform: bool = False, p: float = 1., keepdim: bool = False
+ self,
+ mean: torch.Tensor,
+ std: torch.Tensor,
+ return_transform: bool = False,
+ p: float = 1.,
+ keepdim: bool = False
) -> None:
- super(Denormalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True,
- keepdim=keepdim)
+ super(Denormalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
self.mean = mean
self.std = std
@@ -1274,7 +1411,10 @@ class Denormalize(IntensityAugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return denormalize(input, self.mean, self.std)
@@ -1325,15 +1465,19 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
"""
def __init__(
- self, kernel_size: Union[int, Tuple[int, int]],
- angle: Union[torch.Tensor, float, Tuple[float, float]],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
- border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
- resample: Union[str, int, Resample] = Resample.NEAREST.name,
- return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
+ self,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[torch.Tensor, float, Tuple[float, float]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
+ resample: Union[str, int, Resample] = Resample.NEAREST.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomMotionBlur, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomMotionBlur,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self.kernel_size: Union[int, Tuple[int, int]] = kernel_size
self._device, self._dtype = _extract_device_dtype([angle, direction])
@@ -1352,22 +1496,31 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- angle = _range_bound(
- self.angle, 'angle', center=0., bounds=(-360, 360), device=self._device, dtype=self._dtype)
+ angle = _range_bound(self.angle, 'angle', center=0., bounds=(-360, 360), device=self._device, dtype=self._dtype)
direction = _range_bound(
- self.direction, 'direction', center=0., bounds=(-1, 1), device=self._device, dtype=self._dtype)
+ self.direction, 'direction', center=0., bounds=(-1, 1), device=self._device, dtype=self._dtype
+ )
return rg.random_motion_blur_generator(
- batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype)
+ batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype
+ )
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
kernel_size: int = cast(int, params['ksize_factor'].unique().item())
angle = params['angle_factor']
direction = params['direction_factor']
return motion_blur(
- input, kernel_size, angle, direction, border_type=self.border_type.name.lower(),
- mode=self.resample.name.lower())
+ input,
+ kernel_size,
+ angle,
+ direction,
+ border_type=self.border_type.name.lower(),
+ mode=self.resample.name.lower()
+ )
class RandomSolarize(IntensityAugmentationBase2D):
@@ -1409,9 +1562,13 @@ class RandomSolarize(IntensityAugmentationBase2D):
"""
def __init__(
- self, thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
+ self,
+ thresholds: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
additions: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.1,
- same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
+ same_on_batch: bool = False,
+ return_transform: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
super(RandomSolarize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
self._device, self._dtype = _extract_device_dtype([thresholds, additions])
@@ -1424,14 +1581,20 @@ class RandomSolarize(IntensityAugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
thresholds = _range_bound(
- self.thresholds, 'thresholds', center=0.5, bounds=(0., 1.), device=self._device, dtype=self._dtype)
+ self.thresholds, 'thresholds', center=0.5, bounds=(0., 1.), device=self._device, dtype=self._dtype
+ )
additions = _range_bound(
- self.additions, 'additions', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype)
- return rg.random_solarize_generator(batch_shape[0], thresholds, additions, self.same_on_batch,
- self.device, self.dtype)
+ self.additions, 'additions', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype
+ )
+ return rg.random_solarize_generator(
+ batch_shape[0], thresholds, additions, self.same_on_batch, self.device, self.dtype
+ )
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
thresholds = params['thresholds_factor']
additions: Optional[torch.Tensor]
@@ -1479,11 +1642,15 @@ class RandomPosterize(IntensityAugmentationBase2D):
"""
def __init__(
- self, bits: Union[int, Tuple[int, int], torch.Tensor] = 3,
- same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
+ self,
+ bits: Union[int, Tuple[int, int], torch.Tensor] = 3,
+ same_on_batch: bool = False,
+ return_transform: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomPosterize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomPosterize,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([bits])
self.bits = bits
@@ -1501,7 +1668,10 @@ class RandomPosterize(IntensityAugmentationBase2D):
return rg.random_posterize_generator(batch_shape[0], bits, self.same_on_batch, self.device, self.dtype)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return posterize(input, params['bits_factor'])
@@ -1540,11 +1710,15 @@ class RandomSharpness(IntensityAugmentationBase2D):
"""
def __init__(
- self, sharpness: Union[torch.Tensor, float, Tuple[float, float], torch.Tensor] = 0.5,
- same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
+ self,
+ sharpness: Union[torch.Tensor, float, Tuple[float, float], torch.Tensor] = 0.5,
+ same_on_batch: bool = False,
+ return_transform: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomSharpness, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomSharpness,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([sharpness])
self.sharpness = sharpness
@@ -1559,11 +1733,13 @@ class RandomSharpness(IntensityAugmentationBase2D):
sharpness[0] = 0.
elif not (sharpness.dim() == 1 and sharpness.size(0) == 2):
raise ValueError(f"'sharpness' must be a scalar or a length 2 tensor. Got {sharpness}.")
- return rg.random_sharpness_generator(batch_shape[0], sharpness, self.same_on_batch,
- self.device, self.dtype)
+ return rg.random_sharpness_generator(batch_shape[0], sharpness, self.same_on_batch, self.device, self.dtype)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
factor = params['sharpness_factor']
return sharpness(input, factor)
@@ -1603,22 +1779,28 @@ class RandomEqualize(IntensityAugmentationBase2D):
"""
def __init__(
- self, same_on_batch: bool = False, return_transform: bool = False, p: float = 0.5, keepdim: bool = False
+ self,
+ same_on_batch: bool = False,
+ return_transform: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomEqualize, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomEqualize,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return equalize(input)
class RandomGaussianBlur(IntensityAugmentationBase2D):
-
r"""Apply gaussian blur given tensor image or a batch of tensor images randomly.
Args:
@@ -1653,14 +1835,17 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
[0.8307, 0.6753, 0.7147, 0.5768, 0.7097]]]])
"""
- def __init__(self, kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect',
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomGaussianBlur, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = 'reflect',
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5
+ ) -> None:
+ super(RandomGaussianBlur,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
self.kernel_size = kernel_size
self.sigma = sigma
self.border_type: BorderType = BorderType.get(border_type)
@@ -1669,19 +1854,24 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
return self.__class__.__name__ + f"({super().__repr__()})"
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type.name.lower())
class GaussianBlur(RandomGaussianBlur):
import warnings
- warnings.warn("GaussianBlur is no longer maintained and will be removed from the future versions. "
- "Please use RandomGaussianBlur instead.", category=DeprecationWarning)
+ warnings.warn(
+ "GaussianBlur is no longer maintained and will be removed from the future versions. "
+ "Please use RandomGaussianBlur instead.",
+ category=DeprecationWarning
+ )
class RandomInvert(IntensityAugmentationBase2D):
-
r"""Invert the tensor images values randomly.
Args:
@@ -1704,20 +1894,25 @@ class RandomInvert(IntensityAugmentationBase2D):
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
"""
- def __init__(self,
- max_val: torch.Tensor = torch.tensor(1.),
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomInvert, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(
+ self,
+ max_val: torch.Tensor = torch.tensor(1.),
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5
+ ) -> None:
+ super(RandomInvert,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
self.transform = Invert(max_val)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return self.transform(input)
@@ -1742,12 +1937,9 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
[2., 3.]]]])
"""
- def __init__(self,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomChannelShuffle, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5) -> None:
+ super(RandomChannelShuffle,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -1758,7 +1950,10 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
return dict(channels=channels)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
out = torch.empty_like(input)
for i in range(out.shape[0]):
@@ -1785,14 +1980,16 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
[-1.1788, 1.5684]]]])
"""
- def __init__(self,
- mean: float = 0.,
- std: float = 1.,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomGaussianNoise, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(
+ self,
+ mean: float = 0.,
+ std: float = 1.,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5
+ ) -> None:
+ super(RandomGaussianNoise,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
self.mean = mean
self.std = std
@@ -1804,7 +2001,10 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
return dict(noise=noise)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return input + params['noise'].to(input.device) * self.std + self.mean
@@ -1831,15 +2031,17 @@ class RandomFisheye(GeometricAugmentationBase2D):
torch.Size([1, 1, 2, 2])
"""
- def __init__(self,
- center_x: torch.Tensor,
- center_y: torch.Tensor,
- gamma: torch.Tensor,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomFisheye, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(
+ self,
+ center_x: torch.Tensor,
+ center_y: torch.Tensor,
+ gamma: torch.Tensor,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5
+ ) -> None:
+ super(RandomFisheye,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
self.center_x = self._check_tensor(center_x)
self.center_y = self._check_tensor(center_y)
self.gamma = self._check_tensor(gamma)
@@ -1868,7 +2070,10 @@ class RandomFisheye(GeometricAugmentationBase2D):
return self.identity_matrix(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
# create the initial sampling fields
B, C, H, W = input.shape
@@ -1880,9 +2085,9 @@ class RandomFisheye(GeometricAugmentationBase2D):
center_y = params['center_y'].view(B, 1, 1).to(input)
gamma = params['gamma'].view(B, 1, 1).to(input)
# compute and apply the distances respect to the camera optical center
- distance = ((center_x - field_x) ** 2 + (center_y - field_y) ** 2) ** .5
- field_x = field_x + field_x * distance ** gamma # BxHxw
- field_y = field_y + field_y * distance ** gamma # BxHxW
+ distance = ((center_x - field_x)**2 + (center_y - field_y)**2)**.5
+ field_x = field_x + field_x * distance**gamma # BxHxw
+ field_y = field_y + field_y * distance**gamma # BxHxW
return remap(input, field_x, field_y, normalized_coordinates=True)
@@ -1909,17 +2114,19 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
torch.Size([1, 1, 2, 2])
"""
- def __init__(self,
- kernel_size: Tuple[int, int] = (63, 63),
- sigma: Tuple[float, float] = (32., 32.),
- alpha: Tuple[float, float] = (1., 1.),
- align_corners: bool = False,
- mode: str = 'bilinear',
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomElasticTransform, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int] = (63, 63),
+ sigma: Tuple[float, float] = (32., 32.),
+ alpha: Tuple[float, float] = (1., 1.),
+ align_corners: bool = False,
+ mode: str = 'bilinear',
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5
+ ) -> None:
+ super(RandomElasticTransform,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
self.kernel_size = kernel_size
self.sigma = sigma
self.alpha = alpha
@@ -1937,16 +2144,13 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
return self.identity_matrix(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return elastic_transform2d(
- input,
- params['noise'].to(input),
- self.kernel_size,
- self.sigma,
- self.alpha,
- self.align_corners,
- self.mode
+ input, params['noise'].to(input), self.kernel_size, self.sigma, self.alpha, self.align_corners, self.mode
)
@@ -1972,14 +2176,16 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
This function internally uses :func:`warp_image_tps` to perform the warping.
"""
- def __init__(self,
- scale: float = 0.2,
- align_corners: bool = False,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomThinPlateSpline, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(
+ self,
+ scale: float = 0.2,
+ align_corners: bool = False,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5
+ ) -> None:
+ super(RandomThinPlateSpline,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
self.align_corners = align_corners
self.dist = torch.distributions.Uniform(-scale, scale)
@@ -1999,7 +2205,10 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
return self.identity_matrix(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
src = params['src'].to(input)
dst = params['dst'].to(input)
@@ -2028,15 +2237,17 @@ class RandomBoxBlur(GeometricAugmentationBase2D):
torch.Size([1, 1, 24, 24])
"""
- def __init__(self,
- kernel_size: Tuple[int, int] = (3, 3),
- border_type: str = 'reflect',
- normalized: bool = True,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5) -> None:
- super(RandomBoxBlur, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int] = (3, 3),
+ border_type: str = 'reflect',
+ normalized: bool = True,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5
+ ) -> None:
+ super(RandomBoxBlur,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
self.kernel_size = kernel_size
self.border_type = border_type
self.normalized = normalized
@@ -2045,6 +2256,9 @@ class RandomBoxBlur(GeometricAugmentationBase2D):
return self.identity_matrix(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return box_blur(input, self.kernel_size, self.border_type, self.normalized)
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 32a7b5021..325829820 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -4,9 +4,7 @@ import torch
from torch.nn.functional import pad
from kornia.constants import Resample, BorderType, pi
-from kornia.geometry.transform.affwarp import (
- _compute_rotation_matrix3d, _compute_tensor_center3d
-)
+from kornia.geometry.transform.affwarp import (_compute_rotation_matrix3d, _compute_tensor_center3d)
from kornia.geometry import (
affine3d,
crop_by_boxes3d,
@@ -19,17 +17,11 @@ from kornia.geometry import (
warp_perspective3d,
)
from kornia.filters import motion_blur3d
-from kornia.enhance import (
- equalize3d
-)
+from kornia.enhance import (equalize3d)
from kornia.utils import _extract_device_dtype
from .base import AugmentationBase3D
from . import random_generator as rg
-from .utils import (
- _range_bound,
- _tuple_range_reader,
- _singular_range_check
-)
+from .utils import (_range_bound, _tuple_range_reader, _singular_range_check)
class RandomHorizontalFlip3D(AugmentationBase3D):
@@ -73,24 +65,31 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
[ 0., 0., 0., 1.]]]))
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
- keepdim: bool = False) -> None:
- super(RandomHorizontalFlip3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(
+ self,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
+ ) -> None:
+ super(RandomHorizontalFlip3D,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
w: int = input.shape[-1]
- flip_mat: torch.Tensor = torch.tensor([[-1, 0, 0, w - 1],
- [0, 1, 0, 0],
- [0, 0, 1, 0],
- [0, 0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.repeat(input.size(0), 1, 1)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return torch.flip(input, [-1])
@@ -142,24 +141,31 @@ class RandomVerticalFlip3D(AugmentationBase3D):
[ 0., 0., 0., 1.]]]))
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
- keepdim: bool = False) -> None:
- super(RandomVerticalFlip3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(
+ self,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
+ ) -> None:
+ super(RandomVerticalFlip3D,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
h: int = input.shape[-2]
- flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0],
- [0, -1, 0, h - 1],
- [0, 0, 1, 0],
- [0, 0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.repeat(input.size(0), 1, 1)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return torch.flip(input, [-2])
@@ -212,24 +218,31 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
"""
- def __init__(self, return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5,
- keepdim: bool = False) -> None:
- super(RandomDepthicalFlip3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
+ def __init__(
+ self,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
+ ) -> None:
+ super(RandomDepthicalFlip3D,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
d: int = input.shape[-3]
- flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, -1, d - 1],
- [0, 0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.repeat(input.size(0), 1, 1)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return torch.flip(input, [-3])
@@ -304,20 +317,24 @@ class RandomAffine3D(AugmentationBase3D):
"""
def __init__(
- self, degrees: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
+ self,
+ degrees: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
translate: Optional[Union[torch.Tensor, Tuple[float, float, float]]] = None,
- scale: Optional[Union[torch.Tensor, Tuple[float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]] = None,
+ scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float],
+ Tuple[float, float]]]] = None,
shears: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float],
Tuple[float, float], Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 0.5, keepdim: bool = False
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomAffine3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomAffine3D,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([degrees, shears, translate, scale])
self.degrees = degrees
self.shears = shears
@@ -326,14 +343,15 @@ class RandomAffine3D(AugmentationBase3D):
self.resample = Resample.get(resample)
self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- resample=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
- )
+ self.flags: Dict[
+ str,
+ torch.Tensor] = dict(resample=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners))
def __repr__(self) -> str:
- repr = (f"(degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shears}, "
- f"resample={self.resample.name}, align_corners={self.align_corners}")
+ repr = (
+ f"(degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shears}, "
+ f"resample={self.resample.name}, align_corners={self.align_corners}"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
@@ -360,28 +378,34 @@ class RandomAffine3D(AugmentationBase3D):
_singular_range_check(scale[1], 'scale-y', bounds=(0, float('inf')), mode='2d')
_singular_range_check(scale[2], 'scale-z', bounds=(0, float('inf')), mode='2d')
return rg.random_affine_generator3d(
- batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], degrees,
- translate, scale, shear, self.same_on_batch, self.device, self.dtype)
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], degrees, translate, scale, shear,
+ self.same_on_batch, self.device, self.dtype
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
transform: torch.Tensor = get_affine_matrix3d(
- params['translations'], params['center'], params['scale'], params['angles'],
- deg2rad(params['sxy']), deg2rad(params['sxz']), deg2rad(params['syx']),
- deg2rad(params['syz']), deg2rad(params['szx']), deg2rad(params['szy'])
+ params['translations'], params['center'], params['scale'], params['angles'], deg2rad(params['sxy']),
+ deg2rad(params['sxz']), deg2rad(params['syx']), deg2rad(params['syz']), deg2rad(params['szx']),
+ deg2rad(params['szy'])
).to(input)
return transform
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return warp_affine3d(
- input, transform[:, :3, :], (input.shape[-3], input.shape[-2], input.shape[-1]),
- self.resample.name.lower(), align_corners=self.align_corners)
+ input,
+ transform[:, :3, :], (input.shape[-3], input.shape[-2], input.shape[-1]),
+ self.resample.name.lower(),
+ align_corners=self.align_corners
+ )
class RandomRotation3D(AugmentationBase3D):
-
r"""Apply random rotations to 3D volumes (5D tensor).
Input should be a tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
@@ -439,22 +463,25 @@ class RandomRotation3D(AugmentationBase3D):
"""
def __init__(
- self, degrees: Union[torch.Tensor, float, Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
+ self,
+ degrees: Union[torch.Tensor, float, Tuple[float, float, float], Tuple[Tuple[float, float], Tuple[float, float],
+ Tuple[float, float]]],
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 0.5, keepdim: bool = False
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomRotation3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomRotation3D,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([degrees])
self.degrees = degrees
self.resample = Resample.get(resample)
self.align_corners = align_corners
- self.flags: Dict[str, torch.Tensor] = dict(
- resample=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
- )
+ self.flags: Dict[
+ str,
+ torch.Tensor] = dict(resample=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners))
def __repr__(self) -> str:
repr = f"degrees={self.degrees}, resample={self.resample.name}, align_corners={self.align_corners}"
@@ -481,7 +508,10 @@ class RandomRotation3D(AugmentationBase3D):
return trans_mat
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return affine3d(input, transform[..., :3, :4], self.resample.name.lower(), 'zeros', self.align_corners)
@@ -550,16 +580,21 @@ class RandomMotionBlur3D(AugmentationBase3D):
"""
def __init__(
- self, kernel_size: Union[int, Tuple[int, int]],
- angle: Union[torch.Tensor, float, Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
- border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
- resample: Union[str, int, Resample] = Resample.NEAREST.name,
- return_transform: bool = False, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
+ self,
+ kernel_size: Union[int, Tuple[int, int]],
+ angle: Union[torch.Tensor, float, Tuple[float, float, float], Tuple[Tuple[float, float], Tuple[float, float],
+ Tuple[float, float]]],
+ direction: Union[torch.Tensor, float, Tuple[float, float]],
+ border_type: Union[int, str, BorderType] = BorderType.CONSTANT.name,
+ resample: Union[str, int, Resample] = Resample.NEAREST.name,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
super(RandomMotionBlur3D, self).__init__(
- p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1., keepdim=keepdim)
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1., keepdim=keepdim
+ )
self._device, self._dtype = _extract_device_dtype([angle, direction])
self.kernel_size: Union[int, Tuple[int, int]] = kernel_size
self.angle = angle
@@ -579,21 +614,27 @@ class RandomMotionBlur3D(AugmentationBase3D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
angle: torch.Tensor = _tuple_range_reader(self.angle, 3, self._device, self._dtype)
direction = _range_bound(
- self.direction, 'direction', center=0., bounds=(-1, 1), device=self._device, dtype=self._dtype)
+ self.direction, 'direction', center=0., bounds=(-1, 1), device=self._device, dtype=self._dtype
+ )
return rg.random_motion_blur_generator3d(
- batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype)
+ batch_shape[0], self.kernel_size, angle, direction, self.same_on_batch, self.device, self.dtype
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return self.identity_matrix(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
kernel_size: int = cast(int, params['ksize_factor'].unique().item())
angle = params['angle_factor']
direction = params['direction_factor']
- return motion_blur3d(input, kernel_size, angle, direction, self.border_type.name.lower(),
- self.resample.name.lower())
+ return motion_blur3d(
+ input, kernel_size, angle, direction, self.border_type.name.lower(), self.resample.name.lower()
+ )
class CenterCrop3D(AugmentationBase3D):
@@ -643,13 +684,19 @@ class CenterCrop3D(AugmentationBase3D):
[ 0.6408, 0.4412]]]]])
"""
- def __init__(self, size: Union[int, Tuple[int, int, int]], align_corners: bool = True,
- resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, p: float = 1., keepdim: bool = False) -> None:
+ def __init__(
+ self,
+ size: Union[int, Tuple[int, int, int]],
+ align_corners: bool = True,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False,
+ p: float = 1.,
+ keepdim: bool = False
+ ) -> None:
# same_on_batch is always True for CenterCrop
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
- super(CenterCrop3D, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
+ super(CenterCrop3D,
+ self).__init__(p=1., return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
if isinstance(size, tuple):
self.size = (size[0], size[1], size[2])
elif isinstance(size, int):
@@ -659,8 +706,7 @@ class CenterCrop3D(AugmentationBase3D):
self.resample = Resample.get(resample)
self.align_corners = align_corners
self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
+ interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
)
def __repr__(self) -> str:
@@ -669,20 +715,24 @@ class CenterCrop3D(AugmentationBase3D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.center_crop_generator3d(
- batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.size, device=self.device)
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.size, device=self.device
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform3d(
- params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform3d(params['src'].to(input), params['dst'].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat3d(
- input, transform, self.size, mode=self.resample.name.lower(), align_corners=self.align_corners)
+ input, transform, self.size, mode=self.resample.name.lower(), align_corners=self.align_corners
+ )
class RandomCrop3D(AugmentationBase3D):
@@ -737,16 +787,23 @@ class RandomCrop3D(AugmentationBase3D):
"""
def __init__(
- self, size: Tuple[int, int, int],
+ self,
+ size: Tuple[int, int, int],
padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None,
- pad_if_needed: Optional[bool] = False, fill: int = 0, padding_mode: str = 'constant',
+ pad_if_needed: Optional[bool] = False,
+ fill: int = 0,
+ padding_mode: str = 'constant',
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = True, p: float = 1.0, keepdim: bool = False
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = True,
+ p: float = 1.0,
+ keepdim: bool = False
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super(RandomCrop3D, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim)
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
+ )
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
@@ -755,19 +812,24 @@ class RandomCrop3D(AugmentationBase3D):
self.resample = Resample.get(resample)
self.align_corners = align_corners
self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
+ interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
)
def __repr__(self) -> str:
- repr = (f"crop_size={self.size}, padding={self.padding}, fill={self.fill}, pad_if_needed={self.pad_if_needed}, "
- f"padding_mode={self.padding_mode}, resample={self.resample.name}")
+ repr = (
+ f"crop_size={self.size}, padding={self.padding}, fill={self.fill}, pad_if_needed={self.pad_if_needed}, "
+ f"padding_mode={self.padding_mode}, resample={self.resample.name}"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_crop_generator3d(batch_shape[0], (batch_shape[-3], batch_shape[-2], batch_shape[-1]),
- self.size, same_on_batch=self.same_on_batch, device=self.device,
- dtype=self.dtype)
+ return rg.random_crop_generator3d(
+ batch_shape[0], (batch_shape[-3], batch_shape[-2], batch_shape[-1]),
+ self.size,
+ same_on_batch=self.same_on_batch,
+ device=self.device,
+ dtype=self.dtype
+ )
def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
if self.padding is not None:
@@ -775,15 +837,21 @@ class RandomCrop3D(AugmentationBase3D):
padding = [self.padding, self.padding, self.padding, self.padding, self.padding, self.padding]
elif isinstance(self.padding, (tuple, list)) and len(self.padding) == 3:
padding = [
- self.padding[0], self.padding[0],
- self.padding[1], self.padding[1],
- self.padding[2], self.padding[2],
+ self.padding[0],
+ self.padding[0],
+ self.padding[1],
+ self.padding[1],
+ self.padding[2],
+ self.padding[2],
]
elif isinstance(self.padding, (tuple, list)) and len(self.padding) == 6:
padding = [
- self.padding[0], self.padding[1],
- self.padding[2], self.padding[3], # type: ignore
- self.padding[4], self.padding[5], # type: ignore
+ self.padding[0],
+ self.padding[1],
+ self.padding[2],
+ self.padding[3], # type: ignore
+ self.padding[4], # type: ignore
+ self.padding[5], # type: ignore
]
else:
raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {self.padding}.")
@@ -804,22 +872,27 @@ class RandomCrop3D(AugmentationBase3D):
return input
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- transform: torch.Tensor = get_perspective_transform3d(
- params['src'].to(input), params['dst'].to(input))
+ transform: torch.Tensor = get_perspective_transform3d(params['src'].to(input), params['dst'].to(input))
transform = transform.expand(input.shape[0], -1, -1)
return transform
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return crop_by_transform_mat3d(
- input, transform, self.size,
- mode=self.resample.name.lower(), align_corners=self.align_corners)
+ input, transform, self.size, mode=self.resample.name.lower(), align_corners=self.align_corners
+ )
- def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Dict[str, torch.Tensor]] = None, return_transform: Optional[bool] = None
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
+ def forward( # type: ignore
+ self,
+ input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ return_transform: Optional[bool] = None
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if type(input) == tuple:
input = (self.precrop_padding(input[0]), input[1])
else:
@@ -879,44 +952,55 @@ class RandomPerspective3D(AugmentationBase3D):
"""
def __init__(
- self, distortion_scale: Union[torch.Tensor, float] = 0.5,
+ self,
+ distortion_scale: Union[torch.Tensor, float] = 0.5,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 0.5, keepdim: bool = False
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ align_corners: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False
) -> None:
- super(RandomPerspective3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ super(RandomPerspective3D,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._device, self._dtype = _extract_device_dtype([distortion_scale])
self.distortion_scale = distortion_scale
self.resample = Resample.get(resample)
self.align_corners = align_corners
self.flags: Dict[str, torch.Tensor] = dict(
- interpolation=torch.tensor(self.resample.value),
- align_corners=torch.tensor(align_corners)
+ interpolation=torch.tensor(self.resample.value), align_corners=torch.tensor(align_corners)
)
def __repr__(self) -> str:
- repr = (f"distortion_scale={self.distortion_scale}, resample={self.resample.name}, "
- f"align_corners={self.align_corners}")
+ repr = (
+ f"distortion_scale={self.distortion_scale}, resample={self.resample.name}, "
+ f"align_corners={self.align_corners}"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
distortion_scale = torch.as_tensor(self.distortion_scale, device=self._device, dtype=self._dtype)
return rg.random_perspective_generator3d(
- batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1],
- distortion_scale, self.same_on_batch, self.device, self.dtype)
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], distortion_scale, self.same_on_batch,
+ self.device, self.dtype
+ )
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
- return get_perspective_transform3d(
- params['start_points'], params['end_points']).to(input)
+ return get_perspective_transform3d(params['start_points'], params['end_points']).to(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
transform = cast(torch.Tensor, transform)
return warp_perspective3d(
- input, transform, (input.shape[-3], input.shape[-2], input.shape[-1]),
- flags=self.resample.name.lower(), align_corners=self.align_corners)
+ input,
+ transform, (input.shape[-3], input.shape[-2], input.shape[-1]),
+ flags=self.resample.name.lower(),
+ align_corners=self.align_corners
+ )
class RandomEqualize3D(AugmentationBase3D):
@@ -959,10 +1043,15 @@ class RandomEqualize3D(AugmentationBase3D):
[0.4194, 0.5529, 0.9527]]]]])
"""
- def __init__(self, p: float = 0.5, return_transform: bool = False, same_on_batch: bool = False,
- keepdim: bool = False) -> None:
- super(RandomEqualize3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch,
- keepdim=keepdim)
+ def __init__(
+ self,
+ p: float = 0.5,
+ return_transform: bool = False,
+ same_on_batch: bool = False,
+ keepdim: bool = False
+ ) -> None:
+ super(RandomEqualize3D,
+ self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -971,6 +1060,9 @@ class RandomEqualize3D(AugmentationBase3D):
return self.identity_matrix(input)
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
return equalize3d(input)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 572a84945..365beeff2 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -10,11 +10,7 @@ import kornia
from kornia.utils.helpers import _torch_inverse_cast
from . import functional as F
from .utils import (
- _transform_input,
- _transform_input3d,
- _transform_output_shape,
- _validate_input_dtype,
- _adapted_sampling
+ _transform_input, _transform_input3d, _transform_output_shape, _validate_input_dtype, _adapted_sampling
)
@@ -35,8 +31,7 @@ class _BasicAugmentationBase(nn.Module):
to the batch form (False). Default: False.
"""
- def __init__(self, p: float = 0.5, p_batch: float = 1., same_on_batch: bool = False,
- keepdim: bool = False) -> None:
+ def __init__(self, p: float = 0.5, p_batch: float = 1., same_on_batch: bool = False, keepdim: bool = False) -> None:
super(_BasicAugmentationBase, self).__init__()
self.p = p
self.p_batch = p_batch
@@ -52,9 +47,7 @@ class _BasicAugmentationBase(nn.Module):
def __repr__(self) -> str:
return f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"
- def __unpack_input__(
- self, input: torch.Tensor
- ) -> torch.Tensor:
+ def __unpack_input__(self, input: torch.Tensor) -> torch.Tensor:
return input
def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
@@ -82,14 +75,15 @@ class _BasicAugmentationBase(nn.Module):
self.dtype = dtype
def __batch_prob_generator__(
- self, batch_shape: torch.Size, p: float, p_batch: float, same_on_batch: bool) -> torch.Tensor:
+ self, batch_shape: torch.Size, p: float, p_batch: float, same_on_batch: bool
+ ) -> torch.Tensor:
batch_prob: torch.Tensor
if p_batch == 1:
batch_prob = torch.tensor([True])
elif p_batch == 0:
batch_prob = torch.tensor([False])
else:
- batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch).bool()
+ batch_prob = _adapted_sampling((1, ), self._p_batch_gen, same_on_batch).bool()
if batch_prob.sum().item() == 1:
elem_prob: torch.Tensor
@@ -98,7 +92,7 @@ class _BasicAugmentationBase(nn.Module):
elif p == 0:
elem_prob = torch.tensor([False] * batch_shape[0])
else:
- elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch).bool()
+ elem_prob = _adapted_sampling((batch_shape[0], ), self._p_gen, same_on_batch).bool()
batch_prob = batch_prob * elem_prob
else:
batch_prob = batch_prob.repeat(batch_shape[0])
@@ -106,20 +100,25 @@ class _BasicAugmentationBase(nn.Module):
def forward_parameters(self, batch_shape):
to_apply = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)
- _params = self.generate_parameters(
- torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
+ _params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
if _params is None:
_params = {}
_params['batch_prob'] = to_apply
return _params
- def apply_func(self, input: torch.Tensor, params: Dict[str, torch.Tensor],
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ def apply_func(
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
input = self.transform_tensor(input)
return self.apply_transform(input, params)
- def forward(self, input: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
+ def forward( # type: ignore
+ self,
+ input: torch.Tensor,
+ params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
in_tensor = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
@@ -151,8 +150,14 @@ class _AugmentationBase(_BasicAugmentationBase):
to the batch form (False). Default: False.
"""
- def __init__(self, return_transform: bool = None, same_on_batch: bool = False, p: float = 0.5,
- p_batch: float = 1., keepdim: bool = False) -> None:
+ def __init__(
+ self,
+ return_transform: bool = None,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ p_batch: float = 1.,
+ keepdim: bool = False
+ ) -> None:
super(_AugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
self.p = p
self.p_batch = p_batch
@@ -168,7 +173,10 @@ class _AugmentationBase(_BasicAugmentationBase):
raise NotImplementedError
def apply_transform(
- self, input: torch.Tensor, params: Dict[str, torch.Tensor], transform: Optional[torch.Tensor] = None
+ self,
+ input: torch.Tensor,
+ params: Dict[str, torch.Tensor],
+ transform: Optional[torch.Tensor] = None
) -> torch.Tensor:
raise NotImplementedError
@@ -183,9 +191,13 @@ class _AugmentationBase(_BasicAugmentationBase):
in_tensor = input
return in_tensor, None
- def apply_func(self, in_tensor: torch.Tensor, in_transform: Optional[torch.Tensor], # type: ignore
- params: Dict[str, torch.Tensor], return_transform: bool = False
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ def apply_func( # type: ignore
+ self,
+ in_tensor: torch.Tensor,
+ in_transform: Optional[torch.Tensor], # type: ignore
+ params: Dict[str, torch.Tensor],
+ return_transform: bool = False
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
to_apply = params['batch_prob']
# if no augmentation needed
@@ -213,10 +225,12 @@ class _AugmentationBase(_BasicAugmentationBase):
return output
- def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore
- return_transform: Optional[bool] = None,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
+ def forward( # type: ignore
+ self,
+ input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ params: Optional[Dict[str, torch.Tensor]] = None, # type: ignore
+ return_transform: Optional[bool] = None,
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
in_tensor, in_transform = self.__unpack_input__(input)
self.__check_batching__(input)
ori_shape = in_tensor.shape
@@ -256,8 +270,7 @@ class AugmentationBase2D(_AugmentationBase):
to the batch form (False). Default: False.
"""
- def __check_batching__(self, input: Union[torch.Tensor,
- Tuple[torch.Tensor, torch.Tensor]]):
+ def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
@@ -324,8 +337,11 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
"""
def inverse_transform(
- self, input: torch.Tensor, transform: Optional[torch.Tensor] = None,
- size: Optional[Tuple[int, int]] = None, **kwargs
+ self,
+ input: torch.Tensor,
+ transform: Optional[torch.Tensor] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs
) -> torch.Tensor:
"""By default, the exact transformation as ``apply_transform`` will be used.
"""
@@ -337,10 +353,16 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
return _torch_inverse_cast(transform)
def inverse(
- self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- params: Optional[Dict[str, torch.Tensor]] = None, size: Optional[Tuple[int, int]] = None, **kwargs
+ self,
+ input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ size: Optional[Tuple[int, int]] = None,
+ **kwargs
) -> torch.Tensor:
- if isinstance(input, (list, tuple,)):
+ if isinstance(input, (
+ list,
+ tuple,
+ )):
input, transform = input
else:
transform = self._transform_matrix
@@ -367,8 +389,7 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
output = self.inverse_transform(in_tensor, transform, size, **kwargs)
else:
transform[to_apply] = self.compute_inverse_transformation(transform[to_apply])
- output[to_apply] = self.inverse_transform(
- in_tensor[to_apply], transform[to_apply], size, **kwargs)
+ output[to_apply] = self.inverse_transform(in_tensor[to_apply], transform[to_apply], size, **kwargs)
return cast(torch.Tensor, _transform_output_shape(output, ori_shape)) if self.keepdim else output
@@ -389,8 +410,7 @@ class AugmentationBase3D(_AugmentationBase):
same_on_batch (bool): apply the same transformation across the batch. Default: False.
"""
- def __check_batching__(self, input: Union[torch.Tensor,
- Tuple[torch.Tensor, torch.Tensor]]):
+ def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 5:
@@ -433,8 +453,7 @@ class MixAugmentationBase(_BasicAugmentationBase):
def __init__(self, p: float, p_batch: float, same_on_batch: bool = False, keepdim: bool = False) -> None:
super(MixAugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
- def __check_batching__(self, input: Union[torch.Tensor,
- Tuple[torch.Tensor, torch.Tensor]]):
+ def __check_batching__(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
@@ -453,12 +472,20 @@ class MixAugmentationBase(_BasicAugmentationBase):
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return _transform_input(input)
- def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignore
- params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
+ def apply_transform( # type: ignore
+ self,
+ input: torch.Tensor,
+ label: torch.Tensor, # type: ignore
+ params: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
raise NotImplementedError
- def apply_func(self, in_tensor: torch.Tensor, label: torch.Tensor, # type: ignore
- params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
+ def apply_func( # type: ignore
+ self,
+ in_tensor: torch.Tensor,
+ label: torch.Tensor, # type: ignore
+ params: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
to_apply = params['batch_prob']
# if no augmentation needed
@@ -469,13 +496,17 @@ class MixAugmentationBase(_BasicAugmentationBase):
output, label = self.apply_transform(in_tensor, label, params)
else:
raise ValueError(
- "Mix augmentations must be performed batch-wisely. Element-wise augmentation is not supported.")
+ "Mix augmentations must be performed batch-wisely. Element-wise augmentation is not supported."
+ )
return output, label
- def forward(self, input: torch.Tensor, label: torch.Tensor, # type: ignore
- params: Optional[Dict[str, torch.Tensor]] = None,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
+ def forward( # type: ignore
+ self,
+ input: torch.Tensor,
+ label: torch.Tensor, # type: ignore
+ params: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
in_tensor = self.__unpack_input__(input)
ori_shape = in_tensor.shape
in_tensor = self.transform_tensor(in_tensor)
diff --git a/kornia/augmentation/functional/__temp__.py b/kornia/augmentation/functional/__temp__.py
index 448c400e3..f89514f11 100644
--- a/kornia/augmentation/functional/__temp__.py
+++ b/kornia/augmentation/functional/__temp__.py
@@ -5,15 +5,21 @@ from functools import wraps
def __deprecation_warning(name: str, replacement: str):
- warnings.warn(f"`{name}` is no longer maintained and will be removed from the future versions. "
- f"Please use {replacement} instead.", category=DeprecationWarning)
+ warnings.warn(
+ f"`{name}` is no longer maintained and will be removed from the future versions. "
+ f"Please use {replacement} instead.",
+ category=DeprecationWarning
+ )
def _deprecation_wrapper(f: Callable) -> Callable:
+
@wraps(f)
def wrapper(*args, **kwargs):
warnings.warn(
f"`{f.__name__}` is no longer maintained and will be removed from the future versions. ",
- category=DeprecationWarning)
+ category=DeprecationWarning
+ )
return f(*args, **kwargs)
+
return wrapper
diff --git a/kornia/augmentation/functional/functional.py b/kornia/augmentation/functional/functional.py
index 30f9ce157..fd64ef84a 100644
--- a/kornia/augmentation/functional/functional.py
+++ b/kornia/augmentation/functional/functional.py
@@ -5,42 +5,19 @@ import torch
from kornia.constants import Resample, BorderType, SamplePadding, pi
from kornia.geometry import (
- get_perspective_transform,
- get_affine_matrix2d,
- warp_perspective,
- rotate,
- crop_by_boxes,
- bbox_generator,
- warp_affine,
- hflip,
- vflip,
- deg2rad,
- bbox_to_mask,
- infer_box_shape
+ get_perspective_transform, get_affine_matrix2d, warp_perspective, rotate, crop_by_boxes, bbox_generator,
+ warp_affine, hflip, vflip, deg2rad, bbox_to_mask, infer_box_shape
)
from kornia.color import rgb_to_grayscale
from kornia.enhance import (
- adjust_brightness,
- adjust_contrast,
- adjust_saturation,
- adjust_hue,
- adjust_gamma,
- solarize,
- equalize,
- posterize,
+ adjust_brightness, adjust_contrast, adjust_saturation, adjust_hue, adjust_gamma, solarize, equalize, posterize,
sharpness
)
from kornia.filters import motion_blur
from kornia.geometry.transform.affwarp import _compute_rotation_matrix, _compute_tensor_center
from .. import random_generator as rg
-from ..utils import (
- _validate_input_shape,
- _validate_input_dtype,
- _range_bound,
- _shape_validation,
- _validate_input
-)
+from ..utils import (_validate_input_shape, _validate_input_dtype, _range_bound, _shape_validation, _validate_input)
from .__temp__ import __deprecation_warning, _deprecation_wrapper
@@ -75,9 +52,9 @@ def compute_hflip_transformation(input: torch.Tensor) -> torch.Tensor:
"""
w: int = input.shape[-1]
- flip_mat: torch.Tensor = torch.tensor([[-1, 0, w - 1],
- [0, 1, 0],
- [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.repeat(input.size(0), 1, 1)
@@ -110,18 +87,16 @@ def compute_vflip_transformation(input: torch.Tensor) -> torch.Tensor:
"""
h: int = input.shape[-2]
- flip_mat: torch.Tensor = torch.tensor([[1, 0, 0],
- [0, -1, h - 1],
- [0, 0, 1]], device=input.device, dtype=input.dtype)
+ flip_mat: torch.Tensor = torch.tensor(
+ [[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype
+ )
return flip_mat.repeat(input.size(0), 1, 1)
@_deprecation_wrapper
@_validate_input
-def apply_color_jitter(
- input: torch.Tensor, params: Dict[str, torch.Tensor]
-) -> torch.Tensor:
+def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Apply Color Jitter on a tensor image or a batch of tensor images with given random parameters.
Args:
@@ -139,10 +114,8 @@ def apply_color_jitter(
"""
transforms = [
- lambda img: apply_adjust_brightness(img, params),
- lambda img: apply_adjust_contrast(img, params),
- lambda img: apply_adjust_saturation(img, params),
- lambda img: apply_adjust_hue(img, params)
+ lambda img: apply_adjust_brightness(img, params), lambda img: apply_adjust_contrast(img, params),
+ lambda img: apply_adjust_saturation(img, params), lambda img: apply_adjust_hue(img, params)
]
jittered = input
@@ -223,9 +196,7 @@ def apply_perspective(
resample_name: str = Resample(flags['interpolation'].item()).name.lower()
align_corners: bool = cast(bool, flags['align_corners'].item())
- out_data = warp_perspective(
- input, transform, (height, width),
- mode=resample_name, align_corners=align_corners)
+ out_data = warp_perspective(input, transform, (height, width), mode=resample_name, align_corners=align_corners)
return out_data.view_as(input)
@@ -246,8 +217,8 @@ def compute_perspective_transformation(input: torch.Tensor, params: Dict[str, to
Returns:
torch.Tensor: The perspective transformation matrix :math: `(*, 3, 3)`
"""
- perspective_transform: torch.Tensor = get_perspective_transform(
- params['start_points'], params['end_points']).type_as(input)
+ perspective_transform: torch.Tensor = get_perspective_transform(params['start_points'],
+ params['end_points']).type_as(input)
transform: torch.Tensor = K.eye_like(3, input)
@@ -290,10 +261,13 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Di
padding_mode: str = SamplePadding(flags['padding_mode'].item()).name.lower()
align_corners: bool = cast(bool, flags['align_corners'].item())
- out_data: torch.Tensor = warp_affine(x_data, transform[:, :2, :],
- (height, width), resample_name,
- align_corners=align_corners,
- padding_mode=padding_mode)
+ out_data: torch.Tensor = warp_affine(
+ x_data,
+ transform[:, :2, :], (height, width),
+ resample_name,
+ align_corners=align_corners,
+ padding_mode=padding_mode
+ )
return out_data.view_as(input)
@@ -316,8 +290,8 @@ def compute_affine_transformation(input: torch.Tensor, params: Dict[str, torch.T
torch.Tensor: The affine transformation matrix :math: `(*, 3, 3)`.
"""
transform = get_affine_matrix2d(
- params['translations'], params['center'], params['scale'], params['angle'],
- deg2rad(params['sx']), deg2rad(params['sy'])
+ params['translations'], params['center'], params['scale'], params['angle'], deg2rad(params['sx']),
+ deg2rad(params['sy'])
).type_as(input)
return transform
@@ -399,8 +373,7 @@ def apply_crop(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict
resample_mode: str = Resample.get(flags['interpolation'].item()).name.lower() # type: ignore
align_corners: bool = cast(bool, flags['align_corners'].item())
- return crop_by_boxes(
- input, params['src'], params['dst'], resample_mode, align_corners=align_corners)
+ return crop_by_boxes(input, params['src'], params['dst'], resample_mode, align_corners=align_corners)
@_deprecation_wrapper
@@ -570,8 +543,9 @@ def apply_adjust_gamma(input: torch.Tensor, params: Dict[str, torch.Tensor]) ->
@_deprecation_wrapper
@_validate_input
-def apply_motion_blur(input: torch.Tensor, params: Dict[str, torch.Tensor],
- flags: Dict[str, torch.Tensor]) -> torch.Tensor:
+def apply_motion_blur(
+ input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]
+) -> torch.Tensor:
r"""Perform motion blur on an image.
Args:
@@ -720,9 +694,13 @@ def apply_mixup(input: torch.Tensor, labels: torch.Tensor,
lam = params['mixup_lambdas'].view(-1, 1, 1, 1).expand_as(input).to(labels.device)
inputs = input * (1 - lam) + input_permute * lam
- labels = torch.stack([
- labels.to(input.dtype), labels_permute.to(input.dtype), params['mixup_lambdas'].to(labels.device, input.dtype)
- ], dim=-1).to(labels.device)
+ labels = torch.stack(
+ [
+ labels.to(input.dtype),
+ labels_permute.to(input.dtype), params['mixup_lambdas'].to(labels.device, input.dtype)
+ ],
+ dim=-1
+ ).to(labels.device)
return inputs, labels
@@ -791,7 +769,10 @@ def apply_cutmix(input: torch.Tensor, labels: torch.Tensor,
# compute mask to match input shape
mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)
out_inputs[mask] = input_permute[mask]
- out_labels.append(torch.stack([
- labels.to(input.dtype), labels_permute.to(input.dtype), lam.to(labels.device)], dim=1))
+ out_labels.append(
+ torch.stack([labels.to(input.dtype),
+ labels_permute.to(input.dtype),
+ lam.to(labels.device)], dim=1)
+ )
return out_inputs, torch.stack(out_labels, dim=0)
diff --git a/kornia/augmentation/functional/functional3d.py b/kornia/augmentation/functional/functional3d.py
index e1365d456..f8247361d 100644
--- a/kornia/augmentation/functional/functional3d.py
+++ b/kornia/augmentation/functional/functional3d.py
@@ -4,26 +4,15 @@ import torch
import kornia as K
from kornia.constants import Resample, BorderType, pi
-from kornia.geometry.transform.affwarp import (
- _compute_rotation_matrix3d, _compute_tensor_center3d
-)
+from kornia.geometry.transform.affwarp import (_compute_rotation_matrix3d, _compute_tensor_center3d)
from kornia.geometry.transform.projwarp import warp_affine3d
from kornia.geometry import (
- crop_by_boxes3d,
- warp_perspective3d,
- get_perspective_transform3d,
- rotate3d,
- get_affine_matrix3d,
- deg2rad
-)
-from kornia.enhance import (
- equalize3d
+ crop_by_boxes3d, warp_perspective3d, get_perspective_transform3d, rotate3d, get_affine_matrix3d, deg2rad
)
+from kornia.enhance import (equalize3d)
from .. import random_generator as rg
-from ..utils import (
- _validate_input3d
-)
+from ..utils import (_validate_input3d)
from kornia.filters import motion_blur3d
from .__temp__ import __deprecation_warning, _deprecation_wrapper
@@ -57,10 +46,7 @@ def compute_hflip_transformation3d(input: torch.Tensor) -> torch.Tensor:
"""
w: int = input.shape[-1]
- flip_mat: torch.Tensor = torch.tensor([[-1, 0, 0, w - 1],
- [0, 1, 0, 0],
- [0, 0, 1, 0],
- [0, 0, 0, 1]])
+ flip_mat: torch.Tensor = torch.tensor([[-1, 0, 0, w - 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
return flip_mat.repeat(input.size(0), 1, 1).to(input)
@@ -93,10 +79,7 @@ def compute_vflip_transformation3d(input: torch.Tensor) -> torch.Tensor:
"""
h: int = input.shape[-2]
- flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0],
- [0, -1, 0, h - 1],
- [0, 0, 1, 0],
- [0, 0, 0, 1]])
+ flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0], [0, -1, 0, h - 1], [0, 0, 1, 0], [0, 0, 0, 1]])
return flip_mat.repeat(input.size(0), 1, 1).to(input)
@@ -144,18 +127,16 @@ def compute_dflip_transformation3d(input: torch.Tensor) -> torch.Tensor:
"""
d: int = input.shape[-3]
- flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0],
- [0, 1, 0, 0],
- [0, 0, -1, d - 1],
- [0, 0, 0, 1]])
+ flip_mat: torch.Tensor = torch.tensor([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, d - 1], [0, 0, 0, 1]])
return flip_mat.repeat(input.size(0), 1, 1).to(input)
@_deprecation_wrapper
@_validate_input3d
-def apply_affine3d(input: torch.Tensor, params: Dict[str, torch.Tensor],
- flags: Dict[str, torch.Tensor]) -> torch.Tensor:
+def apply_affine3d(
+ input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]
+) -> torch.Tensor:
r"""Random affine transformation of the image keeping center invariant.
Args:
@@ -190,9 +171,9 @@ def apply_affine3d(input: torch.Tensor, params: Dict[str, torch.Tensor],
resample_name: str = Resample(flags['resample'].item()).name.lower()
align_corners: bool = cast(bool, flags['align_corners'].item())
- out_data: torch.Tensor = warp_affine3d(x_data, transform[:, :3, :],
- (depth, height, width), resample_name,
- align_corners=align_corners)
+ out_data: torch.Tensor = warp_affine3d(
+ x_data, transform[:, :3, :], (depth, height, width), resample_name, align_corners=align_corners
+ )
return out_data.view_as(input)
@@ -219,17 +200,18 @@ def compute_affine_transformation3d(input: torch.Tensor, params: Dict[str, torch
torch.Tensor: The affine transformation matrix :math: `(*, 4, 4)`.
"""
transform = get_affine_matrix3d(
- params['translations'], params['center'], params['scale'], params['angles'],
- deg2rad(params['sxy']), deg2rad(params['sxz']), deg2rad(params['syx']),
- deg2rad(params['syz']), deg2rad(params['szx']), deg2rad(params['szy'])
+ params['translations'], params['center'], params['scale'], params['angles'], deg2rad(params['sxy']),
+ deg2rad(params['sxz']), deg2rad(params['syx']), deg2rad(params['syz']), deg2rad(params['szx']),
+ deg2rad(params['szy'])
).to(input)
return transform
@_deprecation_wrapper
@_validate_input3d
-def apply_rotation3d(input: torch.Tensor, params: Dict[str, torch.Tensor],
- flags: Dict[str, torch.Tensor]) -> torch.Tensor:
+def apply_rotation3d(
+ input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]
+) -> torch.Tensor:
r"""Rotate a tensor image or a batch of tensor images a random amount of degrees.
Args:
@@ -288,8 +270,9 @@ def compute_rotate_tranformation3d(input: torch.Tensor, params: Dict[str, torch.
@_deprecation_wrapper
@_validate_input3d
-def apply_motion_blur3d(input: torch.Tensor, params: Dict[str, torch.Tensor],
- flags: Dict[str, torch.Tensor]) -> torch.Tensor:
+def apply_motion_blur3d(
+ input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]
+) -> torch.Tensor:
r"""Perform motion blur on an image.
Args:
@@ -343,8 +326,7 @@ def apply_crop3d(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Di
resample_mode: str = Resample.get(flags['interpolation'].item()).name.lower() # type: ignore
align_corners: bool = cast(bool, flags['align_corners'].item())
- return crop_by_boxes3d(
- input, params['src'], params['dst'], resample_mode, align_corners=align_corners)
+ return crop_by_boxes3d(input, params['src'], params['dst'], resample_mode, align_corners=align_corners)
@_deprecation_wrapper
@@ -403,8 +385,8 @@ def apply_perspective3d(
align_corners: bool = cast(bool, flags['align_corners'].item())
out_data = warp_perspective3d(
- input, transform, (depth, height, width),
- flags=resample_name, align_corners=align_corners)
+ input, transform, (depth, height, width), flags=resample_name, align_corners=align_corners
+ )
return out_data.view_as(input)
@@ -425,8 +407,8 @@ def compute_perspective_transformation3d(input: torch.Tensor, params: Dict[str,
Returns:
torch.Tensor: The perspective transformation matrix :math: `(*, 4, 4)`
"""
- perspective_transform: torch.Tensor = get_perspective_transform3d(
- params['start_points'], params['end_points']).to(input)
+ perspective_transform: torch.Tensor = get_perspective_transform3d(params['start_points'],
+ params['end_points']).to(input)
transform: torch.Tensor = K.eye_like(4, input)
diff --git a/kornia/augmentation/mix_augmentation.py b/kornia/augmentation/mix_augmentation.py
index b3367a06f..9df7f9d97 100644
--- a/kornia/augmentation/mix_augmentation.py
+++ b/kornia/augmentation/mix_augmentation.py
@@ -81,8 +81,13 @@ class RandomMixUp(MixAugmentationBase):
[1.0000, 1.0000, 0.4162]]))
"""
- def __init__(self, lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- same_on_batch: bool = False, p: float = 1.0, keepdim: bool = False) -> None:
+ def __init__(
+ self,
+ lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ same_on_batch: bool = False,
+ p: float = 1.0,
+ keepdim: bool = False
+ ) -> None:
super(RandomMixUp, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.lambda_val = lambda_val
@@ -98,17 +103,24 @@ class RandomMixUp(MixAugmentationBase):
torch.tensor(self.lambda_val, device=self.device, dtype=self.dtype)
return rg.random_mixup_generator(batch_shape[0], self.p, lambda_val, same_on_batch=self.same_on_batch)
- def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignore
- params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
+ def apply_transform( # type: ignore
+ self,
+ input: torch.Tensor,
+ label: torch.Tensor, # type: ignore
+ params: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
input_permute = input.index_select(dim=0, index=params['mixup_pairs'].to(input.device))
labels_permute = label.index_select(dim=0, index=params['mixup_pairs'].to(label.device))
lam = params['mixup_lambdas'].view(-1, 1, 1, 1).expand_as(input).to(label.device)
inputs = input * (1 - lam) + input_permute * lam
- out_labels = torch.stack([
- label.to(input.dtype), labels_permute.to(input.dtype),
- params['mixup_lambdas'].to(label.device, input.dtype)
- ], dim=-1).to(label.device)
+ out_labels = torch.stack(
+ [
+ label.to(input.dtype),
+ labels_permute.to(input.dtype), params['mixup_lambdas'].to(label.device, input.dtype)
+ ],
+ dim=-1
+ ).to(label.device)
return inputs, out_labels
@@ -189,10 +201,17 @@ class RandomCutMix(MixAugmentationBase):
[1.0000, 0.0000, 0.4444]]]))
"""
- def __init__(self, height: int, width: int, num_mix: int = 1,
- cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- beta: Optional[Union[torch.Tensor, float]] = None, same_on_batch: bool = False,
- p: float = 1., keepdim: bool = False) -> None:
+ def __init__(
+ self,
+ height: int,
+ width: int,
+ num_mix: int = 1,
+ cut_size: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
+ beta: Optional[Union[torch.Tensor, float]] = None,
+ same_on_batch: bool = False,
+ p: float = 1.,
+ keepdim: bool = False
+ ) -> None:
super(RandomCutMix, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.height = height
self.width = width
@@ -201,8 +220,10 @@ class RandomCutMix(MixAugmentationBase):
self.cut_size = cut_size
def __repr__(self) -> str:
- repr = (f"num_mix={self.num_mix}, beta={self.beta}, cut_size={self.cut_size}, "
- f"height={self.height}, width={self.width}")
+ repr = (
+ f"num_mix={self.num_mix}, beta={self.beta}, cut_size={self.cut_size}, "
+ f"height={self.height}, width={self.width}"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
@@ -216,12 +237,23 @@ class RandomCutMix(MixAugmentationBase):
else:
cut_size = cast(torch.Tensor, self.cut_size) if isinstance(self.cut_size, torch.Tensor) else \
torch.tensor(self.cut_size, device=self.device, dtype=self.dtype)
- return rg.random_cutmix_generator(batch_shape[0], width=self.width, height=self.height, p=self.p,
- cut_size=cut_size, num_mix=self.num_mix, beta=beta,
- same_on_batch=self.same_on_batch)
-
- def apply_transform(self, input: torch.Tensor, label: torch.Tensor, # type: ignore
- params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
+ return rg.random_cutmix_generator(
+ batch_shape[0],
+ width=self.width,
+ height=self.height,
+ p=self.p,
+ cut_size=cut_size,
+ num_mix=self.num_mix,
+ beta=beta,
+ same_on_batch=self.same_on_batch
+ )
+
+ def apply_transform( # type: ignore
+ self,
+ input: torch.Tensor,
+ label: torch.Tensor, # type: ignore
+ params: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
height, width = input.size(2), input.size(3)
num_mixes = params['mix_pairs'].size(0)
batch_size = params['mix_pairs'].size(1)
@@ -239,7 +271,10 @@ class RandomCutMix(MixAugmentationBase):
# compute mask to match input shape
mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)
out_inputs[mask] = input_permute[mask]
- out_labels.append(torch.stack([
- label.to(input.dtype), labels_permute.to(input.dtype), lam.to(label.device)], dim=1))
+ out_labels.append(
+ torch.stack([label.to(input.dtype),
+ labels_permute.to(input.dtype),
+ lam.to(label.device)], dim=1)
+ )
return out_inputs, torch.stack(out_labels, dim=0)
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index 896aaabc1..8cd67f89f 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -17,8 +17,12 @@ from kornia.utils import _extract_device_dtype
def random_prob_generator(
- batch_size: int, p: float = 0.5, same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'), dtype: torch.dtype = torch.float32) -> torch.Tensor:
+ batch_size: int,
+ p: float = 0.5,
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
+) -> torch.Tensor:
r"""Generate random probabilities for a batch of inputs.
Args:
@@ -40,7 +44,7 @@ def random_prob_generator(
raise TypeError(f"The probability should be a float number within [0, 1]. Got {type(p)}.")
_bernoulli = Bernoulli(torch.tensor(float(p), device=device, dtype=dtype))
- probs_mask: torch.Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
+ probs_mask: torch.Tensor = _adapted_sampling((batch_size, ), _bernoulli, same_on_batch).bool()
return probs_mask
@@ -96,16 +100,18 @@ def random_color_jitter_generator(
_joint_range_check(hue, "hue", (-0.5, 0.5))
_joint_range_check(saturation, "saturation", (0, float('inf')))
- brightness_factor = _adapted_uniform((batch_size,), brightness[0], brightness[1], same_on_batch)
- contrast_factor = _adapted_uniform((batch_size,), contrast[0], contrast[1], same_on_batch)
- hue_factor = _adapted_uniform((batch_size,), hue[0], hue[1], same_on_batch)
- saturation_factor = _adapted_uniform((batch_size,), saturation[0], saturation[1], same_on_batch)
+ brightness_factor = _adapted_uniform((batch_size, ), brightness[0], brightness[1], same_on_batch)
+ contrast_factor = _adapted_uniform((batch_size, ), contrast[0], contrast[1], same_on_batch)
+ hue_factor = _adapted_uniform((batch_size, ), hue[0], hue[1], same_on_batch)
+ saturation_factor = _adapted_uniform((batch_size, ), saturation[0], saturation[1], same_on_batch)
- return dict(brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
- contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
- hue_factor=hue_factor.to(device=_device, dtype=_dtype),
- saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
- order=torch.randperm(4, device=_device, dtype=_dtype).long())
+ return dict(
+ brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
+ contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
+ hue_factor=hue_factor.to(device=_device, dtype=_dtype),
+ saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
+ order=torch.randperm(4, device=_device, dtype=_dtype).long()
+ )
def random_perspective_generator(
@@ -142,12 +148,16 @@ def random_perspective_generator(
assert type(height) == int and height > 0 and type(width) == int and width > 0, \
f"'height' and 'width' must be integers. Got {height}, {width}."
- start_points: torch.Tensor = torch.tensor([[
- [0., 0],
- [width - 1, 0],
- [width - 1, height - 1],
- [0, height - 1],
- ]], device=distortion_scale.device, dtype=distortion_scale.dtype).expand(batch_size, -1, -1)
+ start_points: torch.Tensor = torch.tensor(
+ [[
+ [0., 0],
+ [width - 1, 0],
+ [width - 1, height - 1],
+ [0, height - 1],
+ ]],
+ device=distortion_scale.device,
+ dtype=distortion_scale.dtype
+ ).expand(batch_size, -1, -1)
# generate random offset not larger than half of the image
fx = distortion_scale * width / 2
@@ -157,20 +167,16 @@ def random_perspective_generator(
# TODO: This line somehow breaks the gradcheck
rand_val: torch.Tensor = _adapted_uniform(
- start_points.shape, torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch
+ start_points.shape, torch.tensor(0, device=device, dtype=dtype), torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch
).to(device=distortion_scale.device, dtype=distortion_scale.dtype)
- pts_norm = torch.tensor([[
- [1, 1],
- [-1, 1],
- [-1, -1],
- [1, -1]
- ]], device=distortion_scale.device, dtype=distortion_scale.dtype)
+ pts_norm = torch.tensor(
+ [[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=distortion_scale.device, dtype=distortion_scale.dtype
+ )
end_points = start_points + factor * rand_val * pts_norm
- return dict(start_points=start_points,
- end_points=end_points)
+ return dict(start_points=start_points, end_points=end_points)
def random_affine_generator(
@@ -224,7 +230,7 @@ def random_affine_generator(
_device, _dtype = _extract_device_dtype([degrees, translate, scale, shear])
degrees = degrees.to(device=device, dtype=dtype)
- angle = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
+ angle = _adapted_uniform((batch_size, ), degrees[0], degrees[1], same_on_batch)
angle = angle.to(device=_device, dtype=_dtype)
# compute tensor ranges
@@ -233,11 +239,10 @@ def random_affine_generator(
assert len(scale.shape) == 1 and (len(scale) == 2 or len(scale) == 4), \
f"`scale` shall have 2 or 4 elements. Got {scale}."
_joint_range_check(cast(torch.Tensor, scale[:2]), "scale")
- _scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
+ _scale = _adapted_uniform((batch_size, ), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
if len(scale) == 4:
_joint_range_check(cast(torch.Tensor, scale[2:]), "scale_y")
- _scale[:, 1] = _adapted_uniform(
- (batch_size,), scale[2], scale[3], same_on_batch)
+ _scale[:, 1] = _adapted_uniform((batch_size, ), scale[2], scale[3], same_on_batch)
_scale = _scale.to(device=_device, dtype=_dtype)
else:
_scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
@@ -248,35 +253,32 @@ def random_affine_generator(
f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}."
max_dx: torch.Tensor = translate[0] * width
max_dy: torch.Tensor = translate[1] * height
- translations = torch.stack([
- _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
- _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch)
- ], dim=-1)
+ translations = torch.stack(
+ [
+ _adapted_uniform((batch_size, ), -max_dx, max_dx, same_on_batch),
+ _adapted_uniform((batch_size, ), -max_dy, max_dy, same_on_batch)
+ ],
+ dim=-1
+ )
translations = translations.to(device=_device, dtype=_dtype)
else:
translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
- center: torch.Tensor = torch.tensor(
- [width, height], device=_device, dtype=_dtype).view(1, 2) / 2. - 0.5
+ center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2. - 0.5
center = center.expand(batch_size, -1)
if shear is not None:
shear = shear.to(device=device, dtype=dtype)
_joint_range_check(cast(torch.Tensor, shear)[0], "shear")
_joint_range_check(cast(torch.Tensor, shear)[1], "shear")
- sx = _adapted_uniform((batch_size,), shear[0][0], shear[0][1], same_on_batch)
- sy = _adapted_uniform((batch_size,), shear[1][0], shear[1][1], same_on_batch)
+ sx = _adapted_uniform((batch_size, ), shear[0][0], shear[0][1], same_on_batch)
+ sy = _adapted_uniform((batch_size, ), shear[1][0], shear[1][1], same_on_batch)
sx = sx.to(device=_device, dtype=_dtype)
sy = sy.to(device=_device, dtype=_dtype)
else:
sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
- return dict(translations=translations,
- center=center,
- scale=_scale,
- angle=angle,
- sx=sx,
- sy=sy)
+ return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
def random_rotation_generator(
@@ -305,8 +307,10 @@ def random_rotation_generator(
_common_param_check(batch_size, same_on_batch)
_joint_range_check(degrees, "degrees")
- _degrees = _adapted_uniform((batch_size,), degrees[0].to(device=device, dtype=dtype),
- degrees[1].to(device=device, dtype=dtype), same_on_batch)
+ _degrees = _adapted_uniform(
+ (batch_size, ), degrees[0].to(device=device, dtype=dtype), degrees[1].to(device=device, dtype=dtype),
+ same_on_batch
+ )
_degrees = _degrees.to(device=degrees.device, dtype=degrees.dtype)
return dict(degrees=_degrees)
@@ -385,7 +389,8 @@ def random_crop_generator(
size = size.to(device=_device, dtype=_dtype)
assert size.shape == torch.Size([batch_size, 2]), (
"If `size` is a tensor, it must be shaped as (B, 2). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}.")
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}."
+ )
assert input_size[0] > 0 and input_size[1] > 0 and (size > 0).all(), \
f"Got non-positive input size or size. {input_size}, {size}."
size = size.floor()
@@ -405,33 +410,37 @@ def random_crop_generator(
if same_on_batch:
# If same_on_batch, select the first then repeat.
- x_start = _adapted_uniform((batch_size,), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
- y_start = _adapted_uniform((batch_size,), 0, y_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
+ x_start = _adapted_uniform((batch_size, ), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
+ y_start = _adapted_uniform((batch_size, ), 0, y_diff[0].to(device=device, dtype=dtype), same_on_batch).floor()
else:
- x_start = _adapted_uniform((1,), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).floor()
- y_start = _adapted_uniform((1,), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).floor()
+ x_start = _adapted_uniform((1, ), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).floor()
+ y_start = _adapted_uniform((1, ), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).floor()
crop_src = bbox_generator(
x_start.view(-1).to(device=_device, dtype=_dtype),
y_start.view(-1).to(device=_device, dtype=_dtype),
torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
- torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]))
+ torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0])
+ )
if resize_to is None:
crop_dst = bbox_generator(
torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- size[:, 1],
- size[:, 0])
+ torch.tensor([0] * batch_size, device=_device, dtype=_dtype), size[:, 1], size[:, 0]
+ )
else:
assert len(resize_to) == 2 and isinstance(resize_to[0], (int,)) and isinstance(resize_to[1], (int,)) \
and resize_to[0] > 0 and resize_to[1] > 0, \
f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}."
- crop_dst = torch.tensor([[
- [0, 0],
- [resize_to[1] - 1, 0],
- [resize_to[1] - 1, resize_to[0] - 1],
- [0, resize_to[0] - 1],
- ]], device=_device, dtype=_dtype).repeat(batch_size, 1, 1)
+ crop_dst = torch.tensor(
+ [[
+ [0, 0],
+ [resize_to[1] - 1, 0],
+ [resize_to[1] - 1, resize_to[0] - 1],
+ [0, resize_to[0] - 1],
+ ]],
+ device=_device,
+ dtype=_dtype
+ ).repeat(batch_size, 1, 1)
_input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
@@ -486,10 +495,8 @@ def random_crop_size_generator(
scale = scale.to(device=device, dtype=dtype)
ratio = ratio.to(device=device, dtype=dtype)
# 10 trails for each element
- area = _adapted_uniform(
- (batch_size, 10), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
- log_ratio = _adapted_uniform(
- (batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)
+ area = _adapted_uniform((batch_size, 10), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
+ log_ratio = _adapted_uniform((batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)
aspect_ratio = torch.exp(log_ratio)
w = torch.sqrt(area * aspect_ratio).round().floor()
@@ -569,60 +576,68 @@ def random_rectangles_params_generator(
_joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
images_area = height * width
- target_areas = _adapted_uniform((batch_size,), scale[0].to(device=device, dtype=dtype),
- scale[1].to(device=device, dtype=dtype), same_on_batch) * images_area
+ target_areas = _adapted_uniform(
+ (batch_size, ), scale[0].to(device=device, dtype=dtype), scale[1].to(device=device, dtype=dtype), same_on_batch
+ ) * images_area
if ratio[0] < 1. and ratio[1] > 1.:
- aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0].to(device=device, dtype=dtype), 1, same_on_batch)
- aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1].to(device=device, dtype=dtype), same_on_batch)
+ aspect_ratios1 = _adapted_uniform((batch_size, ), ratio[0].to(device=device, dtype=dtype), 1, same_on_batch)
+ aspect_ratios2 = _adapted_uniform((batch_size, ), 1, ratio[1].to(device=device, dtype=dtype), same_on_batch)
if same_on_batch:
- rand_idxs = torch.round(_adapted_uniform(
- (1,), torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch)).repeat(batch_size).bool()
+ rand_idxs = torch.round(
+ _adapted_uniform(
+ (1, ), torch.tensor(0, device=device, dtype=dtype), torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch
+ )
+ ).repeat(batch_size).bool()
else:
- rand_idxs = torch.round(_adapted_uniform(
- (batch_size,), torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch)).bool()
+ rand_idxs = torch.round(
+ _adapted_uniform(
+ (batch_size, ), torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype), same_on_batch
+ )
+ ).bool()
aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
else:
aspect_ratios = _adapted_uniform(
- (batch_size,), ratio[0].to(device=device, dtype=dtype),
- ratio[1].to(device=device, dtype=dtype), same_on_batch)
+ (batch_size, ), ratio[0].to(device=device, dtype=dtype), ratio[1].to(device=device, dtype=dtype),
+ same_on_batch
+ )
# based on target areas and aspect ratios, rectangle params are computed
heights = torch.min(
- torch.max(torch.round((target_areas * aspect_ratios) ** (1 / 2)),
- torch.tensor(1., device=device, dtype=dtype)),
+ torch.max(torch.round((target_areas * aspect_ratios)**(1 / 2)), torch.tensor(1., device=device, dtype=dtype)),
torch.tensor(height, device=device, dtype=dtype)
)
widths = torch.min(
- torch.max(torch.round((target_areas / aspect_ratios) ** (1 / 2)),
- torch.tensor(1., device=device, dtype=dtype)),
+ torch.max(torch.round((target_areas / aspect_ratios)**(1 / 2)), torch.tensor(1., device=device, dtype=dtype)),
torch.tensor(width, device=device, dtype=dtype)
)
- xs_ratio = _adapted_uniform((batch_size,), torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch)
- ys_ratio = _adapted_uniform((batch_size,), torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch)
+ xs_ratio = _adapted_uniform(
+ (batch_size, ), torch.tensor(0, device=device, dtype=dtype), torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch
+ )
+ ys_ratio = _adapted_uniform(
+ (batch_size, ), torch.tensor(0, device=device, dtype=dtype), torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch
+ )
xs = xs_ratio * (torch.tensor(width, device=device, dtype=dtype) - widths + 1)
ys = ys_ratio * (torch.tensor(height, device=device, dtype=dtype) - heights + 1)
- return dict(widths=widths.floor().to(device=_device, dtype=_dtype),
- heights=heights.floor().to(device=_device, dtype=_dtype),
- xs=xs.floor().to(device=_device, dtype=_dtype),
- ys=ys.floor().to(device=_device, dtype=_dtype),
- values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype))
+ return dict(
+ widths=widths.floor().to(device=_device, dtype=_dtype),
+ heights=heights.floor().to(device=_device, dtype=_dtype),
+ xs=xs.floor().to(device=_device, dtype=_dtype),
+ ys=ys.floor().to(device=_device, dtype=_dtype),
+ values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype)
+ )
def center_crop_generator(
- batch_size: int,
- height: int,
- width: int,
- size: Tuple[int, int],
- device: torch.device = torch.device('cpu')
+ batch_size: int, height: int, width: int, size: Tuple[int, int], device: torch.device = torch.device('cpu')
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
@@ -642,9 +657,11 @@ def center_crop_generator(
No random number will be generated.
"""
_common_param_check(batch_size)
- if not isinstance(size, (tuple, list,)) and len(size) == 2:
- raise ValueError("Input size must be a tuple/list of length 2. Got {}"
- .format(size))
+ if not isinstance(size, (
+ tuple,
+ list,
+ )) and len(size) == 2:
+ raise ValueError("Input size must be a tuple/list of length 2. Got {}".format(size))
assert type(height) == int and height > 0 and type(width) == int and width > 0, \
f"'height' and 'width' must be integers. Got {height}, {width}."
assert height >= size[0] and width >= size[1], \
@@ -668,21 +685,25 @@ def center_crop_generator(
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: torch.Tensor = torch.tensor([[
- [start_x, start_y],
- [end_x, start_y],
- [end_x, end_y],
- [start_x, end_y],
- ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
+ points_src: torch.Tensor = torch.tensor(
+ [[
+ [start_x, start_y],
+ [end_x, start_y],
+ [end_x, end_y],
+ [start_x, end_y],
+ ]], device=device, dtype=torch.long
+ ).expand(batch_size, -1, -1)
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0],
- [dst_w - 1, 0],
- [dst_w - 1, dst_h - 1],
- [0, dst_h - 1],
- ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
+ points_dst: torch.Tensor = torch.tensor(
+ [[
+ [0, 0],
+ [dst_w - 1, 0],
+ [dst_w - 1, dst_h - 1],
+ [0, dst_h - 1],
+ ]], device=device, dtype=torch.long
+ ).expand(batch_size, -1, -1)
_input_size = torch.tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
@@ -734,23 +755,25 @@ def random_motion_blur_generator(
elif isinstance(kernel_size, tuple):
# kernel_size is fixed across the batch
assert len(kernel_size) == 2, f"`kernel_size` must be (2,) if it is a tuple. Got {kernel_size}."
- ksize_factor = _adapted_uniform(
- (batch_size,), kernel_size[0] // 2, kernel_size[1] // 2,
- same_on_batch=True).int() * 2 + 1
+ ksize_factor = _adapted_uniform((batch_size, ), kernel_size[0] // 2, kernel_size[1] // 2,
+ same_on_batch=True).int() * 2 + 1
else:
raise TypeError(f"Unsupported type: {type(kernel_size)}")
angle_factor = _adapted_uniform(
- (batch_size,), angle[0].to(device=device, dtype=dtype),
- angle[1].to(device=device, dtype=dtype), same_on_batch)
+ (batch_size, ), angle[0].to(device=device, dtype=dtype), angle[1].to(device=device, dtype=dtype), same_on_batch
+ )
direction_factor = _adapted_uniform(
- (batch_size,), direction[0].to(device=device, dtype=dtype),
- direction[1].to(device=device, dtype=dtype), same_on_batch)
+ (batch_size, ), direction[0].to(device=device, dtype=dtype), direction[1].to(device=device, dtype=dtype),
+ same_on_batch
+ )
- return dict(ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
- angle_factor=angle_factor.to(device=_device, dtype=_dtype),
- direction_factor=direction_factor.to(device=_device, dtype=_dtype))
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype)
+ )
def random_solarize_generator(
@@ -790,12 +813,14 @@ def random_solarize_generator(
_device, _dtype = _extract_device_dtype([thresholds, additions])
thresholds_factor = _adapted_uniform(
- (batch_size,), thresholds[0].to(device=device, dtype=dtype),
- thresholds[1].to(device=device, dtype=dtype), same_on_batch)
+ (batch_size, ), thresholds[0].to(device=device, dtype=dtype), thresholds[1].to(device=device, dtype=dtype),
+ same_on_batch
+ )
additions_factor = _adapted_uniform(
- (batch_size,), additions[0].to(device=device, dtype=dtype),
- additions[1].to(device=device, dtype=dtype), same_on_batch)
+ (batch_size, ), additions[0].to(device=device, dtype=dtype), additions[1].to(device=device, dtype=dtype),
+ same_on_batch
+ )
return dict(
thresholds_factor=thresholds_factor.to(device=_device, dtype=_dtype),
@@ -829,12 +854,10 @@ def random_posterize_generator(
_common_param_check(batch_size, same_on_batch)
_joint_range_check(bits, 'bits', (0, 8))
bits_factor = _adapted_uniform(
- (batch_size,), bits[0].to(device=device, dtype=dtype), bits[1].to(device=device, dtype=dtype),
- same_on_batch).int()
+ (batch_size, ), bits[0].to(device=device, dtype=dtype), bits[1].to(device=device, dtype=dtype), same_on_batch
+ ).int()
- return dict(
- bits_factor=bits_factor.to(device=bits.device, dtype=torch.int32)
- )
+ return dict(bits_factor=bits_factor.to(device=bits.device, dtype=torch.int32))
def random_sharpness_generator(
@@ -863,13 +886,13 @@ def random_sharpness_generator(
_common_param_check(batch_size, same_on_batch)
_joint_range_check(sharpness, 'sharpness', bounds=(0, float('inf')))
- sharpness_factor = _adapted_uniform((batch_size,), sharpness[0].to(device=device, dtype=dtype),
- sharpness[1].to(device=device, dtype=dtype), same_on_batch)
-
- return dict(
- sharpness_factor=sharpness_factor.to(device=sharpness.device, dtype=sharpness.dtype)
+ sharpness_factor = _adapted_uniform(
+ (batch_size, ), sharpness[0].to(device=device, dtype=dtype), sharpness[1].to(device=device, dtype=dtype),
+ same_on_batch
)
+ return dict(sharpness_factor=sharpness_factor.to(device=sharpness.device, dtype=sharpness.dtype))
+
def random_mixup_generator(
batch_size: int,
@@ -913,7 +936,8 @@ def random_mixup_generator(
)
mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=device, dtype=dtype).long()
mixup_lambdas: torch.Tensor = _adapted_uniform(
- (batch_size,), lambda_val[0], lambda_val[1], same_on_batch=same_on_batch)
+ (batch_size, ), lambda_val[0], lambda_val[1], same_on_batch=same_on_batch
+ )
mixup_lambdas = mixup_lambdas * batch_probs
return dict(
@@ -1010,9 +1034,10 @@ def random_cutmix_generator(
)
batch_probs: torch.Tensor = random_prob_generator(
- batch_size * num_mix, p, same_on_batch, device=device, dtype=dtype)
+ batch_size * num_mix, p, same_on_batch, device=device, dtype=dtype
+ )
mix_pairs: torch.Tensor = torch.rand(num_mix, batch_size, device=device, dtype=dtype).argsort(dim=1)
- cutmix_betas: torch.Tensor = _adapted_beta((batch_size * num_mix,), beta, beta, same_on_batch=same_on_batch)
+ cutmix_betas: torch.Tensor = _adapted_beta((batch_size * num_mix, ), beta, beta, same_on_batch=same_on_batch)
# Note: torch.clamp does not accept tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
# Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"
cutmix_betas = torch.min(torch.max(cutmix_betas, cut_size[0]), cut_size[1])
@@ -1020,10 +1045,10 @@ def random_cutmix_generator(
cut_height = (cutmix_rate * height).floor().to(device=device, dtype=_dtype)
cut_width = (cutmix_rate * width).floor().to(device=device, dtype=_dtype)
- _gen_shape = (1,)
+ _gen_shape = (1, )
if same_on_batch:
- _gen_shape = (cut_height.size(0),)
+ _gen_shape = (cut_height.size(0), )
cut_height = cut_height[0]
cut_width = cut_width[0]
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 52d9720e2..8f9b1ce90 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -39,13 +39,15 @@ def random_rotation_generator3d(
assert degrees.shape == torch.Size([3, 2]), f"'degrees' must be the shape of (3, 2). Got {degrees.shape}."
_device, _dtype = _extract_device_dtype([degrees])
degrees = degrees.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
+ yaw = _adapted_uniform((batch_size, ), degrees[0][0], degrees[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size, ), degrees[1][0], degrees[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size, ), degrees[2][0], degrees[2][1], same_on_batch)
- return dict(yaw=yaw.to(device=_device, dtype=_dtype),
- pitch=pitch.to(device=_device, dtype=_dtype),
- roll=roll.to(device=_device, dtype=_dtype))
+ return dict(
+ yaw=yaw.to(device=_device, dtype=_dtype),
+ pitch=pitch.to(device=_device, dtype=_dtype),
+ roll=roll.to(device=_device, dtype=_dtype)
+ )
def random_affine_generator3d(
@@ -101,20 +103,23 @@ def random_affine_generator3d(
_device, _dtype = _extract_device_dtype([degrees, translate, scale, shears])
assert degrees.shape == torch.Size([3, 2]), f"'degrees' must be the shape of (3, 2). Got {degrees.shape}."
degrees = degrees.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
+ yaw = _adapted_uniform((batch_size, ), degrees[0][0], degrees[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size, ), degrees[1][0], degrees[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size, ), degrees[2][0], degrees[2][1], same_on_batch)
angles = torch.stack([yaw, pitch, roll], dim=1)
# compute tensor ranges
if scale is not None:
assert scale.shape == torch.Size([3, 2]), f"'scale' must be the shape of (3, 2). Got {scale.shape}."
scale = scale.to(device=device, dtype=dtype)
- scale = torch.stack([
- _adapted_uniform((batch_size,), scale[0, 0], scale[0, 1], same_on_batch),
- _adapted_uniform((batch_size,), scale[1, 0], scale[1, 1], same_on_batch),
- _adapted_uniform((batch_size,), scale[2, 0], scale[2, 1], same_on_batch),
- ], dim=1)
+ scale = torch.stack(
+ [
+ _adapted_uniform((batch_size, ), scale[0, 0], scale[0, 1], same_on_batch),
+ _adapted_uniform((batch_size, ), scale[1, 0], scale[1, 1], same_on_batch),
+ _adapted_uniform((batch_size, ), scale[2, 0], scale[2, 1], same_on_batch),
+ ],
+ dim=1
+ )
else:
scale = torch.ones(batch_size, device=device, dtype=dtype).repeat(1, 3)
@@ -125,41 +130,45 @@ def random_affine_generator3d(
max_dy: torch.Tensor = translate[1] * height
max_dz: torch.Tensor = translate[2] * depth
# translations should be in x,y,z
- translations = torch.stack([
- _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
- _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
- _adapted_uniform((batch_size,), -max_dz, max_dz, same_on_batch)
- ], dim=1)
+ translations = torch.stack(
+ [
+ _adapted_uniform((batch_size, ), -max_dx, max_dx, same_on_batch),
+ _adapted_uniform((batch_size, ), -max_dy, max_dy, same_on_batch),
+ _adapted_uniform((batch_size, ), -max_dz, max_dz, same_on_batch)
+ ],
+ dim=1
+ )
else:
translations = torch.zeros((batch_size, 3), device=device, dtype=dtype)
# center should be in x,y,z
- center: torch.Tensor = torch.tensor(
- [width, height, depth], device=device, dtype=dtype).view(1, 3) / 2. - 0.5
+ center: torch.Tensor = torch.tensor([width, height, depth], device=device, dtype=dtype).view(1, 3) / 2. - 0.5
center = center.expand(batch_size, -1)
if shears is not None:
assert shears.shape == torch.Size([6, 2]), f"'shears' must be the shape of (6, 2). Got {shears.shape}."
shears = shears.to(device=device, dtype=dtype)
- sxy = _adapted_uniform((batch_size,), shears[0, 0], shears[0, 1], same_on_batch)
- sxz = _adapted_uniform((batch_size,), shears[1, 0], shears[1, 1], same_on_batch)
- syx = _adapted_uniform((batch_size,), shears[2, 0], shears[2, 1], same_on_batch)
- syz = _adapted_uniform((batch_size,), shears[3, 0], shears[3, 1], same_on_batch)
- szx = _adapted_uniform((batch_size,), shears[4, 0], shears[4, 1], same_on_batch)
- szy = _adapted_uniform((batch_size,), shears[5, 0], shears[5, 1], same_on_batch)
+ sxy = _adapted_uniform((batch_size, ), shears[0, 0], shears[0, 1], same_on_batch)
+ sxz = _adapted_uniform((batch_size, ), shears[1, 0], shears[1, 1], same_on_batch)
+ syx = _adapted_uniform((batch_size, ), shears[2, 0], shears[2, 1], same_on_batch)
+ syz = _adapted_uniform((batch_size, ), shears[3, 0], shears[3, 1], same_on_batch)
+ szx = _adapted_uniform((batch_size, ), shears[4, 0], shears[4, 1], same_on_batch)
+ szy = _adapted_uniform((batch_size, ), shears[5, 0], shears[5, 1], same_on_batch)
else:
sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=device, dtype=dtype)
- return dict(translations=translations.to(device=_device, dtype=_dtype),
- center=center.to(device=_device, dtype=_dtype),
- scale=scale.to(device=_device, dtype=_dtype),
- angles=angles.to(device=_device, dtype=_dtype),
- sxy=sxy.to(device=_device, dtype=_dtype),
- sxz=sxz.to(device=_device, dtype=_dtype),
- syx=syx.to(device=_device, dtype=_dtype),
- syz=syz.to(device=_device, dtype=_dtype),
- szx=szx.to(device=_device, dtype=_dtype),
- szy=szy.to(device=_device, dtype=_dtype))
+ return dict(
+ translations=translations.to(device=_device, dtype=_dtype),
+ center=center.to(device=_device, dtype=_dtype),
+ scale=scale.to(device=_device, dtype=_dtype),
+ angles=angles.to(device=_device, dtype=_dtype),
+ sxy=sxy.to(device=_device, dtype=_dtype),
+ sxz=sxz.to(device=_device, dtype=_dtype),
+ syx=syx.to(device=_device, dtype=_dtype),
+ syz=syz.to(device=_device, dtype=_dtype),
+ szx=szx.to(device=_device, dtype=_dtype),
+ szy=szy.to(device=_device, dtype=_dtype)
+ )
def random_motion_blur_generator3d(
@@ -204,25 +213,26 @@ def random_motion_blur_generator3d(
assert len(kernel_size) == 2 and kernel_size[0] >= 3 and kernel_size[0] <= kernel_size[1], \
f"`kernel_size` must be greater than 3. Got range {kernel_size}."
# kernel_size is fixed across the batch
- ksize_factor = _adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2,
+ ksize_factor = _adapted_uniform((batch_size, ), kernel_size[0] // 2, kernel_size[1] // 2,
same_on_batch=True).int() * 2 + 1
else:
raise TypeError(f"Unsupported type: {type(kernel_size)}")
assert angle.shape == torch.Size([3, 2]), f"'angle' must be the shape of (3, 2). Got {angle.shape}."
angle = angle.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), angle[0][0], angle[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), angle[1][0], angle[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), angle[2][0], angle[2][1], same_on_batch)
+ yaw = _adapted_uniform((batch_size, ), angle[0][0], angle[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size, ), angle[1][0], angle[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size, ), angle[2][0], angle[2][1], same_on_batch)
angle_factor = torch.stack([yaw, pitch, roll], dim=1)
direction = direction.to(device=device, dtype=dtype)
- direction_factor = _adapted_uniform(
- (batch_size,), direction[0], direction[1], same_on_batch)
+ direction_factor = _adapted_uniform((batch_size, ), direction[0], direction[1], same_on_batch)
- return dict(ksize_factor=ksize_factor.to(device=_device),
- angle_factor=angle_factor.to(device=_device, dtype=_dtype),
- direction_factor=direction_factor.to(device=_device, dtype=_dtype))
+ return dict(
+ ksize_factor=ksize_factor.to(device=_device),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype)
+ )
def center_crop_generator3d(
@@ -251,9 +261,11 @@ def center_crop_generator3d(
Note:
No random number will be generated.
"""
- if not isinstance(size, (tuple, list,)) and len(size) == 3:
- raise ValueError("Input size must be a tuple/list of length 3. Got {}"
- .format(size))
+ if not isinstance(size, (
+ tuple,
+ list,
+ )) and len(size) == 3:
+ raise ValueError("Input size must be a tuple/list of length 3. Got {}".format(size))
assert type(depth) == int and depth > 0 and \
type(height) == int and height > 0 and type(width) == int and width > 0, \
f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}."
@@ -287,32 +299,43 @@ def center_crop_generator3d(
# [x, y, z] origin
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
- points_src: torch.Tensor = torch.tensor([[
- [start_x, start_y, start_z],
- [end_x, start_y, start_z],
- [end_x, end_y, start_z],
- [start_x, end_y, start_z],
- [start_x, start_y, end_z],
- [end_x, start_y, end_z],
- [end_x, end_y, end_z],
- [start_x, end_y, end_z],
- ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
+ points_src: torch.Tensor = torch.tensor(
+ [
+ [
+ [start_x, start_y, start_z],
+ [end_x, start_y, start_z],
+ [end_x, end_y, start_z],
+ [start_x, end_y, start_z],
+ [start_x, start_y, end_z],
+ [end_x, start_y, end_z],
+ [end_x, end_y, end_z],
+ [start_x, end_y, end_z],
+ ]
+ ],
+ device=device,
+ dtype=torch.long
+ ).expand(batch_size, -1, -1)
# [x, y, z] destination
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0, 0],
- [dst_w - 1, 0, 0],
- [dst_w - 1, dst_h - 1, 0],
- [0, dst_h - 1, 0],
- [0, 0, dst_d - 1],
- [dst_w - 1, 0, dst_d - 1],
- [dst_w - 1, dst_h - 1, dst_d - 1],
- [0, dst_h - 1, dst_d - 1],
- ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
- return dict(src=points_src,
- dst=points_dst)
+ points_dst: torch.Tensor = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [dst_w - 1, 0, 0],
+ [dst_w - 1, dst_h - 1, 0],
+ [0, dst_h - 1, 0],
+ [0, 0, dst_d - 1],
+ [dst_w - 1, 0, dst_d - 1],
+ [dst_w - 1, dst_h - 1, dst_d - 1],
+ [0, dst_h - 1, dst_d - 1],
+ ]
+ ],
+ device=device,
+ dtype=torch.long
+ ).expand(batch_size, -1, -1)
+ return dict(src=points_src, dst=points_dst)
def random_crop_generator3d(
@@ -351,7 +374,8 @@ def random_crop_generator3d(
size = size.to(device=device, dtype=dtype)
assert size.shape == torch.Size([batch_size, 3]), (
"If `size` is a tensor, it must be shaped as (B, 3). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}.")
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
+ )
assert len(input_size) == 3 and isinstance(input_size[0], (int,)) and isinstance(input_size[1], (int,)) \
and isinstance(input_size[2], (int,)) and input_size[0] > 0 and input_size[1] > 0 and input_size[2] > 0, \
f"`input_size` must be a tuple of 3 positive integers. Got {input_size}."
@@ -361,8 +385,9 @@ def random_crop_generator3d(
z_diff = input_size[0] - size[:, 0] + 1
if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():
- raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."
- % (str(input_size), str(size)))
+ raise ValueError(
+ "input_size %s cannot be smaller than crop size %s in any dimension." % (str(input_size), str(size))
+ )
if batch_size == 0:
return dict(
@@ -372,47 +397,51 @@ def random_crop_generator3d(
if same_on_batch:
# If same_on_batch, select the first then repeat.
- x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch).floor()
- y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch).floor()
- z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch).floor()
+ x_start = _adapted_uniform((batch_size, ), 0, x_diff[0], same_on_batch).floor()
+ y_start = _adapted_uniform((batch_size, ), 0, y_diff[0], same_on_batch).floor()
+ z_start = _adapted_uniform((batch_size, ), 0, z_diff[0], same_on_batch).floor()
else:
- x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch).floor()
- y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch).floor()
- z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch).floor()
+ x_start = _adapted_uniform((1, ), 0, x_diff, same_on_batch).floor()
+ y_start = _adapted_uniform((1, ), 0, y_diff, same_on_batch).floor()
+ z_start = _adapted_uniform((1, ), 0, z_diff, same_on_batch).floor()
crop_src = bbox_generator3d(
x_start.to(device=_device, dtype=_dtype).view(-1),
y_start.to(device=_device, dtype=_dtype).view(-1),
- z_start.to(device=_device, dtype=_dtype).view(-1),
- size[:, 2].to(device=_device, dtype=_dtype) - 1,
- size[:, 1].to(device=_device, dtype=_dtype) - 1,
- size[:, 0].to(device=_device, dtype=_dtype) - 1)
+ z_start.to(device=_device, dtype=_dtype).view(-1), size[:, 2].to(device=_device, dtype=_dtype) - 1,
+ size[:, 1].to(device=_device, dtype=_dtype) - 1, size[:, 0].to(device=_device, dtype=_dtype) - 1
+ )
if resize_to is None:
crop_dst = bbox_generator3d(
torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- size[:, 2].to(device=_device, dtype=_dtype) - 1,
- size[:, 1].to(device=_device, dtype=_dtype) - 1,
- size[:, 0].to(device=_device, dtype=_dtype) - 1)
+ torch.tensor([0] * batch_size, device=_device,
+ dtype=_dtype), size[:, 2].to(device=_device, dtype=_dtype) - 1,
+ size[:, 1].to(device=_device, dtype=_dtype) - 1, size[:, 0].to(device=_device, dtype=_dtype) - 1
+ )
else:
assert len(resize_to) == 3 and isinstance(resize_to[0], (int,)) and isinstance(resize_to[1], (int,)) \
and isinstance(resize_to[2], (int,)) and resize_to[0] > 0 and resize_to[1] > 0 and resize_to[2] > 0, \
f"`resize_to` must be a tuple of 3 positive integers. Got {resize_to}."
- crop_dst = torch.tensor([[
- [0, 0, 0],
- [resize_to[-1] - 1, 0, 0],
- [resize_to[-1] - 1, resize_to[-2] - 1, 0],
- [0, resize_to[-2] - 1, 0],
- [0, 0, resize_to[-3] - 1],
- [resize_to[-1] - 1, 0, resize_to[-3] - 1],
- [resize_to[-1] - 1, resize_to[-2] - 1, resize_to[-3] - 1],
- [0, resize_to[-2] - 1, resize_to[-3] - 1],
- ]], device=_device, dtype=_dtype).repeat(batch_size, 1, 1)
-
- return dict(src=crop_src.to(device=_device),
- dst=crop_dst.to(device=_device))
+ crop_dst = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [resize_to[-1] - 1, 0, 0],
+ [resize_to[-1] - 1, resize_to[-2] - 1, 0],
+ [0, resize_to[-2] - 1, 0],
+ [0, 0, resize_to[-3] - 1],
+ [resize_to[-1] - 1, 0, resize_to[-3] - 1],
+ [resize_to[-1] - 1, resize_to[-2] - 1, resize_to[-3] - 1],
+ [0, resize_to[-2] - 1, resize_to[-3] - 1],
+ ]
+ ],
+ device=_device,
+ dtype=_dtype
+ ).repeat(batch_size, 1, 1)
+
+ return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
def random_perspective_generator3d(
@@ -450,16 +479,22 @@ def random_perspective_generator3d(
_device, _dtype = _extract_device_dtype([distortion_scale])
distortion_scale = distortion_scale.to(device=device, dtype=dtype)
- start_points: torch.Tensor = torch.tensor([[
- [0., 0, 0],
- [width - 1, 0, 0],
- [width - 1, height - 1, 0],
- [0, height - 1, 0],
- [0., 0, depth - 1],
- [width - 1, 0, depth - 1],
- [width - 1, height - 1, depth - 1],
- [0, height - 1, depth - 1],
- ]], device=device, dtype=dtype).expand(batch_size, -1, -1)
+ start_points: torch.Tensor = torch.tensor(
+ [
+ [
+ [0., 0, 0],
+ [width - 1, 0, 0],
+ [width - 1, height - 1, 0],
+ [0, height - 1, 0],
+ [0., 0, depth - 1],
+ [width - 1, 0, depth - 1],
+ [width - 1, height - 1, depth - 1],
+ [0, height - 1, depth - 1],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).expand(batch_size, -1, -1)
# generate random offset not larger than half of the image
fx = distortion_scale * width / 2
@@ -468,20 +503,28 @@ def random_perspective_generator3d(
factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3)
- rand_val: torch.Tensor = _adapted_uniform(start_points.shape, torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch)
-
- pts_norm = torch.tensor([[
- [1, 1, 1],
- [-1, 1, 1],
- [-1, -1, 1],
- [1, -1, 1],
- [1, 1, -1],
- [-1, 1, -1],
- [-1, -1, -1],
- [1, -1, -1],
- ]], device=device, dtype=dtype)
+ rand_val: torch.Tensor = _adapted_uniform(
+ start_points.shape, torch.tensor(0, device=device, dtype=dtype), torch.tensor(1, device=device, dtype=dtype),
+ same_on_batch
+ )
+
+ pts_norm = torch.tensor(
+ [[
+ [1, 1, 1],
+ [-1, 1, 1],
+ [-1, -1, 1],
+ [1, -1, 1],
+ [1, 1, -1],
+ [-1, 1, -1],
+ [-1, -1, -1],
+ [1, -1, -1],
+ ]],
+ device=device,
+ dtype=dtype
+ )
end_points = start_points + factor * rand_val * pts_norm
- return dict(start_points=start_points.to(device=_device, dtype=_dtype),
- end_points=end_points.to(device=_device, dtype=_dtype))
+ return dict(
+ start_points=start_points.to(device=_device, dtype=_dtype),
+ end_points=end_points.to(device=_device, dtype=_dtype)
+ )
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index 3c32bae97..c6cf1f88f 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -6,42 +6,14 @@ from kornia.augmentation.utils.param_validation import (
_tuple_range_reader,
)
from kornia.augmentation.utils.helpers import (
- _infer_batch_shape,
- _infer_batch_shape3d,
- _transform_input,
- _transform_input3d,
- _validate_input_dtype,
- _validate_shape,
- _validate_input_shape,
- _adapted_sampling,
- _adapted_rsampling,
- _adapted_uniform,
- _adapted_beta,
- _shape_validation,
- _validate_input,
- _validate_input3d,
- _transform_output_shape
+ _infer_batch_shape, _infer_batch_shape3d, _transform_input, _transform_input3d, _validate_input_dtype,
+ _validate_shape, _validate_input_shape, _adapted_sampling, _adapted_rsampling, _adapted_uniform, _adapted_beta,
+ _shape_validation, _validate_input, _validate_input3d, _transform_output_shape
)
__all__ = [
- "_infer_batch_shape",
- "_infer_batch_shape3d",
- "_transform_input",
- "_transform_input3d",
- "_validate_input_dtype",
- "_validate_shape",
- "_validate_input_shape",
- "_adapted_sampling",
- "_adapted_rsampling",
- "_adapted_uniform",
- "_adapted_beta",
- "_shape_validation",
- "_common_param_check",
- "_range_bound",
- "_joint_range_check",
- "_singular_range_check",
- "_tuple_range_reader",
- "_validate_input",
- "_validate_input3d",
- "_transform_output_shape"
+ "_infer_batch_shape", "_infer_batch_shape3d", "_transform_input", "_transform_input3d", "_validate_input_dtype",
+ "_validate_shape", "_validate_input_shape", "_adapted_sampling", "_adapted_rsampling", "_adapted_uniform",
+ "_adapted_beta", "_shape_validation", "_common_param_check", "_range_bound", "_joint_range_check",
+ "_singular_range_check", "_tuple_range_reader", "_validate_input", "_validate_input3d", "_transform_output_shape"
]
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index c81160770..22728c5e6 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -16,12 +16,13 @@ def _validate_input(f: Callable) -> Callable:
Returns:
the wrapped function after input is validated.
"""
+
@wraps(f)
def wrapper(input: torch.Tensor, *args, **kwargs):
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
- _validate_shape(input.shape, required_shapes=('BCHW',))
+ _validate_shape(input.shape, required_shapes=('BCHW', ))
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
return f(input, *args, **kwargs)
@@ -38,6 +39,7 @@ def _validate_input3d(f: Callable) -> Callable:
Returns:
the wrapped function after input is validated.
"""
+
@wraps(f)
def wrapper(input: torch.Tensor, *args, **kwargs):
if not torch.is_tensor(input):
@@ -84,8 +86,7 @@ def _transform_input(input: torch.Tensor) -> torch.Tensor:
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if len(input.shape) not in [2, 3, 4]:
- raise ValueError(
- f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")
+ raise ValueError(f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")
if len(input.shape) == 2:
input = input.unsqueeze(0)
@@ -109,7 +110,8 @@ def _transform_input3d(input: torch.Tensor) -> torch.Tensor:
if len(input.shape) not in [3, 4, 5]:
raise ValueError(
- f"Input size must have a shape of either (D, H, W), (C, D, H, W) or (*, C, D, H, W). Got {input.shape}")
+ f"Input size must have a shape of either (D, H, W), (C, D, H, W) or (*, C, D, H, W). Got {input.shape}"
+ )
if len(input.shape) == 3:
input = input.unsqueeze(0)
@@ -163,7 +165,7 @@ def _transform_output_shape(output: Union[torch.Tensor, Tuple[torch.Tensor, torc
return (out_tensor, trans_matrix) if is_tuple else out_tensor # type: ignore
-def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None:
+def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: Tuple[str, ...] = ("BCHW", )) -> None:
r"""Check if the dtype of the input tensor is in the range of accepted_dtypes
Args:
shape: tensor shape
@@ -193,9 +195,7 @@ def _validate_input_shape(input: torch.Tensor, channel_index: int, number: int)
def _adapted_rsampling(
- shape: Union[Tuple, torch.Size],
- dist: torch.distributions.Distribution,
- same_on_batch=False
+ shape: Union[Tuple, torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
) -> torch.Tensor:
r"""The uniform reparameterized sampling function that accepts 'same_on_batch'.
@@ -209,9 +209,7 @@ def _adapted_rsampling(
def _adapted_sampling(
- shape: Union[Tuple, torch.Size],
- dist: torch.distributions.Distribution,
- same_on_batch=False
+ shape: Union[Tuple, torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
) -> torch.Tensor:
r"""The uniform sampling function that accepts 'same_on_batch'.
@@ -239,10 +237,12 @@ def _adapted_uniform(
By default, sampling happens on the default device and dtype. If low/high is a tensor, sampling will happen
in the same device/dtype as low/high tensor.
"""
- device, dtype = _extract_device_dtype([
- low if isinstance(low, torch.Tensor) else None,
- high if isinstance(high, torch.Tensor) else None,
- ])
+ device, dtype = _extract_device_dtype(
+ [
+ low if isinstance(low, torch.Tensor) else None,
+ high if isinstance(high, torch.Tensor) else None,
+ ]
+ )
low = torch.as_tensor(low, device=device, dtype=dtype)
high = torch.as_tensor(high, device=device, dtype=dtype)
# validate_args=False to fix pytorch 1.7.1 error:
@@ -265,10 +265,12 @@ def _adapted_beta(
By default, sampling happens on the default device and dtype. If a/b is a tensor, sampling will happen
in the same device/dtype as a/b tensor.
"""
- device, dtype = _extract_device_dtype([
- a if isinstance(a, torch.Tensor) else None,
- b if isinstance(b, torch.Tensor) else None,
- ])
+ device, dtype = _extract_device_dtype(
+ [
+ a if isinstance(a, torch.Tensor) else None,
+ b if isinstance(b, torch.Tensor) else None,
+ ]
+ )
a = torch.as_tensor(a, device=device, dtype=dtype)
b = torch.as_tensor(b, device=device, dtype=dtype)
dist = Beta(a, b, validate_args=False)
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index ec12f9967..929e441c5 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -10,10 +10,15 @@ def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
assert type(same_on_batch) == bool, f"`same_on_batch` shall be boolean. Got {same_on_batch}."
-def _range_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[float]], name: str,
- center: float = 0., bounds: Tuple[float, float] = (0, float('inf')),
- check: Optional[str] = 'joint', device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.get_default_dtype()) -> torch.Tensor:
+def _range_bound(
+ factor: Union[torch.Tensor, float, Tuple[float, float], List[float]],
+ name: str,
+ center: float = 0.,
+ bounds: Tuple[float, float] = (0, float('inf')),
+ check: Optional[str] = 'joint',
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.get_default_dtype()
+) -> torch.Tensor:
r"""Check inputs and compute the corresponding factor bounds
"""
if not isinstance(factor, (torch.Tensor)):
@@ -55,11 +60,17 @@ def _joint_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[
else:
raise TypeError(
f"{name} should be a tensor with length 2 whose values between {bounds}. "
- f"Got {ranged_factor}.")
+ f"Got {ranged_factor}."
+ )
-def _singular_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[Tuple[float, float]] = None,
- skip_none: bool = False, mode: str = '2d') -> None:
+def _singular_range_check(
+ ranged_factor: torch.Tensor,
+ name: str,
+ bounds: Optional[Tuple[float, float]] = None,
+ skip_none: bool = False,
+ mode: str = '2d'
+) -> None:
"""check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1]"""
if mode == '2d':
dim_size = 2
@@ -79,7 +90,8 @@ def _singular_range_check(ranged_factor: torch.Tensor, name: str, bounds: Option
else:
raise TypeError(
f"{name} should be a float number or a tuple with length {dim_size} whose values between {bounds}."
- f"Got {ranged_factor}")
+ f"Got {ranged_factor}"
+ )
def _tuple_range_reader(
@@ -103,13 +115,12 @@ def _tuple_range_reader(
if isinstance(input_range, (float, int)):
if input_range < 0:
raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")
- input_range_tmp = torch.tensor(
- [-input_range, input_range], device=device, dtype=dtype).repeat(target_shape[0], 1)
+ input_range_tmp = torch.tensor([-input_range, input_range], device=device,
+ dtype=dtype).repeat(target_shape[0], 1)
elif isinstance(input_range, (tuple, list)) and len(input_range) == 2 \
and isinstance(input_range[0], (float, int)) and isinstance(input_range[1], (float, int)):
- input_range_tmp = torch.tensor(
- input_range, device=device, dtype=dtype).repeat(target_shape[0], 1)
+ input_range_tmp = torch.tensor(input_range, device=device, dtype=dtype).repeat(target_shape[0], 1)
elif isinstance(input_range, (tuple, list)) and len(input_range) == target_shape[0] \
and all([isinstance(x, (float, int)) for x in input_range]):
@@ -122,7 +133,8 @@ def _tuple_range_reader(
else:
raise TypeError(
"If not pass a tensor, it must be float, (float, float) for isotropic operation or a tuple of "
- f"{target_size} floats or {target_size} (float, float) for independent operation. Got {input_range}.")
+ f"{target_size} floats or {target_size} (float, float) for independent operation. Got {input_range}."
+ )
else:
# https://mypy.readthedocs.io/en/latest/casts.html cast to please mypy gods
@@ -131,7 +143,8 @@ def _tuple_range_reader(
if input_range < 0:
raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")
input_range_tmp = input_range.repeat(2) * torch.tensor(
- [-1., 1.], device=input_range.device, dtype=input_range.dtype)
+ [-1., 1.], device=input_range.device, dtype=input_range.dtype
+ )
input_range_tmp = input_range_tmp.repeat(target_shape[0], 1)
elif len(input_range.shape) == 1 and len(input_range) == 2:
@@ -139,7 +152,8 @@ def _tuple_range_reader(
elif len(input_range.shape) == 1 and len(input_range) == target_shape[0]:
input_range_tmp = input_range.unsqueeze(1).repeat(1, 2) * torch.tensor(
- [-1, 1], device=input_range.device, dtype=input_range.dtype)
+ [-1, 1], device=input_range.device, dtype=input_range.dtype
+ )
elif input_range.shape == target_shape:
input_range_tmp = input_range
@@ -147,7 +161,8 @@ def _tuple_range_reader(
else:
raise ValueError(
f"Degrees must be a {list(target_shape)} tensor for the degree range for independent operation."
- f"Got {input_range}")
+ f"Got {input_range}"
+ )
input_range_tmp = input_range
return input_range_tmp
diff --git a/kornia/color/__init__.py b/kornia/color/__init__.py
index f0816bef7..6b00c8d04 100644
--- a/kornia/color/__init__.py
+++ b/kornia/color/__init__.py
@@ -19,7 +19,6 @@ from .xyz import RgbToXyz, XyzToRgb, rgb_to_xyz, xyz_to_rgb
from .luv import RgbToLuv, LuvToRgb, rgb_to_luv, luv_to_rgb
from .lab import RgbToLab, LabToRgb, rgb_to_lab, lab_to_rgb
-
__all__ = [
"rgb_to_grayscale",
"bgr_to_grayscale",
@@ -53,9 +52,7 @@ __all__ = [
"YuvToRgb",
"RgbToXyz",
"XyzToRgb",
-
"RgbToLuv",
-
"LuvToRgb",
"LabToRgb",
"RgbToLab",
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index b9ebddfd3..011b12421 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -5,8 +5,9 @@ import warnings
from kornia.color.rgb import bgr_to_rgb
-def rgb_to_grayscale(image: torch.Tensor,
- rgb_weights: torch.Tensor = torch.tensor([0.299, 0.587, 0.114])) -> torch.Tensor:
+def rgb_to_grayscale(
+ image: torch.Tensor, rgb_weights: torch.Tensor = torch.tensor([0.299, 0.587, 0.114])
+) -> torch.Tensor:
r"""Convert a RGB image to grayscale version of image.
The image data is assumed to be in the range of (0, 1).
@@ -23,20 +24,16 @@ def rgb_to_grayscale(image: torch.Tensor,
>>> gray = rgb_to_grayscale(input) # 2x1x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
if not isinstance(rgb_weights, torch.Tensor):
- raise TypeError("rgb_weights is not a torch.Tensor. Got {}".format(
- type(rgb_weights)))
+ raise TypeError("rgb_weights is not a torch.Tensor. Got {}".format(type(rgb_weights)))
if rgb_weights.shape[-1] != 3:
- raise ValueError("rgb_weights must have a shape of (*, 3). Got {}"
- .format(rgb_weights.shape))
+ raise ValueError("rgb_weights must have a shape of (*, 3). Got {}".format(rgb_weights.shape))
r: torch.Tensor = image[..., 0:1, :, :]
g: torch.Tensor = image[..., 1:2, :, :]
@@ -64,12 +61,10 @@ def bgr_to_grayscale(image: torch.Tensor) -> torch.Tensor:
>>> gray = bgr_to_grayscale(input) # 2x1x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
image_rgb = bgr_to_rgb(image)
gray: torch.Tensor = rgb_to_grayscale(image_rgb)
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index 50f61524f..5423a04cf 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -23,12 +23,10 @@ def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_hls(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
r: torch.Tensor = image[..., 0, :, :]
g: torch.Tensor = image[..., 1, :, :]
@@ -43,8 +41,9 @@ def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
deltac: torch.Tensor = maxc - minc
- s: torch.Tensor = torch.where(l < 0.5, deltac / (maxc + minc), deltac /
- (torch.tensor(2.) - (maxc + minc))) # saturation
+ s: torch.Tensor = torch.where(
+ l < 0.5, deltac / (maxc + minc), deltac / (torch.tensor(2.) - (maxc + minc))
+ ) # saturation
hi: torch.Tensor = torch.zeros_like(deltac)
@@ -59,7 +58,8 @@ def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
# JIT indexing is not supported before 1.6.0 https://github.com/pytorch/pytorch/issues/38962
# image_hls[torch.isnan(image_hls)] = 0.
image_hls = torch.where(
- torch.isnan(image_hls), torch.tensor(0., device=image_hls.device, dtype=image_hls.dtype), image_hls)
+ torch.isnan(image_hls), torch.tensor(0., device=image_hls.device, dtype=image_hls.dtype), image_hls
+ )
return image_hls
@@ -80,12 +80,10 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = hls_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
h: torch.Tensor = image[..., 0, :, :] * 360 / (2 * math.pi)
l: torch.Tensor = image[..., 1, :, :]
@@ -98,12 +96,18 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:
ones_k = torch.ones_like(kr)
- fr: torch.Tensor = l - a * torch.max(torch.min(torch.min(kr - torch.tensor(3.),
- torch.tensor(9.) - kr), ones_k), -1 * ones_k)
- fg: torch.Tensor = l - a * torch.max(torch.min(torch.min(kg - torch.tensor(3.),
- torch.tensor(9.) - kg), ones_k), -1 * ones_k)
- fb: torch.Tensor = l - a * torch.max(torch.min(torch.min(kb - torch.tensor(3.),
- torch.tensor(9.) - kb), ones_k), -1 * ones_k)
+ fr: torch.Tensor = l - a * torch.max(
+ torch.min(torch.min(kr - torch.tensor(3.),
+ torch.tensor(9.) - kr), ones_k), -1 * ones_k
+ )
+ fg: torch.Tensor = l - a * torch.max(
+ torch.min(torch.min(kg - torch.tensor(3.),
+ torch.tensor(9.) - kg), ones_k), -1 * ones_k
+ )
+ fb: torch.Tensor = l - a * torch.max(
+ torch.min(torch.min(kb - torch.tensor(3.),
+ torch.tensor(9.) - kb), ones_k), -1 * ones_k
+ )
out: torch.Tensor = torch.stack([fr, fg, fb], dim=-3)
diff --git a/kornia/color/hsv.py b/kornia/color/hsv.py
index 1e2a821b5..2b168c8ff 100644
--- a/kornia/color/hsv.py
+++ b/kornia/color/hsv.py
@@ -22,12 +22,10 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
>>> output = rgb_to_hsv(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
# The first or last occurance is not guarenteed before 1.6.0
# https://github.com/pytorch/pytorch/issues/20414
@@ -42,8 +40,7 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
s: torch.Tensor = deltac / (v + eps)
# avoid division by zero
- deltac = torch.where(
- deltac == 0, torch.ones_like(deltac, device=deltac.device, dtype=deltac.dtype), deltac)
+ deltac = torch.where(deltac == 0, torch.ones_like(deltac, device=deltac.device, dtype=deltac.dtype), deltac)
maxc_tmp = maxc.unsqueeze(-3) - image
rc: torch.Tensor = maxc_tmp[..., 0, :, :]
@@ -83,12 +80,10 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = hsv_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
h: torch.Tensor = image[..., 0, :, :] / (2 * math.pi)
s: torch.Tensor = image[..., 1, :, :]
@@ -104,9 +99,24 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:
hi = hi.long()
indices: torch.Tensor = torch.stack([hi, hi + 6, hi + 12], dim=-3)
out = torch.stack((
- v, q, p, p, t, v,
- t, v, v, q, p, p,
- p, p, t, v, v, q,
+ v,
+ q,
+ p,
+ p,
+ t,
+ v,
+ t,
+ v,
+ v,
+ q,
+ p,
+ p,
+ p,
+ p,
+ t,
+ v,
+ v,
+ q,
), dim=-3)
out = torch.gather(out, -3, indices)
diff --git a/kornia/color/lab.py b/kornia/color/lab.py
index 1d4ab9ed6..e5d17c8a2 100644
--- a/kornia/color/lab.py
+++ b/kornia/color/lab.py
@@ -5,7 +5,6 @@ import torch.nn as nn
from .xyz import rgb_to_xyz, xyz_to_rgb
from .rgb import rgb_to_linear_rgb, linear_rgb_to_rgb
-
"""
The RGB to Lab color transformations were translated from scikit image's rgb2lab and lab2rgb
@@ -31,12 +30,10 @@ def rgb_to_lab(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_lab(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
# Convert from sRGB to Linear RGB
lin_rgb = rgb_to_linear_rgb(image)
@@ -44,8 +41,7 @@ def rgb_to_lab(image: torch.Tensor) -> torch.Tensor:
xyz_im: torch.Tensor = rgb_to_xyz(lin_rgb)
# normalize for D65 white point
- xyz_ref_white = torch.tensor(
- [0.95047, 1., 1.08883], device=xyz_im.device, dtype=xyz_im.dtype)[..., :, None, None]
+ xyz_ref_white = torch.tensor([0.95047, 1., 1.08883], device=xyz_im.device, dtype=xyz_im.dtype)[..., :, None, None]
xyz_normalized = torch.div(xyz_im, xyz_ref_white)
threshold = 0.008856
@@ -81,12 +77,10 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
>>> output = lab_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
L: torch.Tensor = image[..., 0, :, :]
a: torch.Tensor = image[..., 1, :, :]
@@ -107,14 +101,13 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
xyz = torch.where(fxyz > .2068966, power, scale)
# For D65 white point
- xyz_ref_white = torch.tensor(
- [0.95047, 1., 1.08883], device=xyz.device, dtype=xyz.dtype)[..., :, None, None]
+ xyz_ref_white = torch.tensor([0.95047, 1., 1.08883], device=xyz.device, dtype=xyz.dtype)[..., :, None, None]
xyz_im = xyz * xyz_ref_white
rgbs_im: torch.Tensor = xyz_to_rgb(xyz_im)
# https://github.com/richzhang/colorization-pytorch/blob/66a1cb2e5258f7c8f374f582acc8b1ef99c13c27/util/util.py#L107
-# rgbs_im = torch.where(rgbs_im < 0, torch.zeros_like(rgbs_im), rgbs_im)
+ # rgbs_im = torch.where(rgbs_im < 0, torch.zeros_like(rgbs_im), rgbs_im)
# Convert from RGB Linear to sRGB
rgb_im = linear_rgb_to_rgb(rgbs_im)
diff --git a/kornia/color/luv.py b/kornia/color/luv.py
index 0fe7fcc9a..2cbf98c20 100644
--- a/kornia/color/luv.py
+++ b/kornia/color/luv.py
@@ -5,7 +5,6 @@ import torch.nn as nn
from .xyz import rgb_to_xyz, xyz_to_rgb
from .rgb import rgb_to_linear_rgb, linear_rgb_to_rgb
-
"""
The RGB to Luv color transformations were translated from scikit image's rgb2luv and luv2rgb
@@ -32,12 +31,10 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
>>> output = rgb_to_luv(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
# Convert from sRGB to Linear RGB
lin_rgb = rgb_to_linear_rgb(image)
@@ -49,9 +46,7 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
z: torch.Tensor = xyz_im[..., 2, :, :]
threshold = 0.008856
- L: torch.Tensor = torch.where(y > threshold,
- 116. * torch.pow(y.clamp(min=threshold), 1. / 3.) - 16.,
- 903.3 * y)
+ L: torch.Tensor = torch.where(y > threshold, 116. * torch.pow(y.clamp(min=threshold), 1. / 3.) - 16., 903.3 * y)
# Compute reference white point
xyz_ref_white: Tuple[float, float, float] = (.95047, 1., 1.08883)
@@ -84,21 +79,17 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
>>> output = luv_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
L: torch.Tensor = image[..., 0, :, :]
u: torch.Tensor = image[..., 1, :, :]
v: torch.Tensor = image[..., 2, :, :]
# Convert from Luv to XYZ
- y: torch.Tensor = torch.where(L > 7.999625,
- torch.pow((L + 16) / 116, 3.0),
- L / 903.3)
+ y: torch.Tensor = torch.where(L > 7.999625, torch.pow((L + 16) / 116, 3.0), L / 903.3)
# Compute white point
xyz_ref_white: Tuple[float, float, float] = (0.95047, 1., 1.08883)
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index 4699cceb2..40d617f32 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -18,12 +18,10 @@ def rgb_to_bgr(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_bgr(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}".format(image.shape))
return bgr_to_rgb(image)
@@ -42,12 +40,10 @@ def bgr_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = bgr_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}".format(image.shape))
# flip image channels
out: torch.Tensor = image.flip(-3)
@@ -192,15 +188,12 @@ def rgb_to_linear_rgb(image: torch.Tensor) -> torch.Tensor:
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}".format(image.shape))
- lin_rgb: torch.Tensor = torch.where(image > 0.04045, torch.pow(
- ((image + 0.055) / 1.055), 2.4), image / 12.92)
+ lin_rgb: torch.Tensor = torch.where(image > 0.04045, torch.pow(((image + 0.055) / 1.055), 2.4), image / 12.92)
return lin_rgb
@@ -220,24 +213,15 @@ def linear_rgb_to_rgb(image: torch.Tensor) -> torch.Tensor:
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W).Got {}".format(image.shape))
threshold = 0.0031308
rgb: torch.Tensor = torch.where(
- image > threshold,
- 1.055 *
- torch.pow(
- image.clamp(min=threshold),
- 1 /
- 2.4) -
- 0.055,
- 12.92 *
- image)
+ image > threshold, 1.055 * torch.pow(image.clamp(min=threshold), 1 / 2.4) - 0.055, 12.92 * image
+ )
return rgb
diff --git a/kornia/color/xyz.py b/kornia/color/xyz.py
index ddd3f12b1..e62904a2c 100644
--- a/kornia/color/xyz.py
+++ b/kornia/color/xyz.py
@@ -16,12 +16,10 @@ def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_xyz(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
r: torch.Tensor = image[..., 0, :, :]
g: torch.Tensor = image[..., 1, :, :]
@@ -50,12 +48,10 @@ def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = xyz_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
x: torch.Tensor = image[..., 0, :, :]
y: torch.Tensor = image[..., 1, :, :]
diff --git a/kornia/color/ycbcr.py b/kornia/color/ycbcr.py
index 22591bbff..4f0a225d5 100644
--- a/kornia/color/ycbcr.py
+++ b/kornia/color/ycbcr.py
@@ -16,12 +16,10 @@ def rgb_to_ycbcr(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_ycbcr(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
r: torch.Tensor = image[..., 0, :, :]
g: torch.Tensor = image[..., 1, :, :]
@@ -50,12 +48,10 @@ def ycbcr_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = ycbcr_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
y: torch.Tensor = image[..., 0, :, :]
cb: torch.Tensor = image[..., 1, :, :]
diff --git a/kornia/color/yuv.py b/kornia/color/yuv.py
index 9451762b3..5bd67482d 100644
--- a/kornia/color/yuv.py
+++ b/kornia/color/yuv.py
@@ -18,12 +18,10 @@ def rgb_to_yuv(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_yuv(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
r: torch.Tensor = image[..., 0, :, :]
g: torch.Tensor = image[..., 1, :, :]
@@ -54,12 +52,10 @@ def yuv_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = yuv_to_rgb(input) # 2x3x4x5
"""
if not isinstance(image, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(image)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(image)))
if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}"
- .format(image.shape))
+ raise ValueError("Input size must have a shape of (*, 3, H, W). Got {}".format(image.shape))
y: torch.Tensor = image[..., 0, :, :]
u: torch.Tensor = image[..., 1, :, :]
diff --git a/kornia/constants.py b/kornia/constants.py
index ab9089530..6f1d78198 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -10,6 +10,7 @@ T = TypeVar('T', bound='ConstantBase')
class ConstantBase:
+
@classmethod
def get(cls, value: Union[str, int, T]) -> T: # type: ignore
if type(value) == str:
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index e91f16471..408b733fc 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -65,10 +65,11 @@ class ExtractTensorPatches(nn.Module):
"""
def __init__(
- self,
- window_size: Union[int, Tuple[int, int]],
- stride: Optional[Union[int, Tuple[int, int]]] = 1,
- padding: Optional[Union[int, Tuple[int, int]]] = 0) -> None:
+ self,
+ window_size: Union[int, Tuple[int, int]],
+ stride: Optional[Union[int, Tuple[int, int]]] = 1,
+ padding: Optional[Union[int, Tuple[int, int]]] = 0
+ ) -> None:
super(ExtractTensorPatches, self).__init__()
self.window_size: Tuple[int, int] = _pair(window_size)
self.stride: Tuple[int, int] = _pair(stride)
@@ -82,6 +83,7 @@ class ExtractTensorPatches(nn.Module):
# functional interface
######################
+
def _extract_tensor_patchesnd(
input: torch.Tensor, window_sizes: Tuple[int, ...], strides: Tuple[int, ...]
) -> torch.Tensor:
@@ -104,11 +106,9 @@ def extract_tensor_patches(
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
"""
if not torch.is_tensor(input):
- raise TypeError("Input input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
if padding:
pad_vert, pad_horz = _pair(padding)
diff --git a/kornia/contrib/max_blur_pool.py b/kornia/contrib/max_blur_pool.py
index 7f6080cee..7477d9a5a 100644
--- a/kornia/contrib/max_blur_pool.py
+++ b/kornia/contrib/max_blur_pool.py
@@ -20,9 +20,12 @@ class MaxBlurPool2d(MaxBlurPool2D):
def __init__(self, kernel_size: int, ceil_mode: bool = False) -> None:
super(MaxBlurPool2d, self).__init__(kernel_size, stride=2, max_pool_size=2, ceil_mode=ceil_mode)
- warnings.warn("`MaxBlurPool2d` is deprecated and will be removed after > 0.6. "
- "Please use `kornia.filters.MaxBlurPool2D instead.`",
- DeprecationWarning, stacklevel=2)
+ warnings.warn(
+ "`MaxBlurPool2d` is deprecated and will be removed after > 0.6. "
+ "Please use `kornia.filters.MaxBlurPool2D instead.`",
+ DeprecationWarning,
+ stacklevel=2
+ )
def max_blur_pool2d(input: torch.Tensor, kernel_size: int, ceil_mode: bool = False) -> torch.Tensor:
@@ -30,7 +33,10 @@ def max_blur_pool2d(input: torch.Tensor, kernel_size: int, ceil_mode: bool = Fal
See :class:`~kornia.contrib.MaxBlurPool2d` for details.
"""
- warnings.warn("`max_blur_pool2d` is deprecated and will be removed after > 0.6. "
- "Please use `kornia.filters.max_blur_pool2d instead.`",
- DeprecationWarning, stacklevel=2)
+ warnings.warn(
+ "`max_blur_pool2d` is deprecated and will be removed after > 0.6. "
+ "Please use `kornia.filters.max_blur_pool2d instead.`",
+ DeprecationWarning,
+ stacklevel=2
+ )
return _max_blur_pool2d(input, kernel_size, stride=2, max_pool_size=2, ceil_mode=ceil_mode)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 9c0ac5e25..b227a0494 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -10,7 +10,6 @@ from kornia.color.hsv import rgb_to_hsv, hsv_to_rgb
from kornia.utils.image import _to_bchw, _to_bcdhw
from kornia.utils.helpers import _torch_histc_cast
-
__all__ = [
"adjust_brightness",
"adjust_contrast",
@@ -41,9 +40,14 @@ def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, t
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,)):
- raise TypeError(f"The saturation_factor should be a float number or torch.Tensor."
- f"Got {type(saturation_factor)}")
+ if not isinstance(saturation_factor, (
+ float,
+ torch.Tensor,
+ )):
+ raise TypeError(
+ f"The saturation_factor should be a float number or torch.Tensor."
+ f"Got {type(saturation_factor)}"
+ )
if isinstance(saturation_factor, float):
saturation_factor = torch.as_tensor(saturation_factor)
@@ -124,8 +128,10 @@ def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor])
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
if not isinstance(hue_factor, (float, torch.Tensor)):
- raise TypeError(f"The hue_factor should be a float number or torch.Tensor in the range between"
- f" [-PI, PI]. Got {type(hue_factor)}")
+ raise TypeError(
+ f"The hue_factor should be a float number or torch.Tensor in the range between"
+ f" [-PI, PI]. Got {type(hue_factor)}"
+ )
if isinstance(hue_factor, float):
hue_factor = torch.as_tensor(hue_factor)
@@ -200,8 +206,9 @@ def adjust_hue(input: torch.Tensor, hue_factor: Union[float, torch.Tensor]) -> t
return out
-def adjust_gamma(input: torch.Tensor, gamma: Union[float, torch.Tensor],
- gain: Union[float, torch.Tensor] = 1.) -> torch.Tensor:
+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.
The input image is expected to be in the range of [0, 1].
@@ -267,8 +274,7 @@ def adjust_gamma(input: torch.Tensor, gamma: Union[float, torch.Tensor],
return out
-def adjust_contrast(input: torch.Tensor,
- contrast_factor: Union[float, torch.Tensor]) -> torch.Tensor:
+def adjust_contrast(input: torch.Tensor, contrast_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust Contrast of an image.
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
@@ -300,9 +306,11 @@ def adjust_contrast(input: torch.Tensor,
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,)):
- raise TypeError(f"The factor should be either a float or torch.Tensor. "
- f"Got {type(contrast_factor)}")
+ if not isinstance(contrast_factor, (
+ float,
+ torch.Tensor,
+ )):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. " f"Got {type(contrast_factor)}")
if isinstance(contrast_factor, float):
contrast_factor = torch.tensor([contrast_factor])
@@ -324,8 +332,7 @@ def adjust_contrast(input: torch.Tensor,
return out
-def adjust_brightness(input: torch.Tensor,
- brightness_factor: Union[float, torch.Tensor]) -> torch.Tensor:
+def adjust_brightness(input: torch.Tensor, brightness_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Adjust Brightness of an image.
This implementation aligns OpenCV, not PIL. Hence, the output differs from TorchVision.
@@ -356,9 +363,11 @@ def adjust_brightness(input: torch.Tensor,
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,)):
- raise TypeError(f"The factor should be either a float or torch.Tensor. "
- f"Got {type(brightness_factor)}")
+ if not isinstance(brightness_factor, (
+ float,
+ torch.Tensor,
+ )):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. " f"Got {type(brightness_factor)}")
if isinstance(brightness_factor, float):
brightness_factor = torch.tensor([brightness_factor])
@@ -393,9 +402,11 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
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,)):
- raise TypeError(f"The factor should be either a float or torch.Tensor. "
- f"Got {type(thresholds)}")
+ if not isinstance(thresholds, (
+ float,
+ torch.Tensor,
+ )):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. " f"Got {type(thresholds)}")
if isinstance(thresholds, torch.Tensor) and len(thresholds.shape) != 0:
assert input.size(0) == len(thresholds) and len(thresholds.shape) == 1, \
@@ -407,8 +418,11 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
return torch.where(input < thresholds, input, 1.0 - input)
-def solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5,
- additions: Optional[Union[float, torch.Tensor]] = None) -> torch.Tensor:
+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.
@@ -442,17 +456,21 @@ def solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5,
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,)):
- raise TypeError(f"The factor should be either a float or torch.Tensor. "
- f"Got {type(thresholds)}")
+ if not isinstance(thresholds, (
+ float,
+ torch.Tensor,
+ )):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. " f"Got {type(thresholds)}")
if isinstance(thresholds, float):
thresholds = torch.tensor(thresholds)
if additions is not None:
- if not isinstance(additions, (float, torch.Tensor,)):
- raise TypeError(f"The factor should be either a float or torch.Tensor. "
- f"Got {type(additions)}")
+ if not isinstance(additions, (
+ float,
+ torch.Tensor,
+ )):
+ raise TypeError(f"The factor should be either a float or torch.Tensor. " f"Got {type(additions)}")
if isinstance(additions, float):
additions = torch.tensor(additions)
@@ -500,7 +518,10 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
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,)):
+ 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):
@@ -517,10 +538,10 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
# Potential approach: implementing kornia.LUT with floating points
# https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/functional.py#L472
def _left_shift(input: torch.Tensor, shift: torch.Tensor):
- return ((input * 255).to(torch.uint8) * (2 ** shift)).to(input.dtype) / 255.
+ return ((input * 255).to(torch.uint8) * (2**shift)).to(input.dtype) / 255.
def _right_shift(input: torch.Tensor, shift: torch.Tensor):
- return (input * 255).to(torch.uint8) / (2 ** shift).to(input.dtype) / 255.
+ return (input * 255).to(torch.uint8) / (2**shift).to(input.dtype) / 255.
def _posterize_one(input: torch.Tensor, bits: torch.Tensor):
# Single bits value condition
@@ -585,13 +606,11 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
if len(factor.size()) != 0:
assert factor.shape == torch.Size([input.size(0)]), (
"Input batch size shall match with factor size if factor is not a 0-dim tensor. "
- f"Got {input.size(0)} and {factor.shape}")
+ f"Got {input.size(0)} and {factor.shape}"
+ )
- kernel = torch.tensor([
- [1, 1, 1],
- [1, 5, 1],
- [1, 1, 1]
- ], dtype=input.dtype, device=input.device).view(1, 1, 3, 3).repeat(input.size(1), 1, 1, 1) / 13
+ kernel = torch.tensor([[1, 1, 1], [1, 5, 1], [1, 1, 1]], dtype=input.dtype,
+ device=input.device).view(1, 1, 3, 3).repeat(input.size(1), 1, 1, 1) / 13
# This shall be equivalent to depthwise conv2d:
# Ref: https://discuss.pytorch.org/t/depthwise-and-separable-convolutions-in-pytorch/7315/2
@@ -660,13 +679,9 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
max_ = im.max()
if min_.item() < 0. and not torch.isclose(min_, torch.tensor(0., dtype=min_.dtype)):
- raise ValueError(
- f"Values in the input tensor must greater or equal to 0.0. Found {min_.item()}."
- )
+ raise ValueError(f"Values in the input tensor must greater or equal to 0.0. Found {min_.item()}.")
if max_.item() > 1. and not torch.isclose(max_, torch.tensor(1., dtype=max_.dtype)):
- raise ValueError(
- f"Values in the input tensor must lower or equal to 1.0. Found {max_.item()}."
- )
+ raise ValueError(f"Values in the input tensor must lower or equal to 1.0. Found {max_.item()}.")
ndims = len(im.shape)
if ndims not in (2, 3):
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 24edbc88e..56b4fffaf 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -1,16 +1,13 @@
import torch
import torch.nn as nn
-
__all__ = [
"add_weighted",
"AddWeighted",
]
-def add_weighted(src1: torch.Tensor, alpha: float,
- src2: torch.Tensor, beta: float,
- gamma: float) -> torch.Tensor:
+def add_weighted(src1: torch.Tensor, alpha: float, src2: torch.Tensor, beta: float, gamma: float) -> torch.Tensor:
r"""Calculates the weighted sum of two Tensors.
The function calculates the weighted sum of two Tensors as follows:
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index fbf175681..17e43cb91 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -10,12 +10,12 @@ from kornia.enhance.histogram import histogram
from kornia.utils.image import _to_bchw
from kornia.utils.helpers import _torch_histc_cast
-
__all__ = ["equalize_clahe"]
-def _compute_tiles(imgs: torch.Tensor, grid_size: Tuple[int, int], even_tile_size: bool = False
- ) -> Tuple[torch.Tensor, torch.Tensor]:
+def _compute_tiles(imgs: torch.Tensor,
+ grid_size: Tuple[int, int],
+ even_tile_size: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Compute tiles on an image according to a grid size.
Note that padding can be added to the image in order to crop properly the image.
@@ -51,10 +51,10 @@ def _compute_tiles(imgs: torch.Tensor, grid_size: Tuple[int, int], even_tile_siz
# compute tiles
c: int = batch.shape[-3]
- tiles: torch.Tensor = (batch.unfold(1, c, c) # unfold(dimension, size, step)
- .unfold(2, kernel_vert, kernel_vert)
- .unfold(3, kernel_horz, kernel_horz)
- .squeeze(1)).contiguous() # GH x GW x C x TH x TW
+ tiles: torch.Tensor = (
+ batch.unfold(1, c, c) # unfold(dimension, size, step)
+ .unfold(2, kernel_vert, kernel_vert).unfold(3, kernel_horz, kernel_horz).squeeze(1)
+ ).contiguous() # GH x GW x C x TH x TW
assert tiles.shape[-5] == grid_size[0] # check the grid size
assert tiles.shape[-4] == grid_size[1]
return tiles, batch
@@ -83,10 +83,11 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
interp_kernel_horz: int = tile_size[1] // 2
c: int = padded_imgs.shape[-3]
- interp_tiles: torch.Tensor = (padded_imgs.unfold(1, c, c)
- .unfold(2, interp_kernel_vert, interp_kernel_vert)
- .unfold(3, interp_kernel_horz, interp_kernel_horz)
- .squeeze(1)).contiguous() # 2GH x 2GW x C x TH/2 x TW/2
+ interp_tiles: torch.Tensor = (
+ padded_imgs.unfold(1, c, c).unfold(2, interp_kernel_vert,
+ interp_kernel_vert).unfold(3, interp_kernel_horz,
+ interp_kernel_horz).squeeze(1)
+ ).contiguous() # 2GH x 2GW x C x TH/2 x TW/2
assert interp_tiles.shape[-3] == c
assert interp_tiles.shape[-2] == tile_size[0] / 2
assert interp_tiles.shape[-1] == tile_size[1] / 2
@@ -191,8 +192,9 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
luts_x_interp_tiles[:, 0::gh - 1, 1:-1, 0] = luts[:, 0::max(gh // 2 - 1, 1), i_idxs[:, 0]]
luts_x_interp_tiles[:, 0::gh - 1, 1:-1, 1] = luts[:, 0::max(gh // 2 - 1, 1), i_idxs[:, 1]]
# internal region
- luts_x_interp_tiles[:, 1:-1, 1:-1, :] = luts[
- :, j_idxs.repeat(max(gh - 2, 1), 1, 1).permute(1, 0, 2), i_idxs.repeat(max(gw - 2, 1), 1, 1)]
+ luts_x_interp_tiles[:, 1:-1, 1:-1, :] = luts[:,
+ j_idxs.repeat(max(gh - 2, 1), 1, 1).permute(1, 0, 2),
+ i_idxs.repeat(max(gw - 2, 1), 1, 1)]
return luts_x_interp_tiles
@@ -222,17 +224,18 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
flatten_interp_tiles: torch.Tensor = (interp_tiles * 255).long().flatten(-2, -1) # B x GH x GW x 4 x C x (THxTW)
flatten_interp_tiles = flatten_interp_tiles.unsqueeze(-3).expand(num_imgs, gh, gw, 4, c, th * tw)
preinterp_tiles_equalized = torch.gather( # B x GH x GW x 4 x C x TH x TW
- mapped_luts, 5, flatten_interp_tiles).to(interp_tiles).reshape(num_imgs, gh, gw, 4, c, th, tw)
+ mapped_luts, 5, flatten_interp_tiles
+ ).to(interp_tiles).reshape(num_imgs, gh, gw, 4, c, th, tw)
# interp tiles
tiles_equalized: torch.Tensor = torch.zeros_like(interp_tiles)
# compute the interpolation weights (shapes are 2 x TH x TW because they must be applied to 2 interp tiles)
- ih = torch.arange(2 * th - 1, -1, -1, dtype=interp_tiles.dtype, device=interp_tiles.device).div(
- 2. * th - 1)[None].transpose(-2, -1).expand(2 * th, tw)
+ ih = torch.arange(2 * th - 1, -1, -1, dtype=interp_tiles.dtype,
+ device=interp_tiles.device).div(2. * th - 1)[None].transpose(-2, -1).expand(2 * th, tw)
ih = ih.unfold(0, th, th).unfold(1, tw, tw) # 2 x 1 x TH x TW
- iw = torch.arange(2 * tw - 1, -1, -1, dtype=interp_tiles.dtype, device=interp_tiles.device).div(
- 2. * tw - 1).expand(th, 2 * tw)
+ iw = torch.arange(2 * tw - 1, -1, -1, dtype=interp_tiles.dtype,
+ device=interp_tiles.device).div(2. * tw - 1).expand(th, 2 * tw)
iw = iw.unfold(0, th, th).unfold(1, tw, tw) # 1 x 2 x TH x TW
# compute row and column interpolation weigths
@@ -322,12 +325,13 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40., grid_size: Tupl
hist_tiles, img_padded = _compute_tiles(imgs, grid_size, True)
tile_size: Tuple[int, int] = (hist_tiles.shape[-2], hist_tiles.shape[-1])
interp_tiles: torch.Tensor = (
- _compute_interpolation_tiles(img_padded, tile_size)) # B x 2GH x 2GW x C x TH/2 x TW/2
+ _compute_interpolation_tiles(img_padded, tile_size)
+ ) # B x 2GH x 2GW x C x TH/2 x TW/2
luts: torch.Tensor = _compute_luts(hist_tiles, clip=clip_limit) # B x GH x GW x C x B
equalized_tiles: torch.Tensor = _compute_equalized_tiles(interp_tiles, luts) # B x 2GH x 2GW x C x TH/2 x TW/2
# reconstruct the images form the tiles
-# try permute + contiguous + view
+ # try permute + contiguous + view
eq_imgs: torch.Tensor = equalized_tiles.permute(0, 3, 1, 4, 2, 5).reshape_as(img_padded)
h, w = imgs.shape[-2:]
eq_imgs = eq_imgs[..., :h, :w] # crop imgs if they were padded
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 968120df2..015665258 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -2,14 +2,15 @@ from typing import Tuple
import torch
-
__all__ = [
"histogram",
"histogram2d",
]
-def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor,
+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.
@@ -28,28 +29,22 @@ def marginal_pdf(values: torch.Tensor, bins: torch.Tensor, sigma: torch.Tensor,
"""
if not isinstance(values, torch.Tensor):
- raise TypeError("Input values type is not a torch.Tensor. Got {}"
- .format(type(values)))
+ raise TypeError("Input values type is not a torch.Tensor. Got {}".format(type(values)))
if not isinstance(bins, torch.Tensor):
- raise TypeError("Input bins type is not a torch.Tensor. Got {}"
- .format(type(bins)))
+ raise TypeError("Input bins type is not a torch.Tensor. Got {}".format(type(bins)))
if not isinstance(sigma, torch.Tensor):
- raise TypeError("Input sigma type is not a torch.Tensor. Got {}"
- .format(type(sigma)))
+ 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))
+ 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))
+ 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))
+ raise ValueError("Input sigma must be a of the shape 1" " Got {}".format(sigma.shape))
residuals = values - bins.unsqueeze(0).unsqueeze(0)
kernel_values = torch.exp(-0.5 * (residuals / sigma).pow(2))
@@ -61,8 +56,7 @@ 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:
+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.
@@ -77,24 +71,22 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor,
"""
if not isinstance(kernel_values1, torch.Tensor):
- raise TypeError("Input kernel_values1 type is not a torch.Tensor. Got {}"
- .format(type(kernel_values1)))
+ raise TypeError("Input kernel_values1 type is not a torch.Tensor. Got {}".format(type(kernel_values1)))
if not isinstance(kernel_values2, torch.Tensor):
- raise TypeError("Input kernel_values2 type is not a torch.Tensor. Got {}"
- .format(type(kernel_values2)))
+ 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))
+ 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))
+ 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))
+ raise ValueError(
+ "Inputs kernel_values1 and kernel_values2 must have the same shape."
+ " Got {} and {}".format(kernel_values1.shape, kernel_values2.shape)
+ )
joint_kernel_values = torch.matmul(kernel_values1.transpose(1, 2), kernel_values2)
normalization = torch.sum(joint_kernel_values, dim=(1, 2)).view(-1, 1, 1) + epsilon
@@ -103,8 +95,7 @@ def joint_pdf(kernel_values1: torch.Tensor, kernel_values2: torch.Tensor,
return pdf
-def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor,
- epsilon: float = 1e-10) -> torch.Tensor:
+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.
@@ -132,11 +123,12 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor,
def histogram2d(
- x1: torch.Tensor,
- x2: torch.Tensor,
- bins: torch.Tensor,
- bandwidth: torch.Tensor,
- epsilon: float = 1e-10) -> torch.Tensor:
+ x1: torch.Tensor,
+ x2: torch.Tensor,
+ bins: torch.Tensor,
+ bandwidth: torch.Tensor,
+ epsilon: float = 1e-10
+) -> torch.Tensor:
"""Function that estimates the 2d histogram of the input tensor.
The calculation uses kernel density estimation which requires a bandwidth (smoothing) parameter.
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 96045492d..19a75efec 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -5,7 +5,6 @@ from typing import Union
import torch
import torch.nn as nn
-
__all__ = [
"normalize",
"normalize_min_max",
@@ -60,9 +59,7 @@ class Normalize(nn.Module):
return self.__class__.__name__ + repr
-def normalize(
- data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]
-) -> torch.Tensor:
+def normalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:
r"""Normalize a tensor image with mean and standard deviation.
.. math::
@@ -176,9 +173,7 @@ class Denormalize(nn.Module):
return self.__class__.__name__ + repr
-def denormalize(
- data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]
-) -> torch.Tensor:
+def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> torch.Tensor:
r"""Denormalize a tensor image with mean and standard deviation.
.. math::
@@ -292,7 +287,5 @@ def normalize_min_max(x: torch.Tensor, min_val: float = 0., max_val: float = 1.,
x_min: torch.Tensor = x.view(B, C, -1).min(-1)[0].view(B, C, 1)
x_max: torch.Tensor = x.view(B, C, -1).max(-1)[0].view(B, C, 1)
- x_out: torch.Tensor = (
- (max_val - min_val) * (x.view(B, C, -1) - x_min) / (x_max - x_min + eps) + min_val
- )
+ x_out: torch.Tensor = ((max_val - min_val) * (x.view(B, C, -1) - x_min) / (x_max - x_min + eps) + min_val)
return x_out.view(shape)
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index c2cb1e969..7e345dbbd 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -6,7 +6,6 @@ import torch.nn as nn
from kornia.utils.helpers import _torch_svd_cast
-
__all__ = [
"zca_mean",
"zca_whiten",
@@ -68,9 +67,14 @@ class ZCAWhitening(nn.Module):
[1] `Stanford PCA & ZCA whitening tutorial <http://ufldl.stanford.edu/tutorial/unsupervised/PCAWhitening/>`_
"""
- def __init__(self, dim: int = 0, eps: float = 1e-6,
- unbiased: bool = True, detach_transforms: bool = True,
- compute_inv: bool = False) -> None:
+ def __init__(
+ self,
+ dim: int = 0,
+ eps: float = 1e-6,
+ unbiased: bool = True,
+ detach_transforms: bool = True,
+ compute_inv: bool = False
+ ) -> None:
super(ZCAWhitening, self).__init__()
@@ -100,7 +104,9 @@ class ZCAWhitening(nn.Module):
self.mean_vector: torch.Tensor = mean
self.transform_matrix: torch.Tensor = T
if T_inv is None:
- self.transform_inv: Optional[torch.Tensor] = torch.empty([0, ])
+ self.transform_inv: Optional[torch.Tensor] = torch.empty([
+ 0,
+ ])
else:
self.transform_inv = T_inv
@@ -164,8 +170,10 @@ class ZCAWhitening(nn.Module):
return y
-def zca_mean(inp: torch.Tensor, dim: int = 0,
- unbiased: bool = True, eps: float = 1e-6,
+def zca_mean(inp: torch.Tensor,
+ dim: int = 0,
+ unbiased: bool = True,
+ eps: float = 1e-6,
return_inverse: bool = False) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
r"""
@@ -203,8 +211,7 @@ def zca_mean(inp: torch.Tensor, dim: int = 0,
"""
if not isinstance(inp, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(inp)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(inp)))
if not isinstance(eps, float):
raise TypeError(f"eps type is not a float. Got{type(eps)}")
@@ -221,8 +228,12 @@ def zca_mean(inp: torch.Tensor, dim: int = 0,
inp_size = inp.size()
if dim >= len(inp_size) or dim < -len(inp_size):
- raise IndexError("Dimension out of range (expected to be in range of [{},{}], but got {}"
- .format(-len(inp_size), len(inp_size) - 1, dim))
+ raise IndexError(
+ "Dimension out of range (expected to be in range of [{},{}], but got {}".format(
+ -len(inp_size),
+ len(inp_size) - 1, dim
+ )
+ )
if dim < 0:
dim = len(inp_size) + dim
@@ -263,8 +274,7 @@ def zca_mean(inp: torch.Tensor, dim: int = 0,
return T, mean, T_inv
-def zca_whiten(inp: torch.Tensor, dim: int = 0,
- unbiased: bool = True, eps: float = 1e-6) -> torch.Tensor:
+def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> torch.Tensor:
r"""
Applies ZCA whitening transform.
@@ -290,8 +300,7 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0,
"""
if not isinstance(inp, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(inp)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(inp)))
if not isinstance(eps, float):
raise TypeError(f"eps type is not a float. Got{type(eps)}")
@@ -309,8 +318,9 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0,
return inp_whiten
-def linear_transform(inp: torch.Tensor, transform_matrix: torch.Tensor,
- mean_vector: torch.Tensor, dim: int = 0) -> torch.Tensor:
+def linear_transform(
+ inp: torch.Tensor, transform_matrix: torch.Tensor, mean_vector: torch.Tensor, dim: int = 0
+) -> torch.Tensor:
r"""
Given a transformation matrix and a mean vector, this function will flatten
@@ -356,8 +366,12 @@ def linear_transform(inp: torch.Tensor, transform_matrix: torch.Tensor,
inp_size = inp.size()
if dim >= len(inp_size) or dim < -len(inp_size):
- raise IndexError("Dimension out of range (expected to be in range of [{},{}], but got {}"
- .format(-len(inp_size), len(inp_size) - 1, dim))
+ raise IndexError(
+ "Dimension out of range (expected to be in range of [{},{}], but got {}".format(
+ -len(inp_size),
+ len(inp_size) - 1, dim
+ )
+ )
if dim < 0:
dim = len(inp_size) + dim
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 1c62526dd..1d73721d3 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -1,37 +1,18 @@
-from .responses import (CornerHarris,
- CornerGFTT,
- BlobHessian,
- BlobDoG,
- harris_response,
- gftt_response,
- hessian_response,
- dog_response)
-from .nms import (NonMaximaSuppression2d,
- nms2d,
- NonMaximaSuppression3d,
- nms3d)
+from .responses import (
+ CornerHarris, CornerGFTT, BlobHessian, BlobDoG, harris_response, gftt_response, hessian_response, dog_response
+)
+from .nms import (NonMaximaSuppression2d, nms2d, NonMaximaSuppression3d, nms3d)
# Backward compatibility
from .nms import nms2d as non_maxima_suppression2d
from .nms import nms3d as non_maxima_suppression3d
-from .laf import (extract_patches_from_pyramid,
- extract_patches_simple,
- normalize_laf,
- denormalize_laf,
- laf_to_boundary_points,
- ellipse_to_laf,
- make_upright,
- scale_laf,
- get_laf_scale,
- get_laf_center,
- get_laf_orientation,
- set_laf_orientation,
- raise_error_if_laf_is_not_valid,
- laf_from_center_scale_ori,
- laf_is_inside_image,
- laf_to_three_points,
- laf_from_three_points)
+from .laf import (
+ extract_patches_from_pyramid, extract_patches_simple, normalize_laf, denormalize_laf, laf_to_boundary_points,
+ ellipse_to_laf, make_upright, scale_laf, get_laf_scale, get_laf_center, get_laf_orientation, set_laf_orientation,
+ raise_error_if_laf_is_not_valid, laf_from_center_scale_ori, laf_is_inside_image, laf_to_three_points,
+ laf_from_three_points
+)
from .siftdesc import SIFTDescriptor
from .mkd import MKDDescriptor
from .hardnet import HardNet, HardNet8
@@ -42,7 +23,6 @@ from .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator, LA
from .orientation import LAFOrienter, PatchDominantGradientOrientation, OriNet
from .matching import match_nn, match_mnn, match_snn, match_smnn
-
__all__ = [
"nms2d",
"nms3d",
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 14778b9d1..3217ab483 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -5,10 +5,7 @@ import torch.nn as nn
import math
from kornia.filters import get_gaussian_kernel2d
from kornia.filters import SpatialGradient
-from kornia.feature.laf import (ellipse_to_laf,
- get_laf_scale,
- raise_error_if_laf_is_not_valid,
- scale_laf, make_upright)
+from kornia.feature.laf import (ellipse_to_laf, get_laf_scale, raise_error_if_laf_is_not_valid, scale_laf, make_upright)
from kornia.feature import extract_patches_from_pyramid
urls: Dict[str, str] = dict()
@@ -43,25 +40,28 @@ class PatchAffineShapeEstimator(nn.Module):
Returns:
torch.Tensor: ellipse_shape shape [Bx1x3] """
if not isinstance(patch, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(patch)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))
if not len(patch.shape) == 4:
- raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
- .format(patch.shape))
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(patch.shape))
B, CH, W, H = patch.size()
if (W != self.patch_size) or (H != self.patch_size) or (CH != 1):
raise TypeError(
"input shape should be must be [Bx1x{}x{}]. "
- "Got {}".format(self.patch_size, self.patch_size, patch.size()))
+ "Got {}".format(self.patch_size, self.patch_size, patch.size())
+ )
self.weighting = self.weighting.to(patch.dtype).to(patch.device)
grads: torch.Tensor = self.gradient(patch) * self.weighting
# unpack the edges
gx: torch.Tensor = grads[:, :, 0]
gy: torch.Tensor = grads[:, :, 1]
# abc == 1st axis, mixture, 2nd axis. Ellipse_shape is a 2nd moment matrix.
- ellipse_shape = torch.cat([gx.pow(2).mean(dim=2).mean(dim=2, keepdim=True),
- (gx * gy).mean(dim=2).mean(dim=2, keepdim=True),
- gy.pow(2).mean(dim=2).mean(dim=2, keepdim=True)], dim=2)
+ ellipse_shape = torch.cat(
+ [
+ gx.pow(2).mean(dim=2).mean(dim=2, keepdim=True), (gx * gy).mean(dim=2).mean(dim=2, keepdim=True),
+ gy.pow(2).mean(dim=2).mean(dim=2, keepdim=True)
+ ],
+ dim=2
+ )
# Now lets detect degenerate cases: when 2 or 3 elements are close to zero (e.g. if patch is completely black
bad_mask = ((ellipse_shape < self.eps).float().sum(dim=2, keepdim=True) >= 2).to(ellipse_shape.dtype)
@@ -84,9 +84,7 @@ class LAFAffineShapeEstimator(nn.Module):
patch_size: int, default = 32
affine_shape_detector: nn.Module. Patch affine shape estimator, e.g. PatchAffineShapeEstimator. Default: None """ # noqa pylint: disable
- def __init__(self,
- patch_size: int = 32,
- affine_shape_detector: Optional[nn.Module] = None) -> None:
+ def __init__(self, patch_size: int = 32, affine_shape_detector: Optional[nn.Module] = None) -> None:
super(LAFAffineShapeEstimator, self).__init__()
self.patch_size = patch_size
self.affine_shape_detector = PatchAffineShapeEstimator(self.patch_size)
@@ -108,18 +106,16 @@ class LAFAffineShapeEstimator(nn.Module):
raise_error_if_laf_is_not_valid(laf)
img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
if not isinstance(img, torch.Tensor):
- raise TypeError("img type is not a torch.Tensor. Got {}"
- .format(type(img)))
+ raise TypeError("img type is not a torch.Tensor. Got {}".format(type(img)))
if len(img.shape) != 4:
raise ValueError(img_message)
if laf.size(0) != img.size(0):
- raise ValueError("Batch size of laf and img should be the same. Got {}, {}"
- .format(img.size(0), laf.size(0)))
+ raise ValueError(
+ "Batch size of laf and img should be the same. Got {}, {}".format(img.size(0), laf.size(0))
+ )
B, N = laf.shape[:2]
PS: int = self.patch_size
- patches: torch.Tensor = extract_patches_from_pyramid(img,
- make_upright(laf),
- PS, True).view(-1, 1, PS, PS)
+ patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(laf), PS, True).view(-1, 1, PS, PS)
ellipse_shape: torch.Tensor = self.affine_shape_detector(patches)
ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), ellipse_shape], dim=2).view(B, N, 5)
scale_orig = get_laf_scale(laf)
@@ -145,27 +141,15 @@ class LAFAffNetShapeEstimator(nn.Module):
def __init__(self, pretrained: bool = False):
super(LAFAffNetShapeEstimator, self).__init__()
self.features = nn.Sequential(
- nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),
- nn.BatchNorm2d(16, affine=False),
- nn.ReLU(),
- nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False),
- nn.BatchNorm2d(16, affine=False),
- nn.ReLU(),
- nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False),
- nn.BatchNorm2d(32, affine=False),
- nn.ReLU(),
- nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False),
- nn.BatchNorm2d(32, affine=False),
- nn.ReLU(),
- nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
- nn.BatchNorm2d(64, affine=False),
- nn.ReLU(),
- nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
- nn.BatchNorm2d(64, affine=False),
- nn.ReLU(),
- nn.Dropout(0.25),
- nn.Conv2d(64, 3, kernel_size=8, stride=1, padding=0, bias=True),
- nn.Tanh(),
+ nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(16, affine=False), nn.ReLU(),
+ nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(16, affine=False),
+ nn.ReLU(), nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(32, affine=False), nn.ReLU(),
+ nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(32, affine=False),
+ nn.ReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(64, affine=False), nn.ReLU(),
+ nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(64, affine=False),
+ nn.ReLU(), nn.Dropout(0.25), nn.Conv2d(64, 3, kernel_size=8, stride=1, padding=0, bias=True), nn.Tanh(),
nn.AdaptiveAvgPool2d(1)
)
self.patch_size = 32
@@ -179,7 +163,7 @@ class LAFAffNetShapeEstimator(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- "Utility function that normalizes the input by batch."""
+ "Utility function that normalizes the input by batch." ""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
@@ -197,18 +181,16 @@ class LAFAffNetShapeEstimator(nn.Module):
raise_error_if_laf_is_not_valid(laf)
img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
if not torch.is_tensor(img):
- raise TypeError("img type is not a torch.Tensor. Got {}"
- .format(type(img)))
+ raise TypeError("img type is not a torch.Tensor. Got {}".format(type(img)))
if len(img.shape) != 4:
raise ValueError(img_message)
if laf.size(0) != img.size(0):
- raise ValueError("Batch size of laf and img should be the same. Got {}, {}"
- .format(img.size(0), laf.size(0)))
+ raise ValueError(
+ "Batch size of laf and img should be the same. Got {}, {}".format(img.size(0), laf.size(0))
+ )
B, N = laf.shape[:2]
PS: int = self.patch_size
- patches: torch.Tensor = extract_patches_from_pyramid(img,
- make_upright(laf),
- PS, True).view(-1, 1, PS, PS)
+ patches: torch.Tensor = extract_patches_from_pyramid(img, make_upright(laf), PS, True).view(-1, 1, PS, PS)
xy = self.features(self._normalize_input(patches)).view(-1, 3)
a1 = torch.cat([1.0 + xy[:, 0].reshape(-1, 1, 1), 0 * xy[:, 0].reshape(-1, 1, 1)], dim=2)
a2 = torch.cat([xy[:, 1].reshape(-1, 1, 1), 1.0 + xy[:, 2].reshape(-1, 1, 1)], dim=2)
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 5f1bf2f68..cae8834f4 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -6,7 +6,9 @@ import torch.nn.functional as F
urls: Dict[str, str] = dict()
urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"
-urls["liberty_aug"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" # noqa pylint: disable
+urls[
+ "liberty_aug"
+] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" # noqa pylint: disable
urls["hardnet8v2"] = "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt" # noqa pylint: disable
@@ -68,7 +70,7 @@ class HardNet(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- "Utility function that normalizes the input by batch."""
+ "Utility function that normalizes the input by batch." ""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
@@ -155,7 +157,7 @@ class HardNet8(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
- "Utility function that normalizes the input by batch."""
+ "Utility function that normalizes the input by batch." ""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 53c44a3a2..26d96d386 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -15,8 +15,7 @@ def raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:
"""
laf_message: str = "Invalid laf shape, we expect BxNx2x3. Got: {}".format(laf.shape)
if not isinstance(laf, torch.Tensor):
- raise TypeError("Laf type is not a torch.Tensor. Got {}"
- .format(type(laf)))
+ raise TypeError("Laf type is not a torch.Tensor. Got {}".format(type(laf)))
if len(laf.shape) != 4:
raise ValueError(laf_message)
if laf.size(2) != 2 or laf.size(3) != 3:
@@ -91,8 +90,7 @@ def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:
return kornia.rad2deg(angle_rad).unsqueeze(-1)
-def set_laf_orientation(LAF: torch.Tensor,
- angles_degrees: torch.Tensor) -> torch.Tensor:
+def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
"""Changes the orientation of the LAFs.
Args:
@@ -110,8 +108,10 @@ def set_laf_orientation(LAF: torch.Tensor,
raise_error_if_laf_is_not_valid(LAF)
B, N = LAF.shape[:2]
rotmat: torch.Tensor = angle_to_rotation_matrix(angles_degrees).view(B * N, 2, 2)
- laf_out: torch.Tensor = torch.cat([torch.bmm(make_upright(LAF).view(B * N, 2, 3)[:, :2, :2], rotmat),
- LAF.view(B * N, 2, 3)[:, :2, 2:]], dim=2).view(B, N, 2, 3)
+ laf_out: torch.Tensor = torch.cat(
+ [torch.bmm(make_upright(LAF).view(B * N, 2, 3)[:, :2, :2], rotmat),
+ LAF.view(B * N, 2, 3)[:, :2, 2:]], dim=2
+ ).view(B, N, 2, 3)
return laf_out
@@ -127,25 +127,20 @@ def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.
torch.Tensor: tensor BxNx2x3 .
"""
names = ['xy', 'scale', 'ori']
- for var_name, var, req_shape in zip(names,
- [xy, scale, ori],
- [("B", "N", 2), ("B", "N", 1, 1), ("B", "N", 1)]):
+ for var_name, var, req_shape in zip(names, [xy, scale, ori], [("B", "N", 2), ("B", "N", 1, 1), ("B", "N", 1)]):
if not isinstance(var, torch.Tensor):
- raise TypeError("{} type is not a torch.Tensor. Got {}"
- .format(var_name, type(var)))
+ raise TypeError("{} type is not a torch.Tensor. Got {}".format(var_name, type(var)))
if len(var.shape) != len(req_shape): # type: ignore # because it does not like len(tensor.shape)
- raise TypeError(
- "{} shape should be must be [{}]. "
- "Got {}".format(var_name, str(req_shape), var.size()))
+ raise TypeError("{} shape should be must be [{}]. " "Got {}".format(var_name, str(req_shape), var.size()))
for i, dim in enumerate(req_shape): # type: ignore # because it wants typing for dim
if dim is not int:
continue
if var.size(i) != dim:
raise TypeError(
"{} shape should be must be [{}]. "
- "Got {}".format(var_name, str(req_shape), var.size()))
- unscaled_laf: torch.Tensor = torch.cat([kornia.angle_to_rotation_matrix(ori.squeeze(-1)),
- xy.unsqueeze(-1)], dim=-1)
+ "Got {}".format(var_name, str(req_shape), var.size())
+ )
+ unscaled_laf: torch.Tensor = torch.cat([kornia.angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)
laf: torch.Tensor = scale_laf(unscaled_laf, scale)
return laf
@@ -174,9 +169,7 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torc
>>> output = scale_laf(input, scale) # BxNx2x3
"""
if (type(scale_coef) is not float) and (type(scale_coef) is not torch.Tensor):
- raise TypeError(
- "scale_coef should be float or torch.Tensor "
- "Got {}".format(type(scale_coef)))
+ raise TypeError("scale_coef should be float or torch.Tensor " "Got {}".format(type(scale_coef)))
raise_error_if_laf_is_not_valid(laf)
centerless_laf: torch.Tensor = laf[:, :, :2, :2]
return torch.cat([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3)
@@ -206,12 +199,15 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
scale = det
# The function is equivalent to doing 2x2 SVD and reseting rotation
# matrix to an identity: U, S, V = svd(LAF); LAF_upright = U * S.
- b2a2 = torch.sqrt(laf[..., 0:1, 1:2] ** 2 + laf[..., 0:1, 0:1] ** 2) + eps
- laf1_ell = torch.cat([(b2a2 / det).contiguous(),
- torch.zeros_like(det)], dim=3)
- laf2_ell = torch.cat([((laf[..., 1:2, 1:2] * laf[..., 0:1, 1:2] +
- laf[..., 1:2, 0:1] * laf[..., 0:1, 0:1]) / (b2a2 * det)),
- (det / b2a2).contiguous()], dim=3) # type: ignore
+ b2a2 = torch.sqrt(laf[..., 0:1, 1:2]**2 + laf[..., 0:1, 0:1]**2) + eps
+ laf1_ell = torch.cat([(b2a2 / det).contiguous(), torch.zeros_like(det)], dim=3)
+ laf2_ell = torch.cat( # type: ignore
+ [
+ ((laf[..., 1:2, 1:2] * laf[..., 0:1, 1:2] + laf[..., 1:2, 0:1] * laf[..., 0:1, 0:1]) / (b2a2 * det)),
+ (det / b2a2).contiguous()
+ ],
+ dim=3
+ )
laf_unit_scale = torch.cat([torch.cat([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
return scale_laf(laf_unit_scale, scale)
@@ -240,14 +236,10 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
"""
n_dims = len(ells.size())
if n_dims != 3:
- raise TypeError(
- "ellipse shape should be must be [BxNx5]. "
- "Got {}".format(ells.size()))
+ raise TypeError("ellipse shape should be must be [BxNx5]. " "Got {}".format(ells.size()))
B, N, dim = ells.size()
if (dim != 5):
- raise TypeError(
- "ellipse shape should be must be [BxNx5]. "
- "Got {}".format(ells.size()))
+ raise TypeError("ellipse shape should be must be [BxNx5]. " "Got {}".format(ells.size()))
# Previous implementation was incorrectly using Cholesky decomp as matrix sqrt
# ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),
# torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)
@@ -287,9 +279,14 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
"""
raise_error_if_laf_is_not_valid(LAF)
B, N, _, _ = LAF.size()
- pts = torch.cat([torch.sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
- torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
- torch.ones(n_pts - 1, 1)], dim=1)
+ pts = torch.cat(
+ [
+ torch.sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
+ torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
+ torch.ones(n_pts - 1, 1)
+ ],
+ dim=1
+ )
# Add origin to draw also the orientation
pts = torch.cat([torch.tensor([0., 0., 1.]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
pts = pts.to(LAF.device).to(LAF.dtype)
@@ -299,8 +296,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
return kornia.convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))
-def get_laf_pts_to_draw(LAF: torch.Tensor,
- img_idx: int = 0):
+def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):
"""Returns numpy array for drawing LAFs (local features).
Args:
@@ -392,9 +388,7 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
return coef.expand_as(LAF) * LAF
-def generate_patch_grid_from_normalized_LAF(img: torch.Tensor,
- LAF: torch.Tensor,
- PS: int = 32) -> torch.Tensor:
+def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor, PS: int = 32) -> torch.Tensor:
"""Helper function for affine grid generation.
Args:
@@ -417,17 +411,19 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor,
# and extraction at arbitrary other
LAF_renorm = denormalize_laf(LAF, img)
- grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), # type: ignore
- [B * N, ch, PS, PS], align_corners=False)
+ grid = F.affine_grid(
+ LAF_renorm.view(B * N, 2, 3), # type: ignore
+ [B * N, ch, PS, PS],
+ align_corners=False
+ )
grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w) - 1.0
grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h) - 1.0
return grid
-def extract_patches_simple(img: torch.Tensor,
- laf: torch.Tensor,
- PS: int = 32,
- normalize_lafs_before_extraction: bool = True) -> torch.Tensor:
+def extract_patches_simple(
+ img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
+) -> torch.Tensor:
"""Extract patches defined by LAFs from image tensor.
No smoothing applied, huge aliasing (better use extract_patches_from_pyramid)
@@ -451,15 +447,20 @@ def extract_patches_simple(img: torch.Tensor,
# for loop temporarily, to be refactored
for i in range(B):
grid = generate_patch_grid_from_normalized_LAF(img[i:i + 1], nlaf[i:i + 1], PS).to(img.device)
- out.append(F.grid_sample(img[i:i + 1].expand(grid.size(0), ch, h, w), grid, # type: ignore
- padding_mode="border", align_corners=False))
+ out.append(
+ F.grid_sample(
+ img[i:i + 1].expand(grid.size(0), ch, h, w),
+ grid, # type: ignore
+ padding_mode="border",
+ align_corners=False
+ )
+ )
return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
-def extract_patches_from_pyramid(img: torch.Tensor,
- laf: torch.Tensor,
- PS: int = 32,
- normalize_lafs_before_extraction: bool = True) -> torch.Tensor:
+def extract_patches_from_pyramid(
+ img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
+) -> torch.Tensor:
"""Extract patches defined by LAFs from image tensor.
Patches are extracted from appropriate pyramid level
@@ -493,20 +494,20 @@ def extract_patches_from_pyramid(img: torch.Tensor,
if (scale_mask.float().sum()) == 0:
continue
scale_mask = (scale_mask > 0).view(-1)
- grid = generate_patch_grid_from_normalized_LAF(
- cur_img[i:i + 1],
- nlaf[i:i + 1, scale_mask, :, :],
- PS)
- patches = F.grid_sample(cur_img[i:i + 1].expand(grid.size(0), ch, h, w), grid, # type: ignore
- padding_mode="border", align_corners=False)
+ grid = generate_patch_grid_from_normalized_LAF(cur_img[i:i + 1], nlaf[i:i + 1, scale_mask, :, :], PS)
+ patches = F.grid_sample(
+ cur_img[i:i + 1].expand(grid.size(0), ch, h, w),
+ grid, # type: ignore
+ padding_mode="border",
+ align_corners=False
+ )
out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches)
cur_img = kornia.pyrdown(cur_img)
cur_pyr_level += 1
return out
-def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor,
- border: int = 0) -> torch.Tensor:
+def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:
"""Checks if the LAF is touching or partly outside the image boundary. Returns the mask
of LAFs, which are fully inside the image, i.e. valid.
@@ -540,9 +541,7 @@ def laf_to_three_points(laf: torch.Tensor):
threepts (torch.Tensor): :math:`(B, N, 2, 3)`
"""
raise_error_if_laf_is_not_valid(laf)
- three_pts: torch.Tensor = torch.stack([laf[..., 2] + laf[..., 0],
- laf[..., 2] + laf[..., 1],
- laf[..., 2]], dim=-1)
+ three_pts: torch.Tensor = torch.stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
return three_pts
@@ -556,7 +555,7 @@ def laf_from_three_points(threepts: torch.Tensor):
Returns:
laf (torch.Tensor): :math:`(B, N, 2, 3)`
"""
- laf: torch.Tensor = torch.stack([threepts[..., 0] - threepts[..., 2],
- threepts[..., 1] - threepts[..., 2],
- threepts[..., 2]], dim=-1)
+ laf: torch.Tensor = torch.stack(
+ [threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1
+ )
return laf
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index df217ffde..39c4d0c56 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -2,7 +2,8 @@ import torch
from typing import Tuple, Optional
-def match_nn(desc1: torch.Tensor, desc2: torch.Tensor,
+def match_nn(desc1: torch.Tensor,
+ desc2: torch.Tensor,
dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Function, which finds nearest neighbors in desc2 for each vector in desc1.
@@ -33,7 +34,8 @@ def match_nn(desc1: torch.Tensor, desc2: torch.Tensor,
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
-def match_mnn(desc1: torch.Tensor, desc2: torch.Tensor,
+def match_mnn(desc1: torch.Tensor,
+ desc2: torch.Tensor,
dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function, which finds mutual nearest neighbors in desc2 for each vector in desc1.
@@ -75,8 +77,10 @@ def match_mnn(desc1: torch.Tensor, desc2: torch.Tensor,
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
-def match_snn(desc1: torch.Tensor, desc2: torch.Tensor,
- th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+def match_snn(desc1: torch.Tensor,
+ desc2: torch.Tensor,
+ th: float = 0.8,
+ dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function, which finds nearest neighbors in desc2 for each vector in desc1.
which satisfy first to second nearest neighbor distance <= th.
@@ -114,8 +118,10 @@ def match_snn(desc1: torch.Tensor, desc2: torch.Tensor,
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
-def match_smnn(desc1: torch.Tensor, desc2: torch.Tensor,
- th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+def match_smnn(desc1: torch.Tensor,
+ desc2: torch.Tensor,
+ th: float = 0.8,
+ dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function, which finds mutual nearest neighbors in desc2 for each vector in desc1.
which satisfy first to second nearest neighbor distance <= th.
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 2038c5fca..1a1af1df2 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -9,25 +9,22 @@ from kornia.utils import create_meshgrid
from kornia.geometry.conversions import cart2pol
from kornia.filters import SpatialGradient, GaussianBlur2d
-
# Precomputed coefficients for Von Mises kernel, given N and K(appa).
sqrt2: float = 1.4142135623730951
COEFFS_N1_K1: List[float] = [0.38214156, 0.48090413]
COEFFS_N2_K8: List[float] = [0.14343168, 0.268285, 0.21979234]
COEFFS_N3_K8: List[float] = [0.14343168, 0.268285, 0.21979234, 0.15838885]
-COEFFS: Dict[str, List[float]] = {'xy': COEFFS_N1_K1,
- 'rhophi': COEFFS_N2_K8,
- 'theta': COEFFS_N3_K8}
+COEFFS: Dict[str, List[float]] = {'xy': COEFFS_N1_K1, 'rhophi': COEFFS_N2_K8, 'theta': COEFFS_N3_K8}
-urls: Dict[str, str] = {k: f'https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-{k}-64.pth'
- for k in ['cart', 'polar', 'concat']}
+urls: Dict[str, str] = {
+ k: f'https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-{k}-64.pth'
+ for k in ['cart', 'polar', 'concat']
+}
def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:
"""Gets cartesian and polar parametrizations of grid. """
- kgrid = create_meshgrid(height=patch_size,
- width=patch_size,
- normalized_coordinates=True)
+ kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True)
x = kgrid[0, :, :, 0]
y = kgrid[0, :, :, 1]
rho, phi = cart2pol(x, y)
@@ -73,11 +70,9 @@ class MKDGradients(nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not isinstance(x, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(x)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))
if not len(x.shape) == 4:
- raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
- .format(x.shape))
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(x.shape))
# Modify 'diff' gradient. Before we had lambda function, but it is not jittable
grads_xy = -self.grad(x)
gx = grads_xy[:, :, 0, :, :]
@@ -111,9 +106,7 @@ class VonMisesKernel(nn.Module):
>>> emb = vm(oris) # 23x7x32x32
"""
- def __init__(self,
- patch_size: int,
- coeffs: Union[list, tuple]) -> None:
+ def __init__(self, patch_size: int, coeffs: Union[list, tuple]) -> None:
super().__init__()
self.patch_size = patch_size
@@ -139,12 +132,10 @@ class VonMisesKernel(nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not isinstance(x, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(x)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))
if not len(x.shape) == 4 or x.shape[1] != 1:
- raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
- .format(x.shape))
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(x.shape))
# TODO: unify the two lines below when pytorch 1.6 support is dropped
emb0: torch.Tensor = torch.jit.annotate(torch.Tensor, self.emb0)
@@ -183,22 +174,17 @@ class EmbedGradients(nn.Module):
>>> emb = emb_grads(grads) # 23x7x32x32
"""
- def __init__(self,
- patch_size: int = 32,
- relative: bool = False) -> None:
+ def __init__(self, patch_size: int = 32, relative: bool = False) -> None:
super().__init__()
self.patch_size = patch_size
self.relative = relative
self.eps = 1e-8
# Theta kernel for gradients.
- self.kernel = VonMisesKernel(patch_size=patch_size,
- coeffs=COEFFS['theta'])
+ self.kernel = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS['theta'])
# Relative gradients.
- kgrid = create_meshgrid(height=patch_size,
- width=patch_size,
- normalized_coordinates=True)
+ kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True)
_, phi = cart2pol(kgrid[:, :, :, 0], kgrid[:, :, :, 1])
self.register_buffer('phi', phi)
@@ -209,11 +195,9 @@ class EmbedGradients(nn.Module):
def forward(self, grads: torch.Tensor) -> torch.Tensor:
if not isinstance(grads, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(grads)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(grads)))
if not len(grads.shape) == 4:
- raise ValueError("Invalid input shape, we expect Bx2xHxW. Got: {}"
- .format(grads.shape))
+ raise ValueError("Invalid input shape, we expect Bx2xHxW. Got: {}".format(grads.shape))
mags = grads[:, :1, :, :]
oris = grads[:, 1:, :, :]
if self.relative:
@@ -243,8 +227,7 @@ def spatial_kernel_embedding(kernel_type, grids: dict) -> torch.Tensor:
# Scale appropriately.
grids_normed = {k: v * factors[k] for k, v in grids.items()}
- grids_normed = {k: v.unsqueeze(0).unsqueeze(0).float()
- for k, v in grids_normed.items()}
+ grids_normed = {k: v.unsqueeze(0).unsqueeze(0).float() for k, v in grids_normed.items()}
# x,y/rho,phi kernels.
vm_a = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS[coeffs_])
@@ -255,8 +238,7 @@ def spatial_kernel_embedding(kernel_type, grids: dict) -> torch.Tensor:
# Final precomputed position embedding.
kron_order = get_kron_order(vm_a.d, vm_b.d)
- spatial_kernel = emb_a.index_select(0,
- kron_order[:, 0]) * emb_b.index_select(0, kron_order[:, 1])
+ spatial_kernel = emb_a.index_select(0, kron_order[:, 0]) * emb_b.index_select(0, kron_order[:, 1])
return spatial_kernel
@@ -285,12 +267,14 @@ class ExplicitSpacialEncoding(nn.Module):
>>> desc = ese(emb_ori) # 23x175x32x32
"""
- def __init__(self,
- kernel_type: str = 'polar',
- fmap_size: int = 32,
- in_dims: int = 7,
- do_gmask: bool = True,
- do_l2: bool = True) -> None:
+ def __init__(
+ self,
+ kernel_type: str = 'polar',
+ fmap_size: int = 32,
+ in_dims: int = 7,
+ do_gmask: bool = True,
+ do_l2: bool = True
+ ) -> None:
super().__init__()
if kernel_type not in ['polar', 'cart']:
@@ -338,11 +322,9 @@ class ExplicitSpacialEncoding(nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not isinstance(x, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(x)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))
if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):
- raise ValueError("Invalid input shape, we expect Bx{}xHxW. Got: {}"
- .format(self.in_dims, x.shape))
+ raise ValueError("Invalid input shape, we expect Bx{}xHxW. Got: {}".format(self.in_dims, x.shape))
idx1 = torch.jit.annotate(torch.Tensor, self.idx1)
emb1 = torch.index_select(x, 1, idx1)
output = emb1 * self.emb2
@@ -396,13 +378,15 @@ class Whitening(nn.Module):
>>> wdescs = whitening(descs) # 23x128
"""
- def __init__(self,
- xform: str,
- whitening_model: Union[Dict[str, Dict[str, torch.Tensor]], None],
- in_dims: int,
- output_dims: int = 128,
- keval: int = 40,
- t: float = 0.7) -> None:
+ def __init__(
+ self,
+ xform: str,
+ whitening_model: Union[Dict[str, Dict[str, torch.Tensor]], None],
+ in_dims: int,
+ output_dims: int = 128,
+ keval: int = 40,
+ t: float = 0.7
+ ) -> None:
super().__init__()
self.xform = xform
@@ -423,18 +407,19 @@ class Whitening(nn.Module):
if whitening_model is not None:
self.load_whitening_parameters(whitening_model)
- def load_whitening_parameters(self,
- whitening_model: Dict[str, Dict[str, torch.Tensor]]) -> None:
+ def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, torch.Tensor]]) -> None:
algo = 'lw' if self.xform == 'lw' else 'pca'
wh_model = whitening_model[algo]
self.mean.data = wh_model['mean']
self.evecs.data = wh_model['eigvecs'][:, :self.output_dims]
self.evals.data = wh_model['eigvals'][:self.output_dims]
- modifications = {'pca': self._modify_pca,
- 'lw': self._modify_lw,
- 'pcaws': self._modify_pcaws,
- 'pcawt': self._modify_pcawt}
+ modifications = {
+ 'pca': self._modify_pca,
+ 'lw': self._modify_lw,
+ 'pcaws': self._modify_pcaws,
+ 'pcawt': self._modify_pcawt
+ }
# Call modification.
modifications[self.xform]()
@@ -459,11 +444,9 @@ class Whitening(nn.Module):
def forward(self, x: torch.Tensor) -> torch.Tensor:
if not isinstance(x, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(x)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(x)))
if not len(x.shape) == 2:
- raise ValueError("Invalid input shape, we expect NxD. Got: {}"
- .format(x.shape))
+ raise ValueError("Invalid input shape, we expect NxD. Got: {}".format(x.shape))
x = x - self.mean # Center the data.
x = x @ self.evecs # Apply rotation and/or scaling.
x = torch.sign(x) * torch.pow(torch.abs(x), self.pval) # Powerlaw.
@@ -509,12 +492,14 @@ class MKDDescriptor(nn.Module):
>>> desc = mkd(patches) # 23x128
"""
- def __init__(self,
- patch_size: int = 32,
- kernel_type: str = 'concat',
- whitening: str = 'pcawt',
- training_set: str = 'liberty',
- output_dims: int = 128) -> None:
+ def __init__(
+ self,
+ patch_size: int = 32,
+ kernel_type: str = 'concat',
+ whitening: str = 'pcawt',
+ training_set: str = 'liberty',
+ output_dims: int = 128
+ ) -> None:
super().__init__()
self.patch_size: int = patch_size
@@ -523,9 +508,7 @@ class MKDDescriptor(nn.Module):
self.training_set: str = training_set
self.sigma = 1.4 * (patch_size / 64)
- self.smoothing = GaussianBlur2d((5, 5),
- (self.sigma, self.sigma),
- 'replicate')
+ self.smoothing = GaussianBlur2d((5, 5), (self.sigma, self.sigma), 'replicate')
self.gradients = MKDGradients()
# This stupid thing needed for jitting...
polar_s: str = 'polar'
@@ -537,11 +520,10 @@ class MKDDescriptor(nn.Module):
relative_orientations = {polar_s: True, cart_s: False}
self.feats = {}
for parametrization in self.parametrizations:
- gradient_embedding = EmbedGradients(patch_size=patch_size,
- relative=relative_orientations[parametrization])
- spatial_encoding = ExplicitSpacialEncoding(kernel_type=parametrization,
- fmap_size=patch_size,
- in_dims=gradient_embedding.kernel.d)
+ gradient_embedding = EmbedGradients(patch_size=patch_size, relative=relative_orientations[parametrization])
+ spatial_encoding = ExplicitSpacialEncoding(
+ kernel_type=parametrization, fmap_size=patch_size, in_dims=gradient_embedding.kernel.d
+ )
self.feats[parametrization] = nn.Sequential(gradient_embedding, spatial_encoding)
self.odims += spatial_encoding.odims
@@ -554,19 +536,16 @@ class MKDDescriptor(nn.Module):
urls[self.kernel_type], map_location=lambda storage, loc: storage
)
whitening_model = whitening_models[training_set]
- self.whitening_layer = Whitening(whitening,
- whitening_model,
- in_dims=self.odims,
- output_dims=self.output_dims)
+ self.whitening_layer = Whitening(
+ whitening, whitening_model, in_dims=self.odims, output_dims=self.output_dims
+ )
self.odims = self.output_dims
def forward(self, patches: torch.Tensor) -> torch.Tensor:
if not isinstance(patches, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(patches)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patches)))
if not len(patches.shape) == 4:
- raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
- .format(patches.shape))
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(patches.shape))
# Extract gradients.
g = self.smoothing(patches)
g = self.gradients(g)
@@ -599,9 +578,7 @@ class MKDDescriptor(nn.Module):
def load_whitening_model(kernel_type: str, training_set: str) -> Dict:
- whitening_models = torch.hub.load_state_dict_from_url(
- urls[kernel_type], map_location=lambda storage, loc: storage
- )
+ whitening_models = torch.hub.load_state_dict_from_url(urls[kernel_type], map_location=lambda storage, loc: storage)
whitening_model = whitening_models[training_set]
return whitening_model
@@ -609,12 +586,14 @@ def load_whitening_model(kernel_type: str, training_set: str) -> Dict:
class SimpleKD(nn.Module):
"""Example to write custom Kernel Descriptors. """
- def __init__(self,
- patch_size: int = 32,
- kernel_type: str = 'polar', # 'cart' 'polar'
- whitening: str = 'pcawt', # 'lw', 'pca', 'pcaws', 'pcawt
- training_set: str = 'liberty', # 'liberty', 'notredame', 'yosemite'
- output_dims: int = 128) -> None:
+ def __init__(
+ self,
+ patch_size: int = 32,
+ kernel_type: str = 'polar', # 'cart' 'polar'
+ whitening: str = 'pcawt', # 'lw', 'pca', 'pcaws', 'pcawt
+ training_set: str = 'liberty', # 'liberty', 'notredame', 'yosemite'
+ output_dims: int = 128
+ ) -> None:
super().__init__()
relative: bool = kernel_type == 'polar'
@@ -624,18 +603,12 @@ class SimpleKD(nn.Module):
smoothing = GaussianBlur2d((5, 5), (sigma, sigma), 'replicate')
gradients = MKDGradients()
ori = EmbedGradients(patch_size=patch_size, relative=relative)
- ese = ExplicitSpacialEncoding(kernel_type=kernel_type,
- fmap_size=patch_size, in_dims=ori.kernel.d)
- wh = Whitening(whitening,
- load_whitening_model(kernel_type, training_set),
- in_dims=ese.odims,
- output_dims=output_dims)
-
- self.features = nn.Sequential(smoothing,
- gradients,
- ori,
- ese,
- wh)
+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=patch_size, in_dims=ori.kernel.d)
+ wh = Whitening(
+ whitening, load_whitening_model(kernel_type, training_set), in_dims=ese.odims, output_dims=output_dims
+ )
+
+ self.features = nn.Sequential(smoothing, gradients, ori, ese, wh)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.features(x)
diff --git a/kornia/feature/nms.py b/kornia/feature/nms.py
index e4db350bc..495fb94e4 100644
--- a/kornia/feature/nms.py
+++ b/kornia/feature/nms.py
@@ -30,30 +30,30 @@ class NonMaximaSuppression2d(nn.Module):
def __init__(self, kernel_size: Tuple[int, int]):
super(NonMaximaSuppression2d, self).__init__()
self.kernel_size: Tuple[int, int] = kernel_size
- self.padding: Tuple[int, int,
- int, int] = self._compute_zero_padding2d(kernel_size)
+ self.padding: Tuple[int, int, int, int] = self._compute_zero_padding2d(kernel_size)
self.kernel = _get_nms_kernel2d(*kernel_size)
@staticmethod
- def _compute_zero_padding2d(
- kernel_size: Tuple[int, int]) -> Tuple[int, int, int, int]:
+ def _compute_zero_padding2d(kernel_size: Tuple[int, int]) -> Tuple[int, int, int, int]:
assert isinstance(kernel_size, tuple), type(kernel_size)
assert len(kernel_size) == 2, kernel_size
def pad(x):
return (x - 1) // 2 # zero padding function
- ky, kx = kernel_size # we assume a cubic kernel
+ ky, kx = kernel_size # we assume a cubic kernel
return (pad(ky), pad(ky), pad(kx), pad(kx))
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
assert len(x.shape) == 4, x.shape
B, CH, H, W = x.size()
# find local maximum values
- max_non_center = F.conv2d(F.pad(x, list(self.padding)[::-1], mode='replicate'),
- self.kernel.repeat(CH, 1, 1, 1).to(x.device, x.dtype),
- stride=1,
- groups=CH).view(B, CH, -1, H, W).max(dim=2)[0]
+ max_non_center = F.conv2d(
+ F.pad(x, list(self.padding)[::-1], mode='replicate'),
+ self.kernel.repeat(CH, 1, 1, 1).to(x.device, x.dtype),
+ stride=1,
+ groups=CH
+ ).view(B, CH, -1, H, W).max(dim=2)[0]
mask = x > max_non_center
if mask_only:
return mask
@@ -67,30 +67,30 @@ class NonMaximaSuppression3d(nn.Module):
def __init__(self, kernel_size: Tuple[int, int, int]):
super(NonMaximaSuppression3d, self).__init__()
self.kernel_size: Tuple[int, int, int] = kernel_size
- self.padding: Tuple[int, int, int,
- int, int, int] = self._compute_zero_padding3d(kernel_size)
+ self.padding: Tuple[int, int, int, int, int, int] = self._compute_zero_padding3d(kernel_size)
self.kernel = _get_nms_kernel3d(*kernel_size)
@staticmethod
- def _compute_zero_padding3d(
- kernel_size: Tuple[int, int, int]) -> Tuple[int, int, int, int, int, int]:
+ def _compute_zero_padding3d(kernel_size: Tuple[int, int, int]) -> Tuple[int, int, int, int, int, int]:
assert isinstance(kernel_size, tuple), type(kernel_size)
assert len(kernel_size) == 3, kernel_size
def pad(x):
return (x - 1) // 2 # zero padding function
- kd, ky, kx = kernel_size # we assume a cubic kernel
+ kd, ky, kx = kernel_size # we assume a cubic kernel
return pad(kd), pad(kd), pad(ky), pad(ky), pad(kx), pad(kx)
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
assert len(x.shape) == 5, x.shape
# find local maximum values
B, CH, D, H, W = x.size()
- max_non_center = F.conv3d(F.pad(x, list(self.padding)[::-1], mode='replicate'),
- self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
- stride=1,
- groups=CH).view(B, CH, -1, D, H, W).max(dim=2, keepdim=False)[0]
+ max_non_center = F.conv3d(
+ F.pad(x, list(self.padding)[::-1], mode='replicate'),
+ self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
+ stride=1,
+ groups=CH
+ ).view(B, CH, -1, D, H, W).max(dim=2, keepdim=False)[0]
mask = x > max_non_center
if mask_only:
return mask
@@ -100,8 +100,7 @@ class NonMaximaSuppression3d(nn.Module):
# functiona api
-def nms2d(
- input: torch.Tensor, kernel_size: Tuple[int, int], mask_only: bool = False) -> torch.Tensor:
+def nms2d(input: torch.Tensor, kernel_size: Tuple[int, int], mask_only: bool = False) -> torch.Tensor:
r"""Applies non maxima suppression to filter.
See :class:`~kornia.feature.NonMaximaSuppression2d` for details.
@@ -109,8 +108,7 @@ def nms2d(
return NonMaximaSuppression2d(kernel_size)(input, mask_only)
-def nms3d(
- input: torch.Tensor, kernel_size: Tuple[int, int, int], mask_only: bool = False) -> torch.Tensor:
+def nms3d(input: torch.Tensor, kernel_size: Tuple[int, int, int], mask_only: bool = False) -> torch.Tensor:
r"""Applies non maxima suppression to filter.
See :class:`~kornia.feature.NonMaximaSuppression3d` for details.
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index f2c3a36cb..6eed4fc24 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -7,9 +7,10 @@ import math
from kornia.filters import get_gaussian_kernel2d
from kornia.filters import SpatialGradient
from kornia.constants import pi
-from kornia.feature import (extract_patches_from_pyramid, make_upright,
- normalize_laf, raise_error_if_laf_is_not_valid,
- set_laf_orientation, get_laf_orientation)
+from kornia.feature import (
+ extract_patches_from_pyramid, make_upright, normalize_laf, raise_error_if_laf_is_not_valid, set_laf_orientation,
+ get_laf_orientation
+)
from kornia.geometry import rad2deg
urls: Dict[str, str] = dict()
@@ -39,9 +40,7 @@ class PatchDominantGradientOrientation(nn.Module):
num_angular_bins: int, default is 36
eps: float, for safe division, and arctan, default is 1e-8"""
- def __init__(self,
- patch_size: int = 32,
- num_angular_bins: int = 36, eps: float = 1e-8):
+ def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, eps: float = 1e-8):
super(PatchDominantGradientOrientation, self).__init__()
self.patch_size = patch_size
self.num_ang_bins = num_angular_bins
@@ -66,16 +65,15 @@ class PatchDominantGradientOrientation(nn.Module):
Returns:
torch.Tensor: angle shape [B] """
if not isinstance(patch, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(patch)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))
if not len(patch.shape) == 4:
- raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
- .format(patch.shape))
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(patch.shape))
B, CH, W, H = patch.size()
if (W != self.patch_size) or (H != self.patch_size) or (CH != 1):
raise TypeError(
"input shape should be must be [Bx1x{}x{}]. "
- "Got {}".format(self.patch_size, self.patch_size, patch.size()))
+ "Got {}".format(self.patch_size, self.patch_size, patch.size())
+ )
self.weighting = self.weighting.to(patch.dtype).to(patch.device)
self.angular_smooth = self.angular_smooth.to(patch.dtype).to(patch.device)
grads: torch.Tensor = self.gradient(patch)
@@ -95,8 +93,9 @@ class PatchDominantGradientOrientation(nn.Module):
wo1_big = wo1_big * mag
ang_bins_list = []
for i in range(0, self.num_ang_bins):
- ang_bins_i = F.adaptive_avg_pool2d((bo0_big == i).to(patch.dtype) * wo0_big +
- (bo1_big == i).to(patch.dtype) * wo1_big, (1, 1))
+ ang_bins_i = F.adaptive_avg_pool2d(
+ (bo0_big == i).to(patch.dtype) * wo0_big + (bo1_big == i).to(patch.dtype) * wo1_big, (1, 1)
+ )
ang_bins_list.append(ang_bins_i)
ang_bins = torch.cat(ang_bins_list, 1).view(-1, 1, self.num_ang_bins)
ang_bins = self.angular_smooth(ang_bins)
@@ -132,27 +131,15 @@ class OriNet(nn.Module):
def __init__(self, pretrained: bool = False, eps: float = 1e-8):
super(OriNet, self).__init__()
self.features = nn.Sequential(
- nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),
- nn.BatchNorm2d(16, affine=False),
- nn.ReLU(),
- nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False),
- nn.BatchNorm2d(16, affine=False),
- nn.ReLU(),
- nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False),
- nn.BatchNorm2d(32, affine=False),
- nn.ReLU(),
- nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False),
- nn.BatchNorm2d(32, affine=False),
- nn.ReLU(),
- nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
- nn.BatchNorm2d(64, affine=False),
- nn.ReLU(),
- nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False),
- nn.BatchNorm2d(64, affine=False),
- nn.ReLU(),
- nn.Dropout(0.25),
- nn.Conv2d(64, 2, kernel_size=8, stride=1, padding=1, bias=True),
- nn.Tanh(),
+ nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(16, affine=False), nn.ReLU(),
+ nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(16, affine=False),
+ nn.ReLU(), nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(32, affine=False), nn.ReLU(),
+ nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(32, affine=False),
+ nn.ReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(64, affine=False), nn.ReLU(),
+ nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(64, affine=False),
+ nn.ReLU(), nn.Dropout(0.25), nn.Conv2d(64, 2, kernel_size=8, stride=1, padding=1, bias=True), nn.Tanh(),
nn.AdaptiveAvgPool2d(1)
)
self.eps = eps
@@ -166,7 +153,7 @@ class OriNet(nn.Module):
@staticmethod
def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- "Utility function that normalizes the input by batch."""
+ "Utility function that normalizes the input by batch." ""
sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
# WARNING: we need to .detach() input, otherwise the gradients produced by
# the patches extractor with F.grid_sample are very noisy, making the detector
@@ -193,10 +180,7 @@ class LAFOrienter(nn.Module):
num_angular_bins: int, default is 36
angle_detector: nn.Module. Patch orientation estimator, e.g. PatchDominantGradientOrientation or OriNet. Default: None """ # noqa pylint: disable
- def __init__(self,
- patch_size: int = 32,
- num_angular_bins: int = 36,
- angle_detector: Optional[nn.Module] = None):
+ def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, angle_detector: Optional[nn.Module] = None):
super(LAFOrienter, self).__init__()
self.patch_size = patch_size
self.num_ang_bins = num_angular_bins
@@ -223,20 +207,16 @@ class LAFOrienter(nn.Module):
raise_error_if_laf_is_not_valid(laf)
img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
if not isinstance(img, torch.Tensor):
- raise TypeError("img type is not a torch.Tensor. Got {}"
- .format(type(img)))
+ raise TypeError("img type is not a torch.Tensor. Got {}".format(type(img)))
if len(img.shape) != 4:
raise ValueError(img_message)
if laf.size(0) != img.size(0):
- raise ValueError("Batch size of laf and img should be the same. Got {}, {}"
- .format(img.size(0), laf.size(0)))
+ raise ValueError(
+ "Batch size of laf and img should be the same. Got {}, {}".format(img.size(0), laf.size(0))
+ )
B, N = laf.shape[:2]
- patches: torch.Tensor = extract_patches_from_pyramid(img,
- laf,
- self.patch_size).view(-1,
- 1,
- self.patch_size,
- self.patch_size)
+ patches: torch.Tensor = extract_patches_from_pyramid(img, laf, self.patch_size
+ ).view(-1, 1, self.patch_size, self.patch_size)
angles_radians: torch.Tensor = self.angle_detector(patches).view(B, N)
prev_angle = get_laf_orientation(laf).view_as(angles_radians)
laf_out: torch.Tensor = set_laf_orientation(laf, rad2deg(angles_radians) + prev_angle)
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 50bc64b09..b4182f01a 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -6,10 +6,12 @@ import torch.nn as nn
from kornia.filters import spatial_gradient, gaussian_blur2d
-def harris_response(input: torch.Tensor,
- k: Union[torch.Tensor, float] = 0.04,
- grads_mode: str = 'sobel',
- sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+def harris_response(
+ input: torch.Tensor,
+ k: Union[torch.Tensor, float] = 0.04,
+ grads_mode: str = 'sobel',
+ sigmas: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Computes the Harris cornerness function. Function does not do
any normalization or nms.The response map is computed according the following formulation:
@@ -67,15 +69,12 @@ def harris_response(input: torch.Tensor,
"""
# TODO: Recompute doctest
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
if sigmas is not None:
if not isinstance(sigmas, torch.Tensor):
- raise TypeError("sigmas type is not a torch.Tensor. Got {}"
- .format(type(sigmas)))
+ raise TypeError("sigmas type is not a torch.Tensor. Got {}".format(type(sigmas)))
if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
raise ValueError("Invalid sigmas shape, we expect B == input.size(0). Got: {}".format(sigmas.shape))
gradients: torch.Tensor = spatial_gradient(input, grads_mode)
@@ -84,22 +83,22 @@ def harris_response(input: torch.Tensor,
# compute the structure tensor M elements
- dx2: torch.Tensor = gaussian_blur2d(dx ** 2, (7, 7), (1., 1.))
- dy2: torch.Tensor = gaussian_blur2d(dy ** 2, (7, 7), (1., 1.))
+ dx2: torch.Tensor = gaussian_blur2d(dx**2, (7, 7), (1., 1.))
+ dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1., 1.))
dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1., 1.))
det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
trace_m: torch.Tensor = dx2 + dy2
# compute the response map
- scores: torch.Tensor = det_m - k * (trace_m ** 2)
+ scores: torch.Tensor = det_m - k * (trace_m**2)
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
return scores
-def gftt_response(input: torch.Tensor,
- grads_mode: str = 'sobel',
- sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+def gftt_response(
+ input: torch.Tensor, grads_mode: str = 'sobel', sigmas: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Computes the Shi-Tomasi cornerness function. Function does not do any normalization or nms.
The response map is computed according the following formulation:
@@ -153,24 +152,22 @@ def gftt_response(input: torch.Tensor,
"""
# TODO: Recompute doctest
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
gradients: torch.Tensor = spatial_gradient(input, grads_mode)
dx: torch.Tensor = gradients[:, :, 0]
dy: torch.Tensor = gradients[:, :, 1]
- dx2: torch.Tensor = gaussian_blur2d(dx ** 2, (7, 7), (1., 1.))
- dy2: torch.Tensor = gaussian_blur2d(dy ** 2, (7, 7), (1., 1.))
+ dx2: torch.Tensor = gaussian_blur2d(dx**2, (7, 7), (1., 1.))
+ dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1., 1.))
dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1., 1.))
det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
trace_m: torch.Tensor = dx2 + dy2
- e1: torch.Tensor = 0.5 * (trace_m + torch.sqrt((trace_m ** 2 - 4 * det_m).abs()))
- e2: torch.Tensor = 0.5 * (trace_m - torch.sqrt((trace_m ** 2 - 4 * det_m).abs()))
+ e1: torch.Tensor = 0.5 * (trace_m + torch.sqrt((trace_m**2 - 4 * det_m).abs()))
+ e2: torch.Tensor = 0.5 * (trace_m - torch.sqrt((trace_m**2 - 4 * det_m).abs()))
scores: torch.Tensor = torch.min(e1, e2)
if sigmas is not None:
@@ -178,9 +175,9 @@ def gftt_response(input: torch.Tensor,
return scores
-def hessian_response(input: torch.Tensor,
- grads_mode: str = 'sobel',
- sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+def hessian_response(
+ input: torch.Tensor, grads_mode: str = 'sobel', sigmas: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Computes the absolute of determinant of the Hessian matrix. Function does not do any normalization or nms.
The response map is computed according the following formulation:
@@ -234,24 +231,20 @@ def hessian_response(input: torch.Tensor,
"""
# TODO: Recompute doctest
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
if sigmas is not None:
if not isinstance(sigmas, torch.Tensor):
- raise TypeError("sigmas type is not a torch.Tensor. Got {}"
- .format(type(sigmas)))
+ raise TypeError("sigmas type is not a torch.Tensor. Got {}".format(type(sigmas)))
if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
- raise ValueError("Invalid sigmas shape, we expect B == input.size(0). Got: {}"
- .format(sigmas.shape))
+ raise ValueError("Invalid sigmas shape, we expect B == input.size(0). Got: {}".format(sigmas.shape))
gradients: torch.Tensor = spatial_gradient(input, grads_mode, 2)
dxx: torch.Tensor = gradients[:, :, 0]
dxy: torch.Tensor = gradients[:, :, 1]
dyy: torch.Tensor = gradients[:, :, 2]
- scores: torch.Tensor = dxx * dyy - dxy ** 2
+ scores: torch.Tensor = dxx * dyy - dxy**2
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
return scores
@@ -273,11 +266,9 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 5:
- raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}".format(input.shape))
return input[:, :, 1:] - input[:, :, :-1]
@@ -293,8 +284,11 @@ class BlobDoG(nn.Module):
def __repr__(self) -> str:
return self.__class__.__name__
- def forward(self, input: torch.Tensor, # type: ignore
- sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ def forward(
+ self,
+ input: torch.Tensor, # type: ignore
+ sigmas: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
return dog_response(input) # type: ignore
@@ -303,8 +297,7 @@ class CornerHarris(nn.Module):
See :func:`~kornia.feature.harris_response` for details.
"""
- def __init__(self, k: Union[float, torch.Tensor],
- grads_mode='sobel') -> None:
+ def __init__(self, k: Union[float, torch.Tensor], grads_mode='sobel') -> None:
super(CornerHarris, self).__init__()
if type(k) is float:
self.register_buffer('k', torch.tensor(k))
@@ -318,8 +311,11 @@ class CornerHarris(nn.Module):
'(k=' + str(self.k) + ', ' +\
'grads_mode=' + self.grads_mode + ')'
- def forward(self, input: torch.Tensor, # type: ignore
- sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ def forward(
+ self,
+ input: torch.Tensor, # type: ignore
+ sigmas: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
return harris_response(input, self.k, self.grads_mode, sigmas) # type: ignore
@@ -337,8 +333,11 @@ class CornerGFTT(nn.Module):
return self.__class__.__name__ +\
'grads_mode=' + self.grads_mode + ')'
- def forward(self, input: torch.Tensor, # type: ignore
- sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ def forward(
+ self,
+ input: torch.Tensor, # type: ignore
+ sigmas: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
return gftt_response(input, self.grads_mode, sigmas)
@@ -356,6 +355,9 @@ class BlobHessian(nn.Module):
return self.__class__.__name__ +\
'grads_mode=' + self.grads_mode + ')'
- def forward(self, input: torch.Tensor, # type: ignore
- sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ def forward(
+ self,
+ input: torch.Tensor, # type: ignore
+ sigmas: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
return hessian_response(input, self.grads_mode, sigmas)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index deb78b2d2..b8c7e0939 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -8,9 +8,7 @@ from kornia.geometry import angle_to_rotation_matrix
from kornia.feature.responses import BlobHessian
from kornia.geometry import ConvSoftArgmax3d
from kornia.feature.orientation import PassLAF
-from kornia.feature.laf import (
- denormalize_laf, scale_laf,
- normalize_laf, laf_is_inside_image)
+from kornia.feature.laf import (denormalize_laf, scale_laf, normalize_laf, laf_is_inside_image)
from kornia.geometry.transform import ScalePyramid
@@ -34,8 +32,9 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_le
L: int = sigmas.size(1)
scale_coords = max_coords[:, :, 0].contiguous().view(-1, 1, 1, 1)
# Replace the scale_x_y
- out = torch.cat([sigmas[0, 0] * torch.pow(2.0, scale_coords / float(num_levels)).view(B, N, 1),
- max_coords[:, :, 1:]], dim=2)
+ out = torch.cat(
+ [sigmas[0, 0] * torch.pow(2.0, scale_coords / float(num_levels)).view(B, N, 1), max_coords[:, :, 1:]], dim=2
+ )
return out
@@ -72,20 +71,20 @@ class ScaleSpaceDetector(nn.Module):
Useful for symmetric response functions like DoG or Hessian. Default is False
"""
- def __init__(self,
- num_features: int = 500,
- mr_size: float = 6.0,
- scale_pyr_module: nn.Module = ScalePyramid(3, 1.6, 15),
- resp_module: nn.Module = BlobHessian(),
- nms_module: nn.Module = ConvSoftArgmax3d((3, 3, 3),
- (1, 1, 1),
- (1, 1, 1),
- normalized_coordinates=False,
- output_value=True),
- ori_module: nn.Module = PassLAF(),
- aff_module: nn.Module = PassLAF(),
- minima_are_also_good: bool = False,
- scale_space_response=False):
+ def __init__(
+ self,
+ num_features: int = 500,
+ mr_size: float = 6.0,
+ scale_pyr_module: nn.Module = ScalePyramid(3, 1.6, 15),
+ resp_module: nn.Module = BlobHessian(),
+ nms_module: nn.Module = ConvSoftArgmax3d(
+ (3, 3, 3), (1, 1, 1), (1, 1, 1), normalized_coordinates=False, output_value=True
+ ),
+ ori_module: nn.Module = PassLAF(),
+ aff_module: nn.Module = PassLAF(),
+ minima_are_also_good: bool = False,
+ scale_space_response=False
+ ):
super(ScaleSpaceDetector, self).__init__()
self.mr_size = mr_size
self.num_features = num_features
@@ -110,7 +109,9 @@ class ScaleSpaceDetector(nn.Module):
'ori=' + self.ori.__repr__() + ', ' + \
'aff=' + self.aff.__repr__() + ')'
- def detect(self, img: torch.Tensor, num_feats: int,
+ def detect(self,
+ img: torch.Tensor,
+ num_feats: int,
mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
dev: torch.device = img.device
dtype: torch.dtype = img.dtype
@@ -159,14 +160,19 @@ class ScaleSpaceDetector(nn.Module):
B, N = resp_flat_best.size()
# Converts scale level index from ConvSoftArgmax3d to the actual scale, using the sigmas
- max_coords_best = _scale_index_to_scale(max_coords_best,
- sigmas_oct,
- self.scale_pyr.n_levels) # type: ignore
+ max_coords_best = _scale_index_to_scale(
+ max_coords_best, sigmas_oct, self.scale_pyr.n_levels # type: ignore
+ )
# Create local affine frames (LAFs)
rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
- current_lafs = torch.cat([self.mr_size * max_coords_best[:, :, 0].view(B, N, 1, 1) * rotmat,
- max_coords_best[:, :, 1:3].view(B, N, 2, 1)], dim=3)
+ current_lafs = torch.cat(
+ [
+ self.mr_size * max_coords_best[:, :, 0].view(B, N, 1, 1) * rotmat,
+ max_coords_best[:, :, 1:3].view(B, N, 2, 1)
+ ],
+ dim=3
+ )
# Zero response lafs, which touch the boundary
good_mask = laf_is_inside_image(current_lafs, octave[:, 0])
@@ -185,8 +191,11 @@ class ScaleSpaceDetector(nn.Module):
lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 2, 3))
return responses, denormalize_laf(lafs, img)
- def forward(self, img: torch.Tensor, # type: ignore
- mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
+ def forward( # type: ignore
+ self,
+ img: torch.Tensor, # type: ignore
+ mask: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
"""Three stage local feature detection. First the location and scale of interest points are determined by
detect function. Then affine shape and orientation.
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 563792b64..3141f3856 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -26,8 +26,7 @@ def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
return kernel
-def get_sift_bin_ksize_stride_pad(patch_size: int,
- num_spatial_bins: int) -> Tuple:
+def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tuple:
"""Returns a tuple with SIFT parameters, given the patch size
and number of spatial bins.
@@ -43,10 +42,12 @@ def get_sift_bin_ksize_stride_pad(patch_size: int,
pad: int = ksize // 4
out_size: int = (patch_size + 2 * pad - (ksize - 1) - 1) // stride + 1
if out_size != num_spatial_bins:
- raise ValueError(f"Patch size {patch_size} is incompatible with \
+ raise ValueError(
+ f"Patch size {patch_size} is incompatible with \
requested number of spatial bins {num_spatial_bins} \
for SIFT descriptor. Usually it happens when patch size is too small\
- for num_spatial_bins specified")
+ for num_spatial_bins specified"
+ )
return ksize, stride, pad
@@ -83,13 +84,14 @@ class SIFTDescriptor(nn.Module):
', ' + 'rootsift=' + str(self.rootsift) +\
', ' + 'clipval=' + str(self.clipval) + ')'
- def __init__(self,
- patch_size: int = 41,
- num_ang_bins: int = 8,
- num_spatial_bins: int = 4,
- rootsift: bool = True,
- clipval: float = 0.2,
- ) -> None:
+ def __init__(
+ self,
+ patch_size: int = 41,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+ rootsift: bool = True,
+ clipval: float = 0.2,
+ ) -> None:
super(SIFTDescriptor, self).__init__()
self.eps = 1e-10
self.num_ang_bins = num_ang_bins
@@ -102,16 +104,17 @@ class SIFTDescriptor(nn.Module):
sigma: float = float(ks) / math.sqrt(2.0)
self.gk = get_gaussian_kernel2d((ks, ks), (sigma, sigma), True)
- (self.bin_ksize,
- self.bin_stride,
- self.pad) = get_sift_bin_ksize_stride_pad(patch_size,
- num_spatial_bins)
+ (self.bin_ksize, self.bin_stride, self.pad) = get_sift_bin_ksize_stride_pad(patch_size, num_spatial_bins)
nw = get_sift_pooling_kernel(ksize=self.bin_ksize).float()
- self.pk = nn.Conv2d(1, 1, kernel_size=(nw.size(0), nw.size(1)),
- stride=(self.bin_stride, self.bin_stride),
- padding=(self.pad, self.pad),
- bias=False)
+ self.pk = nn.Conv2d(
+ 1,
+ 1,
+ kernel_size=(nw.size(0), nw.size(1)),
+ stride=(self.bin_stride, self.bin_stride),
+ padding=(self.pad, self.pad),
+ bias=False
+ )
self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1))) # type: ignore # noqa
return
@@ -123,16 +126,15 @@ class SIFTDescriptor(nn.Module):
def forward(self, input):
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}".format(input.shape))
B, CH, W, H = input.size()
if (W != self.patch_size) or (H != self.patch_size) or (CH != 1):
raise TypeError(
"input shape should be must be [Bx1x{}x{}]. "
- "Got {}".format(self.patch_size, self.patch_size, input.size()))
+ "Got {}".format(self.patch_size, self.patch_size, input.size())
+ )
self.pk = self.pk.to(input.dtype).to(input.device)
grads: torch.Tensor = spatial_gradient(input, 'diff')
@@ -167,20 +169,17 @@ class SIFTDescriptor(nn.Module):
return ang_bins
-def sift_describe(input: torch.Tensor,
- patch_size: int = 41,
- num_ang_bins: int = 8,
- num_spatial_bins: int = 4,
- rootsift: bool = True,
- clipval: float = 0.2,
- ) -> torch.Tensor:
+def sift_describe(
+ input: torch.Tensor,
+ patch_size: int = 41,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+ rootsift: bool = True,
+ clipval: float = 0.2,
+) -> torch.Tensor:
r"""Computes the sift descriptor.
See :class:`~kornia.feature.SIFTDescriptor` for details.
"""
- return SIFTDescriptor(patch_size,
- num_ang_bins,
- num_spatial_bins,
- rootsift,
- clipval)(input)
+ return SIFTDescriptor(patch_size, num_ang_bins, num_spatial_bins, rootsift, clipval)(input)
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 049f08fd4..479f6c09f 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -54,14 +54,10 @@ class SOSNet(nn.Module):
nn.Conv2d(128, 128, kernel_size=8, bias=False),
nn.BatchNorm2d(128, affine=False),
)
- self.desc_norm = nn.Sequential(
- nn.LocalResponseNorm(256, alpha=256.0, beta=0.5, k=0.0)
- )
+ self.desc_norm = nn.Sequential(nn.LocalResponseNorm(256, alpha=256.0, beta=0.5, k=0.0))
# load pretrained model
if pretrained:
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['lib'], map_location=lambda storage, loc: storage
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['lib'], map_location=lambda storage, loc: storage)
self.load_state_dict(pretrained_dict, strict=True)
return
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index 8acb21d36..bdd279cd8 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -5,9 +5,12 @@ import torch.nn as nn
import torch.nn.functional as F
urls: Dict[str, str] = dict()
-urls["liberty"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # noqa pylint: disable
-urls["notredame"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params" # noqa pylint: disable
-urls["yosemite"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-yosemite.params" # noqa pylint: disable
+urls["liberty"
+ ] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # noqa pylint: disable
+urls["notredame"
+ ] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params" # noqa pylint: disable
+urls["yosemite"
+ ] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-yosemite.params" # noqa pylint: disable
class TFeat(nn.Module):
@@ -37,17 +40,10 @@ class TFeat(nn.Module):
def __init__(self, pretrained: bool = False) -> None:
super(TFeat, self).__init__()
self.features = nn.Sequential(
- nn.InstanceNorm2d(1, affine=False),
- nn.Conv2d(1, 32, kernel_size=7),
- nn.Tanh(),
- nn.MaxPool2d(kernel_size=2, stride=2),
- nn.Conv2d(32, 64, kernel_size=6),
- nn.Tanh()
- )
- self.descr = nn.Sequential(
- nn.Linear(64 * 8 * 8, 128),
- nn.Tanh()
+ nn.InstanceNorm2d(1, affine=False), nn.Conv2d(1, 32, kernel_size=7), nn.Tanh(),
+ nn.MaxPool2d(kernel_size=2, stride=2), nn.Conv2d(32, 64, kernel_size=6), nn.Tanh()
)
+ self.descr = nn.Sequential(nn.Linear(64 * 8 * 8, 128), nn.Tanh())
# use torch.hub to load pretrained model
if pretrained:
pretrained_dict = torch.hub.load_state_dict_from_url(
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 66747d8b2..1b7d9fd02 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -4,15 +4,15 @@ import torch
import torch.nn as nn
import kornia
-from kornia.filters.kernels import (
- get_box_kernel2d, normalize_kernel2d
-)
+from kornia.filters.kernels import (get_box_kernel2d, normalize_kernel2d)
-def box_blur(input: torch.Tensor,
- kernel_size: Tuple[int, int],
- border_type: str = 'reflect',
- normalized: bool = True) -> torch.Tensor:
+def box_blur(
+ input: torch.Tensor,
+ kernel_size: Tuple[int, int],
+ border_type: str = 'reflect',
+ normalized: bool = True
+) -> torch.Tensor:
r"""Blurs an image using the box filter.
The function smooths an image using the kernel:
@@ -85,9 +85,7 @@ class BoxBlur(nn.Module):
torch.Size([2, 4, 5, 7])
"""
- def __init__(self, kernel_size: Tuple[int, int],
- border_type: str = 'reflect',
- normalized: bool = True) -> None:
+ def __init__(self, kernel_size: Tuple[int, int], border_type: str = 'reflect', normalized: bool = True) -> None:
super(BoxBlur, self).__init__()
self.kernel_size: Tuple[int, int] = kernel_size
self.border_type: str = border_type
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 04a65f58c..daf567e50 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -56,8 +56,7 @@ class BlurPool2D(nn.Module):
def forward(self, input: torch.Tensor) -> torch.Tensor:
# To align the logic with the whole lib
kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
- return _blur_pool_by_kernel2d(
- input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride)
+ return _blur_pool_by_kernel2d(input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride)
class MaxBlurPool2D(nn.Module):
@@ -103,7 +102,8 @@ class MaxBlurPool2D(nn.Module):
# To align the logic with the whole lib
kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
return _max_blur_pool_by_kernel2d(
- input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride, self.max_pool_size, self.ceil_mode)
+ input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride, self.max_pool_size, self.ceil_mode
+ )
def blur_pool2d(input: torch.Tensor, kernel_size: int, stride: int = 2):
@@ -145,7 +145,11 @@ def blur_pool2d(input: torch.Tensor, kernel_size: int, stride: int = 2):
def max_blur_pool2d(
- input: torch.Tensor, kernel_size: int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False
+ input: torch.Tensor,
+ kernel_size: int,
+ stride: int = 2,
+ max_pool_size: int = 2,
+ ceil_mode: bool = False
) -> torch.Tensor:
r"""Compute pools and blurs and downsample a given feature map.
@@ -187,8 +191,7 @@ def _max_blur_pool_by_kernel2d(
assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2), \
f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"
# compute local maxima
- input = F.max_pool2d(
- input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)
+ input = F.max_pool2d(input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)
# blur and downsample
padding: Tuple[int, int] = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.size(1))
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 542ea70c3..c24f00947 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -29,9 +29,9 @@ def _compute_padding(kernel_size: List[int]) -> List[int]:
return out_padding
-def filter2D(input: torch.Tensor, kernel: torch.Tensor,
- border_type: str = 'reflect',
- normalized: bool = False) -> torch.Tensor:
+def filter2D(
+ input: torch.Tensor, kernel: torch.Tensor, border_type: str = 'reflect', normalized: bool = False
+) -> torch.Tensor:
r"""Convolve a tensor with a 2d kernel.
The function applies a given kernel to a tensor. The kernel is applied
@@ -69,24 +69,19 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,
[0., 0., 0., 0., 0.]]]])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input border_type is not torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input border_type is not torch.Tensor. Got {}".format(type(input)))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Input border_type is not torch.Tensor. Got {}"
- .format(type(kernel)))
+ raise TypeError("Input border_type is not torch.Tensor. Got {}".format(type(kernel)))
if not isinstance(border_type, str):
- raise TypeError("Input border_type is not string. Got {}"
- .format(type(kernel)))
+ raise TypeError("Input border_type is not string. Got {}".format(type(kernel)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
if not len(kernel.shape) == 3 and kernel.shape[0] != 1:
- raise ValueError("Invalid kernel shape, we expect 1xHxW. Got: {}"
- .format(kernel.shape))
+ raise ValueError("Invalid kernel shape, we expect 1xHxW. Got: {}".format(kernel.shape))
# prepare kernel
b, c, h, w = input.shape
@@ -112,9 +107,12 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,
return output.view(b, c, h, w)
-def filter3D(input: torch.Tensor, kernel: torch.Tensor,
- border_type: str = 'replicate',
- normalized: bool = False) -> torch.Tensor:
+def filter3D(
+ input: torch.Tensor,
+ kernel: torch.Tensor,
+ border_type: str = 'replicate',
+ normalized: bool = False
+) -> torch.Tensor:
r"""Convolve a tensor with a 3d kernel.
The function applies a given kernel to a tensor. The kernel is applied
@@ -175,24 +173,19 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,
[0., 0., 0., 0., 0.]]]]])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input border_type is not torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input border_type is not torch.Tensor. Got {}".format(type(input)))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Input border_type is not torch.Tensor. Got {}"
- .format(type(kernel)))
+ raise TypeError("Input border_type is not torch.Tensor. Got {}".format(type(kernel)))
if not isinstance(border_type, str):
- raise TypeError("Input border_type is not string. Got {}"
- .format(type(kernel)))
+ raise TypeError("Input border_type is not string. Got {}".format(type(kernel)))
if not len(input.shape) == 5:
- raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}".format(input.shape))
if not len(kernel.shape) == 4 and kernel.shape[0] != 1:
- raise ValueError("Invalid kernel shape, we expect 1xDxHxW. Got: {}"
- .format(kernel.shape))
+ raise ValueError("Invalid kernel shape, we expect 1xDxHxW. Got: {}".format(kernel.shape))
# prepare kernel
b, c, d, h, w = input.shape
@@ -200,8 +193,7 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,
if normalized:
bk, dk, hk, wk = kernel.shape
- tmp_kernel = normalize_kernel2d(tmp_kernel.view(
- bk, dk, hk * wk)).view_as(tmp_kernel)
+ tmp_kernel = normalize_kernel2d(tmp_kernel.view(bk, dk, hk * wk)).view_as(tmp_kernel)
tmp_kernel = tmp_kernel.expand(-1, c, -1, -1, -1)
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 5cad1a95b..c0dcb79a0 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -8,10 +8,11 @@ from kornia.filters.kernels import get_gaussian_kernel2d
def gaussian_blur2d(
- input: torch.Tensor,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect') -> torch.Tensor:
+ input: torch.Tensor,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = 'reflect'
+) -> torch.Tensor:
r"""Creates an operator that blurs a tensor using a Gaussian filter.
The operator smooths the given tensor with a gaussian kernel by convolving
@@ -34,8 +35,7 @@ def gaussian_blur2d(
>>> output.shape
torch.Size([2, 4, 5, 5])
"""
- kernel: torch.Tensor = torch.unsqueeze(
- get_gaussian_kernel2d(kernel_size, sigma), dim=0)
+ kernel: torch.Tensor = torch.unsqueeze(get_gaussian_kernel2d(kernel_size, sigma), dim=0)
return kornia.filter2D(input, kernel, border_type)
@@ -69,9 +69,7 @@ class GaussianBlur2d(nn.Module):
torch.Size([2, 4, 5, 5])
"""
- def __init__(self, kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect') -> None:
+ def __init__(self, kernel_size: Tuple[int, int], sigma: Tuple[float, float], border_type: str = 'reflect') -> None:
super(GaussianBlur2d, self).__init__()
self.kernel_size: Tuple[int, int] = kernel_size
self.sigma: Tuple[float, float] = sigma
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 19ef55e63..19eae4f82 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -11,8 +11,7 @@ def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:
r"""Normalizes both derivative and smoothing kernel.
"""
if len(input.size()) < 2:
- raise TypeError("input should be at least 2D tensor. Got {}"
- .format(input.size()))
+ raise TypeError("input should be at least 2D tensor. Got {}".format(input.size()))
norm: torch.Tensor = input.abs().sum(dim=-1).sum(dim=-1)
return input / (norm.unsqueeze(-1).unsqueeze(-1))
@@ -24,7 +23,7 @@ def gaussian(window_size: int, sigma: float) -> torch.Tensor:
x = torch.arange(window_size, device=device, dtype=dtype) - window_size // 2
if window_size % 2 == 0:
x = x + 0.5
- gauss = torch.exp((-x.pow(2.0) / (2 * sigma ** 2)))
+ gauss = torch.exp((-x.pow(2.0) / (2 * sigma**2)))
return gauss / gauss.sum()
@@ -53,9 +52,8 @@ def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:
ax = torch.abs(x)
y = 3.75 / ax
ans = 0.916281e-2 + y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1 + y * 0.392377e-2)))
- return (torch.exp(ax) / torch.sqrt(ax)) * (
- 0.39894228 + y * (0.1328592e-1 + y * (0.225319e-2 + y * (-0.157565e-2 + y * ans)))
- )
+ coef = (0.39894228 + y * (0.1328592e-1 + y * (0.225319e-2 + y * (-0.157565e-2 + y * ans))))
+ return (torch.exp(ax) / torch.sqrt(ax)) * coef
def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:
@@ -163,24 +161,22 @@ def get_sobel_kernel_3x3() -> torch.Tensor:
def get_sobel_kernel_5x5_2nd_order() -> torch.Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5"""
- return torch.tensor([
- [-1., 0., 2., 0., -1.],
- [-4., 0., 8., 0., -4.],
- [-6., 0., 12., 0., -6.],
- [-4., 0., 8., 0., -4.],
- [-1., 0., 2., 0., -1.]
- ])
+ return torch.tensor(
+ [
+ [-1., 0., 2., 0., -1.], [-4., 0., 8., 0., -4.], [-6., 0., 12., 0., -6.], [-4., 0., 8., 0., -4.],
+ [-1., 0., 2., 0., -1.]
+ ]
+ )
def _get_sobel_kernel_5x5_2nd_order_xy() -> torch.Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5"""
- return torch.tensor([
- [-1., -2., 0., 2., 1.],
- [-2., -4., 0., 4., 2.],
- [0., 0., 0., 0., 0.],
- [2., 4., 0., -4., -2.],
- [1., 2., 0., -2., -1.]
- ])
+ return torch.tensor(
+ [
+ [-1., -2., 0., 2., 1.], [-2., -4., 0., 4., 2.], [0., 0., 0., 0., 0.], [2., 4., 0., -4., -2.],
+ [1., 2., 0., -2., -1.]
+ ]
+ )
def get_diff_kernel_3x3() -> torch.Tensor:
@@ -194,121 +190,68 @@ def get_diff_kernel_3x3() -> torch.Tensor:
def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3"""
- kernel: torch.Tensor = torch.tensor([[[[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [-0.5, 0.0, 0.5],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
- ],
- [[[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, -0.5, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.5, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
- ],
- [[[0.0, 0.0, 0.0],
- [0.0, -0.5, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.5, 0.0],
- [0.0, 0.0, 0.0]],
- ],
- ], device=device, dtype=dtype)
+ kernel: torch.Tensor = torch.tensor(
+ [
+ [
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [-0.5, 0.0, 0.5], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ ],
+ [
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, -0.5, 0.0], [0.0, 0.0, 0.0], [0.0, 0.5, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ ],
+ [
+ [[0.0, 0.0, 0.0], [0.0, -0.5, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.0, 0.0]],
+ ],
+ ],
+ device=device,
+ dtype=dtype
+ )
return kernel.unsqueeze(1)
def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3"""
- kernel: torch.Tensor = torch.tensor([[[[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [1.0, -2.0, 1.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
- ],
- [[[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 1.0, 0.0],
- [0.0, -2.0, 0.0],
- [0.0, 1.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
- ],
- [[[0.0, 0.0, 0.0],
- [0.0, 1.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, -2.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 1.0, 0.0],
- [0.0, 0.0, 0.0]],
- ],
- [[[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[1.0, 0.0, -1.0],
- [0.0, 0.0, 0.0],
- [-1.0, 0.0, 1.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
- ],
- [[[0.0, 1.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, -1.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, -1.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 1.0, 0.0]],
- ],
- [[[0.0, 0.0, 0.0],
- [1.0, 0.0, -1.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0]],
-
- [[0.0, 0.0, 0.0],
- [-1.0, 0.0, 1.0],
- [0.0, 0.0, 0.0]],
- ],
- ], device=device, dtype=dtype)
+ kernel: torch.Tensor = torch.tensor(
+ [
+ [
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ ],
+ [
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 1.0, 0.0], [0.0, -2.0, 0.0], [0.0, 1.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ ],
+ [
+ [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, -2.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]],
+ ],
+ [
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[1.0, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, 1.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ ],
+ [
+ [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, -1.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, -1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
+ ],
+ [
+ [[0.0, 0.0, 0.0], [1.0, 0.0, -1.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [0.0, 0.0, 0.0]],
+ ],
+ ],
+ device=device,
+ dtype=dtype
+ )
return kernel.unsqueeze(1)
@@ -388,9 +331,7 @@ def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cp
return kernel
-def get_gaussian_kernel1d(kernel_size: int,
- sigma: float,
- force_even: bool = False) -> torch.Tensor:
+def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:
r"""Function that returns Gaussian filter coefficients.
Args:
@@ -412,20 +353,13 @@ def get_gaussian_kernel1d(kernel_size: int,
>>> get_gaussian_kernel1d(5, 1.5)
tensor([0.1201, 0.2339, 0.2921, 0.2339, 0.1201])
"""
- if (not isinstance(kernel_size, int) or (
- (kernel_size % 2 == 0) and not force_even) or (
- kernel_size <= 0)):
- raise TypeError(
- "kernel_size must be an odd positive integer. "
- "Got {}".format(kernel_size)
- )
+ if (not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0)):
+ raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))
window_1d: torch.Tensor = gaussian(kernel_size, sigma)
return window_1d
-def get_gaussian_discrete_kernel1d(kernel_size: int,
- sigma: float,
- force_even: bool = False) -> torch.Tensor:
+def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:
r"""Function that returns Gaussian filter coefficients
based on the modified Bessel functions. Adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
@@ -449,20 +383,13 @@ def get_gaussian_discrete_kernel1d(kernel_size: int,
>>> get_gaussian_discrete_kernel1d(5, 1.5)
tensor([0.1096, 0.2323, 0.3161, 0.2323, 0.1096])
"""
- if (not isinstance(kernel_size, int) or (
- (kernel_size % 2 == 0) and not force_even) or (
- kernel_size <= 0)):
- raise TypeError(
- "kernel_size must be an odd positive integer. "
- "Got {}".format(kernel_size)
- )
+ if (not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0)):
+ raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))
window_1d = gaussian_discrete(kernel_size, sigma)
return window_1d
-def get_gaussian_erf_kernel1d(kernel_size: int,
- sigma: float,
- force_even: bool = False) -> torch.Tensor:
+def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:
r"""Function that returns Gaussian filter coefficients by interpolating the error fucntion,
adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
@@ -486,21 +413,15 @@ def get_gaussian_erf_kernel1d(kernel_size: int,
>>> get_gaussian_erf_kernel1d(5, 1.5)
tensor([0.1226, 0.2331, 0.2887, 0.2331, 0.1226])
"""
- if (not isinstance(kernel_size, int) or (
- (kernel_size % 2 == 0) and not force_even) or (
- kernel_size <= 0)):
- raise TypeError(
- "kernel_size must be an odd positive integer. "
- "Got {}".format(kernel_size)
- )
+ if (not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0)):
+ raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))
window_1d = gaussian_discrete_erf(kernel_size, sigma)
return window_1d
def get_gaussian_kernel2d(
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- force_even: bool = False) -> torch.Tensor:
+ kernel_size: Tuple[int, int], sigma: Tuple[float, float], force_even: bool = False
+) -> torch.Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
@@ -527,22 +448,14 @@ def get_gaussian_kernel2d(
[0.0370, 0.0720, 0.0899, 0.0720, 0.0370]])
"""
if not isinstance(kernel_size, tuple) or len(kernel_size) != 2:
- raise TypeError(
- "kernel_size must be a tuple of length two. Got {}".format(
- kernel_size
- )
- )
+ raise TypeError("kernel_size must be a tuple of length two. Got {}".format(kernel_size))
if not isinstance(sigma, tuple) or len(sigma) != 2:
- raise TypeError(
- "sigma must be a tuple of length two. Got {}".format(sigma)
- )
+ raise TypeError("sigma must be a tuple of length two. Got {}".format(sigma))
ksize_x, ksize_y = kernel_size
sigma_x, sigma_y = sigma
kernel_x: torch.Tensor = get_gaussian_kernel1d(ksize_x, sigma_x, force_even)
kernel_y: torch.Tensor = get_gaussian_kernel1d(ksize_y, sigma_y, force_even)
- kernel_2d: torch.Tensor = torch.matmul(
- kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t()
- )
+ kernel_2d: torch.Tensor = torch.matmul(kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t())
return kernel_2d
@@ -567,8 +480,7 @@ def get_laplacian_kernel1d(kernel_size: int) -> torch.Tensor:
"""
if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \
kernel_size <= 0:
- raise TypeError("ksize must be an odd positive integer. Got {}"
- .format(kernel_size))
+ raise TypeError("ksize must be an odd positive integer. Got {}".format(kernel_size))
window_1d: torch.Tensor = laplacian_1d(kernel_size)
return window_1d
@@ -599,18 +511,21 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:
"""
if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \
kernel_size <= 0:
- raise TypeError("ksize must be an odd positive integer. Got {}"
- .format(kernel_size))
+ raise TypeError("ksize must be an odd positive integer. Got {}".format(kernel_size))
kernel = torch.ones((kernel_size, kernel_size))
mid = kernel_size // 2
- kernel[mid, mid] = 1 - kernel_size ** 2
+ kernel[mid, mid] = 1 - kernel_size**2
kernel_2d: torch.Tensor = kernel
return kernel_2d
-def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],
- direction: Union[torch.Tensor, float] = 0., mode: str = 'nearest') -> torch.Tensor:
+def get_motion_kernel2d(
+ kernel_size: int,
+ angle: Union[torch.Tensor, float],
+ direction: Union[torch.Tensor, float] = 0.,
+ mode: str = 'nearest'
+) -> torch.Tensor:
r"""Return 2D motion blur filter.
Args:
@@ -641,10 +556,12 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],
[0.0000, 0.3333, 0.0000],
[0.5000, 0.0000, 0.0000]]])
"""
- device, dtype = _extract_device_dtype([
- angle if isinstance(angle, torch.Tensor) else None,
- direction if isinstance(direction, torch.Tensor) else None,
- ])
+ device, dtype = _extract_device_dtype(
+ [
+ angle if isinstance(angle, torch.Tensor) else None,
+ direction if isinstance(direction, torch.Tensor) else None,
+ ]
+ )
if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size < 3:
raise TypeError("ksize must be an odd integer >= than 3")
@@ -679,8 +596,7 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],
# Alternatively
# m = ((1 - 2 * direction)[:, None].repeat(1, kernel_size) / (kernel_size - 1))
# kernel[:, kernel_size // 2, :] = direction[:, None].repeat(1, kernel_size) + m * torch.arange(0, kernel_size)
- k = torch.stack(
- [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
+ k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
kernel = torch.nn.functional.pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])
assert kernel.shape == torch.Size([direction.size(0), *kernel_tuple])
kernel = kernel.unsqueeze(1)
@@ -691,8 +607,12 @@ def get_motion_kernel2d(kernel_size: int, angle: Union[torch.Tensor, float],
return kernel
-def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[float, float, float]],
- direction: Union[torch.Tensor, float] = 0., mode: str = 'nearest') -> torch.Tensor:
+def get_motion_kernel3d(
+ kernel_size: int,
+ angle: Union[torch.Tensor, Tuple[float, float, float]],
+ direction: Union[torch.Tensor, float] = 0.,
+ mode: str = 'nearest'
+) -> torch.Tensor:
r"""Return 3D motion blur filter.
Args:
@@ -742,10 +662,12 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[float
if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size < 3:
raise TypeError(f"ksize must be an odd integer >= than 3. Got {kernel_size}.")
- device, dtype = _extract_device_dtype([
- angle if isinstance(angle, torch.Tensor) else None,
- direction if isinstance(direction, torch.Tensor) else None,
- ])
+ device, dtype = _extract_device_dtype(
+ [
+ angle if isinstance(angle, torch.Tensor) else None,
+ direction if isinstance(direction, torch.Tensor) else None,
+ ]
+ )
if not isinstance(angle, torch.Tensor):
angle = torch.tensor([angle], device=device, dtype=dtype)
@@ -774,10 +696,10 @@ def get_motion_kernel3d(kernel_size: int, angle: Union[torch.Tensor, Tuple[float
# Element-wise linspace
# kernel[:, kernel_size // 2, kernel_size // 2, :] = torch.stack(
# [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
- k = torch.stack(
- [(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
+ k = torch.stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], dim=-1)
kernel = torch.nn.functional.pad(
- k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0])
+ k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0]
+ )
assert kernel.shape == torch.Size([direction.size(0), *kernel_tuple])
kernel = kernel.unsqueeze(1)
# rotate (counterclockwise) kernel by given angle
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index 50f11135d..039ea0ff0 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -9,10 +9,8 @@ from kornia.filters.kernels import normalize_kernel2d
def laplacian(
- input: torch.Tensor,
- kernel_size: int,
- border_type: str = 'reflect',
- normalized: bool = True) -> torch.Tensor:
+ input: torch.Tensor, kernel_size: int, border_type: str = 'reflect', normalized: bool = True
+) -> torch.Tensor:
r"""Creates an operator that returns a tensor using a Laplacian filter.
The operator smooths the given tensor with a laplacian kernel by convolving
@@ -35,8 +33,7 @@ def laplacian(
>>> output.shape
torch.Size([2, 4, 5, 5])
"""
- kernel: torch.Tensor = torch.unsqueeze(
- get_laplacian_kernel2d(kernel_size), dim=0)
+ kernel: torch.Tensor = torch.unsqueeze(get_laplacian_kernel2d(kernel_size), dim=0)
if normalized:
kernel = normalize_kernel2d(kernel)
@@ -69,9 +66,7 @@ class Laplacian(nn.Module):
torch.Size([2, 4, 5, 5])
"""
- def __init__(self,
- kernel_size: int, border_type: str = 'reflect',
- normalized: bool = True) -> None:
+ def __init__(self, kernel_size: int, border_type: str = 'reflect', normalized: bool = True) -> None:
super(Laplacian, self).__init__()
self.kernel_size: int = kernel_size
self.border_type: str = border_type
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 443b15f7a..8a7e26be6 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -13,8 +13,7 @@ def _compute_zero_padding(kernel_size: Tuple[int, int]) -> Tuple[int, int]:
return computed[0], computed[1]
-def median_blur(input: torch.Tensor,
- kernel_size: Tuple[int, int]) -> torch.Tensor:
+def median_blur(input: torch.Tensor, kernel_size: Tuple[int, int]) -> torch.Tensor:
r"""Blurs an image using the median filter.
Args:
@@ -31,12 +30,10 @@ def median_blur(input: torch.Tensor,
torch.Size([2, 4, 5, 7])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
padding: Tuple[int, int] = _compute_zero_padding(kernel_size)
@@ -45,8 +42,7 @@ def median_blur(input: torch.Tensor,
b, c, h, w = input.shape
# map the local window to single vector
- features: torch.Tensor = F.conv2d(
- input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
+ features: torch.Tensor = F.conv2d(input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
features = features.view(b, c, -1, h, w) # BxCx(K_h * K_w)xHxW
# compute the median along the feature axis
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index aa3a283c8..dd06e6802 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -4,9 +4,7 @@ import torch
import torch.nn as nn
import kornia
-from kornia.filters.kernels import (
- get_motion_kernel2d, get_motion_kernel3d
-)
+from kornia.filters.kernels import (get_motion_kernel2d, get_motion_kernel3d)
class MotionBlur(nn.Module):
@@ -35,9 +33,7 @@ class MotionBlur(nn.Module):
>>> output = motion_blur(input) # 2x4x5x7
"""
- def __init__(
- self, kernel_size: int, angle: float, direction: float, border_type: str = 'constant'
- ) -> None:
+ def __init__(self, kernel_size: int, angle: float, direction: float, border_type: str = 'constant') -> None:
super(MotionBlur, self).__init__()
self.kernel_size = kernel_size
self.angle: float = angle
@@ -79,8 +75,11 @@ class MotionBlur3D(nn.Module):
"""
def __init__(
- self, kernel_size: int, angle: Union[float, Tuple[float, float, float]],
- direction: float, border_type: str = 'constant'
+ self,
+ kernel_size: int,
+ angle: Union[float, Tuple[float, float, float]],
+ direction: float,
+ border_type: str = 'constant'
) -> None:
super(MotionBlur3D, self).__init__()
self.kernel_size = kernel_size
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index eafd5902e..26814f3c7 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -2,15 +2,10 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.filters.kernels import (
- get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
-)
+from kornia.filters.kernels import (get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d)
-def spatial_gradient(input: torch.Tensor,
- mode: str = 'sobel',
- order: int = 1,
- normalized: bool = True) -> torch.Tensor:
+def spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> torch.Tensor:
r"""Computes the first order image derivative in both x and y using a Sobel
operator.
@@ -30,12 +25,10 @@ def spatial_gradient(input: torch.Tensor,
torch.Size([1, 3, 2, 4, 4])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
# allocate kernel
kernel: torch.Tensor = get_spatial_gradient_kernel2d(mode, order)
if normalized:
@@ -50,22 +43,14 @@ def spatial_gradient(input: torch.Tensor,
kernel_flip: torch.Tensor = tmp_kernel.flip(-3)
# Pad with "replicate for spatial dims, but with zeros for channel
- spatial_pad = [
- kernel.size(1) // 2,
- kernel.size(1) // 2,
- kernel.size(2) // 2,
- kernel.size(2) // 2
- ]
+ spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2]
out_channels: int = 3 if order == 2 else 2
- padded_inp: torch.Tensor = F.pad(
- input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')[:, :, None]
+ padded_inp: torch.Tensor = F.pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')[:, :, None]
return F.conv3d(padded_inp, kernel_flip, padding=0).view(b, c, out_channels, h, w)
-def spatial_gradient3d(input: torch.Tensor,
- mode: str = 'diff',
- order: int = 1) -> torch.Tensor:
+def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1) -> torch.Tensor:
r"""Computes the first and second order volume derivative in x, y and d using a diff
operator.
@@ -88,12 +73,10 @@ def spatial_gradient3d(input: torch.Tensor,
torch.Size([1, 4, 3, 2, 4, 4])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 5:
- raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}".format(input.shape))
# allocate kernel
kernel: torch.Tensor = get_spatial_gradient_kernel3d(mode, order)
@@ -115,8 +98,8 @@ def spatial_gradient3d(input: torch.Tensor,
kernel.size(4) // 2
]
out_ch: int = 6 if order == 2 else 3
- return F.conv3d(F.pad(
- input, spatial_pad, 'replicate'), kernel_flip, padding=0, groups=c).view(b, c, out_ch, d, h, w)
+ return F.conv3d(F.pad(input, spatial_pad, 'replicate'), kernel_flip, padding=0,
+ groups=c).view(b, c, out_ch, d, h, w)
def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> torch.Tensor:
@@ -137,12 +120,10 @@ def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> to
torch.Size([1, 3, 4, 4])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
# comput the x/y gradients
edges: torch.Tensor = spatial_gradient(input, normalized=normalized)
@@ -178,10 +159,7 @@ class SpatialGradient(nn.Module):
>>> output = SpatialGradient()(input) # 1x3x2x4x4
"""
- def __init__(self,
- mode: str = 'sobel',
- order: int = 1,
- normalized: bool = True) -> None:
+ def __init__(self, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> None:
super(SpatialGradient, self).__init__()
self.normalized: bool = normalized
self.order: int = order
@@ -219,9 +197,7 @@ class SpatialGradient3d(nn.Module):
torch.Size([1, 4, 3, 2, 4, 4])
"""
- def __init__(self,
- mode: str = 'diff',
- order: int = 1) -> None:
+ def __init__(self, mode: str = 'diff', order: int = 1) -> None:
super(SpatialGradient3d, self).__init__()
self.order: int = order
self.mode: str = mode
@@ -256,8 +232,7 @@ class Sobel(nn.Module):
>>> output = Sobel()(input) # 1x3x4x4
"""
- def __init__(self,
- normalized: bool = True, eps: float = 1e-6) -> None:
+ def __init__(self, normalized: bool = True, eps: float = 1e-6) -> None:
super(Sobel, self).__init__()
self.normalized: bool = normalized
self.eps: float = eps
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index d8bcbb433..57fbfb187 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -8,10 +8,11 @@ from kornia.filters import gaussian_blur2d
def unsharp_mask(
- input: torch.Tensor,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect') -> torch.Tensor:
+ input: torch.Tensor,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = 'reflect'
+) -> torch.Tensor:
r"""Creates an operator that blurs a tensor using the existing Gaussian filter available with the Kornia library.
Arguments:
@@ -62,9 +63,7 @@ class UnsharpMask(nn.Module):
torch.Size([2, 4, 5, 5])
"""
- def __init__(self, kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect') -> None:
+ def __init__(self, kernel_size: Tuple[int, int], sigma: Tuple[float, float], border_type: str = 'reflect') -> None:
super(UnsharpMask, self).__init__()
self.kernel_size: Tuple[int, int] = kernel_size
self.sigma: Tuple[float, float] = sigma
diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.py
index 1ace28383..826614959 100644
--- a/kornia/geometry/camera/perspective.py
+++ b/kornia/geometry/camera/perspective.py
@@ -4,14 +4,10 @@ import torch
import torch.nn.functional as F
from kornia.geometry.linalg import transform_points
-from kornia.geometry.conversions import (
- convert_points_to_homogeneous, convert_points_from_homogeneous
-)
+from kornia.geometry.conversions import (convert_points_to_homogeneous, convert_points_from_homogeneous)
-def project_points(
- point_3d: torch.Tensor,
- camera_matrix: torch.Tensor) -> torch.Tensor:
+def project_points(point_3d: torch.Tensor, camera_matrix: torch.Tensor) -> torch.Tensor:
r"""Projects a 3d point onto the 2d camera plane.
Args:
@@ -24,23 +20,19 @@ def project_points(
torch.Tensor: array of (u, v) cam coordinates with shape :math:`(*, 2)`.
"""
if not isinstance(point_3d, torch.Tensor):
- raise TypeError("Input point_3d type is not a torch.Tensor. Got {}"
- .format(type(point_3d)))
+ raise TypeError("Input point_3d type is not a torch.Tensor. Got {}".format(type(point_3d)))
if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError("Input camera_matrix type is not a torch.Tensor. Got {}"
- .format(type(camera_matrix)))
+ raise TypeError("Input camera_matrix type is not a torch.Tensor. Got {}".format(type(camera_matrix)))
if not (point_3d.device == camera_matrix.device):
raise ValueError("Input tensors must be all in the same device.")
if not point_3d.shape[-1] == 3:
- raise ValueError("Input points_3d must be in the shape of (*, 3)."
- " Got {}".format(point_3d.shape))
+ raise ValueError("Input points_3d must be in the shape of (*, 3)." " Got {}".format(point_3d.shape))
if not camera_matrix.shape[-2:] == (3, 3):
- raise ValueError(
- "Input camera_matrix must be in the shape of (*, 3, 3).")
+ raise ValueError("Input camera_matrix must be in the shape of (*, 3, 3).")
# projection eq. [u, v, w]' = K * [x y z 1]'
# u = fx * X / Z + cx
@@ -65,10 +57,8 @@ def project_points(
def unproject_points(
- point_2d: torch.Tensor,
- depth: torch.Tensor,
- camera_matrix: torch.Tensor,
- normalize: bool = False) -> torch.Tensor:
+ point_2d: torch.Tensor, depth: torch.Tensor, camera_matrix: torch.Tensor, normalize: bool = False
+) -> torch.Tensor:
r"""Unprojects a 2d point in 3d.
Transform coordinates in the pixel frame to the camera frame.
@@ -89,31 +79,25 @@ def unproject_points(
:math:`(*, 3)`.
"""
if not isinstance(point_2d, torch.Tensor):
- raise TypeError("Input point_2d type is not a torch.Tensor. Got {}"
- .format(type(point_2d)))
+ raise TypeError("Input point_2d type is not a torch.Tensor. Got {}".format(type(point_2d)))
if not isinstance(depth, torch.Tensor):
- raise TypeError("Input depth type is not a torch.Tensor. Got {}"
- .format(type(depth)))
+ raise TypeError("Input depth type is not a torch.Tensor. Got {}".format(type(depth)))
if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError("Input camera_matrix type is not a torch.Tensor. Got {}"
- .format(type(camera_matrix)))
+ raise TypeError("Input camera_matrix type is not a torch.Tensor. Got {}".format(type(camera_matrix)))
if not (point_2d.device == depth.device == camera_matrix.device):
raise ValueError("Input tensors must be all in the same device.")
if not point_2d.shape[-1] == 2:
- raise ValueError("Input points_2d must be in the shape of (*, 2)."
- " Got {}".format(point_2d.shape))
+ raise ValueError("Input points_2d must be in the shape of (*, 2)." " Got {}".format(point_2d.shape))
if not depth.shape[-1] == 1:
- raise ValueError("Input depth must be in the shape of (*, 1)."
- " Got {}".format(depth.shape))
+ raise ValueError("Input depth must be in the shape of (*, 1)." " Got {}".format(depth.shape))
if not camera_matrix.shape[-2:] == (3, 3):
- raise ValueError(
- "Input camera_matrix must be in the shape of (*, 3, 3).")
+ raise ValueError("Input camera_matrix must be in the shape of (*, 3, 3).")
# projection eq. K_inv * [u v 1]'
# x = (u - cx) * Z / fx
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index c3244f5d7..cb3b8cee0 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -26,10 +26,9 @@ class PinholeCamera:
advantage of PyTorch parallelism to boost computing performance.
"""
- def __init__(self, intrinsics: torch.Tensor,
- extrinsics: torch.Tensor,
- height: torch.Tensor,
- width: torch.Tensor) -> None:
+ def __init__(
+ self, intrinsics: torch.Tensor, extrinsics: torch.Tensor, height: torch.Tensor, width: torch.Tensor
+ ) -> None:
# verify batch size and shapes
self._check_valid([intrinsics, extrinsics, height, width])
self._check_valid_params(intrinsics, "intrinsics")
@@ -49,22 +48,24 @@ class PinholeCamera:
return True
@staticmethod
- def _check_valid_params(
- data: torch.Tensor,
- data_name: str) -> bool:
- if len(data.shape) not in (3, 4,) and data.shape[-2:] != (4, 4): # Shouldn't this be an OR logic than AND?
- raise ValueError("Argument {0} shape must be in the following shape"
- " Bx4x4 or BxNx4x4. Got {1}".format(data_name,
- data.shape))
+ def _check_valid_params(data: torch.Tensor, data_name: str) -> bool:
+ if len(data.shape) not in (
+ 3,
+ 4,
+ ) and data.shape[-2:] != (4, 4): # Shouldn't this be an OR logic than AND?
+ raise ValueError(
+ "Argument {0} shape must be in the following shape"
+ " Bx4x4 or BxNx4x4. Got {1}".format(data_name, data.shape)
+ )
return True
@staticmethod
- def _check_valid_shape(
- data: torch.Tensor,
- data_name: str) -> bool:
+ def _check_valid_shape(data: torch.Tensor, data_name: str) -> bool:
if not len(data.shape) == 1:
- raise ValueError("Argument {0} shape must be in the following shape"
- " B. Got {1}".format(data_name, data.shape))
+ raise ValueError(
+ "Argument {0} shape must be in the following shape"
+ " B. Got {1}".format(data_name, data.shape)
+ )
return True
@property
@@ -281,19 +282,20 @@ class PinholeCamera:
# NOTE: just for test. Decide if we keep it.
@classmethod
def from_parameters(
- self,
- fx,
- fy,
- cx,
- cy,
- height,
- width,
- tx,
- ty,
- tz,
- batch_size=1,
- device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None):
+ self,
+ fx,
+ fy,
+ cx,
+ cy,
+ height,
+ width,
+ tx,
+ ty,
+ tz,
+ batch_size=1,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None
+ ):
# create the camera matrix
intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
intrinsics[..., 0, 0] += fx
@@ -335,19 +337,18 @@ class PinholeCamerasList(PinholeCamera):
def __init__(self, pinholes_list: Iterable[PinholeCamera]) -> None:
self._initialize_parameters(pinholes_list)
- def _initialize_parameters(
- self,
- pinholes: Iterable[PinholeCamera]) -> 'PinholeCamerasList':
+ def _initialize_parameters(self, pinholes: Iterable[PinholeCamera]) -> 'PinholeCamerasList':
r"""Initialises the class attributes given a cameras list."""
- if not isinstance(pinholes, (list, tuple,)):
- raise TypeError("pinhole must of type list or tuple. Got {}"
- .format(type(pinholes)))
+ if not isinstance(pinholes, (
+ list,
+ tuple,
+ )):
+ raise TypeError("pinhole must of type list or tuple. Got {}".format(type(pinholes)))
height, width = [], []
intrinsics, extrinsics = [], []
for pinhole in pinholes:
if not isinstance(pinhole, PinholeCamera):
- raise TypeError("Argument pinhole must be from type "
- "PinholeCamera. Got {}".format(type(pinhole)))
+ raise TypeError("Argument pinhole must be from type " "PinholeCamera. Got {}".format(type(pinhole)))
height.append(pinhole.height)
width.append(pinhole.width)
intrinsics.append(pinhole.intrinsics)
@@ -553,23 +554,19 @@ def homography_i_H_ref(pinhole_i, pinhole_ref):
homography_i_H_ref(pinhole_i, pinhole_ref) # Nx4x4
"""
# TODO: Add doctest once having `rtvec_to_pose`.
- assert len(
- pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12, pinhole.shape
+ assert len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12, pinhole.shape
assert pinhole_i.shape == pinhole_ref.shape, pinhole_ref.shape
i_pose_base = get_optical_pose_base(pinhole_i)
ref_pose_base = get_optical_pose_base(pinhole_ref)
- i_pose_ref = torch.matmul(i_pose_base,
- inverse_transformation(ref_pose_base))
- return torch.matmul(
- pinhole_matrix(pinhole_i),
- torch.matmul(i_pose_ref, inverse_pinhole_matrix(pinhole_ref)))
+ i_pose_ref = torch.matmul(i_pose_base, inverse_transformation(ref_pose_base))
+ return torch.matmul(pinhole_matrix(pinhole_i), torch.matmul(i_pose_ref, inverse_pinhole_matrix(pinhole_ref)))
+
# based on:
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L26
-def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,
- pixel_coords: torch.Tensor) -> torch.Tensor:
+def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: torch.Tensor) -> torch.Tensor:
r"""Transform coordinates in the pixel frame to the camera frame.
Args:
@@ -583,26 +580,20 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,
torch.Tensor: array of (u, v, 1) cam coordinates with shape BxHxWx3.
"""
if not len(depth.shape) == 4 and depth.shape[1] == 1:
- raise ValueError("Input depth has to be in the shape of "
- "Bx1xHxW. Got {}".format(depth.shape))
+ raise ValueError("Input depth has to be in the shape of " "Bx1xHxW. Got {}".format(depth.shape))
if not len(intrinsics_inv.shape) == 3:
- raise ValueError("Input intrinsics_inv has to be in the shape of "
- "Bx4x4. Got {}".format(intrinsics_inv.shape))
+ raise ValueError("Input intrinsics_inv has to be in the shape of " "Bx4x4. Got {}".format(intrinsics_inv.shape))
if not len(pixel_coords.shape) == 4 and pixel_coords.shape[3] == 3:
- raise ValueError("Input pixel_coords has to be in the shape of "
- "BxHxWx3. Got {}".format(intrinsics_inv.shape))
- cam_coords: torch.Tensor = transform_points(
- intrinsics_inv[:, None], pixel_coords)
+ raise ValueError("Input pixel_coords has to be in the shape of " "BxHxWx3. Got {}".format(intrinsics_inv.shape))
+ cam_coords: torch.Tensor = transform_points(intrinsics_inv[:, None], pixel_coords)
return cam_coords * depth.permute(0, 2, 3, 1)
# based on
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43
-def cam2pixel(
- cam_coords_src: torch.Tensor,
- dst_proj_src: torch.Tensor,
- eps: Optional[float] = 1e-6) -> torch.Tensor:
+
+def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: Optional[float] = 1e-6) -> torch.Tensor:
r"""Transform coordinates in the camera frame to the pixel frame.
Args:
@@ -615,15 +606,15 @@ def cam2pixel(
torch.Tensor: array of [-1, 1] coordinates of shape BxHxWx2.
"""
if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:
- raise ValueError("Input cam_coords_src has to be in the shape of "
- "BxHxWx3. Got {}".format(cam_coords_src.shape))
+ raise ValueError(
+ "Input cam_coords_src has to be in the shape of "
+ "BxHxWx3. Got {}".format(cam_coords_src.shape)
+ )
if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4):
- raise ValueError("Input dst_proj_src has to be in the shape of "
- "Bx4x4. Got {}".format(dst_proj_src.shape))
+ raise ValueError("Input dst_proj_src has to be in the shape of " "Bx4x4. Got {}".format(dst_proj_src.shape))
b, h, w, _ = cam_coords_src.shape
# apply projection matrix to points
- point_coords: torch.Tensor = transform_points(
- dst_proj_src[:, None], cam_coords_src)
+ point_coords: torch.Tensor = transform_points(dst_proj_src[:, None], cam_coords_src)
x_coord: torch.Tensor = point_coords[..., 0]
y_coord: torch.Tensor = point_coords[..., 1]
z_coord: torch.Tensor = point_coords[..., 2]
@@ -638,8 +629,6 @@ def cam2pixel(
# layer api
-
-
'''class PinholeMatrix(nn.Module):
r"""Creates an object that returns the pinhole matrix from a pinhole model
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 3abbac627..f7d54c9ff 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -52,8 +52,7 @@ def rad2deg(tensor: torch.Tensor) -> torch.Tensor:
>>> output = rad2deg(input)
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
return 180. * tensor / pi.to(tensor.device).type(tensor.dtype)
@@ -73,8 +72,7 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:
>>> output = deg2rad(input)
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.
@@ -95,16 +93,14 @@ def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.
>>> x, y = pol2cart(rho, phi)
"""
if not (isinstance(rho, torch.Tensor) & isinstance(phi, torch.Tensor)):
- raise TypeError("Input type is not a torch.Tensor. Got {}, {}".format(
- type(rho), type(phi)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}, {}".format(type(rho), type(phi)))
x = rho * torch.cos(phi)
y = rho * torch.sin(phi)
return x, y
-def cart2pol(x: torch.Tensor, y: torch.Tensor,
- eps: float = 1.e-8) -> Tuple[torch.Tensor, torch.Tensor]:
+def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.e-8) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function that converts cartesian coordinates to polar coordinates.
Args:
@@ -121,16 +117,14 @@ def cart2pol(x: torch.Tensor, y: torch.Tensor,
>>> rho, phi = cart2pol(x, y)
"""
if not (isinstance(x, torch.Tensor) & isinstance(y, torch.Tensor)):
- raise TypeError("Input type is not a torch.Tensor. Got {}, {}".format(
- type(x), type(y)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}, {}".format(type(x), type(y)))
rho = torch.sqrt(x**2 + y**2 + eps)
phi = torch.atan2(y, x)
return rho, phi
-def convert_points_from_homogeneous(
- points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
+def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Function that converts points from homogeneous to Euclidean space.
Examples::
@@ -139,12 +133,10 @@ def convert_points_from_homogeneous(
>>> output = convert_points_from_homogeneous(input) # BxNx2
"""
if not isinstance(points, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(points)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(points)))
if len(points.shape) < 2:
- raise ValueError("Input must be at least a 2D tensor. Got {}".format(
- points.shape))
+ raise ValueError("Input must be at least a 2D tensor. Got {}".format(points.shape))
# we check for points at infinity
z_vec: torch.Tensor = points[..., -1:]
@@ -167,11 +159,9 @@ def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:
>>> output = convert_points_to_homogeneous(input) # BxNx4
"""
if not isinstance(points, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(points)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(points)))
if len(points.shape) < 2:
- raise ValueError("Input must be at least a 2D tensor. Got {}".format(
- points.shape))
+ raise ValueError("Input must be at least a 2D tensor. Got {}".format(points.shape))
return torch.nn.functional.pad(points, [0, 1], "constant", 1.0)
@@ -191,11 +181,9 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:
>>> output = convert_affinematrix_to_homography(input) # Bx3x3
"""
if not isinstance(A, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(A)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(A)))
if not (len(A.shape) == 3 and A.shape[-2:] == (2, 3)):
- raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}"
- .format(A.shape))
+ raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}".format(A.shape))
return _convert_affinematrix_to_homography_impl(A)
@@ -208,11 +196,9 @@ def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
>>> output = convert_affinematrix_to_homography3d(input) # Bx4x4
"""
if not isinstance(A, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(A)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(A)))
if not (len(A.shape) == 3 and A.shape[-2:] == (3, 4)):
- raise ValueError("Input matrix must be a Bx3x4 tensor. Got {}"
- .format(A.shape))
+ raise ValueError("Input matrix must be a Bx3x4 tensor. Got {}".format(A.shape))
return _convert_affinematrix_to_homography_impl(A)
@@ -234,13 +220,10 @@ def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:
>>> output = angle_axis_to_rotation_matrix(input) # Nx3x3
"""
if not isinstance(angle_axis, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(angle_axis)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(angle_axis)))
if not angle_axis.shape[-1] == 3:
- raise ValueError(
- "Input size must be a (*, 3) tensor. Got {}".format(
- angle_axis.shape))
+ raise ValueError("Input size must be a (*, 3) tensor. Got {}".format(angle_axis.shape))
def _compute_rotation_matrix(angle_axis, theta2, eps=1e-6):
# We want to be careful to only evaluate the square root if the
@@ -262,15 +245,13 @@ def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:
r02 = wy * sin_theta + wx * wz * (k_one - cos_theta)
r12 = -wx * sin_theta + wy * wz * (k_one - cos_theta)
r22 = cos_theta + wz * wz * (k_one - cos_theta)
- rotation_matrix = torch.cat(
- [r00, r01, r02, r10, r11, r12, r20, r21, r22], dim=1)
+ rotation_matrix = torch.cat([r00, r01, r02, r10, r11, r12, r20, r21, r22], dim=1)
return rotation_matrix.view(-1, 3, 3)
def _compute_rotation_matrix_taylor(angle_axis):
rx, ry, rz = torch.chunk(angle_axis, 3, dim=1)
k_one = torch.ones_like(rx)
- rotation_matrix = torch.cat(
- [k_one, -rz, ry, rz, k_one, -rx, -ry, rx, k_one], dim=1)
+ rotation_matrix = torch.cat([k_one, -rz, ry, rz, k_one, -rx, -ry, rx, k_one], dim=1)
return rotation_matrix.view(-1, 3, 3)
# stolen from ceres/rotation.h
@@ -321,15 +302,15 @@ def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensor
if not rotation_matrix.shape[-2:] == (3, 3):
raise ValueError(f"Input size must be a (*, 3, 3) tensor. Got {rotation_matrix.shape}")
- quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion: torch.Tensor = rotation_matrix_to_quaternion(rotation_matrix, order=QuaternionCoeffOrder.WXYZ)
return quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
def rotation_matrix_to_quaternion(
- rotation_matrix: torch.Tensor,
- eps: float = 1.e-8,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
+ rotation_matrix: torch.Tensor,
+ eps: float = 1.e-8,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to 4d quaternion vector.
The quaternion vector has components in (w, x, y, z) or (x, y, z, w) format.
@@ -366,20 +347,19 @@ def rotation_matrix_to_quaternion(
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
- warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
- " will be removed after > 0.6. "
- "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+ warnings.warn(
+ "`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead."
+ )
- def safe_zero_division(numerator: torch.Tensor,
- denominator: torch.Tensor) -> torch.Tensor:
+ def safe_zero_division(numerator: torch.Tensor, denominator: torch.Tensor) -> torch.Tensor:
eps: float = torch.finfo(numerator.dtype).tiny # type: ignore
return numerator / torch.clamp(denominator, min=eps)
- rotation_matrix_vec: torch.Tensor = rotation_matrix.view(
- *rotation_matrix.shape[:-2], 9)
+ rotation_matrix_vec: torch.Tensor = rotation_matrix.view(*rotation_matrix.shape[:-2], 9)
- m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.chunk(
- rotation_matrix_vec, chunks=9, dim=-1)
+ m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.chunk(rotation_matrix_vec, chunks=9, dim=-1)
trace: torch.Tensor = m00 + m11 + m22
@@ -434,8 +414,7 @@ def rotation_matrix_to_quaternion(
return quaternion
-def normalize_quaternion(quaternion: torch.Tensor,
- eps: float = 1.e-12) -> torch.Tensor:
+def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.e-12) -> torch.Tensor:
r"""Normalizes a quaternion.
The quaternion should be in (x, y, z, w) format.
@@ -455,13 +434,10 @@ def normalize_quaternion(quaternion: torch.Tensor,
tensor([0.7071, 0.0000, 0.7071, 0.0000])
"""
if not isinstance(quaternion, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(quaternion)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(quaternion)))
if not quaternion.shape[-1] == 4:
- raise ValueError(
- "Input must be a tensor of shape (*, 4). Got {}".format(
- quaternion.shape))
+ raise ValueError("Input must be a tensor of shape (*, 4). Got {}".format(quaternion.shape))
return F.normalize(quaternion, p=2.0, dim=-1, eps=eps)
@@ -469,9 +445,10 @@ def normalize_quaternion(quaternion: torch.Tensor,
# https://github.com/matthew-brett/transforms3d/blob/8965c48401d9e8e66b6a8c37c65f2fc200a076fa/transforms3d/quaternions.py#L101
# https://github.com/tensorflow/graphics/blob/master/tensorflow_graphics/geometry/transformation/rotation_matrix_3d.py#L247
+
def quaternion_to_rotation_matrix(
- quaternion: torch.Tensor,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
+ quaternion: torch.Tensor, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+) -> torch.Tensor:
r"""Converts a quaternion to a rotation matrix.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
@@ -503,9 +480,11 @@ def quaternion_to_rotation_matrix(
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
- warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
- " will be removed after > 0.6. "
- "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+ warnings.warn(
+ "`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead."
+ )
# normalize the input quaternion
quaternion_norm: torch.Tensor = normalize_quaternion(quaternion)
@@ -531,11 +510,13 @@ def quaternion_to_rotation_matrix(
tzz: torch.Tensor = tz * z
one: torch.Tensor = torch.tensor(1.)
- matrix: torch.Tensor = torch.stack((
- one - (tyy + tzz), txy - twz, txz + twy,
- txy + twz, one - (txx + tzz), tyz - twx,
- txz - twy, tyz + twx, one - (txx + tyy)
- ), dim=-1).view(-1, 3, 3)
+ matrix: torch.Tensor = torch.stack(
+ (
+ one - (tyy + tzz), txy - twz, txz + twy, txy + twz, one -
+ (txx + tzz), tyz - twx, txz - twy, tyz + twx, one - (txx + tyy)
+ ),
+ dim=-1
+ ).view(-1, 3, 3)
if len(quaternion.shape) == 1:
matrix = torch.squeeze(matrix, dim=0)
@@ -543,8 +524,8 @@ def quaternion_to_rotation_matrix(
def quaternion_to_angle_axis(
- quaternion: torch.Tensor,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
+ quaternion: torch.Tensor, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+) -> torch.Tensor:
"""Convert quaternion vector to angle axis of rotation.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
@@ -578,9 +559,11 @@ def quaternion_to_angle_axis(
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
- warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
- " will be removed after > 0.6. "
- "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+ warnings.warn(
+ "`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead."
+ )
# unpack input and compute conversion
q1: torch.Tensor = torch.tensor([])
q2: torch.Tensor = torch.tensor([])
@@ -601,9 +584,9 @@ def quaternion_to_angle_axis(
sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)
- two_theta: torch.Tensor = 2.0 * torch.where(cos_theta < 0.0,
- torch.atan2(-sin_theta, -cos_theta),
- torch.atan2(sin_theta, cos_theta))
+ two_theta: torch.Tensor = 2.0 * torch.where(
+ cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta), torch.atan2(sin_theta, cos_theta)
+ )
k_pos: torch.Tensor = two_theta / sin_theta
k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)
@@ -617,9 +600,10 @@ def quaternion_to_angle_axis(
def quaternion_log_to_exp(
- quaternion: torch.Tensor,
- eps: float = 1.e-8,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
+ quaternion: torch.Tensor,
+ eps: float = 1.e-8,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+) -> torch.Tensor:
r"""Applies exponential map to log quaternion.
The quaternion should be in (x, y, z, w) or (w, x, y, z) format.
@@ -650,9 +634,11 @@ def quaternion_log_to_exp(
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
- warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
- " will be removed after > 0.6. "
- "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+ warnings.warn(
+ "`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead."
+ )
# compute quaternion norm
norm_q: torch.Tensor = torch.norm(quaternion, p=2, dim=-1, keepdim=True).clamp(min=eps)
@@ -672,9 +658,10 @@ def quaternion_log_to_exp(
def quaternion_exp_to_log(
- quaternion: torch.Tensor,
- eps: float = 1.e-8,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
+ quaternion: torch.Tensor,
+ eps: float = 1.e-8,
+ order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+) -> torch.Tensor:
r"""Applies the log map to a quaternion.
The quaternion should be in (x, y, z, w) format.
@@ -706,9 +693,11 @@ def quaternion_exp_to_log(
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
- warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
- " will be removed after > 0.6. "
- "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+ warnings.warn(
+ "`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead."
+ )
# unpack quaternion vector and scalar
quaternion_vector: torch.Tensor = torch.tensor([])
@@ -722,12 +711,12 @@ def quaternion_exp_to_log(
quaternion_vector = quaternion[..., 1:4]
# compute quaternion norm
- norm_q: torch.Tensor = torch.norm(
- quaternion_vector, p=2, dim=-1, keepdim=True).clamp(min=eps)
+ norm_q: torch.Tensor = torch.norm(quaternion_vector, p=2, dim=-1, keepdim=True).clamp(min=eps)
# apply log map
quaternion_log: torch.Tensor = quaternion_vector * torch.acos(
- torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q
+ torch.clamp(quaternion_scalar, min=-1.0, max=1.0)
+ ) / norm_q
return quaternion_log
@@ -737,8 +726,8 @@ def quaternion_exp_to_log(
def angle_axis_to_quaternion(
- angle_axis: torch.Tensor,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW) -> torch.Tensor:
+ angle_axis: torch.Tensor, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+) -> torch.Tensor:
r"""Convert an angle axis to a quaternion.
The quaternion vector has components in (x, y, z, w) or (w, x, y, z) format.
@@ -772,9 +761,11 @@ def angle_axis_to_quaternion(
raise ValueError(f"order must be one of {QuaternionCoeffOrder.__members__.keys()}")
if order == QuaternionCoeffOrder.XYZW:
- warnings.warn("`XYZW` quaternion coefficient order is deprecated and"
- " will be removed after > 0.6. "
- "Please use `QuaternionCoeffOrder.WXYZ` instead.")
+ warnings.warn(
+ "`XYZW` quaternion coefficient order is deprecated and"
+ " will be removed after > 0.6. "
+ "Please use `QuaternionCoeffOrder.WXYZ` instead."
+ )
# unpack input and compute conversion
a0: torch.Tensor = angle_axis[..., 0:1]
@@ -793,8 +784,9 @@ def angle_axis_to_quaternion(
k: torch.Tensor = torch.where(mask, k_pos, k_neg)
w: torch.Tensor = torch.where(mask, torch.cos(half_theta), ones)
- quaternion: torch.Tensor = torch.zeros(size=(*angle_axis.shape[:-1], 4), dtype=angle_axis.dtype,
- device=angle_axis.device)
+ quaternion: torch.Tensor = torch.zeros(
+ size=(*angle_axis.shape[:-1], 4), dtype=angle_axis.dtype, device=angle_axis.device
+ )
if order == QuaternionCoeffOrder.XYZW:
quaternion[..., 0:1] = a0 * k
quaternion[..., 1:2] = a1 * k
@@ -811,11 +803,10 @@ def angle_axis_to_quaternion(
# based on:
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L65-L71
+
def normalize_pixel_coordinates(
- pixel_coordinates: torch.Tensor,
- height: int,
- width: int,
- eps: float = 1e-8) -> torch.Tensor:
+ pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Normalize pixel coordinates between -1 and 1.
Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
@@ -831,25 +822,24 @@ def normalize_pixel_coordinates(
torch.Tensor: the normalized pixel coordinates.
"""
if pixel_coordinates.shape[-1] != 2:
- raise ValueError("Input pixel_coordinates must be of shape (*, 2). "
- "Got {}".format(pixel_coordinates.shape))
+ raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
- hw: torch.Tensor = torch.stack([
- torch.tensor(width, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
- torch.tensor(height, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype)
- ])
+ hw: torch.Tensor = torch.stack(
+ [
+ torch.tensor(width, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
+ torch.tensor(height, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype)
+ ]
+ )
- factor: torch.Tensor = torch.tensor(
- 2., device=pixel_coordinates.device, dtype=pixel_coordinates.dtype) / (hw - 1).clamp(eps)
+ factor: torch.Tensor = torch.tensor(2., device=pixel_coordinates.device,
+ dtype=pixel_coordinates.dtype) / (hw - 1).clamp(eps)
return factor * pixel_coordinates - 1
def denormalize_pixel_coordinates(
- pixel_coordinates: torch.Tensor,
- height: int,
- width: int,
- eps: float = 1e-8) -> torch.Tensor:
+ pixel_coordinates: torch.Tensor, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Denormalize pixel coordinates.
The input is assumed to be -1 if on extreme left, 1 if on
@@ -866,12 +856,10 @@ def denormalize_pixel_coordinates(
torch.Tensor: the denormalized pixel coordinates.
"""
if pixel_coordinates.shape[-1] != 2:
- raise ValueError("Input pixel_coordinates must be of shape (*, 2). "
- "Got {}".format(pixel_coordinates.shape))
+ raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
- hw: torch.Tensor = torch.stack([
- torch.tensor(width), torch.tensor(height)
- ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+ hw: torch.Tensor = torch.stack([torch.tensor(width),
+ torch.tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(eps)
@@ -879,11 +867,8 @@ def denormalize_pixel_coordinates(
def normalize_pixel_coordinates3d(
- pixel_coordinates: torch.Tensor,
- depth: int,
- height: int,
- width: int,
- eps: float = 1e-8) -> torch.Tensor:
+ pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Normalize pixel coordinates between -1 and 1.
Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
@@ -900,12 +885,11 @@ def normalize_pixel_coordinates3d(
torch.Tensor: the normalized pixel coordinates.
"""
if pixel_coordinates.shape[-1] != 3:
- raise ValueError("Input pixel_coordinates must be of shape (*, 3). "
- "Got {}".format(pixel_coordinates.shape))
+ raise ValueError("Input pixel_coordinates must be of shape (*, 3). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
- dhw: torch.Tensor = torch.stack([
- torch.tensor(depth), torch.tensor(width), torch.tensor(height)
- ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+ dhw: torch.Tensor = torch.stack([torch.tensor(depth),
+ torch.tensor(width),
+ torch.tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(eps)
@@ -913,11 +897,8 @@ def normalize_pixel_coordinates3d(
def denormalize_pixel_coordinates3d(
- pixel_coordinates: torch.Tensor,
- depth: int,
- height: int,
- width: int,
- eps: float = 1e-8) -> torch.Tensor:
+ pixel_coordinates: torch.Tensor, depth: int, height: int, width: int, eps: float = 1e-8
+) -> torch.Tensor:
r"""Denormalize pixel coordinates.
The input is assumed to be -1 if on extreme left, 1 if on
@@ -936,12 +917,11 @@ def denormalize_pixel_coordinates3d(
torch.Tensor: the denormalized pixel coordinates.
"""
if pixel_coordinates.shape[-1] != 3:
- raise ValueError("Input pixel_coordinates must be of shape (*, 3). "
- "Got {}".format(pixel_coordinates.shape))
+ raise ValueError("Input pixel_coordinates must be of shape (*, 3). " "Got {}".format(pixel_coordinates.shape))
# compute normalization factor
- dhw: torch.Tensor = torch.stack([
- torch.tensor(depth), torch.tensor(width), torch.tensor(height)
- ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+ dhw: torch.Tensor = torch.stack([torch.tensor(depth),
+ torch.tensor(width),
+ torch.tensor(height)]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(eps)
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 50ead24ed..5e9ab3df7 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -9,9 +9,7 @@ from kornia.geometry.linalg import (
transform_points, inverse_transformation, compose_transformations, convert_points_to_homogeneous
)
from kornia.geometry.conversions import normalize_pixel_coordinates
-from kornia.geometry.camera import (
- PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
-)
+from kornia.geometry.camera import (PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points)
from kornia.utils import create_meshgrid
from kornia.filters.sobel import spatial_gradient
@@ -49,17 +47,14 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin
raise ValueError(f"Input depth musth have a shape (B, 1, H, W). Got: {depth.shape}")
if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError(f"Input camera_matrix type is not a torch.Tensor. "
- f"Got {type(camera_matrix)}.")
+ raise TypeError(f"Input camera_matrix type is not a torch.Tensor. " f"Got {type(camera_matrix)}.")
if not len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3):
- raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). "
- f"Got: {camera_matrix.shape}.")
+ raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). " f"Got: {camera_matrix.shape}.")
# create base coordinates grid
batch_size, _, height, width = depth.shape
- points_2d: torch.Tensor = create_meshgrid(
- height, width, normalized_coordinates=False) # 1xHxWx2
+ points_2d: torch.Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
points_2d = points_2d.to(depth.device).to(depth.dtype)
# depth should come in Bx1xHxW
@@ -68,7 +63,8 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin
# project pixels to camera frame
camera_matrix_tmp: torch.Tensor = camera_matrix[:, None, None] # Bx1x1x3x3
points_3d: torch.Tensor = unproject_points(
- points_2d, points_depth, camera_matrix_tmp, normalize=normalize_points) # BxHxWx3
+ points_2d, points_depth, camera_matrix_tmp, normalize=normalize_points
+ ) # BxHxWx3
return points_3d.permute(0, 3, 1, 2) # Bx3xHxW
@@ -98,12 +94,10 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize
raise ValueError(f"Input depth musth have a shape (B, 1, H, W). Got: {depth.shape}")
if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError(f"Input camera_matrix type is not a torch.Tensor. "
- f"Got {type(camera_matrix)}.")
+ raise TypeError(f"Input camera_matrix type is not a torch.Tensor. " f"Got {type(camera_matrix)}.")
if not len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3):
- raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). "
- f"Got: {camera_matrix.shape}.")
+ raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). " f"Got: {camera_matrix.shape}.")
# compute the 3d points from depth
xyz: torch.Tensor = depth_to_3d(depth, camera_matrix, normalize_points) # Bx3xHxW
@@ -119,11 +113,12 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize
def warp_frame_depth(
- image_src: torch.Tensor,
- depth_dst: torch.Tensor,
- src_trans_dst: torch.Tensor,
- camera_matrix: torch.Tensor,
- normalize_points: bool = False) -> torch.Tensor:
+ image_src: torch.Tensor,
+ depth_dst: torch.Tensor,
+ src_trans_dst: torch.Tensor,
+ camera_matrix: torch.Tensor,
+ normalize_points: bool = False
+) -> torch.Tensor:
"""Warp a tensor from a source to destination frame by the depth in the destination.
Compute 3d points from the depth, transform them using given transformation, then project the point cloud to an
@@ -155,20 +150,16 @@ def warp_frame_depth(
raise ValueError(f"Input depth_dst musth have a shape (B, 1, H, W). Got: {depth_dst.shape}")
if not isinstance(src_trans_dst, torch.Tensor):
- raise TypeError(f"Input src_trans_dst type is not a torch.Tensor. "
- f"Got {type(src_trans_dst)}.")
+ raise TypeError(f"Input src_trans_dst type is not a torch.Tensor. " f"Got {type(src_trans_dst)}.")
if not len(src_trans_dst.shape) == 3 and src_trans_dst.shape[-2:] == (3, 3):
- raise ValueError(f"Input src_trans_dst must have a shape (B, 3, 3). "
- f"Got: {src_trans_dst.shape}.")
+ raise ValueError(f"Input src_trans_dst must have a shape (B, 3, 3). " f"Got: {src_trans_dst.shape}.")
if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError(f"Input camera_matrix type is not a torch.Tensor. "
- f"Got {type(camera_matrix)}.")
+ raise TypeError(f"Input camera_matrix type is not a torch.Tensor. " f"Got {type(camera_matrix)}.")
if not len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3):
- raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). "
- f"Got: {camera_matrix.shape}.")
+ raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). " f"Got: {camera_matrix.shape}.")
# unproject source points to camera frame
points_3d_dst: torch.Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxW
@@ -184,8 +175,7 @@ def warp_frame_depth(
# normalize points between [-1 / 1]
height, width = depth_dst.shape[-2:]
- points_2d_src_norm: torch.Tensor = normalize_pixel_coordinates(
- points_2d_src, height, width) # BxHxWx2
+ points_2d_src_norm: torch.Tensor = normalize_pixel_coordinates(points_2d_src, height, width) # BxHxWx2
return F.grid_sample(image_src, points_2d_src_norm, align_corners=True) # type: ignore
@@ -211,12 +201,15 @@ class DepthWarper(nn.Module):
https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
"""
- def __init__(self,
- pinhole_dst: PinholeCamera,
- height: int, width: int,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = True):
+ def __init__(
+ self,
+ pinhole_dst: PinholeCamera,
+ height: int,
+ width: int,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = True
+ ):
super(DepthWarper, self).__init__()
# constructor members
self.width: int = width
@@ -235,21 +228,22 @@ class DepthWarper(nn.Module):
@staticmethod
def _create_meshgrid(height: int, width: int) -> torch.Tensor:
- grid: torch.Tensor = create_meshgrid(
- height, width, normalized_coordinates=False) # 1xHxWx2
+ grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
return convert_points_to_homogeneous(grid) # append ones to last dim
- def compute_projection_matrix(
- self, pinhole_src: PinholeCamera) -> 'DepthWarper':
+ def compute_projection_matrix(self, pinhole_src: PinholeCamera) -> 'DepthWarper':
r"""Computes the projection matrix from the source to destination frame.
"""
if not isinstance(self._pinhole_dst, PinholeCamera):
- raise TypeError("Member self._pinhole_dst expected to be of class "
- "PinholeCamera. Got {}"
- .format(type(self._pinhole_dst)))
+ raise TypeError(
+ "Member self._pinhole_dst expected to be of class "
+ "PinholeCamera. Got {}".format(type(self._pinhole_dst))
+ )
if not isinstance(pinhole_src, PinholeCamera):
- raise TypeError("Argument pinhole_src expected to be of class "
- "PinholeCamera. Got {}".format(type(pinhole_src)))
+ raise TypeError(
+ "Argument pinhole_src expected to be of class "
+ "PinholeCamera. Got {}".format(type(pinhole_src))
+ )
# compute the relative pose between the non reference and the reference
# camera frames.
dst_trans_src: torch.Tensor = compose_transformations(
@@ -259,8 +253,7 @@ class DepthWarper(nn.Module):
# compute the projection matrix between the non reference cameras and
# the reference.
- dst_proj_src: torch.Tensor = torch.matmul(
- self._pinhole_dst.intrinsics, dst_trans_src)
+ dst_proj_src: torch.Tensor = torch.matmul(self._pinhole_dst.intrinsics, dst_trans_src)
# update class members
self._pinhole_src = pinhole_src
@@ -269,7 +262,8 @@ class DepthWarper(nn.Module):
def _compute_projection(self, x, y, invd):
point = torch.tensor(
- [[[x], [y], [1.0], [invd]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype)
+ [[[x], [y], [1.0], [invd]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype
+ )
flow = torch.matmul(self._dst_proj_src, point)
z = 1. / flow[:, 2]
x = (flow[:, 0] * z)
@@ -285,10 +279,8 @@ class DepthWarper(nn.Module):
Vision. Springer Berlin Heidelberg, 2002.
"""
delta_d = 0.01
- xy_m1 = self._compute_projection(self.width / 2, self.height / 2,
- 1.0 - delta_d)
- xy_p1 = self._compute_projection(self.width / 2, self.height / 2,
- 1.0 + delta_d)
+ xy_m1 = self._compute_projection(self.width / 2, self.height / 2, 1.0 - delta_d)
+ xy_p1 = self._compute_projection(self.width / 2, self.height / 2, 1.0 + delta_d)
dx = torch.norm((xy_p1 - xy_m1), 2, dim=-1) / 2.0
dxdd = dx / (delta_d) # pixel*(1/meter)
# half pixel sampling, we're interested in the min for all cameras
@@ -308,8 +300,7 @@ class DepthWarper(nn.Module):
raise ValueError("Please, call compute_projection_matrix.")
if len(depth_src.shape) != 4:
- raise ValueError("Input depth_src has to be in the shape of "
- "Bx1xHxW. Got {}".format(depth_src.shape))
+ raise ValueError("Input depth_src has to be in the shape of " "Bx1xHxW. Got {}".format(depth_src.shape))
# unpack depth attributes
batch_size, _, height, width = depth_src.shape
@@ -317,28 +308,26 @@ class DepthWarper(nn.Module):
dtype: torch.dtype = depth_src.dtype
# expand the base coordinate grid according to the input batch size
- pixel_coords: torch.Tensor = self.grid.to(device=device, dtype=dtype).expand(
- batch_size, -1, -1, -1) # BxHxWx3
+ pixel_coords: torch.Tensor = self.grid.to(device=device, dtype=dtype).expand(batch_size, -1, -1, -1) # BxHxWx3
# reproject the pixel coordinates to the camera frame
cam_coords_src: torch.Tensor = pixel2cam(
depth_src,
- self._pinhole_src.intrinsics_inverse().to(device=device, dtype=dtype),
- pixel_coords) # BxHxWx3
+ self._pinhole_src.intrinsics_inverse().to(device=device, dtype=dtype), pixel_coords
+ ) # BxHxWx3
# reproject the camera coordinates to the pixel
pixel_coords_src: torch.Tensor = cam2pixel(
- cam_coords_src, self._dst_proj_src.to(device=device, dtype=dtype)) # (B*N)xHxWx2
+ cam_coords_src, self._dst_proj_src.to(device=device, dtype=dtype)
+ ) # (B*N)xHxWx2
# normalize between -1 and 1 the coordinates
- pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(
- pixel_coords_src, self.height, self.width)
+ pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(pixel_coords_src, self.height, self.width)
return pixel_coords_src_norm
def forward( # type: ignore
- self,
- depth_src: torch.Tensor,
- patch_dst: torch.Tensor) -> torch.Tensor:
+ self, depth_src: torch.Tensor, patch_dst: torch.Tensor
+ ) -> torch.Tensor:
"""Warps a tensor from destination frame to reference given the depth
in the reference frame.
@@ -368,17 +357,24 @@ class DepthWarper(nn.Module):
>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
>>> image_src = warper(depth_src, image_dst) # NxCxHxW
"""
- return F.grid_sample(patch_dst, self.warp_grid(depth_src), # type: ignore
- mode=self.mode, padding_mode=self.padding_mode,
- align_corners=self.align_corners)
+ return F.grid_sample(
+ patch_dst,
+ self.warp_grid(depth_src), # type: ignore
+ mode=self.mode,
+ padding_mode=self.padding_mode,
+ align_corners=self.align_corners
+ )
-def depth_warp(pinhole_dst: PinholeCamera,
- pinhole_src: PinholeCamera,
- depth_src: torch.Tensor,
- patch_dst: torch.Tensor,
- height: int, width: int,
- align_corners: bool = True):
+def depth_warp(
+ pinhole_dst: PinholeCamera,
+ pinhole_src: PinholeCamera,
+ depth_src: torch.Tensor,
+ patch_dst: torch.Tensor,
+ height: int,
+ width: int,
+ align_corners: bool = True
+):
r"""Function that warps a tensor from destination frame to reference
given the depth in the reference frame.
diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.py
index 9dab30443..204227798 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -52,7 +52,7 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch
Vt = V.transpose(-2, -1)
mask = torch.ones_like(E_mat)
- mask[..., -1:] *= -1. # fill last column with negative values
+ mask[..., -1:] *= -1. # fill last column with negative values
maskt = mask.transpose(-2, -1)
@@ -233,9 +233,8 @@ def motion_from_essential_choose_solution(
return R_out, t_out, points3d_out
-def relative_camera_motion(
- R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2: torch.Tensor
-) -> Tuple[torch.Tensor, torch.Tensor]:
+def relative_camera_motion(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor,
+ t2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Computes the relative camera motion between two cameras.
Given the motion parameters of two cameras, computes the motion parameters of the second
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index d6c49d79d..9052c8940 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -30,15 +30,15 @@ def normalize_points(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Ten
x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1x2
- scale = (points - x_mean).norm(dim=-1).mean(dim=-1) # B
+ scale = (points - x_mean).norm(dim=-1).mean(dim=-1) # B
scale = torch.sqrt(torch.tensor(2.)) / (scale + eps) # B
ones, zeros = torch.ones_like(scale), torch.zeros_like(scale)
- transform = torch.stack([
- scale, zeros, -scale * x_mean[..., 0, 0],
- zeros, scale, -scale * x_mean[..., 0, 1],
- zeros, zeros, ones], dim=-1) # Bx9
+ transform = torch.stack(
+ [scale, zeros, -scale * x_mean[..., 0, 0], zeros, scale, -scale * x_mean[..., 0, 1], zeros, zeros, ones],
+ dim=-1
+ ) # Bx9
transform = transform.view(-1, 3, 3) # Bx3x3
points_norm = kornia.transform_points(transform, points) # BxNx2
@@ -94,9 +94,7 @@ def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torc
# https://www.cc.gatech.edu/~afb/classes/CS4495-Fall2013/slides/CS4495-09-TwoViews-2.pdf
# [x * x', x * y', x, y * x', y * y', y, x', y', 1]
- X = torch.cat([
- x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones
- ], dim=-1) # BxNx9
+ X = torch.cat([x2 * x1, x2 * y1, x2, y2 * x1, y2 * y1, y2, x1, y1, ones], dim=-1) # BxNx9
# apply the weights to the linear system
w_diag = torch.diag_embed(weights)
@@ -173,6 +171,7 @@ def fundamental_from_essential(E_mat: torch.Tensor, K1: torch.Tensor, K2: torch.
# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L109
# https://github.com/openMVG/openMVG/blob/160643be515007580086650f2ae7f1a42d32e9fb/src/openMVG/multiview/projection.cpp#L134
+
def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Tensor:
r"""Get the Fundamental matrix from Projection matrices.
@@ -203,10 +202,19 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Te
X1Y2, X2Y2, X3Y2 = vstack(X1, Y2), vstack(X2, Y2), vstack(X3, Y2)
X1Y3, X2Y3, X3Y3 = vstack(X1, Y3), vstack(X2, Y3), vstack(X3, Y3)
- F_vec = torch.cat([
- X1Y1.det().reshape(-1, 1), X2Y1.det().reshape(-1, 1), X3Y1.det().reshape(-1, 1),
- X1Y2.det().reshape(-1, 1), X2Y2.det().reshape(-1, 1), X3Y2.det().reshape(-1, 1),
- X1Y3.det().reshape(-1, 1), X2Y3.det().reshape(-1, 1), X3Y3.det().reshape(-1, 1),
- ], dim=1)
+ F_vec = torch.cat(
+ [
+ X1Y1.det().reshape(-1, 1),
+ X2Y1.det().reshape(-1, 1),
+ X3Y1.det().reshape(-1, 1),
+ X1Y2.det().reshape(-1, 1),
+ X2Y2.det().reshape(-1, 1),
+ X3Y2.det().reshape(-1, 1),
+ X1Y3.det().reshape(-1, 1),
+ X2Y3.det().reshape(-1, 1),
+ X3Y3.det().reshape(-1, 1),
+ ],
+ dim=1
+ )
return F_vec.view(*P1.shape[:-2], 3, 3)
diff --git a/kornia/geometry/epipolar/metrics.py b/kornia/geometry/epipolar/metrics.py
index 301c51f94..b0b015a9c 100644
--- a/kornia/geometry/epipolar/metrics.py
+++ b/kornia/geometry/epipolar/metrics.py
@@ -4,11 +4,9 @@ import torch
import kornia
-def sampson_epipolar_distance(pts1: torch.Tensor,
- pts2: torch.Tensor,
- Fm: torch.Tensor,
- squared: bool = True,
- eps: float = 1e-8) -> torch.Tensor:
+def sampson_epipolar_distance(
+ pts1: torch.Tensor, pts2: torch.Tensor, Fm: torch.Tensor, squared: bool = True, eps: float = 1e-8
+) -> torch.Tensor:
r"""Returns Sampson distance for correspondences given the fundamental matrix.
Args:
@@ -26,13 +24,10 @@ def sampson_epipolar_distance(pts1: torch.Tensor,
"""
if not isinstance(Fm, torch.Tensor):
- raise TypeError("Fm type is not a torch.Tensor. Got {}".format(
- type(Fm)))
+ raise TypeError("Fm type is not a torch.Tensor. Got {}".format(type(Fm)))
if (len(Fm.shape) != 3) or not Fm.shape[-2:] == (3, 3):
- raise ValueError(
- "Fm must be a (*, 3, 3) tensor. Got {}".format(
- Fm.shape))
+ raise ValueError("Fm must be a (*, 3, 3) tensor. Got {}".format(Fm.shape))
if pts1.size(-1) == 2:
pts1 = kornia.convert_points_to_homogeneous(pts1)
@@ -61,11 +56,9 @@ def sampson_epipolar_distance(pts1: torch.Tensor,
return (out + eps).sqrt()
-def symmetrical_epipolar_distance(pts1: torch.Tensor,
- pts2: torch.Tensor,
- Fm: torch.Tensor,
- squared: bool = True,
- eps: float = 1e-8) -> torch.Tensor:
+def symmetrical_epipolar_distance(
+ pts1: torch.Tensor, pts2: torch.Tensor, Fm: torch.Tensor, squared: bool = True, eps: float = 1e-8
+) -> torch.Tensor:
r"""Returns symmetrical epipolar distance for correspondences given the fundamental matrix.
Args:
@@ -83,13 +76,10 @@ def symmetrical_epipolar_distance(pts1: torch.Tensor,
"""
if not isinstance(Fm, torch.Tensor):
- raise TypeError("Fm type is not a torch.Tensor. Got {}".format(
- type(Fm)))
+ raise TypeError("Fm type is not a torch.Tensor. Got {}".format(type(Fm)))
if (len(Fm.shape) != 3) or not Fm.shape[-2:] == (3, 3):
- raise ValueError(
- "Fm must be a (*, 3, 3) tensor. Got {}".format(
- Fm.shape))
+ raise ValueError("Fm must be a (*, 3, 3) tensor. Got {}".format(Fm.shape))
if pts1.size(-1) == 2:
pts1 = kornia.convert_points_to_homogeneous(pts1)
@@ -112,8 +102,9 @@ def symmetrical_epipolar_distance(pts1: torch.Tensor,
numerator: torch.Tensor = (pts2 * line1_in_2).sum(2).pow(2)
# denominator_inv = 1/ (((Fx)_1**2) + (Fx)_2**2)) + 1/ (((F^Tx')_1**2) + (F^Tx')_2**2))
- denominator_inv: torch.Tensor = (1. / (line1_in_2[..., :2].norm(2, dim=2).pow(2)) +
- 1. / (line2_in_1[..., :2].norm(2, dim=2).pow(2)))
+ denominator_inv: torch.Tensor = (
+ 1. / (line1_in_2[..., :2].norm(2, dim=2).pow(2)) + 1. / (line2_in_1[..., :2].norm(2, dim=2).pow(2))
+ )
out: torch.Tensor = numerator * denominator_inv
if squared:
return out
diff --git a/kornia/geometry/epipolar/numeric.py b/kornia/geometry/epipolar/numeric.py
index 1f36f8276..e595c5d3c 100644
--- a/kornia/geometry/epipolar/numeric.py
+++ b/kornia/geometry/epipolar/numeric.py
@@ -2,9 +2,9 @@
import torch
-
# TODO: this should go to `kornia.geometry.linalg`
+
def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
r"""Returns the cross_product_matrix symmetric matrix of a vector.
@@ -23,10 +23,7 @@ def cross_product_matrix(x: torch.Tensor) -> torch.Tensor:
# construct the matrix, reshape to 3x3 and return
zeros = torch.zeros_like(x0)
- cross_product_matrix_flat = torch.stack([
- zeros, -x2, x1,
- x2, zeros, -x0,
- -x1, x0, zeros], dim=-1)
+ cross_product_matrix_flat = torch.stack([zeros, -x2, x1, x2, zeros, -x0, -x1, x0, zeros], dim=-1)
return cross_product_matrix_flat.view(-1, 3, 3)
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index d88e406ea..95fd7ef27 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -33,8 +33,7 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
return intrinsics
-def random_intrinsics(low: Union[float, torch.Tensor],
- high: Union[float, torch.Tensor]) -> torch.Tensor:
+def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Generates a random camera matrix based on a given uniform distribution.
Args:
@@ -46,18 +45,23 @@ def random_intrinsics(low: Union[float, torch.Tensor],
"""
sampler = torch.distributions.Uniform(low, high)
- fx, fy, cx, cy = [sampler.sample((1,)) for _ in range(4)]
+ fx, fy, cx, cy = [sampler.sample((1, )) for _ in range(4)]
zeros, ones = torch.zeros_like(fx), torch.ones_like(fx)
camera_matrix: torch.Tensor = torch.cat([
- fx, zeros, cx,
- zeros, fy, cy,
- zeros, zeros, ones,
+ fx,
+ zeros,
+ cx,
+ zeros,
+ fy,
+ cy,
+ zeros,
+ zeros,
+ ones,
])
return camera_matrix.view(1, 3, 3)
-def scale_intrinsics(
- camera_matrix: torch.Tensor, scale_factor: Union[float, torch.Tensor]) -> torch.Tensor:
+def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, torch.Tensor]) -> torch.Tensor:
r"""Scale a camera matrix containing the intrinsics.
Applies the scaling factor to the focal length and center of projection.
diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.py
index cc35b8686..690a39f28 100644
--- a/kornia/geometry/epipolar/triangulation.py
+++ b/kornia/geometry/epipolar/triangulation.py
@@ -3,11 +3,12 @@
import torch
import kornia
-
# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68
-def triangulate_points(P1: torch.Tensor, P2: torch.Tensor, points1: torch.Tensor,
- points2: torch.Tensor) -> torch.Tensor:
+
+def triangulate_points(
+ P1: torch.Tensor, P2: torch.Tensor, points1: torch.Tensor, points2: torch.Tensor
+) -> torch.Tensor:
r"""Reconstructs a bunch of points by triangulation.
Triangulates the 3d position of 2d correspondences between several images.
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index e523d32a7..edb6a0c1b 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -12,7 +12,8 @@ TupleTensor = Tuple[torch.Tensor, torch.Tensor]
def find_homography_dlt(
- points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None) -> torch.Tensor:
+ points1: torch.Tensor, points2: torch.Tensor, weights: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Computes the homography matrix using the DLT formulation.
The linear system is solved by using the Weighted Least Squares Solution for the 4 Points algorithm.
@@ -66,11 +67,13 @@ def find_homography_dlt(
return H_norm
-def find_homography_dlt_iterated(points1: torch.Tensor,
- points2: torch.Tensor,
- weights: torch.Tensor,
- soft_inl_th: float = 3.0,
- n_iter: int = 5) -> torch.Tensor:
+def find_homography_dlt_iterated(
+ points1: torch.Tensor,
+ points2: torch.Tensor,
+ weights: torch.Tensor,
+ soft_inl_th: float = 3.0,
+ n_iter: int = 5
+) -> torch.Tensor:
r"""Computes the homography matrix using the iteratively-reweighted least squares (IRWLS).
The linear system is solved by using the Reweighted Least Squares Solution for the 4 Points algorithm.
@@ -86,13 +89,12 @@ def find_homography_dlt_iterated(points1: torch.Tensor,
Returns:
torch.Tensor: the computed homography matrix with shape :math:`(B, 3, 3)`.
"""
-
'''Function, which finds homography via iteratively-reweighted
least squares ToDo: add citation'''
H: torch.Tensor = find_homography_dlt(points1, points2, weights)
for i in range(n_iter - 1):
pts1_in_2: torch.Tensor = kornia.transform_points(H, points1)
error_squared: torch.Tensor = (pts1_in_2 - points2).pow(2).sum(dim=-1)
- weights_new: torch.Tensor = torch.exp(-error_squared / (2.0 * (soft_inl_th ** 2)))
+ weights_new: torch.Tensor = torch.exp(-error_squared / (2.0 * (soft_inl_th**2)))
H = find_homography_dlt(points1, points2, weights_new)
return H
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 3a9d99470..9fc5c15aa 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -7,7 +7,6 @@ from kornia.geometry.conversions import convert_points_to_homogeneous
from kornia.geometry.conversions import convert_points_from_homogeneous
from kornia.testing import check_is_tensor
-
__all__ = [
"compose_transformations",
"relative_transformation",
@@ -18,8 +17,7 @@ __all__ = [
]
-def compose_transformations(
- trans_01: torch.Tensor, trans_12: torch.Tensor) -> torch.Tensor:
+def compose_transformations(trans_01: torch.Tensor, trans_12: torch.Tensor) -> torch.Tensor:
r"""Functions that composes two homogeneous transformations.
.. math::
@@ -48,20 +46,15 @@ def compose_transformations(
"""
if not torch.is_tensor(trans_01):
- raise TypeError("Input trans_01 type is not a torch.Tensor. Got {}"
- .format(type(trans_01)))
+ raise TypeError("Input trans_01 type is not a torch.Tensor. Got {}".format(type(trans_01)))
if not torch.is_tensor(trans_12):
- raise TypeError("Input trans_12 type is not a torch.Tensor. Got {}"
- .format(type(trans_12)))
+ raise TypeError("Input trans_12 type is not a torch.Tensor. Got {}".format(type(trans_12)))
if not trans_01.dim() in (2, 3) and trans_01.shape[-2:] == (4, 4):
- raise ValueError("Input trans_01 must be a of the shape Nx4x4 or 4x4."
- " Got {}".format(trans_01.shape))
+ raise ValueError("Input trans_01 must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_01.shape))
if not trans_12.dim() in (2, 3) and trans_12.shape[-2:] == (4, 4):
- raise ValueError("Input trans_12 must be a of the shape Nx4x4 or 4x4."
- " Got {}".format(trans_12.shape))
+ raise ValueError("Input trans_12 must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_12.shape))
if not trans_01.dim() == trans_12.dim():
- raise ValueError("Input number of dims must match. Got {} and {}"
- .format(trans_01.dim(), trans_12.dim()))
+ raise ValueError("Input number of dims must match. Got {} and {}".format(trans_01.dim(), trans_12.dim()))
# unpack input data
rmat_01: torch.Tensor = trans_01[..., :3, :3] # Nx3x3
rmat_12: torch.Tensor = trans_12[..., :3, :3] # Nx3x3
@@ -106,11 +99,9 @@ def inverse_transformation(trans_12):
>>> trans_21 = inverse_transformation(trans_12) # Nx4x4
"""
if not torch.is_tensor(trans_12):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(trans_12)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(trans_12)))
if not trans_12.dim() in (2, 3) and trans_12.shape[-2:] == (4, 4):
- raise ValueError("Input size must be a Nx4x4 or 4x4. Got {}"
- .format(trans_12.shape))
+ raise ValueError("Input size must be a Nx4x4 or 4x4. Got {}".format(trans_12.shape))
# unpack input tensor
rmat_12: torch.Tensor = trans_12[..., :3, 0:3] # Nx3x3
tvec_12: torch.Tensor = trans_12[..., :3, 3:4] # Nx3x1
@@ -127,8 +118,7 @@ def inverse_transformation(trans_12):
return trans_21
-def relative_transformation(
- trans_01: torch.Tensor, trans_02: torch.Tensor) -> torch.Tensor:
+def relative_transformation(trans_01: torch.Tensor, trans_02: torch.Tensor) -> torch.Tensor:
r"""Function that computes the relative homogenous transformation from a
reference transformation :math:`T_1^{0} = \begin{bmatrix} R_1 & t_1 \\
\mathbf{0} & 1 \end{bmatrix}` to destination :math:`T_2^{0} =
@@ -158,27 +148,21 @@ def relative_transformation(
>>> trans_12 = relative_transformation(trans_01, trans_02) # 4x4
"""
if not torch.is_tensor(trans_01):
- raise TypeError("Input trans_01 type is not a torch.Tensor. Got {}"
- .format(type(trans_01)))
+ raise TypeError("Input trans_01 type is not a torch.Tensor. Got {}".format(type(trans_01)))
if not torch.is_tensor(trans_02):
- raise TypeError("Input trans_02 type is not a torch.Tensor. Got {}"
- .format(type(trans_02)))
+ raise TypeError("Input trans_02 type is not a torch.Tensor. Got {}".format(type(trans_02)))
if not trans_01.dim() in (2, 3) and trans_01.shape[-2:] == (4, 4):
- raise ValueError("Input must be a of the shape Nx4x4 or 4x4."
- " Got {}".format(trans_01.shape))
+ raise ValueError("Input must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_01.shape))
if not trans_02.dim() in (2, 3) and trans_02.shape[-2:] == (4, 4):
- raise ValueError("Input must be a of the shape Nx4x4 or 4x4."
- " Got {}".format(trans_02.shape))
+ raise ValueError("Input must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_02.shape))
if not trans_01.dim() == trans_02.dim():
- raise ValueError("Input number of dims must match. Got {} and {}"
- .format(trans_01.dim(), trans_02.dim()))
+ raise ValueError("Input number of dims must match. Got {} and {}".format(trans_01.dim(), trans_02.dim()))
trans_10: torch.Tensor = inverse_transformation(trans_01)
trans_12: torch.Tensor = compose_transformations(trans_10, trans_02)
return trans_12
-def transform_points(trans_01: torch.Tensor,
- points_1: torch.Tensor) -> torch.Tensor:
+def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Tensor:
r"""Function that applies transformations to a set of points.
Args:
@@ -203,7 +187,8 @@ def transform_points(trans_01: torch.Tensor,
raise TypeError(
"Tensor must be in the same device and dtype. "
f"Got trans_01 with ({trans_01.dtype}, {points_1.dtype}) and "
- f"points_1 with ({points_1.dtype}, {points_1.dtype})")
+ f"points_1 with ({points_1.dtype}, {points_1.dtype})"
+ )
if not trans_01.shape[0] == points_1.shape[0] and trans_01.shape[0] != 1:
raise ValueError("Input batch size must be the same for both tensors or 1")
if not trans_01.shape[-1] == (points_1.shape[-1] + 1):
@@ -218,8 +203,7 @@ def transform_points(trans_01: torch.Tensor,
# to homogeneous
points_1_h = convert_points_to_homogeneous(points_1) # BxNxD+1
# transform coordinates
- points_0_h = torch.bmm(points_1_h,
- trans_01.permute(0, 2, 1))
+ points_0_h = torch.bmm(points_1_h, trans_01.permute(0, 2, 1))
points_0_h = torch.squeeze(points_0_h, dim=-1)
# to euclidean
points_0 = convert_points_from_homogeneous(points_0_h) # BxNxD
@@ -275,8 +259,7 @@ def transform_boxes(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "x
return transformed_boxes
-def perspective_transform_lafs(trans_01: torch.Tensor,
- lafs_1: torch.Tensor) -> torch.Tensor:
+def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:
r"""Function that applies perspective transformations to a set of local affine frames (LAFs).
Args:
@@ -346,7 +329,6 @@ def perspective_transform_lafs(trans_01: torch.Tensor,
# TODO:
# - project_points: from opencv
-
# layer api
# NOTE: is it needed ?
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 2aab133c7..0d223ef3c 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -15,13 +15,12 @@ from kornia.utils.grid import create_meshgrid
def _validate_batched_image_tensor_input(tensor):
check_is_tensor(tensor)
if not len(tensor.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(tensor.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(tensor.shape))
def spatial_softmax2d(
- input: torch.Tensor,
- temperature: torch.Tensor = torch.tensor(1.0),
+ input: torch.Tensor,
+ temperature: torch.Tensor = torch.tensor(1.0),
) -> torch.Tensor:
r"""Applies the Softmax function over features in each image channel.
@@ -61,8 +60,8 @@ def spatial_softmax2d(
def spatial_expectation2d(
- input: torch.Tensor,
- normalized_coordinates: bool = True,
+ input: torch.Tensor,
+ normalized_coordinates: bool = True,
) -> torch.Tensor:
r"""Computes the expectation of coordinate values using spatial probabilities.
@@ -115,18 +114,18 @@ def spatial_expectation2d(
def _safe_zero_division(
- numerator: torch.Tensor,
- denominator: torch.Tensor,
- eps: float = 1e-32,
+ numerator: torch.Tensor,
+ denominator: torch.Tensor,
+ eps: float = 1e-32,
) -> torch.Tensor:
return numerator / torch.clamp(denominator, min=eps)
def render_gaussian2d(
- mean: torch.Tensor,
- std: torch.Tensor,
- size: Tuple[int, int],
- normalized_coordinates: bool = True,
+ mean: torch.Tensor,
+ std: torch.Tensor,
+ size: Tuple[int, int],
+ normalized_coordinates: bool = True,
):
r"""Renders the PDF of a 2D Gaussian distribution.
@@ -161,8 +160,8 @@ def render_gaussian2d(
# where dists = (x - \mu)^2 and ks = -1 / (2 \sigma^2)
# dists <- (x - \mu)^2
- dist_x = (pos_x - mean[..., 0, None, None]) ** 2
- dist_y = (pos_y - mean[..., 1, None, None]) ** 2
+ dist_x = (pos_x - mean[..., 0, None, None])**2
+ dist_y = (pos_y - mean[..., 1, None, None])**2
# ks <- -1 / (2 \sigma^2)
k_x = -0.5 * torch.reciprocal(std[..., 0, None, None])
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 3a1183246..bf1fcde41 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -10,8 +10,7 @@ from kornia.utils import create_meshgrid, create_meshgrid3d
from kornia.geometry import normalize_pixel_coordinates, normalize_pixel_coordinates3d
-def _get_window_grid_kernel2d(h: int, w: int,
- device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
r"""Helper function, which generates a kernel to with window coordinates,
residual to window center.
@@ -29,8 +28,7 @@ def _get_window_grid_kernel2d(h: int, w: int,
return conv_kernel
-def _get_center_kernel2d(h: int, w: int,
- device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
r"""Helper function, which generates a kernel to return center coordinates,
when applied with F.conv2d to 2d coordinates grid.
@@ -57,12 +55,11 @@ def _get_center_kernel2d(h: int, w: int,
else:
w_i1 = (w // 2) - 1
w_i2 = (w // 2) + 1
- center_kernel[(0, 1), (0, 1), h_i1: h_i2, w_i1: w_i2] = 1.0 / float(((h_i2 - h_i1) * (w_i2 - w_i1)))
+ center_kernel[(0, 1), (0, 1), h_i1:h_i2, w_i1:w_i2] = 1.0 / float(((h_i2 - h_i1) * (w_i2 - w_i1)))
return center_kernel
-def _get_center_kernel3d(d: int, h: int, w: int,
- device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
r"""Helper function, which generates a kernel to return center coordinates,
when applied with F.conv2d to 3d coordinates grid.
@@ -96,12 +93,11 @@ def _get_center_kernel3d(d: int, h: int, w: int,
d_i1 = (d // 2) - 1
d_i2 = (d // 2) + 1
center_num = float((h_i2 - h_i1) * (w_i2 - w_i1) * (d_i2 - d_i1))
- center_kernel[(0, 1, 2), (0, 1, 2), d_i1: d_i2, h_i1: h_i2, w_i1: w_i2] = 1.0 / center_num
+ center_kernel[(0, 1, 2), (0, 1, 2), d_i1:d_i2, h_i1:h_i2, w_i1:w_i2] = 1.0 / center_num
return center_kernel
-def _get_window_grid_kernel3d(d: int, h: int, w: int,
- device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
r"""Helper function, which generates a kernel to return coordinates,
residual to window center.
@@ -130,14 +126,16 @@ class ConvSoftArgmax2d(nn.Module):
See :func:`~kornia.geometry.subpix.conv_soft_argmax2d` for details.
"""
- def __init__(self,
- kernel_size: Tuple[int, int] = (3, 3),
- stride: Tuple[int, int] = (1, 1),
- padding: Tuple[int, int] = (1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
- normalized_coordinates: bool = True,
- eps: float = 1e-8,
- output_value: bool = False) -> None:
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int] = (3, 3),
+ stride: Tuple[int, int] = (1, 1),
+ padding: Tuple[int, int] = (1, 1),
+ temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8,
+ output_value: bool = False
+ ) -> None:
super(ConvSoftArgmax2d, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
@@ -158,14 +156,10 @@ class ConvSoftArgmax2d(nn.Module):
', ' + 'output_value=' + str(self.output_value) + ')'
def forward(self, x: torch.Tensor): # type: ignore
- return conv_soft_argmax2d(x,
- self.kernel_size,
- self.stride,
- self.padding,
- self.temperature,
- self.normalized_coordinates,
- self.eps,
- self.output_value)
+ return conv_soft_argmax2d(
+ x, self.kernel_size, self.stride, self.padding, self.temperature, self.normalized_coordinates, self.eps,
+ self.output_value
+ )
class ConvSoftArgmax3d(nn.Module):
@@ -174,15 +168,17 @@ class ConvSoftArgmax3d(nn.Module):
See :func:`~kornia.geometry.subpix.conv_soft_argmax3d` for details.
"""
- def __init__(self,
- kernel_size: Tuple[int, int, int] = (3, 3, 3),
- stride: Tuple[int, int, int] = (1, 1, 1),
- padding: Tuple[int, int, int] = (1, 1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
- normalized_coordinates: bool = False,
- eps: float = 1e-8,
- output_value: bool = True,
- strict_maxima_bonus: float = 0.0) -> None:
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int, int] = (3, 3, 3),
+ stride: Tuple[int, int, int] = (1, 1, 1),
+ padding: Tuple[int, int, int] = (1, 1, 1),
+ temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ normalized_coordinates: bool = False,
+ eps: float = 1e-8,
+ output_value: bool = True,
+ strict_maxima_bonus: float = 0.0
+ ) -> None:
super(ConvSoftArgmax3d, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
@@ -206,26 +202,22 @@ class ConvSoftArgmax3d(nn.Module):
', ' + 'output_value=' + str(self.output_value) + ')'
def forward(self, x: torch.Tensor): # type: ignore
- return conv_soft_argmax3d(x,
- self.kernel_size,
- self.stride,
- self.padding,
- self.temperature,
- self.normalized_coordinates,
- self.eps,
- self.output_value,
- self.strict_maxima_bonus)
-
-
-def conv_soft_argmax2d(input: torch.Tensor,
- kernel_size: Tuple[int, int] = (3, 3),
- stride: Tuple[int, int] = (1, 1),
- padding: Tuple[int, int] = (1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
- normalized_coordinates: bool = True,
- eps: float = 1e-8,
- output_value: bool = False) -> Union[torch.Tensor,
- Tuple[torch.Tensor, torch.Tensor]]:
+ return conv_soft_argmax3d(
+ x, self.kernel_size, self.stride, self.padding, self.temperature, self.normalized_coordinates, self.eps,
+ self.output_value, self.strict_maxima_bonus
+ )
+
+
+def conv_soft_argmax2d(
+ input: torch.Tensor,
+ kernel_size: Tuple[int, int] = (3, 3),
+ stride: Tuple[int, int] = (1, 1),
+ padding: Tuple[int, int] = (1, 1),
+ temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8,
+ output_value: bool = False
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Function that computes the convolutional spatial Soft-Argmax 2D over the windows
of a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap values
themselves. On each window, the function computed is
@@ -265,16 +257,13 @@ def conv_soft_argmax2d(input: torch.Tensor,
>>> nms_coords, nms_val = conv_soft_argmax2d(input, (3,3), (2,2), (1,1), output_value=True)
"""
if not torch.is_tensor(input):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}".format(input.shape))
if temperature <= 0:
- raise ValueError("Temperature should be positive float or tensor. Got: {}"
- .format(temperature))
+ raise ValueError("Temperature should be positive float or tensor. Got: {}".format(temperature))
b, c, h, w = input.shape
kx, ky = kernel_size
@@ -300,28 +289,18 @@ def conv_soft_argmax2d(input: torch.Tensor,
# softmax denominator
den = pool_coef * F.avg_pool2d(x_exp, kernel_size, stride=stride, padding=padding) + eps
- x_softmaxpool = pool_coef * F.avg_pool2d(x_exp * input,
- kernel_size,
- stride=stride,
- padding=padding) / den
+ x_softmaxpool = pool_coef * F.avg_pool2d(x_exp * input, kernel_size, stride=stride, padding=padding) / den
x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3))
# We need to output also coordinates
# Pooled window center coordinates
- grid_global: torch.Tensor = create_meshgrid(h, w, False, device).to(
- dtype).permute(0, 3, 1, 2)
+ grid_global: torch.Tensor = create_meshgrid(h, w, False, device).to(dtype).permute(0, 3, 1, 2)
- grid_global_pooled = F.conv2d(grid_global,
- center_kernel,
- stride=stride,
- padding=padding)
+ grid_global_pooled = F.conv2d(grid_global, center_kernel, stride=stride, padding=padding)
# Coordinates of maxima residual to window center
# prepare kernel
- coords_max: torch.Tensor = F.conv2d(x_exp,
- window_kernel,
- stride=stride,
- padding=padding)
+ coords_max: torch.Tensor = F.conv2d(x_exp, window_kernel, stride=stride, padding=padding)
coords_max = coords_max / den.expand_as(coords_max)
coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
@@ -340,15 +319,17 @@ def conv_soft_argmax2d(input: torch.Tensor,
return coords_max
-def conv_soft_argmax3d(input: torch.Tensor,
- kernel_size: Tuple[int, int, int] = (3, 3, 3),
- stride: Tuple[int, int, int] = (1, 1, 1),
- padding: Tuple[int, int, int] = (1, 1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
- normalized_coordinates: bool = False,
- eps: float = 1e-8,
- output_value: bool = True,
- strict_maxima_bonus: float = 0.0) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+def conv_soft_argmax3d(
+ input: torch.Tensor,
+ kernel_size: Tuple[int, int, int] = (3, 3, 3),
+ stride: Tuple[int, int, int] = (1, 1, 1),
+ padding: Tuple[int, int, int] = (1, 1, 1),
+ temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ normalized_coordinates: bool = False,
+ eps: float = 1e-8,
+ output_value: bool = True,
+ strict_maxima_bonus: float = 0.0
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Function that computes the convolutional spatial Soft-Argmax 3D over the windows
of a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap values
themselves.
@@ -394,16 +375,13 @@ def conv_soft_argmax3d(input: torch.Tensor,
>>> nms_coords, nms_val = conv_soft_argmax3d(input, (3, 3, 3), (1, 2, 2), (0, 1, 1))
"""
if not torch.is_tensor(input):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 5:
- raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}".format(input.shape))
if temperature <= 0:
- raise ValueError("Temperature should be positive float or tensor. Got: {}"
- .format(temperature))
+ raise ValueError("Temperature should be positive float or tensor. Got: {}".format(temperature))
b, c, d, h, w = input.shape
kx, ky, kz = kernel_size
@@ -425,27 +403,17 @@ def conv_soft_argmax3d(input: torch.Tensor,
pool_coef: float = float(kx * ky * kz)
# softmax denominator
- den = pool_coef * F.avg_pool3d(x_exp.view_as(input),
- kernel_size,
- stride=stride,
- padding=padding) + eps
+ den = pool_coef * F.avg_pool3d(x_exp.view_as(input), kernel_size, stride=stride, padding=padding) + eps
# We need to output also coordinates
# Pooled window center coordinates
- grid_global: torch.Tensor = create_meshgrid3d(
- d, h, w, False, device=device).to(dtype).permute(0, 4, 1, 2, 3)
+ grid_global: torch.Tensor = create_meshgrid3d(d, h, w, False, device=device).to(dtype).permute(0, 4, 1, 2, 3)
- grid_global_pooled = F.conv3d(grid_global,
- center_kernel,
- stride=stride,
- padding=padding)
+ grid_global_pooled = F.conv3d(grid_global, center_kernel, stride=stride, padding=padding)
# Coordinates of maxima residual to window center
# prepare kernel
- coords_max: torch.Tensor = F.conv3d(x_exp,
- window_kernel,
- stride=stride,
- padding=padding)
+ coords_max: torch.Tensor = F.conv3d(x_exp, window_kernel, stride=stride, padding=padding)
coords_max = coords_max / den.expand_as(coords_max)
coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
@@ -462,10 +430,9 @@ def conv_soft_argmax3d(input: torch.Tensor,
if not output_value:
return coords_max
- x_softmaxpool = pool_coef * F.avg_pool3d(x_exp.view(input.size()) * input,
- kernel_size,
- stride=stride,
- padding=padding) / den
+ x_softmaxpool = pool_coef * F.avg_pool3d(
+ x_exp.view(input.size()) * input, kernel_size, stride=stride, padding=padding
+ ) / den
if strict_maxima_bonus > 0:
in_levels: int = input.size(2)
out_levels: int = x_softmaxpool.size(2)
@@ -473,19 +440,16 @@ def conv_soft_argmax3d(input: torch.Tensor,
strict_maxima: torch.Tensor = F.avg_pool3d(kornia.feature.nms3d(input, kernel_size), 1, stride, 0)
strict_maxima = strict_maxima[:, :, skip_levels:out_levels - skip_levels]
x_softmaxpool *= 1.0 + strict_maxima_bonus * strict_maxima
- x_softmaxpool = x_softmaxpool.view(b,
- c,
- x_softmaxpool.size(2),
- x_softmaxpool.size(3),
- x_softmaxpool.size(4))
+ x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3), x_softmaxpool.size(4))
return coords_max, x_softmaxpool
def spatial_soft_argmax2d(
- input: torch.Tensor,
- temperature: torch.Tensor = torch.tensor(1.0),
- normalized_coordinates: bool = True,
- eps: float = 1e-8) -> torch.Tensor:
+ input: torch.Tensor,
+ temperature: torch.Tensor = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8
+) -> torch.Tensor:
r"""Function that computes the Spatial Soft-Argmax 2D
of a given input heatmap.
@@ -523,10 +487,12 @@ class SpatialSoftArgmax2d(nn.Module):
See :func:`~kornia.geometry.subpix.spatial_soft_argmax2d` for details.
"""
- def __init__(self,
- temperature: torch.Tensor = torch.tensor(1.0),
- normalized_coordinates: bool = True,
- eps: float = 1e-8) -> None:
+ def __init__(
+ self,
+ temperature: torch.Tensor = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8
+ ) -> None:
super(SpatialSoftArgmax2d, self).__init__()
self.temperature: torch.Tensor = temperature
self.normalized_coordinates: bool = normalized_coordinates
@@ -539,8 +505,7 @@ class SpatialSoftArgmax2d(nn.Module):
'eps=' + str(self.eps) + ')'
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return spatial_soft_argmax2d(input, self.temperature,
- self.normalized_coordinates, self.eps)
+ return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates, self.eps)
def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7):
@@ -572,15 +537,12 @@ def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, e
>>> nms_coords, nms_val = conv_quad_interp3d(input, 1.0)
"""
if not torch.is_tensor(input):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 5:
- raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}".format(input.shape))
B, CH, D, H, W = input.shape
dev: torch.device = input.device
- grid_global: torch.Tensor = create_meshgrid3d(D, H, W, False,
- device=input.device).permute(0, 4, 1, 2, 3)
+ grid_global: torch.Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)
grid_global = grid_global.to(input.dtype)
# to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient
@@ -596,9 +558,7 @@ def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, e
dys = 0.25 * A[..., 4] # normalization to match OpenCV implementation
dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementation
- Hes = torch.stack([dxx, dxy, dxs,
- dxy, dyy, dys,
- dxs, dys, dss], dim=-1).view(-1, 3, 3)
+ Hes = torch.stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], dim=-1).view(-1, 3, 3)
# The following is needed to avoid singular cases
Hes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
@@ -629,8 +589,7 @@ class ConvQuadInterp3d(nn.Module):
See :func:`~kornia.geometry.subpix.conv_quad_interp3d` for details.
"""
- def __init__(self,
- strict_maxima_bonus: float = 10.0, eps: float = 1e-7) -> None:
+ def __init__(self, strict_maxima_bonus: float = 10.0, eps: float = 1e-7) -> None:
super(ConvQuadInterp3d, self).__init__()
self.strict_maxima_bonus = strict_maxima_bonus
self.eps = eps
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 63a9f14a2..f69a66646 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -6,12 +6,8 @@ import torch.nn as nn
from math import ceil
import kornia
-from kornia.geometry.transform.imgwarp import (
- warp_affine, get_rotation_matrix2d, get_affine_matrix2d
-)
-from kornia.geometry.transform.projwarp import (
- warp_affine3d, get_projective_transform
-)
+from kornia.geometry.transform.imgwarp import (warp_affine, get_rotation_matrix2d, get_affine_matrix2d)
+from kornia.geometry.transform.projwarp import (warp_affine3d, get_projective_transform)
from kornia.utils import _extract_device_dtype
from kornia.utils.image import _to_bchw
@@ -43,9 +39,7 @@ def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
height, width = tensor.shape[-2:]
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
- center: torch.Tensor = torch.tensor(
- [center_x, center_y],
- device=tensor.device, dtype=tensor.dtype)
+ center: torch.Tensor = torch.tensor([center_x, center_y], device=tensor.device, dtype=tensor.dtype)
return center
@@ -56,22 +50,20 @@ def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
center_z: float = float(depth - 1) / 2
- center: torch.Tensor = torch.tensor(
- [center_x, center_y, center_z],
- device=tensor.device, dtype=tensor.dtype)
+ center: torch.Tensor = torch.tensor([center_x, center_y, center_z], device=tensor.device, dtype=tensor.dtype)
return center
-def _compute_rotation_matrix(angle: torch.Tensor,
- center: torch.Tensor) -> torch.Tensor:
+def _compute_rotation_matrix(angle: torch.Tensor, center: torch.Tensor) -> torch.Tensor:
"""Computes a pure affine rotation matrix."""
scale: torch.Tensor = torch.ones_like(center)
matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
return matrix
-def _compute_rotation_matrix3d(yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor,
- center: torch.Tensor) -> torch.Tensor:
+def _compute_rotation_matrix3d(
+ yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor, center: torch.Tensor
+) -> torch.Tensor:
"""Computes a pure affine rotation matrix."""
if len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 0:
yaw = yaw.unsqueeze(dim=0)
@@ -94,8 +86,7 @@ def _compute_rotation_matrix3d(yaw: torch.Tensor, pitch: torch.Tensor, roll: tor
def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:
"""Computes affine matrix for translation."""
- matrix: torch.Tensor = torch.eye(
- 3, device=translation.device, dtype=translation.dtype)
+ matrix: torch.Tensor = torch.eye(3, device=translation.device, dtype=translation.dtype)
matrix = matrix.repeat(translation.shape[0], 1, 1)
dx, dy = torch.chunk(translation, chunks=2, dim=-1)
@@ -104,8 +95,7 @@ def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:
return matrix
-def _compute_scaling_matrix(scale: torch.Tensor,
- center: torch.Tensor) -> torch.Tensor:
+def _compute_scaling_matrix(scale: torch.Tensor, center: torch.Tensor) -> torch.Tensor:
"""Computes affine matrix for scaling."""
angle: torch.Tensor = torch.zeros(scale.shape[:1], device=scale.device, dtype=scale.dtype)
matrix: torch.Tensor = get_rotation_matrix2d(center, angle, scale)
@@ -126,9 +116,14 @@ def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:
# based on:
# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L166
-def affine(tensor: torch.Tensor, matrix: torch.Tensor,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+
+def affine(
+ tensor: torch.Tensor,
+ matrix: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Apply an affine transformation to the image.
Args:
@@ -163,8 +158,7 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor,
# warp the input tensor
height: int = tensor.shape[-2]
width: int = tensor.shape[-1]
- warped: torch.Tensor = warp_affine(tensor, matrix, (height, width),
- mode, padding_mode, align_corners)
+ warped: torch.Tensor = warp_affine(tensor, matrix, (height, width), mode, padding_mode, align_corners)
# return in the original shape
if is_unbatched:
@@ -173,9 +167,13 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor,
return warped
-def affine3d(tensor: torch.Tensor, matrix: torch.Tensor,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: bool = False) -> torch.Tensor:
+def affine3d(
+ tensor: torch.Tensor,
+ matrix: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False
+) -> torch.Tensor:
r"""Apply an affine transformation to the 3d volume.
Args:
@@ -211,8 +209,7 @@ def affine3d(tensor: torch.Tensor, matrix: torch.Tensor,
depth: int = tensor.shape[-3]
height: int = tensor.shape[-2]
width: int = tensor.shape[-1]
- warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width),
- mode, padding_mode, align_corners)
+ warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode, padding_mode, align_corners)
# return in the original shape
if is_unbatched:
@@ -224,10 +221,15 @@ def affine3d(tensor: torch.Tensor, matrix: torch.Tensor,
# based on:
# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L185
-def rotate(tensor: torch.Tensor, angle: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+
+def rotate(
+ tensor: torch.Tensor,
+ angle: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Rotate the tensor anti-clockwise about the centre.
Args:
@@ -254,20 +256,19 @@ def rotate(tensor: torch.Tensor, angle: torch.Tensor,
torch.Size([1, 3, 4, 4])
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(angle, torch.Tensor):
- raise TypeError("Input angle type is not a torch.Tensor. Got {}"
- .format(type(angle)))
+ raise TypeError("Input angle type is not a torch.Tensor. Got {}".format(type(angle)))
if center is not None and not isinstance(center, torch.Tensor):
- raise TypeError("Input center type is not a torch.Tensor. Got {}"
- .format(type(center)))
+ raise TypeError("Input center type is not a torch.Tensor. Got {}".format(type(center)))
- if len(tensor.shape) not in (3, 4,):
- raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. "
- "Got: {}".format(tensor.shape))
+ if len(tensor.shape) not in (
+ 3,
+ 4,
+ ):
+ raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. " "Got: {}".format(tensor.shape))
# compute the rotation center
if center is None:
@@ -283,11 +284,16 @@ def rotate(tensor: torch.Tensor, angle: torch.Tensor,
return affine(tensor, rotation_matrix[..., :2, :3], mode, padding_mode, align_corners)
-def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor,
- pitch: torch.Tensor, roll: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: bool = False) -> torch.Tensor:
+def rotate3d(
+ tensor: torch.Tensor,
+ yaw: torch.Tensor,
+ pitch: torch.Tensor,
+ roll: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False
+) -> torch.Tensor:
r"""Rotate 3D the tensor anti-clockwise about the centre.
Args:
@@ -311,8 +317,7 @@ def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor,
torch.Tensor: The rotated tensor with shape as input.
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(yaw, torch.Tensor):
raise TypeError("yaw is not a torch.Tensor. Got {}".format(type(yaw)))
@@ -324,12 +329,13 @@ def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor,
raise TypeError("roll is not a torch.Tensor. Got {}".format(type(roll)))
if center is not None and not isinstance(center, torch.Tensor):
- raise TypeError("Input center type is not a torch.Tensor. Got {}"
- .format(type(center)))
+ raise TypeError("Input center type is not a torch.Tensor. Got {}".format(type(center)))
- if len(tensor.shape) not in (4, 5,):
- raise ValueError("Invalid tensor shape, we expect CxDxHxW or BxCxDxHxW. "
- "Got: {}".format(tensor.shape))
+ if len(tensor.shape) not in (
+ 4,
+ 5,
+ ):
+ raise ValueError("Invalid tensor shape, we expect CxDxHxW or BxCxDxHxW. " "Got: {}".format(tensor.shape))
# compute the rotation center
if center is None:
@@ -347,9 +353,13 @@ def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor,
return affine3d(tensor, rotation_matrix[..., :3, :4], mode, padding_mode, align_corners)
-def translate(tensor: torch.Tensor, translation: torch.Tensor,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def translate(
+ tensor: torch.Tensor,
+ translation: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Translate the tensor in pixel units.
Args:
@@ -374,16 +384,16 @@ def translate(tensor: torch.Tensor, translation: torch.Tensor,
torch.Size([1, 3, 4, 4])
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(translation, torch.Tensor):
- raise TypeError("Input translation type is not a torch.Tensor. Got {}"
- .format(type(translation)))
+ raise TypeError("Input translation type is not a torch.Tensor. Got {}".format(type(translation)))
- if len(tensor.shape) not in (3, 4,):
- raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. "
- "Got: {}".format(tensor.shape))
+ if len(tensor.shape) not in (
+ 3,
+ 4,
+ ):
+ raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. " "Got: {}".format(tensor.shape))
# compute the translation matrix
translation_matrix: torch.Tensor = _compute_translation_matrix(translation)
@@ -392,10 +402,14 @@ def translate(tensor: torch.Tensor, translation: torch.Tensor,
return affine(tensor, translation_matrix[..., :2, :3], mode, padding_mode, align_corners)
-def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def scale(
+ tensor: torch.Tensor,
+ scale_factor: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Scale the tensor by a factor.
Args:
@@ -424,12 +438,10 @@ def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
torch.Size([1, 3, 4, 4])
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(scale_factor, torch.Tensor):
- raise TypeError("Input scale_factor type is not a torch.Tensor. Got {}"
- .format(type(scale_factor)))
+ raise TypeError("Input scale_factor type is not a torch.Tensor. Got {}".format(type(scale_factor)))
if len(scale_factor.shape) == 1:
# convert isotropic scaling to x-y direction
@@ -449,9 +461,13 @@ def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,
return affine(tensor, scaling_matrix[..., :2, :3], mode, padding_mode, align_corners)
-def shear(tensor: torch.Tensor, shear: torch.Tensor,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: bool = False) -> torch.Tensor:
+def shear(
+ tensor: torch.Tensor,
+ shear: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False
+) -> torch.Tensor:
r"""Shear the tensor.
Args:
@@ -476,16 +492,16 @@ def shear(tensor: torch.Tensor, shear: torch.Tensor,
torch.Size([1, 3, 4, 4])
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(shear, torch.Tensor):
- raise TypeError("Input shear type is not a torch.Tensor. Got {}"
- .format(type(shear)))
+ raise TypeError("Input shear type is not a torch.Tensor. Got {}".format(type(shear)))
- if len(tensor.shape) not in (3, 4,):
- raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. "
- "Got: {}".format(tensor.shape))
+ if len(tensor.shape) not in (
+ 3,
+ 4,
+ ):
+ raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. " "Got: {}".format(tensor.shape))
# compute the translation matrix
shear_matrix: torch.Tensor = _compute_shear_matrix(shear)
@@ -494,9 +510,7 @@ def shear(tensor: torch.Tensor, shear: torch.Tensor,
return affine(tensor, shear_matrix[..., :2, :3], mode, padding_mode, align_corners)
-def _side_to_image_size(
- side_size: int, aspect_ratio: float, side: str = "short"
-) -> Tuple[int, int]:
+def _side_to_image_size(side_size: int, aspect_ratio: float, side: str = "short") -> Tuple[int, int]:
if side not in ("short", "long", "vert", "horz"):
raise ValueError(f"side can be one of 'short', 'long', 'vert', and 'horz'. Got '{side}'")
if side == "vert":
@@ -509,9 +523,14 @@ def _side_to_image_size(
return int(side_size / aspect_ratio), side_size
-def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]],
- interpolation: str = 'bilinear', align_corners: Optional[bool] = None,
- side: str = "short", antialias: bool = False) -> torch.Tensor:
+def resize(
+ input: torch.Tensor,
+ size: Union[int, Tuple[int, int]],
+ interpolation: str = 'bilinear',
+ align_corners: Optional[bool] = None,
+ side: str = "short",
+ antialias: bool = False
+) -> torch.Tensor:
r"""Resize the input torch.Tensor to the given size.
Args:
@@ -540,8 +559,7 @@ def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]],
torch.Size([1, 3, 6, 8])
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(input)))
input_size = h, w = input.shape[-2:]
if isinstance(size, int):
@@ -569,8 +587,7 @@ def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]],
ks = int(2.0 * 2 * sigmas[0] + 1), int(2.0 * 2 * sigmas[1] + 1)
input_tmp = kornia.filters.gaussian_blur2d(input_tmp, ks, sigmas)
- output = torch.nn.functional.interpolate(
- input_tmp, size=size, mode=interpolation, align_corners=align_corners)
+ output = torch.nn.functional.interpolate(input_tmp, size=size, mode=interpolation, align_corners=align_corners)
if len(input.shape) != len(output.shape):
output = output.squeeze()
@@ -644,9 +661,14 @@ class Resize(nn.Module):
torch.Size([1, 3, 6, 8])
"""
- def __init__(self, size: Union[int, Tuple[int, int]], interpolation: str = 'bilinear',
- align_corners: Optional[bool] = None, side: str = "short",
- antialias: bool = False) -> None:
+ def __init__(
+ self,
+ size: Union[int, Tuple[int, int]],
+ interpolation: str = 'bilinear',
+ align_corners: Optional[bool] = None,
+ side: str = "short",
+ antialias: bool = False
+ ) -> None:
super(Resize, self).__init__()
self.size: Union[int, Tuple[int, int]] = size
self.interpolation: str = interpolation
@@ -655,8 +677,14 @@ class Resize(nn.Module):
self.antialias: bool = antialias
def forward(self, input: torch.Tensor) -> torch.Tensor:
- return resize(input, self.size, self.interpolation,
- align_corners=self.align_corners, side=self.side, antialias=self.antialias)
+ return resize(
+ input,
+ self.size,
+ self.interpolation,
+ align_corners=self.align_corners,
+ side=self.side,
+ antialias=self.antialias
+ )
class Affine(nn.Module):
@@ -695,15 +723,15 @@ class Affine(nn.Module):
"""
def __init__(
- self,
- angle: Optional[torch.Tensor] = None,
- translation: Optional[torch.Tensor] = None,
- scale_factor: Optional[torch.Tensor] = None,
- shear: Optional[torch.Tensor] = None,
- center: Optional[torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ self,
+ angle: Optional[torch.Tensor] = None,
+ translation: Optional[torch.Tensor] = None,
+ scale_factor: Optional[torch.Tensor] = None,
+ shear: Optional[torch.Tensor] = None,
+ center: Optional[torch.Tensor] = None,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
) -> None:
batch_sizes = [arg.size()[0] for arg in (angle, translation, scale_factor, shear) if arg is not None]
if not batch_sizes:
@@ -792,8 +820,9 @@ class Rescale(nn.Module):
self.antialias: bool = antialias
def forward(self, input: torch.Tensor) -> torch.Tensor:
- return rescale(input, self.factor, self.interpolation,
- align_corners=self.align_corners, antialias=self.antialias)
+ return rescale(
+ input, self.factor, self.interpolation, align_corners=self.align_corners, antialias=self.antialias
+ )
class Rotate(nn.Module):
@@ -822,11 +851,14 @@ class Rotate(nn.Module):
torch.Size([1, 3, 4, 4])
"""
- def __init__(self, angle: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> None:
+ def __init__(
+ self,
+ angle: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+ ) -> None:
super(Rotate, self).__init__()
self.angle: torch.Tensor = angle
self.center: Union[None, torch.Tensor] = center
@@ -862,10 +894,13 @@ class Translate(nn.Module):
torch.Size([1, 3, 4, 4])
"""
- def __init__(self, translation: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> None:
+ def __init__(
+ self,
+ translation: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+ ) -> None:
super(Translate, self).__init__()
self.translation: torch.Tensor = translation
self.mode: str = mode
@@ -904,11 +939,14 @@ class Scale(nn.Module):
torch.Size([1, 3, 4, 4])
"""
- def __init__(self, scale_factor: torch.Tensor,
- center: Union[None, torch.Tensor] = None,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> None:
+ def __init__(
+ self,
+ scale_factor: torch.Tensor,
+ center: Union[None, torch.Tensor] = None,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+ ) -> None:
super(Scale, self).__init__()
self.scale_factor: torch.Tensor = scale_factor
self.center: Union[None, torch.Tensor] = center
@@ -945,10 +983,13 @@ class Shear(nn.Module):
torch.Size([1, 3, 4, 4])
"""
- def __init__(self, shear: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = False) -> None:
+ def __init__(
+ self,
+ shear: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False
+ ) -> None:
super(Shear, self).__init__()
self.shear: torch.Tensor = shear
self.mode: str = mode
diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.py
index 318a99efa..0c40ffd7b 100644
--- a/kornia/geometry/transform/crop/crop2d.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -2,9 +2,7 @@ from typing import Tuple, Union, Optional
import torch
-from kornia.geometry.transform.imgwarp import (
- warp_perspective, get_perspective_transform, warp_affine
-)
+from kornia.geometry.transform.imgwarp import (warp_perspective, get_perspective_transform, warp_affine)
__all__ = [
"crop_and_resize",
@@ -18,9 +16,14 @@ __all__ = [
]
-def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int],
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def crop_and_resize(
+ tensor: torch.Tensor,
+ boxes: torch.Tensor,
+ size: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Extract crops from 2D images (4D tensor) and resize given a bounding box.
Args:
@@ -58,16 +61,16 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
[10., 11.]]]])
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(boxes, torch.Tensor):
- raise TypeError("Input boxes type is not a torch.Tensor. Got {}"
- .format(type(boxes)))
+ raise TypeError("Input boxes type is not a torch.Tensor. Got {}".format(type(boxes)))
- if not isinstance(size, (tuple, list,)) and len(size) == 2:
- raise ValueError("Input size must be a tuple/list of length 2. Got {}"
- .format(size))
+ if not isinstance(size, (
+ tuple,
+ list,
+ )) and len(size) == 2:
+ raise ValueError("Input size must be a tuple/list of length 2. Got {}".format(size))
assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
@@ -80,19 +83,25 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
# [x, y] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0],
- [dst_w - 1, 0],
- [dst_w - 1, dst_h - 1],
- [0, dst_h - 1],
- ]], device=tensor.device, dtype=tensor.dtype).expand(points_src.shape[0], -1, -1)
+ points_dst: torch.Tensor = torch.tensor(
+ [[
+ [0, 0],
+ [dst_w - 1, 0],
+ [dst_w - 1, dst_h - 1],
+ [0, dst_h - 1],
+ ]], device=tensor.device, dtype=tensor.dtype
+ ).expand(points_src.shape[0], -1, -1)
return crop_by_boxes(tensor, points_src, points_dst, mode, padding_mode, align_corners)
-def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def center_crop(
+ tensor: torch.Tensor,
+ size: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Crop the 2D images (4D tensor) from the center.
Args:
@@ -120,12 +129,13 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
[ 9., 10., 11., 12.]]]])
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
- if not isinstance(size, (tuple, list,)) and len(size) == 2:
- raise ValueError("Input size must be a tuple/list of length 2. Got {}"
- .format(size))
+ if not isinstance(size, (
+ tuple,
+ list,
+ )) and len(size) == 2:
+ raise ValueError("Input size must be a tuple/list of length 2. Got {}".format(size))
assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
@@ -147,29 +157,39 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: torch.Tensor = torch.tensor([[
- [start_x, start_y],
- [end_x, start_y],
- [end_x, end_y],
- [start_x, end_y],
- ]], device=tensor.device, dtype=tensor.dtype)
+ points_src: torch.Tensor = torch.tensor(
+ [[
+ [start_x, start_y],
+ [end_x, start_y],
+ [end_x, end_y],
+ [start_x, end_y],
+ ]],
+ device=tensor.device,
+ dtype=tensor.dtype
+ )
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0],
- [dst_w - 1, 0],
- [dst_w - 1, dst_h - 1],
- [0, dst_h - 1],
- ]], device=tensor.device, dtype=tensor.dtype).expand(points_src.shape[0], -1, -1)
+ points_dst: torch.Tensor = torch.tensor(
+ [[
+ [0, 0],
+ [dst_w - 1, 0],
+ [dst_w - 1, dst_h - 1],
+ [0, dst_h - 1],
+ ]], device=tensor.device, dtype=tensor.dtype
+ ).expand(points_src.shape[0], -1, -1)
- return crop_by_boxes(tensor, points_src, points_dst,
- mode, padding_mode, align_corners)
+ return crop_by_boxes(tensor, points_src, points_dst, mode, padding_mode, align_corners)
-def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Tensor,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def crop_by_boxes(
+ tensor: torch.Tensor,
+ src_box: torch.Tensor,
+ dst_box: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
"""Perform crop transform on 2D images (4D tensor) given two bounding boxes.
Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
@@ -224,25 +244,29 @@ def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Te
# compute transformation between points and warp
# Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
- dst_trans_src: torch.Tensor = get_perspective_transform(
- src_box.to(tensor), dst_box.to(tensor))
+ dst_trans_src: torch.Tensor = get_perspective_transform(src_box.to(tensor), dst_box.to(tensor))
bbox: Tuple[torch.Tensor, torch.Tensor] = infer_box_shape(dst_box)
assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all(), (
f"Cropping height, width and depth must be exact same in a batch. "
- f"Got height {bbox[0]} and width {bbox[1]}.")
+ f"Got height {bbox[0]} and width {bbox[1]}."
+ )
h_out: int = int(bbox[0][0].item())
w_out: int = int(bbox[1][0].item())
return crop_by_transform_mat(
- tensor, dst_trans_src, (h_out, w_out),
- mode=mode, padding_mode=padding_mode, align_corners=align_corners)
+ tensor, dst_trans_src, (h_out, w_out), mode=mode, padding_mode=padding_mode, align_corners=align_corners
+ )
def crop_by_transform_mat(
- tensor: torch.Tensor, transform: torch.Tensor, out_size: Tuple[int, int],
- mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: Optional[bool] = None
+ tensor: torch.Tensor,
+ transform: torch.Tensor,
+ out_size: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
) -> torch.Tensor:
"""Perform crop transform on 2D images (4D tensor) given a perspective transformation matrix.
@@ -260,12 +284,11 @@ def crop_by_transform_mat(
torch.Tensor: the output tensor with patches.
"""
# simulate broadcasting
- dst_trans_src = torch.as_tensor(
- transform.expand(tensor.shape[0], -1, -1), device=tensor.device, dtype=tensor.dtype)
+ dst_trans_src = torch.as_tensor(transform.expand(tensor.shape[0], -1, -1), device=tensor.device, dtype=tensor.dtype)
patches: torch.Tensor = warp_affine(
- tensor, dst_trans_src[:, :2, :], out_size,
- mode=mode, padding_mode=padding_mode, align_corners=align_corners)
+ tensor, dst_trans_src[:, :2, :], out_size, mode=mode, padding_mode=padding_mode, align_corners=align_corners
+ )
return patches
@@ -319,17 +342,17 @@ def validate_bboxes(boxes: torch.Tensor) -> bool:
order: top-left, top-right, bottom-right, bottom-left. The
coordinates must be in the x, y order.
"""
- if not torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1),
- (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)):
- raise ValueError("Boxes must have be rectangular, while get widths %s and %s" %
- (str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1),
- str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1)))
-
- if not torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1),
- (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)):
- raise ValueError("Boxes must have be rectangular, while get heights %s and %s" %
- (str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1),
- str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1)))
+ if not torch.allclose((boxes[:, 1, 0] - boxes[:, 0, 0] + 1), (boxes[:, 2, 0] - boxes[:, 3, 0] + 1)):
+ raise ValueError(
+ "Boxes must have be rectangular, while get widths %s and %s" %
+ (str(boxes[:, 1, 0] - boxes[:, 0, 0] + 1), str(boxes[:, 2, 0] - boxes[:, 3, 0] + 1))
+ )
+
+ if not torch.allclose((boxes[:, 2, 1] - boxes[:, 0, 1] + 1), (boxes[:, 3, 1] - boxes[:, 1, 1] + 1)):
+ raise ValueError(
+ "Boxes must have be rectangular, while get heights %s and %s" %
+ (str(boxes[:, 2, 1] - boxes[:, 0, 1] + 1), str(boxes[:, 3, 1] - boxes[:, 1, 1] + 1))
+ )
return True
diff --git a/kornia/geometry/transform/crop/crop3d.py b/kornia/geometry/transform/crop/crop3d.py
index d6f92a832..0dffa139a 100644
--- a/kornia/geometry/transform/crop/crop3d.py
+++ b/kornia/geometry/transform/crop/crop3d.py
@@ -2,9 +2,7 @@ from typing import Tuple, Optional
import torch
-from kornia.geometry.transform.projwarp import (
- get_perspective_transform3d, warp_affine3d
-)
+from kornia.geometry.transform.projwarp import (get_perspective_transform3d, warp_affine3d)
__all__ = [
"crop_and_resize3d",
@@ -18,8 +16,13 @@ __all__ = [
]
-def crop_and_resize3d(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int, int],
- interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
+def crop_and_resize3d(
+ tensor: torch.Tensor,
+ boxes: torch.Tensor,
+ size: Tuple[int, int, int],
+ interpolation: str = 'bilinear',
+ align_corners: bool = False
+) -> torch.Tensor:
r"""Extract crops from 3D volumes (5D tensor) and resize them.
Args:
@@ -77,14 +80,14 @@ def crop_and_resize3d(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int
[45.0000, 47.0000]]]]])
"""
if not isinstance(tensor, (torch.Tensor)):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(boxes, (torch.Tensor)):
- raise TypeError("Input boxes type is not a torch.Tensor. Got {}"
- .format(type(boxes)))
- if not isinstance(size, (tuple, list,)) and len(size) != 3:
- raise ValueError("Input size must be a tuple/list of length 3. Got {}"
- .format(size))
+ raise TypeError("Input boxes type is not a torch.Tensor. Got {}".format(type(boxes)))
+ if not isinstance(size, (
+ tuple,
+ list,
+ )) and len(size) != 3:
+ raise ValueError("Input size must be a tuple/list of length 3. Got {}".format(size))
assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
# unpack input data
dst_d, dst_h, dst_w = size[0], size[1], size[2]
@@ -97,23 +100,32 @@ def crop_and_resize3d(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int
# [x, y, z] destination
# from front to back
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0, 0],
- [dst_w - 1, 0, 0],
- [dst_w - 1, dst_h - 1, 0],
- [0, dst_h - 1, 0],
- [0, 0, dst_d - 1],
- [dst_w - 1, 0, dst_d - 1],
- [dst_w - 1, dst_h - 1, dst_d - 1],
- [0, dst_h - 1, dst_d - 1],
- ]], dtype=tensor.dtype, device=tensor.device).expand(points_src.shape[0], -1, -1)
+ points_dst: torch.Tensor = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [dst_w - 1, 0, 0],
+ [dst_w - 1, dst_h - 1, 0],
+ [0, dst_h - 1, 0],
+ [0, 0, dst_d - 1],
+ [dst_w - 1, 0, dst_d - 1],
+ [dst_w - 1, dst_h - 1, dst_d - 1],
+ [0, dst_h - 1, dst_d - 1],
+ ]
+ ],
+ dtype=tensor.dtype,
+ device=tensor.device
+ ).expand(points_src.shape[0], -1, -1)
return crop_by_boxes3d(tensor, points_src, points_dst, interpolation, align_corners)
-def center_crop3d(tensor: torch.Tensor, size: Tuple[int, int, int],
- interpolation: str = 'bilinear',
- align_corners: bool = True) -> torch.Tensor:
+def center_crop3d(
+ tensor: torch.Tensor,
+ size: Tuple[int, int, int],
+ interpolation: str = 'bilinear',
+ align_corners: bool = True
+) -> torch.Tensor:
r"""Crop the 3D volumes (5D tensor) at the center.
Args:
@@ -157,14 +169,15 @@ def center_crop3d(tensor: torch.Tensor, size: Tuple[int, int, int],
[41.0000, 42.0000]]]]])
"""
if not isinstance(tensor, (torch.Tensor)):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
- if not isinstance(size, (tuple, list,)) and len(size) == 3:
- raise ValueError("Input size must be a tuple/list of length 3. Got {}"
- .format(size))
+ if not isinstance(size, (
+ tuple,
+ list,
+ )) and len(size) == 3:
+ raise ValueError("Input size must be a tuple/list of length 3. Got {}".format(size))
# unpack input sizes
dst_d, dst_h, dst_w = size
@@ -188,40 +201,53 @@ def center_crop3d(tensor: torch.Tensor, size: Tuple[int, int, int],
# [x, y, z] origin
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
- points_src: torch.Tensor = torch.tensor([[
- [start_x, start_y, start_z],
- [end_x, start_y, start_z],
- [end_x, end_y, start_z],
- [start_x, end_y, start_z],
- [start_x, start_y, end_z],
- [end_x, start_y, end_z],
- [end_x, end_y, end_z],
- [start_x, end_y, end_z],
- ]], device=tensor.device)
+ points_src: torch.Tensor = torch.tensor(
+ [
+ [
+ [start_x, start_y, start_z],
+ [end_x, start_y, start_z],
+ [end_x, end_y, start_z],
+ [start_x, end_y, start_z],
+ [start_x, start_y, end_z],
+ [end_x, start_y, end_z],
+ [end_x, end_y, end_z],
+ [start_x, end_y, end_z],
+ ]
+ ],
+ device=tensor.device
+ )
# [x, y, z] destination
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
- points_dst: torch.Tensor = torch.tensor([[
- [0, 0, 0],
- [dst_w - 1, 0, 0],
- [dst_w - 1, dst_h - 1, 0],
- [0, dst_h - 1, 0],
- [0, 0, dst_d - 1],
- [dst_w - 1, 0, dst_d - 1],
- [dst_w - 1, dst_h - 1, dst_d - 1],
- [0, dst_h - 1, dst_d - 1],
- ]], device=tensor.device).expand(points_src.shape[0], -1, -1)
-
- return crop_by_boxes3d(tensor,
- points_src.to(tensor.dtype),
- points_dst.to(tensor.dtype),
- interpolation,
- align_corners)
-
-
-def crop_by_boxes3d(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Tensor,
- interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
+ points_dst: torch.Tensor = torch.tensor(
+ [
+ [
+ [0, 0, 0],
+ [dst_w - 1, 0, 0],
+ [dst_w - 1, dst_h - 1, 0],
+ [0, dst_h - 1, 0],
+ [0, 0, dst_d - 1],
+ [dst_w - 1, 0, dst_d - 1],
+ [dst_w - 1, dst_h - 1, dst_d - 1],
+ [0, dst_h - 1, dst_d - 1],
+ ]
+ ],
+ device=tensor.device
+ ).expand(points_src.shape[0], -1, -1)
+
+ return crop_by_boxes3d(
+ tensor, points_src.to(tensor.dtype), points_dst.to(tensor.dtype), interpolation, align_corners
+ )
+
+
+def crop_by_boxes3d(
+ tensor: torch.Tensor,
+ src_box: torch.Tensor,
+ dst_box: torch.Tensor,
+ interpolation: str = 'bilinear',
+ align_corners: bool = False
+) -> torch.Tensor:
"""Perform crop transform on 3D volumes (5D tensor) by bounding boxes.
Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
@@ -304,19 +330,26 @@ def crop_by_boxes3d(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.
bbox = infer_box_shape3d(dst_box)
assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all() and (bbox[2] == bbox[2][0]).all(), (
"Cropping height, width and depth must be exact same in a batch."
- f"Got height {bbox[0]}, width {bbox[1]} and depth {bbox[2]}.")
+ f"Got height {bbox[0]}, width {bbox[1]} and depth {bbox[2]}."
+ )
patches: torch.Tensor = crop_by_transform_mat3d(
- tensor, dst_trans_src,
- (int(bbox[0][0].item()), int(bbox[1][0].item()), int(bbox[2][0].item())),
- mode=interpolation, align_corners=align_corners)
+ tensor,
+ dst_trans_src, (int(bbox[0][0].item()), int(bbox[1][0].item()), int(bbox[2][0].item())),
+ mode=interpolation,
+ align_corners=align_corners
+ )
return patches
def crop_by_transform_mat3d(
- tensor: torch.Tensor, transform: torch.Tensor, out_size: Tuple[int, int, int],
- mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: Optional[bool] = None
+ tensor: torch.Tensor,
+ transform: torch.Tensor,
+ out_size: Tuple[int, int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
) -> torch.Tensor:
"""Perform crop transform on 3D volumes (5D tensor) given a perspective transformation matrix.
@@ -337,8 +370,8 @@ def crop_by_transform_mat3d(
dst_trans_src = transform.expand(tensor.shape[0], -1, -1)
patches: torch.Tensor = warp_affine3d(
- tensor, dst_trans_src[:, :3, :], out_size,
- flags=mode, padding_mode=padding_mode, align_corners=align_corners)
+ tensor, dst_trans_src[:, :3, :], out_size, flags=mode, padding_mode=padding_mode, align_corners=align_corners
+ )
return patches
@@ -478,15 +511,18 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Ten
mask_out = []
# TODO: Looking for a vectorized way
for m, box in zip(mask, boxes):
- m = m.index_fill(0, torch.arange(
- box[0, 2].item(), box[4, 2].item() + 1, device=box.device, dtype=torch.long
- ), torch.tensor(1, device=box.device, dtype=box.dtype))
- m = m.index_fill(1, torch.arange(
- box[1, 1].item(), box[2, 1].item() + 1, device=box.device, dtype=torch.long
- ), torch.tensor(1, device=box.device, dtype=box.dtype))
- m = m.index_fill(2, torch.arange(
- box[0, 0].item(), box[1, 0].item() + 1, device=box.device, dtype=torch.long
- ), torch.tensor(1, device=box.device, dtype=box.dtype))
+ m = m.index_fill(
+ 0, torch.arange(box[0, 2].item(), box[4, 2].item() + 1, device=box.device, dtype=torch.long),
+ torch.tensor(1, device=box.device, dtype=box.dtype)
+ )
+ m = m.index_fill(
+ 1, torch.arange(box[1, 1].item(), box[2, 1].item() + 1, device=box.device, dtype=torch.long),
+ torch.tensor(1, device=box.device, dtype=box.dtype)
+ )
+ m = m.index_fill(
+ 2, torch.arange(box[0, 0].item(), box[1, 0].item() + 1, device=box.device, dtype=torch.long),
+ torch.tensor(1, device=box.device, dtype=box.dtype)
+ )
m = m.unsqueeze(dim=0)
m_out = torch.ones_like(m)
m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=1, keepdim=True)
@@ -498,8 +534,8 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Ten
def bbox_generator3d(
- x_start: torch.Tensor, y_start: torch.Tensor, z_start: torch.Tensor,
- width: torch.Tensor, height: torch.Tensor, depth: torch.Tensor
+ x_start: torch.Tensor, y_start: torch.Tensor, z_start: torch.Tensor, width: torch.Tensor, height: torch.Tensor,
+ depth: torch.Tensor
) -> torch.Tensor:
"""Generate 3D bounding boxes according to the provided start coords, width, height and depth.
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 3327d065b..ae7fa7ef5 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -6,17 +6,18 @@ import torch.nn.functional as F
import kornia
from kornia.filters.kernels import get_gaussian_kernel2d
-
__all__ = ["elastic_transform2d"]
-def elastic_transform2d(image: torch.Tensor,
- noise: torch.Tensor,
- kernel_size: Tuple[int, int] = (63, 63),
- sigma: Tuple[float, float] = (32., 32.),
- alpha: Tuple[float, float] = (1., 1.),
- align_corners: bool = False,
- mode: str = 'bilinear') -> torch.Tensor:
+def elastic_transform2d(
+ image: torch.Tensor,
+ noise: torch.Tensor,
+ kernel_size: Tuple[int, int] = (63, 63),
+ sigma: Tuple[float, float] = (32., 32.),
+ alpha: Tuple[float, float] = (1., 1.),
+ align_corners: bool = False,
+ mode: str = 'bilinear'
+) -> torch.Tensor:
r"""Applies elastic transform of images as described in :cite:`Simard2003BestPF`.
Args:
@@ -86,7 +87,6 @@ def elastic_transform2d(image: torch.Tensor,
# Warp image based on displacement matrix
b, c, h, w = image.shape
grid = kornia.utils.create_meshgrid(h, w, device=image.device).to(image.dtype)
- warped = F.grid_sample(
- image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode)
+ warped = F.grid_sample(image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode)
return warped
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 852ee3489..c959f0d60 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -71,13 +71,15 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
# functional api
-def homography_warp(patch_src: torch.Tensor,
- src_homo_dst: torch.Tensor,
- dsize: Tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = False,
- normalized_coordinates: bool = True) -> torch.Tensor:
+def homography_warp(
+ patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
+ dsize: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False,
+ normalized_coordinates: bool = True
+) -> torch.Tensor:
r"""Warp image patchs or tensors by normalized 2D homographies.
See :class:`~kornia.geometry.warp.HomographyWarper` for details.
@@ -107,25 +109,27 @@ def homography_warp(patch_src: torch.Tensor,
>>> output = homography_warp(input, homography, (32, 32))
"""
if not src_homo_dst.device == patch_src.device:
- raise TypeError("Patch and homography must be on the same device. \
- Got patch.device: {} src_H_dst.device: {}.".format(
- patch_src.device, src_homo_dst.device))
+ raise TypeError(
+ "Patch and homography must be on the same device. \
+ Got patch.device: {} src_H_dst.device: {}.".format(patch_src.device, src_homo_dst.device)
+ )
height, width = dsize
grid = create_meshgrid(height, width, normalized_coordinates=normalized_coordinates)
warped_grid = warp_grid(grid, src_homo_dst)
- return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode,
- align_corners=align_corners)
+ return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
-def homography_warp3d(patch_src: torch.Tensor,
- src_homo_dst: torch.Tensor,
- dsize: Tuple[int, int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = False,
- normalized_coordinates: bool = True) -> torch.Tensor:
+def homography_warp3d(
+ patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False,
+ normalized_coordinates: bool = True
+) -> torch.Tensor:
r"""Warp image patchs or tensors by normalized 3D homographies.
Args:
@@ -153,17 +157,18 @@ def homography_warp3d(patch_src: torch.Tensor,
>>> output = homography_warp(input, homography, (32, 32))
"""
if not src_homo_dst.device == patch_src.device:
- raise TypeError("Patch and homography must be on the same device. \
- Got patch.device: {} src_H_dst.device: {}.".format(
- patch_src.device, src_homo_dst.device))
+ raise TypeError(
+ "Patch and homography must be on the same device. \
+ Got patch.device: {} src_H_dst.device: {}.".format(patch_src.device, src_homo_dst.device)
+ )
depth, height, width = dsize
- grid = create_meshgrid3d(depth, height, width, normalized_coordinates=normalized_coordinates,
- device=patch_src.device)
+ grid = create_meshgrid3d(
+ depth, height, width, normalized_coordinates=normalized_coordinates, device=patch_src.device
+ )
warped_grid = warp_grid3d(grid, src_homo_dst)
- return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode,
- align_corners=align_corners)
+ return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
# layer api
@@ -189,13 +194,14 @@ class HomographyWarper(nn.Module):
_warped_grid: Optional[torch.Tensor]
def __init__(
- self,
- height: int,
- width: int,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- normalized_coordinates: bool = True,
- align_corners: bool = False) -> None:
+ self,
+ height: int,
+ width: int,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ normalized_coordinates: bool = True,
+ align_corners: bool = False
+ ) -> None:
super(HomographyWarper, self).__init__()
self.width: int = width
self.height: int = height
@@ -204,8 +210,7 @@ class HomographyWarper(nn.Module):
self.normalized_coordinates: bool = normalized_coordinates
self.align_corners: bool = align_corners
# create base grid to compute the flow
- self.grid: torch.Tensor = create_meshgrid(
- height, width, normalized_coordinates=normalized_coordinates)
+ self.grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates=normalized_coordinates)
# initialice the warped destination grid
self._warped_grid = None
@@ -224,10 +229,7 @@ class HomographyWarper(nn.Module):
"""
self._warped_grid = warp_grid(self.grid, src_homo_dst)
- def forward(
- self,
- patch_src: torch.Tensor,
- src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
+ def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
r"""Warp a tensor from source into reference frame.
Args:
@@ -257,30 +259,46 @@ class HomographyWarper(nn.Module):
_warped_grid = self._warped_grid
if src_homo_dst is not None:
warped_patch = homography_warp(
- patch_src, src_homo_dst, (self.height, self.width), mode=self.mode,
- padding_mode=self.padding_mode, align_corners=self.align_corners,
- normalized_coordinates=self.normalized_coordinates)
+ patch_src,
+ src_homo_dst, (self.height, self.width),
+ mode=self.mode,
+ padding_mode=self.padding_mode,
+ align_corners=self.align_corners,
+ normalized_coordinates=self.normalized_coordinates
+ )
elif _warped_grid is not None:
if not _warped_grid.device == patch_src.device:
- raise TypeError("Patch and warped grid must be on the same device. \
+ raise TypeError(
+ "Patch and warped grid must be on the same device. \
Got patch.device: {} warped_grid.device: {}. Whether \
recall precompute_warp_grid() with the correct device \
for the homograhy or change the patch device.".format(
- patch_src.device, _warped_grid.device))
+ patch_src.device, _warped_grid.device
+ )
+ )
warped_patch = F.grid_sample(
- patch_src, _warped_grid, mode=self.mode, padding_mode=self.padding_mode,
- align_corners=self.align_corners)
+ patch_src,
+ _warped_grid,
+ mode=self.mode,
+ padding_mode=self.padding_mode,
+ align_corners=self.align_corners
+ )
else:
- raise RuntimeError("Unknown warping. If homographies are not provided \
+ raise RuntimeError(
+ "Unknown warping. If homographies are not provided \
they must be preset using the method: \
- precompute_warp_grid().")
+ precompute_warp_grid()."
+ )
return warped_patch
def normal_transform_pixel(
- height: int, width: int, eps: float = 1e-14,
- device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ height: int,
+ width: int,
+ eps: float = 1e-14,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
@@ -292,9 +310,7 @@ def normal_transform_pixel(
Returns:
torch.Tensor: normalized transform with shape :math:`(1, 3, 3)`.
"""
- tr_mat = torch.tensor([[1.0, 0.0, -1.0],
- [0.0, 1.0, -1.0],
- [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
+ tr_mat = torch.tensor([[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
# prevent divide by zero bugs
width_denom: float = eps if width == 1 else width - 1.0
@@ -307,8 +323,12 @@ def normal_transform_pixel(
def normal_transform_pixel3d(
- depth: int, height: int, width: int, eps: float = 1e-14,
- device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ depth: int,
+ height: int,
+ width: int,
+ eps: float = 1e-14,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
@@ -321,10 +341,11 @@ def normal_transform_pixel3d(
Returns:
Tensor: normalized transform with shape :math:`(1, 4, 4)`.
"""
- tr_mat = torch.tensor([[1.0, 0.0, 0.0, -1.0],
- [0.0, 1.0, 0.0, -1.0],
- [0.0, 0.0, 1.0, -1.0],
- [0.0, 0.0, 0.0, 1.0]], device=device, dtype=dtype) # 4x4
+ tr_mat = torch.tensor(
+ [[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]],
+ device=device,
+ dtype=dtype
+ ) # 4x4
# prevent divide by zero bugs
width_denom: float = eps if width == 1 else width - 1.0
@@ -338,8 +359,9 @@ def normal_transform_pixel3d(
return tr_mat.unsqueeze(0) # 1x4x4
-def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
- dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]) -> torch.Tensor:
+def normalize_homography(
+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]
+) -> torch.Tensor:
r"""Normalize a given homography in pixels to [-1, 1].
Args:
@@ -354,30 +376,28 @@ def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
check_is_tensor(dst_pix_trans_src_pix)
if not (len(dst_pix_trans_src_pix.shape) == 3 or dst_pix_trans_src_pix.shape[-2:] == (3, 3)):
- raise ValueError("Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}"
- .format(dst_pix_trans_src_pix.shape))
+ raise ValueError(
+ "Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}".format(dst_pix_trans_src_pix.shape)
+ )
# source and destination sizes
src_h, src_w = dsize_src
dst_h, dst_w = dsize_dst
# compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(
- src_h, src_w).to(dst_pix_trans_src_pix)
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(src_h, src_w).to(dst_pix_trans_src_pix)
src_pix_trans_src_norm = _torch_inverse_cast(src_norm_trans_src_pix)
- dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(
- dst_h, dst_w).to(dst_pix_trans_src_pix)
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(dst_h, dst_w).to(dst_pix_trans_src_pix)
# compute chain transformations
- dst_norm_trans_src_norm: torch.Tensor = (
- dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
- )
+ dst_norm_trans_src_norm: torch.Tensor = (dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm))
return dst_norm_trans_src_norm
-def normalize_homography3d(dst_pix_trans_src_pix: torch.Tensor,
- dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]) -> torch.Tensor:
+def normalize_homography3d(
+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]
+) -> torch.Tensor:
r"""Normalize a given homography in pixels to [-1, 1].
Args:
@@ -395,21 +415,18 @@ def normalize_homography3d(dst_pix_trans_src_pix: torch.Tensor,
check_is_tensor(dst_pix_trans_src_pix)
if not (len(dst_pix_trans_src_pix.shape) == 3 or dst_pix_trans_src_pix.shape[-2:] == (4, 4)):
- raise ValueError("Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}"
- .format(dst_pix_trans_src_pix.shape))
+ raise ValueError(
+ "Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}".format(dst_pix_trans_src_pix.shape)
+ )
# source and destination sizes
src_d, src_h, src_w = dsize_src
dst_d, dst_h, dst_w = dsize_dst
# compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel3d(
- src_d, src_h, src_w).to(dst_pix_trans_src_pix)
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel3d(src_d, src_h, src_w).to(dst_pix_trans_src_pix)
src_pix_trans_src_norm = _torch_inverse_cast(src_norm_trans_src_pix)
- dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel3d(
- dst_d, dst_h, dst_w).to(dst_pix_trans_src_pix)
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel3d(dst_d, dst_h, dst_w).to(dst_pix_trans_src_pix)
# compute chain transformations
- dst_norm_trans_src_norm: torch.Tensor = (
- dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
- )
+ dst_norm_trans_src_norm: torch.Tensor = (dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm))
return dst_norm_trans_src_norm
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 62b6b03be..64cbb8788 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -4,38 +4,30 @@ import warnings
import torch
import torch.nn.functional as F
-from kornia.geometry.transform.homography_warper import (
- normalize_homography, homography_warp
-)
+from kornia.geometry.transform.homography_warper import (normalize_homography, homography_warp)
from kornia.geometry.conversions import (
deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography, convert_affinematrix_to_homography3d
)
-from kornia.geometry.transform.projwarp import (
- get_projective_transform
-)
+from kornia.geometry.transform.projwarp import (get_projective_transform)
from kornia.utils import create_meshgrid
from kornia.geometry.linalg import transform_points
from kornia.utils.helpers import _torch_inverse_cast, _torch_solve_cast
-
__all__ = [
- "warp_perspective",
- "warp_affine",
- "get_perspective_transform",
- "get_rotation_matrix2d",
- "remap",
- "invert_affine_transform",
- "angle_to_rotation_matrix",
- "get_affine_matrix2d",
- "get_affine_matrix3d",
- "get_shear_matrix2d",
- "get_shear_matrix3d"
+ "warp_perspective", "warp_affine", "get_perspective_transform", "get_rotation_matrix2d", "remap",
+ "invert_affine_transform", "angle_to_rotation_matrix", "get_affine_matrix2d", "get_affine_matrix3d",
+ "get_shear_matrix2d", "get_shear_matrix3d"
]
-def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def warp_perspective(
+ src: torch.Tensor,
+ M: torch.Tensor,
+ dsize: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Applies a perspective transformation to an image.
The function warp_perspective transforms the source image using
@@ -75,27 +67,24 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
tutorials/warp_perspective.html>`_.
"""
if not isinstance(src, torch.Tensor):
- raise TypeError("Input src type is not a torch.Tensor. Got {}"
- .format(type(src)))
+ raise TypeError("Input src type is not a torch.Tensor. Got {}".format(type(src)))
if not isinstance(M, torch.Tensor):
- raise TypeError("Input M type is not a torch.Tensor. Got {}"
- .format(type(M)))
+ raise TypeError("Input M type is not a torch.Tensor. Got {}".format(type(M)))
if not len(src.shape) == 4:
- raise ValueError("Input src must be a BxCxHxW tensor. Got {}"
- .format(src.shape))
+ raise ValueError("Input src must be a BxCxHxW tensor. Got {}".format(src.shape))
if not (len(M.shape) == 3 and M.shape[-2:] == (3, 3)):
- raise ValueError("Input M must be a Bx3x3 tensor. Got {}"
- .format(M.shape))
+ raise ValueError("Input M must be a Bx3x3 tensor. Got {}".format(M.shape))
# TODO: remove the statement below in kornia v0.6
if align_corners is None:
message: str = (
"The align_corners default value has been changed. By default now is set True "
"in order to match cv2.warpPerspective. In case you want to keep your previous "
- "behaviour set it to False. This warning will disappear in kornia > v0.6.")
+ "behaviour set it to False. This warning will disappear in kornia > v0.6."
+ )
warnings.warn(message)
# set default value for align corners
align_corners = True
@@ -104,8 +93,7 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
h_out, w_out = dsize
# we normalize the 3x3 transformation matrix and convert to 3x4
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
- M, (H, W), (h_out, w_out)) # Bx3x3
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M, (H, W), (h_out, w_out)) # Bx3x3
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm) # Bx3x3
@@ -114,16 +102,17 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
device=src.device).to(src.dtype).repeat(B, 1, 1, 1)
grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid)
- return F.grid_sample(src, grid,
- align_corners=align_corners,
- mode=mode,
- padding_mode=padding_mode)
+ return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
-def warp_affine(src: torch.Tensor, M: torch.Tensor,
- dsize: Tuple[int, int], mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def warp_affine(
+ src: torch.Tensor,
+ M: torch.Tensor,
+ dsize: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Applies an affine transformation to a tensor.
The function warp_affine transforms the source tensor using
@@ -162,27 +151,24 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
tutorials/warp_affine.html>`__.
"""
if not isinstance(src, torch.Tensor):
- raise TypeError("Input src type is not a torch.Tensor. Got {}"
- .format(type(src)))
+ raise TypeError("Input src type is not a torch.Tensor. Got {}".format(type(src)))
if not isinstance(M, torch.Tensor):
- raise TypeError("Input M type is not a torch.Tensor. Got {}"
- .format(type(M)))
+ raise TypeError("Input M type is not a torch.Tensor. Got {}".format(type(M)))
if not len(src.shape) == 4:
- raise ValueError("Input src must be a BxCxHxW tensor. Got {}"
- .format(src.shape))
+ raise ValueError("Input src must be a BxCxHxW tensor. Got {}".format(src.shape))
if not (len(M.shape) == 3 or M.shape[-2:] == (2, 3)):
- raise ValueError("Input M must be a Bx2x3 tensor. Got {}"
- .format(M.shape))
+ raise ValueError("Input M must be a Bx2x3 tensor. Got {}".format(M.shape))
# TODO: remove the statement below in kornia v0.6
if align_corners is None:
message: str = (
"The align_corners default value has been changed. By default now is set True "
"in order to match cv2.warpAffine. In case you want to keep your previous "
- "behaviour set it to False. This warning will disappear in kornia > v0.6.")
+ "behaviour set it to False. This warning will disappear in kornia > v0.6."
+ )
warnings.warn(message)
# set default value for align corners
align_corners = True
@@ -191,20 +177,14 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
# we generate a 3x3 transformation matrix from 2x3 affine
M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
- M_3x3, (H, W), dsize)
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M_3x3, (H, W), dsize)
# src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
- grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :],
- [B, C, dsize[0], dsize[1]],
- align_corners=align_corners)
+ grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :], [B, C, dsize[0], dsize[1]], align_corners=align_corners)
- return F.grid_sample(src, grid,
- align_corners=align_corners,
- mode=mode,
- padding_mode=padding_mode)
+ return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
def get_perspective_transform(src, dst):
@@ -245,24 +225,21 @@ def get_perspective_transform(src, dst):
This function is often used in conjuntion with :func:`warp_perspective`.
"""
if not isinstance(src, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(src)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(src)))
if not isinstance(dst, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(dst)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(dst)))
if not src.shape[-2:] == (4, 2):
- raise ValueError("Inputs must be a Bx4x2 tensor. Got {}"
- .format(src.shape))
+ raise ValueError("Inputs must be a Bx4x2 tensor. Got {}".format(src.shape))
if not src.shape == dst.shape:
- raise ValueError("Inputs must have the same shape. Got {}"
- .format(dst.shape))
+ raise ValueError("Inputs must have the same shape. Got {}".format(dst.shape))
if not (src.shape[0] == dst.shape[0]):
- raise ValueError("Inputs must have same batch size dimension. Expect {} but got {}"
- .format(src.shape, dst.shape))
+ raise ValueError(
+ "Inputs must have same batch size dimension. Expect {} but got {}".format(src.shape, dst.shape)
+ )
# we build matrix A by using only 4 point correspondence. The linear
# system is solved with the least square method, so here
@@ -276,12 +253,19 @@ def get_perspective_transform(src, dst):
A = torch.stack(p, dim=1)
# b is a Bx8x1
- b = torch.stack([
- dst[:, 0:1, 0], dst[:, 0:1, 1],
- dst[:, 1:2, 0], dst[:, 1:2, 1],
- dst[:, 2:3, 0], dst[:, 2:3, 1],
- dst[:, 3:4, 0], dst[:, 3:4, 1],
- ], dim=1)
+ b = torch.stack(
+ [
+ dst[:, 0:1, 0],
+ dst[:, 0:1, 1],
+ dst[:, 1:2, 0],
+ dst[:, 1:2, 1],
+ dst[:, 2:3, 0],
+ dst[:, 2:3, 1],
+ dst[:, 3:4, 0],
+ dst[:, 3:4, 1],
+ ],
+ dim=1
+ )
# solve the system Ax = b
X, LU = _torch_solve_cast(b, A)
@@ -299,14 +283,13 @@ def _build_perspective_param(p: torch.Tensor, q: torch.Tensor, axis: str) -> tor
zeros = torch.zeros_like(p)[..., 0:1]
if axis == 'x':
return torch.cat(
- [p[:, 0:1], p[:, 1:2], ones, zeros, zeros, zeros,
- -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1]
- ], dim=1)
+ [p[:, 0:1], p[:, 1:2], ones, zeros, zeros, zeros, -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1]], dim=1
+ )
if axis == 'y':
return torch.cat(
- [zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], ones,
- -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2]], dim=1)
+ [zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], ones, -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2]], dim=1
+ )
raise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")
@@ -333,10 +316,7 @@ def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:
return torch.stack([cos_a, sin_a, -sin_a, cos_a], dim=-1).view(*angle.shape, 2, 2)
-def get_rotation_matrix2d(
- center: torch.Tensor,
- angle: torch.Tensor,
- scale: torch.Tensor) -> torch.Tensor:
+def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
r"""Calculates an affine matrix of 2D rotation.
The function calculates the following matrix:
@@ -380,42 +360,41 @@ def get_rotation_matrix2d(
This function is often used in conjuntion with :func:`warp_affine`.
"""
if not isinstance(center, torch.Tensor):
- raise TypeError("Input center type is not a torch.Tensor. Got {}"
- .format(type(center)))
+ raise TypeError("Input center type is not a torch.Tensor. Got {}".format(type(center)))
if not isinstance(angle, torch.Tensor):
- raise TypeError("Input angle type is not a torch.Tensor. Got {}"
- .format(type(angle)))
+ raise TypeError("Input angle type is not a torch.Tensor. Got {}".format(type(angle)))
if not isinstance(scale, torch.Tensor):
- raise TypeError("Input scale type is not a torch.Tensor. Got {}"
- .format(type(scale)))
+ raise TypeError("Input scale type is not a torch.Tensor. Got {}".format(type(scale)))
if not (len(center.shape) == 2 and center.shape[1] == 2):
- raise ValueError("Input center must be a Bx2 tensor. Got {}"
- .format(center.shape))
+ raise ValueError("Input center must be a Bx2 tensor. Got {}".format(center.shape))
if not len(angle.shape) == 1:
- raise ValueError("Input angle must be a B tensor. Got {}"
- .format(angle.shape))
+ raise ValueError("Input angle must be a B tensor. Got {}".format(angle.shape))
if not (len(scale.shape) == 2 and scale.shape[1] == 2):
- raise ValueError("Input scale must be a Bx2 tensor. Got {}"
- .format(scale.shape))
+ raise ValueError("Input scale must be a Bx2 tensor. Got {}".format(scale.shape))
if not (center.shape[0] == angle.shape[0] == scale.shape[0]):
- raise ValueError("Inputs must have same batch size dimension. Got center {}, angle {} and scale {}"
- .format(center.shape, angle.shape, scale.shape))
+ raise ValueError(
+ "Inputs must have same batch size dimension. Got center {}, angle {} and scale {}".format(
+ center.shape, angle.shape, scale.shape
+ )
+ )
if not (center.device == angle.device == scale.device) or not (center.dtype == angle.dtype == scale.dtype):
- raise ValueError("Inputs must have same device Got center ({}, {}), angle ({}, {}) and scale ({}, {})"
- .format(center.device, center.dtype, angle.device, angle.dtype, scale.device, scale.dtype))
+ raise ValueError(
+ "Inputs must have same device Got center ({}, {}), angle ({}, {}) and scale ({}, {})".format(
+ center.device, center.dtype, angle.device, angle.dtype, scale.device, scale.dtype
+ )
+ )
# convert angle and apply scale
rotation_matrix: torch.Tensor = angle_to_rotation_matrix(angle)
- scaling_matrix: torch.Tensor = torch.zeros(
- (2, 2), device=rotation_matrix.device, dtype=rotation_matrix.dtype).fill_diagonal_(1).repeat(
- rotation_matrix.size(0), 1, 1)
+ scaling_matrix: torch.Tensor = torch.zeros((2, 2), device=rotation_matrix.device, dtype=rotation_matrix.dtype
+ ).fill_diagonal_(1).repeat(rotation_matrix.size(0), 1, 1)
scaling_matrix = scaling_matrix * scale.unsqueeze(dim=2).repeat(1, 1, 2)
scaled_rotation: torch.Tensor = rotation_matrix @ scaling_matrix
@@ -429,8 +408,7 @@ def get_rotation_matrix2d(
# create output tensor
batch_size: int = center.shape[0]
one = torch.tensor(1., device=center.device, dtype=center.dtype)
- M: torch.Tensor = torch.zeros(
- batch_size, 2, 3, device=center.device, dtype=center.dtype)
+ M: torch.Tensor = torch.zeros(batch_size, 2, 3, device=center.device, dtype=center.dtype)
M[..., 0:2, 0:2] = scaled_rotation
M[..., 0, 2] = (one - alpha) * x - beta * y
@@ -438,9 +416,15 @@ def get_rotation_matrix2d(
return M
-def remap(tensor: torch.Tensor, map_x: torch.Tensor, map_y: torch.Tensor,
- mode: str = 'bilinear', padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None, normalized_coordinates: bool = False) -> torch.Tensor:
+def remap(
+ tensor: torch.Tensor,
+ map_x: torch.Tensor,
+ map_y: torch.Tensor,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None,
+ normalized_coordinates: bool = False
+) -> torch.Tensor:
r"""Applies a generic geometrical transformation to a tensor.
The function remap transforms the source tensor using the specified map:
@@ -479,16 +463,13 @@ def remap(tensor: torch.Tensor, map_x: torch.Tensor, map_y: torch.Tensor,
This function is often used in conjuntion with :func:`create_meshgrid`.
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))
if not isinstance(map_x, torch.Tensor):
- raise TypeError("Input map_x type is not a torch.Tensor. Got {}"
- .format(type(map_x)))
+ raise TypeError("Input map_x type is not a torch.Tensor. Got {}".format(type(map_x)))
if not isinstance(map_y, torch.Tensor):
- raise TypeError("Input map_y type is not a torch.Tensor. Got {}"
- .format(type(map_y)))
+ raise TypeError("Input map_y type is not a torch.Tensor. Got {}".format(type(map_y)))
if not tensor.shape[-2:] == map_x.shape[-2:] == map_y.shape[-2:]:
raise ValueError("Inputs last two dimensions must match.")
@@ -537,12 +518,10 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
This function is often used in conjuntion with :func:`warp_affine`.
"""
if not isinstance(matrix, torch.Tensor):
- raise TypeError("Input matrix type is not a torch.Tensor. Got {}"
- .format(type(matrix)))
+ raise TypeError("Input matrix type is not a torch.Tensor. Got {}".format(type(matrix)))
if not (len(matrix.shape) == 3 and matrix.shape[-2:] == (2, 3)):
- raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}"
- .format(matrix.shape))
+ raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}".format(matrix.shape))
matrix_tmp: torch.Tensor = convert_affinematrix_to_homography(matrix)
matrix_inv: torch.Tensor = torch.inverse(matrix_tmp)
@@ -550,8 +529,14 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
return matrix_inv[..., :2, :3]
-def get_affine_matrix2d(translations: torch.Tensor, center: torch.Tensor, scale: torch.Tensor, angle: torch.Tensor,
- sx: Optional[torch.Tensor] = None, sy: Optional[torch.Tensor] = None) -> torch.Tensor:
+def get_affine_matrix2d(
+ translations: torch.Tensor,
+ center: torch.Tensor,
+ scale: torch.Tensor,
+ angle: torch.Tensor,
+ sx: Optional[torch.Tensor] = None,
+ sy: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Composes affine matrix from the components.
Args:
@@ -623,19 +608,34 @@ def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None,
sx_tan = torch.tan(sx) # type: ignore
sy_tan = torch.tan(sy) # type: ignore
ones = torch.ones_like(sx) # type: ignore
- shear_mat = torch.stack([
- ones, -sx_tan, sx_tan * y, # type: ignore # noqa: E241
- -sy_tan, ones + sx_tan * sy_tan, sy_tan * (sx_tan * y + x) # noqa: E241
- ], dim=-1).view(-1, 2, 3)
+ shear_mat = torch.stack(
+ [
+ ones,
+ -sx_tan,
+ sx_tan * y, # type: ignore # noqa: E241
+ -sy_tan,
+ ones + sx_tan * sy_tan,
+ sy_tan * (sx_tan * y + x) # noqa: E241
+ ],
+ dim=-1
+ ).view(-1, 2, 3)
shear_mat = convert_affinematrix_to_homography(shear_mat)
return shear_mat
-def get_affine_matrix3d(translations: torch.Tensor, center: torch.Tensor, scale: torch.Tensor, angles: torch.Tensor,
- sxy: Optional[torch.Tensor] = None, sxz: Optional[torch.Tensor] = None,
- syx: Optional[torch.Tensor] = None, syz: Optional[torch.Tensor] = None,
- szx: Optional[torch.Tensor] = None, szy: Optional[torch.Tensor] = None) -> torch.Tensor:
+def get_affine_matrix3d(
+ translations: torch.Tensor,
+ center: torch.Tensor,
+ scale: torch.Tensor,
+ angles: torch.Tensor,
+ sxy: Optional[torch.Tensor] = None,
+ sxz: Optional[torch.Tensor] = None,
+ syx: Optional[torch.Tensor] = None,
+ syz: Optional[torch.Tensor] = None,
+ szx: Optional[torch.Tensor] = None,
+ szy: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Composes 3d affine matrix from the components.
Args:
@@ -672,9 +672,12 @@ def get_affine_matrix3d(translations: torch.Tensor, center: torch.Tensor, scale:
def get_shear_matrix3d(
center: torch.Tensor,
- sxy: Optional[torch.Tensor] = None, sxz: Optional[torch.Tensor] = None,
- syx: Optional[torch.Tensor] = None, syz: Optional[torch.Tensor] = None,
- szx: Optional[torch.Tensor] = None, szy: Optional[torch.Tensor] = None,
+ sxy: Optional[torch.Tensor] = None,
+ sxz: Optional[torch.Tensor] = None,
+ syx: Optional[torch.Tensor] = None,
+ syz: Optional[torch.Tensor] = None,
+ szx: Optional[torch.Tensor] = None,
+ szy: Optional[torch.Tensor] = None,
):
r"""Composes shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis then z-axis.
@@ -742,7 +745,8 @@ def get_shear_matrix3d(
# compute translation matrix
m00, m10, m20, m01, m11, m21, m02, m12, m22 = _compute_shear_matrix_3d(
- sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan)
+ sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan
+ )
m03 = m01 * y + m02 * z
m13 = m10 * x + m11 * y + m12 * z - y
@@ -752,13 +756,10 @@ def get_shear_matrix3d(
sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan = \
- sxy_tan, - sxz_tan, - syx_tan, - syz_tan, - szx_tan, - szy_tan
m00, m10, m20, m01, m11, m21, m02, m12, m22 = _compute_shear_matrix_3d(
- sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan)
+ sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan
+ )
- shear_mat = torch.stack([
- m00, m01, m02, m03,
- m10, m11, m12, m13,
- m20, m21, m22, m23
- ], dim=-1).view(-1, 3, 4)
+ shear_mat = torch.stack([m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23], dim=-1).view(-1, 3, 4)
shear_mat = convert_affinematrix_to_homography3d(shear_mat)
return shear_mat
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index df282cc5e..5d45a6e40 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -11,20 +11,19 @@ from kornia.testing import check_is_tensor
from kornia.utils.helpers import _torch_solve_cast, _torch_inverse_cast
__all__ = [
- "warp_affine3d",
- "get_projective_transform",
- "projection_from_Rt",
- "get_perspective_transform3d",
+ "warp_affine3d", "get_projective_transform", "projection_from_Rt", "get_perspective_transform3d",
"warp_perspective3d"
]
-def warp_affine3d(src: torch.Tensor,
- M: torch.Tensor,
- dsize: Tuple[int, int, int],
- flags: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None) -> torch.Tensor:
+def warp_affine3d(
+ src: torch.Tensor,
+ M: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ flags: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None
+) -> torch.Tensor:
r"""Applies a projective transformation a to 3d tensor.
.. warning::
@@ -56,7 +55,8 @@ def warp_affine3d(src: torch.Tensor,
message: str = (
"The align_corners default value has been changed. By default now is set True "
"in order to match cv2.warpAffine. In case you want to keep your previous "
- "behaviour set it to False. This warning will disappear in kornia > v0.6.")
+ "behaviour set it to False. This warning will disappear in kornia > v0.6."
+ )
warnings.warn(message)
# set default value for align corners
align_corners = True
@@ -67,8 +67,7 @@ def warp_affine3d(src: torch.Tensor,
M_4x4 = convert_affinematrix_to_homography3d(M) # Bx4x4
# we need to normalize the transformation since grid sample needs -1/1 coordinates
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(
- M_4x4, size_src, size_out) # Bx4x4
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
P_norm: torch.Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
@@ -77,7 +76,8 @@ def warp_affine3d(src: torch.Tensor,
dsize_out: List[int] = [B, C] + list(size_out)
grid = torch.nn.functional.affine_grid(P_norm, dsize_out, align_corners=align_corners)
return torch.nn.functional.grid_sample(
- src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode)
+ src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode
+ )
def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
@@ -222,24 +222,21 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
This function is often used in conjuntion with :func:`warp_perspective3d`.
"""
if not isinstance(src, (torch.Tensor)):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(src)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(src)))
if not isinstance(dst, (torch.Tensor)):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(dst)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(dst)))
if not src.shape[-2:] == (8, 3):
- raise ValueError("Inputs must be a Bx8x3 tensor. Got {}"
- .format(src.shape))
+ raise ValueError("Inputs must be a Bx8x3 tensor. Got {}".format(src.shape))
if not src.shape == dst.shape:
- raise ValueError("Inputs must have the same shape. Got {}"
- .format(dst.shape))
+ raise ValueError("Inputs must have the same shape. Got {}".format(dst.shape))
if not (src.shape[0] == dst.shape[0]):
- raise ValueError("Inputs must have same batch size dimension. Expect {} but got {}"
- .format(src.shape, dst.shape))
+ raise ValueError(
+ "Inputs must have same batch size dimension. Expect {} but got {}".format(src.shape, dst.shape)
+ )
assert src.device == dst.device and src.dtype == dst.dtype, (
f"Expect `src` and `dst` to be in the same device (Got {src.dtype}, {dst.dtype}) "
@@ -261,16 +258,29 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
A = torch.stack(p, dim=1)
# b is a Bx15x1
- b = torch.stack([
- dst[:, 0:1, 0], dst[:, 0:1, 1], dst[:, 0:1, 2],
- dst[:, 1:2, 0], dst[:, 1:2, 1], dst[:, 1:2, 2],
- dst[:, 2:3, 0], dst[:, 2:3, 1], dst[:, 2:3, 2],
- # dst[:, 3:4, 0], dst[:, 3:4, 1], dst[:, 3:4, 2],
- # dst[:, 4:5, 0], dst[:, 4:5, 1], dst[:, 4:5, 2],
- dst[:, 5:6, 0], dst[:, 5:6, 1], dst[:, 5:6, 2],
- # dst[:, 6:7, 0], dst[:, 6:7, 1], dst[:, 6:7, 2],
- dst[:, 7:8, 0], dst[:, 7:8, 1], dst[:, 7:8, 2],
- ], dim=1)
+ b = torch.stack(
+ [
+ dst[:, 0:1, 0],
+ dst[:, 0:1, 1],
+ dst[:, 0:1, 2],
+ dst[:, 1:2, 0],
+ dst[:, 1:2, 1],
+ dst[:, 1:2, 2],
+ dst[:, 2:3, 0],
+ dst[:, 2:3, 1],
+ dst[:, 2:3, 2],
+ # dst[:, 3:4, 0], dst[:, 3:4, 1], dst[:, 3:4, 2],
+ # dst[:, 4:5, 0], dst[:, 4:5, 1], dst[:, 4:5, 2],
+ dst[:, 5:6, 0],
+ dst[:, 5:6, 1],
+ dst[:, 5:6, 2],
+ # dst[:, 6:7, 0], dst[:, 6:7, 1], dst[:, 6:7, 2],
+ dst[:, 7:8, 0],
+ dst[:, 7:8, 1],
+ dst[:, 7:8, 2],
+ ],
+ dim=1
+ )
# solve the system Ax = b
X, LU = _torch_solve_cast(b, A)
@@ -287,35 +297,43 @@ def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> t
zeros = torch.zeros_like(p)[..., 0:1]
if axis == 'x':
- return torch.cat([
- p[:, 0:1], p[:, 1:2], p[:, 2:3], ones,
- zeros, zeros, zeros, zeros,
- zeros, zeros, zeros, zeros,
- -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1], -p[:, 2:3] * q[:, 0:1]
- ], dim=1)
+ return torch.cat(
+ [
+ p[:, 0:1], p[:, 1:2], p[:, 2:3], ones, zeros, zeros, zeros, zeros, zeros, zeros, zeros, zeros,
+ -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1], -p[:, 2:3] * q[:, 0:1]
+ ],
+ dim=1
+ )
if axis == 'y':
- return torch.cat([
- zeros, zeros, zeros, zeros,
- p[:, 0:1], p[:, 1:2], p[:, 2:3], ones,
- zeros, zeros, zeros, zeros,
- -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2], -p[:, 2:3] * q[:, 1:2]
- ], dim=1)
+ return torch.cat(
+ [
+ zeros, zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], p[:, 2:3], ones, zeros, zeros, zeros, zeros,
+ -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2], -p[:, 2:3] * q[:, 1:2]
+ ],
+ dim=1
+ )
if axis == 'z':
- return torch.cat([
- zeros, zeros, zeros, zeros,
- zeros, zeros, zeros, zeros,
- p[:, 0:1], p[:, 1:2], p[:, 2:3], ones,
- -p[:, 0:1] * q[:, 2:3], -p[:, 1:2] * q[:, 2:3], -p[:, 2:3] * q[:, 2:3]
- ], dim=1)
+ return torch.cat(
+ [
+ zeros, zeros, zeros, zeros, zeros, zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], p[:, 2:3], ones,
+ -p[:, 0:1] * q[:, 2:3], -p[:, 1:2] * q[:, 2:3], -p[:, 2:3] * q[:, 2:3]
+ ],
+ dim=1
+ )
raise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")
-def warp_perspective3d(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int, int],
- flags: str = 'bilinear', border_mode: str = 'zeros',
- align_corners: bool = False) -> torch.Tensor:
+def warp_perspective3d(
+ src: torch.Tensor,
+ M: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ flags: str = 'bilinear',
+ border_mode: str = 'zeros',
+ align_corners: bool = False
+) -> torch.Tensor:
r"""Applies a perspective transformation to an image.
The function warp_perspective transforms the source image using
@@ -347,26 +365,23 @@ def warp_perspective3d(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int
check_is_tensor(M)
if not len(src.shape) == 5:
- raise ValueError("Input src must be a BxCxDxHxW tensor. Got {}"
- .format(src.shape))
+ raise ValueError("Input src must be a BxCxDxHxW tensor. Got {}".format(src.shape))
if not (len(M.shape) == 3 or M.shape[-2:] == (4, 4)):
- raise ValueError("Input M must be a Bx4x4 tensor. Got {}"
- .format(M.shape))
+ raise ValueError("Input M must be a Bx4x4 tensor. Got {}".format(M.shape))
# launches the warper
d, h, w = src.shape[-3:]
return transform_warp_impl3d(src, M, (d, h, w), dsize, flags, border_mode, align_corners)
-def transform_warp_impl3d(src: torch.Tensor, dst_pix_trans_src_pix: torch.Tensor,
- dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int],
- grid_mode: str, padding_mode: str, align_corners: bool) -> torch.Tensor:
+def transform_warp_impl3d(
+ src: torch.Tensor, dst_pix_trans_src_pix: torch.Tensor, dsize_src: Tuple[int, int, int],
+ dsize_dst: Tuple[int, int, int], grid_mode: str, padding_mode: str, align_corners: bool
+) -> torch.Tensor:
"""Compute the transform in normalized cooridnates and perform the warping.
"""
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(
- dst_pix_trans_src_pix, dsize_src, dsize_dst)
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
- return homography_warp3d(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode,
- align_corners, True)
+ return homography_warp3d(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode, align_corners, True)
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index d7f72467e..17009dbc6 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -20,13 +20,14 @@ __all__ = [
def _get_pyramid_gaussian_kernel() -> torch.Tensor:
"""Utility function that return a pre-computed gaussian kernel."""
- return torch.tensor([[
- [1., 4., 6., 4., 1.],
- [4., 16., 24., 16., 4.],
- [6., 24., 36., 24., 6.],
- [4., 16., 24., 16., 4.],
- [1., 4., 6., 4., 1.]
- ]]) / 256.
+ return torch.tensor(
+ [
+ [
+ [1., 4., 6., 4., 1.], [4., 16., 24., 16., 4.], [6., 24., 36., 24., 6.], [4., 16., 24., 16., 4.],
+ [1., 4., 6., 4., 1.]
+ ]
+ ]
+ ) / 256.
class PyrDown(nn.Module):
@@ -117,11 +118,7 @@ class ScalePyramid(nn.Module):
>>> sp, sigmas, pds = ScalePyramid(3, 15)(input)
"""
- def __init__(self,
- n_levels: int = 3,
- init_sigma: float = 1.6,
- min_size: int = 15,
- double_image: bool = False):
+ def __init__(self, n_levels: int = 3, init_sigma: float = 1.6, min_size: int = 15, double_image: bool = False):
super(ScalePyramid, self).__init__()
# 3 extra levels are needed for DoG nms.
self.n_levels = n_levels
@@ -129,7 +126,7 @@ class ScalePyramid(nn.Module):
self.init_sigma = init_sigma
self.min_size = min_size
self.border = min_size // 2 - 1
- self.sigma_step = 2 ** (1. / float(self.n_levels))
+ self.sigma_step = 2**(1. / float(self.n_levels))
self.double_image = double_image
return
@@ -173,16 +170,12 @@ class ScalePyramid(nn.Module):
cur_level = x
return cur_level, cur_sigma, pixel_distance
- def forward(self, x: torch.Tensor) -> Tuple[ # type: ignore
- List, List, List]:
+ def forward(self, x: torch.Tensor) -> Tuple[List, List, List]: # type: ignore
bs, ch, h, w = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
sigmas = [cur_sigma * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]
- pixel_dists = [pixel_distance * torch.ones(
- bs,
- self.n_levels + self.extra_levels).to(
- x.device).to(x.dtype)]
+ pixel_dists = [pixel_distance * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]
pyr = [[cur_level]]
oct_idx = 0
while True:
@@ -198,39 +191,29 @@ class ScalePyramid(nn.Module):
if ksize % 2 == 0:
ksize += 1
- cur_level = gaussian_blur2d(
- cur_level, (ksize, ksize), (sigma, sigma))
+ cur_level = gaussian_blur2d(cur_level, (ksize, ksize), (sigma, sigma))
cur_sigma *= self.sigma_step
pyr[-1].append(cur_level)
sigmas[-1][:, level_idx] = cur_sigma
pixel_dists[-1][:, level_idx] = pixel_distance
_pyr = pyr[-1][-self.extra_levels]
- nextOctaveFirstLevel = F.interpolate(_pyr, size=(_pyr.size(-2) // 2, _pyr.size(-1) // 2),
- mode='nearest') # Nearest matches OpenCV SIFT
+ nextOctaveFirstLevel = F.interpolate(
+ _pyr, size=(_pyr.size(-2) // 2, _pyr.size(-1) // 2), mode='nearest'
+ ) # Nearest matches OpenCV SIFT
pixel_distance *= 2.0
cur_sigma = self.init_sigma
- if (min(nextOctaveFirstLevel.size(2),
- nextOctaveFirstLevel.size(3)) <= self.min_size):
+ if (min(nextOctaveFirstLevel.size(2), nextOctaveFirstLevel.size(3)) <= self.min_size):
break
pyr.append([nextOctaveFirstLevel])
- sigmas.append(cur_sigma * torch.ones(
- bs,
- self.n_levels + self.extra_levels).to(
- x.device))
- pixel_dists.append(
- pixel_distance * torch.ones(
- bs,
- self.n_levels + self.extra_levels).to(
- x.device))
+ sigmas.append(cur_sigma * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device))
+ pixel_dists.append(pixel_distance * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device))
oct_idx += 1
for i in range(len(pyr)):
pyr[i] = torch.stack(pyr[i], dim=2) # type: ignore
return pyr, sigmas, pixel_dists
-def pyrdown(
- input: torch.Tensor,
- border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:
+def pyrdown(input: torch.Tensor, border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:
r"""Blurs a tensor and downsamples it.
Args:
@@ -258,8 +241,9 @@ def pyrdown(
x_blur: torch.Tensor = filter2D(input, kernel, border_type)
# downsample.
- out: torch.Tensor = F.interpolate(x_blur, size=(height // 2, width // 2), mode='bilinear',
- align_corners=align_corners)
+ out: torch.Tensor = F.interpolate(
+ x_blur, size=(height // 2, width // 2), mode='bilinear', align_corners=align_corners
+ )
return out
@@ -290,18 +274,19 @@ def pyrup(input: torch.Tensor, border_type: str = 'reflect', align_corners: bool
kernel: torch.Tensor = _get_pyramid_gaussian_kernel()
# upsample tensor
b, c, height, width = input.shape
- x_up: torch.Tensor = F.interpolate(input, size=(height * 2, width * 2),
- mode='bilinear', align_corners=align_corners)
+ x_up: torch.Tensor = F.interpolate(
+ input, size=(height * 2, width * 2), mode='bilinear', align_corners=align_corners
+ )
# blurs upsampled tensor
x_blur: torch.Tensor = filter2D(x_up, kernel, border_type)
return x_blur
-def build_pyramid(
- input: torch.Tensor,
- max_level: int,
- border_type: str = 'reflect', align_corners: bool = False) -> List[torch.Tensor]:
+def build_pyramid(input: torch.Tensor,
+ max_level: int,
+ border_type: str = 'reflect',
+ align_corners: bool = False) -> List[torch.Tensor]:
r"""Constructs the Gaussian pyramid for an image.
The function constructs a vector of images and builds the Gaussian pyramid
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index c7b485a78..d834d841f 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -5,11 +5,7 @@ import torch.nn as nn
from kornia.utils import create_meshgrid
-__all__ = [
- "get_tps_transform",
- "warp_points_tps",
- "warp_image_tps"
-]
+__all__ = ["get_tps_transform", "warp_points_tps", "warp_image_tps"]
# utilities for computing thin plate spline transforms
@@ -93,8 +89,9 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> Tup
return (kernel_weights, affine_weights)
-def warp_points_tps(points_src: torch.Tensor, kernel_centers: torch.Tensor,
- kernel_weights: torch.Tensor, affine_weights: torch.Tensor) -> torch.Tensor:
+def warp_points_tps(
+ points_src: torch.Tensor, kernel_centers: torch.Tensor, kernel_weights: torch.Tensor, affine_weights: torch.Tensor
+) -> torch.Tensor:
r"""Warp a tensor of coordinate points using the thin plate spline defined by kernel points, kernel weights,
and affine weights.
@@ -152,17 +149,20 @@ def warp_points_tps(points_src: torch.Tensor, kernel_centers: torch.Tensor,
# broadcast the kernel distance matrix against the x and y weights to compute the x and y
# transforms simultaneously
- warped: torch.Tensor = (
- k_matrix[..., None].mul(kernel_weights[:, None]).sum(-2) +
- points_src[..., None].mul(affine_weights[:, None, 1:]).sum(-2) +
- affine_weights[:, None, 0]
- )
+ k_mul_kernel = k_matrix[..., None].mul(kernel_weights[:, None]).sum(-2)
+ points_mul_affine = points_src[..., None].mul(affine_weights[:, None, 1:]).sum(-2)
+ warped: torch.Tensor = k_mul_kernel + points_mul_affine + affine_weights[:, None, 0]
return warped
-def warp_image_tps(image: torch.Tensor, kernel_centers: torch.Tensor, kernel_weights: torch.Tensor,
- affine_weights: torch.Tensor, align_corners: bool = False) -> torch.Tensor:
+def warp_image_tps(
+ image: torch.Tensor,
+ kernel_centers: torch.Tensor,
+ kernel_weights: torch.Tensor,
+ affine_weights: torch.Tensor,
+ align_corners: bool = False
+) -> torch.Tensor:
r"""Warp an image tensor according to the thin plate spline transform defined by kernel centers,
kernel weights, and affine weights.
diff --git a/kornia/geometry/warp/depth_warper.py b/kornia/geometry/warp/depth_warper.py
index e7f25e361..699b57b82 100644
--- a/kornia/geometry/warp/depth_warper.py
+++ b/kornia/geometry/warp/depth_warper.py
@@ -3,13 +3,8 @@ from typing import Union
import torch
import warnings
-from kornia.geometry.depth import (
- DepthWarper as _DepthWarper,
- depth_warp as _depth_warp
-)
-from kornia.geometry.camera import (
- PinholeCamera, cam2pixel, pixel2cam
-)
+from kornia.geometry.depth import (DepthWarper as _DepthWarper, depth_warp as _depth_warp)
+from kornia.geometry.camera import (PinholeCamera, cam2pixel, pixel2cam)
__all__ = [
"depth_warp",
@@ -20,29 +15,44 @@ __all__ = [
class DepthWarper(_DepthWarper):
__doc__ = _DepthWarper.__doc__
- def __init__(self,
- pinhole_dst: PinholeCamera,
- height: int, width: int,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = True):
+ def __init__(
+ self,
+ pinhole_dst: PinholeCamera,
+ height: int,
+ width: int,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = True
+ ):
super(DepthWarper, self).__init__(
- pinhole_dst=pinhole_dst, height=height, width=width, mode=mode, padding_mode=padding_mode,
- align_corners=align_corners)
+ pinhole_dst=pinhole_dst,
+ height=height,
+ width=width,
+ mode=mode,
+ padding_mode=padding_mode,
+ align_corners=align_corners
+ )
warnings.warn(
"`DepthWarper` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.DepthWarper instead.`",
- DeprecationWarning, stacklevel=2)
-
-
-def depth_warp(pinhole_dst: PinholeCamera,
- pinhole_src: PinholeCamera,
- depth_src: torch.Tensor,
- patch_dst: torch.Tensor,
- height: int, width: int,
- align_corners: bool = True):
+ DeprecationWarning,
+ stacklevel=2
+ )
+
+
+def depth_warp(
+ pinhole_dst: PinholeCamera,
+ pinhole_src: PinholeCamera,
+ depth_src: torch.Tensor,
+ patch_dst: torch.Tensor,
+ height: int,
+ width: int,
+ align_corners: bool = True
+):
__doc__ = _depth_warp.__doc__
warnings.warn(
"`depth_warp` is deprecated and will be removed > 0.6.0. Please use `kornia.geometry.depth_warp instead.`",
- DeprecationWarning, stacklevel=2)
+ DeprecationWarning,
+ stacklevel=2
+ )
return _depth_warp(pinhole_dst, pinhole_src, depth_src, patch_dst, height, width, align_corners)
diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.py
index a192e6ff5..ad32a85c0 100644
--- a/kornia/geometry/warp/homography_warper.py
+++ b/kornia/geometry/warp/homography_warper.py
@@ -26,114 +26,142 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
warnings.warn(
"`warp_grid` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.warp_grid instead.`",
- DeprecationWarning, stacklevel=2)
+ DeprecationWarning,
+ stacklevel=2
+ )
return HMW.warp_grid(grid, src_homo_dst)
def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
__doc__ = HMW.warp_grid3d.__doc__
- warnings.warn("`warp_grid3d` is deprecated. Please use `kornia.geometry.transform.warp_grid3d instead.`",
- DeprecationWarning, stacklevel=2)
+ warnings.warn(
+ "`warp_grid3d` is deprecated. Please use `kornia.geometry.transform.warp_grid3d instead.`",
+ DeprecationWarning,
+ stacklevel=2
+ )
return HMW.warp_grid3d(grid, src_homo_dst)
# functional api
-def homography_warp(patch_src: torch.Tensor,
- src_homo_dst: torch.Tensor,
- dsize: Tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = False,
- normalized_coordinates: bool = True) -> torch.Tensor:
+def homography_warp(
+ patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
+ dsize: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False,
+ normalized_coordinates: bool = True
+) -> torch.Tensor:
__doc__ = HMW.homography_warp.__doc__
warnings.warn(
"`homography_warp` is deprecated and will be removed > 0.6.0."
"Please use `kornia.geometry.transform.homography_warp instead.`",
- DeprecationWarning, stacklevel=2)
+ DeprecationWarning,
+ stacklevel=2
+ )
return HMW.homography_warp(
- patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates)
+ patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates
+ )
-def homography_warp3d(patch_src: torch.Tensor,
- src_homo_dst: torch.Tensor,
- dsize: Tuple[int, int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = False,
- normalized_coordinates: bool = True) -> torch.Tensor:
+def homography_warp3d(
+ patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False,
+ normalized_coordinates: bool = True
+) -> torch.Tensor:
__doc__ = HMW.homography_warp3d.__doc__
warnings.warn(
"`homography_warp3d` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.homography_warp3d instead.`",
- DeprecationWarning, stacklevel=2
+ DeprecationWarning,
+ stacklevel=2
)
return HMW.homography_warp3d(
- patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates)
+ patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates
+ )
class HomographyWarper(HMW.HomographyWarper):
__doc__ = HMW.HomographyWarper.__doc__
def __init__(
- self,
- height: int,
- width: int,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- normalized_coordinates: bool = True,
- align_corners: bool = False) -> None:
- super(HomographyWarper, self).__init__(
- height, width, mode, padding_mode, normalized_coordinates, align_corners)
+ self,
+ height: int,
+ width: int,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ normalized_coordinates: bool = True,
+ align_corners: bool = False
+ ) -> None:
+ super(HomographyWarper, self).__init__(height, width, mode, padding_mode, normalized_coordinates, align_corners)
warnings.warn(
"`HomographyWarper` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.HomographyWarper instead.`",
- DeprecationWarning, stacklevel=2
+ DeprecationWarning,
+ stacklevel=2
)
def normal_transform_pixel(
- height: int, width: int, eps: float = 1e-14,
- device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ height: int,
+ width: int,
+ eps: float = 1e-14,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
__doc__ = HMW.normal_transform_pixel.__doc__
warnings.warn(
"`normal_transform_pixel` is deprecated and will be removed > 0.6.0."
"Please use `kornia.geometry.transform.normal_transform_pixel instead.`",
- DeprecationWarning, stacklevel=2
+ DeprecationWarning,
+ stacklevel=2
)
return HMW.normal_transform_pixel(height, width, eps, device, dtype)
def normal_transform_pixel3d(
- depth: int, height: int, width: int, eps: float = 1e-14,
- device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+ depth: int,
+ height: int,
+ width: int,
+ eps: float = 1e-14,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
__doc__ = HMW.normal_transform_pixel3d.__doc__
warnings.warn(
"`normal_transform_pixel3d` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.normal_transform_pixel3d instead.`",
- DeprecationWarning, stacklevel=2
+ DeprecationWarning,
+ stacklevel=2
)
return HMW.normal_transform_pixel3d(depth, height, width, eps, device=device, dtype=dtype)
-def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
- dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]) -> torch.Tensor:
+def normalize_homography(
+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]
+) -> torch.Tensor:
__doc__ = HMW.normalize_homography.__doc__
warnings.warn(
"`normalize_homography` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.normalize_homography instead.`",
- DeprecationWarning, stacklevel=2
+ DeprecationWarning,
+ stacklevel=2
)
return HMW.normalize_homography(dst_pix_trans_src_pix, dsize_src, dsize_dst)
-def normalize_homography3d(dst_pix_trans_src_pix: torch.Tensor,
- dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]) -> torch.Tensor:
+def normalize_homography3d(
+ dst_pix_trans_src_pix: torch.Tensor, dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]
+) -> torch.Tensor:
__doc__ = HMW.normalize_homography3d.__doc__
warnings.warn(
"`normalize_homography3d` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.normalize_homography3d instead.`",
- DeprecationWarning, stacklevel=2
+ DeprecationWarning,
+ stacklevel=2
)
return HMW.normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index d8c50d28b..42ba78057 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -2,9 +2,7 @@ from .ssim import SSIM, ssim, SSIMLoss, ssim_loss
from .dice import DiceLoss, dice_loss
from .tversky import TverskyLoss, tversky_loss
from .focal import FocalLoss, focal_loss, BinaryFocalLossWithLogits, binary_focal_loss_with_logits
-from .depth_smooth import (
- InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss
-)
+from .depth_smooth import (InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss)
from .divergence import kl_div_loss_2d, js_div_loss_2d
from .total_variation import TotalVariation, total_variation
from .psnr import PSNRLoss, psnr_loss, psnr
diff --git a/kornia/losses/depth_smooth.py b/kornia/losses/depth_smooth.py
index 5fd993252..4ba829db1 100644
--- a/kornia/losses/depth_smooth.py
+++ b/kornia/losses/depth_smooth.py
@@ -16,9 +16,7 @@ def _gradient_y(img: torch.Tensor) -> torch.Tensor:
return img[:, :, :-1, :] - img[:, :, 1:, :]
-def inverse_depth_smoothness_loss(
- idepth: torch.Tensor,
- image: torch.Tensor) -> torch.Tensor:
+def inverse_depth_smoothness_loss(idepth: torch.Tensor, image: torch.Tensor) -> torch.Tensor:
r"""Criterion that computes image-aware inverse depth smoothness loss.
.. math::
@@ -40,34 +38,27 @@ def inverse_depth_smoothness_loss(
>>> loss = inverse_depth_smoothness_loss(idepth, image)
"""
if not isinstance(idepth, torch.Tensor):
- raise TypeError("Input idepth type is not a torch.Tensor. Got {}"
- .format(type(idepth)))
+ raise TypeError("Input idepth type is not a torch.Tensor. Got {}".format(type(idepth)))
if not isinstance(image, torch.Tensor):
- raise TypeError("Input image type is not a torch.Tensor. Got {}"
- .format(type(image)))
+ raise TypeError("Input image type is not a torch.Tensor. Got {}".format(type(image)))
if not len(idepth.shape) == 4:
- raise ValueError("Invalid idepth shape, we expect BxCxHxW. Got: {}"
- .format(idepth.shape))
+ raise ValueError("Invalid idepth shape, we expect BxCxHxW. Got: {}".format(idepth.shape))
if not len(image.shape) == 4:
- raise ValueError("Invalid image shape, we expect BxCxHxW. Got: {}"
- .format(image.shape))
+ raise ValueError("Invalid image shape, we expect BxCxHxW. Got: {}".format(image.shape))
if not idepth.shape[-2:] == image.shape[-2:]:
- raise ValueError("idepth and image shapes must be the same. Got: {} and {}"
- .format(idepth.shape, image.shape))
+ raise ValueError("idepth and image shapes must be the same. Got: {} and {}".format(idepth.shape, image.shape))
if not idepth.device == image.device:
raise ValueError(
- "idepth and image must be in the same device. Got: {} and {}" .format(
- idepth.device, image.device))
+ "idepth and image must be in the same device. Got: {} and {}".format(idepth.device, image.device)
+ )
if not idepth.dtype == image.dtype:
- raise ValueError(
- "idepth and image must be in the same dtype. Got: {} and {}" .format(
- idepth.dtype, image.dtype))
+ raise ValueError("idepth and image must be in the same dtype. Got: {} and {}".format(idepth.dtype, image.dtype))
# compute the gradients
idepth_dx: torch.Tensor = _gradient_x(idepth)
@@ -76,10 +67,8 @@ def inverse_depth_smoothness_loss(
image_dy: torch.Tensor = _gradient_y(image)
# compute image weights
- weights_x: torch.Tensor = torch.exp(
- -torch.mean(torch.abs(image_dx), dim=1, keepdim=True))
- weights_y: torch.Tensor = torch.exp(
- -torch.mean(torch.abs(image_dy), dim=1, keepdim=True))
+ weights_x: torch.Tensor = torch.exp(-torch.mean(torch.abs(image_dx), dim=1, keepdim=True))
+ weights_y: torch.Tensor = torch.exp(-torch.mean(torch.abs(image_dy), dim=1, keepdim=True))
# apply image weights to depth
smoothness_x: torch.Tensor = torch.abs(idepth_dx * weights_x)
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 441b11f6a..5d20c2227 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -6,10 +6,10 @@ import torch.nn.functional as F
from kornia.utils.one_hot import one_hot
-
# based on:
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
+
def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Criterion that computes SΓΈrensen-Dice Coefficient loss.
@@ -49,29 +49,24 @@ def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> t
>>> output.backward()
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxNxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxNxHxW. Got: {}".format(input.shape))
if not input.shape[-2:] == target.shape[-2:]:
- raise ValueError("input and target shapes must be the same. Got: {} and {}"
- .format(input.shape, target.shape))
+ raise ValueError("input and target shapes must be the same. Got: {} and {}".format(input.shape, target.shape))
if not input.device == target.device:
raise ValueError(
- "input and target must be in the same device. Got: {} and {}" .format(
- input.device, target.device))
+ "input and target must be in the same device. Got: {} and {}".format(input.device, target.device)
+ )
# compute softmax over the classes axis
input_soft: torch.Tensor = F.softmax(input, dim=1)
# create the labels one hot tensor
- target_one_hot: torch.Tensor = one_hot(
- target, num_classes=input.shape[1],
- device=input.device, dtype=input.dtype)
+ target_one_hot: torch.Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)
# compute the actual dice score
dims = (1, 2, 3)
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index b03d999fb..44e1ab315 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -1,6 +1,5 @@
r"""Losses based on the divergence between probability distributions."""
-
import torch
import torch.nn.functional as F
@@ -22,6 +21,7 @@ def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
m = 0.5 * (p + q)
return 0.5 * _kl_div_2d(p, m) + 0.5 * _kl_div_2d(q, m)
+
# TODO: add this to the main module
@@ -31,11 +31,7 @@ def _reduce_loss(losses: torch.Tensor, reduction: str) -> torch.Tensor:
return torch.mean(losses) if reduction == 'mean' else torch.sum(losses)
-def js_div_loss_2d(
- input: torch.Tensor,
- target: torch.Tensor,
- reduction: str = 'mean'
-):
+def js_div_loss_2d(input: torch.Tensor, target: torch.Tensor, reduction: str = 'mean'):
r"""Calculates the Jensen-Shannon divergence loss between heatmaps.
Args:
@@ -56,11 +52,7 @@ def js_div_loss_2d(
return _reduce_loss(_js_div_2d(target, input), reduction)
-def kl_div_loss_2d(
- input: torch.Tensor,
- target: torch.Tensor,
- reduction: str = 'mean'
-):
+def kl_div_loss_2d(input: torch.Tensor, target: torch.Tensor, reduction: str = 'mean'):
r"""Calculates the Kullback-Leibler divergence loss between heatmaps.
Args:
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 25fc006d4..4d7d9f1ce 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -6,17 +6,18 @@ import torch.nn.functional as F
from kornia.utils.one_hot import one_hot
-
# based on:
# https://github.com/zhezh/focalloss/blob/master/focalloss.py
+
def focal_loss(
- input: torch.Tensor,
- target: torch.Tensor,
- alpha: float,
- gamma: float = 2.0,
- reduction: str = 'none',
- eps: float = 1e-8) -> torch.Tensor:
+ input: torch.Tensor,
+ target: torch.Tensor,
+ alpha: float,
+ gamma: float = 2.0,
+ reduction: str = 'none',
+ eps: float = 1e-8
+) -> torch.Tensor:
r"""Criterion that computes Focal loss.
According to :cite:`lin2018focal`, the Focal loss is computed as follows:
@@ -50,35 +51,31 @@ def focal_loss(
>>> output.backward()
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) >= 2:
- raise ValueError("Invalid input shape, we expect BxCx*. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCx*. Got: {}".format(input.shape))
if input.size(0) != target.size(0):
- raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
- .format(input.size(0), target.size(0)))
+ raise ValueError(
+ 'Expected input batch_size ({}) to match target batch_size ({}).'.format(input.size(0), target.size(0))
+ )
n = input.size(0)
- out_size = (n,) + input.size()[2:]
+ out_size = (n, ) + input.size()[2:]
if target.size()[1:] != input.size()[2:]:
- raise ValueError('Expected target size {}, got {}'.format(
- out_size, target.size()))
+ raise ValueError('Expected target size {}, got {}'.format(out_size, target.size()))
if not input.device == target.device:
raise ValueError(
- "input and target must be in the same device. Got: {} and {}" .format(
- input.device, target.device))
+ "input and target must be in the same device. Got: {} and {}".format(input.device, target.device)
+ )
# compute softmax over the classes axis
input_soft: torch.Tensor = F.softmax(input, dim=1) + eps
# create the labels one hot tensor
- target_one_hot: torch.Tensor = one_hot(
- target, num_classes=input.shape[1],
- device=input.device, dtype=input.dtype)
+ target_one_hot: torch.Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)
# compute the actual focal loss
weight = torch.pow(-input_soft + 1., gamma)
@@ -93,8 +90,7 @@ def focal_loss(
elif reduction == 'sum':
loss = torch.sum(loss_tmp)
else:
- raise NotImplementedError("Invalid reduction mode: {}"
- .format(reduction))
+ raise NotImplementedError("Invalid reduction mode: {}".format(reduction))
return loss
@@ -134,8 +130,7 @@ class FocalLoss(nn.Module):
>>> output.backward()
"""
- def __init__(self, alpha: float, gamma: float = 2.0,
- reduction: str = 'none', eps: float = 1e-8) -> None:
+ def __init__(self, alpha: float, gamma: float = 2.0, reduction: str = 'none', eps: float = 1e-8) -> None:
super(FocalLoss, self).__init__()
self.alpha: float = alpha
self.gamma: float = gamma
@@ -147,12 +142,13 @@ class FocalLoss(nn.Module):
def binary_focal_loss_with_logits(
- input: torch.Tensor,
- target: torch.Tensor,
- alpha: float = .25,
- gamma: float = 2.0,
- reduction: str = 'none',
- eps: float = 1e-8) -> torch.Tensor:
+ input: torch.Tensor,
+ target: torch.Tensor,
+ alpha: float = .25,
+ gamma: float = 2.0,
+ reduction: str = 'none',
+ eps: float = 1e-8
+) -> torch.Tensor:
r"""Function that computes Binary Focal loss.
.. math::
@@ -183,16 +179,15 @@ def binary_focal_loss_with_logits(
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) >= 2:
- raise ValueError("Invalid input shape, we expect BxCx*. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxCx*. Got: {}".format(input.shape))
if input.size(0) != target.size(0):
- raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
- .format(input.size(0), target.size(0)))
+ raise ValueError(
+ 'Expected input batch_size ({}) to match target batch_size ({}).'.format(input.size(0), target.size(0))
+ )
probs = torch.sigmoid(input)
target = target.unsqueeze(dim=1)
@@ -208,8 +203,7 @@ def binary_focal_loss_with_logits(
elif reduction == 'sum':
loss = torch.sum(loss_tmp)
else:
- raise NotImplementedError("Invalid reduction mode: {}"
- .format(reduction))
+ raise NotImplementedError("Invalid reduction mode: {}".format(reduction))
return loss
@@ -247,8 +241,7 @@ class BinaryFocalLossWithLogits(nn.Module):
>>> output.backward()
"""
- def __init__(self, alpha: float, gamma: float = 2.0,
- reduction: str = 'none') -> None:
+ def __init__(self, alpha: float, gamma: float = 2.0, reduction: str = 'none') -> None:
super(BinaryFocalLossWithLogits, self).__init__()
self.alpha: float = alpha
self.gamma: float = gamma
@@ -256,5 +249,4 @@ class BinaryFocalLossWithLogits(nn.Module):
self.eps: float = 1e-8
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
- return binary_focal_loss_with_logits(
- input, target, self.alpha, self.gamma, self.reduction, self.eps)
+ return binary_focal_loss_with_logits(input, target, self.alpha, self.gamma, self.reduction, self.eps)
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index e66287619..b45b37e4f 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -47,7 +47,7 @@ def psnr(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Ten
if input.shape != target.shape:
raise TypeError(f"Expected tensors of equal shapes, but got {input.shape} and {target.shape}")
- return 10. * torch.log10(max_val ** 2 / mse(input, target, reduction='mean'))
+ return 10. * torch.log10(max_val**2 / mse(input, target, reduction='mean'))
def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index c4721f013..106928428 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -7,8 +7,9 @@ import torch.nn.functional as F
from kornia.filters import get_gaussian_kernel2d, filter2D
-def ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int,
- max_val: float = 1.0, eps: float = 1e-12) -> torch.Tensor:
+def ssim(
+ img1: torch.Tensor, img2: torch.Tensor, window_size: int, max_val: float = 1.0, eps: float = 1e-12
+) -> torch.Tensor:
r"""Function that computes the Structural Similarity (SSIM) index map between two images.
Measures the (SSIM) index between each element in the input `x` and target `y`.
@@ -42,61 +43,58 @@ def ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int,
>>> ssim_map = ssim(input1, input2, 5) # 1x4x5x5
"""
if not isinstance(img1, torch.Tensor):
- raise TypeError("Input img1 type is not a torch.Tensor. Got {}"
- .format(type(img1)))
+ raise TypeError("Input img1 type is not a torch.Tensor. Got {}".format(type(img1)))
if not isinstance(img2, torch.Tensor):
- raise TypeError("Input img2 type is not a torch.Tensor. Got {}"
- .format(type(img2)))
+ raise TypeError("Input img2 type is not a torch.Tensor. Got {}".format(type(img2)))
if not isinstance(max_val, float):
raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")
if not len(img1.shape) == 4:
- raise ValueError("Invalid img1 shape, we expect BxCxHxW. Got: {}"
- .format(img1.shape))
+ raise ValueError("Invalid img1 shape, we expect BxCxHxW. Got: {}".format(img1.shape))
if not len(img2.shape) == 4:
- raise ValueError("Invalid img2 shape, we expect BxCxHxW. Got: {}"
- .format(img2.shape))
+ raise ValueError("Invalid img2 shape, we expect BxCxHxW. Got: {}".format(img2.shape))
if not img1.shape == img2.shape:
- raise ValueError("img1 and img2 shapes must be the same. Got: {} and {}"
- .format(img1.shape, img2.shape))
+ raise ValueError("img1 and img2 shapes must be the same. Got: {} and {}".format(img1.shape, img2.shape))
# prepare kernel
- kernel: torch.Tensor = (
- get_gaussian_kernel2d((window_size, window_size), (1.5, 1.5)).unsqueeze(0)
- )
+ kernel: torch.Tensor = (get_gaussian_kernel2d((window_size, window_size), (1.5, 1.5)).unsqueeze(0))
# compute coefficients
- C1: float = (0.01 * max_val) ** 2
- C2: float = (0.03 * max_val) ** 2
+ C1: float = (0.01 * max_val)**2
+ C2: float = (0.03 * max_val)**2
# compute local mean per channel
mu1: torch.Tensor = filter2D(img1, kernel)
mu2: torch.Tensor = filter2D(img2, kernel)
- mu1_sq = mu1 ** 2
- mu2_sq = mu2 ** 2
+ mu1_sq = mu1**2
+ mu2_sq = mu2**2
mu1_mu2 = mu1 * mu2
# compute local sigma per channel
- sigma1_sq = filter2D(img1 ** 2, kernel) - mu1_sq
- sigma2_sq = filter2D(img2 ** 2, kernel) - mu2_sq
+ sigma1_sq = filter2D(img1**2, kernel) - mu1_sq
+ sigma2_sq = filter2D(img2**2, kernel) - mu2_sq
sigma12 = filter2D(img1 * img2, kernel) - mu1_mu2
# compute the similarity index map
num: torch.Tensor = (2. * mu1_mu2 + C1) * (2. * sigma12 + C2)
- den: torch.Tensor = (
- (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
- )
+ den: torch.Tensor = ((mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
return num / (den + eps)
-def ssim_loss(img1: torch.Tensor, img2: torch.Tensor, window_size: int,
- max_val: float = 1.0, eps: float = 1e-12, reduction: str = 'mean') -> torch.Tensor:
+def ssim_loss(
+ img1: torch.Tensor,
+ img2: torch.Tensor,
+ window_size: int,
+ max_val: float = 1.0,
+ eps: float = 1e-12,
+ reduction: str = 'mean'
+) -> torch.Tensor:
r"""Function that computes a loss based on the SSIM measurement.
The loss, or the Structural dissimilarity (DSSIM) is described as:
@@ -216,8 +214,7 @@ class SSIMLoss(nn.Module):
>>> loss = criterion(input1, input2)
"""
- def __init__(self, window_size: int, max_val: float = 1.0,
- eps: float = 1e-12, reduction: str = 'mean') -> None:
+ def __init__(self, window_size: int, max_val: float = 1.0, eps: float = 1e-12, reduction: str = 'mean') -> None:
super(SSIMLoss, self).__init__()
self.window_size: int = window_size
self.max_val: float = max_val
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 4d0fd7e6e..a92b02003 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -22,9 +22,7 @@ def total_variation(img: torch.Tensor) -> torch.Tensor:
raise TypeError(f"Input type is not a torch.Tensor. Got {type(img)}")
if len(img.shape) < 3 or len(img.shape) > 4:
- raise ValueError(
- f"Expected input tensor to be of ndim 3 or 4, but got {len(img.shape)}."
- )
+ raise ValueError(f"Expected input tensor to be of ndim 3 or 4, but got {len(img.shape)}.")
pixel_dif1 = img[..., 1:, :] - img[..., :-1, :]
pixel_dif2 = img[..., :, 1:] - img[..., :, :-1]
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index dd0dc99cd..978ae2a8a 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -10,10 +10,9 @@ from kornia.utils.one_hot import one_hot
# https://github.com/kevinzakka/pytorch-goodies/blob/master/losses.py
-def tversky_loss(input: torch.Tensor,
- target: torch.Tensor,
- alpha: float, beta: float,
- eps: float = 1e-8) -> torch.Tensor:
+def tversky_loss(
+ input: torch.Tensor, target: torch.Tensor, alpha: float, beta: float, eps: float = 1e-8
+) -> torch.Tensor:
r"""Criterion that computes Tversky Coefficient loss.
According to :cite:`salehi2017tversky`, we compute the Tversky Coefficient as follows:
@@ -53,29 +52,24 @@ def tversky_loss(input: torch.Tensor,
>>> output.backward()
"""
if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(input)))
if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect BxNxHxW. Got: {}"
- .format(input.shape))
+ raise ValueError("Invalid input shape, we expect BxNxHxW. Got: {}".format(input.shape))
if not input.shape[-2:] == target.shape[-2:]:
- raise ValueError("input and target shapes must be the same. Got: {} and {}"
- .format(input.shape, input.shape))
+ raise ValueError("input and target shapes must be the same. Got: {} and {}".format(input.shape, input.shape))
if not input.device == target.device:
raise ValueError(
- "input and target must be in the same device. Got: {} and {}" .format(
- input.device, target.device))
+ "input and target must be in the same device. Got: {} and {}".format(input.device, target.device)
+ )
# compute softmax over the classes axis
input_soft: torch.Tensor = F.softmax(input, dim=1)
# create the labels one hot tensor
- target_one_hot: torch.Tensor = one_hot(
- target, num_classes=input.shape[1],
- device=input.device, dtype=input.dtype)
+ target_one_hot: torch.Tensor = one_hot(target, num_classes=input.shape[1], device=input.device, dtype=input.dtype)
# compute the actual dice score
dims = (1, 2, 3)
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 9d6b13c7f..5942621f8 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -26,20 +26,16 @@ def dilation(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List[i
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
if len(tensor.shape) != 4:
- raise ValueError("Input size must have 4 dimensions. Got {}".format(
- tensor.dim()))
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(tensor.dim()))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
- type(kernel)))
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(type(kernel)))
if len(kernel.shape) != 2:
- raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
- kernel.dim()))
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(kernel.dim()))
# origin
se_h, se_w = kernel.shape
@@ -80,20 +76,16 @@ def erosion(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List[in
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
if len(tensor.shape) != 4:
- raise ValueError("Input size must have 4 dimensions. Got {}".format(
- tensor.dim()))
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(tensor.dim()))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
- type(kernel)))
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(type(kernel)))
if len(kernel.shape) != 2:
- raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
- kernel.dim()))
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(kernel.dim()))
# origin
se_h, se_w = kernel.shape
@@ -134,20 +126,16 @@ def opening(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List[in
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
if len(tensor.shape) != 4:
- raise ValueError("Input size must have 4 dimensions. Got {}".format(
- tensor.dim()))
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(tensor.dim()))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
- type(kernel)))
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(type(kernel)))
if len(kernel.shape) != 2:
- raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
- kernel.dim()))
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(kernel.dim()))
return dilation(erosion(tensor, kernel, origin=origin), kernel, origin=origin)
@@ -174,20 +162,16 @@ def closing(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List[in
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
if len(tensor.shape) != 4:
- raise ValueError("Input size must have 4 dimensions. Got {}".format(
- tensor.dim()))
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(tensor.dim()))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
- type(kernel)))
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(type(kernel)))
if len(kernel.shape) != 2:
- raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
- kernel.dim()))
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(kernel.dim()))
return erosion(dilation(tensor, kernel, origin=origin), kernel, origin=origin)
@@ -242,20 +226,16 @@ def top_hat(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List[in
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
if len(tensor.shape) != 4:
- raise ValueError("Input size must have 4 dimensions. Got {}".format(
- tensor.dim()))
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(tensor.dim()))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
- type(kernel)))
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(type(kernel)))
if len(kernel.shape) != 2:
- raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
- kernel.dim()))
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(kernel.dim()))
return tensor - opening(tensor, kernel, origin=origin)
@@ -285,19 +265,15 @@ def bottom_hat(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
if len(tensor.shape) != 4:
- raise ValueError("Input size must have 4 dimensions. Got {}".format(
- tensor.dim()))
+ raise ValueError("Input size must have 4 dimensions. Got {}".format(tensor.dim()))
if not isinstance(kernel, torch.Tensor):
- raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(
- type(kernel)))
+ raise TypeError("Kernel type is not a torch.Tensor. Got {}".format(type(kernel)))
if len(kernel.shape) != 2:
- raise ValueError("Kernel size must have 2 dimensions. Got {}".format(
- kernel.dim()))
+ raise ValueError("Kernel size must have 2 dimensions. Got {}".format(kernel.dim()))
return closing(tensor, kernel, origin=origin) - tensor
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 58100037d..f03da3d6d 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -9,10 +9,7 @@ from copy import deepcopy
import torch
import numpy as np
-
-__all__ = [
- 'tensor_to_gradcheck_var', 'create_eye_batch', 'xla_is_available'
-]
+__all__ = ['tensor_to_gradcheck_var', 'create_eye_batch', 'xla_is_available']
def xla_is_available() -> bool:
@@ -25,16 +22,14 @@ def xla_is_available() -> bool:
def create_checkerboard(h, w, nw):
"""Creates a synthetic checkered board of shape HxW and window size `nw`.
"""
- return np.kron([[1, 0] * nw, [0, 1] * nw] * nw,
- np.ones((h // (2 * nw), w // (2 * nw)))).astype(np.float32)
+ return np.kron([[1, 0] * nw, [0, 1] * nw] * nw, np.ones((h // (2 * nw), w // (2 * nw)))).astype(np.float32)
# TODO: Isn't this function duplicated with eye_like?
def create_eye_batch(batch_size, eye_size, device=None, dtype=None):
"""Creates a batch of identity matrices of shape Bx3x3
"""
- return torch.eye(eye_size, device=device, dtype=dtype).view(
- 1, eye_size, eye_size).expand(batch_size, -1, -1)
+ return torch.eye(eye_size, device=device, dtype=dtype).view(1, eye_size, eye_size).expand(batch_size, -1, -1)
def create_random_homography(batch_size, eye_size, std_val=1e-3):
@@ -69,9 +64,7 @@ def check_is_tensor(obj):
def create_rectified_fundamental_matrix(batch_size):
"""Creates a batch of rectified fundamental matrices of shape Bx3x3
"""
- F_rect = torch.tensor([[0., 0., 0.],
- [0., 0., -1.],
- [0., 1., 0.]]).view(1, 3, 3)
+ F_rect = torch.tensor([[0., 0., 0.], [0., 0., -1.], [0., 1., 0.]]).view(1, 3, 3)
F_repeat = F_rect.repeat(batch_size, 1, 1)
return F_repeat
@@ -86,6 +79,7 @@ def create_random_fundamental_matrix(batch_size, std_val=1e-3):
class BaseTester(ABC):
+
@abstractmethod
def test_smoke(self):
raise NotImplementedError("Implement a stupid routine.")
@@ -139,8 +133,9 @@ def _get_precision(device: torch.device, dtype: torch.dtype) -> float:
return 1e-4
-def _get_precision_by_name(device: torch.device, device_target: str,
- tol_val: float, tol_val_default: float = 1e-4) -> float:
+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}.")
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index 0556cfff4..c0b7a9599 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -59,16 +59,17 @@ def draw_rectangle(
for b in range(batch):
for n in range(num_rectangle):
if fill:
- image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1),
+ image[b, :,
+ int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1),
int(rectangle[b, n, 0]):int(rectangle[b, n, 2] + 1)] = color[b, n, :, None, None]
else:
- image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1),
- rectangle[b, n, 0]] = color[b, n, :, None]
- image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1),
- rectangle[b, n, 2]] = color[b, n, :, None]
- image[b, :, rectangle[b, n, 1], int(rectangle[b, n, 0]):int(
- rectangle[b, n, 2] + 1)] = color[b, n, :, None]
- image[b, :, rectangle[b, n, 3], int(rectangle[b, n, 0]):int(
- rectangle[b, n, 2] + 1)] = color[b, n, :, None]
+ image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1), rectangle[b, n, 0]] = color[b, n, :,
+ None]
+ image[b, :, int(rectangle[b, n, 1]):int(rectangle[b, n, 3] + 1), rectangle[b, n, 2]] = color[b, n, :,
+ None]
+ image[b, :, rectangle[b, n, 1],
+ int(rectangle[b, n, 0]):int(rectangle[b, n, 2] + 1)] = color[b, n, :, None]
+ image[b, :, rectangle[b, n, 3],
+ int(rectangle[b, n, 0]):int(rectangle[b, n, 2] + 1)] = color[b, n, :, None]
return image
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index eb8a537cf..19a664ca3 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -5,11 +5,12 @@ import kornia as K
def create_meshgrid(
- height: int,
- width: int,
- normalized_coordinates: bool = True,
- device: Optional[torch.device] = torch.device('cpu'),
- dtype: torch.dtype = torch.float32) -> torch.Tensor:
+ height: int,
+ width: int,
+ normalized_coordinates: bool = True,
+ device: Optional[torch.device] = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
+) -> torch.Tensor:
"""Generates a coordinate grid for an image.
When the flag `normalized_coordinates` is set to True, the grid is
@@ -43,18 +44,18 @@ def create_meshgrid(
xs = (xs / (width - 1) - 0.5) * 2
ys = (ys / (height - 1) - 0.5) * 2
# generate grid by stacking coordinates
- base_grid: torch.Tensor = torch.stack(
- torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
+ base_grid: torch.Tensor = torch.stack(torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
return torch.unsqueeze(base_grid, dim=0).permute(0, 2, 3, 1) # 1xHxWx2
def create_meshgrid3d(
- depth: int,
- height: int,
- width: int,
- normalized_coordinates: bool = True,
- device: Optional[torch.device] = torch.device('cpu'),
- dtype: torch.dtype = torch.float32) -> torch.Tensor:
+ depth: int,
+ height: int,
+ width: int,
+ normalized_coordinates: bool = True,
+ device: Optional[torch.device] = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
+) -> torch.Tensor:
"""Generates a coordinate grid for an image.
When the flag `normalized_coordinates` is set to True, the grid is
@@ -84,6 +85,5 @@ def create_meshgrid3d(
ys = (ys / (height - 1) - 0.5) * 2
zs = (ys / (height - 1) - 0.5) * 2
# generate grid by stacking coordinates
- base_grid: torch.Tensor = torch.stack(
- torch.meshgrid([zs, xs, ys])).transpose(1, 2) # 3xHxW
+ base_grid: torch.Tensor = torch.stack(torch.meshgrid([zs, xs, ys])).transpose(1, 2) # 3xHxW
return base_grid.unsqueeze(0).permute(0, 3, 4, 2, 1) # 1xHxWx3
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index cd34b4707..8839f6bcc 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -14,7 +14,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
device, dtype = None, None
for tensor in tensor_list:
if tensor is not None:
- if not isinstance(tensor, (torch.Tensor,)):
+ if not isinstance(tensor, (torch.Tensor, )):
continue
_device = tensor.device
_dtype = tensor.dtype
@@ -22,8 +22,10 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
device = _device
dtype = _dtype
elif device != _device or dtype != _dtype:
- raise ValueError("Passed values are not in the same device and dtype."
- f"Got ({device}, {dtype}) and ({_device}, {_dtype}).")
+ raise ValueError(
+ "Passed values are not in the same device and dtype."
+ f"Got ({device}, {dtype}) and ({_device}, {_dtype})."
+ )
if device is None:
# TODO: update this when having torch.get_default_device()
device = torch.device('cpu')
@@ -41,7 +43,10 @@ def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
"""
assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
dtype: torch.dtype = input.dtype
- if dtype not in (torch.float32, torch.float64,):
+ if dtype not in (
+ torch.float32,
+ torch.float64,
+ ):
dtype = torch.float32
return torch.inverse(input.to(dtype)).to(input.dtype)
@@ -55,7 +60,10 @@ def _torch_histc_cast(input: torch.Tensor, bins: int, min: int, max: int) -> tor
"""
assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
dtype: torch.dtype = input.dtype
- if dtype not in (torch.float32, torch.float64,):
+ if dtype not in (
+ torch.float32,
+ torch.float64,
+ ):
dtype = torch.float32
return torch.histc(input.to(dtype), bins, min, max).to(input.dtype)
@@ -71,7 +79,10 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
"""
assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
dtype: torch.dtype = input.dtype
- if dtype not in (torch.float32, torch.float64,):
+ if dtype not in (
+ torch.float32,
+ torch.float64,
+ ):
dtype = torch.float32
out1, out2, out3 = torch.svd(input.to(dtype))
@@ -88,7 +99,10 @@ def _torch_solve_cast(input: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tenso
"""
assert isinstance(input, torch.Tensor), f"Input must be torch.Tensor. Got: {type(input)}."
dtype: torch.dtype = input.dtype
- if dtype not in (torch.float32, torch.float64,):
+ if dtype not in (
+ torch.float32,
+ torch.float64,
+ ):
dtype = torch.float32
out1, out2 = torch.solve(input.to(dtype), A.to(dtype))
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 9c6d4cd7e..84a74422a 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -18,13 +18,11 @@ def image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor:
torch.Tensor: tensor of the form :math:`(B, C, H, W)` if keepdim is ``False``,
:math:`(C, H, W)` otherwise.
"""
- if not isinstance(image, (np.ndarray,)):
- raise TypeError("Input type must be a numpy.ndarray. Got {}".format(
- type(image)))
+ if not isinstance(image, (np.ndarray, )):
+ raise TypeError("Input type must be a numpy.ndarray. Got {}".format(type(image)))
if len(image.shape) > 4 or len(image.shape) < 2:
- raise ValueError(
- "Input size must be a two, three or four dimensional array")
+ raise ValueError("Input size must be a two, three or four dimensional array")
input_shape = image.shape
tensor: torch.Tensor = torch.from_numpy(image)
@@ -40,8 +38,7 @@ def image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor:
tensor = tensor.permute(0, 3, 1, 2)
keepdim = True # no need to unsqueeze
else:
- raise ValueError(
- "Cannot process image with shape {}".format(input_shape))
+ raise ValueError("Cannot process image with shape {}".format(input_shape))
return tensor.unsqueeze(0) if not keepdim else tensor
@@ -110,12 +107,10 @@ def tensor_to_image(tensor: torch.Tensor) -> np.ndarray:
"""
if not isinstance(tensor, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}".format(
- type(tensor)))
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
if len(tensor.shape) > 4 or len(tensor.shape) < 2:
- raise ValueError(
- "Input size must be a two, three or four dimensional tensor")
+ raise ValueError("Input size must be a two, three or four dimensional tensor")
input_shape = tensor.shape
image: np.ndarray = tensor.cpu().detach().numpy()
@@ -138,8 +133,7 @@ def tensor_to_image(tensor: torch.Tensor) -> np.ndarray:
if input_shape[1] == 1:
image = image.squeeze(-1)
else:
- raise ValueError(
- "Cannot process tensor with shape {}".format(input_shape))
+ raise ValueError("Cannot process tensor with shape {}".format(input_shape))
return image
diff --git a/kornia/utils/metrics/confusion_matrix.py b/kornia/utils/metrics/confusion_matrix.py
index b0d705c79..5bd222554 100644
--- a/kornia/utils/metrics/confusion_matrix.py
+++ b/kornia/utils/metrics/confusion_matrix.py
@@ -7,10 +7,8 @@ import torch
def confusion_matrix(
- input: torch.Tensor,
- target: torch.Tensor,
- num_classes: int,
- normalized: Optional[bool] = False) -> torch.Tensor:
+ input: torch.Tensor, target: torch.Tensor, num_classes: int, normalized: Optional[bool] = False
+) -> torch.Tensor:
r"""Compute confusion matrix to evaluate the accuracy of a classification.
Args:
@@ -30,20 +28,21 @@ def confusion_matrix(
:math:`(B, K, K)` where K is the number of classes.
"""
if not torch.is_tensor(input) and input.dtype is not torch.int64:
- raise TypeError("Input input type is not a torch.Tensor with "
- "torch.int64 dtype. Got {}".format(type(input)))
+ raise TypeError("Input input type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(input)))
if not torch.is_tensor(target) and target.dtype is not torch.int64:
- raise TypeError("Input target type is not a torch.Tensor with "
- "torch.int64 dtype. Got {}".format(type(target)))
+ raise TypeError(
+ "Input target type is not a torch.Tensor with "
+ "torch.int64 dtype. Got {}".format(type(target))
+ )
if not input.shape == target.shape:
- raise ValueError("Inputs input and target must have the same shape. "
- "Got: {} and {}".format(input.shape, target.shape))
+ raise ValueError(
+ "Inputs input and target must have the same shape. "
+ "Got: {} and {}".format(input.shape, target.shape)
+ )
if not input.device == target.device:
- raise ValueError("Inputs must be in the same device. "
- "Got: {} - {}".format(input.device, target.device))
+ raise ValueError("Inputs must be in the same device. " "Got: {} - {}".format(input.device, target.device))
if not isinstance(num_classes, int) or num_classes < 2:
- raise ValueError("The number of classes must be an integer bigger "
- "than two. Got: {}".format(num_classes))
+ raise ValueError("The number of classes must be an integer bigger " "than two. Got: {}".format(num_classes))
batch_size: int = input.shape[0]
# hack for bitcounting 2 arrays together
@@ -58,8 +57,7 @@ def confusion_matrix(
confusion_list.append(bin_count)
confusion_vec: torch.Tensor = torch.stack(confusion_list)
- confusion_mat: torch.Tensor = confusion_vec.view(
- batch_size, num_classes, num_classes).to(torch.float32) # BxKxK
+ confusion_mat: torch.Tensor = confusion_vec.view(batch_size, num_classes, num_classes).to(torch.float32) # BxKxK
if normalized:
norm_val: torch.Tensor = torch.sum(confusion_mat, dim=1, keepdim=True)
diff --git a/kornia/utils/metrics/mean_iou.py b/kornia/utils/metrics/mean_iou.py
index c14730820..d5e887906 100644
--- a/kornia/utils/metrics/mean_iou.py
+++ b/kornia/utils/metrics/mean_iou.py
@@ -4,11 +4,7 @@ import torch
from kornia.utils.metrics.confusion_matrix import confusion_matrix
-def mean_iou(
- input: torch.Tensor,
- target: torch.Tensor,
- num_classes: int,
- eps: Optional[float] = 1e-6) -> torch.Tensor:
+def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: Optional[float] = 1e-6) -> torch.Tensor:
r"""Calculate mean Intersection-Over-Union (mIOU).
The function internally computes the confusion matrix.
@@ -28,20 +24,21 @@ def mean_iou(
with shape :math:`(B, K)` where K is the number of classes.
"""
if not torch.is_tensor(input) and input.dtype is not torch.int64:
- raise TypeError("Input input type is not a torch.Tensor with "
- "torch.int64 dtype. Got {}".format(type(input)))
+ raise TypeError("Input input type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(input)))
if not torch.is_tensor(target) and target.dtype is not torch.int64:
- raise TypeError("Input target type is not a torch.Tensor with "
- "torch.int64 dtype. Got {}".format(type(target)))
+ raise TypeError(
+ "Input target type is not a torch.Tensor with "
+ "torch.int64 dtype. Got {}".format(type(target))
+ )
if not input.shape == target.shape:
- raise ValueError("Inputs input and target must have the same shape. "
- "Got: {} and {}".format(input.shape, target.shape))
+ raise ValueError(
+ "Inputs input and target must have the same shape. "
+ "Got: {} and {}".format(input.shape, target.shape)
+ )
if not input.device == target.device:
- raise ValueError("Inputs must be in the same device. "
- "Got: {} - {}".format(input.device, target.device))
+ raise ValueError("Inputs must be in the same device. " "Got: {} - {}".format(input.device, target.device))
if not isinstance(num_classes, int) or num_classes < 2:
- raise ValueError("The number of classes must be an integer bigger "
- "than two. Got: {}".format(num_classes))
+ raise ValueError("The number of classes must be an integer bigger " "than two. Got: {}".format(num_classes))
# we first compute the confusion matrix
conf_mat: torch.Tensor = confusion_matrix(input, target, num_classes)
diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.py
index 3c1f41ee8..839a8b048 100644
--- a/kornia/utils/one_hot.py
+++ b/kornia/utils/one_hot.py
@@ -3,11 +3,13 @@ from typing import Optional
import torch
-def one_hot(labels: torch.Tensor,
- num_classes: int,
- device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None,
- eps: float = 1e-6) -> torch.Tensor:
+def one_hot(
+ labels: torch.Tensor,
+ num_classes: int,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ eps: float = 1e-6
+) -> torch.Tensor:
r"""Converts an integer label x-D tensor to a one-hot (x+1)-D tensor.
Args:
@@ -39,21 +41,15 @@ def one_hot(labels: torch.Tensor,
"""
if not isinstance(labels, torch.Tensor):
- raise TypeError("Input labels type is not a torch.Tensor. Got {}"
- .format(type(labels)))
+ raise TypeError("Input labels type is not a torch.Tensor. Got {}".format(type(labels)))
if not labels.dtype == torch.int64:
- raise ValueError(
- "labels must be of the same dtype torch.int64. Got: {}" .format(
- labels.dtype))
+ raise ValueError("labels must be of the same dtype torch.int64. Got: {}".format(labels.dtype))
if num_classes < 1:
- raise ValueError("The number of classes must be bigger than one."
- " Got: {}".format(num_classes))
+ raise ValueError("The number of classes must be bigger than one." " Got: {}".format(num_classes))
shape = labels.shape
- one_hot = torch.zeros(
- (shape[0], num_classes) + shape[1:], device=device, dtype=dtype
- )
+ one_hot = torch.zeros((shape[0], num_classes) + shape[1:], device=device, dtype=dtype)
return one_hot.scatter_(1, labels.unsqueeze(1), 1.0) + eps
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.py
index 8f90e2b7e..526b4a468 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/utils/pointcloud_io.py
@@ -14,14 +14,11 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
component is assumed to be a 3d point coordinate :math:`(X, Y, Z)`.
"""
if not isinstance(filename, str) and filename[-3:] == '.ply':
- raise TypeError("Input filename must be a string in with the .ply "
- "extension. Got {}".format(filename))
+ raise TypeError("Input filename must be a string in with the .ply " "extension. Got {}".format(filename))
if not torch.is_tensor(pointcloud):
- raise TypeError("Input pointcloud type is not a torch.Tensor. Got {}"
- .format(type(pointcloud)))
+ raise TypeError("Input pointcloud type is not a torch.Tensor. Got {}".format(type(pointcloud)))
if not len(pointcloud.shape) == 3 and pointcloud.shape[-1] == 3:
- raise TypeError("Input pointcloud must be in the following shape "
- "HxWx3. Got {}.".format(pointcloud.shape))
+ raise TypeError("Input pointcloud must be in the following shape " "HxWx3. Got {}.".format(pointcloud.shape))
# flatten the input pointcloud in a vector to iterate points
xyz_vec: torch.Tensor = pointcloud.reshape(-1, 3)
@@ -48,8 +45,7 @@ def save_pointcloud_ply(filename: str, pointcloud: torch.Tensor) -> None:
f.write(data_str)
-def load_pointcloud_ply(
- filename: str, header_size: Optional[int] = 8) -> torch.Tensor:
+def load_pointcloud_ply(filename: str, header_size: Optional[int] = 8) -> torch.Tensor:
r"""Utility function to load from disk a pointcloud in PLY format.
Args:
@@ -62,13 +58,11 @@ def load_pointcloud_ply(
:math:`(*, 3)` where :math:`*` represents the number of points.
"""
if not isinstance(filename, str) and filename[-3:] == '.ply':
- raise TypeError("Input filename must be a string in with the .ply "
- "extension. Got {}".format(filename))
+ raise TypeError("Input filename must be a string in with the .ply " "extension. Got {}".format(filename))
if not os.path.isfile(filename):
raise ValueError("Input filename is not an existing file.")
if not (isinstance(header_size, int) and header_size > 0):
- raise TypeError("Input header_size must be a positive integer. Got {}."
- .format(header_size))
+ raise TypeError("Input header_size must be a positive integer. Got {}.".format(header_size))
# open the file and populate tensor
with open(filename, 'r') as f:
points = []
diff --git a/requirements-dev.txt b/requirements-dev.txt
index 92d1c2118..53af987ca 100644
--- a/requirements-dev.txt
+++ b/requirements-dev.txt
@@ -3,5 +3,5 @@ pytest==5.4.2
pytest-flake8==1.0.6
pytest-cov==2.9.0
pytest-mypy==0.7.0
-autopep8
pydocstyle
+yapf
\ No newline at end of file
diff --git a/setup.cfg b/setup.cfg
index 20bf793c7..4b442c43c 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -27,3 +27,17 @@ exclude_lines =
raise
if 0:
if __name__ == .__main__.:
+
+
+[yapf]
+based_on_style = pep8
+spaces_before_comment = 2
+split_before_logical_operator = true
+split_before_arithmetic_operator = true
+COLUMN_LIMIT = 120
+;COALESCE_BRACKETS = true
+DEDENT_CLOSING_BRACKETS = true
+ALLOW_SPLIT_BEFORE_DICT_VALUE = false
+BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF = true
+NO_SPACES_AROUND_SELECTED_BINARY_OPERATORS = false
+DISABLE_ENDING_COMMA_HEURISTIC = false
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index b128a3f27..f66389946 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -34,7 +34,6 @@ from kornia.augmentation import (
RandomThinPlateSpline,
)
-
from kornia.testing import BaseTester, default_with_one_parameter_changed, cartesian_product_of_parameters
from kornia.augmentation.base import AugmentationBase2D
from kornia.utils.helpers import _torch_inverse_cast
@@ -72,11 +71,14 @@ class CommonTests(BaseTester):
self._test_smoke_call_implementation(params=param_set)
self._test_smoke_return_transform_implementation(params=param_set)
- @pytest.mark.parametrize("input_shape,expected_output_shape",
- [((4, 5), (1, 1, 4, 5)), ((3, 4, 5), (1, 3, 4, 5)), ((2, 3, 4, 5), (2, 3, 4, 5))])
+ @pytest.mark.parametrize(
+ "input_shape,expected_output_shape",
+ [((4, 5), (1, 1, 4, 5)), ((3, 4, 5), (1, 3, 4, 5)), ((2, 3, 4, 5), (2, 3, 4, 5))]
+ )
def test_cardinality(self, input_shape, expected_output_shape):
self._test_cardinality_implementation(
- input_shape=input_shape, expected_output_shape=expected_output_shape, params=self._default_param_set)
+ input_shape=input_shape, expected_output_shape=expected_output_shape, params=self._default_param_set
+ )
def test_random_p_0(self):
self._test_random_p_0_implementation(params=self._default_param_set)
@@ -109,12 +111,12 @@ class CommonTests(BaseTester):
def test_gradcheck(self):
self._test_gradcheck_implementation(params=self._default_param_set)
-# TODO Implement
-# test_batch
-# test_batch_return_transform
-# test_coordinate check
-# test_jit
-# test_gradcheck
+ # TODO Implement
+ # test_batch
+ # test_batch_return_transform
+ # test_coordinate check
+ # test_jit
+ # test_gradcheck
def _create_augmentation_from_params(self, **params):
return self._augmentation_cls(**params)
@@ -124,13 +126,15 @@ class CommonTests(BaseTester):
############################################################################################################
def _test_smoke_implementation(self, params):
- assert issubclass(self._augmentation_cls,
- AugmentationBase2D), f"{self._augmentation_cls} is not a subclass of AugmentationBase2D"
+ assert issubclass(
+ self._augmentation_cls, AugmentationBase2D
+ ), f"{self._augmentation_cls} is not a subclass of AugmentationBase2D"
# Can be instatiated
augmentation = self._create_augmentation_from_params(**params, return_transform=False)
assert issubclass(
- type(augmentation), AugmentationBase2D), f"{type(augmentation)} is not a subclass of AugmentationBase2D"
+ type(augmentation), AugmentationBase2D
+ ), f"{type(augmentation)} is not a subclass of AugmentationBase2D"
# generate_parameters can be called and returns the correct amount of parameters
batch_shape = (4, 3, 5, 6)
@@ -163,7 +167,8 @@ class CommonTests(BaseTester):
assert transformation.shape == expected_transformation_shape
output, final_transformation = augmentation(
- (test_input, test_transform), params=generated_params, return_transform=True)
+ (test_input, test_transform), params=generated_params, return_transform=True
+ )
assert output.shape[0] == batch_shape[0]
assert final_transformation.shape == expected_transformation_shape
assert_allclose(final_transformation, transformation @ test_transform, atol=1e-4, rtol=1e-4)
@@ -191,7 +196,8 @@ class CommonTests(BaseTester):
assert_allclose(final_transformation, transformation @ test_transform, atol=1e-4, rtol=1e-4)
output, final_transformation = augmentation(
- (test_input, test_transform), params=generated_params, return_transform=True)
+ (test_input, test_transform), params=generated_params, return_transform=True
+ )
assert output.shape[0] == batch_shape[0]
assert final_transformation.shape == expected_transformation_shape
assert_allclose(final_transformation, transformation @ test_transform, atol=1e-4, rtol=1e-4)
@@ -203,7 +209,7 @@ class CommonTests(BaseTester):
test_input = torch.rand(input_shape, device=self.device, dtype=self.dtype)
output = augmentation(test_input)
assert len(output.shape) == 4
- assert output.shape == torch.Size((1,) * (4 - len(input_shape)) + tuple(input_shape))
+ assert output.shape == torch.Size((1, ) * (4 - len(input_shape)) + tuple(input_shape))
# p==1.0
augmentation = self._create_augmentation_from_params(**params, p=1.0)
@@ -239,7 +245,8 @@ class CommonTests(BaseTester):
assert_allclose(output, expected_output.to(self.device).to(self.dtype), atol=1e-4, rtol=1e-4)
def _test_random_p_1_return_transform_implementation(
- self, input_tensor, expected_output, expected_transformation, params):
+ self, input_tensor, expected_output, expected_transformation, params
+ ):
augmentation = self._create_augmentation_from_params(**params, p=1.0, return_transform=True)
output, transformation = augmentation(input_tensor.to(self.device).to(self.dtype))
# Output should match
@@ -247,8 +254,7 @@ class CommonTests(BaseTester):
assert_allclose(output, expected_output.to(self.device).to(self.dtype), atol=1e-4, rtol=1e-4)
# Transformation should match
assert transformation.shape == expected_transformation.shape
- assert_allclose(transformation, expected_transformation.to(
- self.device).to(self.dtype), atol=1e-4, rtol=1e-4)
+ assert_allclose(transformation, expected_transformation.to(self.device).to(self.dtype), atol=1e-4, rtol=1e-4)
def _test_module_implementation(self, params):
augmentation = self._create_augmentation_from_params(**params, p=0.5, return_transform=True)
@@ -282,14 +288,11 @@ class CommonTests(BaseTester):
if (transform == kornia.eye_like(3, transform)).all():
pytest.skip("Test not relevant for intensity augmentations.")
- indices = kornia.create_meshgrid(height=output.shape[-2],
- width=output.shape[-1],
- normalized_coordinates=False,
- device=self.device)
+ indices = kornia.create_meshgrid(
+ height=output.shape[-2], width=output.shape[-1], normalized_coordinates=False, device=self.device
+ )
output_indices = indices.reshape((1, -1, 2)).to(dtype=self.dtype)
- input_indices = kornia.geometry.transform_points(
- _torch_inverse_cast(transform.to(self.dtype)),
- output_indices)
+ input_indices = kornia.geometry.transform_points(_torch_inverse_cast(transform.to(self.dtype)), output_indices)
output_indices = output_indices.round().long().squeeze(0)
input_indices = input_indices.round().long().squeeze(0)
@@ -305,13 +308,9 @@ class CommonTests(BaseTester):
input_tensor = torch.rand((3, 5, 5), device=self.device, dtype=self.dtype) # 3 x 3
input_tensor = utils.tensor_to_gradcheck_var(input_tensor) # to var
assert gradcheck(
- self._create_augmentation_from_params(
- **params,
- p=1.,
- return_transform=False),
- (input_tensor,
- ),
- raise_exception=True)
+ self._create_augmentation_from_params(**params, p=1., return_transform=False), (input_tensor, ),
+ raise_exception=True
+ )
class TestRandomEqualizeAlternative(CommonTests):
@@ -329,18 +328,20 @@ class TestRandomEqualizeAlternative(CommonTests):
input_tensor = torch.arange(20., device=self.device, dtype=self.dtype) / 20
input_tensor = input_tensor.repeat(1, 2, 20, 1)
- expected_output = 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=self.device, dtype=self.dtype)
+ expected_output = 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=self.device,
+ dtype=self.dtype
+ )
expected_output = expected_output.repeat(1, 2, 20, 1)
parameters = {}
self._test_random_p_1_implementation(
- input_tensor=input_tensor,
- expected_output=expected_output,
- params=parameters)
+ input_tensor=input_tensor, expected_output=expected_output, params=parameters
+ )
def test_random_p_1_return_transform(self):
torch.manual_seed(42)
@@ -356,17 +357,21 @@ class TestRandomEqualizeAlternative(CommonTests):
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
def test_batch(self):
input_tensor = torch.arange(20., device=self.device, dtype=self.dtype) / 20
input_tensor = input_tensor.repeat(2, 3, 20, 1)
- expected_output = 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=self.device, dtype=self.dtype)
+ expected_output = 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=self.device,
+ dtype=self.dtype
+ )
expected_output = expected_output.repeat(2, 3, 20, 1)
expected_transformation = kornia.eye_like(3, input_tensor)
@@ -375,13 +380,15 @@ class TestRandomEqualizeAlternative(CommonTests):
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
def test_exception(self):
with pytest.raises(ValueError):
- self._create_augmentation_from_params(p=1.)(torch.ones(
- (1, 3, 4, 5) * 200, device=self.device, dtype=self.dtype))
+ self._create_augmentation_from_params(p=1.)(
+ torch.ones((1, 3, 4, 5) * 200, device=self.device, dtype=self.dtype)
+ )
class TestCenterCropAlternative(CommonTests):
@@ -393,70 +400,97 @@ class TestCenterCropAlternative(CommonTests):
_augmentation_cls = CenterCrop
_default_param_set: Dict["str", Any] = {"size": (2, 2), "align_corners": True}
- @pytest.fixture(params=default_with_one_parameter_changed(default=_default_param_set,
- **possible_params), scope="class")
+ @pytest.fixture(
+ params=default_with_one_parameter_changed(default=_default_param_set, **possible_params), scope="class"
+ )
def param_set(self, request):
return request.param
- @pytest.mark.parametrize("input_shape,expected_output_shape",
- [((4, 5), (1, 1, 2, 3)), ((3, 4, 5), (1, 3, 2, 3)), ((2, 3, 4, 5), (2, 3, 2, 3))])
+ @pytest.mark.parametrize(
+ "input_shape,expected_output_shape",
+ [((4, 5), (1, 1, 2, 3)), ((3, 4, 5), (1, 3, 2, 3)), ((2, 3, 4, 5), (2, 3, 2, 3))]
+ )
def test_cardinality(self, input_shape, expected_output_shape):
- self._test_cardinality_implementation(input_shape=input_shape,
- expected_output_shape=expected_output_shape,
- params={"size": (2, 3), "align_corners": True})
+ self._test_cardinality_implementation(
+ input_shape=input_shape,
+ expected_output_shape=expected_output_shape,
+ params={
+ "size": (2, 3),
+ "align_corners": True
+ }
+ )
@pytest.mark.xfail(reason="size=(1,2) results in RuntimeError: solve_cpu: For batch 0: U(3,3) is zero, singular U.")
def test_random_p_1(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, 0.4],
- [0.5, 0.6, 0.7, 0.8],
- [0.9, 0.0, 0.1, 0.2]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 0.0, 0.1, 0.2]]], device=self.device, dtype=self.dtype
+ )
expected_output = torch.tensor([[[
- [0.6, 0.7, ],
+ [
+ 0.6,
+ 0.7,
+ ],
]]], device=self.device, dtype=self.dtype)
parameters = {"size": (1, 2), "align_corners": True, "resample": 0}
self._test_random_p_1_implementation(
- input_tensor=input_tensor,
- expected_output=expected_output,
- params=parameters)
+ input_tensor=input_tensor, expected_output=expected_output, params=parameters
+ )
def test_random_p_1_return_transform(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, 0.4],
- [0.5, 0.6, 0.7, 0.8],
- [0.9, 0.0, 0.1, 0.2]]], device=self.device, dtype=self.dtype)
- expected_output = torch.tensor([[[
- [0.2, 0.3, ],
- [0.6, 0.7, ],
- [0.0, 0.1, ],
- ]]], device=self.device, dtype=self.dtype)
- expected_transformation = torch.tensor([[[1., 0., -1.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 0.0, 0.1, 0.2]]], device=self.device, dtype=self.dtype
+ )
+ expected_output = torch.tensor(
+ [[[
+ [
+ 0.2,
+ 0.3,
+ ],
+ [
+ 0.6,
+ 0.7,
+ ],
+ [
+ 0.0,
+ 0.1,
+ ],
+ ]]], device=self.device, dtype=self.dtype
+ )
+ expected_transformation = torch.tensor(
+ [[[1., 0., -1.], [0., 1., 0.], [0., 0., 1.]]], device=self.device, dtype=self.dtype
+ )
parameters = {"size": (3, 2), "align_corners": True, "resample": 0}
self._test_random_p_1_return_transform_implementation(
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
def test_batch(self):
torch.manual_seed(42)
input_tensor = torch.rand((2, 3, 4, 4), device=self.device, dtype=self.dtype)
expected_output = input_tensor[:, :, 1:3, 1:3]
- expected_transformation = torch.tensor([[[1., 0., -1.],
- [0., 1., -1.],
- [0., 0., 1.]]], device=self.device, dtype=self.dtype).repeat(2, 1, 1,)
+ expected_transformation = torch.tensor(
+ [[[1., 0., -1.], [0., 1., -1.], [0., 0., 1.]]], device=self.device, dtype=self.dtype
+ ).repeat(
+ 2,
+ 1,
+ 1,
+ )
parameters = {"size": (2, 2), "align_corners": True, "resample": 0}
self._test_random_p_1_return_transform_implementation(
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
@pytest.mark.xfail(reason="No input validation is implemented yet.")
def test_exception(self):
@@ -489,56 +523,129 @@ class TestRandomHorizontalFlipAlternative(CommonTests):
def test_random_p_1(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]], device=self.device, dtype=self.dtype)
- expected_output = torch.tensor([[[[0.3, 0.2, 0.1, ],
- [0.6, 0.5, 0.4, ],
- [0.9, 0.8, 0.7, ]]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]], device=self.device, dtype=self.dtype
+ )
+ expected_output = torch.tensor(
+ [[[[
+ 0.3,
+ 0.2,
+ 0.1,
+ ], [
+ 0.6,
+ 0.5,
+ 0.4,
+ ], [
+ 0.9,
+ 0.8,
+ 0.7,
+ ]]]], device=self.device, dtype=self.dtype
+ )
parameters = {}
self._test_random_p_1_implementation(
- input_tensor=input_tensor,
- expected_output=expected_output,
- params=parameters)
+ input_tensor=input_tensor, expected_output=expected_output, params=parameters
+ )
def test_random_p_1_return_transform(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]], device=self.device, dtype=self.dtype)
- expected_output = torch.tensor([[[[0.3, 0.2, 0.1, ],
- [0.6, 0.5, 0.4, ],
- [0.9, 0.8, 0.7, ]]]], device=self.device, dtype=self.dtype)
- expected_transformation = torch.tensor([[[-1.0, 0.0, 2.0],
- [0.0, 1.0, 0.0],
- [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]], device=self.device, dtype=self.dtype
+ )
+ expected_output = torch.tensor(
+ [[[[
+ 0.3,
+ 0.2,
+ 0.1,
+ ], [
+ 0.6,
+ 0.5,
+ 0.4,
+ ], [
+ 0.9,
+ 0.8,
+ 0.7,
+ ]]]], device=self.device, dtype=self.dtype
+ )
+ expected_transformation = torch.tensor(
+ [[[-1.0, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype
+ )
parameters = {}
self._test_random_p_1_return_transform_implementation(
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
def test_batch(self):
torch.manual_seed(12)
- input_tensor = torch.tensor([[[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]]], device=self.device, dtype=self.dtype).repeat((2, 1, 1, 1))
- expected_output = torch.tensor([[[[0.3, 0.2, 0.1, ],
- [0.6, 0.5, 0.4, ],
- [0.9, 0.8, 0.7, ]]]], device=self.device, dtype=self.dtype).repeat((2, 1, 1, 1)) # noqa: E501
- expected_transformation = torch.tensor([[[-1.0, 0.0, 2.0],
- [0.0, 1.0, 0.0],
- [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype).repeat((2, 1, 1)) # noqa: E501
+ input_tensor = torch.tensor(
+ [[[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]]], device=self.device, dtype=self.dtype
+ ).repeat((2, 1, 1, 1))
+ expected_output = torch.tensor(
+ [[[[
+ 0.3,
+ 0.2,
+ 0.1,
+ ], [
+ 0.6,
+ 0.5,
+ 0.4,
+ ], [
+ 0.9,
+ 0.8,
+ 0.7,
+ ]]]], device=self.device, dtype=self.dtype
+ ).repeat((2, 1, 1, 1)) # noqa: E501
+ expected_transformation = torch.tensor(
+ [[[-1.0, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype
+ ).repeat((2, 1, 1)) # noqa: E501
parameters = {}
self._test_random_p_1_return_transform_implementation(
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
@pytest.mark.skip(reason="No special parameters to validate.")
def test_exception(self):
@@ -557,56 +664,129 @@ class TestRandomVerticalFlipAlternative(CommonTests):
def test_random_p_1(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]], device=self.device, dtype=self.dtype)
- expected_output = torch.tensor([[[[0.7, 0.8, 0.9, ],
- [0.4, 0.5, 0.6, ],
- [0.1, 0.2, 0.3, ]]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]], device=self.device, dtype=self.dtype
+ )
+ expected_output = torch.tensor(
+ [[[[
+ 0.7,
+ 0.8,
+ 0.9,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.1,
+ 0.2,
+ 0.3,
+ ]]]], device=self.device, dtype=self.dtype
+ )
parameters = {}
self._test_random_p_1_implementation(
- input_tensor=input_tensor,
- expected_output=expected_output,
- params=parameters)
+ input_tensor=input_tensor, expected_output=expected_output, params=parameters
+ )
def test_random_p_1_return_transform(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]], device=self.device, dtype=self.dtype)
- expected_output = torch.tensor([[[[0.7, 0.8, 0.9, ],
- [0.4, 0.5, 0.6, ],
- [0.1, 0.2, 0.3, ]]]], device=self.device, dtype=self.dtype)
- expected_transformation = torch.tensor([[[1.0, 0.0, 0.0],
- [0.0, -1.0, 2.0],
- [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]], device=self.device, dtype=self.dtype
+ )
+ expected_output = torch.tensor(
+ [[[[
+ 0.7,
+ 0.8,
+ 0.9,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.1,
+ 0.2,
+ 0.3,
+ ]]]], device=self.device, dtype=self.dtype
+ )
+ expected_transformation = torch.tensor(
+ [[[1.0, 0.0, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype
+ )
parameters = {}
self._test_random_p_1_return_transform_implementation(
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
def test_batch(self):
torch.manual_seed(12)
- input_tensor = torch.tensor([[[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]]], device=self.device, dtype=self.dtype).repeat((2, 1, 1, 1))
- expected_output = torch.tensor([[[[0.7, 0.8, 0.9, ],
- [0.4, 0.5, 0.6, ],
- [0.1, 0.2, 0.3, ]]]], device=self.device, dtype=self.dtype).repeat((2, 1, 1, 1)) # noqa: E501
- expected_transformation = torch.tensor([[[1.0, 0.0, 0.0],
- [0.0, -1.0, 2.0],
- [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype).repeat((2, 1, 1)) # noqa: E501
+ input_tensor = torch.tensor(
+ [[[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]]], device=self.device, dtype=self.dtype
+ ).repeat((2, 1, 1, 1))
+ expected_output = torch.tensor(
+ [[[[
+ 0.7,
+ 0.8,
+ 0.9,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.1,
+ 0.2,
+ 0.3,
+ ]]]], device=self.device, dtype=self.dtype
+ ).repeat((2, 1, 1, 1)) # noqa: E501
+ expected_transformation = torch.tensor(
+ [[[1.0, 0.0, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype
+ ).repeat((2, 1, 1)) # noqa: E501
parameters = {}
self._test_random_p_1_return_transform_implementation(
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
@pytest.mark.skip(reason="No special parameters to validate.")
def test_exception(self):
@@ -622,52 +802,113 @@ class TestRandomRotationAlternative(CommonTests):
_augmentation_cls = RandomRotation
_default_param_set: Dict["str", Any] = {"degrees": (30., 30.), "align_corners": True}
- @pytest.fixture(params=default_with_one_parameter_changed(default=_default_param_set,
- **possible_params), scope="class")
+ @pytest.fixture(
+ params=default_with_one_parameter_changed(default=_default_param_set, **possible_params), scope="class"
+ )
def param_set(self, request):
return request.param
def test_random_p_1(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]], device=self.device, dtype=self.dtype)
- expected_output = torch.tensor([[[[0.3, 0.6, 0.9, ],
- [0.2, 0.5, 0.8, ],
- [0.1, 0.4, 0.7, ]]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]], device=self.device, dtype=self.dtype
+ )
+ expected_output = torch.tensor(
+ [[[[
+ 0.3,
+ 0.6,
+ 0.9,
+ ], [
+ 0.2,
+ 0.5,
+ 0.8,
+ ], [
+ 0.1,
+ 0.4,
+ 0.7,
+ ]]]], device=self.device, dtype=self.dtype
+ )
parameters = {"degrees": (90., 90.), "align_corners": True}
self._test_random_p_1_implementation(
- input_tensor=input_tensor,
- expected_output=expected_output,
- params=parameters)
+ input_tensor=input_tensor, expected_output=expected_output, params=parameters
+ )
def test_random_p_1_return_transform(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]], device=self.device, dtype=self.dtype)
- expected_output = torch.tensor([[[[0.7, 0.4, 0.1, ],
- [0.8, 0.5, 0.2, ],
- [0.9, 0.6, 0.3, ]]]], device=self.device, dtype=self.dtype)
- expected_transformation = torch.tensor([[[0.0, -1.0, 2.0],
- [1.0, 0.0, 0.0],
- [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype)
+ input_tensor = torch.tensor(
+ [[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]], device=self.device, dtype=self.dtype
+ )
+ expected_output = torch.tensor(
+ [[[[
+ 0.7,
+ 0.4,
+ 0.1,
+ ], [
+ 0.8,
+ 0.5,
+ 0.2,
+ ], [
+ 0.9,
+ 0.6,
+ 0.3,
+ ]]]], device=self.device, dtype=self.dtype
+ )
+ expected_transformation = torch.tensor(
+ [[[0.0, -1.0, 2.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], device=self.device, dtype=self.dtype
+ )
parameters = {"degrees": (-90., -90.), "align_corners": True}
self._test_random_p_1_return_transform_implementation(
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
def test_batch(self):
torch.manual_seed(12)
- input_tensor = torch.tensor([[[[0.1, 0.2, 0.3, ],
- [0.4, 0.5, 0.6, ],
- [0.7, 0.8, 0.9, ]]]], device=self.device, dtype=self.dtype).repeat((2, 1, 1, 1))
+ input_tensor = torch.tensor(
+ [[[[
+ 0.1,
+ 0.2,
+ 0.3,
+ ], [
+ 0.4,
+ 0.5,
+ 0.6,
+ ], [
+ 0.7,
+ 0.8,
+ 0.9,
+ ]]]], device=self.device, dtype=self.dtype
+ ).repeat((2, 1, 1, 1))
expected_output = input_tensor
expected_transformation = kornia.eye_like(3, input_tensor)
parameters = {"degrees": (-360., -360.), "align_corners": True}
@@ -675,7 +916,8 @@ class TestRandomRotationAlternative(CommonTests):
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
@pytest.mark.xfail(reason="No input validation is implemented yet.")
def test_exception(self):
@@ -709,69 +951,38 @@ class TestRandomGrayscaleAlternative(CommonTests):
def param_set(self, request):
return request.param
- @pytest.mark.parametrize("input_shape,expected_output_shape",
- [((3, 4, 5), (1, 3, 4, 5)), ((2, 3, 4, 5), (2, 3, 4, 5))])
+ @pytest.mark.parametrize(
+ "input_shape,expected_output_shape", [((3, 4, 5), (1, 3, 4, 5)), ((2, 3, 4, 5), (2, 3, 4, 5))]
+ )
def test_cardinality(self, input_shape, expected_output_shape):
self._test_cardinality_implementation(
- input_shape=input_shape, expected_output_shape=expected_output_shape, params=self._default_param_set)
+ input_shape=input_shape, expected_output_shape=expected_output_shape, params=self._default_param_set
+ )
def test_random_p_1(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[0.1, 0.2, 0.3, 0.4],
- [0.5, 0.6, 0.7, 0.8],
- [0.9, 0.0, 0.1, 0.2]], device=self.device, dtype=self.dtype).repeat(1, 3, 1, 1)
+ input_tensor = torch.tensor(
+ [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 0.0, 0.1, 0.2]], device=self.device, dtype=self.dtype
+ ).repeat(1, 3, 1, 1)
expected_output = (
- input_tensor *
- torch.tensor(
- [
- 0.299,
- 0.587,
- 0.114],
- device=self.device,
- dtype=self.dtype).view(
- 1,
- 3,
- 1,
- 1)).sum(
- dim=1,
- keepdim=True).repeat(
- 1,
- 3,
- 1,
- 1)
+ input_tensor * torch.tensor([0.299, 0.587, 0.114], device=self.device, dtype=self.dtype).view(1, 3, 1, 1)
+ ).sum(dim=1, keepdim=True).repeat(1, 3, 1, 1)
parameters = {}
self._test_random_p_1_implementation(
- input_tensor=input_tensor,
- expected_output=expected_output,
- params=parameters)
+ input_tensor=input_tensor, expected_output=expected_output, params=parameters
+ )
def test_random_p_1_return_transform(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[0.1, 0.2, 0.3, 0.4],
- [0.5, 0.6, 0.7, 0.8],
- [0.9, 0.0, 0.1, 0.2]], device=self.device, dtype=self.dtype).repeat(1, 3, 1, 1)
+ input_tensor = torch.tensor(
+ [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 0.0, 0.1, 0.2]], device=self.device, dtype=self.dtype
+ ).repeat(1, 3, 1, 1)
expected_output = (
- input_tensor *
- torch.tensor(
- [
- 0.299,
- 0.587,
- 0.114],
- device=self.device,
- dtype=self.dtype).view(
- 1,
- 3,
- 1,
- 1)).sum(
- dim=1,
- keepdim=True).repeat(
- 1,
- 3,
- 1,
- 1)
+ input_tensor * torch.tensor([0.299, 0.587, 0.114], device=self.device, dtype=self.dtype).view(1, 3, 1, 1)
+ ).sum(dim=1, keepdim=True).repeat(1, 3, 1, 1)
expected_transformation = kornia.eye_like(3, input_tensor)
parameters = {}
@@ -779,33 +990,18 @@ class TestRandomGrayscaleAlternative(CommonTests):
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
def test_batch(self):
torch.manual_seed(42)
- input_tensor = torch.tensor([[0.1, 0.2, 0.3, 0.4],
- [0.5, 0.6, 0.7, 0.8],
- [0.9, 0.0, 0.1, 0.2]], device=self.device, dtype=self.dtype).repeat(2, 3, 1, 1)
+ input_tensor = torch.tensor(
+ [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], [0.9, 0.0, 0.1, 0.2]], device=self.device, dtype=self.dtype
+ ).repeat(2, 3, 1, 1)
expected_output = (
- input_tensor *
- torch.tensor(
- [
- 0.299,
- 0.587,
- 0.114],
- device=self.device,
- dtype=self.dtype).view(
- 1,
- 3,
- 1,
- 1)).sum(
- dim=1,
- keepdim=True).repeat(
- 1,
- 3,
- 1,
- 1)
+ input_tensor * torch.tensor([0.299, 0.587, 0.114], device=self.device, dtype=self.dtype).view(1, 3, 1, 1)
+ ).sum(dim=1, keepdim=True).repeat(1, 3, 1, 1)
expected_transformation = kornia.eye_like(3, input_tensor)
parameters = {}
@@ -813,7 +1009,8 @@ class TestRandomGrayscaleAlternative(CommonTests):
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters)
+ params=parameters
+ )
@pytest.mark.xfail(reason="No input validation is implemented yet when p=0.")
def test_exception(self):
@@ -842,23 +1039,21 @@ class TestRandomHorizontalFlip:
f2 = RandomHorizontalFlip(p=1.)
f3 = RandomHorizontalFlip(p=0.)
- input = torch.tensor([[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 1., 2.]], device=device, dtype=dtype) # 3 x 4
+ input = torch.tensor(
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ ) # 3 x 4
- expected = torch.tensor([[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [2., 1., 0., 0.]], device=device, dtype=dtype) # 3 x 4
+ expected = torch.tensor(
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [2., 1., 0., 0.]], device=device, dtype=dtype
+ ) # 3 x 4
expected = expected.to(device)
- expected_transform = torch.tensor([[-1., 0., 3.],
- [0., 1., 0.],
- [0., 0., 1.]], device=device, dtype=dtype) # 3 x 3
+ expected_transform = torch.tensor(
+ [[-1., 0., 3.], [0., 1., 0.], [0., 0., 1.]], device=device, dtype=dtype
+ ) # 3 x 3
- identity = torch.tensor([[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]], device=device, dtype=dtype) # 3 x 3
+ identity = torch.tensor([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], device=device, dtype=dtype) # 3 x 3
assert (f(input)[0] == expected).all()
assert (f(input)[1] == expected_transform).all()
@@ -876,21 +1071,19 @@ class TestRandomHorizontalFlip:
f = RandomHorizontalFlip(p=1.0, return_transform=True)
f1 = RandomHorizontalFlip(p=0.0, return_transform=True)
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [1., 1., 0.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ expected = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected_transform = torch.tensor([[[-1., 0., 2.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
+ expected_transform = torch.tensor(
+ [[[-1., 0., 2.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype
+ ) # 1 x 3 x 3
- identity = torch.tensor([[[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
+ identity = torch.tensor([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
input = input.repeat(5, 3, 1, 1) # 5 x 3 x 3 x 3
expected = expected.repeat(5, 3, 1, 1) # 5 x 3 x 3 x 3
@@ -922,39 +1115,45 @@ class TestRandomHorizontalFlip:
RandomHorizontalFlip(p=1.0),
)
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected_transform = torch.tensor([[[-1., 0., 2.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
+ expected_transform = torch.tensor(
+ [[[-1., 0., 2.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype
+ ) # 1 x 3 x 3
expected_transform_1 = expected_transform @ expected_transform
- assert(f(input)[0] == input).all()
- assert(f(input)[1] == expected_transform_1).all()
- assert(f1(input)[0] == input).all()
- assert(f1(input)[1] == expected_transform).all()
+ assert (f(input)[0] == input).all()
+ assert (f(input)[1] == expected_transform_1).all()
+ assert (f1(input)[0] == input).all()
+ assert (f1(input)[1] == expected_transform).all()
# TODO: Introduce Kornia.Sequential to do the inverse.
def test_random_hflip_coord_check(self, device, dtype):
f = RandomHorizontalFlip(p=1.0, return_transform=True)
- input = torch.tensor([[[[1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 4
-
- input_coordinates = torch.tensor([[
- [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], # x coord
- [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], # y coord
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
- ]], device=device, dtype=dtype) # 1 x 3 x 3
+ input = torch.tensor(
+ [[[[1., 2., 3., 4.], [5., 6., 7., 8.], [9., 10., 11., 12.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 4
- expected_output = torch.tensor([[[[4., 3., 2., 1.],
- [8., 7., 6., 5.],
- [12., 11., 10., 9.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 4
+ input_coordinates = torch.tensor(
+ [
+ [
+ [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], # x coord
+ [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], # y coord
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 3 x 3
+
+ expected_output = torch.tensor(
+ [[[[4., 3., 2., 1.], [8., 7., 6., 5.], [12., 11., 10., 9.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 4
output, transform = f(input)
result_coordinates = transform @ input_coordinates
@@ -966,40 +1165,39 @@ class TestRandomHorizontalFlip:
assert output.shape == expected_output.shape
assert (output == expected_output).all()
# Transformed indices must not be out of bound
- assert (torch.torch.logical_and(result_coordinates[0, 0, :] >= 0,
- result_coordinates[0, 0, :] < input.shape[-1])).all()
- assert (torch.torch.logical_and(result_coordinates[0, 1, :] >= 0,
- result_coordinates[0, 1, :] < input.shape[-2])).all()
+ assert (
+ torch.torch.logical_and(result_coordinates[0, 0, :] >= 0, result_coordinates[0, 0, :] < input.shape[-1])
+ ).all()
+ assert (
+ torch.torch.logical_and(result_coordinates[0, 1, :] >= 0, result_coordinates[0, 1, :] < input.shape[-2])
+ ).all()
# Values in the output tensor at the places of transformed indices must
# have the same value as the input tensor has at the corresponding
# positions
- assert (output[..., result_coordinates[0, 1, :], result_coordinates[0, 0, :]] ==
- input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]]).all()
+ assert (
+ output[..., result_coordinates[0, 1, :],
+ result_coordinates[0, 0, :]] == input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]]
+ ).all()
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
return kornia.apply_hflip(data)
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[0., 0., 0.],
- [0., 5., 5.],
- [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[[0., 0., 0.], [0., 5., 5.], [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -1030,21 +1228,19 @@ class TestRandomVerticalFlip:
f2 = RandomVerticalFlip(p=1.)
f3 = RandomVerticalFlip(p=0.)
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected = torch.tensor([[[[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ expected = torch.tensor(
+ [[[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected_transform = torch.tensor([[[1., 0., 0.],
- [0., -1., 2.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 3 x 3
+ expected_transform = torch.tensor(
+ [[[1., 0., 0.], [0., -1., 2.], [0., 0., 1.]]], device=device, dtype=dtype
+ ) # 3 x 3
- identity = torch.tensor([[[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 3 x 3
+ identity = torch.tensor([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype) # 3 x 3
assert_allclose(f(input)[0], expected, atol=1e-4, rtol=1e-4)
assert_allclose(f(input)[1], expected_transform, atol=1e-4, rtol=1e-4)
@@ -1063,21 +1259,19 @@ class TestRandomVerticalFlip:
f = RandomVerticalFlip(p=1.0, return_transform=True)
f1 = RandomVerticalFlip(p=0.0, return_transform=True)
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected = torch.tensor([[[[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ expected = torch.tensor(
+ [[[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected_transform = torch.tensor([[[1., 0., 0.],
- [0., -1., 2.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
+ expected_transform = torch.tensor(
+ [[[1., 0., 0.], [0., -1., 2.], [0., 0., 1.]]], device=device, dtype=dtype
+ ) # 1 x 3 x 3
- identity = torch.tensor([[[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
+ identity = torch.tensor([[[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
input = input.repeat(5, 3, 1, 1) # 5 x 3 x 3 x 3
expected = expected.repeat(5, 3, 1, 1) # 5 x 3 x 3 x 3
@@ -1109,13 +1303,13 @@ class TestRandomVerticalFlip:
RandomVerticalFlip(p=1.0),
)
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected_transform = torch.tensor([[[1., 0., 0.],
- [0., -1., 2.],
- [0., 0., 1.]]], device=device, dtype=dtype) # 1 x 3 x 3
+ expected_transform = torch.tensor(
+ [[[1., 0., 0.], [0., -1., 2.], [0., 0., 1.]]], device=device, dtype=dtype
+ ) # 1 x 3 x 3
expected_transform_1 = expected_transform @ expected_transform
@@ -1128,19 +1322,25 @@ class TestRandomVerticalFlip:
f = RandomVerticalFlip(p=1.0, return_transform=True)
- input = torch.tensor([[[[1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 4
-
- input_coordinates = torch.tensor([[
- [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], # x coord
- [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], # y coord
- [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
- ]], device=device, dtype=dtype) # 1 x 3 x 3
+ input = torch.tensor(
+ [[[[1., 2., 3., 4.], [5., 6., 7., 8.], [9., 10., 11., 12.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 4
- expected_output = torch.tensor([[[[9., 10., 11., 12.],
- [5., 6., 7., 8.],
- [1., 2., 3., 4.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 4
+ input_coordinates = torch.tensor(
+ [
+ [
+ [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3], # x coord
+ [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], # y coord
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 3 x 3
+
+ expected_output = torch.tensor(
+ [[[[9., 10., 11., 12.], [5., 6., 7., 8.], [1., 2., 3., 4.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 4
output, transform = f(input)
result_coordinates = transform @ input_coordinates
@@ -1152,39 +1352,38 @@ class TestRandomVerticalFlip:
assert output.shape == expected_output.shape
assert (output == expected_output).all()
# Transformed indices must not be out of bound
- assert (torch.torch.logical_and(result_coordinates[0, 0, :] >= 0,
- result_coordinates[0, 0, :] < input.shape[-1])).all()
- assert (torch.torch.logical_and(result_coordinates[0, 1, :] >= 0,
- result_coordinates[0, 1, :] < input.shape[-2])).all()
+ assert (
+ torch.torch.logical_and(result_coordinates[0, 0, :] >= 0, result_coordinates[0, 0, :] < input.shape[-1])
+ ).all()
+ assert (
+ torch.torch.logical_and(result_coordinates[0, 1, :] >= 0, result_coordinates[0, 1, :] < input.shape[-2])
+ ).all()
# Values in the output tensor at the places of transformed indices must
# have the same value as the input tensor has at the corresponding
# positions
- assert (output[..., result_coordinates[0, 1, :], result_coordinates[0, 0, :]] ==
- input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]]).all()
+ assert (
+ output[..., result_coordinates[0, 1, :],
+ result_coordinates[0, 0, :]] == input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]]
+ ).all()
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
return kornia.apply_vflip(data)
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -1244,33 +1443,30 @@ class TestColorJitter:
assert (res[0] == res[1]).all()
def _get_expected_brightness(self, device, dtype):
- return torch.tensor([
- [[[0.2529, 0.3529, 0.4529],
- [0.7529, 0.6529, 0.5529],
- [0.8529, 0.9529, 1.0000]],
- [[0.2529, 0.3529, 0.4529],
- [0.7529, 0.6529, 0.5529],
- [0.8529, 0.9529, 1.0000]],
- [[0.2529, 0.3529, 0.4529],
- [0.7529, 0.6529, 0.5529],
- [0.8529, 0.9529, 1.0000]]],
- [[[0.2660, 0.3660, 0.4660],
- [0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]],
- [[0.2660, 0.3660, 0.4660],
- [0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]],
- [[0.2660, 0.3660, 0.4660],
- [0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]]]], device=device, dtype=dtype)
+ return torch.tensor(
+ [
+ [
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]]
+ ],
+ [
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
def test_random_brightness(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(brightness=0.2)
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
expected = self._get_expected_brightness(device, dtype)
@@ -1281,9 +1477,9 @@ class TestColorJitter:
torch.manual_seed(42)
f = ColorJitter(brightness=(0.8, 1.2))
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
expected = self._get_expected_brightness(device, dtype)
@@ -1291,33 +1487,30 @@ class TestColorJitter:
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
def _get_expected_contrast(self, device, dtype):
- return torch.tensor([
- [[[0.0953, 0.1906, 0.2859],
- [0.5719, 0.4766, 0.3813],
- [0.6672, 0.7625, 0.9531]],
- [[0.0953, 0.1906, 0.2859],
- [0.5719, 0.4766, 0.3813],
- [0.6672, 0.7625, 0.9531]],
- [[0.0953, 0.1906, 0.2859],
- [0.5719, 0.4766, 0.3813],
- [0.6672, 0.7625, 0.9531]]],
- [[[0.1184, 0.2367, 0.3551],
- [0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]],
- [[0.1184, 0.2367, 0.3551],
- [0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]],
- [[0.1184, 0.2367, 0.3551],
- [0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]]]], device=device, dtype=dtype)
+ return torch.tensor(
+ [
+ [
+ [[0.0953, 0.1906, 0.2859], [0.5719, 0.4766, 0.3813], [0.6672, 0.7625, 0.9531]],
+ [[0.0953, 0.1906, 0.2859], [0.5719, 0.4766, 0.3813], [0.6672, 0.7625, 0.9531]],
+ [[0.0953, 0.1906, 0.2859], [0.5719, 0.4766, 0.3813], [0.6672, 0.7625, 0.9531]]
+ ],
+ [
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]],
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]],
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
def test_random_contrast(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(contrast=0.2)
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
expected = self._get_expected_contrast(device, dtype)
@@ -1328,9 +1521,9 @@ class TestColorJitter:
torch.manual_seed(42)
f = ColorJitter(contrast=[0.8, 1.2])
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
expected = self._get_expected_contrast(device, dtype)
@@ -1338,41 +1531,38 @@ class TestColorJitter:
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-5)
def _get_expected_saturation(self, device, dtype):
- return torch.tensor([
- [[[0.1876, 0.2584, 0.3389],
- [0.6292, 0.5000, 0.4000],
- [0.7097, 0.8000, 1.0000]],
- [[1.0000, 0.5292, 0.6097],
- [0.6292, 0.3195, 0.2195],
- [0.8000, 0.1682, 0.2779]],
- [[0.6389, 0.8000, 0.7000],
- [0.9000, 0.3195, 0.2195],
- [0.8000, 0.4389, 0.5487]]],
- [[[0.0000, 0.1295, 0.2530],
- [0.5648, 0.5000, 0.4000],
- [0.6883, 0.8000, 1.0000]],
- [[1.0000, 0.4648, 0.5883],
- [0.5648, 0.2765, 0.1765],
- [0.8000, 0.0178, 0.1060]],
- [[0.5556, 0.8000, 0.7000],
- [0.9000, 0.2765, 0.1765],
- [0.8000, 0.3530, 0.4413]]]], device=device, dtype=dtype)
+ return torch.tensor(
+ [
+ [
+ [[0.1876, 0.2584, 0.3389], [0.6292, 0.5000, 0.4000], [0.7097, 0.8000, 1.0000]],
+ [[1.0000, 0.5292, 0.6097], [0.6292, 0.3195, 0.2195], [0.8000, 0.1682, 0.2779]],
+ [[0.6389, 0.8000, 0.7000], [0.9000, 0.3195, 0.2195], [0.8000, 0.4389, 0.5487]]
+ ],
+ [
+ [[0.0000, 0.1295, 0.2530], [0.5648, 0.5000, 0.4000], [0.6883, 0.8000, 1.0000]],
+ [[1.0000, 0.4648, 0.5883], [0.5648, 0.2765, 0.1765], [0.8000, 0.0178, 0.1060]],
+ [[0.5556, 0.8000, 0.7000], [0.9000, 0.2765, 0.1765], [0.8000, 0.3530, 0.4413]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
def test_random_saturation(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(saturation=0.2)
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = self._get_expected_saturation(device, dtype)
@@ -1382,17 +1572,17 @@ class TestColorJitter:
torch.manual_seed(42)
f = ColorJitter(saturation=torch.tensor(0.2))
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = self._get_expected_saturation(device, dtype)
@@ -1403,17 +1593,17 @@ class TestColorJitter:
torch.manual_seed(42)
f = ColorJitter(saturation=(0.8, 1.2))
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = self._get_expected_saturation(device, dtype)
@@ -1421,41 +1611,38 @@ class TestColorJitter:
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
def _get_expected_hue(self, device, dtype):
- return torch.tensor([
- [[[0.1000, 0.2000, 0.3000],
- [0.6000, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.5251, 0.6167],
- [0.6126, 0.3000, 0.2000],
- [0.8000, 0.1000, 0.2000]],
- [[0.5623, 0.8000, 0.7000],
- [0.9000, 0.3084, 0.2084],
- [0.7958, 0.4293, 0.5335]]],
- [[[0.1000, 0.2000, 0.3000],
- [0.6116, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.4769, 0.5846],
- [0.6000, 0.3077, 0.2077],
- [0.7961, 0.1000, 0.2000]],
- [[0.6347, 0.8000, 0.7000],
- [0.9000, 0.3000, 0.2000],
- [0.8000, 0.3730, 0.4692]]]], device=device, dtype=dtype)
+ return torch.tensor(
+ [
+ [
+ [[0.1000, 0.2000, 0.3000], [0.6000, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.5251, 0.6167], [0.6126, 0.3000, 0.2000], [0.8000, 0.1000, 0.2000]],
+ [[0.5623, 0.8000, 0.7000], [0.9000, 0.3084, 0.2084], [0.7958, 0.4293, 0.5335]]
+ ],
+ [
+ [[0.1000, 0.2000, 0.3000], [0.6116, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.4769, 0.5846], [0.6000, 0.3077, 0.2077], [0.7961, 0.1000, 0.2000]],
+ [[0.6347, 0.8000, 0.7000], [0.9000, 0.3000, 0.2000], [0.8000, 0.3730, 0.4692]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
def test_random_hue(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(hue=0.1 / pi.item())
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = self._get_expected_hue(device, dtype)
@@ -1466,17 +1653,17 @@ class TestColorJitter:
torch.manual_seed(42)
f = ColorJitter(hue=[-0.1 / pi, 0.1 / pi])
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = self._get_expected_hue(device, dtype)
@@ -1487,17 +1674,17 @@ class TestColorJitter:
torch.manual_seed(42)
f = ColorJitter(hue=[-0.1 / pi.item(), 0.1 / pi.item()])
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = self._get_expected_hue(device, dtype)
@@ -1542,11 +1729,11 @@ class TestColorJitter:
class TestRectangleRandomErasing:
+
@pytest.mark.parametrize("erase_scale_range", [(.001, .001), (1., 1.)])
@pytest.mark.parametrize("aspect_ratio_range", [(.1, .1), (10., 10.)])
@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
- def test_random_rectangle_erasing_shape(
- self, batch_shape, erase_scale_range, aspect_ratio_range):
+ def test_random_rectangle_erasing_shape(self, batch_shape, erase_scale_range, aspect_ratio_range):
input = torch.rand(batch_shape)
rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=1.)
assert rand_rec(input).shape == batch_shape
@@ -1554,8 +1741,7 @@ class TestRectangleRandomErasing:
@pytest.mark.parametrize("erase_scale_range", [(.001, .001), (1., 1.)])
@pytest.mark.parametrize("aspect_ratio_range", [(.1, .1), (10., 10.)])
@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
- def test_no_rectangle_erasing_shape(
- self, batch_shape, erase_scale_range, aspect_ratio_range):
+ def test_no_rectangle_erasing_shape(self, batch_shape, erase_scale_range, aspect_ratio_range):
input = torch.rand(batch_shape)
rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=0.)
assert rand_rec(input).equal(input)
@@ -1589,15 +1775,14 @@ class TestRectangleRandomErasing:
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(img):
return kornia.augmentation.random_rectangle_erase(img, (.2, .4), (.3, .5))
batch_size, channels, height, width = 2, 3, 64, 64
img = torch.ones(batch_size, channels, height, width)
- expected = RandomErasing(
- 1.0, (.2, .4), (.3, .5)
- )(img)
+ expected = RandomErasing(1.0, (.2, .4), (.3, .5))(img)
actual = op_script(img)
assert_allclose(actual, expected, atol=1e-4, rtol=1e-4)
@@ -1629,65 +1814,100 @@ class TestRandomGrayscale:
assert (res[0] == res[1]).all()
def test_opencv_true(self, device, dtype):
- data = torch.tensor([[[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
- expected = torch.tensor([[[[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]]]],
- device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
img_gray = kornia.augmentation.RandomGrayscale(p=1.)(data)
assert_allclose(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_opencv_false(self, device, dtype):
- data = torch.tensor([[[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
expected = data
@@ -1695,66 +1915,96 @@ class TestRandomGrayscale:
assert_allclose(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_opencv_true_batch(self, device, dtype):
- data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
data = data.unsqueeze(0).repeat(4, 1, 1, 1)
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
- expected = torch.tensor([[[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
expected = expected.unsqueeze(0).repeat(4, 1, 1, 1)
img_gray = kornia.augmentation.RandomGrayscale(p=1.)(data)
assert_allclose(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_opencv_false_batch(self, device, dtype):
- data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
data = data.unsqueeze(0).repeat(4, 1, 1, 1)
expected = data
@@ -1780,8 +2030,8 @@ class TestRandomGrayscale:
def test_gradcheck(self, device, dtype):
input = torch.rand((3, 5, 5), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.augmentation.RandomGrayscale(p=1.), (input,), raise_exception=True)
- assert gradcheck(kornia.augmentation.RandomGrayscale(p=0.), (input,), raise_exception=True)
+ assert gradcheck(kornia.augmentation.RandomGrayscale(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(kornia.augmentation.RandomGrayscale(p=0.), (input, ), raise_exception=True)
class TestCenterCrop:
@@ -1830,7 +2080,7 @@ class TestCenterCrop:
def test_gradcheck(self, device, dtype):
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.augmentation.CenterCrop(3), (input,), raise_exception=True)
+ assert gradcheck(kornia.augmentation.CenterCrop(3), (input, ), raise_exception=True)
class TestRandomRotation:
@@ -1853,24 +2103,41 @@ class TestRandomRotation:
f = RandomRotation(degrees=45.0, return_transform=True, p=1.)
f1 = RandomRotation(degrees=45.0, p=1.)
- input = torch.tensor([[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]], device=device, dtype=dtype) # 4 x 4
+ input = torch.tensor(
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ ) # 4 x 4
- expected = torch.tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
- [0.0000, 0.0029, 0.0000, 0.0176],
- [0.0029, 1.0000, 1.9883, 0.0000],
- [0.0000, 0.0088, 1.0117, 1.9649]]]], device=device, dtype=dtype) # 1 x 4 x 4
-
- expected_transform = torch.tensor([[[1.0000, -0.0059, 0.0088],
- [0.0059, 1.0000, -0.0088],
- [0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 1 x 3 x 3
-
- expected_2 = torch.tensor([[[[0.1322, 0.0000, 0.7570, 0.2644],
- [0.3785, 0.0000, 0.4166, 0.0000],
- [0.0000, 0.6309, 1.5910, 1.2371],
- [0.0000, 0.1444, 0.3177, 0.6499]]]], device=device, dtype=dtype) # 1 x 4 x 4
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.9824, 0.0088, 0.0000, 1.9649], [0.0000, 0.0029, 0.0000, 0.0176],
+ [0.0029, 1.0000, 1.9883, 0.0000], [0.0000, 0.0088, 1.0117, 1.9649]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 4 x 4
+
+ expected_transform = torch.tensor(
+ [[[1.0000, -0.0059, 0.0088], [0.0059, 1.0000, -0.0088], [0.0000, 0.0000, 1.0000]]],
+ device=device,
+ dtype=dtype
+ ) # 1 x 3 x 3
+
+ expected_2 = torch.tensor(
+ [
+ [
+ [
+ [0.1322, 0.0000, 0.7570, 0.2644], [0.3785, 0.0000, 0.4166, 0.0000],
+ [0.0000, 0.6309, 1.5910, 1.2371], [0.0000, 0.1444, 0.3177, 0.6499]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 4 x 4
out, mat = f(input)
assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
@@ -1883,26 +2150,37 @@ class TestRandomRotation:
f = RandomRotation(degrees=45.0, return_transform=True, p=1.)
- input = torch.tensor([[[[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]]]], device=device, dtype=dtype) # 1 x 1 x 4 x 4
-
- expected = torch.tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
- [0.0000, 0.0029, 0.0000, 0.0176],
- [0.0029, 1.0000, 1.9883, 0.0000],
- [0.0000, 0.0088, 1.0117, 1.9649]]],
- [[[0.1322, 0.0000, 0.7570, 0.2644],
- [0.3785, 0.0000, 0.4166, 0.0000],
- [0.0000, 0.6309, 1.5910, 1.2371],
- [0.0000, 0.1444, 0.3177, 0.6499]]]], device=device, dtype=dtype) # 2 x 1 x 4 x 4
-
- expected_transform = torch.tensor([[[1.0000, -0.0059, 0.0088],
- [0.0059, 1.0000, -0.0088],
- [0.0000, 0.0000, 1.0000]],
- [[0.9125, 0.4090, -0.4823],
- [-0.4090, 0.9125, 0.7446],
- [0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 2 x 3 x 3
+ input = torch.tensor(
+ [[[[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 4 x 4
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.9824, 0.0088, 0.0000, 1.9649], [0.0000, 0.0029, 0.0000, 0.0176],
+ [0.0029, 1.0000, 1.9883, 0.0000], [0.0000, 0.0088, 1.0117, 1.9649]
+ ]
+ ],
+ [
+ [
+ [0.1322, 0.0000, 0.7570, 0.2644], [0.3785, 0.0000, 0.4166, 0.0000],
+ [0.0000, 0.6309, 1.5910, 1.2371], [0.0000, 0.1444, 0.3177, 0.6499]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2 x 1 x 4 x 4
+
+ expected_transform = torch.tensor(
+ [
+ [[1.0000, -0.0059, 0.0088], [0.0059, 1.0000, -0.0088], [0.0000, 0.0000, 1.0000]],
+ [[0.9125, 0.4090, -0.4823], [-0.4090, 0.9125, 0.7446], [0.0000, 0.0000, 1.0000]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 5 x 3 x 3 x 3
@@ -1929,23 +2207,34 @@ class TestRandomRotation:
RandomRotation(10.4, p=1.),
)
- input = torch.tensor([[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]], device=device, dtype=dtype) # 4 x 4
-
- expected = torch.tensor([[[[0.1314, 0.1050, 0.6649, 0.2628],
- [0.3234, 0.0202, 0.4256, 0.1671],
- [0.0525, 0.5976, 1.5199, 1.1306],
- [0.0000, 0.1453, 0.3224, 0.5796]]]], device=device, dtype=dtype) # 1 x 4 x 4
-
- expected_transform = torch.tensor([[[0.8864, 0.4629, -0.5240],
- [-0.4629, 0.8864, 0.8647],
- [0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 1 x 3 x 3
+ input = torch.tensor(
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ ) # 4 x 4
- expected_transform_2 = torch.tensor([[[0.8381, -0.5455, 1.0610],
- [0.5455, 0.8381, -0.5754],
- [0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 1 x 3 x 3
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.1314, 0.1050, 0.6649, 0.2628], [0.3234, 0.0202, 0.4256, 0.1671],
+ [0.0525, 0.5976, 1.5199, 1.1306], [0.0000, 0.1453, 0.3224, 0.5796]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 4 x 4
+
+ expected_transform = torch.tensor(
+ [[[0.8864, 0.4629, -0.5240], [-0.4629, 0.8864, 0.8647], [0.0000, 0.0000, 1.0000]]],
+ device=device,
+ dtype=dtype
+ ) # 1 x 3 x 3
+
+ expected_transform_2 = torch.tensor(
+ [[[0.8381, -0.5455, 1.0610], [0.5455, 0.8381, -0.5754], [0.0000, 0.0000, 1.0000]]],
+ device=device,
+ dtype=dtype
+ ) # 1 x 3 x 3
out, mat = f(input)
_, mat_2 = f1(input)
@@ -1960,28 +2249,24 @@ class TestRandomRotation:
@torch.jit.script
def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
- flags = dict(
- interpolation=torch.tensor(1),
- align_corners=torch.tensor(True)
- )
+ flags = dict(interpolation=torch.tensor(1), align_corners=torch.tensor(True))
return kornia.apply_rotation(data, params={"degrees": torch.tensor(45.0)}, flags=flags)
- input = torch.tensor([[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]], device=device, dtype=dtype) # 4 x 4
+ input = torch.tensor(
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ ) # 4 x 4
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
- expected = torch.tensor([[[0.0000, 0.2584, 0.0000],
- [2.9552, 5.0000, 0.2584],
- [1.6841, 0.4373, 0.0000]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[0.0000, 0.2584, 0.0000], [2.9552, 5.0000, 0.2584], [1.6841, 0.4373, 0.0000]]],
+ device=device,
+ dtype=dtype
+ )
actual = op_trace(input)
@@ -2008,15 +2293,8 @@ class TestRandomCrop:
def test_no_padding(self, device, dtype):
torch.manual_seed(0)
- inp = torch.tensor([[[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]]], device=device, dtype=dtype)
- expected = torch.tensor([[[
- [3., 4., 5.],
- [6., 7., 8.]
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor([[[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[3., 4., 5.], [6., 7., 8.]]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.)
out = rc(inp)
@@ -2026,9 +2304,7 @@ class TestRandomCrop:
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(out2, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(0)
- inversed = torch.tensor([[[[0., 0., 0.],
- [3., 4., 5.],
- [6., 7., 8.]]]], device=device, dtype=dtype)
+ inversed = torch.tensor([[[[0., 0., 0.], [3., 4., 5.], [6., 7., 8.]]]], device=device, dtype=dtype)
aug = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1., cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -2037,28 +2313,21 @@ class TestRandomCrop:
def test_no_padding_batch(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
- expected = torch.tensor([
- [[[0., 1., 2.],
- [3., 4., 5.]]],
- [[[3., 4., 5.],
- [6., 7., 8.]]]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device,
+ dtype=dtype).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor(
+ [[[[0., 1., 2.], [3., 4., 5.]]], [[[3., 4., 5.], [6., 7., 8.]]]], device=device, dtype=dtype
+ )
rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(42)
- inversed = torch.tensor([
- [[[0., 1., 2.],
- [3., 4., 5.],
- [0., 0., 0.]]],
- [[[0., 0., 0.],
- [3., 4., 5.],
- [6., 7., 8.]]]], device=device, dtype=dtype)
+ inversed = torch.tensor(
+ [[[[0., 1., 2.], [3., 4., 5.], [0., 0., 0.]]], [[[0., 0., 0.], [3., 4., 5.], [6., 7., 8.]]]],
+ device=device,
+ dtype=dtype
+ )
aug = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1., cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -2072,15 +2341,8 @@ class TestRandomCrop:
def test_padding(self, device, dtype):
torch.manual_seed(42)
- inp = torch.tensor([[[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]]], device=device, dtype=dtype)
- expected = torch.tensor([[[
- [7., 8., 7.],
- [4., 5., 4.]
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor([[[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[7., 8., 7.], [4., 5., 4.]]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), padding=1, padding_mode='reflect', align_corners=True, p=1.)
out = rc(inp)
@@ -2090,13 +2352,10 @@ class TestRandomCrop:
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(out2, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(42)
- inversed = torch.tensor([[[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 7., 8.]
- ]]], device=device, dtype=dtype)
+ inversed = torch.tensor([[[[0., 0., 0.], [0., 0., 0.], [0., 7., 8.]]]], device=device, dtype=dtype)
aug = RandomCrop(
- size=(2, 3), padding=1, padding_mode='reflect', align_corners=True, p=1., cropping_mode="resample")
+ size=(2, 3), padding=1, padding_mode='reflect', align_corners=True, p=1., cropping_mode="resample"
+ )
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(aug.inverse(out), inversed, atol=1e-4, rtol=1e-4)
@@ -2104,35 +2363,23 @@ class TestRandomCrop:
def test_padding_batch_1(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
- expected = torch.tensor([[[
- [1., 2., 0.],
- [4., 5., 0.]
- ]], [[
- [7., 8., 0.],
- [0., 0., 0.]
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device,
+ dtype=dtype).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor(
+ [[[[1., 2., 0.], [4., 5., 0.]]], [[[7., 8., 0.], [0., 0., 0.]]]], device=device, dtype=dtype
+ )
rc = RandomCrop(size=(2, 3), padding=1, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(42)
- inversed = torch.tensor([[[
- [0., 1., 2.],
- [0., 4., 5.],
- [0., 0., 0.]
- ]], [[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 7., 8.]
- ]]], device=device, dtype=dtype)
- aug = RandomCrop(
- size=(2, 3), padding=1, align_corners=True, p=1., cropping_mode="resample")
+ inversed = torch.tensor(
+ [[[[0., 1., 2.], [0., 4., 5.], [0., 0., 0.]]], [[[0., 0., 0.], [0., 0., 0.], [0., 7., 8.]]]],
+ device=device,
+ dtype=dtype
+ )
+ aug = RandomCrop(size=(2, 3), padding=1, align_corners=True, p=1., cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(aug.inverse(out), inversed, atol=1e-4, rtol=1e-4)
@@ -2140,34 +2387,25 @@ class TestRandomCrop:
def test_padding_batch_2(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
- expected = torch.tensor([[[
- [1., 2., 10.],
- [4., 5., 10.]
- ]], [[
- [4., 5., 10.],
- [7., 8., 10.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device,
+ dtype=dtype).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor(
+ [[[[1., 2., 10.], [4., 5., 10.]]], [[
+ [4., 5., 10.],
+ [7., 8., 10.],
+ ]]], device=device, dtype=dtype
+ )
rc = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(42)
- inversed = torch.tensor([[[
- [0., 1., 2.],
- [0., 4., 5.],
- [0., 0., 0.]
- ]], [[
- [0., 0., 0.],
- [0., 4., 5.],
- [0., 7., 8.]
- ]]], device=device, dtype=dtype)
- aug = RandomCrop(
- size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1., cropping_mode="resample")
+ inversed = torch.tensor(
+ [[[[0., 1., 2.], [0., 4., 5.], [0., 0., 0.]]], [[[0., 0., 0.], [0., 4., 5.], [0., 7., 8.]]]],
+ device=device,
+ dtype=dtype
+ )
+ aug = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1., cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(aug.inverse(out), inversed, atol=1e-4, rtol=1e-4)
@@ -2175,50 +2413,31 @@ class TestRandomCrop:
def test_padding_batch_3(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
- expected = torch.tensor([[[
- [8., 8., 8.],
- [8., 0., 1.]
- ]], [[
- [8., 8., 8.],
- [1., 2., 8.]
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device,
+ dtype=dtype).repeat(batch_size, 1, 1, 1)
+ expected = torch.tensor(
+ [[[[8., 8., 8.], [8., 0., 1.]]], [[[8., 8., 8.], [1., 2., 8.]]]], device=device, dtype=dtype
+ )
rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(0)
- inversed = torch.tensor([[[
- [0., 1., 0.],
- [0., 0., 0.],
- [0., 0., 0.]
- ]], [[
- [0., 1., 2.],
- [0., 0., 0.],
- [0., 0., 0.]
- ]]], device=device, dtype=dtype)
- aug = RandomCrop(
- size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1., cropping_mode="resample")
+ inversed = torch.tensor(
+ [[[[0., 1., 0.], [0., 0., 0.], [0., 0., 0.]]], [[[0., 1., 2.], [0., 0., 0.], [0., 0., 0.]]]],
+ device=device,
+ dtype=dtype
+ )
+ aug = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1., cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(aug.inverse(out), inversed, atol=1e-4, rtol=1e-4)
def test_padding_no_forward(self, device, dtype):
torch.manual_seed(0)
- inp = torch.tensor([[[
- [3., 4., 5.],
- [6., 7., 8.]
- ]]], device=device, dtype=dtype)
- trans = torch.tensor([[
- [1., 2., 3.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor([[[[3., 4., 5.], [6., 7., 8.]]]], device=device, dtype=dtype)
+ trans = torch.tensor([[[1., 2., 3.], [3., 4., 5.], [6., 7., 8.]]], device=device, dtype=dtype)
# Not return transform
rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=9, align_corners=True, p=0.)
@@ -2244,34 +2463,24 @@ class TestRandomCrop:
inp = torch.tensor([[
[0., 1., 2.],
]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
- expected = torch.tensor([
- [[[9., 9., 9.],
- [0., 1., 2.]]],
- [[[9., 9., 9.],
- [0., 1., 2.]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[[9., 9., 9.], [0., 1., 2.]]], [[[9., 9., 9.], [0., 1., 2.]]]], device=device, dtype=dtype
+ )
rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(0)
- inversed = torch.tensor([
- [[[0., 1., 2.]]],
- [[[0., 1., 2.]]]
- ], device=device, dtype=dtype)
- aug = RandomCrop(
- size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1., cropping_mode="resample")
+ inversed = torch.tensor([[[[0., 1., 2.]]], [[[0., 1., 2.]]]], device=device, dtype=dtype)
+ aug = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1., cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(aug.inverse(out), inversed, atol=1e-4, rtol=1e-4)
def test_crop_modes(self, device, dtype):
torch.manual_seed(0)
- img = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype)
+ img = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device, dtype=dtype)
op1 = RandomCrop(size=(2, 2), cropping_mode='resample')
out = op1(img)
@@ -2305,7 +2514,7 @@ class TestRandomCrop:
# 1. Trace op
img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
- op_trace = torch.jit.trace(op_script, (img,))
+ op_trace = torch.jit.trace(op_script, (img, ))
# 2. Generate new input
img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
@@ -2328,43 +2537,32 @@ class TestRandomResizedCrop:
def test_no_resize(self, device, dtype):
torch.manual_seed(0)
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device, dtype=dtype)
- expected = torch.tensor(
- [[[[0.0000, 1.0000, 2.0000],
- [6.0000, 7.0000, 8.0000]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[0.0000, 1.0000, 2.0000], [6.0000, 7.0000, 8.0000]]]], device=device, dtype=dtype)
- rrc = RandomResizedCrop(
- size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0))
+ rrc = RandomResizedCrop(size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0))
# It will crop a size of (2, 3) from the aspect ratio implementation of torch
out = rrc(inp)
assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
torch.manual_seed(0)
- aug = RandomResizedCrop(
- size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0), cropping_mode="resample")
+ aug = RandomResizedCrop(size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0), cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
assert_allclose(aug.inverse(out), inp[None], atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
- f = RandomResizedCrop(
- size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0), same_on_batch=True)
- input = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ f = RandomResizedCrop(size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0), same_on_batch=True)
+ input = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device,
+ dtype=dtype).repeat(2, 1, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
torch.manual_seed(0)
aug = RandomResizedCrop(
- size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0), same_on_batch=True, cropping_mode="resample")
+ size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0), same_on_batch=True, cropping_mode="resample"
+ )
out = aug(input)
inversed = aug.inverse(out)
assert (inversed[0] == inversed[1]).all()
@@ -2372,26 +2570,20 @@ class TestRandomResizedCrop:
def test_crop_scale_ratio(self, device, dtype):
# This is included in doctest
torch.manual_seed(0)
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device, dtype=dtype)
expected = torch.tensor(
- [[[[1.0000, 1.5000, 2.0000],
- [4.0000, 4.5000, 5.0000],
- [7.0000, 7.5000, 8.0000]]]], device=device, dtype=dtype)
+ [[[[1.0000, 1.5000, 2.0000], [4.0000, 4.5000, 5.0000], [7.0000, 7.5000, 8.0000]]]],
+ device=device,
+ dtype=dtype
+ )
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (3, 3) from the aspect ratio implementation of torch
out = rrc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
torch.manual_seed(0)
- inversed = torch.tensor([
- [[[0., 1., 2.],
- [0., 4., 5.],
- [0., 7., 8.]]]], device=device, dtype=dtype)
+ inversed = torch.tensor([[[[0., 1., 2.], [0., 4., 5.], [0., 7., 8.]]]], device=device, dtype=dtype)
aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -2400,16 +2592,20 @@ class TestRandomResizedCrop:
def test_crop_size_greater_than_input(self, device, dtype):
# This is included in doctest
torch.manual_seed(0)
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device, dtype=dtype)
- exp = torch.tensor([[[[1.0000, 1.3333, 1.6667, 2.0000],
- [3.0000, 3.3333, 3.6667, 4.0000],
- [5.0000, 5.3333, 5.6667, 6.0000],
- [7.0000, 7.3333, 7.6667, 8.0000]]]], device=device, dtype=dtype)
+ exp = torch.tensor(
+ [
+ [
+ [
+ [1.0000, 1.3333, 1.6667, 2.0000], [3.0000, 3.3333, 3.6667, 4.0000],
+ [5.0000, 5.3333, 5.6667, 6.0000], [7.0000, 7.3333, 7.6667, 8.0000]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
rrc = RandomResizedCrop(size=(4, 4), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (3, 3) from the aspect ratio implementation of torch
@@ -2418,10 +2614,7 @@ class TestRandomResizedCrop:
assert_allclose(out, exp, atol=1e-4, rtol=1e-4)
torch.manual_seed(0)
- inversed = torch.tensor([
- [[[0., 1., 2.],
- [0., 4., 5.],
- [0., 7., 8.]]]], device=device, dtype=dtype)
+ inversed = torch.tensor([[[[0., 1., 2.], [0., 4., 5.], [0., 7., 8.]]]], device=device, dtype=dtype)
aug = RandomResizedCrop(size=(4, 4), scale=(3., 3.), ratio=(2., 2.), cropping_mode="resample")
out = aug(inp)
assert_allclose(out, exp, atol=1e-4, rtol=1e-4)
@@ -2430,32 +2623,28 @@ class TestRandomResizedCrop:
def test_crop_scale_ratio_batch(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
- inp = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
+ inp = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device,
+ dtype=dtype).repeat(batch_size, 1, 1, 1)
- expected = torch. tensor([
- [[[1.0000, 1.5000, 2.0000],
- [4.0000, 4.5000, 5.0000],
- [7.0000, 7.5000, 8.0000]]],
- [[[0.0000, 0.5000, 1.0000],
- [3.0000, 3.5000, 4.0000],
- [6.0000, 6.5000, 7.0000]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [[[1.0000, 1.5000, 2.0000], [4.0000, 4.5000, 5.0000], [7.0000, 7.5000, 8.0000]]],
+ [[[0.0000, 0.5000, 1.0000], [3.0000, 3.5000, 4.0000], [6.0000, 6.5000, 7.0000]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
torch.manual_seed(0)
- inversed = torch.tensor([
- [[[0., 1., 2.],
- [0., 4., 5.],
- [0., 7., 8.]]],
- [[[0., 1., 0.],
- [3., 4., 0.],
- [6., 7., 0.]]]], device=device, dtype=dtype)
+ inversed = torch.tensor(
+ [[[[0., 1., 2.], [0., 4., 5.], [0., 7., 8.]]], [[[0., 1., 0.], [3., 4., 0.], [6., 7., 0.]]]],
+ device=device,
+ dtype=dtype
+ )
aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), cropping_mode="resample")
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -2463,11 +2652,7 @@ class TestRandomResizedCrop:
def test_crop_modes(self, device, dtype):
torch.manual_seed(0)
- img = torch.tensor([[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]], device=device, dtype=dtype)
+ img = torch.tensor([[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]], device=device, dtype=dtype)
op1 = RandomResizedCrop(size=(4, 4), cropping_mode='resample')
out = op1(img)
@@ -2480,8 +2665,7 @@ class TestRandomResizedCrop:
torch.manual_seed(0) # for random reproductibility
inp = torch.rand((1, 3, 3), device=device, dtype=dtype) # 3 x 3
inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(RandomResizedCrop(
- size=(3, 3), scale=(1., 1.), ratio=(1., 1.)), (inp, ), raise_exception=True)
+ assert gradcheck(RandomResizedCrop(size=(3, 3), scale=(1., 1.), ratio=(1., 1.)), (inp, ), raise_exception=True)
class TestRandomEqualize:
@@ -2503,13 +2687,13 @@ class TestRandomEqualize:
inputs = self.build_input(channels, height, width, bs, 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
- ])
- expected = self.build_input(channels, height, width, bs=1, row=row_expected,
- 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
+ ]
+ )
+ expected = self.build_input(channels, height, width, bs=1, row=row_expected, device=device, dtype=dtype)
identity = kornia.eye_like(3, expected) # 3 x 3
assert_allclose(f(inputs)[0], expected, rtol=1e-4, atol=1e-4)
@@ -2529,13 +2713,13 @@ class TestRandomEqualize:
inputs = self.build_input(channels, height, width, bs, 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
- ])
- expected = self.build_input(channels, height, width, bs, row=row_expected,
- 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
+ ]
+ )
+ expected = self.build_input(channels, height, width, bs, row=row_expected, device=device, dtype=dtype)
identity = kornia.eye_like(3, expected) # 2 x 3 x 3
@@ -2559,7 +2743,7 @@ class TestRandomEqualize:
input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomEqualize(p=0.5), (input,), raise_exception=True)
+ assert gradcheck(RandomEqualize(p=0.5), (input, ), raise_exception=True)
@staticmethod
def build_input(channels, height, width, bs=1, row=None, device='cpu', dtype=torch.float32):
@@ -2597,14 +2781,9 @@ class TestRandomChannelShuffle:
torch.manual_seed(0)
img = torch.arange(1 * 3 * 2 * 2, device=device, dtype=dtype).view(1, 3, 2, 2)
- out_expected = torch.tensor([[
- [[8., 9.],
- [10., 11.]],
- [[0., 1.],
- [2., 3.]],
- [[4., 5.],
- [6., 7.]]]
- ], device=device, dtype=dtype)
+ out_expected = torch.tensor(
+ [[[[8., 9.], [10., 11.]], [[0., 1.], [2., 3.]], [[4., 5.], [6., 7.]]]], device=device, dtype=dtype
+ )
aug = RandomChannelShuffle(p=1.)
out = aug(img)
@@ -2626,8 +2805,10 @@ class TestNormalize:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self, device, dtype):
f = Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]))
- repr = ("Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
- "same_on_batch=False, return_transform=False)")
+ repr = (
+ "Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
+ "same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
def test_random_normalize(self, device, dtype):
@@ -2675,7 +2856,8 @@ class TestNormalize:
input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(
- Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1.), (input,), raise_exception=True)
+ Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1.), (input, ), raise_exception=True
+ )
class TestDenormalize:
@@ -2684,8 +2866,10 @@ class TestDenormalize:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self, device, dtype):
f = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]))
- repr = ("Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
- "same_on_batch=False, return_transform=False)")
+ repr = (
+ "Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
+ "same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
def test_random_denormalize(self, device, dtype):
@@ -2733,7 +2917,8 @@ class TestDenormalize:
input = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(
- Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1.), (input,), raise_exception=True)
+ Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1.), (input, ), raise_exception=True
+ )
class TestRandomFisheye:
@@ -2757,7 +2942,7 @@ class TestRandomFisheye:
center_x = utils.tensor_to_gradcheck_var(center_x) # to var
center_y = utils.tensor_to_gradcheck_var(center_y) # to var
gamma = utils.tensor_to_gradcheck_var(gamma) # to var
- assert gradcheck(RandomFisheye(center_x, center_y, gamma), (img,), raise_exception=True)
+ assert gradcheck(RandomFisheye(center_x, center_y, gamma), (img, ), raise_exception=True)
class TestRandomElasticTransform:
diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.py
index 4868a258b..696d15b94 100644
--- a/test/augmentation/test_augmentation_3d.py
+++ b/test/augmentation/test_augmentation_3d.py
@@ -40,35 +40,31 @@ class TestRandomHorizontalFlip3D:
f2 = RandomHorizontalFlip3D(p=1.)
f3 = RandomHorizontalFlip3D(p=0.)
- input = torch.tensor([[[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 1., 2.]],
- [[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 1., 2.]]]) # 2 x 3 x 4
+ input = torch.tensor(
+ [
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]],
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]]
+ ]
+ ) # 2 x 3 x 4
input = input.to(device)
- expected = torch.tensor([[[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [2., 1., 0., 0.]],
- [[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [2., 1., 0., 0.]]]) # 2 x 3 x 4
+ expected = torch.tensor(
+ [
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [2., 1., 0., 0.]],
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [2., 1., 0., 0.]]
+ ]
+ ) # 2 x 3 x 4
expected = expected.to(device)
- expected_transform = torch.tensor([[-1., 0., 0., 3.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]) # 4 x 4
+ expected_transform = torch.tensor(
+ [[-1., 0., 0., 3.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]
+ ) # 4 x 4
expected_transform = expected_transform.to(device)
- identity = torch.tensor([[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]) # 4 x 4
+ identity = torch.tensor([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) # 4 x 4
identity = identity.to(device)
assert (f(input)[0] == expected).all()
@@ -83,26 +79,18 @@ class TestRandomHorizontalFlip3D:
f = RandomHorizontalFlip3D(p=1.0, return_transform=True)
f1 = RandomHorizontalFlip3D(p=0.0, return_transform=True)
- input = torch.tensor([[[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]]]) # 1 x 1 x 1 x 3 x 3
+ input = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]]) # 1 x 1 x 1 x 3 x 3
input = input.to(device)
- expected = torch.tensor([[[[[0., 0., 0.],
- [0., 0., 0.],
- [1., 1., 0.]]]]]) # 1 x 1 x 1 x 3 x 3
+ expected = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]]]]]) # 1 x 1 x 1 x 3 x 3
expected = expected.to(device)
- expected_transform = torch.tensor([[[-1., 0., 0., 2.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ expected_transform = torch.tensor(
+ [[[-1., 0., 0., 2.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]
+ ) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
- identity = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ identity = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4
identity = identity.to(device)
input = input.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3
@@ -132,49 +120,41 @@ class TestRandomHorizontalFlip3D:
RandomHorizontalFlip3D(p=1.0),
)
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
+ input = torch.tensor([[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
input = input.to(device)
- expected_transform = torch.tensor([[[-1., 0., 0., 2.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ expected_transform = torch.tensor(
+ [[[-1., 0., 0., 2.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]
+ ) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
expected_transform_1 = expected_transform @ expected_transform
expected_transform_1 = expected_transform_1.to(device)
- assert(f(input)[0] == input).all()
- assert(f(input)[1] == expected_transform_1).all()
- assert(f1(input)[0] == input).all()
- assert(f1(input)[1] == expected_transform).all()
+ assert (f(input)[0] == input).all()
+ assert (f(input)[1] == expected_transform_1).all()
+ assert (f1(input)[0] == input).all()
+ assert (f1(input)[1] == expected_transform).all()
@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) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
return kornia.apply_hflip3d(data)
- input = torch.tensor([[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]) # 1 x 3 x 3
+ input = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]) # 1 x 3 x 3
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]]) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[0., 0., 0.],
- [0., 5., 5.],
- [0., 0., 0.]]]) # 3 x 3
+ expected = torch.tensor([[[0., 0., 0.], [0., 5., 5.], [0., 0., 0.]]]) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -205,29 +185,25 @@ class TestRandomVerticalFlip3D:
f2 = RandomVerticalFlip3D(p=1.)
f3 = RandomVerticalFlip3D(p=0.)
- input = torch.tensor([[[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]],
- [[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]]], device=device, dtype=dtype) # 1 x 1 x 2 x 3 x 3
-
- expected = torch.tensor([[[[[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]],
- [[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]]]]], device=device, dtype=dtype) # 1 x 1 x 2 x 3 x 3
-
- expected_transform = torch.tensor([[[1., 0., 0., 0.],
- [0., -1., 0., 2.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]], device=device, dtype=dtype) # 4 x 4
-
- identity = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]], device=device, dtype=dtype) # 1 x 4 x 4
+ input = torch.tensor(
+ [[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], [[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 2 x 3 x 3
+
+ expected = torch.tensor(
+ [[[[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]], [[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]]]],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 2 x 3 x 3
+
+ expected_transform = torch.tensor(
+ [[[1., 0., 0., 0.], [0., -1., 0., 2.], [0., 0., 1., 0.], [0., 0., 0., 1.]]], device=device, dtype=dtype
+ ) # 4 x 4
+
+ identity = torch.tensor(
+ [[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]], device=device, dtype=dtype
+ ) # 1 x 4 x 4
assert_allclose(f(input)[0], expected)
assert_allclose(f(input)[1], expected_transform)
@@ -241,26 +217,18 @@ class TestRandomVerticalFlip3D:
f = RandomVerticalFlip3D(p=1.0, return_transform=True)
f1 = RandomVerticalFlip3D(p=0.0, return_transform=True)
- input = torch.tensor([[[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]]]) # 1 x 1 x 1 x 3 x 3
+ input = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]]) # 1 x 1 x 1 x 3 x 3
input = input.to(device)
- expected = torch.tensor([[[[[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]]]]]) # 1 x 1 x 1 x 3 x 3
+ expected = torch.tensor([[[[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]]]]) # 1 x 1 x 1 x 3 x 3
expected = expected.to(device)
- expected_transform = torch.tensor([[[1., 0., 0., 0.],
- [0., -1., 0., 2.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ expected_transform = torch.tensor(
+ [[[1., 0., 0., 0.], [0., -1., 0., 2.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]
+ ) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
- identity = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ identity = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4
identity = identity.to(device)
input = input.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3
@@ -290,15 +258,12 @@ class TestRandomVerticalFlip3D:
RandomVerticalFlip3D(p=1.0),
)
- input = torch.tensor([[[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]]]) # 1 x 1 x 1 x 4 x 4
+ input = torch.tensor([[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]]) # 1 x 1 x 1 x 4 x 4
input = input.to(device)
- expected_transform = torch.tensor([[[1., 0., 0., 0.],
- [0., -1., 0., 2.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ expected_transform = torch.tensor(
+ [[[1., 0., 0., 0.], [0., -1., 0., 2.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]
+ ) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
expected_transform_1 = expected_transform @ expected_transform
@@ -310,27 +275,22 @@ class TestRandomVerticalFlip3D:
@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) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
return kornia.apply_vflip3d(data)
- input = torch.tensor([[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]) # 4 x 4
+ input = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]) # 4 x 4
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]]]) # 1 x 4 x 4
+ input = torch.tensor([[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]) # 1 x 4 x 4
input = input.repeat(2, 1, 1) # 2 x 4 x 4
- expected = torch.tensor([[[[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]]]]) # 1 x 4 x 4
+ expected = torch.tensor([[[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]]) # 1 x 4 x 4
expected = expected.repeat(2, 1, 1)
@@ -361,29 +321,39 @@ class TestRandomDepthicalFlip3D:
f2 = RandomDepthicalFlip3D(p=1.)
f3 = RandomDepthicalFlip3D(p=0.)
- input = torch.tensor([[[[[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 1.]],
- [[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 2.]]]]], device=device, dtype=dtype) # 2 x 3 x 4
-
- expected = torch.tensor([[[[[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 2.]],
- [[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 1.]]]]], device=device, dtype=dtype) # 2 x 3 x 4
-
- expected_transform = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., -1., 1.],
- [0., 0., 0., 1.]]], device=device, dtype=dtype) # 4 x 4
-
- identity = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]], device=device, dtype=dtype) # 4 x 4
+ input = torch.tensor(
+ [
+ [
+ [
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]],
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2 x 3 x 4
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]],
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2 x 3 x 4
+
+ expected_transform = torch.tensor(
+ [[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 1.], [0., 0., 0., 1.]]], device=device, dtype=dtype
+ ) # 4 x 4
+
+ identity = torch.tensor(
+ [[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]], device=device, dtype=dtype
+ ) # 4 x 4
assert_allclose(f(input)[0], expected)
assert_allclose(f(input)[1], expected_transform)
@@ -397,33 +367,29 @@ class TestRandomDepthicalFlip3D:
f = RandomDepthicalFlip3D(p=1.0, return_transform=True)
f1 = RandomDepthicalFlip3D(p=0.0, return_transform=True)
- input = torch.tensor([[[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 1.]],
- [[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 2.]]]) # 2 x 3 x 4
+ input = torch.tensor(
+ [
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]],
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]]
+ ]
+ ) # 2 x 3 x 4
input = input.to(device)
- expected = torch.tensor([[[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 2.]],
- [[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 1.]]]) # 2 x 3 x 4
+ expected = torch.tensor(
+ [
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]],
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]]
+ ]
+ ) # 2 x 3 x 4
expected = expected.to(device)
- expected_transform = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., -1., 1.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ expected_transform = torch.tensor(
+ [[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 1.], [0., 0., 0., 1.]]]
+ ) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
- identity = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ identity = torch.tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]) # 1 x 4 x 4
identity = identity.to(device)
input = input.repeat(5, 3, 1, 1, 1) # 5 x 3 x 3 x 3 x 3
@@ -453,18 +419,21 @@ class TestRandomDepthicalFlip3D:
RandomDepthicalFlip3D(p=1.0),
)
- input = torch.tensor([[[[[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 1.]],
- [[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 0., 2.]]]]]) # 2 x 3 x 4
+ input = torch.tensor(
+ [
+ [
+ [
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 1.]],
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 2.]]
+ ]
+ ]
+ ]
+ ) # 2 x 3 x 4
input = input.to(device)
- expected_transform = torch.tensor([[[1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [0., 0., -1., 1.],
- [0., 0., 0., 1.]]]) # 1 x 4 x 4
+ expected_transform = torch.tensor(
+ [[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., -1., 1.], [0., 0., 0., 1.]]]
+ ) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
expected_transform_1 = expected_transform @ expected_transform
@@ -476,27 +445,22 @@ class TestRandomDepthicalFlip3D:
@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) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
return kornia.apply_vflip3d(data)
- input = torch.tensor([[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]) # 4 x 4
+ input = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]) # 4 x 4
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]]]) # 1 x 4 x 4
+ input = torch.tensor([[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]) # 1 x 4 x 4
input = input.repeat(2, 1, 1) # 2 x 4 x 4
- expected = torch.tensor([[[[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]]]]) # 1 x 4 x 4
+ expected = torch.tensor([[[[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]]]) # 1 x 4 x 4
expected = expected.repeat(2, 1, 1)
@@ -532,36 +496,49 @@ class TestRandomRotation3D:
f = RandomRotation3D(degrees=45.0, return_transform=True)
f1 = RandomRotation3D(degrees=45.0)
- input = torch.tensor([[[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]]], device=device, dtype=dtype) # 3 x 4 x 4
-
- expected = torch.tensor([[[[[0.0000, 0.0000, 0.6810, 0.5250],
- [0.5052, 0.0000, 0.0000, 0.0613],
- [0.1159, 0.1072, 0.5324, 0.0870],
- [0.0000, 0.0000, 0.1927, 0.0000]],
- [[0.0000, 0.1683, 0.6963, 0.1131],
- [0.0566, 0.0000, 0.5215, 0.2796],
- [0.0694, 0.6039, 1.4519, 1.1240],
- [0.0000, 0.1325, 0.1542, 0.2510]],
- [[0.0000, 0.2054, 0.0000, 0.0000],
- [0.0026, 0.6088, 0.7358, 0.2319],
- [0.1261, 1.0830, 1.3687, 1.4940],
- [0.0000, 0.0416, 0.2012, 0.3124]]]]], device=device, dtype=dtype)
-
- expected_transform = torch.tensor([[[0.6523, 0.3666, -0.6635, 0.6352],
- [-0.6185, 0.7634, -0.1862, 1.4689],
- [0.4382, 0.5318, 0.7247, -1.1797],
- [0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 3 x 4 x 4
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0.0000, 0.0000, 0.6810, 0.5250], [0.5052, 0.0000, 0.0000, 0.0613],
+ [0.1159, 0.1072, 0.5324, 0.0870], [0.0000, 0.0000, 0.1927, 0.0000]
+ ],
+ [
+ [0.0000, 0.1683, 0.6963, 0.1131], [0.0566, 0.0000, 0.5215, 0.2796],
+ [0.0694, 0.6039, 1.4519, 1.1240], [0.0000, 0.1325, 0.1542, 0.2510]
+ ],
+ [
+ [0.0000, 0.2054, 0.0000, 0.0000], [0.0026, 0.6088, 0.7358, 0.2319],
+ [0.1261, 1.0830, 1.3687, 1.4940], [0.0000, 0.0416, 0.2012, 0.3124]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected_transform = torch.tensor(
+ [
+ [
+ [0.6523, 0.3666, -0.6635, 0.6352], [-0.6185, 0.7634, -0.1862, 1.4689],
+ [0.4382, 0.5318, 0.7247, -1.1797], [0.0000, 0.0000, 0.0000, 1.0000]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
out, mat = f(input)
assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
@@ -576,52 +553,71 @@ class TestRandomRotation3D:
f = RandomRotation3D(degrees=45.0, return_transform=True)
- input = torch.tensor([[[[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]]]], device=device, dtype=dtype) # 1 x 1 x 4 x 4
-
- expected = torch.tensor([[[[[1.0000, 0.0000, 0.0000, 2.0000],
- [0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 2.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 2.0000]],
- [[1.0000, 0.0000, 0.0000, 2.0000],
- [0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 2.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 2.0000]],
- [[1.0000, 0.0000, 0.0000, 2.0000],
- [0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 2.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 2.0000]]]],
- [[[[0.0000, 0.0726, 0.0000, 0.0000],
- [0.1038, 1.0134, 0.5566, 0.1519],
- [0.0000, 1.0849, 1.1068, 0.0000],
- [0.1242, 1.1065, 0.9681, 0.0000]],
- [[0.0000, 0.0047, 0.0166, 0.0000],
- [0.0579, 0.4459, 0.0000, 0.4728],
- [0.1864, 1.3349, 0.7530, 0.3251],
- [0.1431, 1.2481, 0.4471, 0.0000]],
- [[0.0000, 0.4840, 0.2314, 0.0000],
- [0.0000, 0.0328, 0.0000, 0.1434],
- [0.1899, 0.5580, 0.0000, 0.9170],
- [0.0000, 0.2042, 0.1571, 0.0855]]]]], device=device, dtype=dtype)
-
- expected_transform = torch.tensor([[[1.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 1.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 1.0000]],
- [[0.7522, -0.6326, -0.1841, 1.5047],
- [0.6029, 0.5482, 0.5796, -0.8063],
- [-0.2657, -0.5470, 0.7938, 1.4252],
- [0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1 x 1 x 4 x 4
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [1.0000, 0.0000, 0.0000, 2.0000], [0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 1.0000, 2.0000, 0.0000], [0.0000, 0.0000, 1.0000, 2.0000]
+ ],
+ [
+ [1.0000, 0.0000, 0.0000, 2.0000], [0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 1.0000, 2.0000, 0.0000], [0.0000, 0.0000, 1.0000, 2.0000]
+ ],
+ [
+ [1.0000, 0.0000, 0.0000, 2.0000], [0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 1.0000, 2.0000, 0.0000], [0.0000, 0.0000, 1.0000, 2.0000]
+ ]
+ ]
+ ],
+ [
+ [
+ [
+ [0.0000, 0.0726, 0.0000, 0.0000], [0.1038, 1.0134, 0.5566, 0.1519],
+ [0.0000, 1.0849, 1.1068, 0.0000], [0.1242, 1.1065, 0.9681, 0.0000]
+ ],
+ [
+ [0.0000, 0.0047, 0.0166, 0.0000], [0.0579, 0.4459, 0.0000, 0.4728],
+ [0.1864, 1.3349, 0.7530, 0.3251], [0.1431, 1.2481, 0.4471, 0.0000]
+ ],
+ [
+ [0.0000, 0.4840, 0.2314, 0.0000], [0.0000, 0.0328, 0.0000, 0.1434],
+ [0.1899, 0.5580, 0.0000, 0.9170], [0.0000, 0.2042, 0.1571, 0.0855]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected_transform = torch.tensor(
+ [
+ [
+ [1.0000, 0.0000, 0.0000, 0.0000], [0.0000, 1.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 1.0000, 0.0000], [0.0000, 0.0000, 0.0000, 1.0000]
+ ],
+ [
+ [0.7522, -0.6326, -0.1841, 1.5047], [0.6029, 0.5482, 0.5796, -0.8063],
+ [-0.2657, -0.5470, 0.7938, 1.4252], [0.0000, 0.0000, 0.0000, 1.0000]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
input = input.repeat(2, 1, 1, 1, 1) # 5 x 4 x 4 x 3
@@ -648,41 +644,60 @@ class TestRandomRotation3D:
RandomRotation3D(10.4),
)
- input = torch.tensor([[[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]]], device=device, dtype=dtype) # 3 x 4 x 4
-
- expected = torch.tensor([[[[[0.3431, 0.1239, 0.0000, 1.0348],
- [0.0000, 0.2035, 0.1139, 0.1770],
- [0.0789, 0.9057, 1.7780, 0.0000],
- [0.0000, 0.2286, 1.2498, 1.2643]],
- [[0.5460, 0.2131, 0.0000, 1.1453],
- [0.0000, 0.0899, 0.0000, 0.4293],
- [0.0797, 1.0193, 1.6677, 0.0000],
- [0.0000, 0.2458, 1.2765, 1.0920]],
- [[0.6322, 0.2614, 0.0000, 0.9207],
- [0.0000, 0.0037, 0.0000, 0.6551],
- [0.0689, 0.9251, 1.3442, 0.0000],
- [0.0000, 0.2449, 0.9856, 0.6862]]]]], device=device, dtype=dtype)
-
- expected_transform = torch.tensor([[[0.9857, -0.1686, -0.0019, 0.2762],
- [0.1668, 0.9739, 0.1538, -0.3650],
- [-0.0241, -0.1520, 0.9881, 0.2760],
- [0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
-
- expected_transform_2 = torch.tensor([[[0.2348, -0.1615, 0.9585, 0.4316],
- [0.1719, 0.9775, 0.1226, -0.3467],
- [-0.9567, 0.1360, 0.2573, 1.9738],
- [0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 3 x 4 x 4
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0.3431, 0.1239, 0.0000, 1.0348], [0.0000, 0.2035, 0.1139, 0.1770],
+ [0.0789, 0.9057, 1.7780, 0.0000], [0.0000, 0.2286, 1.2498, 1.2643]
+ ],
+ [
+ [0.5460, 0.2131, 0.0000, 1.1453], [0.0000, 0.0899, 0.0000, 0.4293],
+ [0.0797, 1.0193, 1.6677, 0.0000], [0.0000, 0.2458, 1.2765, 1.0920]
+ ],
+ [
+ [0.6322, 0.2614, 0.0000, 0.9207], [0.0000, 0.0037, 0.0000, 0.6551],
+ [0.0689, 0.9251, 1.3442, 0.0000], [0.0000, 0.2449, 0.9856, 0.6862]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected_transform = torch.tensor(
+ [
+ [
+ [0.9857, -0.1686, -0.0019, 0.2762], [0.1668, 0.9739, 0.1538, -0.3650],
+ [-0.0241, -0.1520, 0.9881, 0.2760], [0.0000, 0.0000, 0.0000, 1.0000]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected_transform_2 = torch.tensor(
+ [
+ [
+ [0.2348, -0.1615, 0.9585, 0.4316], [0.1719, 0.9775, 0.1226, -0.3467],
+ [-0.9567, 0.1360, 0.2573, 1.9738], [0.0000, 0.0000, 0.0000, 1.0000]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
out, mat = f(input)
_, mat_2 = f1(input)
@@ -697,42 +712,29 @@ class TestRandomRotation3D:
@torch.jit.script
def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
- flags = dict(
- interpolation=torch.tensor(1),
- align_corners=torch.tensor(True)
- )
+ flags = dict(interpolation=torch.tensor(1), align_corners=torch.tensor(True))
return kornia.apply_rotation3d(data, params={"degrees": torch.tensor(45.0)}, flags=flags)
- input = torch.tensor([[[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]]]) # 3 x 4 x 4
+ input = torch.tensor(
+ [
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]],
+ [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]
+ ]
+ ) # 3 x 4 x 4
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]],
- [[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]],
- [[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]]]) # 3 x 3 x 3
-
- expected = torch.tensor([[[0.0000, 0.2584, 0.0000],
- [2.9552, 5.0000, 0.2584],
- [1.6841, 0.4373, 0.0000]]])
+ input = torch.tensor(
+ [
+ [[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]], [[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]],
+ [[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]]
+ ]
+ ) # 3 x 3 x 3
+
+ expected = torch.tensor([[[0.0000, 0.2584, 0.0000], [2.9552, 5.0000, 0.2584], [1.6841, 0.4373, 0.0000]]])
actual = op_trace(input)
@@ -761,35 +763,57 @@ class TestRandomCrop3D:
@pytest.mark.parametrize("batch_size", [1, 2])
def test_no_padding(self, batch_size, device, dtype):
torch.manual_seed(42)
- inp = torch.tensor([[[[
- [0., 1., 2., 3., 4.],
- [5., 6., 7., 8., 9.],
- [10, 11, 12, 13, 14],
- [15, 16, 17, 18, 19],
- [20, 21, 22, 23, 24]
- ]]]], device=device, dtype=dtype).repeat(batch_size, 1, 5, 1, 1)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 1., 2., 3., 4.], [5., 6., 7., 8., 9.], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19],
+ [20, 21, 22, 23, 24]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).repeat(batch_size, 1, 5, 1, 1)
f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.)
out = f(inp)
if batch_size == 1:
- expected = torch.tensor([[[[
- [11, 12, 13, 14],
- [16, 17, 18, 19],
- [21, 22, 23, 24]
- ]]]], device=device, dtype=dtype).repeat(batch_size, 1, 2, 1, 1)
+ expected = torch.tensor(
+ [[[[[11, 12, 13, 14], [16, 17, 18, 19], [21, 22, 23, 24]]]]], device=device, dtype=dtype
+ ).repeat(batch_size, 1, 2, 1, 1)
if batch_size == 2:
- expected = torch.tensor([
- [[[[6.0000, 7.0000, 8.0000, 9.0000],
- [11.0000, 12.0000, 13.0000, 14.0000],
- [16.0000, 17.0000, 18.0000, 19.0000]],
- [[6.0000, 7.0000, 8.0000, 9.0000],
- [11.0000, 12.0000, 13.0000, 14.0000],
- [16.0000, 17.0000, 18.0000, 19.0000]]]],
- [[[[11.0000, 12.0000, 13.0000, 14.0000],
- [16.0000, 17.0000, 18.0000, 19.0000],
- [21.0000, 22.0000, 23.0000, 24.0000]],
- [[11.0000, 12.0000, 13.0000, 14.0000],
- [16.0000, 17.0000, 18.0000, 19.0000],
- [21.0000, 22.0000, 23.0000, 24.0000]]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [6.0000, 7.0000, 8.0000, 9.0000], [11.0000, 12.0000, 13.0000, 14.0000],
+ [16.0000, 17.0000, 18.0000, 19.0000]
+ ],
+ [
+ [6.0000, 7.0000, 8.0000, 9.0000], [11.0000, 12.0000, 13.0000, 14.0000],
+ [16.0000, 17.0000, 18.0000, 19.0000]
+ ]
+ ]
+ ],
+ [
+ [
+ [
+ [11.0000, 12.0000, 13.0000, 14.0000], [16.0000, 17.0000, 18.0000, 19.0000],
+ [21.0000, 22.0000, 23.0000, 24.0000]
+ ],
+ [
+ [11.0000, 12.0000, 13.0000, 14.0000], [16.0000, 17.0000, 18.0000, 19.0000],
+ [21.0000, 22.0000, 23.0000, 24.0000]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -803,26 +827,26 @@ class TestRandomCrop3D:
def test_padding_batch(self, padding, device, dtype):
torch.manual_seed(42)
batch_size = 2
- inp = torch.tensor([[[
- [0., 1., 2.],
- [3., 4., 5.],
- [6., 7., 8.]
- ]]], device=device, dtype=dtype).repeat(batch_size, 1, 3, 1, 1)
- expected = torch.tensor([[[
- [[0., 1., 2., 10.],
- [3., 4., 5., 10.],
- [6., 7., 8., 10.]],
- [[0., 1., 2., 10.],
- [3., 4., 5., 10.],
- [6., 7., 8., 10.]],
- ]], [[
- [[3., 4., 5., 10.],
- [6., 7., 8., 10.],
- [10, 10, 10, 10.]],
- [[3., 4., 5., 10.],
- [6., 7., 8., 10.],
- [10, 10, 10, 10.]],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor([[[[0., 1., 2.], [3., 4., 5.], [6., 7., 8.]]]], device=device,
+ dtype=dtype).repeat(batch_size, 1, 3, 1, 1)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [[0., 1., 2., 10.], [3., 4., 5., 10.], [6., 7., 8., 10.]],
+ [[0., 1., 2., 10.], [3., 4., 5., 10.], [6., 7., 8., 10.]],
+ ]
+ ],
+ [
+ [
+ [[3., 4., 5., 10.], [6., 7., 8., 10.], [10, 10, 10, 10.]],
+ [[3., 4., 5., 10.], [6., 7., 8., 10.], [10, 10, 10, 10.]],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
f = RandomCrop3D(size=(2, 3, 4), fill=10., padding=padding, align_corners=True, p=1.)
out = f(inp)
@@ -833,14 +857,18 @@ class TestRandomCrop3D:
inp = torch.tensor([[
[0., 1., 2.],
]], device=device, dtype=dtype)
- expected = torch.tensor([[[
- [[9., 9., 9., 9.],
- [9., 9., 9., 9.],
- [9., 9., 9., 9.]],
- [[0., 1., 2., 9.],
- [9., 9., 9., 9.],
- [9., 9., 9., 9.]],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [[9., 9., 9., 9.], [9., 9., 9., 9.], [9., 9., 9., 9.]],
+ [[0., 1., 2., 9.], [9., 9., 9., 9.], [9., 9., 9., 9.]],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
rc = RandomCrop3D(size=(2, 3, 4), pad_if_needed=True, fill=9, align_corners=True, p=1.)
out = rc(inp)
@@ -871,7 +899,7 @@ class TestRandomCrop3D:
# 1. Trace op
img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
- op_trace = torch.jit.trace(op_script, (img,))
+ op_trace = torch.jit.trace(op_script, (img, ))
# 2. Generate new input
img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
@@ -904,7 +932,7 @@ class TestCenterCrop3D:
def test_gradcheck(self, device, dtype):
input = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.augmentation.CenterCrop3D(3), (input,), raise_exception=True)
+ assert gradcheck(kornia.augmentation.CenterCrop3D(3), (input, ), raise_exception=True)
class TestRandomEqualize3D:
@@ -926,11 +954,12 @@ class TestRandomEqualize3D:
inputs3d = self.build_input(channels, depth, height, width, bs, device=device, dtype=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, dtype=dtype)
- expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected,
- device=device, dtype=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,
+ dtype=dtype
+ )
+ expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected, device=device, dtype=dtype)
identity = kornia.eye_like(4, expected)
@@ -951,11 +980,8 @@ class TestRandomEqualize3D:
inputs3d = self.build_input(channels, depth, height, width, bs, device=device, dtype=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
- ])
- expected = self.build_input(channels, depth, height, width, bs, row=row_expected,
- device=device, dtype=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])
+ expected = self.build_input(channels, depth, height, width, bs, row=row_expected, device=device, dtype=dtype)
identity = kornia.eye_like(4, expected) # 2 x 4 x 4
@@ -978,7 +1004,7 @@ class TestRandomEqualize3D:
inputs3d = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3 x 3
inputs3d = utils.tensor_to_gradcheck_var(inputs3d) # to var
- assert gradcheck(RandomEqualize3D(p=0.5), (inputs3d,), raise_exception=True)
+ assert gradcheck(RandomEqualize3D(p=0.5), (inputs3d, ), raise_exception=True)
@staticmethod
def build_input(channels, depth, height, width, bs=1, row=None, device='cpu', dtype=torch.float32):
diff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.py
index 9354af785..c4f65dd0f 100644
--- a/test/augmentation/test_augmentation_mix.py
+++ b/test/augmentation/test_augmentation_mix.py
@@ -2,10 +2,7 @@ import torch
from torch.testing import assert_allclose
from torch.autograd import gradcheck
-from kornia.augmentation import (
- RandomMixUp,
- RandomCutMix
-)
+from kornia.augmentation import (RandomMixUp, RandomCutMix)
class TestRandomMixUp:
@@ -19,16 +16,18 @@ class TestRandomMixUp:
torch.manual_seed(0)
f = RandomMixUp(p=1.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
lam = torch.tensor([0.1320, 0.3074], device=device, dtype=dtype)
- expected = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),
- torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1]]
+ expected = torch.stack(
+ [
+ torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),
+ torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1]
+ ]
)
out_image, out_label = f(input, label)
@@ -42,10 +41,10 @@ class TestRandomMixUp:
torch.manual_seed(0)
f = RandomMixUp(p=0.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
lam = torch.tensor([0., 0.], device=device, dtype=dtype)
@@ -60,10 +59,10 @@ class TestRandomMixUp:
torch.manual_seed(0)
f = RandomMixUp(lambda_val=(0., 0.), p=1.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
lam = torch.tensor([0., 0.], device=device, dtype=dtype)
@@ -80,17 +79,19 @@ class TestRandomMixUp:
torch.manual_seed(0)
f = RandomMixUp(same_on_batch=True, p=1.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
lam = torch.tensor([0.0885, 0.0885], device=device, dtype=dtype)
- expected = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),
- torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1]
- ])
+ expected = torch.stack(
+ [
+ torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),
+ torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1]
+ ]
+ )
out_image, out_label = f(input, label)
assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)
@@ -103,27 +104,31 @@ class TestRandomCutMix:
def test_smoke(self, device, dtype):
f = RandomCutMix(width=3, height=3)
- repr = ("RandomCutMix(num_mix=1, beta=None, cut_size=None, height=3, width=3, p=1.0, "
- "p_batch=1.0, same_on_batch=False)")
+ repr = (
+ "RandomCutMix(num_mix=1, beta=None, cut_size=None, height=3, width=3, p=1.0, "
+ "p_batch=1.0, same_on_batch=False)"
+ )
assert str(f) == repr
def test_random_mixup_p1(self, device, dtype):
torch.manual_seed(76)
f = RandomCutMix(width=4, height=3, p=1.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
lam = torch.tensor([0.1320, 0.3074], device=device, dtype=dtype)
- expected = torch.tensor([[[[0., 0., 0., 1.],
- [0., 0., 0., 1.],
- [1., 1., 1., 1.]]],
- [[[1., 1., 1., 0.],
- [1., 1., 1., 0.],
- [0., 0., 0., 0.]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [[[0., 0., 0., 1.], [0., 0., 0., 1.], [1., 1., 1., 1.]]],
+ [[[1., 1., 1., 0.], [1., 1., 1., 0.], [0., 0., 0., 0.]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
out_image, out_label = f(input, label)
@@ -136,10 +141,10 @@ class TestRandomCutMix:
torch.manual_seed(76)
f = RandomCutMix(p=0., width=4, height=3)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
expected = input.clone()
@@ -155,18 +160,20 @@ class TestRandomCutMix:
# beta cannot be 0 after torch 1.8.0
f = RandomCutMix(beta=1e-7, width=4, height=3, p=1.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
- expected = torch.tensor([[[[0., 0., 1., 1.],
- [0., 0., 1., 1.],
- [1., 1., 1., 1.]]],
- [[[1., 1., 0., 0.],
- [1., 1., 0., 0.],
- [0., 0., 0., 0.]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [[[0., 0., 1., 1.], [0., 0., 1., 1.], [1., 1., 1., 1.]]],
+ [[[1., 1., 0., 0.], [1., 1., 0., 0.], [0., 0., 0., 0.]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
out_image, out_label = f(input, label)
@@ -180,51 +187,62 @@ class TestRandomCutMix:
torch.manual_seed(76)
f = RandomCutMix(width=4, height=3, num_mix=5, p=1.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
- expected = torch.tensor([[[[0., 0., 0., 1.],
- [0., 0., 0., 1.],
- [1., 1., 1., 1.]]],
- [[[1., 1., 0., 0.],
- [1., 1., 0., 0.],
- [0., 0., 0., 0.]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [[[0., 0., 0., 1.], [0., 0., 0., 1.], [1., 1., 1., 1.]]],
+ [[[1., 1., 0., 0.], [1., 1., 0., 0.], [0., 0., 0., 0.]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
out_image, out_label = f(input, label)
assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)
assert (out_label[:, :, 0] == label).all()
- assert (out_label[:, :, 1] == torch.tensor(
- [[1, 0], [1, 0], [1, 0], [1, 0], [0, 1]], device=device)).all()
- assert_allclose(out_label[:, :, 2], torch.tensor(
- [[0.0833, 0.3333], [0., 0.1667], [0.5, 0.0833], [0.0833, 0.], [0.5, 0.3333]],
- device=device, dtype=dtype), rtol=1e-4, atol=1e-4)
+ assert (out_label[:, :, 1] == torch.tensor([[1, 0], [1, 0], [1, 0], [1, 0], [0, 1]], device=device)).all()
+ assert_allclose(
+ out_label[:, :, 2],
+ torch.tensor(
+ [[0.0833, 0.3333], [0., 0.1667], [0.5, 0.0833], [0.0833, 0.], [0.5, 0.3333]],
+ device=device,
+ dtype=dtype
+ ),
+ rtol=1e-4,
+ atol=1e-4
+ )
def test_random_mixup_same_on_batch(self, device, dtype):
torch.manual_seed(42)
f = RandomCutMix(same_on_batch=True, width=4, height=3, p=1.)
- input = torch.stack([
- torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)
- ])
+ input = torch.stack(
+ [torch.ones(1, 3, 4, device=device, dtype=dtype),
+ torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ )
label = torch.tensor([1, 0], device=device)
lam = torch.tensor([0.0885, 0.0885], device=device, dtype=dtype)
- expected = torch.tensor([[[[0., 0., 0., 1.],
- [0., 0., 0., 1.],
- [1., 1., 1., 1.]]],
- [[[1., 1., 1., 0.],
- [1., 1., 1., 0.],
- [0., 0., 0., 0.]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [[[0., 0., 0., 1.], [0., 0., 0., 1.], [1., 1., 1., 1.]]],
+ [[[1., 1., 1., 0.], [1., 1., 1., 0.], [0., 0., 0., 0.]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
out_image, out_label = f(input, label)
assert_allclose(out_image, expected, rtol=1e-4, atol=1e-4)
assert (out_label[0, :, 0] == label).all()
assert (out_label[0, :, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()
- assert_allclose(out_label[0, :, 2],
- torch.tensor([0.5000, 0.5000], device=device, dtype=dtype), rtol=1e-4, atol=1e-4)
+ assert_allclose(
+ out_label[0, :, 2], torch.tensor([0.5000, 0.5000], device=device, dtype=dtype), rtol=1e-4, atol=1e-4
+ )
diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.py
index 175950cf8..6aa00f2ef 100644
--- a/test/augmentation/test_backward.py
+++ b/test/augmentation/test_backward.py
@@ -5,13 +5,7 @@ import torch.nn as nn
from torch.testing import assert_allclose
from kornia.augmentation import (
- ColorJitter,
- RandomAffine,
- RandomErasing,
- RandomRotation,
- RandomPerspective,
- RandomSharpness,
- RandomResizedCrop,
+ ColorJitter, RandomAffine, RandomErasing, RandomRotation, RandomPerspective, RandomSharpness, RandomResizedCrop,
RandomMotionBlur
)
@@ -74,16 +68,23 @@ class TestRandomAffineBackward:
@pytest.mark.parametrize("degrees", [10, [10., 20.], (10, 20), torch.tensor(10.), torch.tensor([10, 20])])
@pytest.mark.parametrize("translate", [[0.1, 0.2], torch.tensor([0.1, 0.2])])
- @pytest.mark.parametrize("scale", [
- [0.1, 0.2], [0.1, 0.2, 0.3, 0.4], torch.tensor([0.1, 0.2]), torch.tensor([0.1, 0.2, 0.3, 0.4])])
- @pytest.mark.parametrize("shear", [
- [10., 20.], [10., 20., 30., 40.], torch.tensor([10, 20]), torch.tensor([10, 20, 30, 40])])
+ @pytest.mark.parametrize(
+ "scale", [[0.1, 0.2], [0.1, 0.2, 0.3, 0.4],
+ torch.tensor([0.1, 0.2]),
+ torch.tensor([0.1, 0.2, 0.3, 0.4])]
+ )
+ @pytest.mark.parametrize(
+ "shear", [[10., 20.], [10., 20., 30., 40.],
+ torch.tensor([10, 20]),
+ torch.tensor([10, 20, 30, 40])]
+ )
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("return_transform", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
- def test_param(self, degrees, translate, scale, shear, resample, align_corners, return_transform,
- same_on_batch, device, dtype):
+ def test_param(
+ self, degrees, translate, scale, shear, resample, align_corners, return_transform, same_on_batch, device, dtype
+ ):
_degrees = degrees if isinstance(degrees, (int, float, list, tuple)) else \
nn.Parameter(degrees.clone().to(device=device, dtype=dtype))
@@ -97,8 +98,16 @@ class TestRandomAffineBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomAffine(
- _degrees, _translate, _scale, _shear, resample, align_corners=align_corners,
- return_transform=return_transform, same_on_batch=same_on_batch, p=1.)
+ _degrees,
+ _translate,
+ _scale,
+ _shear,
+ resample,
+ align_corners=align_corners,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch,
+ p=1.
+ )
if return_transform:
output, _ = aug(input)
@@ -177,8 +186,12 @@ class TestRandomRotationBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomRotation(
- _degrees, resample, align_corners=align_corners,
- return_transform=return_transform, same_on_batch=same_on_batch)
+ _degrees,
+ resample,
+ align_corners=align_corners,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch
+ )
if return_transform:
output, _ = aug(input)
@@ -221,8 +234,13 @@ class TestRandomPerspectiveBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomPerspective(
- _distortion_scale, resample=resample, return_transform=return_transform,
- same_on_batch=same_on_batch, align_corners=align_corners, p=1.)
+ _distortion_scale,
+ resample=resample,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch,
+ align_corners=align_corners,
+ p=1.
+ )
if return_transform:
output, _ = aug(input)
@@ -267,8 +285,7 @@ class TestRandomMotionBlurBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
- aug = RandomMotionBlur(
- (3, 3), _angle, _direction, border_type, resample, return_transform, same_on_batch, p=1.)
+ aug = RandomMotionBlur((3, 3), _angle, _direction, border_type, resample, return_transform, same_on_batch, p=1.)
if return_transform:
output, _ = aug(input)
@@ -317,8 +334,7 @@ class TestRandomSharpnessBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
- aug = RandomSharpness(
- _sharpness, return_transform=return_transform, same_on_batch=same_on_batch)
+ aug = RandomSharpness(_sharpness, return_transform=return_transform, same_on_batch=same_on_batch)
if return_transform:
output, _ = aug(input)
@@ -357,8 +373,14 @@ class TestRandomResizedCropBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomResizedCrop(
- (8, 8), _scale, _ratio, resample=resample, return_transform=return_transform,
- same_on_batch=same_on_batch, align_corners=align_corners)
+ (8, 8),
+ _scale,
+ _ratio,
+ resample=resample,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch,
+ align_corners=align_corners
+ )
if return_transform:
output, _ = aug(input)
diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.py
index 967c7880c..29ca68804 100644
--- a/test/augmentation/test_backward_3d.py
+++ b/test/augmentation/test_backward_3d.py
@@ -4,35 +4,45 @@ import torch.nn as nn
from torch.testing import assert_allclose
-from kornia.augmentation import (
- RandomAffine3D,
- RandomRotation3D,
- RandomPerspective3D,
- RandomMotionBlur3D
-)
+from kornia.augmentation import (RandomAffine3D, RandomRotation3D, RandomPerspective3D, RandomMotionBlur3D)
class TestRandomAffine3DBackward:
- @pytest.mark.parametrize("degrees", [
- 10, [10., 20.], [10., 20., 30.], [(10, 20), (10, 20), (10, 20)],
- torch.tensor(10.), torch.tensor([10., 20.]), torch.tensor([10, 20, 30]),
- torch.tensor([(10, 20), (10, 20), (10, 20)])])
+ @pytest.mark.parametrize(
+ "degrees", [
+ 10, [10., 20.], [10., 20., 30.], [(10, 20), (10, 20), (10, 20)],
+ torch.tensor(10.),
+ torch.tensor([10., 20.]),
+ torch.tensor([10, 20, 30]),
+ torch.tensor([(10, 20), (10, 20), (10, 20)])
+ ]
+ )
@pytest.mark.parametrize("translate", [[0.1, 0.2, 0.3], torch.tensor([0.1, 0.2, 0.3])])
- @pytest.mark.parametrize("scale", [
- [0.1, 0.2], [(0.1, 0.2), (0.1, 0.2), (0.1, 0.2)],
- torch.tensor([0.1, 0.2]), torch.tensor([(0.1, 0.2), (0.1, 0.2), (0.1, 0.2)])])
- @pytest.mark.parametrize("shear", [
- 10., [10., 20.], [10., 20., 30., 40., 50., 60.],
- [(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)],
- torch.tensor(10), torch.tensor([10, 20]), torch.tensor([10., 20., 30., 40., 50., 60.]),
- torch.tensor([(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)])])
+ @pytest.mark.parametrize(
+ "scale", [
+ [0.1, 0.2], [(0.1, 0.2), (0.1, 0.2), (0.1, 0.2)],
+ torch.tensor([0.1, 0.2]),
+ torch.tensor([(0.1, 0.2), (0.1, 0.2), (0.1, 0.2)])
+ ]
+ )
+ @pytest.mark.parametrize(
+ "shear", [
+ 10., [10., 20.], [10., 20., 30., 40., 50., 60.],
+ [(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)],
+ torch.tensor(10),
+ torch.tensor([10, 20]),
+ torch.tensor([10., 20., 30., 40., 50., 60.]),
+ torch.tensor([(-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.), (-10., 10.)])
+ ]
+ )
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("return_transform", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
- def test_param(self, degrees, translate, scale, shear, resample, align_corners, return_transform,
- same_on_batch, device, dtype):
+ def test_param(
+ self, degrees, translate, scale, shear, resample, align_corners, return_transform, same_on_batch, device, dtype
+ ):
_degrees = degrees if isinstance(degrees, (int, float, list, tuple)) else \
nn.Parameter(degrees.clone().to(device=device, dtype=dtype))
@@ -46,8 +56,16 @@ class TestRandomAffine3DBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomAffine3D(
- _degrees, _translate, _scale, _shear, resample, align_corners=align_corners,
- return_transform=return_transform, same_on_batch=same_on_batch, p=1.)
+ _degrees,
+ _translate,
+ _scale,
+ _shear,
+ resample,
+ align_corners=align_corners,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch,
+ p=1.
+ )
if return_transform:
output, _ = aug(input)
@@ -113,10 +131,15 @@ class TestRandomAffine3DBackward:
class TestRandomRotation3DBackward:
- @pytest.mark.parametrize("degrees", [
- 10, [10., 20.], [10., 20., 30.], [(10, 20), (10, 20), (10, 20)],
- torch.tensor(10.), torch.tensor([10., 20.]), torch.tensor([10, 20, 30]),
- torch.tensor([(10, 20), (10, 20), (10, 20)])])
+ @pytest.mark.parametrize(
+ "degrees", [
+ 10, [10., 20.], [10., 20., 30.], [(10, 20), (10, 20), (10, 20)],
+ torch.tensor(10.),
+ torch.tensor([10., 20.]),
+ torch.tensor([10, 20, 30]),
+ torch.tensor([(10, 20), (10, 20), (10, 20)])
+ ]
+ )
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("return_transform", [True, False])
@@ -129,8 +152,13 @@ class TestRandomRotation3DBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomRotation3D(
- _degrees, resample, align_corners=align_corners,
- return_transform=return_transform, same_on_batch=same_on_batch, p=1.)
+ _degrees,
+ resample,
+ align_corners=align_corners,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch,
+ p=1.
+ )
if return_transform:
output, _ = aug(input)
@@ -173,8 +201,13 @@ class TestRandomPerspective3DBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomPerspective3D(
- _distortion_scale, resample=resample, return_transform=return_transform,
- same_on_batch=same_on_batch, align_corners=align_corners, p=1.)
+ _distortion_scale,
+ resample=resample,
+ return_transform=return_transform,
+ same_on_batch=same_on_batch,
+ align_corners=align_corners,
+ p=1.
+ )
if return_transform:
output, _ = aug(input)
@@ -221,7 +254,8 @@ class TestRandomMotionBlur3DBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
aug = RandomMotionBlur3D(
- (3, 3), _angle, _direction, border_type, resample, return_transform, same_on_batch, p=1.)
+ (3, 3), _angle, _direction, border_type, resample, return_transform, same_on_batch, p=1.
+ )
if return_transform:
output, _ = aug(input)
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index 0cfc33728..6b4f0b3dd 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -29,18 +29,20 @@ class TestBasicAugmentationBase:
assert output.shape == torch.Size([2, 3, 1, 4, 5])
assert_allclose(input, output[:, :, 0, :, :])
- @pytest.mark.parametrize("p,p_batch,same_on_batch,num,seed", [
- (1., 1., False, 12, 1),
- (1., 0., False, 0, 1),
- (0., 1., False, 0, 1),
- (0., 0., False, 0, 1),
- (.5, .1, False, 7, 3),
- (.5, .1, True, 12, 3),
- (.3, 1., False, 2, 1),
- (.3, 1., True, 0, 1),
- ])
+ @pytest.mark.parametrize(
+ "p,p_batch,same_on_batch,num,seed", [
+ (1., 1., False, 12, 1),
+ (1., 0., False, 0, 1),
+ (0., 1., False, 0, 1),
+ (0., 0., False, 0, 1),
+ (.5, .1, False, 7, 3),
+ (.5, .1, True, 12, 3),
+ (.3, 1., False, 2, 1),
+ (.3, 1., True, 0, 1),
+ ]
+ )
def test_forward_params(self, p, p_batch, same_on_batch, num, seed, device, dtype):
- input_shape = (12,)
+ input_shape = (12, )
torch.manual_seed(seed)
augmentation = _BasicAugmentationBase(p, p_batch, same_on_batch)
with patch.object(augmentation, "generate_parameters", autospec=True) as generate_parameters:
@@ -75,14 +77,16 @@ class TestBasicAugmentationBase:
class TestAugmentationBase2D:
- @pytest.mark.parametrize('input_shape, in_trans_shape', [
- ((2, 3, 4, 5), (2, 3, 3)),
- ((3, 4, 5), (3, 3)),
- ((4, 5), (3, 3)),
- pytest.param((1, 2, 3, 4, 5), (2, 3, 3), marks=pytest.mark.xfail),
- pytest.param((2, 3, 4, 5), (1, 3, 3), marks=pytest.mark.xfail),
- pytest.param((2, 3, 4, 5), (3, 3), marks=pytest.mark.xfail),
- ])
+ @pytest.mark.parametrize(
+ 'input_shape, in_trans_shape', [
+ ((2, 3, 4, 5), (2, 3, 3)),
+ ((3, 4, 5), (3, 3)),
+ ((4, 5), (3, 3)),
+ pytest.param((1, 2, 3, 4, 5), (2, 3, 3), marks=pytest.mark.xfail),
+ pytest.param((2, 3, 4, 5), (1, 3, 3), marks=pytest.mark.xfail),
+ pytest.param((2, 3, 4, 5), (3, 3), marks=pytest.mark.xfail),
+ ]
+ )
def test_check_batching(self, device, dtype, input_shape, in_trans_shape):
input = torch.rand(input_shape, device=device, dtype=dtype)
in_trans = torch.rand(in_trans_shape, device=device, dtype=dtype)
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 02015af12..a6b016d34 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -9,32 +9,33 @@ class TestVideoSequential:
@pytest.mark.parametrize('shape', [(3, 4), (2, 3, 4), (2, 3, 5, 6), (2, 3, 4, 5, 6, 7)])
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_exception(self, shape, data_format, device, dtype):
- aug_list = K.VideoSequential(
- K.ColorJitter(0.1, 0.1, 0.1, 0.1), data_format=data_format, same_on_frame=True)
+ aug_list = K.VideoSequential(K.ColorJitter(0.1, 0.1, 0.1, 0.1), data_format=data_format, same_on_frame=True)
with pytest.raises(AssertionError):
input = torch.randn(*shape, device=device, dtype=dtype)
output = aug_list(input)
- @pytest.mark.parametrize('augmentation', [
- K.RandomAffine(360, p=1.),
- K.CenterCrop((3, 3), p=1.),
- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.),
- K.RandomCrop((5, 5), p=1.),
- K.RandomErasing(p=1.),
- K.RandomGrayscale(p=1.),
- K.RandomHorizontalFlip(p=1.),
- K.RandomVerticalFlip(p=1.),
- K.RandomPerspective(p=1.),
- K.RandomResizedCrop((5, 5), p=1.),
- K.RandomRotation(360., p=1.),
- K.RandomSolarize(p=1.),
- K.RandomPosterize(p=1.),
- K.RandomSharpness(p=1.),
- K.RandomEqualize(p=1.),
- K.RandomMotionBlur(3, 35., 0.5, p=1.),
- K.Normalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.),
- K.Denormalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.),
- ])
+ @pytest.mark.parametrize(
+ 'augmentation', [
+ K.RandomAffine(360, p=1.),
+ K.CenterCrop((3, 3), p=1.),
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.),
+ K.RandomCrop((5, 5), p=1.),
+ K.RandomErasing(p=1.),
+ K.RandomGrayscale(p=1.),
+ K.RandomHorizontalFlip(p=1.),
+ K.RandomVerticalFlip(p=1.),
+ K.RandomPerspective(p=1.),
+ K.RandomResizedCrop((5, 5), p=1.),
+ K.RandomRotation(360., p=1.),
+ K.RandomSolarize(p=1.),
+ K.RandomPosterize(p=1.),
+ K.RandomSharpness(p=1.),
+ K.RandomEqualize(p=1.),
+ K.RandomMotionBlur(3, 35., 0.5, p=1.),
+ K.Normalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.),
+ K.Denormalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.),
+ ]
+ )
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_augmentation(self, augmentation, data_format, device, dtype):
input = torch.randint(255, (1, 3, 3, 5, 6), device=device, dtype=dtype).repeat(2, 1, 1, 1, 1) / 255.
@@ -42,12 +43,10 @@ class TestVideoSequential:
aug_list = K.VideoSequential(augmentation, data_format=data_format, same_on_frame=True)
output = aug_list(input)
- @pytest.mark.parametrize('augmentations', [
- [
- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=.5),
- K.RandomAffine(360, p=.5),
- ]
- ])
+ @pytest.mark.parametrize('augmentations', [[
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=.5),
+ K.RandomAffine(360, p=.5),
+ ]])
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_p_half(self, augmentations, data_format, device, dtype):
input = torch.randn(1, 3, 3, 5, 6, device=device, dtype=dtype).repeat(2, 1, 1, 1, 1)
@@ -58,20 +57,22 @@ class TestVideoSequential:
assert not (output[0] == input[0]).all()
assert (output[1] == input[1]).all()
- @pytest.mark.parametrize('augmentations', [
- [
- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.),
- K.RandomAffine(360, p=1.),
- ],
- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)],
- [K.RandomAffine(360, p=1.)],
- [
- K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.),
- K.RandomAffine(360, p=0.),
- ],
- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.)],
- [K.RandomAffine(360, p=0.)],
- ])
+ @pytest.mark.parametrize(
+ 'augmentations', [
+ [
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.),
+ K.RandomAffine(360, p=1.),
+ ],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)],
+ [K.RandomAffine(360, p=1.)],
+ [
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.),
+ K.RandomAffine(360, p=0.),
+ ],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.)],
+ [K.RandomAffine(360, p=0.)],
+ ]
+ )
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_same_on_frame(self, augmentations, data_format, device, dtype):
aug_list = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=True)
@@ -89,10 +90,7 @@ class TestVideoSequential:
assert (output[:, 1] == output[:, 2]).all()
assert (output[:, 2] == output[:, 3]).all()
- @pytest.mark.parametrize('augmentations', [
- [K.RandomAffine(360, p=1.)],
- [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)]
- ])
+ @pytest.mark.parametrize('augmentations', [[K.RandomAffine(360, p=1.)], [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.)]])
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_against_sequential(self, augmentations, data_format, device, dtype):
aug_list_1 = K.VideoSequential(*augmentations, data_format=data_format, same_on_frame=False)
diff --git a/test/augmentation/test_functional.py b/test/augmentation/test_functional.py
index 1aa864380..eaf32ad4c 100644
--- a/test/augmentation/test_functional.py
+++ b/test/augmentation/test_functional.py
@@ -15,25 +15,25 @@ from kornia.augmentation import ColorJitter
class TestHorizontalFlipFn:
def test_random_hflip(self, device, dtype):
- input = torch.tensor([[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 1., 2.]], device=device, dtype=dtype) # 3 x 4
+ input = torch.tensor(
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ ) # 3 x 4
- expected = torch.tensor([[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [2., 1., 0., 0.]], device=device, dtype=dtype) # 3 x 4
+ expected = torch.tensor(
+ [[0., 0., 0., 0.], [0., 0., 0., 0.], [2., 1., 0., 0.]], device=device, dtype=dtype
+ ) # 3 x 4
assert (F.apply_hflip(input[None, None]) == expected).all()
def test_batch_random_hflip(self, device, dtype):
batch_size = 5
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [1., 1., 0.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ expected = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(batch_size, 3, 1, 1) # 5 x 3 x 3 x 3
expected = expected.repeat(batch_size, 3, 1, 1) # 5 x 3 x 3 x 3
@@ -43,26 +43,22 @@ class TestHorizontalFlipFn:
class TestVerticalFlipFn:
def test_random_vflip(self, device, dtype):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
- expected = torch.tensor([[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
assert (F.apply_vflip(input[None, None]) == expected).all()
def test_batch_random_vflip(self, device, dtype):
batch_size = 5
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
- expected = torch.tensor([[[[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ expected = torch.tensor(
+ [[[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]]], device=device, dtype=dtype
+ ) # 1 x 1 x 3 x 3
input = input.repeat(batch_size, 3, 1, 1) # 5 x 3 x 3 x 3
expected = expected.repeat(batch_size, 3, 1, 1) # 5 x 3 x 3 x 3
@@ -113,35 +109,23 @@ class TestColorJitter:
'order': torch.tensor([2, 3, 0, 1])
}
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
+ input = torch.tensor([[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[[0.2529, 0.3529, 0.4529],
- [0.7529, 0.6529, 0.5529],
- [0.8529, 0.9529, 1.0000]],
-
- [[0.2529, 0.3529, 0.4529],
- [0.7529, 0.6529, 0.5529],
- [0.8529, 0.9529, 1.0000]],
-
- [[0.2529, 0.3529, 0.4529],
- [0.7529, 0.6529, 0.5529],
- [0.8529, 0.9529, 1.0000]]],
-
-
- [[[0.2660, 0.3660, 0.4660],
- [0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]],
-
- [[0.2660, 0.3660, 0.4660],
- [0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]],
-
- [[0.2660, 0.3660, 0.4660],
- [0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]]]]) # 1 x 1 x 3 x 3
+ expected = torch.tensor(
+ [
+ [
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529], [0.7529, 0.6529, 0.5529], [0.8529, 0.9529, 1.0000]]
+ ],
+ [
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]]
+ ]
+ ]
+ ) # 1 x 1 x 3 x 3
assert_allclose(F.apply_color_jitter(input, jitter_param), expected)
@@ -155,35 +139,23 @@ class TestColorJitter:
'order': torch.tensor([2, 3, 0, 1])
}
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
+ input = torch.tensor([[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[[0.0953, 0.1906, 0.2859],
- [0.5719, 0.4766, 0.3813],
- [0.6672, 0.7625, 0.9531]],
-
- [[0.0953, 0.1906, 0.2859],
- [0.5719, 0.4766, 0.3813],
- [0.6672, 0.7625, 0.9531]],
-
- [[0.0953, 0.1906, 0.2859],
- [0.5719, 0.4766, 0.3813],
- [0.6672, 0.7625, 0.9531]]],
-
-
- [[[0.1184, 0.2367, 0.3551],
- [0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]],
-
- [[0.1184, 0.2367, 0.3551],
- [0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]],
-
- [[0.1184, 0.2367, 0.3551],
- [0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]]]])
+ expected = torch.tensor(
+ [
+ [
+ [[0.0953, 0.1906, 0.2859], [0.5719, 0.4766, 0.3813], [0.6672, 0.7625, 0.9531]],
+ [[0.0953, 0.1906, 0.2859], [0.5719, 0.4766, 0.3813], [0.6672, 0.7625, 0.9531]],
+ [[0.0953, 0.1906, 0.2859], [0.5719, 0.4766, 0.3813], [0.6672, 0.7625, 0.9531]]
+ ],
+ [
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]],
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]],
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]]
+ ]
+ ]
+ )
assert_allclose(F.apply_color_jitter(input, jitter_param), expected, atol=1e-4, rtol=1e-5)
@@ -197,43 +169,49 @@ class TestColorJitter:
'order': torch.tensor([2, 3, 0, 1])
}
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ]
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[[1.8763e-01, 2.5842e-01, 3.3895e-01],
- [6.2921e-01, 5.0000e-01, 4.0000e-01],
- [7.0974e-01, 8.0000e-01, 1.0000e+00]],
-
- [[1.0000e+00, 5.2921e-01, 6.0974e-01],
- [6.2921e-01, 3.1947e-01, 2.1947e-01],
- [8.0000e-01, 1.6816e-01, 2.7790e-01]],
-
- [[6.3895e-01, 8.0000e-01, 7.0000e-01],
- [9.0000e-01, 3.1947e-01, 2.1947e-01],
- [8.0000e-01, 4.3895e-01, 5.4869e-01]]],
-
-
- [[[1.1921e-07, 1.2953e-01, 2.5302e-01],
- [5.6476e-01, 5.0000e-01, 4.0000e-01],
- [6.8825e-01, 8.0000e-01, 1.0000e+00]],
-
- [[1.0000e+00, 4.6476e-01, 5.8825e-01],
- [5.6476e-01, 2.7651e-01, 1.7651e-01],
- [8.0000e-01, 1.7781e-02, 1.0603e-01]],
-
- [[5.5556e-01, 8.0000e-01, 7.0000e-01],
- [9.0000e-01, 2.7651e-01, 1.7651e-01],
- [8.0000e-01, 3.5302e-01, 4.4127e-01]]]])
+ expected = torch.tensor(
+ [
+ [
+ [
+ [1.8763e-01, 2.5842e-01, 3.3895e-01], [6.2921e-01, 5.0000e-01, 4.0000e-01],
+ [7.0974e-01, 8.0000e-01, 1.0000e+00]
+ ],
+ [
+ [1.0000e+00, 5.2921e-01, 6.0974e-01], [6.2921e-01, 3.1947e-01, 2.1947e-01],
+ [8.0000e-01, 1.6816e-01, 2.7790e-01]
+ ],
+ [
+ [6.3895e-01, 8.0000e-01, 7.0000e-01], [9.0000e-01, 3.1947e-01, 2.1947e-01],
+ [8.0000e-01, 4.3895e-01, 5.4869e-01]
+ ]
+ ],
+ [
+ [
+ [1.1921e-07, 1.2953e-01, 2.5302e-01], [5.6476e-01, 5.0000e-01, 4.0000e-01],
+ [6.8825e-01, 8.0000e-01, 1.0000e+00]
+ ],
+ [
+ [1.0000e+00, 4.6476e-01, 5.8825e-01], [5.6476e-01, 2.7651e-01, 1.7651e-01],
+ [8.0000e-01, 1.7781e-02, 1.0603e-01]
+ ],
+ [
+ [5.5556e-01, 8.0000e-01, 7.0000e-01], [9.0000e-01, 2.7651e-01, 1.7651e-01],
+ [8.0000e-01, 3.5302e-01, 4.4127e-01]
+ ]
+ ]
+ ]
+ )
assert_allclose(F.apply_color_jitter(input, jitter_param), expected, atol=1e-4, rtol=1e-5)
@@ -246,42 +224,31 @@ class TestColorJitter:
'saturation_factor': torch.tensor([1., 1.]),
'order': torch.tensor([2, 3, 0, 1])
}
- input = torch.tensor([[[[0.1, 0.2, 0.3],
- [0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]],
-
- [[1.0, 0.5, 0.6],
- [0.6, 0.3, 0.2],
- [0.8, 0.1, 0.2]],
-
- [[0.6, 0.8, 0.7],
- [0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
+ input = torch.tensor(
+ [
+ [
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[1.0, 0.5, 0.6], [0.6, 0.3, 0.2], [0.8, 0.1, 0.2]],
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, .5]]
+ ]
+ ]
+ ) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[[0.1000, 0.2000, 0.3000],
- [0.6000, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
-
- [[1.0000, 0.5251, 0.6167],
- [0.6126, 0.3000, 0.2000],
- [0.8000, 0.1000, 0.2000]],
-
- [[0.5623, 0.8000, 0.7000],
- [0.9000, 0.3084, 0.2084],
- [0.7958, 0.4293, 0.5335]]],
-
- [[[0.1000, 0.2000, 0.3000],
- [0.6116, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
-
- [[1.0000, 0.4769, 0.5846],
- [0.6000, 0.3077, 0.2077],
- [0.7961, 0.1000, 0.2000]],
-
- [[0.6347, 0.8000, 0.7000],
- [0.9000, 0.3000, 0.2000],
- [0.8000, 0.3730, 0.4692]]]])
+ expected = torch.tensor(
+ [
+ [
+ [[0.1000, 0.2000, 0.3000], [0.6000, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.5251, 0.6167], [0.6126, 0.3000, 0.2000], [0.8000, 0.1000, 0.2000]],
+ [[0.5623, 0.8000, 0.7000], [0.9000, 0.3084, 0.2084], [0.7958, 0.4293, 0.5335]]
+ ],
+ [
+ [[0.1000, 0.2000, 0.3000], [0.6116, 0.5000, 0.4000], [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.4769, 0.5846], [0.6000, 0.3077, 0.2077], [0.7961, 0.1000, 0.2000]],
+ [[0.6347, 0.8000, 0.7000], [0.9000, 0.3000, 0.2000], [0.8000, 0.3730, 0.4692]]
+ ]
+ ]
+ )
assert_allclose(F.apply_color_jitter(input, jitter_param), expected, atol=1e-4, rtol=1e-5)
@@ -289,86 +256,118 @@ class TestColorJitter:
class TestRandomGrayscale:
def test_opencv_true(self, device):
- data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]])
+ data = torch.tensor(
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ]
+ )
data = data.to(device)
- expected = torch.tensor([[[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]]])
+ expected = torch.tensor(
+ [
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ]
+ ]
+ )
expected = expected.to(device)
assert_allclose(F.apply_grayscale(data[None]), expected[None])
def test_opencv_true_batch(self, device):
batch_size = 4
- data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]])
+ data = torch.tensor(
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ]
+ )
data = data.to(device)
data = data.unsqueeze(0).repeat(batch_size, 1, 1, 1)
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
- expected = torch.tensor([[[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]],
-
- [[0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]]])
+ expected = torch.tensor(
+ [
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ],
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ]
+ ]
+ )
expected = expected.to(device)
expected = expected.unsqueeze(0).repeat(batch_size, 1, 1, 1)
@@ -386,18 +385,19 @@ class TestRandomRectangleEarasing:
"ys": torch.tensor([5]),
"values": torch.tensor([0.])
}
- expected = torch.tensor([[[
- [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
- [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
- [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
- [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
- [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.]
- ]]]).to(device)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
+ [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
+ [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.],
+ [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 0., 0., 0., 0., 0.]
+ ]
+ ]
+ ]
+ ).to(device)
assert_allclose(F.apply_erase_rectangles(inputs, rect_params), expected)
def test_rectangle_erasing2(self, device):
@@ -410,41 +410,20 @@ class TestRandomRectangleEarasing:
"values": torch.tensor([0., 0., 0.])
}
expected = torch.tensor(
- [[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.]],
-
- [[0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.]],
-
- [[0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.]]],
-
- [[[1., 1., 1.],
- [1., 0., 0.],
- [1., 0., 0.]],
-
- [[1., 1., 1.],
- [1., 0., 0.],
- [1., 0., 0.]],
-
- [[1., 1., 1.],
- [1., 0., 0.],
- [1., 0., 0.]]],
-
- [[[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 0.]],
-
- [[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 0.]],
-
- [[1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 0.]]]]
+ [
+ [
+ [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],
+ [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]
+ ],
+ [
+ [[1., 1., 1.], [1., 0., 0.], [1., 0., 0.]], [[1., 1., 1.], [1., 0., 0.], [1., 0., 0.]],
+ [[1., 1., 1.], [1., 0., 0.], [1., 0., 0.]]
+ ],
+ [
+ [[1., 1., 1.], [1., 1., 1.], [1., 1., 0.]], [[1., 1., 1.], [1., 1., 1.], [1., 1., 0.]],
+ [[1., 1., 1.], [1., 1., 1.], [1., 1., 0.]]
+ ]
+ ]
).to(device)
assert_allclose(F.apply_erase_rectangles(inputs, rect_params), expected)
diff --git a/test/augmentation/test_motionblur.py b/test/augmentation/test_motionblur.py
index 1ebbc00fe..d32dac4af 100644
--- a/test/augmentation/test_motionblur.py
+++ b/test/augmentation/test_motionblur.py
@@ -34,8 +34,14 @@ class TestRandomMotionBlur:
@pytest.mark.parametrize("return_transform", [True, False])
@pytest.mark.parametrize("p", [0., 1.])
def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):
- f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5,
- same_on_batch=same_on_batch, return_transform=return_transform, p=p)
+ f = RandomMotionBlur(
+ kernel_size=(3, 5),
+ angle=(10, 30),
+ direction=0.5,
+ same_on_batch=same_on_batch,
+ return_transform=return_transform,
+ p=p
+ )
torch.manual_seed(0)
batch_size = 2
input = torch.randn(1, 3, 5, 6).repeat(batch_size, 1, 1, 1)
@@ -65,8 +71,10 @@ class TestRandomMotionBlur:
f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.)
output = f(input)
- expected = motion_blur(input, f._params['ksize_factor'].unique().item(), f._params['angle_factor'],
- f._params['direction_factor'], f.border_type.name.lower())
+ expected = motion_blur(
+ input, f._params['ksize_factor'].unique().item(), f._params['angle_factor'], f._params['direction_factor'],
+ f.border_type.name.lower()
+ )
assert_allclose(output, expected, rtol=1e-4, atol=1e-4)
@@ -82,8 +90,10 @@ class TestRandomMotionBlur:
'direction_factor': torch.tensor([-0.5]),
'border_type': torch.tensor([0]),
}
- assert gradcheck(RandomMotionBlur(
- kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0), (inp, params), raise_exception=True)
+ assert gradcheck(
+ RandomMotionBlur(kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0), (inp, params),
+ raise_exception=True
+ )
class TestRandomMotionBlur3D:
@@ -101,8 +111,14 @@ class TestRandomMotionBlur3D:
@pytest.mark.parametrize("return_transform", [True, False])
@pytest.mark.parametrize("p", [0., 1.])
def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):
- f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5,
- same_on_batch=same_on_batch, return_transform=return_transform, p=p)
+ f = RandomMotionBlur3D(
+ kernel_size=(3, 5),
+ angle=(10, 30),
+ direction=0.5,
+ same_on_batch=same_on_batch,
+ return_transform=return_transform,
+ p=p
+ )
batch_size = 2
input = torch.randn(1, 3, 5, 6, 7, device=device, dtype=dtype).repeat(batch_size, 1, 1, 1, 1)
@@ -131,8 +147,10 @@ class TestRandomMotionBlur3D:
f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.)
output = f(input)
- expected = motion_blur3d(input, f._params['ksize_factor'].unique().item(), f._params['angle_factor'],
- f._params['direction_factor'], f.border_type.name.lower())
+ expected = motion_blur3d(
+ input, f._params['ksize_factor'].unique().item(), f._params['angle_factor'], f._params['direction_factor'],
+ f.border_type.name.lower()
+ )
assert_allclose(output, expected, rtol=1e-4, atol=1e-4)
@@ -147,5 +165,7 @@ class TestRandomMotionBlur3D:
'direction_factor': torch.tensor([-0.5]),
'border_type': torch.tensor([0]),
}
- assert gradcheck(RandomMotionBlur3D(
- kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0), (inp, params), raise_exception=True)
+ assert gradcheck(
+ RandomMotionBlur3D(kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0), (inp, params),
+ raise_exception=True
+ )
diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.py
index 7b855b4fc..c5950520a 100644
--- a/test/augmentation/test_perspective.py
+++ b/test/augmentation/test_perspective.py
@@ -17,13 +17,8 @@ class TestPerspective:
start_points = torch.rand(1, 4, 2).to(device)
end_points = torch.rand(1, 4, 2).to(device)
- params = dict(
- batch_prob=batch_prob, start_points=start_points,
- end_points=end_points)
- flags = dict(
- interpolation=torch.tensor(1),
- align_corners=torch.tensor(False)
- )
+ params = dict(batch_prob=batch_prob, start_points=start_points, end_points=end_points)
+ flags = dict(interpolation=torch.tensor(1), align_corners=torch.tensor(False))
out_data = F.apply_perspective(x_data, params, flags)
assert out_data.shape == x_data.shape
@@ -38,15 +33,13 @@ class TestPerspective:
end_points = torch.rand(1, 4, 2).to(device)
end_points = utils.tensor_to_gradcheck_var(end_points) # to var
- params = dict(
- start_points=start_points,
- end_points=end_points
- )
- flags = dict(
- interpolation=torch.tensor(1),
- align_corners=torch.tensor(False)
- )
- assert gradcheck(F.apply_perspective, (input, params, flags,), raise_exception=True)
+ params = dict(start_points=start_points, end_points=end_points)
+ flags = dict(interpolation=torch.tensor(1), align_corners=torch.tensor(False))
+ assert gradcheck(F.apply_perspective, (
+ input,
+ params,
+ flags,
+ ), raise_exception=True)
class TestRandomPerspective:
@@ -112,20 +105,28 @@ class TestRandomPerspective:
torch.manual_seed(0)
x_data = torch.rand(1, 2, 4, 5).to(device)
- expected_output = torch.tensor([[[[0.0000, 0.0000, 0.0000, 0.0197, 0.0429],
- [0.0000, 0.5632, 0.5322, 0.3677, 0.1430],
- [0.0000, 0.3083, 0.4032, 0.1761, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.0000, 0.1189, 0.0586],
- [0.0000, 0.7087, 0.5420, 0.3995, 0.0863],
- [0.0000, 0.2695, 0.5981, 0.5888, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]],
- device=device, dtype=x_data.dtype)
-
- expected_transform = torch.tensor([[[1.0523, 0.3493, 0.3046],
- [-0.1066, 1.0426, 0.5846],
- [0.0351, 0.1213, 1.0000]]],
- device=device, dtype=x_data.dtype)
+ expected_output = torch.tensor(
+ [
+ [
+ [
+ [0.0000, 0.0000, 0.0000, 0.0197, 0.0429], [0.0000, 0.5632, 0.5322, 0.3677, 0.1430],
+ [0.0000, 0.3083, 0.4032, 0.1761, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ],
+ [
+ [0.0000, 0.0000, 0.0000, 0.1189, 0.0586], [0.0000, 0.7087, 0.5420, 0.3995, 0.0863],
+ [0.0000, 0.2695, 0.5981, 0.5888, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=x_data.dtype
+ )
+
+ expected_transform = torch.tensor(
+ [[[1.0523, 0.3493, 0.3046], [-0.1066, 1.0426, 0.5846], [0.0351, 0.1213, 1.0000]]],
+ device=device,
+ dtype=x_data.dtype
+ )
aug = kornia.augmentation.RandomPerspective(p=.99999999, return_transform=True) # step one the random state
@@ -143,7 +144,7 @@ class TestRandomPerspective:
input = torch.rand(1, 2, 5, 7).to(device)
input = utils.tensor_to_gradcheck_var(input) # to var
# TODO: turned off with p=0
- assert gradcheck(kornia.augmentation.RandomPerspective(p=0.), (input,), raise_exception=True)
+ assert gradcheck(kornia.augmentation.RandomPerspective(p=0.), (input, ), raise_exception=True)
class TestRandomAffine:
@@ -166,16 +167,22 @@ class TestRandomAffine:
@pytest.mark.parametrize("degrees", [45., (-45., 45.), torch.tensor([45., 45.])])
@pytest.mark.parametrize("translate", [(0.1, 0.1), torch.tensor([0.1, 0.1])])
- @pytest.mark.parametrize("scale", [
- (0.8, 1.2), (0.8, 1.2, 0.9, 1.1), torch.tensor([0.8, 1.2]), torch.tensor([0.8, 1.2, 0.7, 1.3])])
- @pytest.mark.parametrize("shear", [
- 5., (-5., 5.), (-5., 5., -3., 3.), torch.tensor(5.),
- torch.tensor([-5., 5.]), torch.tensor([-5., 5., -3., 3.])
- ])
+ @pytest.mark.parametrize(
+ "scale", [(0.8, 1.2), (0.8, 1.2, 0.9, 1.1),
+ torch.tensor([0.8, 1.2]),
+ torch.tensor([0.8, 1.2, 0.7, 1.3])]
+ )
+ @pytest.mark.parametrize(
+ "shear", [
+ 5., (-5., 5.), (-5., 5., -3., 3.),
+ torch.tensor(5.),
+ torch.tensor([-5., 5.]),
+ torch.tensor([-5., 5., -3., 3.])
+ ]
+ )
def test_batch_multi_params(self, degrees, translate, scale, shear, device, dtype):
x_data = torch.rand(2, 2, 8, 9).to(device)
- aug = kornia.augmentation.RandomAffine(
- degrees=degrees, translate=translate, scale=scale, shear=shear)
+ aug = kornia.augmentation.RandomAffine(degrees=degrees, translate=translate, scale=scale, shear=shear)
out = aug(x_data)
assert out.shape == x_data.shape
assert aug.inverse(out).shape == x_data.shape
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index 586b563db..f701a3f29 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -1,4 +1,3 @@
-
import pytest
import torch
from torch.testing import assert_allclose
@@ -45,20 +44,22 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
def test_valid_param_combinations(self, p, batch_size, same_on_batch, device, dtype):
random_prob_generator(batch_size=batch_size, p=p, same_on_batch=same_on_batch)
- @pytest.mark.parametrize('p', [
- # Should be failed if p > 1. or p < 0.
- (-1.),
- (2.)
- ])
+ @pytest.mark.parametrize(
+ 'p',
+ [
+ # Should be failed if p > 1. or p < 0.
+ (-1.),
+ (2.)
+ ]
+ )
def test_invalid_param_combinations(self, p, device, dtype):
with pytest.raises(Exception):
random_prob_generator(batch_size=8, p=p)
- @pytest.mark.parametrize('p,expected', [
- (0., [False] * 8),
- (0.5, [False, False, True, False, True, False, True, False]),
- (1., [True] * 8)
- ])
+ @pytest.mark.parametrize(
+ 'p,expected',
+ [(0., [False] * 8), (0.5, [False, False, True, False, True, False, True, False]), (1., [True] * 8)]
+ )
def test_random_gen(self, p, expected, device, dtype):
torch.manual_seed(42)
batch_size = 8
@@ -92,37 +93,34 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
brightness.to(device=device, dtype=dtype) if brightness is not None else None,
contrast.to(device=device, dtype=dtype) if contrast is not None else None,
saturation.to(device=device, dtype=dtype) if saturation is not None else None,
- hue.to(device=device, dtype=dtype) if hue is not None else None,
- same_on_batch
+ hue.to(device=device, dtype=dtype) if hue is not None else None, same_on_batch
)
- @pytest.mark.parametrize('brightness,contrast,saturation,hue', [
- # Should be failed if value out of bounds or tensor.shape != [1, 2]
- (torch.tensor([-1., 2.]), None, None, None),
- (torch.tensor([0., 3.]), None, None, None),
- (torch.tensor(0.), None, None, None),
- (torch.tensor([0.]), None, None, None),
- (torch.tensor([0., 1., 2.]), None, None, None),
-
- (None, torch.tensor([-1., 2.]), None, None),
- (None, torch.tensor(0.), None, None),
- (None, torch.tensor([0.]), None, None),
- (None, torch.tensor([0., 1., 2.]), None, None),
-
- (None, None, torch.tensor([-1., 2.]), None),
- (None, None, torch.tensor(0.), None),
- (None, None, torch.tensor([0.]), None),
- (None, None, torch.tensor([0., 1., 2.]), None),
-
- (None, None, None, torch.tensor([-1., 0.])),
- (None, None, None, torch.tensor([0, 1.])),
- (None, None, None, torch.tensor(0.)),
- (None, None, None, torch.tensor([0.])),
- (None, None, None, torch.tensor([0., 1., 2.])),
- ])
- def test_invalid_param_combinations(
- self, brightness, contrast, saturation, hue, device, dtype
- ):
+ @pytest.mark.parametrize(
+ 'brightness,contrast,saturation,hue',
+ [
+ # Should be failed if value out of bounds or tensor.shape != [1, 2]
+ (torch.tensor([-1., 2.]), None, None, None),
+ (torch.tensor([0., 3.]), None, None, None),
+ (torch.tensor(0.), None, None, None),
+ (torch.tensor([0.]), None, None, None),
+ (torch.tensor([0., 1., 2.]), None, None, None),
+ (None, torch.tensor([-1., 2.]), None, None),
+ (None, torch.tensor(0.), None, None),
+ (None, torch.tensor([0.]), None, None),
+ (None, torch.tensor([0., 1., 2.]), None, None),
+ (None, None, torch.tensor([-1., 2.]), None),
+ (None, None, torch.tensor(0.), None),
+ (None, None, torch.tensor([0.]), None),
+ (None, None, torch.tensor([0., 1., 2.]), None),
+ (None, None, None, torch.tensor([-1., 0.])),
+ (None, None, None, torch.tensor([0, 1.])),
+ (None, None, None, torch.tensor(0.)),
+ (None, None, None, torch.tensor([0.])),
+ (None, None, None, torch.tensor([0., 1., 2.])),
+ ]
+ )
+ def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):
with pytest.raises(Exception):
random_color_jitter_generator(
8,
@@ -136,20 +134,26 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 8
jitter_params = random_color_jitter_generator(
- batch_size, brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),
+ batch_size,
+ brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),
contrast=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
saturation=torch.tensor([0.6, 1.4], device=device, dtype=dtype),
- hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype))
+ hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype)
+ )
expected_jitter_params = {
'brightness_factor': torch.tensor(
- [1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype),
+ [1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype
+ ),
'contrast_factor': torch.tensor(
- [1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype),
+ [1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype
+ ),
'hue_factor': torch.tensor(
- [0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype),
+ [0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype
+ ),
'saturation_factor': torch.tensor(
- [0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype),
+ [0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype
+ ),
'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype)
}
@@ -159,24 +163,28 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order'"
assert_allclose(
- jitter_params['brightness_factor'], expected_jitter_params['brightness_factor'], rtol=1e-4, atol=1e-4)
- assert_allclose(
- jitter_params['contrast_factor'], expected_jitter_params['contrast_factor'], rtol=1e-4, atol=1e-4)
- assert_allclose(
- jitter_params['hue_factor'], expected_jitter_params['hue_factor'], rtol=1e-4, atol=1e-4)
+ jitter_params['brightness_factor'], expected_jitter_params['brightness_factor'], rtol=1e-4, atol=1e-4
+ )
assert_allclose(
- jitter_params['saturation_factor'], expected_jitter_params['saturation_factor'], rtol=1e-4, atol=1e-4)
+ jitter_params['contrast_factor'], expected_jitter_params['contrast_factor'], rtol=1e-4, atol=1e-4
+ )
+ assert_allclose(jitter_params['hue_factor'], expected_jitter_params['hue_factor'], rtol=1e-4, atol=1e-4)
assert_allclose(
- jitter_params['order'].to(dtype), expected_jitter_params['order'], rtol=1e-4, atol=1e-4)
+ jitter_params['saturation_factor'], expected_jitter_params['saturation_factor'], rtol=1e-4, atol=1e-4
+ )
+ assert_allclose(jitter_params['order'].to(dtype), expected_jitter_params['order'], rtol=1e-4, atol=1e-4)
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
jitter_params = random_color_jitter_generator(
- batch_size, brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),
+ batch_size,
+ brightness=torch.tensor([0.8, 1.2], device=device, dtype=dtype),
contrast=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
saturation=torch.tensor([0.6, 1.4], device=device, dtype=dtype),
- hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype), same_on_batch=True)
+ hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype),
+ same_on_batch=True
+ )
expected_res = {
'brightness_factor': torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),
@@ -186,16 +194,11 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
'order': torch.tensor([2, 3, 0, 1], device=device, dtype=dtype)
}
- assert_allclose(
- jitter_params['brightness_factor'], expected_res['brightness_factor'], rtol=1e-4, atol=1e-4)
- assert_allclose(
- jitter_params['contrast_factor'], expected_res['contrast_factor'], rtol=1e-4, atol=1e-4)
- assert_allclose(
- jitter_params['hue_factor'], expected_res['hue_factor'], rtol=1e-4, atol=1e-4)
- assert_allclose(
- jitter_params['saturation_factor'], expected_res['saturation_factor'], rtol=1e-4, atol=1e-4)
- assert_allclose(
- jitter_params['order'].to(dtype), expected_res['order'], rtol=1e-4, atol=1e-4)
+ assert_allclose(jitter_params['brightness_factor'], expected_res['brightness_factor'], rtol=1e-4, atol=1e-4)
+ assert_allclose(jitter_params['contrast_factor'], expected_res['contrast_factor'], rtol=1e-4, atol=1e-4)
+ assert_allclose(jitter_params['hue_factor'], expected_res['hue_factor'], rtol=1e-4, atol=1e-4)
+ assert_allclose(jitter_params['saturation_factor'], expected_res['saturation_factor'], rtol=1e-4, atol=1e-4)
+ assert_allclose(jitter_params['order'].to(dtype), expected_res['order'], rtol=1e-4, atol=1e-4)
class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
@@ -204,50 +207,53 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('distortion_scale', [torch.tensor(0.), torch.tensor(0.5), torch.tensor(1.)])
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(
- self, height, width, distortion_scale, batch_size, same_on_batch, device, dtype
- ):
+ def test_valid_param_combinations(self, height, width, distortion_scale, batch_size, same_on_batch, device, dtype):
random_perspective_generator(
- batch_size=8, height=height, width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('height,width,distortion_scale', [
- # Should be failed if distortion_scale > 1. or distortion_scale < 0.
- (-100, 100, torch.tensor(0.5)),
- (100, -100, torch.tensor(0.5)),
- (100, 100, torch.tensor(-0.5)),
- (100, 100, torch.tensor(1.5)),
- (100, 100, torch.tensor([0., 0.5])),
- ])
+ batch_size=8,
+ height=height,
+ width=width,
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype),
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'height,width,distortion_scale',
+ [
+ # Should be failed if distortion_scale > 1. or distortion_scale < 0.
+ (-100, 100, torch.tensor(0.5)),
+ (100, -100, torch.tensor(0.5)),
+ (100, 100, torch.tensor(-0.5)),
+ (100, 100, torch.tensor(1.5)),
+ (100, 100, torch.tensor([0., 0.5])),
+ ]
+ )
def test_invalid_param_combinations(self, height, width, distortion_scale, device, dtype):
with pytest.raises(Exception):
random_perspective_generator(
- batch_size=8, height=height, width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype))
+ batch_size=8,
+ height=height,
+ width=width,
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype)
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
res = random_perspective_generator(batch_size, 200, 200, torch.tensor(0.5, device=device, dtype=dtype))
expected = dict(
- start_points=torch.tensor([
- [[0., 0.],
- [199., 0.],
- [199., 199.],
- [0., 199.]],
- [[0., 0.],
- [199., 0.],
- [199., 199.],
- [0., 199.]]], device=device, dtype=dtype),
- end_points=torch.tensor([
- [[44.1135, 45.7502],
- [179.8568, 47.9653],
- [179.4776, 168.9552],
- [12.8286, 159.3179]],
- [[47.0386, 6.6593],
- [152.2701, 29.6790],
- [155.5298, 170.6142],
- [37.0547, 177.5298]]], device=device, dtype=dtype),
+ start_points=torch.tensor(
+ [[[0., 0.], [199., 0.], [199., 199.], [0., 199.]], [[0., 0.], [199., 0.], [199., 199.], [0., 199.]]],
+ device=device,
+ dtype=dtype
+ ),
+ end_points=torch.tensor(
+ [
+ [[44.1135, 45.7502], [179.8568, 47.9653], [179.4776, 168.9552], [12.8286, 159.3179]],
+ [[47.0386, 6.6593], [152.2701, 29.6790], [155.5298, 170.6142], [37.0547, 177.5298]]
+ ],
+ device=device,
+ dtype=dtype
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'])
@@ -257,18 +263,16 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 2
res = random_perspective_generator(
- batch_size, 200, 200, torch.tensor(0.5, device=device, dtype=dtype), same_on_batch=True)
+ batch_size, 200, 200, torch.tensor(0.5, device=device, dtype=dtype), same_on_batch=True
+ )
expected = dict(
- start_points=torch.tensor([
- [[0., 0.],
- [199., 0.],
- [199., 199.],
- [0., 199.]]], device=device, dtype=dtype).repeat(2, 1, 1),
- end_points=torch.tensor([
- [[44.1135, 45.7502],
- [179.8568, 47.9653],
- [179.4776, 168.9552],
- [12.8286, 159.3179]]], device=device, dtype=dtype).repeat(2, 1, 1),
+ start_points=torch.tensor([[[0., 0.], [199., 0.], [199., 199.], [0., 199.]]], device=device,
+ dtype=dtype).repeat(2, 1, 1),
+ end_points=torch.tensor(
+ [[[44.1135, 45.7502], [179.8568, 47.9653], [179.4776, 168.9552], [12.8286, 159.3179]]],
+ device=device,
+ dtype=dtype
+ ).repeat(2, 1, 1),
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'])
@@ -289,36 +293,44 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
self, batch_size, height, width, degrees, translate, scale, shear, same_on_batch, device, dtype
):
random_affine_generator(
- batch_size=batch_size, height=height, width=width, degrees=degrees.to(device=device, dtype=dtype),
+ batch_size=batch_size,
+ height=height,
+ width=width,
+ degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('height,width,degrees,translate,scale,shear', [
- (-100, 100, torch.tensor([10, 20]), None, None, None),
- (100, -100, torch.tensor([10, 20]), None, None, None),
- (100, 100, 0.5, None, None, None),
- (100, 100, torch.tensor([10, 20, 30]), None, None, None),
- (100, 100, torch.tensor([10, 20]), torch.tensor([0.1]), None, None),
- (10, 10, torch.tensor([1, 2]), torch.tensor([0.1, 0.2, 0.3]), None, None),
- (100, 100, torch.tensor([10, 20]), None, torch.tensor([1]), None),
- (100, 100, torch.tensor([10, 20]), None, torch.tensor([1, 2, 3]), None),
- (100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1])),
- (100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1, 2])),
- (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3])),
- (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4])),
- (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4, 5])),
- ])
- def test_invalid_param_combinations(
- self, height, width, degrees, translate, scale, shear, device, dtype
- ):
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'height,width,degrees,translate,scale,shear', [
+ (-100, 100, torch.tensor([10, 20]), None, None, None),
+ (100, -100, torch.tensor([10, 20]), None, None, None),
+ (100, 100, 0.5, None, None, None),
+ (100, 100, torch.tensor([10, 20, 30]), None, None, None),
+ (100, 100, torch.tensor([10, 20]), torch.tensor([0.1]), None, None),
+ (10, 10, torch.tensor([1, 2]), torch.tensor([0.1, 0.2, 0.3]), None, None),
+ (100, 100, torch.tensor([10, 20]), None, torch.tensor([1]), None),
+ (100, 100, torch.tensor([10, 20]), None, torch.tensor([1, 2, 3]), None),
+ (100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1])),
+ (100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1, 2])),
+ (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3])),
+ (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4])),
+ (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4, 5])),
+ ]
+ )
+ def test_invalid_param_combinations(self, height, width, degrees, translate, scale, shear, device, dtype):
with pytest.raises(Exception):
random_affine_generator(
- batch_size=8, height=height, width=width, degrees=degrees.to(device=device, dtype=dtype),
+ batch_size=8,
+ height=height,
+ width=width,
+ degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shear=shear.to(device=device, dtype=dtype) if shear is not None else None)
+ shear=shear.to(device=device, dtype=dtype) if shear is not None else None
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -327,8 +339,15 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
scale = torch.tensor([0.7, 1.2], device=device, dtype=dtype)
shear = torch.tensor([[10, 20], [10, 20]], device=device, dtype=dtype)
res = random_affine_generator(
- batch_size=2, height=200, width=200, degrees=degrees,
- translate=translate, scale=scale, shear=shear, same_on_batch=False)
+ batch_size=2,
+ height=200,
+ width=200,
+ degrees=degrees,
+ translate=translate,
+ scale=scale,
+ shear=shear,
+ same_on_batch=False
+ )
expected = dict(
translations=torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
@@ -352,8 +371,15 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
scale = torch.tensor([0.7, 1.2], device=device, dtype=dtype)
shear = torch.tensor([[10, 20], [10, 20]], device=device, dtype=dtype)
res = random_affine_generator(
- batch_size=2, height=200, width=200, degrees=degrees,
- translate=translate, scale=scale, shear=shear, same_on_batch=True)
+ batch_size=2,
+ height=200,
+ width=200,
+ degrees=degrees,
+ translate=translate,
+ scale=scale,
+ shear=shear,
+ same_on_batch=True
+ )
expected = dict(
translations=torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
@@ -378,27 +404,22 @@ class TestRandomRotationGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, degrees, same_on_batch, device, dtype):
random_rotation_generator(
- batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
+ batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch
+ )
- @pytest.mark.parametrize('degrees', [
- (torch.tensor(10)),
- (torch.tensor([10])),
- (torch.tensor([10, 20, 30]))
- ])
+ @pytest.mark.parametrize('degrees', [(torch.tensor(10)), (torch.tensor([10])), (torch.tensor([10, 20, 30]))])
def test_invalid_param_combinations(self, degrees, device, dtype):
batch_size = 8
with pytest.raises(Exception):
- random_rotation_generator(
- batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype))
+ random_rotation_generator(batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
degrees = torch.tensor([10, 20])
res = random_rotation_generator(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False)
- expected = dict(
- degrees=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype)
+ batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False
)
+ expected = dict(degrees=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype))
assert res.keys() == expected.keys()
assert_allclose(res['degrees'], expected['degrees'])
@@ -406,10 +427,9 @@ class TestRandomRotationGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
degrees = torch.tensor([10, 20])
res = random_rotation_generator(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True)
- expected = dict(
- degrees=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype)
+ batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True
)
+ expected = dict(degrees=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype))
assert res.keys() == expected.keys()
assert_allclose(res['degrees'], expected['degrees'])
@@ -421,55 +441,55 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('size', [(100, 100), torch.tensor([50, 50])])
@pytest.mark.parametrize('resize_to', [None, (100, 100)])
@pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(
- self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype
- ):
+ def test_valid_param_combinations(self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype):
if isinstance(size, torch.Tensor):
size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)
random_crop_generator(
- batch_size=batch_size, input_size=input_size,
+ batch_size=batch_size,
+ input_size=input_size,
size=size,
resize_to=resize_to,
- same_on_batch=same_on_batch, device=device, dtype=dtype)
+ same_on_batch=same_on_batch,
+ device=device,
+ dtype=dtype
+ )
- @pytest.mark.parametrize('input_size,size,resize_to', [
- ((-300, 300), (200, 200), (100, 100)),
- ((200, 200), torch.tensor([50, 50]), (100, 100)),
- ])
+ @pytest.mark.parametrize(
+ 'input_size,size,resize_to', [
+ ((-300, 300), (200, 200), (100, 100)),
+ ((200, 200), torch.tensor([50, 50]), (100, 100)),
+ ]
+ )
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
batch_size = 2
with pytest.raises(Exception):
random_crop_generator(
- batch_size=batch_size, input_size=input_size,
+ batch_size=batch_size,
+ input_size=input_size,
size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
- resize_to=resize_to)
+ resize_to=resize_to
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
degrees = torch.tensor([10, 20], device=device, dtype=dtype)
res = random_crop_generator(
- batch_size=2, input_size=(100, 100),
+ batch_size=2,
+ input_size=(100, 100),
size=torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype),
- resize_to=(200, 200))
+ resize_to=(200, 200)
+ )
expected = dict(
- src=torch.tensor([
- [[36, 19],
- [95, 19],
- [95, 68],
- [36, 68]],
- [[19, 29],
- [98, 29],
- [98, 98],
- [19, 98]]], device=device, dtype=dtype),
- dst=torch.tensor([
- [[0, 0],
- [199, 0],
- [199, 199],
- [0, 199]],
- [[0, 0],
- [199, 0],
- [199, 199],
- [0, 199]]], device=device, dtype=dtype),
+ src=torch.tensor(
+ [[[36, 19], [95, 19], [95, 68], [36, 68]], [[19, 29], [98, 29], [98, 98], [19, 98]]],
+ device=device,
+ dtype=dtype
+ ),
+ dst=torch.tensor(
+ [[[0, 0], [199, 0], [199, 199], [0, 199]], [[0, 0], [199, 0], [199, 199], [0, 199]]],
+ device=device,
+ dtype=dtype
+ ),
input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
@@ -480,28 +500,23 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
degrees = torch.tensor([10, 20], device=device, dtype=dtype)
res = random_crop_generator(
- batch_size=2, input_size=(100, 100),
+ batch_size=2,
+ input_size=(100, 100),
size=torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype),
- resize_to=(200, 200), same_on_batch=True)
+ resize_to=(200, 200),
+ same_on_batch=True
+ )
expected = dict(
- src=torch.tensor([
- [[36, 46],
- [95, 46],
- [95, 95],
- [36, 95]],
- [[36, 46],
- [115, 46],
- [115, 115],
- [36, 115]]], device=device, dtype=dtype),
- dst=torch.tensor([
- [[0, 0],
- [199, 0],
- [199, 199],
- [0, 199]],
- [[0, 0],
- [199, 0],
- [199, 199],
- [0, 199]]], device=device, dtype=dtype),
+ src=torch.tensor(
+ [[[36, 46], [95, 46], [95, 95], [36, 95]], [[36, 46], [115, 46], [115, 115], [36, 115]]],
+ device=device,
+ dtype=dtype
+ ),
+ dst=torch.tensor(
+ [[[0, 0], [199, 0], [199, 199], [0, 199]], [[0, 0], [199, 0], [199, 199], [0, 199]]],
+ device=device,
+ dtype=dtype
+ ),
input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
@@ -516,61 +531,63 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('scale', [torch.tensor([.7, 1.3])])
@pytest.mark.parametrize('ratio', [torch.tensor([.9, 1.1])])
@pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(
- self, batch_size, size, scale, ratio, same_on_batch, device, dtype
- ):
+ def test_valid_param_combinations(self, batch_size, size, scale, ratio, same_on_batch, device, dtype):
random_crop_size_generator(
- batch_size=batch_size, size=size,
+ batch_size=batch_size,
+ size=size,
scale=scale.to(device=device, dtype=dtype),
ratio=ratio.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('size,scale,ratio', [
- ((100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1])),
- ((100, 100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1])),
- ((100, 100), torch.tensor([.7]), torch.tensor([.9, 1.1])),
- ((100, 100), torch.tensor([.7, 1.3, 1.5]), torch.tensor([.9, 1.1])),
- ((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9])),
- ((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1, 1.3])),
- ])
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'size,scale,ratio', [
+ ((100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1])),
+ ((100, 100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1])),
+ ((100, 100), torch.tensor([.7]), torch.tensor([.9, 1.1])),
+ ((100, 100), torch.tensor([.7, 1.3, 1.5]), torch.tensor([.9, 1.1])),
+ ((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9])),
+ ((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1, 1.3])),
+ ]
+ )
def test_invalid_param_combinations(self, size, scale, ratio, device, dtype):
batch_size = 2
with pytest.raises(Exception):
random_crop_size_generator(
- batch_size=batch_size, size=size,
+ batch_size=batch_size,
+ size=size,
scale=scale.to(device=device, dtype=dtype),
ratio=ratio.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch)
+ same_on_batch=same_on_batch
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
res = random_crop_size_generator(
- batch_size=8, size=(100, 100),
+ batch_size=8,
+ size=(100, 100),
scale=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
ratio=torch.tensor([0.9, 1.1], device=device, dtype=dtype),
- same_on_batch=False)
+ same_on_batch=False
+ )
expected = dict(
- size=torch.tensor([
- [99, 94],
- [91, 95],
- [90, 96],
- [87, 86],
- [94, 98],
- [87, 81],
- [85, 93],
- [83, 90]], device=device, dtype=dtype)
+ size=torch.tensor(
+ [[99, 94], [91, 95], [90, 96], [87, 86], [94, 98], [87, 81], [85, 93], [83, 90]],
+ device=device,
+ dtype=dtype
+ )
)
assert res.keys() == expected.keys()
assert_allclose(res['size'], expected['size'])
res = random_crop_size_generator(
- batch_size=100, size=(100, 100),
+ batch_size=100,
+ size=(100, 100),
scale=torch.tensor([0.999, 1.], device=device, dtype=dtype),
ratio=torch.tensor([1., 1.], device=device, dtype=dtype),
- same_on_batch=False)
- expected = dict(
- size=torch.tensor([[100, 100]], device=device, dtype=dtype).repeat(100, 1)
+ same_on_batch=False
)
+ expected = dict(size=torch.tensor([[100, 100]], device=device, dtype=dtype).repeat(100, 1))
assert res.keys() == expected.keys()
assert_allclose(res['size'], expected['size'])
@@ -578,20 +595,18 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
degrees = torch.tensor([10, 20])
res = random_crop_size_generator(
- batch_size=8, size=(100, 100),
+ batch_size=8,
+ size=(100, 100),
scale=torch.tensor([0.7, 1.3], device=device, dtype=dtype),
ratio=torch.tensor([0.9, 1.1], device=device, dtype=dtype),
- same_on_batch=True)
+ same_on_batch=True
+ )
expected = dict(
- size=torch.tensor([
- [99, 95],
- [99, 95],
- [99, 95],
- [99, 95],
- [99, 95],
- [99, 95],
- [99, 95],
- [99, 95]], device=device, dtype=dtype),
+ size=torch.tensor(
+ [[99, 95], [99, 95], [99, 95], [99, 95], [99, 95], [99, 95], [99, 95], [99, 95]],
+ device=device,
+ dtype=dtype
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['size'], expected['size'])
@@ -610,29 +625,40 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
self, batch_size, height, width, scale, ratio, value, same_on_batch, device, dtype
):
random_rectangles_params_generator(
- batch_size=batch_size, height=height, width=width, scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype), value=value, same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('height,width,scale,ratio,value', [
- (-100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
- (100, -100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
- (100, -100, torch.tensor([0.7]), torch.tensor([0.7, 1.3]), 0),
- (100, 100, torch.tensor([0.7, 1.3, 1.5]), torch.tensor([0.7, 1.3]), 0),
- (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7]), 0),
- (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3, 1.5]), 0),
- (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), -1),
- (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 2),
- (
- 100, 100, torch.tensor([.5, .7]), torch.tensor([.7, .9]), torch.tensor(0.5)),
- ])
- def test_invalid_param_combinations(
- self, height, width, scale, ratio, value, device, dtype
- ):
+ batch_size=batch_size,
+ height=height,
+ width=width,
+ scale=scale.to(device=device, dtype=dtype),
+ ratio=ratio.to(device=device, dtype=dtype),
+ value=value,
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'height,width,scale,ratio,value', [
+ (-100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
+ (100, -100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
+ (100, -100, torch.tensor([0.7]), torch.tensor([0.7, 1.3]), 0),
+ (100, 100, torch.tensor([0.7, 1.3, 1.5]), torch.tensor([0.7, 1.3]), 0),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7]), 0),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3, 1.5]), 0),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), -1),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 2),
+ (100, 100, torch.tensor([.5, .7]), torch.tensor([.7, .9]), torch.tensor(0.5)),
+ ]
+ )
+ def test_invalid_param_combinations(self, height, width, scale, ratio, value, device, dtype):
batch_size = 8
with pytest.raises(Exception):
random_rectangles_params_generator(
- batch_size=batch_size, height=height, width=width, scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype), value=value, same_on_batch=same_on_batch)
+ batch_size=batch_size,
+ height=height,
+ width=width,
+ scale=scale.to(device=device, dtype=dtype),
+ ratio=ratio.to(device=device, dtype=dtype),
+ value=value,
+ same_on_batch=same_on_batch
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -641,8 +667,8 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
ratio = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
value = 0.5
res = random_rectangles_params_generator(
- batch_size=2, height=height, width=width, scale=scale,
- ratio=ratio, value=value, same_on_batch=False)
+ batch_size=2, height=height, width=width, scale=scale, ratio=ratio, value=value, same_on_batch=False
+ )
expected = dict(
widths=torch.tensor([100, 100], device=device, dtype=dtype),
heights=torch.tensor([0, 0], device=device, dtype=dtype),
@@ -664,8 +690,8 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
ratio = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
value = 0.5
res = random_rectangles_params_generator(
- batch_size=2, height=height, width=width, scale=scale,
- ratio=ratio, value=value, same_on_batch=True)
+ batch_size=2, height=height, width=width, scale=scale, ratio=ratio, value=value, same_on_batch=True
+ )
expected = dict(
widths=torch.tensor([100, 100], device=device, dtype=dtype),
heights=torch.tensor([0, 0], device=device, dtype=dtype),
@@ -687,18 +713,18 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('height', [200])
@pytest.mark.parametrize('width', [200])
@pytest.mark.parametrize('size', [(100, 100)])
- def test_valid_param_combinations(
- self, batch_size, height, width, size, device, dtype
- ):
+ def test_valid_param_combinations(self, batch_size, height, width, size, device, dtype):
center_crop_generator(batch_size=batch_size, height=height, width=width, size=size)
- @pytest.mark.parametrize('height,width,size', [
- (200, -200, (100, 100)),
- (-200, 200, (100, 100)),
- (100, 100, (120, 120)),
- (150, 100, (120, 120)),
- (100, 150, (120, 120)),
- ])
+ @pytest.mark.parametrize(
+ 'height,width,size', [
+ (200, -200, (100, 100)),
+ (-200, 200, (100, 100)),
+ (100, 100, (120, 120)),
+ (150, 100, (120, 120)),
+ (100, 150, (120, 120)),
+ ]
+ )
def test_invalid_param_combinations(self, height, width, size, device, dtype):
batch_size = 2
with pytest.raises(Exception):
@@ -708,24 +734,16 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
res = center_crop_generator(batch_size=2, height=200, width=200, size=(120, 150))
expected = dict(
- src=torch.tensor([
- [[25, 40],
- [174, 40],
- [174, 159],
- [25, 159]],
- [[25, 40],
- [174, 40],
- [174, 159],
- [25, 159]]], device=device, dtype=torch.long),
- dst=torch.tensor([
- [[0, 0],
- [149, 0],
- [149, 119],
- [0, 119]],
- [[0, 0],
- [149, 0],
- [149, 119],
- [0, 119]]], device=device, dtype=torch.long),
+ src=torch.tensor(
+ [[[25, 40], [174, 40], [174, 159], [25, 159]], [[25, 40], [174, 40], [174, 159], [25, 159]]],
+ device=device,
+ dtype=torch.long
+ ),
+ dst=torch.tensor(
+ [[[0, 0], [149, 0], [149, 119], [0, 119]], [[0, 0], [149, 0], [149, 119], [0, 119]]],
+ device=device,
+ dtype=torch.long
+ ),
input_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
@@ -745,31 +763,42 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, kernel_size, angle, direction, same_on_batch, device, dtype):
random_motion_blur_generator(
- batch_size=batch_size, kernel_size=kernel_size,
+ batch_size=batch_size,
+ kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('kernel_size,angle,direction', [
- (4, torch.tensor([30, 100]), torch.tensor([-1, 1])),
- (1, torch.tensor([30, 100]), torch.tensor([-1, 1])),
- ((1, 2, 3), torch.tensor([30, 100]), torch.tensor([-1, 1])),
- (3, torch.tensor([30, 100]), torch.tensor([-2, 1])),
- (3, torch.tensor([30, 100]), torch.tensor([-1, 2])),
- ])
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'kernel_size,angle,direction', [
+ (4, torch.tensor([30, 100]), torch.tensor([-1, 1])),
+ (1, torch.tensor([30, 100]), torch.tensor([-1, 1])),
+ ((1, 2, 3), torch.tensor([30, 100]), torch.tensor([-1, 1])),
+ (3, torch.tensor([30, 100]), torch.tensor([-2, 1])),
+ (3, torch.tensor([30, 100]), torch.tensor([-1, 2])),
+ ]
+ )
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
with pytest.raises(Exception):
random_motion_blur_generator(
- batch_size=8, kernel_size=kernel_size, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype))
+ batch_size=8,
+ kernel_size=kernel_size,
+ angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype)
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
angle = torch.tensor([30, 90])
direction = torch.tensor([-1, 1])
res = random_motion_blur_generator(
- batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype), same_on_batch=False)
+ batch_size=2,
+ kernel_size=3,
+ angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype),
+ same_on_batch=False
+ )
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor([82.9362, 84.9002], device=device, dtype=dtype),
@@ -785,8 +814,12 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
angle = torch.tensor([30, 90])
direction = torch.tensor([-1, 1])
res = random_motion_blur_generator(
- batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype), same_on_batch=True)
+ batch_size=2,
+ kernel_size=3,
+ angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype),
+ same_on_batch=True
+ )
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor([82.9362, 82.9362], device=device, dtype=dtype),
@@ -806,34 +839,46 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, thresholds, additions, same_on_batch, device, dtype):
random_solarize_generator(
- batch_size=batch_size, thresholds=thresholds.to(device=device, dtype=dtype),
- additions=additions.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('thresholds,additions', [
- (torch.tensor([0, 2]), torch.tensor([-0.5, 0.5])),
- (torch.tensor([-1, 1]), torch.tensor([-0.5, 0.5])),
- ([0, 1], torch.tensor([-0.5, 0.5])),
- (torch.tensor([0, 1]), torch.tensor([-0.5, 1])),
- (torch.tensor([0, 1]), torch.tensor([-1, 0.5])),
- (torch.tensor([0, 1]), [-0.5, 0.5]),
- ])
+ batch_size=batch_size,
+ thresholds=thresholds.to(device=device, dtype=dtype),
+ additions=additions.to(device=device, dtype=dtype),
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'thresholds,additions', [
+ (torch.tensor([0, 2]), torch.tensor([-0.5, 0.5])),
+ (torch.tensor([-1, 1]), torch.tensor([-0.5, 0.5])),
+ ([0, 1], torch.tensor([-0.5, 0.5])),
+ (torch.tensor([0, 1]), torch.tensor([-0.5, 1])),
+ (torch.tensor([0, 1]), torch.tensor([-1, 0.5])),
+ (torch.tensor([0, 1]), [-0.5, 0.5]),
+ ]
+ )
def test_invalid_param_combinations(self, thresholds, additions, device, dtype):
with pytest.raises(Exception):
random_solarize_generator(
- batch_size=batch_size, thresholds=thresholds.to(device=device, dtype=dtype),
- additions=additions.to(device=device, dtype=dtype))
+ batch_size=batch_size,
+ thresholds=thresholds.to(device=device, dtype=dtype),
+ additions=additions.to(device=device, dtype=dtype)
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
res = random_solarize_generator(
- batch_size=batch_size, thresholds=torch.tensor([0, 1], device=device, dtype=dtype),
- additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype), same_on_batch=False)
+ batch_size=batch_size,
+ thresholds=torch.tensor([0, 1], device=device, dtype=dtype),
+ additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype),
+ same_on_batch=False
+ )
expected = dict(
thresholds_factor=torch.tensor(
- [0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype),
+ [0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype
+ ),
additions_factor=torch.tensor(
- [0.4408, -0.3668, 0.4346, 0.0936, 0.3694, 0.0677, 0.2411, -0.0706], device=device, dtype=dtype),
+ [0.4408, -0.3668, 0.4346, 0.0936, 0.3694, 0.0677, 0.2411, -0.0706], device=device, dtype=dtype
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['thresholds_factor'], expected['thresholds_factor'], rtol=1e-4, atol=1e-4)
@@ -843,13 +888,18 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 8
res = random_solarize_generator(
- batch_size=batch_size, thresholds=torch.tensor([0, 1], device=device, dtype=dtype),
- additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype), same_on_batch=True)
+ batch_size=batch_size,
+ thresholds=torch.tensor([0, 1], device=device, dtype=dtype),
+ additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype),
+ same_on_batch=True
+ )
expected = dict(
thresholds_factor=torch.tensor(
- [0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype),
+ [0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype
+ ),
additions_factor=torch.tensor(
- [0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150], device=device, dtype=dtype),
+ [0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150], device=device, dtype=dtype
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['thresholds_factor'], expected['thresholds_factor'], rtol=1e-4, atol=1e-4)
@@ -863,28 +913,30 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, bits, same_on_batch, device, dtype):
random_posterize_generator(
- batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
+ batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch
+ )
- @pytest.mark.parametrize('bits', [
- (torch.tensor([-1, 1])),
- (torch.tensor([0, 9])),
- (torch.tensor([3])),
- ([0, 8]),
- ])
+ @pytest.mark.parametrize(
+ 'bits', [
+ (torch.tensor([-1, 1])),
+ (torch.tensor([0, 9])),
+ (torch.tensor([3])),
+ ([0, 8]),
+ ]
+ )
def test_invalid_param_combinations(self, bits, device, dtype):
with pytest.raises(Exception):
random_posterize_generator(
- batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
+ batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(9)
batch_size = 8
res = random_posterize_generator(
- batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=False)
- expected = dict(
- bits_factor=torch.tensor(
- [5, 2, 3, 6, 7, 7, 2, 7], device=device, dtype=torch.int32)
+ batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=False
)
+ expected = dict(bits_factor=torch.tensor([5, 2, 3, 6, 7, 7, 2, 7], device=device, dtype=torch.int32))
assert res.keys() == expected.keys()
assert_allclose(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
@@ -892,11 +944,9 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
torch.manual_seed(9)
batch_size = 8
res = random_posterize_generator(
- batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=True)
- expected = dict(
- bits_factor=torch.tensor(
- [5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32)
+ batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=True
)
+ expected = dict(bits_factor=torch.tensor([5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32))
assert res.keys() == expected.keys()
assert_allclose(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
@@ -908,7 +958,8 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, sharpness, same_on_batch, device, dtype):
random_sharpness_generator(
- batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
+ batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch
+ )
@pytest.mark.parametrize('sharpness', [
(torch.tensor([-1, 5])),
@@ -918,16 +969,18 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
def test_invalid_param_combinations(self, sharpness, device, dtype):
with pytest.raises(Exception):
random_sharpness_generator(
- batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
+ batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
res = random_sharpness_generator(
- batch_size=batch_size, sharpness=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=False)
+ batch_size=batch_size, sharpness=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=False
+ )
expected = dict(
- sharpness_factor=torch.tensor(
- [0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype)
+ sharpness_factor=torch.
+ tensor([0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)
@@ -936,10 +989,11 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 8
res = random_sharpness_generator(
- batch_size=batch_size, sharpness=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=True)
+ batch_size=batch_size, sharpness=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=True
+ )
expected = dict(
- sharpness_factor=torch.tensor(
- [0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype)
+ sharpness_factor=torch.
+ tensor([0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)
@@ -953,32 +1007,39 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, p, lambda_val, same_on_batch, device, dtype):
random_mixup_generator(
- batch_size=batch_size, p=p,
- lambda_val=lambda_val.to(
- device=device, dtype=dtype) if isinstance(lambda_val, (torch.Tensor)) else lambda_val,
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('lambda_val', [
- (torch.tensor([-1, 1])),
- (torch.tensor([0, 2])),
- (torch.tensor([0, 0.5, 1])),
- ([0., 1.]),
- ])
+ batch_size=batch_size,
+ p=p,
+ lambda_val=lambda_val.to(device=device, dtype=dtype) if isinstance(lambda_val,
+ (torch.Tensor)) else lambda_val,
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'lambda_val', [
+ (torch.tensor([-1, 1])),
+ (torch.tensor([0, 2])),
+ (torch.tensor([0, 0.5, 1])),
+ ([0., 1.]),
+ ]
+ )
def test_invalid_param_combinations(self, lambda_val, device, dtype):
with pytest.raises(Exception):
- random_mixup_generator(
- batch_size=8, lambda_val=lambda_val.to(device=device, dtype=dtype))
+ random_mixup_generator(batch_size=8, lambda_val=lambda_val.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
res = random_mixup_generator(
- batch_size=batch_size, p=0.5,
- lambda_val=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=False)
+ batch_size=batch_size,
+ p=0.5,
+ lambda_val=torch.tensor([0., 1.], device=device, dtype=dtype),
+ same_on_batch=False
+ )
expected = dict(
mixup_pairs=torch.tensor([6, 1, 0, 7, 2, 5, 3, 4], device=device, dtype=torch.long),
mixup_lambdas=torch.tensor(
- [0.0000, 0.0000, 0.5739, 0.0000, 0.6274, 0.0000, 0.4414, 0.0000], device=device, dtype=dtype)
+ [0.0000, 0.0000, 0.5739, 0.0000, 0.6274, 0.0000, 0.4414, 0.0000], device=device, dtype=dtype
+ )
)
assert res.keys() == expected.keys()
assert_allclose(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
@@ -988,12 +1049,16 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
torch.manual_seed(9)
batch_size = 8
res = random_mixup_generator(
- batch_size=batch_size, p=.9999,
- lambda_val=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=True)
+ batch_size=batch_size,
+ p=.9999,
+ lambda_val=torch.tensor([0., 1.], device=device, dtype=dtype),
+ same_on_batch=True
+ )
expected = dict(
mixup_pairs=torch.tensor([4, 6, 7, 5, 0, 1, 3, 2], device=device, dtype=torch.long),
mixup_lambdas=torch.tensor(
- [0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804], device=device, dtype=dtype)
+ [0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804], device=device, dtype=dtype
+ )
)
assert res.keys() == expected.keys()
assert_allclose(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
@@ -1013,47 +1078,61 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
self, batch_size, p, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype
):
random_cutmix_generator(
- batch_size=batch_size, p=p, width=width, height=height, num_mix=num_mix,
+ batch_size=batch_size,
+ p=p,
+ width=width,
+ height=height,
+ num_mix=num_mix,
beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (torch.Tensor)) else beta,
cut_size=cut_size.to(device=device, dtype=dtype) if isinstance(cut_size, (torch.Tensor)) else cut_size,
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('width,height,num_mix,beta,cut_size', [
- (200, -200, 1, None, None),
- (-200, 200, 1, None, None),
- (200, 200, 0, None, None),
- (200, 200, 1.5, None, None),
- (200, 200, 1, torch.tensor([0., 1.]), None),
- (200, 200, 1, None, torch.tensor([-1., 1.])),
- (200, 200, 1, None, torch.tensor([0., 2.])),
- ])
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'width,height,num_mix,beta,cut_size', [
+ (200, -200, 1, None, None),
+ (-200, 200, 1, None, None),
+ (200, 200, 0, None, None),
+ (200, 200, 1.5, None, None),
+ (200, 200, 1, torch.tensor([0., 1.]), None),
+ (200, 200, 1, None, torch.tensor([-1., 1.])),
+ (200, 200, 1, None, torch.tensor([0., 2.])),
+ ]
+ )
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_invalid_param_combinations(self, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype):
with pytest.raises(Exception):
random_cutmix_generator(
- batch_size=8, p=0.5, width=width, height=height, num_mix=num_mix,
+ batch_size=8,
+ p=0.5,
+ width=width,
+ height=height,
+ num_mix=num_mix,
beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (torch.Tensor)) else beta,
cut_size=beta.to(device=device, dtype=dtype) if isinstance(cut_size, (torch.Tensor)) else cut_size,
- same_on_batch=same_on_batch)
+ same_on_batch=same_on_batch
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
res = random_cutmix_generator(
- batch_size=batch_size, width=200, height=200, p=0.5, num_mix=1,
+ batch_size=batch_size,
+ width=200,
+ height=200,
+ p=0.5,
+ num_mix=1,
beta=torch.tensor(1., device=device, dtype=dtype),
- cut_size=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=False)
+ cut_size=torch.tensor([0., 1.], device=device, dtype=dtype),
+ same_on_batch=False
+ )
expected = dict(
mix_pairs=torch.tensor([[0, 1]], device=device, dtype=torch.long),
- crop_src=torch.tensor([[
- [[71, 108],
- [70, 108],
- [70, 107],
- [71, 107]],
- [[39, 1],
- [38, 1],
- [38, 0],
- [39, 0]]]], device=device, dtype=dtype)
+ crop_src=torch.tensor(
+ [[[[71, 108], [70, 108], [70, 107], [71, 107]], [[39, 1], [38, 1], [38, 0], [39, 0]]]],
+ device=device,
+ dtype=dtype
+ )
)
assert res.keys() == expected.keys()
assert_allclose(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
@@ -1063,20 +1142,22 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 2
res = random_cutmix_generator(
- batch_size=batch_size, width=200, height=200, p=0.5, num_mix=1,
+ batch_size=batch_size,
+ width=200,
+ height=200,
+ p=0.5,
+ num_mix=1,
beta=torch.tensor(1., device=device, dtype=dtype),
- cut_size=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=True)
+ cut_size=torch.tensor([0., 1.], device=device, dtype=dtype),
+ same_on_batch=True
+ )
expected = dict(
mix_pairs=torch.tensor([[1, 0]], device=device, dtype=torch.long),
- crop_src=torch.tensor([[
- [[114, 53],
- [113, 53],
- [113, 52],
- [114, 52]],
- [[114, 53],
- [113, 53],
- [113, 52],
- [114, 52]]]], device=device, dtype=dtype)
+ crop_src=torch.tensor(
+ [[[[114, 53], [113, 53], [113, 52], [114, 52]], [[114, 53], [113, 53], [113, 52], [114, 52]]]],
+ device=device,
+ dtype=dtype
+ )
)
assert res.keys() == expected.keys()
assert_allclose(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
diff --git a/test/augmentation/test_random_generator_3d.py b/test/augmentation/test_random_generator_3d.py
index 73bd1e563..02c5673de 100644
--- a/test/augmentation/test_random_generator_3d.py
+++ b/test/augmentation/test_random_generator_3d.py
@@ -37,62 +37,69 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
self, depth, height, width, distortion_scale, batch_size, same_on_batch, device, dtype
):
random_perspective_generator3d(
- batch_size=batch_size, depth=depth, height=height, width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('depth,height,width,distortion_scale', [
- # Should be failed if distortion_scale > 1. or distortion_scale < 0.
- (-100, 100, 100, torch.tensor(0.5)),
- (100, -100, 100, torch.tensor(0.5)),
- (100, 100, -100, torch.tensor(-0.5)),
- (100, 100, 100, torch.tensor(1.5)),
- (100, 100, 100, torch.tensor([0., 0.5])),
- ])
+ batch_size=batch_size,
+ depth=depth,
+ height=height,
+ width=width,
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype),
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'depth,height,width,distortion_scale',
+ [
+ # Should be failed if distortion_scale > 1. or distortion_scale < 0.
+ (-100, 100, 100, torch.tensor(0.5)),
+ (100, -100, 100, torch.tensor(0.5)),
+ (100, 100, -100, torch.tensor(-0.5)),
+ (100, 100, 100, torch.tensor(1.5)),
+ (100, 100, 100, torch.tensor([0., 0.5])),
+ ]
+ )
def test_invalid_param_combinations(self, depth, height, width, distortion_scale, device, dtype):
with pytest.raises(Exception):
random_perspective_generator3d(
- batch_size=8, height=height, width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype))
+ batch_size=8,
+ height=height,
+ width=width,
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype)
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- res = random_perspective_generator3d(
- batch_size, 200, 200, 200, torch.tensor(0.5, device=device, dtype=dtype))
+ res = random_perspective_generator3d(batch_size, 200, 200, 200, torch.tensor(0.5, device=device, dtype=dtype))
expected = dict(
- start_points=torch.tensor([[[0., 0., 0.],
- [199., 0., 0.],
- [199., 199., 0.],
- [0., 199., 0.],
- [0., 0., 199.],
- [199., 0., 199.],
- [199., 199., 199.],
- [0., 199., 199.]],
- [[0., 0., 0.],
- [199., 0., 0.],
- [199., 199., 0.],
- [0., 199., 0.],
- [0., 0., 199.],
- [199., 0., 199.],
- [199., 199., 199.],
- [0., 199., 199.]]], device=device, dtype=dtype),
+ start_points=torch.tensor(
+ [
+ [
+ [0., 0., 0.], [199., 0., 0.], [199., 199., 0.], [0., 199., 0.], [0., 0., 199.],
+ [199., 0., 199.], [199., 199., 199.], [0., 199., 199.]
+ ],
+ [
+ [0., 0., 0.], [199., 0., 0.], [199., 199., 0.], [0., 199., 0.], [0., 0., 199.],
+ [199., 0., 199.], [199., 199., 199.], [0., 199., 199.]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ),
end_points=torch.tensor(
- [[[44.1135, 45.7502, 19.1432],
- [151.0347, 19.5224, 30.0448],
- [186.1714, 159.3179, 47.0386],
- [6.6593, 152.2701, 29.6790],
- [43.4702, 28.3858, 161.9453],
- [177.5298, 44.2721, 170.3048],
- [185.6710, 167.6275, 185.5184],
- [22.0682, 184.1540, 157.4157]],
- [[5.2657, 13.4747, 17.9406],
- [189.0318, 27.3596, 0.3080],
- [151.4223, 195.2367, 44.3007],
- [29.1605, 182.1176, 40.4487],
- [28.8963, 45.1991, 171.2670],
- [181.8843, 31.7171, 180.7795],
- [163.4786, 151.6794, 159.5485],
- [14.0707, 159.5684, 169.5268]]], device=device, dtype=dtype),
+ [
+ [
+ [44.1135, 45.7502, 19.1432], [151.0347, 19.5224, 30.0448], [186.1714, 159.3179, 47.0386],
+ [6.6593, 152.2701, 29.6790], [43.4702, 28.3858, 161.9453], [177.5298, 44.2721, 170.3048],
+ [185.6710, 167.6275, 185.5184], [22.0682, 184.1540, 157.4157]
+ ],
+ [
+ [5.2657, 13.4747, 17.9406], [189.0318, 27.3596, 0.3080], [151.4223, 195.2367, 44.3007],
+ [29.1605, 182.1176, 40.4487], [28.8963, 45.1991, 171.2670], [181.8843, 31.7171, 180.7795],
+ [163.4786, 151.6794, 159.5485], [14.0707, 159.5684, 169.5268]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)
@@ -102,41 +109,39 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 2
res = random_perspective_generator3d(
- batch_size, 200, 200, 200, torch.tensor(0.5, device=device, dtype=dtype), same_on_batch=True)
+ batch_size, 200, 200, 200, torch.tensor(0.5, device=device, dtype=dtype), same_on_batch=True
+ )
expected = dict(
- start_points=torch.tensor([[[0., 0., 0.],
- [199., 0., 0.],
- [199., 199., 0.],
- [0., 199., 0.],
- [0., 0., 199.],
- [199., 0., 199.],
- [199., 199., 199.],
- [0., 199., 199.]],
- [[0., 0., 0.],
- [199., 0., 0.],
- [199., 199., 0.],
- [0., 199., 0.],
- [0., 0., 199.],
- [199., 0., 199.],
- [199., 199., 199.],
- [0., 199., 199.]]], device=device, dtype=dtype),
+ start_points=torch.tensor(
+ [
+ [
+ [0., 0., 0.], [199., 0., 0.], [199., 199., 0.], [0., 199., 0.], [0., 0., 199.],
+ [199., 0., 199.], [199., 199., 199.], [0., 199., 199.]
+ ],
+ [
+ [0., 0., 0.], [199., 0., 0.], [199., 199., 0.], [0., 199., 0.], [0., 0., 199.],
+ [199., 0., 199.], [199., 199., 199.], [0., 199., 199.]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ),
end_points=torch.tensor(
- [[[44.1135, 45.7502, 19.1432],
- [151.0347, 19.5224, 30.0448],
- [186.1714, 159.3179, 47.0386],
- [6.6593, 152.2701, 29.6790],
- [43.4702, 28.3858, 161.9453],
- [177.5298, 44.2721, 170.3048],
- [185.6710, 167.6275, 185.5184],
- [22.0682, 184.1540, 157.4157]],
- [[44.1135, 45.7502, 19.1432],
- [151.0347, 19.5224, 30.0448],
- [186.1714, 159.3179, 47.0386],
- [6.6593, 152.2701, 29.6790],
- [43.4702, 28.3858, 161.9453],
- [177.5298, 44.2721, 170.3048],
- [185.6710, 167.6275, 185.5184],
- [22.0682, 184.1540, 157.4157]]], device=device, dtype=dtype)
+ [
+ [
+ [44.1135, 45.7502, 19.1432], [151.0347, 19.5224, 30.0448], [186.1714, 159.3179, 47.0386],
+ [6.6593, 152.2701, 29.6790], [43.4702, 28.3858, 161.9453], [177.5298, 44.2721, 170.3048],
+ [185.6710, 167.6275, 185.5184], [22.0682, 184.1540, 157.4157]
+ ],
+ [
+ [44.1135, 45.7502, 19.1432], [151.0347, 19.5224, 30.0448], [186.1714, 159.3179, 47.0386],
+ [6.6593, 152.2701, 29.6790], [43.4702, 28.3858, 161.9453], [177.5298, 44.2721, 170.3048],
+ [185.6710, 167.6275, 185.5184], [22.0682, 184.1540, 157.4157]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)
@@ -156,36 +161,44 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
self, batch_size, depth, height, width, degrees, translate, scale, shear, same_on_batch, device, dtype
):
random_affine_generator3d(
- batch_size=batch_size, depth=depth, height=height, width=width,
+ batch_size=batch_size,
+ depth=depth,
+ height=height,
+ width=width,
degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
shears=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('depth,height,width,degrees,translate,scale,shear', [
- (-100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
- (100, -100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
- (100, 100, -100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
- (100, 100, 100, torch.tensor([0, 9]), None, None, None),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1]), None, None),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([[0.2, 0.2, 0.2]]), None),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([0.2]), None),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, torch.tensor([[20, 20, 30]])),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, torch.tensor([20])),
- ])
- def test_invalid_param_combinations(
- self, depth, height, width, degrees, translate, scale, shear, device, dtype
- ):
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'depth,height,width,degrees,translate,scale,shear', [
+ (-100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
+ (100, -100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
+ (100, 100, -100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
+ (100, 100, 100, torch.tensor([0, 9]), None, None, None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1]), None, None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([[0.2, 0.2, 0.2]]), None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([0.2]), None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, torch.tensor([[20, 20, 30]])),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, torch.tensor([20])),
+ ]
+ )
+ def test_invalid_param_combinations(self, depth, height, width, degrees, translate, scale, shear, device, dtype):
with pytest.raises(Exception):
random_affine_generator3d(
- batch_size=8, depth=depth, height=height, width=width,
+ batch_size=8,
+ depth=depth,
+ height=height,
+ width=width,
degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shears=shear.to(device=device, dtype=dtype) if shear is not None else None)
+ shears=shear.to(device=device, dtype=dtype) if shear is not None else None
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -194,20 +207,22 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
scale = torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]])
shear = torch.tensor([[0, 20], [0, 20], [0, 20], [0, 20], [0, 20], [0, 20]])
res = random_affine_generator3d(
- batch_size=2, depth=200, height=200, width=200,
+ batch_size=2,
+ depth=200,
+ height=200,
+ width=200,
degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shears=shear.to(device=device, dtype=dtype) if shear is not None else None)
+ shears=shear.to(device=device, dtype=dtype) if shear is not None else None
+ )
expected = dict(
translations=torch.tensor(
- [[14.7762, 9.6438, 15.4177], [2.7086, -2.8238, 2.9562]], device=device, dtype=dtype),
- center=torch.tensor(
- [[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),
- scale=torch.tensor(
- [[0.8283, 1.1704, 1.1673], [1.0968, 0.7666, 0.9968]], device=device, dtype=dtype),
- angles=torch.tensor(
- [[18.8227, 13.8286, 13.9045], [19.1500, 19.5931, 16.0090]], device=device, dtype=dtype),
+ [[14.7762, 9.6438, 15.4177], [2.7086, -2.8238, 2.9562]], device=device, dtype=dtype
+ ),
+ center=torch.tensor([[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),
+ scale=torch.tensor([[0.8283, 1.1704, 1.1673], [1.0968, 0.7666, 0.9968]], device=device, dtype=dtype),
+ angles=torch.tensor([[18.8227, 13.8286, 13.9045], [19.1500, 19.5931, 16.0090]], device=device, dtype=dtype),
sxy=torch.tensor([5.3316, 12.5490], device=device, dtype=dtype),
sxz=torch.tensor([5.3926, 8.8273], device=device, dtype=dtype),
syx=torch.tensor([5.9384, 16.6337], device=device, dtype=dtype),
@@ -234,21 +249,23 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
scale = torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]])
shear = torch.tensor([[0, 20], [0, 20], [0, 20], [0, 20], [0, 20], [0, 20]])
res = random_affine_generator3d(
- batch_size=2, depth=200, height=200, width=200,
+ batch_size=2,
+ depth=200,
+ height=200,
+ width=200,
degrees=degrees.to(device=device, dtype=dtype),
translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
shears=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=True)
+ same_on_batch=True
+ )
expected = dict(
translations=torch.tensor(
- [[-9.7371, 11.7457, 17.6309], [-9.7371, 11.7457, 17.6309]], device=device, dtype=dtype),
- center=torch.tensor(
- [[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),
- scale=torch.tensor(
- [[1.1797, 0.8952, 1.0004], [1.1797, 0.8952, 1.0004]], device=device, dtype=dtype),
- angles=torch.tensor(
- [[18.8227, 19.1500, 13.8286], [18.8227, 19.1500, 13.8286]], device=device, dtype=dtype),
+ [[-9.7371, 11.7457, 17.6309], [-9.7371, 11.7457, 17.6309]], device=device, dtype=dtype
+ ),
+ center=torch.tensor([[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),
+ scale=torch.tensor([[1.1797, 0.8952, 1.0004], [1.1797, 0.8952, 1.0004]], device=device, dtype=dtype),
+ angles=torch.tensor([[18.8227, 19.1500, 13.8286], [18.8227, 19.1500, 13.8286]], device=device, dtype=dtype),
sxy=torch.tensor([2.6637, 2.6637], device=device, dtype=dtype),
sxz=torch.tensor([18.6920, 18.6920], device=device, dtype=dtype),
syx=torch.tensor([11.8716, 11.8716], device=device, dtype=dtype),
@@ -276,24 +293,27 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, degrees, same_on_batch, device, dtype):
random_rotation_generator3d(
- batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('degrees', [
- (torch.tensor(10)),
- (torch.tensor([10])),
- (torch.tensor([[0, 30]])),
- (torch.tensor([[0, 30], [0, 30]])),
- ])
+ batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'degrees', [
+ (torch.tensor(10)),
+ (torch.tensor([10])),
+ (torch.tensor([[0, 30]])),
+ (torch.tensor([[0, 30], [0, 30]])),
+ ]
+ )
def test_invalid_param_combinations(self, degrees, device, dtype):
with pytest.raises(Exception):
- random_rotation_generator3d(
- batch_size=8, degrees=degrees.to(device=device, dtype=dtype))
+ random_rotation_generator3d(batch_size=8, degrees=degrees.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
degrees = torch.tensor([[0, 30], [0, 30], [0, 30]])
res = random_rotation_generator3d(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False)
+ batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False
+ )
expected = dict(
yaw=torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),
pitch=torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),
@@ -308,7 +328,8 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
torch.manual_seed(42)
degrees = torch.tensor([[0, 30], [0, 30], [0, 30]])
res = random_rotation_generator3d(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True)
+ batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True
+ )
expected = dict(
yaw=torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),
pitch=torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),
@@ -327,70 +348,71 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
@pytest.mark.parametrize('size', [(100, 100, 100), torch.tensor([50, 60, 70])])
@pytest.mark.parametrize('resize_to', [None, (100, 100, 100)])
@pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(
- self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype
- ):
+ def test_valid_param_combinations(self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype):
if isinstance(size, torch.Tensor):
size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)
random_crop_generator3d(
- batch_size=batch_size, input_size=input_size,
+ batch_size=batch_size,
+ input_size=input_size,
size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
resize_to=resize_to,
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('input_size,size,resize_to', [
- ((-300, 300, 300), (200, 200, 200), (100, 100, 100)),
- ((100, 100, 100), (200, 200, 200), (100, 100, 100)),
- ((200, 200, 200), torch.tensor([50, 50, 50]), (100, 100, 100)),
- ((100, 100, 100), torch.tensor([[50, 60, 70], [50, 60, 70]]), (100, 100)),
- ])
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'input_size,size,resize_to', [
+ ((-300, 300, 300), (200, 200, 200), (100, 100, 100)),
+ ((100, 100, 100), (200, 200, 200), (100, 100, 100)),
+ ((200, 200, 200), torch.tensor([50, 50, 50]), (100, 100, 100)),
+ ((100, 100, 100), torch.tensor([[50, 60, 70], [50, 60, 70]]), (100, 100)),
+ ]
+ )
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
with pytest.raises(Exception):
random_crop_generator3d(
- batch_size=2, input_size=input_size,
+ batch_size=2,
+ input_size=input_size,
size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
- resize_to=resize_to)
+ resize_to=resize_to
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
res = random_crop_generator3d(
- batch_size=2, input_size=(200, 200, 200),
+ batch_size=2,
+ input_size=(200, 200, 200),
size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype),
- resize_to=(100, 100, 100))
+ resize_to=(100, 100, 100)
+ )
expected = dict(
src=torch.tensor(
- [[[115, 53, 58],
- [184, 53, 58],
- [184, 112, 58],
- [115, 112, 58],
- [115, 53, 107],
- [184, 53, 107],
- [184, 112, 107],
- [115, 112, 107]],
- [[119, 135, 90],
- [188, 135, 90],
- [188, 194, 90],
- [119, 194, 90],
- [119, 135, 139],
- [188, 135, 139],
- [188, 194, 139],
- [119, 194, 139]]], device=device, dtype=dtype),
- dst=torch.tensor([[[0, 0, 0],
- [99, 0, 0],
- [99, 99, 0],
- [0, 99, 0],
- [0, 0, 99],
- [99, 0, 99],
- [99, 99, 99],
- [0, 99, 99]],
- [[0, 0, 0],
- [99, 0, 0],
- [99, 99, 0],
- [0, 99, 0],
- [0, 0, 99],
- [99, 0, 99],
- [99, 99, 99],
- [0, 99, 99]]], device=device, dtype=dtype),
+ [
+ [
+ [115, 53, 58], [184, 53, 58], [184, 112, 58], [115, 112, 58], [115, 53, 107], [184, 53, 107],
+ [184, 112, 107], [115, 112, 107]
+ ],
+ [
+ [119, 135, 90], [188, 135, 90], [188, 194, 90], [119, 194, 90], [119, 135, 139],
+ [188, 135, 139], [188, 194, 139], [119, 194, 139]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ),
+ dst=torch.tensor(
+ [
+ [
+ [0, 0, 0], [99, 0, 0], [99, 99, 0], [0, 99, 0], [0, 0, 99], [99, 0, 99], [99, 99, 99],
+ [0, 99, 99]
+ ],
+ [
+ [0, 0, 0], [99, 0, 0], [99, 99, 0], [0, 99, 0], [0, 0, 99], [99, 0, 99], [99, 99, 99],
+ [0, 99, 99]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'], expected['src'], atol=1e-4, rtol=1e-4)
@@ -399,43 +421,41 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
res = random_crop_generator3d(
- batch_size=2, input_size=(200, 200, 200),
+ batch_size=2,
+ input_size=(200, 200, 200),
size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype),
- resize_to=(100, 100, 100), same_on_batch=True)
+ resize_to=(100, 100, 100),
+ same_on_batch=True
+ )
expected = dict(
src=torch.tensor(
- [[[115, 129, 57],
- [184, 129, 57],
- [184, 188, 57],
- [115, 188, 57],
- [115, 129, 106],
- [184, 129, 106],
- [184, 188, 106],
- [115, 188, 106]],
- [[115, 129, 57],
- [184, 129, 57],
- [184, 188, 57],
- [115, 188, 57],
- [115, 129, 106],
- [184, 129, 106],
- [184, 188, 106],
- [115, 188, 106]]], device=device, dtype=dtype),
- dst=torch.tensor([[[0, 0, 0],
- [99, 0, 0],
- [99, 99, 0],
- [0, 99, 0],
- [0, 0, 99],
- [99, 0, 99],
- [99, 99, 99],
- [0, 99, 99]],
- [[0, 0, 0],
- [99, 0, 0],
- [99, 99, 0],
- [0, 99, 0],
- [0, 0, 99],
- [99, 0, 99],
- [99, 99, 99],
- [0, 99, 99]]], device=device, dtype=dtype),
+ [
+ [
+ [115, 129, 57], [184, 129, 57], [184, 188, 57], [115, 188, 57], [115, 129, 106],
+ [184, 129, 106], [184, 188, 106], [115, 188, 106]
+ ],
+ [
+ [115, 129, 57], [184, 129, 57], [184, 188, 57], [115, 188, 57], [115, 129, 106],
+ [184, 129, 106], [184, 188, 106], [115, 188, 106]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ),
+ dst=torch.tensor(
+ [
+ [
+ [0, 0, 0], [99, 0, 0], [99, 99, 0], [0, 99, 0], [0, 0, 99], [99, 0, 99], [99, 99, 99],
+ [0, 99, 99]
+ ],
+ [
+ [0, 0, 0], [99, 0, 0], [99, 99, 0], [0, 99, 0], [0, 0, 99], [99, 0, 99], [99, 99, 99],
+ [0, 99, 99]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'], expected['src'], atol=1e-4, rtol=1e-4)
@@ -447,45 +467,46 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('depth,height,width', [(200, 200, 200)])
@pytest.mark.parametrize('size', [(100, 100, 100)])
- def test_valid_param_combinations(
- self, batch_size, depth, height, width, size, device, dtype
- ):
+ def test_valid_param_combinations(self, batch_size, depth, height, width, size, device, dtype):
center_crop_generator3d(batch_size=batch_size, depth=depth, height=height, width=width, size=size)
- @pytest.mark.parametrize('depth,height,width,size', [
- (200, 200, -200, (100, 100, 100)),
- (200, -200, 200, (100, 100)),
- (200, 100, 100, (300, 120, 100)),
- (200, 150, 100, (120, 180, 100)),
- (200, 100, 150, (120, 80, 200)),
- ])
+ @pytest.mark.parametrize(
+ 'depth,height,width,size', [
+ (200, 200, -200, (100, 100, 100)),
+ (200, -200, 200, (100, 100)),
+ (200, 100, 100, (300, 120, 100)),
+ (200, 150, 100, (120, 180, 100)),
+ (200, 100, 150, (120, 80, 200)),
+ ]
+ )
def test_invalid_param_combinations(self, depth, height, width, size, device, dtype):
with pytest.raises(Exception):
- center_crop_generator3d(
- batch_size=2, depth=depth, height=height, width=width, size=size)
+ center_crop_generator3d(batch_size=2, depth=depth, height=height, width=width, size=size)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
res = center_crop_generator3d(batch_size=2, depth=200, height=200, width=200, size=(120, 150, 100))
expected = dict(
- src=torch.tensor([
- [[50, 25, 40],
- [149, 25, 40],
- [149, 174, 40],
- [50, 174, 40],
- [50, 25, 159],
- [149, 25, 159],
- [149, 174, 159],
- [50, 174, 159]]], device=device, dtype=torch.long).repeat(2, 1, 1),
- dst=torch.tensor([
- [[0, 0, 0],
- [99, 0, 0],
- [99, 149, 0],
- [0, 149, 0],
- [0, 0, 119],
- [99, 0, 119],
- [99, 149, 119],
- [0, 149, 119]]], device=device, dtype=torch.long).repeat(2, 1, 1),
+ src=torch.tensor(
+ [
+ [
+ [50, 25, 40], [149, 25, 40], [149, 174, 40], [50, 174, 40], [50, 25, 159], [149, 25, 159],
+ [149, 174, 159], [50, 174, 159]
+ ]
+ ],
+ device=device,
+ dtype=torch.long
+ ).repeat(2, 1, 1),
+ dst=torch.tensor(
+ [
+ [
+ [0, 0, 0], [99, 0, 0], [99, 149, 0], [0, 149, 0], [0, 0, 119], [99, 0, 119], [99, 149, 119],
+ [0, 149, 119]
+ ]
+ ],
+ device=device,
+ dtype=torch.long
+ ).repeat(2, 1, 1),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'].to(device=device), expected['src'], atol=1e-4, rtol=1e-4)
@@ -504,36 +525,47 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, kernel_size, angle, direction, same_on_batch, device, dtype):
random_motion_blur_generator3d(
- batch_size=batch_size, kernel_size=kernel_size,
+ batch_size=batch_size,
+ kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch)
-
- @pytest.mark.parametrize('kernel_size,angle,direction', [
- (4, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
- (1, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
- ((3, 4, 5), torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
- (3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-2, 1])),
- (3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 2])),
- ])
+ same_on_batch=same_on_batch
+ )
+
+ @pytest.mark.parametrize(
+ 'kernel_size,angle,direction', [
+ (4, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
+ (1, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
+ ((3, 4, 5), torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
+ (3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-2, 1])),
+ (3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 2])),
+ ]
+ )
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
with pytest.raises(Exception):
random_motion_blur_generator3d(
- batch_size=8, kernel_size=kernel_size, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype))
+ batch_size=8,
+ kernel_size=kernel_size,
+ angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype)
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
angle = torch.tensor([(10, 30), (30, 60), (60, 90)])
direction = torch.tensor([-1, 1])
res = random_motion_blur_generator3d(
- batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype), same_on_batch=False)
+ batch_size=2,
+ kernel_size=3,
+ angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype),
+ same_on_batch=False
+ )
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
- angle_factor=torch.tensor([
- [27.6454, 41.4859, 71.7134],
- [28.3001, 58.7792, 78.0269]], device=device, dtype=dtype),
+ angle_factor=torch.tensor(
+ [[27.6454, 41.4859, 71.7134], [28.3001, 58.7792, 78.0269]], device=device, dtype=dtype
+ ),
direction_factor=torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
@@ -546,13 +578,17 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
angle = torch.tensor([(10, 30), (30, 60), (60, 90)])
direction = torch.tensor([-1, 1])
res = random_motion_blur_generator3d(
- batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype), same_on_batch=True)
+ batch_size=2,
+ kernel_size=3,
+ angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype),
+ same_on_batch=True
+ )
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
- angle_factor=torch.tensor([
- [27.6454, 57.4501, 71.4859],
- [27.6454, 57.4501, 71.4859]], device=device, dtype=dtype),
+ angle_factor=torch.tensor(
+ [[27.6454, 57.4501, 71.4859], [27.6454, 57.4501, 71.4859]], device=device, dtype=dtype
+ ),
direction_factor=torch.tensor([0.9186, 0.9186], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
diff --git a/test/augmentation/test_transformation_matrix.py b/test/augmentation/test_transformation_matrix.py
index b949466eb..b18b1734d 100644
--- a/test/augmentation/test_transformation_matrix.py
+++ b/test/augmentation/test_transformation_matrix.py
@@ -15,28 +15,20 @@ from kornia.augmentation import ColorJitter
class TestHorizontalFlipFn:
def test_random_hflip(self, device):
- input = torch.tensor([[0., 0., 0., 0.],
- [0., 0., 0., 0.],
- [0., 0., 1., 2.]]) # 3 x 4
+ input = torch.tensor([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]]) # 3 x 4
input.to(device)
- expected_transform = torch.tensor([[-1., 0., 3.],
- [0., 1., 0.],
- [0., 0., 1.]]) # 3 x 3
+ expected_transform = torch.tensor([[-1., 0., 3.], [0., 1., 0.], [0., 0., 1.]]) # 3 x 3
assert (F.compute_hflip_transformation(input[None, None]) == expected_transform).all()
def test_batch_random_hflip(self, device):
batch_size = 5
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
+ input = torch.tensor([[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
input.to(device)
- expected_transform = torch.tensor([[[-1., 0., 2.],
- [0., 1., 0.],
- [0., 0., 1.]]]) # 1 x 3 x 3
+ expected_transform = torch.tensor([[[-1., 0., 2.], [0., 1., 0.], [0., 0., 1.]]]) # 1 x 3 x 3
input = input.repeat(batch_size, 3, 1, 1) # 5 x 3 x 3 x 3
expected_transform = expected_transform.repeat(batch_size, 1, 1) # 5 x 3 x 3
@@ -48,28 +40,20 @@ class TestVerticalFlipFn:
def test_random_vflip(self, device):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]) # 3 x 3
input.to(device)
- expected_transform = torch.tensor([[1., 0., 0.],
- [0., -1., 2.],
- [0., 0., 1.]]) # 3 x 3
+ expected_transform = torch.tensor([[1., 0., 0.], [0., -1., 2.], [0., 0., 1.]]) # 3 x 3
assert (F.compute_vflip_transformation(input[None, None]) == expected_transform).all()
def test_batch_random_vflip(self, device):
batch_size = 5
- input = torch.tensor([[[[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
+ input = torch.tensor([[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]) # 1 x 1 x 3 x 3
input.to(device)
- expected_transform = torch.tensor([[[1., 0., 0.],
- [0., -1., 2.],
- [0., 0., 1.]]]) # 1 x 3 x 3
+ expected_transform = torch.tensor([[[1., 0., 0.], [0., -1., 2.], [0., 0., 1.]]]) # 1 x 3 x 3
input = input.repeat(batch_size, 3, 1, 1) # 5 x 3 x 3 x 3
expected_transform = expected_transform.repeat(batch_size, 1, 1) # 5 x 3 x 3
diff --git a/test/color/test_gray.py b/test/color/test_gray.py
index a3f3c147e..ba0c42f4a 100644
--- a/test/color/test_gray.py
+++ b/test/color/test_gray.py
@@ -9,13 +9,13 @@ from torch.testing import assert_allclose
class TestRgbToGrayscale(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.rgb_to_grayscale(img), torch.Tensor)
- @pytest.mark.parametrize(
- "batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])
+ @pytest.mark.parametrize("batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])
def test_cardinality(self, device, dtype, batch_size, height, width):
img = torch.ones(batch_size, 3, height, width, device=device, dtype=dtype)
assert kornia.rgb_to_grayscale(img).shape == (batch_size, 1, height, width)
@@ -38,34 +38,48 @@ class TestRgbToGrayscale(BaseTester):
assert kornia.color.rgb_to_grayscale(img, rgb_weights=rgb_weights)
def test_opencv(self, device, dtype):
- data = torch.tensor([
- [[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]
- ], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
- expected = torch.tensor([[
- [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
- [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
- [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
- [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
- [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [0.4684734, 0.8954562, 0.6064363, 0.5236061, 0.6106016],
+ [0.1709944, 0.5133104, 0.7915002, 0.5745703, 0.1680204],
+ [0.5279005, 0.6092287, 0.3034387, 0.5333768, 0.6064113],
+ [0.3503858, 0.5720159, 0.7052018, 0.4558409, 0.3261529],
+ [0.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
img_gray = kornia.rgb_to_grayscale(data)
assert_allclose(img_gray, expected)
@@ -83,7 +97,7 @@ class TestRgbToGrayscale(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.rgb_to_grayscale, (img,), raise_exception=True)
+ assert gradcheck(kornia.rgb_to_grayscale, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -103,13 +117,13 @@ class TestRgbToGrayscale(BaseTester):
class TestBgrToGrayscale(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert kornia.bgr_to_grayscale(img) is not None
- @pytest.mark.parametrize(
- "batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])
+ @pytest.mark.parametrize("batch_size, height, width", [(1, 3, 4), (2, 2, 4), (3, 4, 1)])
def test_cardinality(self, device, dtype, batch_size, height, width):
img = torch.ones(batch_size, 3, height, width, device=device, dtype=dtype)
assert kornia.bgr_to_grayscale(img).shape == (batch_size, 1, height, width)
@@ -127,34 +141,48 @@ class TestBgrToGrayscale(BaseTester):
assert kornia.color.bgr_to_grayscale(img)
def test_opencv(self, device, dtype):
- data = torch.tensor([
- [[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
-
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
-
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]
- ], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
- expected = torch.tensor([[
- [0.4485849, 0.8233618, 0.6262833, 0.6218331, 0.6341921],
- [0.3200093, 0.4340172, 0.7107211, 0.5454938, 0.2801398],
- [0.6149265, 0.7018101, 0.3503231, 0.4891168, 0.5292346],
- [0.5096100, 0.4336508, 0.6704276, 0.4525143, 0.2134447],
- [0.7878902, 0.6494595, 0.5211386, 0.6623823, 0.6660464],
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [0.4485849, 0.8233618, 0.6262833, 0.6218331, 0.6341921],
+ [0.3200093, 0.4340172, 0.7107211, 0.5454938, 0.2801398],
+ [0.6149265, 0.7018101, 0.3503231, 0.4891168, 0.5292346],
+ [0.5096100, 0.4336508, 0.6704276, 0.4525143, 0.2134447],
+ [0.7878902, 0.6494595, 0.5211386, 0.6623823, 0.6660464],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
img_gray = kornia.bgr_to_grayscale(data)
assert_allclose(img_gray, expected)
@@ -163,7 +191,7 @@ class TestBgrToGrayscale(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.bgr_to_grayscale, (img,), raise_exception=True)
+ assert gradcheck(kornia.bgr_to_grayscale, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_hls.py b/test/color/test_hls.py
index da0da49f9..6798b5c1e 100644
--- a/test/color/test_hls.py
+++ b/test/color/test_hls.py
@@ -10,13 +10,13 @@ from torch.testing import assert_allclose
class TestRgbToHls(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_hls(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_hls(img).shape == shape
@@ -34,42 +34,62 @@ class TestRgbToHls(BaseTester):
assert kornia.color.rgb_to_hls(img)
def test_unit(self, device, dtype):
- data = torch.tensor([
- [[0.4237059, 0.1935902, 0.8585021, 0.3790484, 0.1389151],
- [0.5933651, 0.0474544, 0.2801555, 0.1691061, 0.9221829],
- [0.2351739, 0.5852075, 0.5789326, 0.8411915, 0.5960411],
- [0.0290176, 0.6459382, 0.8581501, 0.4755400, 0.7735767],
- [0.9497226, 0.0919441, 0.5462211, 0.7836787, 0.6403612]],
- [[0.2280025, 0.1352853, 0.7999730, 0.6658246, 0.4910861],
- [0.3499791, 0.1250734, 0.6315800, 0.4785843, 0.8477826],
- [0.3646359, 0.2415122, 0.5301932, 0.0782518, 0.8710389],
- [0.6957581, 0.6162295, 0.6259052, 0.1753750, 0.6737530],
- [0.7678874, 0.9825978, 0.0234877, 0.2485284, 0.8159551]],
- [[0.7330830, 0.9015747, 0.0229067, 0.4280063, 0.5400181],
- [0.0037299, 0.3259412, 0.3467951, 0.9575506, 0.1525899],
- [0.9660432, 0.5287710, 0.6654660, 0.3797526, 0.4981400],
- [0.7422802, 0.9926301, 0.5334370, 0.7852844, 0.4397180],
- [0.2281681, 0.2560037, 0.5134379, 0.5800887, 0.8685090]]
- ], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0.4237059, 0.1935902, 0.8585021, 0.3790484, 0.1389151],
+ [0.5933651, 0.0474544, 0.2801555, 0.1691061, 0.9221829],
+ [0.2351739, 0.5852075, 0.5789326, 0.8411915, 0.5960411],
+ [0.0290176, 0.6459382, 0.8581501, 0.4755400, 0.7735767],
+ [0.9497226, 0.0919441, 0.5462211, 0.7836787, 0.6403612]
+ ],
+ [
+ [0.2280025, 0.1352853, 0.7999730, 0.6658246, 0.4910861],
+ [0.3499791, 0.1250734, 0.6315800, 0.4785843, 0.8477826],
+ [0.3646359, 0.2415122, 0.5301932, 0.0782518, 0.8710389],
+ [0.6957581, 0.6162295, 0.6259052, 0.1753750, 0.6737530],
+ [0.7678874, 0.9825978, 0.0234877, 0.2485284, 0.8159551]
+ ],
+ [
+ [0.7330830, 0.9015747, 0.0229067, 0.4280063, 0.5400181],
+ [0.0037299, 0.3259412, 0.3467951, 0.9575506, 0.1525899],
+ [0.9660432, 0.5287710, 0.6654660, 0.3797526, 0.4981400],
+ [0.7422802, 0.9926301, 0.5334370, 0.7852844, 0.4397180],
+ [0.2281681, 0.2560037, 0.5134379, 0.5800887, 0.8685090]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# OpenCV
- expected = torch.tensor([
- [[4.59454770, 4.26846900, 0.97384680, 2.27317070, 3.26934400],
- [0.61494170, 3.89691880, 2.29297200, 3.77774720, 0.94595980],
- [4.00329600, 5.40794320, 4.56610100, 5.86935100, 1.81946310],
- [3.20989560, 4.27144400, 0.29820946, 4.70416550, 0.73408560],
- [0.78329855, 2.28729030, 5.30166340, 5.63437900, 3.38281500]],
- [[0.48054275, 0.51843000, 0.44070444, 0.52243650, 0.33946657],
- [0.29854750, 0.18669781, 0.45586777, 0.56332830, 0.53738640],
- [0.60060860, 0.41335985, 0.59782960, 0.45972168, 0.68458940],
- [0.38564888, 0.80442977, 0.69579350, 0.48032972, 0.60664740],
- [0.58894540, 0.53727096, 0.28485440, 0.51610350, 0.75443510]],
- [[0.52553130, 0.79561585, 0.94802250, 0.30024928, 0.59078425],
- [0.98750657, 0.74582230, 0.38544560, 0.90278864, 0.83178820],
- [0.91497860, 0.41573380, 0.16817844, 0.82978433, 0.59113250],
- [0.92475650, 0.96231550, 0.53370523, 0.63488615, 0.42437580],
- [0.87768690, 0.96239233, 0.91754496, 0.55295944, 0.46453667]]
- ], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [4.59454770, 4.26846900, 0.97384680, 2.27317070, 3.26934400],
+ [0.61494170, 3.89691880, 2.29297200, 3.77774720, 0.94595980],
+ [4.00329600, 5.40794320, 4.56610100, 5.86935100, 1.81946310],
+ [3.20989560, 4.27144400, 0.29820946, 4.70416550, 0.73408560],
+ [0.78329855, 2.28729030, 5.30166340, 5.63437900, 3.38281500]
+ ],
+ [
+ [0.48054275, 0.51843000, 0.44070444, 0.52243650, 0.33946657],
+ [0.29854750, 0.18669781, 0.45586777, 0.56332830, 0.53738640],
+ [0.60060860, 0.41335985, 0.59782960, 0.45972168, 0.68458940],
+ [0.38564888, 0.80442977, 0.69579350, 0.48032972, 0.60664740],
+ [0.58894540, 0.53727096, 0.28485440, 0.51610350, 0.75443510]
+ ],
+ [
+ [0.52553130, 0.79561585, 0.94802250, 0.30024928, 0.59078425],
+ [0.98750657, 0.74582230, 0.38544560, 0.90278864, 0.83178820],
+ [0.91497860, 0.41573380, 0.16817844, 0.82978433, 0.59113250],
+ [0.92475650, 0.96231550, 0.53370523, 0.63488615, 0.42437580],
+ [0.87768690, 0.96239233, 0.91754496, 0.55295944, 0.46453667]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kornia.color.rgb_to_hls(data), expected)
@@ -77,11 +97,14 @@ class TestRgbToHls(BaseTester):
data = torch.ones(2, 3, 5, 5, device=device, dtype=dtype)
# OpenCV
- expected = torch.cat([
- torch.zeros(2, 1, 5, 5, device=device, dtype=dtype),
- torch.ones(2, 1, 5, 5, device=device, dtype=dtype),
- torch.zeros(2, 1, 5, 5, device=device, dtype=dtype)
- ], dim=1)
+ expected = torch.cat(
+ [
+ torch.zeros(2, 1, 5, 5, device=device, dtype=dtype),
+ torch.ones(2, 1, 5, 5, device=device, dtype=dtype),
+ torch.zeros(2, 1, 5, 5, device=device, dtype=dtype)
+ ],
+ dim=1
+ )
assert_allclose(kornia.color.rgb_to_hls(data), expected)
@@ -89,7 +112,7 @@ class TestRgbToHls(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_hls, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_hls, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -109,13 +132,13 @@ class TestRgbToHls(BaseTester):
class TestHlsToRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.hls_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.hls_to_rgb(img).shape == shape
@@ -133,44 +156,68 @@ class TestHlsToRgb(BaseTester):
assert kornia.color.hls_to_rgb(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[0.5513626, 0.8487718, 0.1822479, 0.2851745, 0.2669488],
- [0.7596772, 0.4565057, 0.6181599, 0.3852497, 0.7746902],
- [0.5742747, 0.1957062, 0.7530835, 0.2104362, 0.9449323],
- [0.9918052, 0.2437515, 0.4718738, 0.8502576, 0.1675640],
- [0.9210159, 0.0538564, 0.5801026, 0.6110542, 0.3768399]],
- [[0.4111853, 0.0183454, 0.7832276, 0.2975794, 0.1139528],
- [0.6207729, 0.1073406, 0.8335325, 0.5700451, 0.2594557],
- [0.7520493, 0.5097187, 0.4719872, 0.9477938, 0.1640292],
- [0.8973427, 0.6455371, 0.7567374, 0.3159562, 0.8135307],
- [0.0855004, 0.6645504, 0.9923756, 0.6209313, 0.2356791]],
- [[0.4734681, 0.0422099, 0.7405791, 0.9671807, 0.1793800],
- [0.8221875, 0.7219887, 0.3627397, 0.4403201, 0.0024084],
- [0.0803350, 0.9432759, 0.0241543, 0.8292291, 0.7745832],
- [0.3707901, 0.0851424, 0.5805428, 0.1098685, 0.4238486],
- [0.1058410, 0.0816052, 0.5792874, 0.9578886, 0.6281684]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [0.5513626, 0.8487718, 0.1822479, 0.2851745, 0.2669488],
+ [0.7596772, 0.4565057, 0.6181599, 0.3852497, 0.7746902],
+ [0.5742747, 0.1957062, 0.7530835, 0.2104362, 0.9449323],
+ [0.9918052, 0.2437515, 0.4718738, 0.8502576, 0.1675640],
+ [0.9210159, 0.0538564, 0.5801026, 0.6110542, 0.3768399]
+ ],
+ [
+ [0.4111853, 0.0183454, 0.7832276, 0.2975794, 0.1139528],
+ [0.6207729, 0.1073406, 0.8335325, 0.5700451, 0.2594557],
+ [0.7520493, 0.5097187, 0.4719872, 0.9477938, 0.1640292],
+ [0.8973427, 0.6455371, 0.7567374, 0.3159562, 0.8135307],
+ [0.0855004, 0.6645504, 0.9923756, 0.6209313, 0.2356791]
+ ],
+ [
+ [0.4734681, 0.0422099, 0.7405791, 0.9671807, 0.1793800],
+ [0.8221875, 0.7219887, 0.3627397, 0.4403201, 0.0024084],
+ [0.0803350, 0.9432759, 0.0241543, 0.8292291, 0.7745832],
+ [0.3707901, 0.0851424, 0.5805428, 0.1098685, 0.4238486],
+ [0.1058410, 0.0816052, 0.5792874, 0.9578886, 0.6281684]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
data[:, 0] = 2 * math.pi * data[:, 0]
# OpenCV
- expected = torch.tensor([[
- [[0.21650219, 0.01911971, 0.91374826, 0.17609520, 0.10979544],
- [0.65698080, 0.02984191, 0.77314806, 0.38072730, 0.25964087],
- [0.73213010, 0.81102980, 0.47240910, 0.96834683, 0.29108350],
- [0.93540700, 0.64780010, 0.61551300, 0.35066980, 0.89171433],
- [0.09454980, 0.69192480, 0.98795897, 0.25782573, 0.08763295]],
- [[0.48587522, 0.01757100, 0.94376480, 0.58539250, 0.13439366],
- [0.30897713, 0.18483935, 0.80829670, 0.75936294, 0.25883088],
- [0.75421450, 0.97218925, 0.46058673, 0.99108470, 0.03697497],
- [0.85927840, 0.67571700, 0.89796180, 0.28124255, 0.89256540],
- [0.07645091, 0.65486740, 0.99254686, 0.50014400, 0.38372523]],
- [[0.60586834, 0.01897625, 0.62269044, 0.00976634, 0.09351197],
- [0.93256867, 0.14439031, 0.89391685, 0.49867177, 0.26008060],
- [0.77196840, 0.04724807, 0.48338777, 0.90450300, 0.12093388],
- [0.86302150, 0.61535730, 0.85029656, 0.34361976, 0.73449594],
- [0.08502806, 0.63717590, 0.99679226, 0.98403690, 0.16492467]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.21650219, 0.01911971, 0.91374826, 0.17609520, 0.10979544],
+ [0.65698080, 0.02984191, 0.77314806, 0.38072730, 0.25964087],
+ [0.73213010, 0.81102980, 0.47240910, 0.96834683, 0.29108350],
+ [0.93540700, 0.64780010, 0.61551300, 0.35066980, 0.89171433],
+ [0.09454980, 0.69192480, 0.98795897, 0.25782573, 0.08763295]
+ ],
+ [
+ [0.48587522, 0.01757100, 0.94376480, 0.58539250, 0.13439366],
+ [0.30897713, 0.18483935, 0.80829670, 0.75936294, 0.25883088],
+ [0.75421450, 0.97218925, 0.46058673, 0.99108470, 0.03697497],
+ [0.85927840, 0.67571700, 0.89796180, 0.28124255, 0.89256540],
+ [0.07645091, 0.65486740, 0.99254686, 0.50014400, 0.38372523]
+ ],
+ [
+ [0.60586834, 0.01897625, 0.62269044, 0.00976634, 0.09351197],
+ [0.93256867, 0.14439031, 0.89391685, 0.49867177, 0.26008060],
+ [0.77196840, 0.04724807, 0.48338777, 0.90450300, 0.12093388],
+ [0.86302150, 0.61535730, 0.85029656, 0.34361976, 0.73449594],
+ [0.08502806, 0.63717590, 0.99679226, 0.98403690, 0.16492467]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
f = kornia.color.hls_to_rgb
assert_allclose(f(data), expected)
@@ -185,7 +232,7 @@ class TestHlsToRgb(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.hls_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.hls_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_hsv.py b/test/color/test_hsv.py
index 914bc080e..fc98a0a7a 100644
--- a/test/color/test_hsv.py
+++ b/test/color/test_hsv.py
@@ -10,13 +10,13 @@ from torch.testing import assert_allclose
class TestRgbToHsv(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_hsv(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_hsv(img).shape == shape
@@ -34,42 +34,62 @@ class TestRgbToHsv(BaseTester):
assert kornia.color.rgb_to_hsv(img)
def test_unit(self, device, dtype):
- data = torch.tensor([
- [[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
- [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
- [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
- [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
- [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]],
- [[0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
- [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
- [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
- [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
- [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]],
- [[0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
- [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
- [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
- [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
- [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]]
- ], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
+ [0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
+ [0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
+ [0.0086008, 0.8288748, 0.9647092, 0.8922020, 0.7614344],
+ [0.2898048, 0.1282895, 0.7621747, 0.5657831, 0.9918593]
+ ],
+ [
+ [0.5414237, 0.9962701, 0.8947155, 0.5900949, 0.9483274],
+ [0.0468036, 0.3933847, 0.8046577, 0.3640994, 0.0632100],
+ [0.6171775, 0.8624780, 0.4126036, 0.7600935, 0.7279997],
+ [0.4237089, 0.5365476, 0.5591233, 0.1523191, 0.1382165],
+ [0.8932794, 0.8517839, 0.7152701, 0.8983801, 0.5905426]
+ ],
+ [
+ [0.2869580, 0.4700376, 0.2743714, 0.8135023, 0.2229074],
+ [0.9306560, 0.3734594, 0.4566821, 0.7599275, 0.7557513],
+ [0.7415742, 0.6115875, 0.3317572, 0.0379378, 0.1315770],
+ [0.8692724, 0.0809556, 0.7767404, 0.8742208, 0.1522012],
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# OpenCV
- expected = torch.tensor([
- [[1.6519808, 1.31889750, 2.24879380, 3.58221600, 2.25095400],
- [4.2816400, 0.04868213, 0.83454597, 5.53361700, 4.31957400],
- [3.4185164, 2.79190370, 2.88832240, 1.74746920, 1.36192720],
- [3.6837196, 0.63789610, 5.72131160, 5.26143740, 6.25968700],
- [2.9292210, 2.56143520, 0.97840965, 1.57294110, 6.02352240]],
- [[0.4699935, 0.52820253, 0.81324730, 0.65267974, 0.89941100],
- [0.9497089, 0.53438100, 0.48878422, 0.60298723, 0.91636120],
- [0.6343409, 0.87112963, 0.81016120, 0.95008780, 0.81926220],
- [0.9901055, 0.90233060, 0.42042294, 0.82927720, 0.81847864],
- [0.6755719, 0.84938710, 0.93686795, 0.73741645, 0.40461043]],
- [[0.5414237, 0.99627006, 0.89471555, 0.81350225, 0.94832740],
- [0.9306560, 0.80207086, 0.89332560, 0.91709770, 0.75575125],
- [0.7415741, 0.86247796, 0.41260356, 0.76009345, 0.72799970],
- [0.8692723, 0.82887480, 0.96470920, 0.89220200, 0.76143440],
- [0.8932794, 0.85178390, 0.76217470, 0.89838010, 0.99185926]]
- ], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [1.6519808, 1.31889750, 2.24879380, 3.58221600, 2.25095400],
+ [4.2816400, 0.04868213, 0.83454597, 5.53361700, 4.31957400],
+ [3.4185164, 2.79190370, 2.88832240, 1.74746920, 1.36192720],
+ [3.6837196, 0.63789610, 5.72131160, 5.26143740, 6.25968700],
+ [2.9292210, 2.56143520, 0.97840965, 1.57294110, 6.02352240]
+ ],
+ [
+ [0.4699935, 0.52820253, 0.81324730, 0.65267974, 0.89941100],
+ [0.9497089, 0.53438100, 0.48878422, 0.60298723, 0.91636120],
+ [0.6343409, 0.87112963, 0.81016120, 0.95008780, 0.81926220],
+ [0.9901055, 0.90233060, 0.42042294, 0.82927720, 0.81847864],
+ [0.6755719, 0.84938710, 0.93686795, 0.73741645, 0.40461043]
+ ],
+ [
+ [0.5414237, 0.99627006, 0.89471555, 0.81350225, 0.94832740],
+ [0.9306560, 0.80207086, 0.89332560, 0.91709770, 0.75575125],
+ [0.7415741, 0.86247796, 0.41260356, 0.76009345, 0.72799970],
+ [0.8692723, 0.82887480, 0.96470920, 0.89220200, 0.76143440],
+ [0.8932794, 0.85178390, 0.76217470, 0.89838010, 0.99185926]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kornia.color.rgb_to_hsv(data), expected)
@@ -84,7 +104,7 @@ class TestRgbToHsv(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_hsv, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_hsv, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -104,13 +124,13 @@ class TestRgbToHsv(BaseTester):
class TestHsvToRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.hsv_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.hsv_to_rgb(img).shape == shape
@@ -128,42 +148,66 @@ class TestHsvToRgb(BaseTester):
assert kornia.color.hsv_to_rgb(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[3.5433271, 5.6390061, 1.3766849, 2.5384088, 4.6848912],
- [5.7209363, 5.3262630, 6.2059994, 4.1164689, 2.3872600],
- [0.6370091, 3.6186798, 5.9170871, 2.8275447, 5.4289737],
- [0.2751994, 1.6632686, 1.0049511, 0.7046204, 1.3791083],
- [0.7863123, 4.4852505, 4.3064494, 2.5573561, 5.9083076]],
- [[0.5026655, 0.9453601, 0.5929778, 0.2632897, 0.4590443],
- [0.6201433, 0.5610679, 0.9653260, 0.0830478, 0.5000827],
- [0.6067343, 0.6422323, 0.6777940, 0.7705711, 0.6050767],
- [0.5495264, 0.5573426, 0.4683768, 0.2268902, 0.2116482],
- [0.6525245, 0.0022379, 0.4909980, 0.1682271, 0.6327152]],
- [[0.8471680, 0.9302199, 0.3265766, 0.7944570, 0.7038843],
- [0.4833369, 0.2088473, 0.1169234, 0.4966302, 0.6448684],
- [0.2713015, 0.5893380, 0.6015301, 0.6801558, 0.2322258],
- [0.5704236, 0.6797268, 0.4755683, 0.4811209, 0.5317836],
- [0.3236262, 0.0999796, 0.3614958, 0.5117705, 0.8194097]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [3.5433271, 5.6390061, 1.3766849, 2.5384088, 4.6848912],
+ [5.7209363, 5.3262630, 6.2059994, 4.1164689, 2.3872600],
+ [0.6370091, 3.6186798, 5.9170871, 2.8275447, 5.4289737],
+ [0.2751994, 1.6632686, 1.0049511, 0.7046204, 1.3791083],
+ [0.7863123, 4.4852505, 4.3064494, 2.5573561, 5.9083076]
+ ],
+ [
+ [0.5026655, 0.9453601, 0.5929778, 0.2632897, 0.4590443],
+ [0.6201433, 0.5610679, 0.9653260, 0.0830478, 0.5000827],
+ [0.6067343, 0.6422323, 0.6777940, 0.7705711, 0.6050767],
+ [0.5495264, 0.5573426, 0.4683768, 0.2268902, 0.2116482],
+ [0.6525245, 0.0022379, 0.4909980, 0.1682271, 0.6327152]
+ ],
+ [
+ [0.8471680, 0.9302199, 0.3265766, 0.7944570, 0.7038843],
+ [0.4833369, 0.2088473, 0.1169234, 0.4966302, 0.6448684],
+ [0.2713015, 0.5893380, 0.6015301, 0.6801558, 0.2322258],
+ [0.5704236, 0.6797268, 0.4755683, 0.4811209, 0.5317836],
+ [0.3236262, 0.0999796, 0.3614958, 0.5117705, 0.8194097]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# OpenCV
- expected = torch.tensor([[
- [[0.42132590, 0.93021995, 0.26564622, 0.58528465, 0.53384290],
- [0.48333693, 0.20884734, 0.11692339, 0.45538613, 0.32238087],
- [0.27130150, 0.21084610, 0.60153013, 0.15604737, 0.23222584],
- [0.57042360, 0.45685310, 0.47556830, 0.48112088, 0.49611038],
- [0.32362622, 0.09981924, 0.20394461, 0.42567685, 0.81940967]],
- [[0.68380290, 0.05082710, 0.32657660, 0.79445700, 0.38077020],
- [0.18359877, 0.09166980, 0.00405421, 0.45823452, 0.64486840],
- [0.20682439, 0.41690278, 0.19381660, 0.68015575, 0.09171140],
- [0.33933756, 0.67972680, 0.46658220, 0.44541004, 0.53178360],
- [0.27101707, 0.09975589, 0.18400209, 0.51177055, 0.30095676]],
- [[0.84716797, 0.59178180, 0.13292392, 0.67397410, 0.70388430],
- [0.34453064, 0.19874583, 0.01237347, 0.49663020, 0.41256943],
- [0.10669357, 0.58933800, 0.33635240, 0.52297890, 0.20633064],
- [0.25696078, 0.30088606, 0.25282317, 0.37195927, 0.41923255],
- [0.11245217, 0.09997964, 0.36149580, 0.46373847, 0.48655340]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.42132590, 0.93021995, 0.26564622, 0.58528465, 0.53384290],
+ [0.48333693, 0.20884734, 0.11692339, 0.45538613, 0.32238087],
+ [0.27130150, 0.21084610, 0.60153013, 0.15604737, 0.23222584],
+ [0.57042360, 0.45685310, 0.47556830, 0.48112088, 0.49611038],
+ [0.32362622, 0.09981924, 0.20394461, 0.42567685, 0.81940967]
+ ],
+ [
+ [0.68380290, 0.05082710, 0.32657660, 0.79445700, 0.38077020],
+ [0.18359877, 0.09166980, 0.00405421, 0.45823452, 0.64486840],
+ [0.20682439, 0.41690278, 0.19381660, 0.68015575, 0.09171140],
+ [0.33933756, 0.67972680, 0.46658220, 0.44541004, 0.53178360],
+ [0.27101707, 0.09975589, 0.18400209, 0.51177055, 0.30095676]
+ ],
+ [
+ [0.84716797, 0.59178180, 0.13292392, 0.67397410, 0.70388430],
+ [0.34453064, 0.19874583, 0.01237347, 0.49663020, 0.41256943],
+ [0.10669357, 0.58933800, 0.33635240, 0.52297890, 0.20633064],
+ [0.25696078, 0.30088606, 0.25282317, 0.37195927, 0.41923255],
+ [0.11245217, 0.09997964, 0.36149580, 0.46373847, 0.48655340]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
f = kornia.color.hsv_to_rgb
assert_allclose(f(data), expected)
@@ -178,7 +222,7 @@ class TestHsvToRgb(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.hsv_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.hsv_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_lab.py b/test/color/test_lab.py
index 6e5f1e758..c54080b82 100644
--- a/test/color/test_lab.py
+++ b/test/color/test_lab.py
@@ -10,13 +10,13 @@ import kornia.testing as utils
class TestRgbToLab(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_lab(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_lab(img).shape == shape
@@ -34,48 +34,56 @@ class TestRgbToLab(BaseTester):
assert kornia.color.rgb_to_lab(img)
def test_unit(self, device, dtype):
- data = torch.tensor([
- [[0., 1., 0.69396782, 0.63581685, 0.09902618],
- [0.59459005, 0.74215373, 0.89662376, 0.25920381, 0.89937686],
- [0.29857584, 0.28139791, 0.16441015, 0.55507519, 0.06124221],
- [0.40908658, 0.10261389, 0.01691456, 0.76006799, 0.32971736]],
- [[0., 1., 0.79009938, 0.91742945, 0.60044175],
- [0.42812678, 0.18552390, 0.04186043, 0.38030245, 0.15420346],
- [0.13552373, 0.53955473, 0.79102736, 0.49050815, 0.75271446],
- [0.39861023, 0.80680277, 0.82823833, 0.54438462, 0.22063386]],
- [[0., 1., 0.84317145, 0.59529881, 0.15297393],
- [0.59235313, 0.36617295, 0.34600773, 0.40304737, 0.61720451],
- [0.46040250, 0.42006640, 0.54765106, 0.48982632, 0.13914755],
- [0.58402964, 0.89597990, 0.98276161, 0.25019163, 0.69285921]]
- ], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0., 1., 0.69396782, 0.63581685, 0.09902618],
+ [0.59459005, 0.74215373, 0.89662376, 0.25920381, 0.89937686],
+ [0.29857584, 0.28139791, 0.16441015, 0.55507519, 0.06124221],
+ [0.40908658, 0.10261389, 0.01691456, 0.76006799, 0.32971736]
+ ],
+ [
+ [0., 1., 0.79009938, 0.91742945, 0.60044175],
+ [0.42812678, 0.18552390, 0.04186043, 0.38030245, 0.15420346],
+ [0.13552373, 0.53955473, 0.79102736, 0.49050815, 0.75271446],
+ [0.39861023, 0.80680277, 0.82823833, 0.54438462, 0.22063386]
+ ],
+ [
+ [0., 1., 0.84317145, 0.59529881, 0.15297393],
+ [0.59235313, 0.36617295, 0.34600773, 0.40304737, 0.61720451],
+ [0.46040250, 0.42006640, 0.54765106, 0.48982632, 0.13914755],
+ [0.58402964, 0.89597990, 0.98276161, 0.25019163, 0.69285921]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using skimage: rgb2lab(data)
- expected = torch.tensor([[[0., 100., 79.75208576, 86.38913217,
- 55.25164186],
- [51.66668553, 43.81214392, 48.93865503, 39.03804484,
- 52.55152607],
- [23.7114063, 52.38661792, 72.54607218, 53.89587489,
- 67.94892652],
- [45.02897165, 75.98315061, 78.257619, 61.85069778,
- 33.77972627]],
-
- [[0., -0.002454937, -5.40909568, -37.74958445,
- -55.02172792],
- [24.16049084, 58.53088654, 75.33566652, -9.65827726,
- 76.94753157],
- [36.53113547, -28.57665427, -54.16269089, 6.2586262,
- -67.69290198],
- [12.32708756, -33.04781428, -29.29282657, 13.46090338,
- 42.98737069]],
-
- [[0., 0.00465342, -9.49591204, 32.9931831,
- 47.80929165],
- [-16.11189945, 7.72083678, 19.17820444, -6.90801653,
- -17.46468994],
- [-39.99097133, 9.92432127, 19.90687976, 2.40429413,
- 61.24066709],
- [-25.45166461, -22.94347485, -31.32259433, 47.2621717,
- -60.05694598]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [0., 100., 79.75208576, 86.38913217, 55.25164186],
+ [51.66668553, 43.81214392, 48.93865503, 39.03804484, 52.55152607],
+ [23.7114063, 52.38661792, 72.54607218, 53.89587489, 67.94892652],
+ [45.02897165, 75.98315061, 78.257619, 61.85069778, 33.77972627]
+ ],
+ [
+ [0., -0.002454937, -5.40909568, -37.74958445, -55.02172792],
+ [24.16049084, 58.53088654, 75.33566652, -9.65827726, 76.94753157],
+ [36.53113547, -28.57665427, -54.16269089, 6.2586262, -67.69290198],
+ [12.32708756, -33.04781428, -29.29282657, 13.46090338, 42.98737069]
+ ],
+ [
+ [0., 0.00465342, -9.49591204, 32.9931831, 47.80929165],
+ [-16.11189945, 7.72083678, 19.17820444, -6.90801653, -17.46468994],
+ [-39.99097133, 9.92432127, 19.90687976, 2.40429413, 61.24066709],
+ [-25.45166461, -22.94347485, -31.32259433, 47.2621717, -60.05694598]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
assert_allclose(kornia.color.rgb_to_lab(data), expected, rtol=tol_val, atol=tol_val)
@@ -93,7 +101,7 @@ class TestRgbToLab(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_lab, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_lab, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -113,13 +121,13 @@ class TestRgbToLab(BaseTester):
class TestLabToRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.lab_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.lab_to_rgb(img).shape == shape
@@ -137,75 +145,86 @@ class TestLabToRgb(BaseTester):
assert kornia.color.lab_to_rgb(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[50.21928787, 23.29810143, 14.98279190, 62.50927353, 72.78904724],
- [70.86846924, 68.75330353, 52.81696701, 76.17090607, 88.63134003],
- [46.87160873, 72.38699341, 37.71450806, 82.57386780, 74.79967499],
- [77.33016968, 47.39180374, 61.76217651, 90.83254242, 86.96239471]],
- [[65.81327057, -3.69859719, 0.16971001, 14.86583614, -65.54960632],
- [-41.03258133, -19.52661896, 64.16155243, -58.53935242, -71.78411102],
- [112.05227661, -60.13330460, 43.07910538, -51.01456833, -58.25787354],
- [-62.37575531, 50.88882065, -39.27450943, 17.00958824, -24.93779755]],
- [[-69.53346252, -73.34986877, -11.47461891, 66.73863220, 70.43983459],
- [51.92737579, 58.77009583, 45.97863388, 24.44452858, 98.81991577],
- [-7.60597992, 78.97976685, -69.31867218, 67.33953857, 14.28889370],
- [92.31149292, -85.91405487, -32.83668518, -23.45091820, 69.99038696]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [50.21928787, 23.29810143, 14.98279190, 62.50927353, 72.78904724],
+ [70.86846924, 68.75330353, 52.81696701, 76.17090607, 88.63134003],
+ [46.87160873, 72.38699341, 37.71450806, 82.57386780, 74.79967499],
+ [77.33016968, 47.39180374, 61.76217651, 90.83254242, 86.96239471]
+ ],
+ [
+ [65.81327057, -3.69859719, 0.16971001, 14.86583614, -65.54960632],
+ [-41.03258133, -19.52661896, 64.16155243, -58.53935242, -71.78411102],
+ [112.05227661, -60.13330460, 43.07910538, -51.01456833, -58.25787354],
+ [-62.37575531, 50.88882065, -39.27450943, 17.00958824, -24.93779755]
+ ],
+ [
+ [-69.53346252, -73.34986877, -11.47461891, 66.73863220, 70.43983459],
+ [51.92737579, 58.77009583, 45.97863388, 24.44452858, 98.81991577],
+ [-7.60597992, 78.97976685, -69.31867218, 67.33953857, 14.28889370],
+ [92.31149292, -85.91405487, -32.83668518, -23.45091820, 69.99038696]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using skimage: lab2rgb(data)
- expected = torch.tensor([[[[0.63513142, 0., 0.10660624, 0.79048697,
- 0.26823414],
- [0.48903025, 0.64529494, 0.91140099, 0.15877841,
- 0.45987959],
- [1., 0.36069696, 0.29236125, 0.55744393,
- 0.],
- [0.41710863, 0.3198324, 0., 0.94256868,
- 0.82748892]],
-
- [[0.28210726, 0.26080003, 0.15027717, 0.54540429,
- 0.80323837],
- [0.748392, 0.68774842, 0.24204415, 0.83695682,
- 0.9902132],
- [0., 0.79101603, 0.26633725, 0.89223337,
- 0.82301254],
- [0.84857086, 0.34455393, 0.66555314, 0.86168397,
- 0.8948667]],
-
- [[0.94172458, 0.66390044, 0.21043296, 0.02453515,
- 0.04169043],
- [0.28233233, 0.20235374, 0.19803933, 0.55069441,
- 0.],
- [0.50205101, 0., 0.79745394, 0.25376936,
- 0.6114783],
- [0., 1., 0.80867314, 1.,
- 0.28778443]]]], device=device, dtype=dtype)
-
- expected_unclipped = torch.tensor([[[[0.63513142, -1.78708635, 0.10660624, 0.79048697,
- 0.26823414],
- [0.48903025, 0.64529494, 0.91140099, 0.15877841,
- 0.45987959],
- [1.01488435, 0.36069696, 0.29236125, 0.55744393,
- -0.28090181],
- [0.41710863, 0.3198324, -1.81087917, 0.94256868,
- 0.82748892]],
-
- [[0.28210726, 0.26080003, 0.15027717, 0.54540429,
- 0.80323837],
- [0.748392, 0.68774842, 0.24204415, 0.83695682,
- 0.9902132],
- [-1.37862046, 0.79101603, 0.26633725, 0.89223337,
- 0.82301254],
- [0.84857086, 0.34455393, 0.66555314, 0.86168397,
- 0.8948667]],
-
- [[0.94172458, 0.66390044, 0.21043296, 0.02453515,
- 0.04169043],
- [0.28233233, 0.20235374, 0.19803933, 0.55069441,
- -0.62707704],
- [0.50205101, -0.25005965, 0.79745394, 0.25376936,
- 0.6114783],
- [-0.55802926, 1.0223477, 0.80867314, 1.07334156,
- 0.28778443]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.63513142, 0., 0.10660624, 0.79048697, 0.26823414],
+ [0.48903025, 0.64529494, 0.91140099, 0.15877841, 0.45987959],
+ [1., 0.36069696, 0.29236125, 0.55744393, 0.],
+ [0.41710863, 0.3198324, 0., 0.94256868, 0.82748892]
+ ],
+ [
+ [0.28210726, 0.26080003, 0.15027717, 0.54540429, 0.80323837],
+ [0.748392, 0.68774842, 0.24204415, 0.83695682, 0.9902132],
+ [0., 0.79101603, 0.26633725, 0.89223337, 0.82301254],
+ [0.84857086, 0.34455393, 0.66555314, 0.86168397, 0.8948667]
+ ],
+ [
+ [0.94172458, 0.66390044, 0.21043296, 0.02453515, 0.04169043],
+ [0.28233233, 0.20235374, 0.19803933, 0.55069441, 0.],
+ [0.50205101, 0., 0.79745394, 0.25376936, 0.6114783], [0., 1., 0.80867314, 1., 0.28778443]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected_unclipped = torch.tensor(
+ [
+ [
+ [
+ [0.63513142, -1.78708635, 0.10660624, 0.79048697, 0.26823414],
+ [0.48903025, 0.64529494, 0.91140099, 0.15877841, 0.45987959],
+ [1.01488435, 0.36069696, 0.29236125, 0.55744393, -0.28090181],
+ [0.41710863, 0.3198324, -1.81087917, 0.94256868, 0.82748892]
+ ],
+ [
+ [0.28210726, 0.26080003, 0.15027717, 0.54540429, 0.80323837],
+ [0.748392, 0.68774842, 0.24204415, 0.83695682, 0.9902132],
+ [-1.37862046, 0.79101603, 0.26633725, 0.89223337, 0.82301254],
+ [0.84857086, 0.34455393, 0.66555314, 0.86168397, 0.8948667]
+ ],
+ [
+ [0.94172458, 0.66390044, 0.21043296, 0.02453515, 0.04169043],
+ [0.28233233, 0.20235374, 0.19803933, 0.55069441, -0.62707704],
+ [0.50205101, -0.25005965, 0.79745394, 0.25376936, 0.6114783],
+ [-0.55802926, 1.0223477, 0.80867314, 1.07334156, 0.28778443]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
assert_allclose(kornia.color.lab_to_rgb(data), expected, rtol=tol_val, atol=tol_val)
@@ -225,7 +244,7 @@ class TestLabToRgb(BaseTester):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
img = kornia.rgb_to_lab(img)
- assert gradcheck(kornia.color.lab_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.lab_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_luv.py b/test/color/test_luv.py
index 8d7526a35..343f567a3 100644
--- a/test/color/test_luv.py
+++ b/test/color/test_luv.py
@@ -9,13 +9,13 @@ from torch.testing import assert_allclose
class TestRgbToLuv(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_luv(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_luv(img).shape == shape
@@ -33,36 +33,56 @@ class TestRgbToLuv(BaseTester):
assert kornia.color.rgb_to_luv(img)
def test_unit(self, device, dtype):
- data = torch.tensor([
- [[0., 1., 0.69396782, 0.63581685, 0.09902618],
- [0.59459005, 0.74215373, 0.89662376, 0.25920381, 0.89937686],
- [0.29857584, 0.28139791, 0.16441015, 0.55507519, 0.06124221],
- [0.40908658, 0.10261389, 0.01691456, 0.76006799, 0.32971736]],
- [[0., 1., 0.79009938, 0.91742945, 0.60044175],
- [0.42812678, 0.18552390, 0.04186043, 0.38030245, 0.15420346],
- [0.13552373, 0.53955473, 0.79102736, 0.49050815, 0.75271446],
- [0.39861023, 0.80680277, 0.82823833, 0.54438462, 0.22063386]],
- [[0., 1., 0.84317145, 0.59529881, 0.15297393],
- [0.59235313, 0.36617295, 0.34600773, 0.40304737, 0.61720451],
- [0.46040250, 0.42006640, 0.54765106, 0.48982632, 0.13914755],
- [0.58402964, 0.89597990, 0.98276161, 0.25019163, 0.69285921]]
- ], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [0., 1., 0.69396782, 0.63581685, 0.09902618],
+ [0.59459005, 0.74215373, 0.89662376, 0.25920381, 0.89937686],
+ [0.29857584, 0.28139791, 0.16441015, 0.55507519, 0.06124221],
+ [0.40908658, 0.10261389, 0.01691456, 0.76006799, 0.32971736]
+ ],
+ [
+ [0., 1., 0.79009938, 0.91742945, 0.60044175],
+ [0.42812678, 0.18552390, 0.04186043, 0.38030245, 0.15420346],
+ [0.13552373, 0.53955473, 0.79102736, 0.49050815, 0.75271446],
+ [0.39861023, 0.80680277, 0.82823833, 0.54438462, 0.22063386]
+ ],
+ [
+ [0., 1., 0.84317145, 0.59529881, 0.15297393],
+ [0.59235313, 0.36617295, 0.34600773, 0.40304737, 0.61720451],
+ [0.46040250, 0.42006640, 0.54765106, 0.48982632, 0.13914755],
+ [0.58402964, 0.89597990, 0.98276161, 0.25019163, 0.69285921]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using skimage: rgb2luv(data)
- expected = torch.tensor([
- [[0., 100., 79.75208282, 86.38912964, 55.25164032],
- [51.66668701, 43.81214523, 48.93865585, 39.03804398, 52.55152512],
- [23.71140671, 52.38661957, 72.54607391, 53.89587402, 67.94892883],
- [45.02897263, 75.98315430, 78.25762177, 61.85069656, 33.77972794]],
- [[-0., -0.00054950, -13.54032803, -35.42317200, -49.27433014],
- [21.34596062, 94.13956451, 137.11340332, -14.69241238, 102.94833374],
- [9.55611229, -30.01761436, -58.94236755, 9.83261871, -62.96137619],
- [-1.55336237, -55.22497559, -56.21067810, 43.76751328, 1.46367633]],
- [[-0., 0.00766720, -13.74480152, 52.17128372, 60.92724228],
- [-27.01125526, -1.72837746, 6.57535267, -7.83582020, -38.45543289],
- [-50.89970779, 17.65329361, 36.54148102, 2.25501800, 78.93702698],
- [-38.39783859, -31.71204376, -46.63606644, 50.16629410, -84.74416351]]
- ], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [0., 100., 79.75208282, 86.38912964, 55.25164032],
+ [51.66668701, 43.81214523, 48.93865585, 39.03804398, 52.55152512],
+ [23.71140671, 52.38661957, 72.54607391, 53.89587402, 67.94892883],
+ [45.02897263, 75.98315430, 78.25762177, 61.85069656, 33.77972794]
+ ],
+ [
+ [-0., -0.00054950, -13.54032803, -35.42317200, -49.27433014],
+ [21.34596062, 94.13956451, 137.11340332, -14.69241238, 102.94833374],
+ [9.55611229, -30.01761436, -58.94236755, 9.83261871, -62.96137619],
+ [-1.55336237, -55.22497559, -56.21067810, 43.76751328, 1.46367633]
+ ],
+ [
+ [-0., 0.00766720, -13.74480152, 52.17128372, 60.92724228],
+ [-27.01125526, -1.72837746, 6.57535267, -7.83582020, -38.45543289],
+ [-50.89970779, 17.65329361, 36.54148102, 2.25501800, 78.93702698],
+ [-38.39783859, -31.71204376, -46.63606644, 50.16629410, -84.74416351]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
tol_val: float = _get_precision(device, dtype)
assert_allclose(kornia.color.rgb_to_luv(data), expected, rtol=tol_val, atol=tol_val)
@@ -79,7 +99,7 @@ class TestRgbToLuv(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_luv, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_luv, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -99,13 +119,13 @@ class TestRgbToLuv(BaseTester):
class TestLuvToRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.luv_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.luv_to_rgb(img).shape == shape
@@ -123,37 +143,61 @@ class TestLuvToRgb(BaseTester):
assert kornia.color.luv_to_rgb(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[50.21928787, 23.29810143, 14.98279190, 62.50927353, 72.78904724],
- [70.86846924, 68.75330353, 52.81696701, 76.17090607, 88.63134003],
- [46.87160873, 72.38699341, 37.71450806, 82.57386780, 74.79967499],
- [77.33016968, 47.39180374, 61.76217651, 90.83254242, 86.96239471]],
- [[65.81327057, -3.69859719, 0.16971001, 14.86583614, -65.54960632],
- [-41.03258133, -19.52661896, 64.16155243, -58.53935242, -71.78411102],
- [112.05227661, -60.13330460, 43.07910538, -51.01456833, -58.25787354],
- [-62.37575531, 50.88882065, -39.27450943, 17.00958824, -24.93779755]],
- [[-69.53346252, -73.34986877, -11.47461891, 66.73863220, 70.43983459],
- [51.92737579, 58.77009583, 45.97863388, 24.44452858, 98.81991577],
- [-7.60597992, 78.97976685, -69.31867218, 67.33953857, 14.28889370],
- [92.31149292, -85.91405487, -32.83668518, -23.45091820, 69.99038696]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [50.21928787, 23.29810143, 14.98279190, 62.50927353, 72.78904724],
+ [70.86846924, 68.75330353, 52.81696701, 76.17090607, 88.63134003],
+ [46.87160873, 72.38699341, 37.71450806, 82.57386780, 74.79967499],
+ [77.33016968, 47.39180374, 61.76217651, 90.83254242, 86.96239471]
+ ],
+ [
+ [65.81327057, -3.69859719, 0.16971001, 14.86583614, -65.54960632],
+ [-41.03258133, -19.52661896, 64.16155243, -58.53935242, -71.78411102],
+ [112.05227661, -60.13330460, 43.07910538, -51.01456833, -58.25787354],
+ [-62.37575531, 50.88882065, -39.27450943, 17.00958824, -24.93779755]
+ ],
+ [
+ [-69.53346252, -73.34986877, -11.47461891, 66.73863220, 70.43983459],
+ [51.92737579, 58.77009583, 45.97863388, 24.44452858, 98.81991577],
+ [-7.60597992, 78.97976685, -69.31867218, 67.33953857, 14.28889370],
+ [92.31149292, -85.91405487, -32.83668518, -23.45091820, 69.99038696]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using skimage: luv2rgb(data)
- expected = torch.tensor([[
- [[0.78923208, 0.17048222, 0.14947766, 0.65528989, 0.07863078],
- [0.41649094, 0.55222923, 0.72673196, 0.21939684, 0.34298307],
- [0.82763243, 0.24021322, 0.58888060, 0.47255886, 0.16407511],
- [0.30320778, 0.72233224, 0.21593384, 0.98893607, 0.71707106]],
- [[0.20532851, 0.13188709, 0.13879408, 0.59964627, 0.80721593],
- [0.75411713, 0.70656943, 0.41770950, 0.82750136, 0.99659365],
- [0.12436169, 0.79804462, 0.10958754, 0.89803618, 0.81000644],
- [0.85726571, 0.17667055, 0.63285238, 0.85567462, 0.91538441]],
- [[0.73985511, 0.59308004, 0.21156698, 0.03804367, 0.32732114],
- [0.42489606, 0.33011687, 0.12804756, 0.64905322, 0.25216782],
- [0.41637793, 0.22158240, 0.63437861, 0.46121466, 0.68336427],
- [0.06325728, 0.78878325, 0.74280596, 0.99514300, 0.47176042]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.78923208, 0.17048222, 0.14947766, 0.65528989, 0.07863078],
+ [0.41649094, 0.55222923, 0.72673196, 0.21939684, 0.34298307],
+ [0.82763243, 0.24021322, 0.58888060, 0.47255886, 0.16407511],
+ [0.30320778, 0.72233224, 0.21593384, 0.98893607, 0.71707106]
+ ],
+ [
+ [0.20532851, 0.13188709, 0.13879408, 0.59964627, 0.80721593],
+ [0.75411713, 0.70656943, 0.41770950, 0.82750136, 0.99659365],
+ [0.12436169, 0.79804462, 0.10958754, 0.89803618, 0.81000644],
+ [0.85726571, 0.17667055, 0.63285238, 0.85567462, 0.91538441]
+ ],
+ [
+ [0.73985511, 0.59308004, 0.21156698, 0.03804367, 0.32732114],
+ [0.42489606, 0.33011687, 0.12804756, 0.64905322, 0.25216782],
+ [0.41637793, 0.22158240, 0.63437861, 0.46121466, 0.68336427],
+ [0.06325728, 0.78878325, 0.74280596, 0.99514300, 0.47176042]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kornia.color.luv_to_rgb(data), expected, rtol=1e-4, atol=1e-4)
@@ -170,7 +214,7 @@ class TestLuvToRgb(BaseTester):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
img = kornia.rgb_to_luv(img)
- assert gradcheck(kornia.color.luv_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.luv_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_rgb.py b/test/color/test_rgb.py
index b1f20e3d0..d5abc0b8d 100644
--- a/test/color/test_rgb.py
+++ b/test/color/test_rgb.py
@@ -9,13 +9,13 @@ from torch.testing import assert_allclose
class TestRgbToBgr(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_bgr(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_bgr(img).shape == shape
@@ -50,17 +50,13 @@ class TestRgbToBgr(BaseTester):
assert_allclose(data_bgr, data_bgr_new)
def test_unit(self, device, dtype):
- data = torch.tensor([
- [[1., 1.], [1., 1.]],
- [[2., 2.], [2., 2.]],
- [[3., 3.], [3., 3.]]
- ], device=device, dtype=dtype) # 3x2x2
-
- expected = torch.tensor([
- [[3., 3.], [3., 3.]],
- [[2., 2.], [2., 2.]],
- [[1., 1.], [1., 1.]]
- ], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[2., 2.], [2., 2.]], [[3., 3.], [3., 3.]]], device=device, dtype=dtype
+ ) # 3x2x2
+
+ expected = torch.tensor(
+ [[[3., 3.], [3., 3.]], [[2., 2.], [2., 2.]], [[1., 1.], [1., 1.]]], device=device, dtype=dtype
+ ) # 3x2x2
f = kornia.color.rgb_to_bgr
assert_allclose(f(data), expected)
@@ -69,7 +65,7 @@ class TestRgbToBgr(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_bgr, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_bgr, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -97,13 +93,13 @@ class TestRgbToBgr(BaseTester):
class TestRgbToRgba(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_rgba(img, 0.), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
out_shape = list(shape)
out_shape[-3] += 1
@@ -159,49 +155,39 @@ class TestRgbToRgba(BaseTester):
@pytest.mark.parametrize("aval", [0.4, 45.])
def test_unit(self, device, dtype, aval):
- data = torch.tensor([[
- [[1., 1.],
- [1., 1.]],
- [[2., 2.],
- [2., 2.]],
- [[3., 3.],
- [3., 3.]]
- ]], device=device, dtype=dtype) # Bx3x2x2
-
- expected = torch.tensor([[
- [[1.0, 1.0],
- [1.0, 1.0]],
- [[2.0, 2.0],
- [2.0, 2.0]],
- [[3.0, 3.0],
- [3.0, 3.0]],
- [[aval, aval],
- [aval, aval]]
- ]], device=device, dtype=dtype) # Bx4x2x2
+ data = torch.tensor(
+ [[[[1., 1.], [1., 1.]], [[2., 2.], [2., 2.]], [[3., 3.], [3., 3.]]]], device=device, dtype=dtype
+ ) # Bx3x2x2
+
+ expected = torch.tensor(
+ [
+ [
+ [[1.0, 1.0], [1.0, 1.0]], [[2.0, 2.0], [2.0, 2.0]], [[3.0, 3.0], [3.0, 3.0]],
+ [[aval, aval], [aval, aval]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # Bx4x2x2
assert_allclose(kornia.rgb_to_rgba(data, aval), expected)
@pytest.mark.parametrize("aval", [0.4, 45.])
def test_unit_aval_th(self, device, dtype, aval):
- data = torch.tensor([[
- [[1., 1.],
- [1., 1.]],
- [[2., 2.],
- [2., 2.]],
- [[3., 3.],
- [3., 3.]]
- ]], device=device, dtype=dtype) # Bx3x2x2
-
- expected = torch.tensor([[
- [[1.0, 1.0],
- [1.0, 1.0]],
- [[2.0, 2.0],
- [2.0, 2.0]],
- [[3.0, 3.0],
- [3.0, 3.0]],
- [[aval, aval],
- [aval, aval]]
- ]], device=device, dtype=dtype) # Bx4x2x2
+ data = torch.tensor(
+ [[[[1., 1.], [1., 1.]], [[2., 2.], [2., 2.]], [[3., 3.], [3., 3.]]]], device=device, dtype=dtype
+ ) # Bx3x2x2
+
+ expected = torch.tensor(
+ [
+ [
+ [[1.0, 1.0], [1.0, 1.0]], [[2.0, 2.0], [2.0, 2.0]], [[3.0, 3.0], [3.0, 3.0]],
+ [[aval, aval], [aval, aval]]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # Bx4x2x2
aval = torch.full_like(data[:, :1], aval) # Bx1xHxW
assert_allclose(kornia.rgb_to_rgba(data, aval), expected)
@@ -264,14 +250,14 @@ class TestRgbToRgba(BaseTester):
class TestLinearRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_linear_rgb(img), torch.Tensor)
assert isinstance(kornia.color.linear_rgb_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_linear_rgb(img).shape == shape
@@ -307,31 +293,37 @@ class TestLinearRgb(BaseTester):
assert_allclose(data_bgr, data_bgr_new)
def test_unit(self, device, dtype):
- data = torch.tensor([
- [[1., 0.], [0.5, 0.1]],
- [[1., 0.], [0.5, 0.2]],
- [[1., 0.], [0.5, 0.3]]
- ], device=device, dtype=dtype) # 3x2x2
-
- expected = torch.tensor([[[1.00000000, 0.00000000], [0.21404116, 0.01002283]],
- [[1.00000000, 0.00000000], [0.21404116, 0.03310477]],
- [[1.00000000, 0.00000000], [0.21404116, 0.07323898]]
- ], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [[[1., 0.], [0.5, 0.1]], [[1., 0.], [0.5, 0.2]], [[1., 0.], [0.5, 0.3]]], device=device, dtype=dtype
+ ) # 3x2x2
+
+ expected = torch.tensor(
+ [
+ [[1.00000000, 0.00000000], [0.21404116, 0.01002283]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.03310477]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.07323898]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 3x2x2
f = kornia.color.rgb_to_linear_rgb
assert_allclose(f(data), expected)
def test_unit_linear(self, device, dtype):
- data = torch.tensor([[[1.00000000, 0.00000000], [0.21404116, 0.01002283]],
- [[1.00000000, 0.00000000], [0.21404116, 0.03310477]],
- [[1.00000000, 0.00000000], [0.21404116, 0.07323898]]
- ], device=device, dtype=dtype) # 3x2x2
-
- expected = torch.tensor([
- [[1., 0.], [0.5, 0.1]],
- [[1., 0.], [0.5, 0.2]],
- [[1., 0.], [0.5, 0.3]]
- ], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [
+ [[1.00000000, 0.00000000], [0.21404116, 0.01002283]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.03310477]],
+ [[1.00000000, 0.00000000], [0.21404116, 0.07323898]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 3x2x2
+
+ expected = torch.tensor(
+ [[[1., 0.], [0.5, 0.1]], [[1., 0.], [0.5, 0.2]], [[1., 0.], [0.5, 0.3]]], device=device, dtype=dtype
+ ) # 3x2x2
f = kornia.color.linear_rgb_to_rgb
assert_allclose(f(data), expected)
@@ -340,8 +332,8 @@ class TestLinearRgb(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_linear_rgb, (img,), raise_exception=True)
- assert gradcheck(kornia.color.linear_rgb_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_linear_rgb, (img, ), raise_exception=True)
+ assert gradcheck(kornia.color.linear_rgb_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_xyz.py b/test/color/test_xyz.py
index 107874048..c2f811c60 100644
--- a/test/color/test_xyz.py
+++ b/test/color/test_xyz.py
@@ -9,13 +9,13 @@ from torch.testing import assert_allclose
class TestRgbToXyz(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_xyz(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_xyz(img).shape == shape
@@ -33,36 +33,54 @@ class TestRgbToXyz(BaseTester):
assert kornia.color.rgb_to_xyz(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[0.9637, 0.0586, 0.6470, 0.6212, 0.9622],
- [0.8293, 0.4858, 0.8953, 0.2607, 0.3250],
- [0.5314, 0.4189, 0.8388, 0.8065, 0.2211],
- [0.9682, 0.2928, 0.4118, 0.2533, 0.0455]],
- [[0.6936, 0.3457, 0.9466, 0.9937, 0.2692],
- [0.7485, 0.7320, 0.8323, 0.6889, 0.4831],
- [0.1865, 0.7439, 0.1366, 0.8858, 0.2077],
- [0.6227, 0.6140, 0.3936, 0.5024, 0.4157]],
- [[0.6477, 0.9269, 0.7531, 0.7349, 0.9485],
- [0.4264, 0.8539, 0.9830, 0.2269, 0.1138],
- [0.3988, 0.1605, 0.6220, 0.0546, 0.1106],
- [0.2128, 0.5673, 0.0781, 0.1431, 0.3310]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [0.9637, 0.0586, 0.6470, 0.6212, 0.9622], [0.8293, 0.4858, 0.8953, 0.2607, 0.3250],
+ [0.5314, 0.4189, 0.8388, 0.8065, 0.2211], [0.9682, 0.2928, 0.4118, 0.2533, 0.0455]
+ ],
+ [
+ [0.6936, 0.3457, 0.9466, 0.9937, 0.2692], [0.7485, 0.7320, 0.8323, 0.6889, 0.4831],
+ [0.1865, 0.7439, 0.1366, 0.8858, 0.2077], [0.6227, 0.6140, 0.3936, 0.5024, 0.4157]
+ ],
+ [
+ [0.6477, 0.9269, 0.7531, 0.7349, 0.9485], [0.4264, 0.8539, 0.9830, 0.2269, 0.1138],
+ [0.3988, 0.1605, 0.6220, 0.0546, 0.1106], [0.2128, 0.5673, 0.0781, 0.1431, 0.3310]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
- expected = torch.tensor([[
- [[0.7623584, 0.31501925, 0.7412189, 0.7441359, 0.66425407],
- [0.6866283, 0.61618143, 0.84423876, 0.39480132, 0.32732624],
- [0.3578189, 0.4677382, 0.50703406, 0.6592388, 0.18541752],
- [0.6603961, 0.44267434, 0.32468265, 0.30994105, 0.22713262]],
- [[0.7477299, 0.32658678, 0.86891913, 0.89580274, 0.4656054],
- [0.7424382, 0.6884378, 0.8565741, 0.5644922, 0.4228247],
- [0.2751717, 0.63267857, 0.3209684, 0.8089483, 0.20354219],
- [0.6665957, 0.5423198, 0.37470126, 0.42349333, 0.33085644]],
- [[0.7167665, 0.92310345, 0.8409531, 0.82877415, 0.95198023],
- [0.51042646, 0.9080406, 1.0505873, 0.30275896, 0.17200153],
- [0.4114541, 0.24927814, 0.62354034, 0.17305644, 0.13412625],
- [0.29514894, 0.6179093, 0.12908883, 0.20075734, 0.3649534]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.7623584, 0.31501925, 0.7412189, 0.7441359, 0.66425407],
+ [0.6866283, 0.61618143, 0.84423876, 0.39480132, 0.32732624],
+ [0.3578189, 0.4677382, 0.50703406, 0.6592388, 0.18541752],
+ [0.6603961, 0.44267434, 0.32468265, 0.30994105, 0.22713262]
+ ],
+ [
+ [0.7477299, 0.32658678, 0.86891913, 0.89580274, 0.4656054],
+ [0.7424382, 0.6884378, 0.8565741, 0.5644922, 0.4228247],
+ [0.2751717, 0.63267857, 0.3209684, 0.8089483, 0.20354219],
+ [0.6665957, 0.5423198, 0.37470126, 0.42349333, 0.33085644]
+ ],
+ [
+ [0.7167665, 0.92310345, 0.8409531, 0.82877415, 0.95198023],
+ [0.51042646, 0.9080406, 1.0505873, 0.30275896, 0.17200153],
+ [0.4114541, 0.24927814, 0.62354034, 0.17305644, 0.13412625],
+ [0.29514894, 0.6179093, 0.12908883, 0.20075734, 0.3649534]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kornia.color.rgb_to_xyz(data), expected)
@@ -78,7 +96,7 @@ class TestRgbToXyz(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_xyz, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_xyz, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -98,13 +116,13 @@ class TestRgbToXyz(BaseTester):
class TestXyzToRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.xyz_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.xyz_to_rgb(img).shape == shape
@@ -122,36 +140,60 @@ class TestXyzToRgb(BaseTester):
assert kornia.color.xyz_to_rgb(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[0.6315228, 0.4196397, 0.33123854, 0.3277169, 0.20501322],
- [0.44133404, 0.4823162, 0.528561, 0.51644784, 0.28001237],
- [0.31131047, 0.8453884, 0.4486181, 0.6015828, 0.42048606],
- [0.5472367, 0.48154795, 0.36668795, 0.39913517, 0.40271503]],
- [[0.79137707, 0.501063, 0.3700857, 0.57410157, 0.15295872],
- [0.570678, 0.76664513, 0.48567873, 0.47680324, 0.2583247],
- [0.38080955, 0.9315215, 0.4404478, 0.50659215, 0.5984908],
- [0.5388581, 0.76993656, 0.4027568, 0.5952581, 0.68663263]],
- [[0.86013114, 0.17629854, 0.83010703, 0.27881518, 0.30543375],
- [0.17009716, 0.61201245, 0.33521807, 0.15526368, 0.7401195],
- [0.34011865, 0.6541383, 0.96909684, 0.43090558, 0.70467836],
- [0.6738866, 0.47461915, 0.91508406, 0.44147202, 0.14099535]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [0.6315228, 0.4196397, 0.33123854, 0.3277169, 0.20501322],
+ [0.44133404, 0.4823162, 0.528561, 0.51644784, 0.28001237],
+ [0.31131047, 0.8453884, 0.4486181, 0.6015828, 0.42048606],
+ [0.5472367, 0.48154795, 0.36668795, 0.39913517, 0.40271503]
+ ],
+ [
+ [0.79137707, 0.501063, 0.3700857, 0.57410157, 0.15295872],
+ [0.570678, 0.76664513, 0.48567873, 0.47680324, 0.2583247],
+ [0.38080955, 0.9315215, 0.4404478, 0.50659215, 0.5984908],
+ [0.5388581, 0.76993656, 0.4027568, 0.5952581, 0.68663263]
+ ],
+ [
+ [0.86013114, 0.17629854, 0.83010703, 0.27881518, 0.30543375],
+ [0.17009716, 0.61201245, 0.33521807, 0.15526368, 0.7401195],
+ [0.34011865, 0.6541383, 0.96909684, 0.43090558, 0.70467836],
+ [0.6738866, 0.47461915, 0.91508406, 0.44147202, 0.14099535]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
- expected = torch.tensor([[
- [[0.4011656, 0.5017336, 0.09065688, 0.04048038, 0.2769511],
- [0.46811658, 0.07937729, 0.79911184, 0.8632158, 0.1413149],
- [0.2538725, 0.98146427, 0.29357457, 0.95588684, 0.09129933],
- [0.6090472, 0.14032376, 0.11294556, 0.15829873, 0.1792411]],
- [[0.90825266, 0.54057753, 0.40771842, 0.7709542, 0.1009315],
- [0.64988965, 0.99616426, 0.41274834, 0.40036052, 0.24396756],
- [0.42678973, 0.95531154, 0.43172216, 0.3851813, 0.7444883],
- [0.5084846, 0.99737406, 0.4381809, 0.7481805, 0.9036418]],
- [[0.78309417, 0.10751611, 0.82060075, 0.19588977, 0.3031369],
- [0.08796211, 0.51749885, 0.28474382, 0.09561294, 0.74540937],
- [0.2992335, 0.5486014, 0.95973116, 0.38571155, 0.64634556],
- [0.6330101, 0.3715171, 0.90575427, 0.36752605, 0.03138365]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.4011656, 0.5017336, 0.09065688, 0.04048038, 0.2769511],
+ [0.46811658, 0.07937729, 0.79911184, 0.8632158, 0.1413149],
+ [0.2538725, 0.98146427, 0.29357457, 0.95588684, 0.09129933],
+ [0.6090472, 0.14032376, 0.11294556, 0.15829873, 0.1792411]
+ ],
+ [
+ [0.90825266, 0.54057753, 0.40771842, 0.7709542, 0.1009315],
+ [0.64988965, 0.99616426, 0.41274834, 0.40036052, 0.24396756],
+ [0.42678973, 0.95531154, 0.43172216, 0.3851813, 0.7444883],
+ [0.5084846, 0.99737406, 0.4381809, 0.7481805, 0.9036418]
+ ],
+ [
+ [0.78309417, 0.10751611, 0.82060075, 0.19588977, 0.3031369],
+ [0.08796211, 0.51749885, 0.28474382, 0.09561294, 0.74540937],
+ [0.2992335, 0.5486014, 0.95973116, 0.38571155, 0.64634556],
+ [0.6330101, 0.3715171, 0.90575427, 0.36752605, 0.03138365]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kornia.color.xyz_to_rgb(data), expected, atol=1e-4, rtol=1e-4)
@@ -167,7 +209,7 @@ class TestXyzToRgb(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.xyz_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.xyz_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_ycbcr.py b/test/color/test_ycbcr.py
index 31c7b904e..879a0f38d 100644
--- a/test/color/test_ycbcr.py
+++ b/test/color/test_ycbcr.py
@@ -9,13 +9,13 @@ from torch.testing import assert_allclose
class TestRgbToYcbcr(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_ycbcr(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_ycbcr(img).shape == shape
@@ -33,42 +33,60 @@ class TestRgbToYcbcr(BaseTester):
assert kornia.color.rgb_to_ycbcr(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[0.7925, 0.8704, 0.2771, 0.3279, 0.0193],
- [0.2483, 0.6212, 0.9859, 0.5044, 0.5621],
- [0.5762, 0.3959, 0.2931, 0.2669, 0.0243],
- [0.6989, 0.0529, 0.8344, 0.6523, 0.8980],
- [0.5181, 0.9341, 0.2172, 0.0520, 0.7266]],
- [[0.8413, 0.0284, 0.3625, 0.8864, 0.5595],
- [0.3791, 0.0235, 0.4251, 0.0619, 0.5270],
- [0.3516, 0.8005, 0.9571, 0.4113, 0.6119],
- [0.0632, 0.8836, 0.0261, 0.1550, 0.4923],
- [0.2332, 0.7044, 0.9514, 0.2443, 0.2818]],
- [[0.6899, 0.2063, 0.3179, 0.8989, 0.4378],
- [0.0384, 0.5230, 0.6416, 0.9749, 0.7863],
- [0.8577, 0.3115, 0.2375, 0.5446, 0.9837],
- [0.3213, 0.6618, 0.5977, 0.3999, 0.4962],
- [0.1385, 0.5831, 0.9756, 0.8714, 0.8017]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [0.7925, 0.8704, 0.2771, 0.3279, 0.0193], [0.2483, 0.6212, 0.9859, 0.5044, 0.5621],
+ [0.5762, 0.3959, 0.2931, 0.2669, 0.0243], [0.6989, 0.0529, 0.8344, 0.6523, 0.8980],
+ [0.5181, 0.9341, 0.2172, 0.0520, 0.7266]
+ ],
+ [
+ [0.8413, 0.0284, 0.3625, 0.8864, 0.5595], [0.3791, 0.0235, 0.4251, 0.0619, 0.5270],
+ [0.3516, 0.8005, 0.9571, 0.4113, 0.6119], [0.0632, 0.8836, 0.0261, 0.1550, 0.4923],
+ [0.2332, 0.7044, 0.9514, 0.2443, 0.2818]
+ ],
+ [
+ [0.6899, 0.2063, 0.3179, 0.8989, 0.4378], [0.0384, 0.5230, 0.6416, 0.9749, 0.7863],
+ [0.8577, 0.3115, 0.2375, 0.5446, 0.9837], [0.3213, 0.6618, 0.5977, 0.3999, 0.4962],
+ [0.1385, 0.5831, 0.9756, 0.8714, 0.8017]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
- expected = torch.tensor([[
- [[0.8094629, 0.30041942, 0.33188093, 0.7208117, 0.38409105],
- [0.30114722, 0.2591345, 0.6174494, 0.29830942, 0.5670594],
- [0.47643244, 0.623786, 0.6765313, 0.38332558, 0.47857922],
- [0.2826805, 0.60994685, 0.33298355, 0.3316514, 0.6140681],
- [0.30756146, 0.75926465, 0.7346588, 0.25828302, 0.4740529]],
- [[0.43258172, 0.4469004, 0.492101, 0.60042214, 0.53028214],
- [0.35180065, 0.64882994, 0.51362985, 0.8815981, 0.62366176],
- [0.71505237, 0.32387614, 0.2523859, 0.5909421, 0.78490996],
- [0.52178127, 0.529264, 0.64931786, 0.53848785, 0.43353173],
- [0.4046721, 0.40065458, 0.6358658, 0.8458253, 0.6847739]],
- [[0.48791525, 0.9063825, 0.46094114, 0.21983841, 0.23989305],
- [0.46231723, 0.7581379, 0.7626976, 0.6469568, 0.496467],
- [0.5711212, 0.33752257, 0.22661471, 0.4169921, 0.17608929],
- [0.7967522, 0.10283372, 0.85753804, 0.72865105, 0.70245713],
- [0.65009415, 0.6246666, 0.13107029, 0.35291404, 0.6800583]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.8094629, 0.30041942, 0.33188093, 0.7208117, 0.38409105],
+ [0.30114722, 0.2591345, 0.6174494, 0.29830942, 0.5670594],
+ [0.47643244, 0.623786, 0.6765313, 0.38332558, 0.47857922],
+ [0.2826805, 0.60994685, 0.33298355, 0.3316514, 0.6140681],
+ [0.30756146, 0.75926465, 0.7346588, 0.25828302, 0.4740529]
+ ],
+ [
+ [0.43258172, 0.4469004, 0.492101, 0.60042214, 0.53028214],
+ [0.35180065, 0.64882994, 0.51362985, 0.8815981, 0.62366176],
+ [0.71505237, 0.32387614, 0.2523859, 0.5909421, 0.78490996],
+ [0.52178127, 0.529264, 0.64931786, 0.53848785, 0.43353173],
+ [0.4046721, 0.40065458, 0.6358658, 0.8458253, 0.6847739]
+ ],
+ [
+ [0.48791525, 0.9063825, 0.46094114, 0.21983841, 0.23989305],
+ [0.46231723, 0.7581379, 0.7626976, 0.6469568, 0.496467],
+ [0.5711212, 0.33752257, 0.22661471, 0.4169921, 0.17608929],
+ [0.7967522, 0.10283372, 0.85753804, 0.72865105, 0.70245713],
+ [0.65009415, 0.6246666, 0.13107029, 0.35291404, 0.6800583]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kornia.color.rgb_to_ycbcr(data), expected, atol=1e-4, rtol=1e-4)
@@ -80,7 +98,7 @@ class TestRgbToYcbcr(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_ycbcr, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_ycbcr, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -100,13 +118,13 @@ class TestRgbToYcbcr(BaseTester):
class TestYcbcrToRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.ycbcr_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.ycbcr_to_rgb(img).shape == shape
@@ -124,42 +142,60 @@ class TestYcbcrToRgb(BaseTester):
assert kornia.color.ycbcr_to_rgb(img)
def test_unit(self, device, dtype):
- data = torch.tensor([[
- [[0.9892, 0.2620, 0.4184, 0.5286, 0.2793],
- [0.0722, 0.8828, 0.8714, 0.0657, 0.7798],
- [0.8118, 0.7522, 0.0260, 0.8811, 0.5226],
- [0.0644, 0.3648, 0.4448, 0.4202, 0.7316],
- [0.9138, 0.1956, 0.4257, 0.6381, 0.1353]],
- [[0.7408, 0.8529, 0.5119, 0.0220, 0.0226],
- [0.8963, 0.5652, 0.9568, 0.6977, 0.8221],
- [0.4645, 0.0478, 0.4952, 0.5492, 0.4861],
- [0.9980, 0.9978, 0.0281, 0.5283, 0.8146],
- [0.7789, 0.2663, 0.6437, 0.6926, 0.5627]],
- [[0.7377, 0.7152, 0.3080, 0.8515, 0.4841],
- [0.7192, 0.3297, 0.7337, 0.0230, 0.2464],
- [0.6399, 0.8998, 0.3838, 0.3043, 0.3774],
- [0.1281, 0.6731, 0.4218, 0.3963, 0.8541],
- [0.2245, 0.2413, 0.2351, 0.9522, 0.8158]]
- ]], device=device, dtype=dtype)
+ data = torch.tensor(
+ [
+ [
+ [
+ [0.9892, 0.2620, 0.4184, 0.5286, 0.2793], [0.0722, 0.8828, 0.8714, 0.0657, 0.7798],
+ [0.8118, 0.7522, 0.0260, 0.8811, 0.5226], [0.0644, 0.3648, 0.4448, 0.4202, 0.7316],
+ [0.9138, 0.1956, 0.4257, 0.6381, 0.1353]
+ ],
+ [
+ [0.7408, 0.8529, 0.5119, 0.0220, 0.0226], [0.8963, 0.5652, 0.9568, 0.6977, 0.8221],
+ [0.4645, 0.0478, 0.4952, 0.5492, 0.4861], [0.9980, 0.9978, 0.0281, 0.5283, 0.8146],
+ [0.7789, 0.2663, 0.6437, 0.6926, 0.5627]
+ ],
+ [
+ [0.7377, 0.7152, 0.3080, 0.8515, 0.4841], [0.7192, 0.3297, 0.7337, 0.0230, 0.2464],
+ [0.6399, 0.8998, 0.3838, 0.3043, 0.3774], [0.1281, 0.6731, 0.4218, 0.3963, 0.8541],
+ [0.2245, 0.2413, 0.2351, 0.9522, 0.8158]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
- expected = torch.tensor([[
- [[1.3226931, 0.5639256, 0.14902398, 1.0217545, 0.2569923],
- [0.37973762, 0.64386904, 1.1992811, -0.603531, 0.4239992],
- [1.0080798, 1.3131194, -0.1370286, 0.60653293, 0.3505922],
- [-0.4573757, 0.6076593, 0.33508536, 0.27470887, 1.2284023],
- [0.52727354, -0.1673561, 0.05404532, 1.2725366, 0.5783674]],
- [[0.736647, -0.01305042, 0.55139434, 0.44206098, 0.4548782],
- [-0.22063601, 0.98196536, 0.54739904, 0.33826917, 0.850068],
- [0.72412336, 0.6222996, 0.110618, 1.0039049, 0.614918],
- [0.15862459, 0.0699634, 0.66296846, 0.4845066, 0.3705502],
- [1.0145653, 0.46070462, 0.5654058, 0.24897486, -0.11174999]],
- [[1.4161384, 0.88769174, 0.4394987, -0.31889397, -0.5671302],
- [0.77483994, 0.99839956, 1.6813064, 0.41622213, 1.3508832],
- [0.7488585, -0.04955059, 0.01748962, 0.9683316, 0.49795526],
- [0.9473541, 1.2473994, -0.3918787, 0.47037587, 1.2893858],
- [1.4082898, -0.21875012, 0.6804801, 0.9795798, 0.24646705]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [1.3226931, 0.5639256, 0.14902398, 1.0217545, 0.2569923],
+ [0.37973762, 0.64386904, 1.1992811, -0.603531, 0.4239992],
+ [1.0080798, 1.3131194, -0.1370286, 0.60653293, 0.3505922],
+ [-0.4573757, 0.6076593, 0.33508536, 0.27470887, 1.2284023],
+ [0.52727354, -0.1673561, 0.05404532, 1.2725366, 0.5783674]
+ ],
+ [
+ [0.736647, -0.01305042, 0.55139434, 0.44206098, 0.4548782],
+ [-0.22063601, 0.98196536, 0.54739904, 0.33826917, 0.850068],
+ [0.72412336, 0.6222996, 0.110618, 1.0039049, 0.614918],
+ [0.15862459, 0.0699634, 0.66296846, 0.4845066, 0.3705502],
+ [1.0145653, 0.46070462, 0.5654058, 0.24897486, -0.11174999]
+ ],
+ [
+ [1.4161384, 0.88769174, 0.4394987, -0.31889397, -0.5671302],
+ [0.77483994, 0.99839956, 1.6813064, 0.41622213, 1.3508832],
+ [0.7488585, -0.04955059, 0.01748962, 0.9683316, 0.49795526],
+ [0.9473541, 1.2473994, -0.3918787, 0.47037587, 1.2893858],
+ [1.4082898, -0.21875012, 0.6804801, 0.9795798, 0.24646705]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kornia.color.ycbcr_to_rgb(data), expected, atol=1e-4, rtol=1e-4)
@@ -171,7 +207,7 @@ class TestYcbcrToRgb(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.ycbcr_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.ycbcr_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/color/test_yuv.py b/test/color/test_yuv.py
index 9a792510e..558cdbd08 100644
--- a/test/color/test_yuv.py
+++ b/test/color/test_yuv.py
@@ -10,13 +10,13 @@ from torch.testing import assert_allclose
class TestRgbToYuv(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.rgb_to_yuv(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.rgb_to_yuv(img).shape == shape
@@ -50,7 +50,7 @@ class TestRgbToYuv(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.rgb_to_yuv, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_yuv, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -70,13 +70,13 @@ class TestRgbToYuv(BaseTester):
class TestYuvToRgb(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
img = torch.rand(C, H, W, device=device, dtype=dtype)
assert isinstance(kornia.color.yuv_to_rgb(img), torch.Tensor)
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.ones(shape, device=device, dtype=dtype)
assert kornia.color.yuv_to_rgb(img).shape == shape
@@ -110,7 +110,7 @@ class TestYuvToRgb(BaseTester):
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.rand(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(kornia.color.yuv_to_rgb, (img,), raise_exception=True)
+ assert gradcheck(kornia.color.yuv_to_rgb, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.py
index 3f7acf660..571f14ceb 100644
--- a/test/enhance/test_adjust.py
+++ b/test/enhance/test_adjust.py
@@ -11,13 +11,12 @@ from torch.testing import assert_allclose
class TestInvert:
+
def test_smoke(self, device, dtype):
img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
assert kornia.enhance.invert(img) is not None
- @pytest.mark.parametrize("shape", [
- (3, 4, 4), (2, 4, 3, 3), (1, 3, 2, 1, 1)
- ])
+ @pytest.mark.parametrize("shape", [(3, 4, 4), (2, 4, 3, 3), (1, 3, 2, 1, 1)])
def test_cardinality(self, device, dtype, shape):
img = torch.rand(shape, device=device, dtype=dtype)
out = kornia.enhance.invert(img, torch.tensor(1.))
@@ -58,15 +57,11 @@ class TestInvert:
class TestAdjustSaturation:
- def test_saturation_one(self, device, dtype):
- data = torch.tensor([[[.5, .5],
- [.5, .5]],
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ def test_saturation_one(self, device, dtype):
+ data = torch.tensor(
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = data.clone()
@@ -74,23 +69,14 @@ class TestAdjustSaturation:
assert_allclose(f(data), expected)
def test_saturation_one_batch(self, device, dtype):
- data = torch.tensor([[[[.5, .5],
- [.5, .5]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]],
-
- [[[.5, .5],
- [.5, .5]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
+ data = torch.tensor(
+ [
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]],
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
expected = data
f = kornia.enhance.AdjustSaturation(torch.ones(2))
@@ -100,20 +86,15 @@ class TestAdjustSaturation:
batch_size, channels, height, width = 2, 3, 4, 5
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)
+ assert gradcheck(kornia.adjust_saturation, (img, 2.), raise_exception=True)
class TestAdjustHue:
- def test_hue_one(self, device, dtype):
- data = torch.tensor([[[.5, .5],
- [.5, .5]],
-
- [[.5, .5],
- [.5, .5]],
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ def test_hue_one(self, device, dtype):
+ data = torch.tensor(
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = data.clone()
@@ -121,46 +102,28 @@ class TestAdjustHue:
assert_allclose(f(data), expected)
def test_hue_one_batch(self, device, dtype):
- data = torch.tensor([[[[.5, .5],
- [.5, .5]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]],
-
- [[[.5, .5],
- [.5, .5]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
+ data = torch.tensor(
+ [
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]],
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.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, device, dtype):
- data = torch.tensor([[[[.5, .5],
- [.5, .5]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]],
-
- [[[.5, .5],
- [.5, .5]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
+ data = torch.tensor(
+ [
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]],
+ [[[.5, .5], [.5, .5]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
pi_t = torch.tensor([-pi, pi], device=device, dtype=dtype)
f = kornia.enhance.AdjustHue(pi_t)
@@ -172,20 +135,15 @@ class TestAdjustHue:
batch_size, channels, height, width = 2, 3, 4, 5
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)
+ assert gradcheck(kornia.adjust_hue, (img, 2.), raise_exception=True)
class TestAdjustGamma:
- def test_gamma_zero(self, device, dtype):
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ def test_gamma_zero(self, device, dtype):
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = torch.ones_like(data)
@@ -193,14 +151,9 @@ class TestAdjustGamma:
assert_allclose(f(data), expected)
def test_gamma_one(self, device, dtype):
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = data.clone()
@@ -208,85 +161,49 @@ class TestAdjustGamma:
assert_allclose(f(data), expected)
def test_gamma_one_gain_two(self, device, dtype):
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
-
- expected = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]]], device=device, dtype=dtype) # 3x2x2
+ expected = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]]], device=device, dtype=dtype
+ ) # 3x2x2
f = kornia.enhance.AdjustGamma(1., 2.)
assert_allclose(f(data), expected)
def test_gamma_two(self, device, dtype):
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
-
- expected = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.25, .25],
- [.25, .25]],
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
- [[.0625, .0625],
- [.0625, .0625]]], device=device, dtype=dtype) # 3x2x2
+ expected = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.25, .25], [.25, .25]], [[.0625, .0625], [.0625, .0625]]],
+ device=device,
+ dtype=dtype
+ ) # 3x2x2
f = kornia.enhance.AdjustGamma(2.)
assert_allclose(f(data), expected)
def test_gamma_two_batch(self, device, dtype):
- data = torch.tensor([[[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]],
-
- [[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]]], device=device, dtype=dtype) # 2x3x2x2
-
- expected = torch.tensor([[[[1., 1.],
- [1., 1.]],
-
- [[.25, .25],
- [.25, .25]],
-
- [[.0625, .0625],
- [.0625, .0625]]],
-
- [[[1., 1.],
- [1., 1.]],
-
- [[.25, .25],
- [.25, .25]],
-
- [[.0625, .0625],
- [.0625, .0625]]]], device=device, dtype=dtype) # 2x3x2x2
+ data = torch.tensor(
+ [
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]],
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
+
+ expected = torch.tensor(
+ [
+ [[[1., 1.], [1., 1.]], [[.25, .25], [.25, .25]], [[.0625, .0625], [.0625, .0625]]],
+ [[[1., 1.], [1., 1.]], [[.25, .25], [.25, .25]], [[.0625, .0625], [.0625, .0625]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
p1 = torch.tensor([2., 2.], device=device, dtype=dtype)
p2 = torch.ones(2, device=device, dtype=dtype)
@@ -298,21 +215,16 @@ class TestAdjustGamma:
batch_size, channels, height, width = 2, 3, 4, 5
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)
+ assert gradcheck(kornia.adjust_gamma, (img, 1., 2.), raise_exception=True)
class TestAdjustContrast:
+
def test_factor_zero(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = torch.zeros_like(data)
@@ -321,14 +233,9 @@ class TestAdjustContrast:
def test_factor_one(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = data.clone()
@@ -337,52 +244,30 @@ class TestAdjustContrast:
def test_factor_two(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
-
- expected = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[1., 1.],
- [1., 1.]],
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
- [[.5, .5],
- [.5, .5]]], device=device, dtype=dtype) # 3x2x2
+ expected = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]]], device=device, dtype=dtype
+ ) # 3x2x2
f = kornia.enhance.AdjustContrast(2.)
assert_allclose(f(data), expected)
def test_factor_tensor(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]],
-
- [[.5, .5],
- [.5, .5]]], device=device, dtype=dtype) # 4x2x2
-
- expected = torch.tensor([[[0., 0.],
- [0., 0.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.375, .375],
- [.375, .375]],
-
- [[1., 1.],
- [1., 1.]]], device=device, dtype=dtype) # 4x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]], [[.5, .5], [.5, .5]]],
+ device=device,
+ dtype=dtype
+ ) # 4x2x2
+
+ expected = torch.tensor(
+ [[[0., 0.], [0., 0.]], [[.5, .5], [.5, .5]], [[.375, .375], [.375, .375]], [[1., 1.], [1., 1.]]],
+ device=device,
+ dtype=dtype
+ ) # 4x2x2
factor = torch.tensor([0, 1, 1.5, 2], device=device, dtype=dtype)
@@ -391,41 +276,23 @@ class TestAdjustContrast:
def test_factor_tensor_color(self, device, dtype):
# prepare input data
- data = torch.tensor([[[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]],
-
- [[[0., 0.],
- [0., 0.]],
-
- [[.3, .3],
- [.3, .3]],
-
- [[.6, .6],
- [.6, .6]]]], device=device, dtype=dtype) # 2x3x2x2
-
- expected = torch.tensor([[[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]],
-
- [[[0., 0.],
- [0., 0.]],
-
- [[.6, .6],
- [.6, .6]],
-
- [[1., 1.],
- [1., 1.]]]], device=device, dtype=dtype) # 2x3x2x2
+ data = torch.tensor(
+ [
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]],
+ [[[0., 0.], [0., 0.]], [[.3, .3], [.3, .3]], [[.6, .6], [.6, .6]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
+
+ expected = torch.tensor(
+ [
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]],
+ [[[0., 0.], [0., 0.]], [[.6, .6], [.6, .6]], [[1., 1.], [1., 1.]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
factor = torch.tensor([1, 2], device=device, dtype=dtype)
@@ -434,41 +301,25 @@ class TestAdjustContrast:
def test_factor_tensor_shape(self, device, dtype):
# prepare input data
- data = torch.tensor([[[[1., 1., .5],
- [1., 1., .5]],
-
- [[.5, .5, .25],
- [.5, .5, .25]],
-
- [[.25, .25, .25],
- [.6, .6, .3]]],
-
- [[[0., 0., 1.],
- [0., 0., .25]],
-
- [[.3, .3, .4],
- [.3, .3, .4]],
-
- [[.6, .6, 0.],
- [.3, .2, .1]]]], device=device, dtype=dtype) # 2x3x2x3
-
- expected = torch.tensor([[[[1., 1., .75],
- [1., 1., .75]],
-
- [[.75, .75, .375],
- [.75, .75, .375]],
-
- [[.375, .375, .375],
- [.9, .9, .45]]],
-
- [[[0., 0., 1.],
- [0., 0., .5]],
-
- [[.6, .6, .8],
- [.6, .6, .8]],
-
- [[1., 1., 0.],
- [.6, .4, .2]]]], device=device, dtype=dtype) # 2x3x2x3
+ data = torch.tensor(
+ [
+ [[[1., 1., .5], [1., 1., .5]], [[.5, .5, .25], [.5, .5, .25]], [[.25, .25, .25], [.6, .6, .3]]],
+ [[[0., 0., 1.], [0., 0., .25]], [[.3, .3, .4], [.3, .3, .4]], [[.6, .6, 0.], [.3, .2, .1]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x3
+
+ expected = torch.tensor(
+ [
+ [
+ [[1., 1., .75], [1., 1., .75]], [[.75, .75, .375], [.75, .75, .375]],
+ [[.375, .375, .375], [.9, .9, .45]]
+ ], [[[0., 0., 1.], [0., 0., .5]], [[.6, .6, .8], [.6, .6, .8]], [[1., 1., 0.], [.6, .4, .2]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x3
factor = torch.tensor([1.5, 2.], device=device, dtype=dtype)
@@ -479,21 +330,16 @@ class TestAdjustContrast:
batch_size, channels, height, width = 2, 3, 4, 5
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)
+ assert gradcheck(kornia.adjust_contrast, (img, 2.), raise_exception=True)
class TestAdjustBrightness:
+
def test_factor_zero(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = data.clone()
@@ -502,14 +348,9 @@ class TestAdjustBrightness:
def test_factor_one(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
expected = torch.ones_like(data)
@@ -518,40 +359,24 @@ class TestAdjustBrightness:
def test_factor_minus(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.75, .75],
- [.75, .75]],
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.75, .75], [.75, .75]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ ) # 3x2x2
- [[.25, .25],
- [.25, .25]]], device=device, dtype=dtype) # 3x2x2
-
- expected = torch.tensor([[[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]],
-
- [[0., 0.],
- [0., 0.]]], device=device, dtype=dtype) # 3x2x2
+ expected = torch.tensor(
+ [[[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]], [[0., 0.], [0., 0.]]], device=device, dtype=dtype
+ ) # 3x2x2
f = kornia.enhance.AdjustBrightness(-0.5)
assert_allclose(f(data), expected)
def test_factor_tensor(self, device, dtype):
# prepare input data
- data = torch.tensor([[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]],
-
- [[.5, .5],
- [.5, .5]]], device=device, dtype=dtype) # 4x2x2
+ data = torch.tensor(
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]], [[.5, .5], [.5, .5]]],
+ device=device,
+ dtype=dtype
+ ) # 4x2x2
factor = torch.tensor([0, 0.5, 0.75, 2], device=device, dtype=dtype)
@@ -562,41 +387,23 @@ class TestAdjustBrightness:
def test_factor_tensor_color(self, device, dtype):
# prepare input data
- data = torch.tensor([[[[1., 1.],
- [1., 1.]],
-
- [[.5, .5],
- [.5, .5]],
-
- [[.25, .25],
- [.25, .25]]],
-
- [[[0., 0.],
- [0., 0.]],
-
- [[.3, .3],
- [.3, .3]],
-
- [[.6, .6],
- [.6, .6]]]], device=device, dtype=dtype) # 2x3x2x2
-
- expected = torch.tensor([[[[1., 1.],
- [1., 1.]],
-
- [[.75, .75],
- [.75, .75]],
-
- [[.5, .5],
- [.5, .5]]],
-
- [[[.1, .1],
- [.1, .1]],
-
- [[.4, .4],
- [.4, .4]],
-
- [[.7, .7],
- [.7, .7]]]], device=device, dtype=dtype) # 2x3x2x2
+ data = torch.tensor(
+ [
+ [[[1., 1.], [1., 1.]], [[.5, .5], [.5, .5]], [[.25, .25], [.25, .25]]],
+ [[[0., 0.], [0., 0.]], [[.3, .3], [.3, .3]], [[.6, .6], [.6, .6]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
+
+ expected = torch.tensor(
+ [
+ [[[1., 1.], [1., 1.]], [[.75, .75], [.75, .75]], [[.5, .5], [.5, .5]]],
+ [[[.1, .1], [.1, .1]], [[.4, .4], [.4, .4]], [[.7, .7], [.7, .7]]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x3x2x2
factor = torch.tensor([0.25, 0.1], device=device, dtype=dtype)
@@ -607,11 +414,11 @@ class TestAdjustBrightness:
batch_size, channels, height, width = 2, 3, 4, 5
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)
+ assert gradcheck(kornia.adjust_brightness, (img, 2.), raise_exception=True)
class TestEqualize:
+
def test_shape_equalize(self, device, dtype):
bs, channels, height, width = 1, 3, 4, 5
@@ -633,14 +440,16 @@ class TestEqualize:
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, 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,
+ dtype=dtype
+ )
- expected = self.build_input(bs, channels, height, width,
- device=device, dtype=dtype, row=row_expected)
+ expected = self.build_input(bs, channels, height, width, device=device, dtype=dtype, row=row_expected)
f = kornia.enhance.equalize
@@ -651,14 +460,16 @@ class TestEqualize:
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, 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,
+ dtype=dtype
+ )
- expected = self.build_input(bs, channels, height, width,
- device=device, dtype=dtype, row=row_expected)
+ expected = self.build_input(bs, channels, height, width, device=device, dtype=dtype, row=row_expected)
f = kornia.enhance.equalize
@@ -668,8 +479,7 @@ class TestEqualize:
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)
+ assert gradcheck(kornia.enhance.equalize, (inputs, ), raise_exception=True)
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 3
@@ -693,6 +503,7 @@ class TestEqualize:
class TestEqualize3D:
+
def test_shape_equalize3d(self, device, dtype):
bs, channels, depth, height, width = 1, 3, 6, 10, 10
@@ -714,12 +525,13 @@ class TestEqualize3D:
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, dtype=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,
+ dtype=dtype
+ )
- expected = self.build_input(
- bs, channels, depth, height, width, device, dtype, row=row_expected)
+ expected = self.build_input(bs, channels, depth, height, width, device, dtype, row=row_expected)
f = kornia.enhance.equalize3d
@@ -728,15 +540,15 @@ class TestEqualize3D:
def test_equalize3d_batch(self, device, dtype):
bs, channels, depth, height, width = 2, 3, 6, 10, 10
- inputs3d = self.build_input(
- bs, channels, depth, height, width, device, dtype)
+ 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, dtype=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,
+ dtype=dtype
+ )
- expected = self.build_input(
- bs, channels, depth, height, width, device, dtype, row=row_expected)
+ expected = self.build_input(bs, channels, depth, height, width, device, dtype, row=row_expected)
f = kornia.enhance.equalize3d
@@ -746,8 +558,7 @@ class TestEqualize3D:
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)
+ 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
@@ -780,14 +591,12 @@ class TestSharpness(BaseTester):
img = torch.rand(B, C, H, W, device=device, dtype=dtype)
assert isinstance(TestSharpness.f(img, 0.8), torch.Tensor)
- @pytest.mark.parametrize("batch_size, height, width, factor", [
- (1, 4, 5, 0.0),
- (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(
+ "batch_size, height, width, factor", [
+ (1, 4, 5, 0.0), (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, factor, device, dtype):
inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
@@ -811,10 +620,11 @@ class TestSharpness(BaseTester):
# img = PIL.Image.fromarray(arr)
# en = ImageEnhance.Sharpness(img).enhance(0.8)
# 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)
+ 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
+ )
# If factor == 1, shall return original
# TODO(jian): add test for this case
@@ -831,21 +641,23 @@ class TestSharpness(BaseTester):
# img = PIL.Image.fromarray(arr)
# en = ImageEnhance.Sharpness(img).enhance(0.8)
# 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.6323, 0.3489, 0.4017],
- [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.6323, 0.3489, 0.4017],
- [0.0223, 0.1143, 0.2939],
- [0.5185, 0.6977, 0.8000]]]], device=device, dtype=dtype)
+ expected_08 = torch.tensor(
+ [
+ [[[0.4963, 0.7682, 0.0885], [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
+ )
+
+ expected_08_13 = torch.tensor(
+ [
+ [[[0.4963, 0.7682, 0.0885], [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
+ )
# If factor == 1, shall return original
tol_val: float = utils._get_precision(device, dtype)
@@ -888,15 +700,13 @@ class TestSolarize(BaseTester):
img = torch.rand(B, C, H, W, device=device, dtype=dtype)
assert isinstance(TestSolarize.f(img, 0.8), torch.Tensor)
- @pytest.mark.parametrize("batch_size, height, width, thresholds, additions", [
- (1, 4, 5, 0.8, None),
- (1, 4, 5, 0.8, 0.4),
- (2, 4, 5, 0.8, None),
- (1, 4, 5, torch.tensor(0.8), None),
- (2, 4, 5, torch.tensor(0.8), None),
- (2, 4, 5, torch.tensor([0.8, 0.7]), None),
- (2, 4, 5, torch.tensor([0.8, 0.7]), torch.tensor([0., 0.4]))
- ])
+ @pytest.mark.parametrize(
+ "batch_size, height, width, thresholds, additions", [
+ (1, 4, 5, 0.8, None), (1, 4, 5, 0.8, 0.4), (2, 4, 5, 0.8, None), (1, 4, 5, torch.tensor(0.8), None),
+ (2, 4, 5, torch.tensor(0.8), None), (2, 4, 5, torch.tensor([0.8, 0.7]), None),
+ (2, 4, 5, torch.tensor([0.8, 0.7]), torch.tensor([0., 0.4]))
+ ]
+ )
@pytest.mark.parametrize("channels", [1, 3, 5])
def test_cardinality(self, batch_size, channels, height, width, thresholds, additions, device, dtype):
inputs = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
@@ -925,10 +735,18 @@ class TestSolarize(BaseTester):
# 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)
+ 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)
@@ -968,15 +786,12 @@ class TestPosterize(BaseTester):
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, 1),
- (2, 4, 5, 0),
- (1, 4, 5, torch.tensor(8)),
- (2, 4, 5, torch.tensor(8)),
- (2, 4, 5, torch.tensor([0, 8])),
- (3, 4, 5, torch.tensor([0, 1, 8]))
- ])
+ @pytest.mark.parametrize(
+ "batch_size, height, width, bits", [
+ (1, 4, 5, 8), (2, 4, 5, 1), (2, 4, 5, 0), (1, 4, 5, torch.tensor(8)), (2, 4, 5, torch.tensor(8)),
+ (2, 4, 5, torch.tensor([0, 8])), (3, 4, 5, torch.tensor([0, 1, 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)
@@ -1003,10 +818,9 @@ class TestPosterize(BaseTester):
# 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)
+ 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))
diff --git a/test/enhance/test_core.py b/test/enhance/test_core.py
index b5de824a3..1fc270da9 100644
--- a/test/enhance/test_core.py
+++ b/test/enhance/test_core.py
@@ -29,10 +29,7 @@ class TestAddWeighted:
@pytest.mark.parametrize("size", [2, 3, 4, 5])
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
- )
+ assert_allclose(TestAddWeighted.fcn(src1, alpha, src2, beta, gamma), src1 * alpha + src2 * beta + gamma)
def test_jit(self, device, dtype):
src1, src2, alpha, beta, gamma = self.get_input(device, dtype, size=3)
@@ -45,12 +42,10 @@ class TestAddWeighted:
@pytest.mark.parametrize("size", [2, 3])
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, 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)
+ 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)
diff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.py
index 90a20fb06..322d43825 100644
--- a/test/enhance/test_equalization.py
+++ b/test/enhance/test_equalization.py
@@ -10,6 +10,7 @@ from torch.testing import assert_allclose
class TestEqualization(BaseTester):
+
def test_smoke(self, device, dtype):
C, H, W = 1, 10, 20
img = torch.rand(C, H, W, device=device, dtype=dtype)
@@ -42,13 +43,12 @@ class TestEqualization(BaseTester):
assert isinstance(res, torch.Tensor)
assert res.shape == img.shape
- @pytest.mark.parametrize("B, clip, grid, exception_type", [
- (0, 1., (2, 2), ValueError),
- (1, 1, (2, 2), TypeError),
- (1, 2., 2, TypeError),
- (1, 2., (2, 2, 2), TypeError),
- (1, 2., (2, 2.), TypeError),
- (1, 2., (2, 0), ValueError)])
+ @pytest.mark.parametrize(
+ "B, clip, grid, exception_type", [
+ (0, 1., (2, 2), ValueError), (1, 1, (2, 2), TypeError), (1, 2., 2, TypeError),
+ (1, 2., (2, 2, 2), TypeError), (1, 2., (2, 2.), TypeError), (1, 2., (2, 0), ValueError)
+ ]
+ )
def test_exception(self, B, clip, grid, exception_type):
C, H, W = 1, 10, 20
img = torch.rand(B, C, H, W)
@@ -65,14 +65,15 @@ class TestEqualization(BaseTester):
with pytest.raises(TypeError):
enhance.equalize_clahe([1, 2, 3])
- @pytest.mark.xfail(raises=RuntimeError,
- reason="Sometimes generates the error: 'Numerical gradient for function expected to be zero'")
+ @pytest.mark.xfail(
+ raises=RuntimeError,
+ reason="Sometimes generates the error: 'Numerical gradient for function expected to be zero'"
+ )
def test_gradcheck(self, device, dtype):
bs, channels, height, width = 1, 1, 6, 6
inputs = torch.rand(bs, channels, height, width, device=device, dtype=dtype)
inputs = tensor_to_gradcheck_var(inputs)
- assert gradcheck(enhance.equalize_clahe, (inputs, 40., (2, 2)),
- raise_exception=True)
+ assert gradcheck(enhance.equalize_clahe, (inputs, 40., (2, 2)), raise_exception=True)
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 10, 20
@@ -99,10 +100,23 @@ class TestEqualization(BaseTester):
res = enhance.equalize_clahe(img, clip_limit=clip_limit, grid_size=grid_size)
# NOTE: for next versions we need to improve the computation of the LUT
# and test with a better image
- assert torch.allclose(res[..., 0, :], torch.tensor(
- [[[0.0471, 0.0980, 0.1490, 0.2000, 0.2471, 0.2980, 0.3490, 0.3490,
- 0.4471, 0.4471, 0.5490, 0.5490, 0.6471, 0.6471, 0.6980, 0.7490,
- 0.8000, 0.8471, 0.8980, 1.0000]]], dtype=res.dtype, device=res.device), atol=1e-04, rtol=1e-04)
+ assert torch.allclose(
+ res[..., 0, :],
+ torch.tensor(
+ [
+ [
+ [
+ 0.0471, 0.0980, 0.1490, 0.2000, 0.2471, 0.2980, 0.3490, 0.3490, 0.4471, 0.4471, 0.5490,
+ 0.5490, 0.6471, 0.6471, 0.6980, 0.7490, 0.8000, 0.8471, 0.8980, 1.0000
+ ]
+ ]
+ ],
+ dtype=res.dtype,
+ device=res.device
+ ),
+ atol=1e-04,
+ rtol=1e-04
+ )
def test_ahe(self, img):
clip_limit: float = 0.
@@ -110,10 +124,23 @@ class TestEqualization(BaseTester):
res = enhance.equalize_clahe(img, clip_limit=clip_limit, grid_size=grid_size)
# NOTE: for next versions we need to improve the computation of the LUT
# and test with a better image
- assert torch.allclose(res[..., 0, :], torch.tensor(
- [[[0.2471, 0.4980, 0.7490, 0.6667, 0.4980, 0.4980, 0.7490, 0.4993,
- 0.4980, 0.2471, 0.7490, 0.4993, 0.4980, 0.2471, 0.4980, 0.4993,
- 0.3333, 0.2471, 0.4980, 1.0000]]], dtype=res.dtype, device=res.device), atol=1e-04, rtol=1e-04)
+ assert torch.allclose(
+ res[..., 0, :],
+ torch.tensor(
+ [
+ [
+ [
+ 0.2471, 0.4980, 0.7490, 0.6667, 0.4980, 0.4980, 0.7490, 0.4993, 0.4980, 0.2471, 0.7490,
+ 0.4993, 0.4980, 0.2471, 0.4980, 0.4993, 0.3333, 0.2471, 0.4980, 1.0000
+ ]
+ ]
+ ],
+ dtype=res.dtype,
+ device=res.device
+ ),
+ atol=1e-04,
+ rtol=1e-04
+ )
def test_clahe(self, img):
clip_limit: float = 2.
@@ -121,7 +148,20 @@ class TestEqualization(BaseTester):
res = enhance.equalize_clahe(img, clip_limit=clip_limit, grid_size=grid_size)
# NOTE: for next versions we need to improve the computation of the LUT
# and test with a better image
- assert torch.allclose(res[..., 0, :], torch.tensor(
- [[[0.1216, 0.8745, 0.9373, 0.9163, 0.8745, 0.8745, 0.9373, 0.8745,
- 0.8745, 0.8118, 0.9373, 0.8745, 0.8745, 0.8118, 0.8745, 0.8745,
- 0.8327, 0.8118, 0.8745, 1.0000]]], dtype=res.dtype, device=res.device), atol=1e-04, rtol=1e-04)
+ assert torch.allclose(
+ res[..., 0, :],
+ torch.tensor(
+ [
+ [
+ [
+ 0.1216, 0.8745, 0.9373, 0.9163, 0.8745, 0.8745, 0.9373, 0.8745, 0.8745, 0.8118, 0.9373,
+ 0.8745, 0.8745, 0.8118, 0.8745, 0.8745, 0.8327, 0.8118, 0.8745, 1.0000
+ ]
+ ]
+ ],
+ dtype=res.dtype,
+ device=res.device
+ ),
+ atol=1e-04,
+ rtol=1e-04
+ )
diff --git a/test/enhance/test_histogram.py b/test/enhance/test_histogram.py
index 5a8aae7db..d90adffaa 100644
--- a/test/enhance/test_histogram.py
+++ b/test/enhance/test_histogram.py
@@ -38,7 +38,7 @@ class TestHistogram:
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)
+ bandwidth = torch.tensor(2 * 0.4**2, device=device, dtype=dtype)
inputs = (input1, bins, bandwidth)
op = TestHistogram.fcn
@@ -49,7 +49,7 @@ class TestHistogram:
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)
+ bandwidth = torch.tensor(2 * 0.4**2, device=device, dtype=dtype)
pdf = TestHistogram.fcn(input1, input2, bandwidth)
ans = 0.1 * torch.ones(1, 10, device=device, dtype=dtype)
@@ -91,7 +91,7 @@ class TestHistogram2d:
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)
+ bandwidth = torch.tensor(2 * 0.4**2, device=device, dtype=dtype)
inputs = (input1, input2, bins, bandwidth)
op = TestHistogram2d.fcn
@@ -103,7 +103,7 @@ class TestHistogram2d:
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)
+ bandwidth = torch.tensor(2 * 0.4**2, device=device, dtype=dtype)
pdf = TestHistogram2d.fcn(input1, input2, bins, bandwidth)
ans = 0.1 * kornia.eye_like(10, pdf)
diff --git a/test/enhance/test_normalize.py b/test/enhance/test_normalize.py
index 246636323..13a846d67 100644
--- a/test/enhance/test_normalize.py
+++ b/test/enhance/test_normalize.py
@@ -25,8 +25,7 @@ class TestNormalize:
std = torch.tensor([2.0], device=device, dtype=dtype)
# expected output
- expected = torch.tensor([0.25],
- device=device, dtype=dtype).repeat(1, 2, 2).view_as(data)
+ 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)
@@ -97,7 +96,7 @@ class TestNormalize:
mean = utils.tensor_to_gradcheck_var(mean) # to var
std = utils.tensor_to_gradcheck_var(std) # to var
- assert gradcheck(kornia.enhance.Normalize(mean, std), (data,), raise_exception=True)
+ assert gradcheck(kornia.enhance.Normalize(mean, std), (data, ), raise_exception=True)
def test_single_value(self, device, dtype):
# prepare input data
@@ -123,6 +122,7 @@ class TestNormalize:
class TestDenormalize:
+
def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
@@ -210,7 +210,7 @@ class TestDenormalize:
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)
+ assert gradcheck(kornia.enhance.Denormalize(mean, std), (data, ), raise_exception=True)
def test_single_value(self, device, dtype):
@@ -237,6 +237,7 @@ class TestDenormalize:
class TestNormalizeMinMax(BaseTester):
+
def test_smoke(self, device, dtype):
x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
assert kornia.normalize_min_max(x) is not None
@@ -253,14 +254,12 @@ class TestNormalizeMinMax(BaseTester):
with pytest.raises(TypeError):
assert kornia.normalize_min_max(x, 2., '')
- @pytest.mark.parametrize("input_shape", [
- (1, 2, 3, 4), (2, 1, 4, 3), (1, 3, 2, 1)])
+ @pytest.mark.parametrize("input_shape", [(1, 2, 3, 4), (2, 1, 4, 3), (1, 3, 2, 1)])
def test_cardinality(self, device, dtype, input_shape):
x = torch.rand(input_shape, device=device, dtype=dtype)
assert kornia.normalize_min_max(x).shape == input_shape
- @pytest.mark.parametrize("min_val, max_val", [
- (1., 2.), (2., 3.), (5., 20.), (40., 1000.)])
+ @pytest.mark.parametrize("min_val, max_val", [(1., 2.), (2., 3.), (5., 20.), (40., 1000.)])
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)
@@ -274,11 +273,13 @@ class TestNormalizeMinMax(BaseTester):
[9., 5., 2.],
]]], device=device, dtype=dtype)
- expected = torch.tensor([[[
- [-0.8, -0.6, -0.2],
- [-1., 0., -0.2],
- [1., 0.2, -0.4],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[
+ [-0.8, -0.6, -0.2],
+ [-1., 0., -0.2],
+ [1., 0.2, -0.4],
+ ]]], device=device, dtype=dtype
+ )
actual = kornia.normalize_min_max(x, min_val=-1., max_val=1.)
assert_allclose(actual, expected, atol=1e-6, rtol=1e-6)
@@ -293,7 +294,7 @@ class TestNormalizeMinMax(BaseTester):
@pytest.mark.grad
def test_gradcheck(self, device, dtype):
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)
+ assert gradcheck(kornia.normalize_min_max, (x, ), raise_exception=True)
@pytest.mark.skip(reason="not implemented yet")
@pytest.mark.nn
diff --git a/test/enhance/test_zca.py b/test/enhance/test_zca.py
index 872446ebb..ae7ffeedd 100644
--- a/test/enhance/test_zca.py
+++ b/test/enhance/test_zca.py
@@ -14,10 +14,7 @@ class TestZCA:
@pytest.mark.parametrize("unbiased", [True, False])
def test_zca_unbiased(self, unbiased, device, dtype):
- data = torch.tensor([[0, 1],
- [1, 0],
- [-1, 0],
- [0, -1]], device=device, dtype=dtype)
+ data = torch.tensor([[0, 1], [1, 0], [-1, 0], [0, -1]], device=device, dtype=dtype)
if unbiased:
unbiased_val = 1.5
@@ -38,25 +35,28 @@ class TestZCA:
if 'xla' in device.type:
pytest.skip("buggy with XLA devices.")
- data = torch.tensor([[0, 1],
- [1, 0],
- [-1, 0],
- [0, -1]], device=device, dtype=dtype)
+ data = torch.tensor([[0, 1], [1, 0], [-1, 0], [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],
- ], device=device, dtype=dtype)
+ 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],
- ], device=device, dtype=dtype)
+ 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)
@@ -90,11 +90,7 @@ class TestZCA:
"""
- data = torch.tensor([[2, 0],
- [0, 1],
- [-2, 0],
- [0, -1]],
- device=device, dtype=dtype)
+ data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=dtype)
data = utils.tensor_to_gradcheck_var(data)
@@ -107,17 +103,13 @@ class TestZCA:
def zca_T_inv(x):
return kornia.enhance.zca_mean(x, return_inverse=True)[2]
- assert gradcheck(zca_T, (data,), raise_exception=True)
- assert gradcheck(zca_mu, (data,), raise_exception=True)
- assert gradcheck(zca_T_inv, (data,), raise_exception=True)
+ assert gradcheck(zca_T, (data, ), raise_exception=True)
+ 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, dtype):
- data = torch.tensor([[2, 0],
- [0, 1],
- [-2, 0],
- [0, -1]],
- device=device, dtype=dtype)
+ data = torch.tensor([[2, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=dtype)
data = utils.tensor_to_gradcheck_var(data)
@@ -125,23 +117,18 @@ class TestZCA:
zca = kornia.enhance.ZCAWhitening(detach_transforms=False)
return zca(x, include_fit=True)
- assert gradcheck(zca_fit, (data,), raise_exception=True)
+ assert gradcheck(zca_fit, (data, ), raise_exception=True)
def test_grad_detach_zca(self, device, dtype):
- data = torch.tensor([[1, 0],
- [0, 1],
- [-2, 0],
- [0, -1]],
- device=device, dtype=dtype)
+ data = torch.tensor([[1, 0], [0, 1], [-2, 0], [0, -1]], device=device, dtype=dtype)
data = utils.tensor_to_gradcheck_var(data)
zca = kornia.enhance.ZCAWhitening()
zca.fit(data)
- assert gradcheck(zca,
- (data,), raise_exception=True)
+ assert gradcheck(zca, (data, ), raise_exception=True)
def test_not_fitted(self, device, dtype):
@@ -170,10 +157,7 @@ class TestZCA:
@pytest.mark.parametrize("unbiased", [True, False])
def test_zca_whiten_func_unbiased(self, unbiased, device, dtype):
- data = torch.tensor([[0, 1],
- [1, 0],
- [-1, 0],
- [0, -1]], device=device, dtype=dtype)
+ data = torch.tensor([[0, 1], [1, 0], [-1, 0], [0, -1]], device=device, dtype=dtype)
if unbiased:
unbiased_val = 1.5
diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.py
index 24a7104a3..a7610ec9d 100644
--- a/test/feature/test_affine_shape_estimator.py
+++ b/test/feature/test_affine_shape_estimator.py
@@ -8,6 +8,7 @@ from kornia.feature.affine_shape import *
class TestPatchAffineShapeEstimator:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = PatchAffineShapeEstimator(32).to(device)
@@ -37,8 +38,7 @@ class TestPatchAffineShapeEstimator:
ori = PatchAffineShapeEstimator(width).to(device)
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(ori, (patches, ),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(ori, (patches, ), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -50,6 +50,7 @@ class TestPatchAffineShapeEstimator:
class TestLAFAffineShapeEstimator:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -83,8 +84,13 @@ class TestLAFAffineShapeEstimator:
patches = utils.tensor_to_gradcheck_var(patches) # to var
laf = torch.tensor([[[[5., 0., 26.], [0., 5., 26.]]]], device=device)
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(LAFAffineShapeEstimator(11).to(device), (laf, patches),
- raise_exception=True, rtol=1e-3, atol=1e-3, nondet_tol=1e-4)
+ assert gradcheck(
+ LAFAffineShapeEstimator(11).to(device), (laf, patches),
+ raise_exception=True,
+ rtol=1e-3,
+ atol=1e-3,
+ nondet_tol=1e-4
+ )
@pytest.mark.jit
@pytest.mark.skip("Failing because of extract patches")
@@ -99,6 +105,7 @@ class TestLAFAffineShapeEstimator:
class TestLAFAffNetShapeEstimator:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -140,8 +147,13 @@ class TestLAFAffNetShapeEstimator:
patches = utils.tensor_to_gradcheck_var(patches) # to var
laf = torch.tensor([[[[8., 0., 16.], [0., 8., 16.]]]], device=device)
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype), (laf, patches),
- raise_exception=True, rtol=1e-3, atol=1e-3, nondet_tol=1e-4)
+ assert gradcheck(
+ LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype), (laf, patches),
+ raise_exception=True,
+ rtol=1e-3,
+ atol=1e-3,
+ nondet_tol=1e-4
+ )
@pytest.mark.jit
@pytest.mark.skip("Laf type is not a torch.Tensor????")
diff --git a/test/feature/test_hardnet.py b/test/feature/test_hardnet.py
index 82455409b..437e3b2ee 100644
--- a/test/feature/test_hardnet.py
+++ b/test/feature/test_hardnet.py
@@ -9,6 +9,7 @@ import kornia.testing as utils # test utils
class TestHardNet:
+
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
hardnet = HardNet().to(device)
@@ -27,8 +28,13 @@ class TestHardNet:
patches = torch.rand(2, 1, 32, 32, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
hardnet = HardNet().to(patches.device, patches.dtype)
- assert gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4,
- raise_exception=True, )
+ assert gradcheck(
+ hardnet,
+ (patches, ),
+ eps=1e-4,
+ atol=1e-4,
+ raise_exception=True,
+ )
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -40,6 +46,7 @@ class TestHardNet:
class TestHardNet8:
+
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
hardnet = HardNet8().to(device)
@@ -58,8 +65,13 @@ class TestHardNet8:
patches = torch.rand(2, 1, 32, 32, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
hardnet = HardNet8().to(patches.device, patches.dtype)
- assert gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4,
- raise_exception=True, )
+ assert gradcheck(
+ hardnet,
+ (patches, ),
+ eps=1e-4,
+ atol=1e-4,
+ raise_exception=True,
+ )
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/feature/test_laf.py b/test/feature/test_laf.py
index 0cff50f45..1b78e00ed 100644
--- a/test/feature/test_laf.py
+++ b/test/feature/test_laf.py
@@ -10,6 +10,7 @@ from torch.autograd import gradcheck
class TestAngleToRotationMatrix:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4).to(device)
rotmat = kornia.geometry.transform.imgwarp.angle_to_rotation_matrix(inp)
@@ -17,8 +18,7 @@ class TestAngleToRotationMatrix:
def test_angles(self, device):
ang_deg = torch.tensor([0, 90.], device=device)
- expected = torch.tensor([[[1.0, 0.], [0., 1.0]],
- [[0, 1.0], [-1.0, 0]]], device=device)
+ expected = torch.tensor([[[1.0, 0.], [0., 1.0]], [[0, 1.0], [-1.0, 0]]], device=device)
rotmat = kornia.geometry.transform.imgwarp.angle_to_rotation_matrix(ang_deg)
assert_allclose(rotmat, expected)
@@ -26,9 +26,7 @@ class TestAngleToRotationMatrix:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.geometry.transform.imgwarp.angle_to_rotation_matrix,
- (img,),
- raise_exception=True)
+ assert gradcheck(kornia.geometry.transform.imgwarp.angle_to_rotation_matrix, (img, ), raise_exception=True)
@pytest.mark.jit
@pytest.mark.skip("Problems with kornia.pi")
@@ -41,6 +39,7 @@ class TestAngleToRotationMatrix:
class TestGetLAFScale:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
rotmat = kornia.feature.get_laf_scale(inp)
@@ -57,9 +56,7 @@ class TestGetLAFScale:
batch_size, channels, height, width = 1, 2, 2, 3
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.get_laf_scale,
- (img,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.get_laf_scale, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -71,6 +68,7 @@ class TestGetLAFScale:
class TestGetLAFCenter:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
xy = kornia.feature.get_laf_center(inp)
@@ -87,9 +85,7 @@ class TestGetLAFCenter:
batch_size, channels, height, width = 1, 2, 2, 3
img = torch.rand(batch_size, channels, height, width)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.get_laf_center,
- (img,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.get_laf_center, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -101,6 +97,7 @@ class TestGetLAFCenter:
class TestGetLAFOri:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
ori = kornia.feature.get_laf_orientation(inp)
@@ -117,9 +114,7 @@ class TestGetLAFOri:
batch_size, channels, height, width = 1, 2, 2, 3
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.get_laf_orientation,
- (img,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.get_laf_orientation, (img, ), raise_exception=True)
@pytest.mark.jit
@pytest.mark.skip("Union")
@@ -132,6 +127,7 @@ class TestGetLAFOri:
class TestScaleLAF:
+
def test_shape_float(self, device):
inp = torch.ones(7, 3, 2, 3, device=device).float()
scale = 23.
@@ -156,9 +152,7 @@ class TestScaleLAF:
scale = torch.rand(batch_size, device=device)
scale = utils.tensor_to_gradcheck_var(scale) # to var
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.scale_laf,
- (laf, scale),
- raise_exception=True, atol=1e-4)
+ assert gradcheck(kornia.feature.scale_laf, (laf, scale), raise_exception=True, atol=1e-4)
@pytest.mark.jit
@pytest.mark.skip("Union")
@@ -172,6 +166,7 @@ class TestScaleLAF:
class TestSetLAFOri:
+
def test_shape_tensor(self, device):
inp = torch.ones(7, 3, 2, 3, device=device).float()
ori = torch.ones(7, 3, 1, 1, device=device).float()
@@ -191,9 +186,7 @@ class TestSetLAFOri:
ori = torch.rand(batch_size, channels, 1, 1, device=device)
ori = utils.tensor_to_gradcheck_var(ori) # to var
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.set_laf_orientation,
- (laf, ori),
- raise_exception=True, atol=1e-4)
+ assert gradcheck(kornia.feature.set_laf_orientation, (laf, ori), raise_exception=True, atol=1e-4)
@pytest.mark.jit
@pytest.mark.skip("Union")
@@ -207,6 +200,7 @@ class TestSetLAFOri:
class TestMakeUpright:
+
def test_shape(self, device):
inp = torch.ones(5, 3, 2, 3, device=device)
rotmat = kornia.feature.make_upright(inp)
@@ -236,9 +230,7 @@ class TestMakeUpright:
batch_size, channels, height, width = 14, 2, 2, 3
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.make_upright,
- (img,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.make_upright, (img, ), raise_exception=True)
@pytest.mark.jit
@pytest.mark.skip("Union")
@@ -251,6 +243,7 @@ class TestMakeUpright:
class TestELL2LAF:
+
def test_shape(self, device):
inp = torch.ones(5, 3, 5, device=device)
inp[:, :, 3] = 0
@@ -272,9 +265,7 @@ class TestELL2LAF:
img[:, :, 4] += 1.
# assure it is positive definite
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.ellipse_to_laf,
- (img,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.ellipse_to_laf, (img, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -288,6 +279,7 @@ class TestELL2LAF:
class TestNormalizeLAF:
+
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3)
img = torch.rand(5, 3, 10, 10)
@@ -309,9 +301,10 @@ class TestNormalizeLAF:
img = torch.rand(batch_size, 3, 10, 32)
img = utils.tensor_to_gradcheck_var(img) # to var
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.normalize_laf,
- (laf, img,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.normalize_laf, (
+ laf,
+ img,
+ ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -325,6 +318,7 @@ class TestNormalizeLAF:
class TestLAF2pts:
+
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)
n_pts = 13
@@ -334,12 +328,7 @@ class TestLAF2pts:
laf = torch.tensor([[1, 0, 1], [0, 1, 1]], device=device).float()
laf = laf.view(1, 1, 2, 3)
n_pts = 6
- expected = torch.tensor([[[[1, 1],
- [1, 2],
- [2, 1],
- [1, 0],
- [0, 1],
- [1, 2]]]], device=device).float()
+ expected = torch.tensor([[[[1, 1], [1, 2], [2, 1], [1, 0], [0, 1], [1, 2]]]], device=device).float()
pts = kornia.feature.laf_to_boundary_points(laf, n_pts)
assert_allclose(pts, expected)
@@ -347,9 +336,7 @@ class TestLAF2pts:
batch_size, channels, height, width = 3, 2, 2, 3
laf = torch.rand(batch_size, channels, height, width, device=device)
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.laf_to_boundary_points,
- (laf),
- raise_exception=True)
+ assert gradcheck(kornia.feature.laf_to_boundary_points, (laf), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -361,6 +348,7 @@ class TestLAF2pts:
class TestDenormalizeLAF:
+
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)
img = torch.rand(5, 3, 10, 10, device=device)
@@ -382,9 +370,10 @@ class TestDenormalizeLAF:
img = torch.rand(batch_size, 3, 10, 32, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(kornia.feature.denormalize_laf,
- (laf, img,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.denormalize_laf, (
+ laf,
+ img,
+ ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -398,6 +387,7 @@ class TestDenormalizeLAF:
class TestGenPatchGrid:
+
def test_shape(self, device):
laf = torch.rand(5, 3, 2, 3, device=device)
img = torch.rand(5, 3, 10, 10, device=device)
@@ -413,12 +403,15 @@ class TestGenPatchGrid:
from kornia.feature.laf import generate_patch_grid_from_normalized_LAF
img = utils.tensor_to_gradcheck_var(img) # to var
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(generate_patch_grid_from_normalized_LAF,
- (img, laf, PS,),
- raise_exception=True)
+ assert gradcheck(generate_patch_grid_from_normalized_LAF, (
+ img,
+ laf,
+ PS,
+ ), raise_exception=True)
class TestExtractPatchesSimple:
+
def test_shape(self, device):
laf = torch.rand(5, 4, 2, 3, device=device)
img = torch.rand(5, 3, 100, 30, device=device)
@@ -435,12 +428,11 @@ class TestExtractPatchesSimple:
PS = 11
img = utils.tensor_to_gradcheck_var(img) # to var
nlaf = utils.tensor_to_gradcheck_var(nlaf) # to var
- assert gradcheck(kornia.feature.extract_patches_simple,
- (img, nlaf, PS, False),
- raise_exception=True)
+ assert gradcheck(kornia.feature.extract_patches_simple, (img, nlaf, PS, False), raise_exception=True)
class TestExtractPatchesPyr:
+
def test_shape(self, device):
laf = torch.rand(5, 4, 2, 3, device=device)
img = torch.rand(5, 3, 100, 30, device=device)
@@ -457,12 +449,11 @@ class TestExtractPatchesPyr:
PS = 11
img = utils.tensor_to_gradcheck_var(img) # to var
nlaf = utils.tensor_to_gradcheck_var(nlaf) # to var
- assert gradcheck(kornia.feature.extract_patches_from_pyramid,
- (img, nlaf, PS, False),
- raise_exception=True)
+ assert gradcheck(kornia.feature.extract_patches_from_pyramid, (img, nlaf, PS, False), raise_exception=True)
class TestLAFIsTouchingBoundary:
+
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)
img = torch.rand(5, 3, 10, 10, device=device)
@@ -471,8 +462,7 @@ class TestLAFIsTouchingBoundary:
def test_touch(self, device):
w, h = 10, 5
img = torch.rand(1, 3, h, w, device=device)
- laf = torch.tensor([[[[10, 0, 3], [0, 10, 3]],
- [[1, 0, 5], [0, 1, 2]]]], device=device).float()
+ laf = torch.tensor([[[[10, 0, 3], [0, 10, 3]], [[1, 0, 5], [0, 1, 2]]]], device=device).float()
expected = torch.tensor([[False, True]], device=device)
assert torch.all(kornia.feature.laf_is_inside_image(laf, img) == expected).item()
@@ -480,14 +470,14 @@ class TestLAFIsTouchingBoundary:
def test_jit(self, device, dtype):
w, h = 10, 5
img = torch.rand(1, 3, h, w, device=device)
- laf = torch.tensor([[[[10, 0, 3], [0, 10, 3]],
- [[1, 0, 5], [0, 1, 2]]]], device=device).float()
+ laf = torch.tensor([[[[10, 0, 3], [0, 10, 3]], [[1, 0, 5], [0, 1, 2]]]], device=device).float()
model = kornia.feature.laf_is_inside_image
model_jit = torch.jit.script(kornia.feature.laf_is_inside_image)
assert_allclose(model(laf, img), model_jit(laf, img))
class TestGetCreateLAF:
+
def test_shape(self, device):
xy = torch.ones(1, 3, 2, device=device)
ori = torch.ones(1, 3, 1, device=device)
@@ -521,9 +511,11 @@ class TestGetCreateLAF:
xy = utils.tensor_to_gradcheck_var(torch.rand(batch_size, channels, 2, device=device))
ori = utils.tensor_to_gradcheck_var(torch.rand(batch_size, channels, 1, device=device))
scale = utils.tensor_to_gradcheck_var(torch.abs(torch.rand(batch_size, channels, 1, 1, device=device)))
- assert gradcheck(kornia.feature.laf_from_center_scale_ori,
- (xy, scale, ori,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.laf_from_center_scale_ori, (
+ xy,
+ scale,
+ ori,
+ ), raise_exception=True)
@pytest.mark.skip("Depends on angle-to-rotation-matric")
@pytest.mark.jit
@@ -538,6 +530,7 @@ class TestGetCreateLAF:
class TestGetLAF3pts:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
out = kornia.feature.laf_to_three_points(inp)
@@ -558,9 +551,7 @@ class TestGetLAF3pts:
batch_size, channels, height, width = 3, 2, 2, 3
inp = torch.rand(batch_size, channels, height, width, device=device)
inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(kornia.feature.laf_to_three_points,
- (inp,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.laf_to_three_points, (inp, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -572,6 +563,7 @@ class TestGetLAF3pts:
class TestGetLAFFrom3pts:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 2, 3, device=device)
out = kornia.feature.laf_from_three_points(inp)
@@ -599,9 +591,7 @@ class TestGetLAFFrom3pts:
batch_size, channels, height, width = 3, 2, 2, 3
inp = torch.rand(batch_size, channels, height, width, device=device)
inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(kornia.feature.laf_from_three_points,
- (inp,),
- raise_exception=True)
+ assert gradcheck(kornia.feature.laf_from_three_points, (inp, ), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/feature/test_local_features_orientation.py b/test/feature/test_local_features_orientation.py
index 9098d38d4..9a2da53ac 100644
--- a/test/feature/test_local_features_orientation.py
+++ b/test/feature/test_local_features_orientation.py
@@ -8,6 +8,7 @@ from kornia.feature.orientation import *
class TestPassLAF:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -38,11 +39,11 @@ class TestPassLAF:
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
laf = torch.rand(batch_size, 4, 2, 3)
- assert gradcheck(PassLAF().to(device), (patches, laf),
- raise_exception=True)
+ assert gradcheck(PassLAF().to(device), (patches, laf), raise_exception=True)
class TestPatchDominantGradientOrientation:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = PatchDominantGradientOrientation(32).to(device)
@@ -72,8 +73,7 @@ class TestPatchDominantGradientOrientation:
ori = PatchDominantGradientOrientation(width).to(device)
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(ori, (patches, ),
- raise_exception=True)
+ assert gradcheck(ori, (patches, ), raise_exception=True)
@pytest.mark.jit
@pytest.mark.skip(" Compiled functions can't take variable number")
@@ -86,6 +86,7 @@ class TestPatchDominantGradientOrientation:
class TestOriNet:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = OriNet().to(device=device, dtype=inp.dtype).eval()
@@ -134,6 +135,7 @@ class TestOriNet:
class TestLAFOrienter:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
laf = torch.rand(1, 1, 2, 3, device=device)
@@ -169,5 +171,4 @@ class TestLAFOrienter:
laf[:, :, 0, 1] = 0
laf[:, :, 1, 0] = 0
laf = utils.tensor_to_gradcheck_var(laf) # to var
- assert gradcheck(LAFOrienter(8).to(device), (laf, patches),
- raise_exception=True, rtol=1e-3, atol=1e-3)
+ assert gradcheck(LAFOrienter(8).to(device), (laf, patches), raise_exception=True, rtol=1e-3, atol=1e-3)
diff --git a/test/feature/test_matching.py b/test/feature/test_matching.py
index 33e1ad81f..e22f4c60e 100644
--- a/test/feature/test_matching.py
+++ b/test/feature/test_matching.py
@@ -9,7 +9,8 @@ from kornia.feature.matching import *
class TestMatchNN:
@pytest.mark.parametrize(
- "num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
+ "num_desc1, num_desc2, dim",
+ [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
)
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -34,14 +35,14 @@ class TestMatchNN:
desc2 = torch.rand(7, 8, device=device)
desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- assert gradcheck(match_mnn, (desc1, desc2),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(match_mnn, (desc1, desc2), raise_exception=True, nondet_tol=1e-4)
class TestMatchMNN:
@pytest.mark.parametrize(
- "num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
+ "num_desc1, num_desc2, dim",
+ [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
)
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -68,14 +69,14 @@ class TestMatchMNN:
desc2 = torch.rand(7, 8, device=device)
desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- assert gradcheck(match_mnn, (desc1, desc2),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(match_mnn, (desc1, desc2), raise_exception=True, nondet_tol=1e-4)
class TestMatchSNN:
@pytest.mark.parametrize(
- "num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
+ "num_desc1, num_desc2, dim",
+ [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
)
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -112,14 +113,14 @@ class TestMatchSNN:
desc2 = torch.rand(7, 8, device=device)
desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- assert gradcheck(match_snn, (desc1, desc2, 0.8),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(match_snn, (desc1, desc2, 0.8), raise_exception=True, nondet_tol=1e-4)
class TestMatchSMNN:
@pytest.mark.parametrize(
- "num_desc1, num_desc2, dim", [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
+ "num_desc1, num_desc2, dim",
+ [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
)
def test_shape(self, num_desc1, num_desc2, dim, device):
desc1 = torch.rand(num_desc1, dim, device=device)
@@ -157,5 +158,4 @@ class TestMatchSMNN:
desc2 = torch.rand(7, 8, device=device)
desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
- assert gradcheck(match_smnn, (desc1, desc2, 0.8),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(match_smnn, (desc1, desc2, 0.8), raise_exception=True, nondet_tol=1e-4)
diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.py
index f4f8a140b..2c9979204 100644
--- a/test/feature/test_mkd.py
+++ b/test/feature/test_mkd.py
@@ -16,14 +16,14 @@ def test_get_grid_dict(ps):
assert grid_dict[k].shape == (ps, ps)
- [(1, 1), (1, 2), (2, 1), (5, 6)])
[email protected]("d1,d2", [(1, 1), (1, 2), (2, 1), (5, 6)])
def test_get_kron_order(d1, d2):
out = get_kron_order(d1, d2)
assert out.shape == (d1 * d2, 2)
class TestMKDGradients:
+
@pytest.mark.parametrize("ps", [5, 13, 25])
def test_shape(self, ps, device):
inp = torch.ones(1, 1, ps, ps).to(device)
@@ -63,8 +63,8 @@ class TestMKDGradients:
mkd_grads = MKDGradients()
mkd_grads.to(device)
return mkd_grads(patches)
- assert gradcheck(grad_describe, (patches),
- raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(grad_describe, (patches), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -76,51 +76,45 @@ class TestMKDGradients:
class TestVonMisesKernel:
- @ pytest.mark.parametrize("ps", [5, 13, 25])
+
+ @pytest.mark.parametrize("ps", [5, 13, 25])
def test_shape(self, ps, device):
inp = torch.ones(1, 1, ps, ps).to(device)
- vm = VonMisesKernel(patch_size=ps,
- coeffs=[0.38214156, 0.48090413]).to(device)
+ vm = VonMisesKernel(patch_size=ps, coeffs=[0.38214156, 0.48090413]).to(device)
out = vm(inp)
assert out.shape == (1, 3, ps, ps)
- @ pytest.mark.parametrize("bs", [1, 5, 13])
+ @pytest.mark.parametrize("bs", [1, 5, 13])
def test_batch_shape(self, bs, device):
inp = torch.ones(bs, 1, 15, 15).to(device)
- vm = VonMisesKernel(patch_size=15,
- coeffs=[0.38214156, 0.48090413]).to(device)
+ vm = VonMisesKernel(patch_size=15, coeffs=[0.38214156, 0.48090413]).to(device)
out = vm(inp)
assert out.shape == (bs, 3, 15, 15)
- @ pytest.mark.parametrize("coeffs", COEFFS.values())
+ @pytest.mark.parametrize("coeffs", COEFFS.values())
def test_coeffs(self, coeffs, device):
inp = torch.ones(1, 1, 15, 15).to(device)
- vm = VonMisesKernel(patch_size=15,
- coeffs=coeffs).to(device)
+ vm = VonMisesKernel(patch_size=15, coeffs=coeffs).to(device)
out = vm(inp)
assert out.shape == (1, 2 * len(coeffs) - 1, 15, 15)
def test_print(self, device):
- vm = VonMisesKernel(patch_size=32,
- coeffs=[0.38214156, 0.48090413]).to(device)
+ vm = VonMisesKernel(patch_size=32, coeffs=[0.38214156, 0.48090413]).to(device)
vm.__repr__()
def test_toy(self, device):
patch = torch.ones(1, 1, 6, 6).float().to(device)
patch[0, 0, :, 3:] = 0
- vm = VonMisesKernel(patch_size=6,
- coeffs=[0.38214156, 0.48090413]).to(device)
+ vm = VonMisesKernel(patch_size=6, coeffs=[0.38214156, 0.48090413]).to(device)
out = vm(patch)
expected = torch.ones_like(out[0, 0, :, :]).to(device)
assert_allclose(out[0, 0, :, :], expected * 0.6182, atol=1e-3, rtol=1e-3)
- expected = torch.Tensor([0.3747, 0.3747, 0.3747,
- 0.6935, 0.6935, 0.6935]).to(device)
+ expected = torch.Tensor([0.3747, 0.3747, 0.3747, 0.6935, 0.6935, 0.6935]).to(device)
expected = expected.unsqueeze(0).repeat(6, 1)
assert_allclose(out[0, 1, :, :], expected, atol=1e-3, rtol=1e-3)
- expected = torch.Tensor([0.5835, 0.5835, 0.5835,
- 0.0000, 0.0000, 0.0000]).to(device)
+ expected = torch.Tensor([0.5835, 0.5835, 0.5835, 0.0000, 0.0000, 0.0000]).to(device)
expected = expected.unsqueeze(0).repeat(6, 1)
assert_allclose(out[0, 2, :, :], expected, atol=1e-3, rtol=1e-3)
@@ -133,55 +127,52 @@ class TestVonMisesKernel:
vmkernel = VonMisesKernel(patch_size=ps, coeffs=[0.38214156, 0.48090413]).double()
vmkernel.to(device)
return vmkernel(patches.double())
- assert gradcheck(vm_describe, (patches, ps),
- raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(vm_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device, dtype):
B, C, H, W = 2, 1, 13, 13
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
- model = VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval() # noqa
- model_jit = torch.jit.script(VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()) # noqa
+ model = VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device,
+ patches.dtype).eval() # noqa
+ model_jit = torch.jit.script(
+ VonMisesKernel(patch_size=13, coeffs=[0.38214156, 0.48090413]).to(patches.device, patches.dtype).eval()
+ ) # noqa
assert_allclose(model(patches), model_jit(patches))
class TestEmbedGradients:
- @pytest.mark.parametrize("ps,relative", [(5, True), (13, True), (25, True),
- (5, False), (13, False), (25, False)])
+ @pytest.mark.parametrize("ps,relative", [(5, True), (13, True), (25, True), (5, False), (13, False), (25, False)])
def test_shape(self, ps, relative, device):
inp = torch.ones(1, 2, ps, ps).to(device)
- emb_grads = EmbedGradients(patch_size=ps,
- relative=relative).to(device)
+ emb_grads = EmbedGradients(patch_size=ps, relative=relative).to(device)
out = emb_grads(inp)
assert out.shape == (1, 7, ps, ps)
@pytest.mark.parametrize("bs", [1, 5, 13])
def test_batch_shape(self, bs, device):
inp = torch.ones(bs, 2, 15, 15).to(device)
- emb_grads = EmbedGradients(patch_size=15,
- relative=True).to(device)
+ emb_grads = EmbedGradients(patch_size=15, relative=True).to(device)
out = emb_grads(inp)
assert out.shape == (bs, 7, 15, 15)
def test_print(self, device):
- emb_grads = EmbedGradients(patch_size=15,
- relative=True).to(device)
+ emb_grads = EmbedGradients(patch_size=15, relative=True).to(device)
emb_grads.__repr__()
def test_toy(self, device):
grads = torch.ones(1, 2, 6, 6).float().to(device)
grads[0, 0, :, 3:] = 0
- emb_grads = EmbedGradients(patch_size=6,
- relative=True).to(device)
+ emb_grads = EmbedGradients(patch_size=6, relative=True).to(device)
out = emb_grads(grads)
expected = torch.ones_like(out[0, 0, :, :3]).to(device)
assert_allclose(out[0, 0, :, :3], expected * .3787, atol=1e-3, rtol=1e-3)
assert_allclose(out[0, 0, :, 3:], expected * 0, atol=1e-3, rtol=1e-3)
# TODO: review this test implementation
- @pytest.mark.xfail(
- reason="RuntimeError: Jacobian mismatch for output 0 with respect to input 0,")
+ @pytest.mark.xfail(reason="RuntimeError: Jacobian mismatch for output 0 with respect to input 0,")
def test_gradcheck(self, device):
batch_size, channels, ps = 1, 2, 13
patches = torch.rand(batch_size, channels, ps, ps).to(device)
@@ -191,20 +182,21 @@ class TestEmbedGradients:
emb_grads = EmbedGradients(patch_size=ps, relative=True).double()
emb_grads.to(device)
return emb_grads(patches.double())
- assert gradcheck(emb_grads_describe, (patches, ps),
- raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(emb_grads_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device, dtype):
B, C, H, W = 2, 2, 13, 13
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
model = EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()) # noqa
+ model_jit = torch.jit.script(
+ EmbedGradients(patch_size=W, relative=True).to(patches.device, patches.dtype).eval()
+ ) # noqa
assert_allclose(model(patches), model_jit(patches))
[email protected]("kernel_type,d,ps", [('cart', 9, 9), ('polar', 25, 9),
- ('cart', 9, 16), ('polar', 25, 16)])
[email protected]("kernel_type,d,ps", [('cart', 9, 9), ('polar', 25, 9), ('cart', 9, 16), ('polar', 25, 16)])
def test_spatial_kernel_embedding(kernel_type, ps, d):
grids = get_grid_dict(ps)
spatial_kernel = spatial_kernel_embedding(kernel_type, grids)
@@ -213,49 +205,41 @@ def test_spatial_kernel_embedding(kernel_type, ps, d):
class TestExplicitSpacialEncoding:
- @pytest.mark.parametrize("kernel_type,ps,in_dims", [('cart', 9, 3),
- ('polar', 9, 3), ('cart', 13, 7), ('polar', 13, 7)])
+ @pytest.mark.parametrize(
+ "kernel_type,ps,in_dims", [('cart', 9, 3), ('polar', 9, 3), ('cart', 13, 7), ('polar', 13, 7)]
+ )
def test_shape(self, kernel_type, ps, in_dims, device):
inp = torch.ones(1, in_dims, ps, ps).to(device)
- ese = ExplicitSpacialEncoding(kernel_type=kernel_type,
- fmap_size=ps,
- in_dims=in_dims).to(device)
+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=ps, in_dims=in_dims).to(device)
out = ese(inp)
d_ = 9 if kernel_type == 'cart' else 25
assert out.shape == (1, d_ * in_dims)
- @pytest.mark.parametrize("kernel_type,bs", [('cart', 1), ('cart', 5), ('cart', 13),
- ('polar', 1), ('polar', 5), ('polar', 13)])
+ @pytest.mark.parametrize(
+ "kernel_type,bs", [('cart', 1), ('cart', 5), ('cart', 13), ('polar', 1), ('polar', 5), ('polar', 13)]
+ )
def test_batch_shape(self, kernel_type, bs, device):
inp = torch.ones(bs, 7, 15, 15).to(device)
- ese = ExplicitSpacialEncoding(kernel_type=kernel_type,
- fmap_size=15,
- in_dims=7).to(device)
+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)
out = ese(inp)
d_ = 9 if kernel_type == 'cart' else 25
assert out.shape == (bs, d_ * 7)
@pytest.mark.parametrize("kernel_type", ['cart', 'polar'])
def test_print(self, kernel_type, device):
- ese = ExplicitSpacialEncoding(kernel_type=kernel_type,
- fmap_size=15,
- in_dims=7).to(device)
+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=15, in_dims=7).to(device)
ese.__repr__()
def test_toy(self, device):
inp = torch.ones(1, 2, 6, 6).to(device).float()
inp[0, 0, :, :] = 0
- cart_ese = ExplicitSpacialEncoding(kernel_type='cart',
- fmap_size=6,
- in_dims=2).to(device)
+ cart_ese = ExplicitSpacialEncoding(kernel_type='cart', fmap_size=6, in_dims=2).to(device)
out = cart_ese(inp)
out_part = out[:, :9]
expected = torch.zeros_like(out_part).to(device)
assert_allclose(out_part, expected, atol=1e-3, rtol=1e-3)
- polar_ese = ExplicitSpacialEncoding(kernel_type='polar',
- fmap_size=6,
- in_dims=2).to(device)
+ polar_ese = ExplicitSpacialEncoding(kernel_type='polar', fmap_size=6, in_dims=2).to(device)
out = polar_ese(inp)
out_part = out[:, :25]
expected = torch.zeros_like(out_part).to(device)
@@ -268,65 +252,52 @@ class TestExplicitSpacialEncoding:
patches = utils.tensor_to_gradcheck_var(patches) # to var
def explicit_spatial_describe(patches, ps=13):
- ese = ExplicitSpacialEncoding(kernel_type=kernel_type,
- fmap_size=ps,
- in_dims=2)
+ ese = ExplicitSpacialEncoding(kernel_type=kernel_type, fmap_size=ps, in_dims=2)
ese.to(device)
return ese(patches)
- assert gradcheck(explicit_spatial_describe, (patches, ps),
- raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(explicit_spatial_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device, dtype):
B, C, H, W = 2, 2, 13, 13
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
- model = ExplicitSpacialEncoding(kernel_type='cart',
- fmap_size=W,
- in_dims=2).to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(ExplicitSpacialEncoding(kernel_type='cart',
- fmap_size=W,
- in_dims=2).to(patches.device, patches.dtype).eval()) # noqa
+ model = ExplicitSpacialEncoding(kernel_type='cart', fmap_size=W, in_dims=2).to(patches.device,
+ patches.dtype).eval()
+ model_jit = torch.jit.script(
+ ExplicitSpacialEncoding(kernel_type='cart', fmap_size=W, in_dims=2).to(patches.device, patches.dtype).eval()
+ ) # noqa
assert_allclose(model(patches), model_jit(patches))
class TestWhitening:
- @pytest.mark.parametrize("kernel_type,xform,output_dims", [
- ('cart', None, 3), ('polar', None, 3),
- ('cart', 'lw', 7), ('polar', 'lw', 7),
- ('cart', 'pca', 9), ('polar', 'pca', 9)
- ])
+
+ @pytest.mark.parametrize(
+ "kernel_type,xform,output_dims", [
+ ('cart', None, 3), ('polar', None, 3), ('cart', 'lw', 7), ('polar', 'lw', 7), ('cart', 'pca', 9),
+ ('polar', 'pca', 9)
+ ]
+ )
def test_shape(self, kernel_type, xform, output_dims, device):
in_dims = 63 if kernel_type == 'cart' else 175
- wh = Whitening(xform=xform,
- whitening_model=None,
- in_dims=in_dims,
- output_dims=output_dims).to(device)
+ wh = Whitening(xform=xform, whitening_model=None, in_dims=in_dims, output_dims=output_dims).to(device)
inp = torch.ones(1, in_dims).to(device)
out = wh(inp)
assert out.shape == (1, output_dims)
@pytest.mark.parametrize("bs", [1, 3, 7])
def test_batch_shape(self, bs, device):
- wh = Whitening(xform='lw',
- whitening_model=None,
- in_dims=175,
- output_dims=128).to(device)
+ wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=128).to(device)
inp = torch.ones(bs, 175).to(device)
out = wh(inp)
assert out.shape == (bs, 128)
def test_print(self, device):
- wh = Whitening(xform='lw',
- whitening_model=None,
- in_dims=175,
- output_dims=128).to(device)
+ wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=128).to(device)
wh.__repr__()
def test_toy(self, device):
- wh = Whitening(xform='lw',
- whitening_model=None,
- in_dims=175,
- output_dims=175).to(device)
+ wh = Whitening(xform='lw', whitening_model=None, in_dims=175, output_dims=175).to(device)
inp = torch.ones(1, 175).to(device).float()
out = wh(inp)
expected = torch.ones_like(inp).to(device) * 0.0756
@@ -338,47 +309,43 @@ class TestWhitening:
patches = utils.tensor_to_gradcheck_var(patches) # to var
def whitening_describe(patches, in_dims=175):
- wh = Whitening(xform='lw',
- whitening_model=None,
- in_dims=in_dims).double()
+ wh = Whitening(xform='lw', whitening_model=None, in_dims=in_dims).double()
wh.to(device)
return wh(patches.double())
- assert gradcheck(whitening_describe, (patches, in_dims),
- raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(whitening_describe, (patches, in_dims), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device, dtype):
batch_size, in_dims = 1, 175
patches = torch.rand(batch_size, in_dims).to(device)
- model = Whitening(xform='lw',
- whitening_model=None,
- in_dims=in_dims).to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(Whitening(xform='lw',
- whitening_model=None,
- in_dims=in_dims).to(patches.device, patches.dtype).eval()) # noqa
+ model = Whitening(xform='lw', whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()
+ model_jit = torch.jit.script(
+ Whitening(xform='lw', whitening_model=None, in_dims=in_dims).to(patches.device, patches.dtype).eval()
+ ) # noqa
assert_allclose(model(patches), model_jit(patches))
class TestMKDDescriptor:
dims = {'cart': 63, 'polar': 175, 'concat': 238}
- @pytest.mark.parametrize("ps,kernel_type", [(9, 'concat'),
- (9, 'cart'), (9, 'polar'), (32, 'concat'), (32, 'cart'), (32, 'polar')])
+ @pytest.mark.parametrize(
+ "ps,kernel_type", [(9, 'concat'), (9, 'cart'), (9, 'polar'), (32, 'concat'), (32, 'cart'), (32, 'polar')]
+ )
def test_shape(self, ps, kernel_type, device):
- mkd = MKDDescriptor(patch_size=ps,
- kernel_type=kernel_type,
- whitening=None).to(device)
+ mkd = MKDDescriptor(patch_size=ps, kernel_type=kernel_type, whitening=None).to(device)
inp = torch.ones(1, 1, ps, ps).to(device)
out = mkd(inp)
assert out.shape == (1, self.dims[kernel_type])
- @pytest.mark.parametrize("ps,kernel_type,whitening", [(9, 'concat', 'lw'),
- (9, 'cart', 'lw'), (9, 'polar', 'lw'), (9, 'concat', 'pcawt'),
- (9, 'cart', 'pcawt'), (9, 'polar', 'pcawt')])
+ @pytest.mark.parametrize(
+ "ps,kernel_type,whitening", [
+ (9, 'concat', 'lw'), (9, 'cart', 'lw'), (9, 'polar', 'lw'), (9, 'concat', 'pcawt'), (9, 'cart', 'pcawt'),
+ (9, 'polar', 'pcawt')
+ ]
+ )
def test_whitened_shape(self, ps, kernel_type, whitening, device):
- mkd = MKDDescriptor(patch_size=ps,
- kernel_type=kernel_type,
- whitening=whitening).to(device)
+ mkd = MKDDescriptor(patch_size=ps, kernel_type=kernel_type, whitening=whitening).to(device)
inp = torch.ones(1, 1, ps, ps).to(device)
out = mkd(inp)
output_dims = min(self.dims[kernel_type], 128)
@@ -386,26 +353,19 @@ class TestMKDDescriptor:
@pytest.mark.parametrize("bs", [1, 3, 7])
def test_batch_shape(self, bs, device):
- mkd = MKDDescriptor(patch_size=19,
- kernel_type='concat',
- whitening=None).to(device)
+ mkd = MKDDescriptor(patch_size=19, kernel_type='concat', whitening=None).to(device)
inp = torch.ones(bs, 1, 19, 19).to(device)
out = mkd(inp)
assert out.shape == (bs, 238)
def test_print(self, device):
- mkd = MKDDescriptor(patch_size=32,
- whitening='lw',
- training_set='liberty',
- output_dims=128).to(device)
+ mkd = MKDDescriptor(patch_size=32, whitening='lw', training_set='liberty', output_dims=128).to(device)
mkd.__repr__()
def test_toy(self, device):
inp = torch.ones(1, 1, 6, 6).to(device).float()
inp[0, 0, :, :] = 0
- mkd = MKDDescriptor(patch_size=6,
- kernel_type='concat',
- whitening=None).to(device)
+ mkd = MKDDescriptor(patch_size=6, kernel_type='concat', whitening=None).to(device)
out = mkd(inp)
out_part = out[0, -28:]
expected = torch.zeros_like(out_part).to(device)
@@ -419,13 +379,11 @@ class TestMKDDescriptor:
patches = utils.tensor_to_gradcheck_var(patches) # to var
def mkd_describe(patches, patch_size=19):
- mkd = MKDDescriptor(patch_size=patch_size,
- kernel_type='concat',
- whitening=whitening).double()
+ mkd = MKDDescriptor(patch_size=patch_size, kernel_type='concat', whitening=whitening).double()
mkd.to(device)
return mkd(patches.double())
- assert gradcheck(mkd_describe, (patches, ps),
- raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(mkd_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.skip("neither dict, nor nn.ModuleDict works")
@pytest.mark.jit
@@ -434,30 +392,26 @@ class TestMKDDescriptor:
patches = torch.rand(batch_size, channels, ps, ps).to(device)
kt = 'concat'
wt = 'lw'
- model = MKDDescriptor(patch_size=ps,
- kernel_type=kt,
- whitening=wt).to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(MKDDescriptor(patch_size=ps, kernel_type=kt,
- whitening=wt).to(patches.device, patches.dtype).eval()) # noqa
+ model = MKDDescriptor(patch_size=ps, kernel_type=kt, whitening=wt).to(patches.device, patches.dtype).eval()
+ model_jit = torch.jit.script(
+ MKDDescriptor(patch_size=ps, kernel_type=kt, whitening=wt).to(patches.device, patches.dtype).eval()
+ ) # noqa
assert_allclose(model(patches), model_jit(patches))
class TestSimpleKD:
dims = {'cart': 63, 'polar': 175}
- @pytest.mark.parametrize("ps,kernel_type", [(9, 'cart'), (9, 'polar'),
- (32, 'cart'), (32, 'polar')])
+ @pytest.mark.parametrize("ps,kernel_type", [(9, 'cart'), (9, 'polar'), (32, 'cart'), (32, 'polar')])
def test_shape(self, ps, kernel_type, device):
- skd = SimpleKD(patch_size=ps,
- kernel_type=kernel_type).to(device)
+ skd = SimpleKD(patch_size=ps, kernel_type=kernel_type).to(device)
inp = torch.ones(1, 1, ps, ps).to(device)
out = skd(inp)
assert out.shape == (1, min(128, self.dims[kernel_type]))
@pytest.mark.parametrize("bs", [1, 3, 7])
def test_batch_shape(self, bs, device):
- skd = SimpleKD(patch_size=19,
- kernel_type='polar').to(device)
+ skd = SimpleKD(patch_size=19, kernel_type='polar').to(device)
inp = torch.ones(bs, 1, 19, 19).to(device)
out = skd(inp)
assert out.shape == (bs, 128)
@@ -472,17 +426,19 @@ class TestSimpleKD:
patches = utils.tensor_to_gradcheck_var(patches) # to var
def skd_describe(patches, patch_size=19):
- skd = SimpleKD(patch_size=ps, kernel_type='polar',
- whitening='lw').double()
+ skd = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').double()
skd.to(device)
return skd(patches.double())
- assert gradcheck(skd_describe, (patches, ps),
- raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(skd_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device, dtype):
batch_size, channels, ps = 1, 1, 19
patches = torch.rand(batch_size, channels, ps, ps).to(device)
- model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval() # noqa
- model_jit = torch.jit.script(SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()) # noqa
+ model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device,
+ patches.dtype).eval() # noqa
+ model_jit = torch.jit.script(
+ SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()
+ ) # noqa
assert_allclose(model(patches), model_jit(patches))
diff --git a/test/feature/test_nms.py b/test/feature/test_nms.py
index a2fe76fa0..80142299e 100644
--- a/test/feature/test_nms.py
+++ b/test/feature/test_nms.py
@@ -9,6 +9,7 @@ from torch.autograd import gradcheck
class TestNMS2d:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)
@@ -20,19 +21,33 @@ class TestNMS2d:
assert nms(inp).shape == inp.shape
def test_nms(self, device):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0.1, 1., 0., 1., 1., 0.],
- [0., 0.7, 1.1, 0., 1., 2., 0.],
- [0., 0.8, 1., 0., 1., 1., 0.],
- ]]], device=device).float()
-
- expected = torch.tensor([[[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0, 0, 0., 0, 0., 0.],
- [0., 0, 1.1, 0., 0., 2., 0.],
- [0., 0, 0, 0., 0., 0., 0.],
- ]]], device=device).float()
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0.1, 1., 0., 1., 1., 0.],
+ [0., 0.7, 1.1, 0., 1., 2., 0.],
+ [0., 0.8, 1., 0., 1., 1., 0.],
+ ]
+ ]
+ ],
+ device=device
+ ).float()
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0, 0, 0., 0, 0., 0.],
+ [0., 0, 1.1, 0., 0., 2., 0.],
+ [0., 0, 0, 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device
+ ).float()
nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)
scores = nms(inp)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
@@ -42,11 +57,11 @@ class TestNMS2d:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.nms2d, (img, (3, 3)),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(kornia.feature.nms2d, (img, (3, 3)), raise_exception=True, nondet_tol=1e-4)
class TestNMS3d:
+
def test_shape(self, device):
inp = torch.ones(1, 1, 3, 4, 4, device=device)
nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).to(device)
@@ -58,39 +73,47 @@ class TestNMS3d:
assert nms(inp).shape == inp.shape
def test_nms(self, device):
- inp = torch.tensor([[[
- [[0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]],
- [[0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 1., 2., 1., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.]],
- [[0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]],
- ]]]).to(device)
-
- expected = torch.tensor([[[[[0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]],
- [[0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 2., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]],
- [[0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]]]]]).to(device)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 1., 2., 1., 0.], [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ ]
+ ]
+ ]
+ ).to(device)
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 2., 0., 0.], [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ]
+ ]
+ ]
+ ]
+ ).to(device)
nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).to(device)
scores = nms(inp)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
@@ -99,5 +122,4 @@ class TestNMS3d:
batch_size, channels, depth, height, width = 1, 1, 4, 5, 4
img = torch.rand(batch_size, channels, depth, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.nms3d, (img, (3, 3, 3)),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(kornia.feature.nms3d, (img, (3, 3, 3)), raise_exception=True, nondet_tol=1e-4)
diff --git a/test/feature/test_responces_local_features.py b/test/feature/test_responces_local_features.py
index caacaaabc..0a7727c18 100644
--- a/test/feature/test_responces_local_features.py
+++ b/test/feature/test_responces_local_features.py
@@ -9,6 +9,7 @@ from torch.autograd import gradcheck
class TestCornerHarris:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
harris = kornia.feature.CornerHarris(k=0.04).to(device)
@@ -20,64 +21,90 @@ class TestCornerHarris:
assert harris(inp).shape == (2, 6, 4, 4)
def test_corners(self, device):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]]], device=device).float()
-
- expected = torch.tensor([[[
- [0.0042, 0.0054, 0.0035, 0.0006, 0.0035, 0.0054, 0.0042],
- [0.0054, 0.0068, 0.0046, 0.0014, 0.0046, 0.0068, 0.0054],
- [0.0035, 0.0046, 0.0034, 0.0014, 0.0034, 0.0046, 0.0035],
- [0.0006, 0.0014, 0.0014, 0.0006, 0.0014, 0.0014, 0.0006],
- [0.0035, 0.0046, 0.0034, 0.0014, 0.0034, 0.0046, 0.0035],
- [0.0054, 0.0068, 0.0046, 0.0014, 0.0046, 0.0068, 0.0054],
- [0.0042, 0.0054, 0.0035, 0.0006, 0.0035, 0.0054, 0.0042]]]],
- device=device).float()
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device
+ ).float()
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.0042, 0.0054, 0.0035, 0.0006, 0.0035, 0.0054, 0.0042],
+ [0.0054, 0.0068, 0.0046, 0.0014, 0.0046, 0.0068, 0.0054],
+ [0.0035, 0.0046, 0.0034, 0.0014, 0.0034, 0.0046, 0.0035],
+ [0.0006, 0.0014, 0.0014, 0.0006, 0.0014, 0.0014, 0.0006],
+ [0.0035, 0.0046, 0.0034, 0.0014, 0.0034, 0.0046, 0.0035],
+ [0.0054, 0.0068, 0.0046, 0.0014, 0.0046, 0.0068, 0.0054],
+ [0.0042, 0.0054, 0.0035, 0.0006, 0.0035, 0.0054, 0.0042]
+ ]
+ ]
+ ],
+ device=device
+ ).float()
harris = kornia.feature.CornerHarris(k=0.04).to(device)
scores = harris(inp)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
def test_corners_batch(self, device):
- inp = torch.tensor([[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]], device=device).repeat(2, 1, 1, 1)
- expected = torch.tensor([[
- [0.0415, 0.0541, 0.0346, 0.0058, 0.0346, 0.0541, 0.0415],
- [0.0541, 0.0678, 0.0457, 0.0145, 0.0457, 0.0678, 0.0541],
- [0.0346, 0.0457, 0.0335, 0.0139, 0.0335, 0.0457, 0.0346],
- [0.0058, 0.0145, 0.0139, 0.0064, 0.0139, 0.0145, 0.0058],
- [0.0346, 0.0457, 0.0335, 0.0139, 0.0335, 0.0457, 0.0346],
- [0.0541, 0.0678, 0.0457, 0.0145, 0.0457, 0.0678, 0.0541],
- [0.0415, 0.0541, 0.0346, 0.0058, 0.0346, 0.0541, 0.0415]
- ], [
- [0.0415, 0.0547, 0.0447, 0.0440, 0.0490, 0.0182, 0.0053],
- [0.0547, 0.0688, 0.0557, 0.0549, 0.0610, 0.0229, 0.0066],
- [0.0447, 0.0557, 0.0444, 0.0437, 0.0489, 0.0168, 0.0035],
- [0.0440, 0.0549, 0.0437, 0.0431, 0.0481, 0.0166, 0.0034],
- [0.0490, 0.0610, 0.0489, 0.0481, 0.0541, 0.0205, 0.0060],
- [0.0182, 0.0229, 0.0168, 0.0166, 0.0205, 0.0081, 0.0025],
- [0.0053, 0.0066, 0.0035, 0.0034, 0.0060, 0.0025, 0.0008]
- ]], device=device).repeat(2, 1, 1, 1) / 10.
+ inp = torch.tensor(
+ [
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]
+ ],
+ device=device
+ ).repeat(2, 1, 1, 1)
+ expected = torch.tensor(
+ [
+ [
+ [0.0415, 0.0541, 0.0346, 0.0058, 0.0346, 0.0541, 0.0415],
+ [0.0541, 0.0678, 0.0457, 0.0145, 0.0457, 0.0678, 0.0541],
+ [0.0346, 0.0457, 0.0335, 0.0139, 0.0335, 0.0457, 0.0346],
+ [0.0058, 0.0145, 0.0139, 0.0064, 0.0139, 0.0145, 0.0058],
+ [0.0346, 0.0457, 0.0335, 0.0139, 0.0335, 0.0457, 0.0346],
+ [0.0541, 0.0678, 0.0457, 0.0145, 0.0457, 0.0678, 0.0541],
+ [0.0415, 0.0541, 0.0346, 0.0058, 0.0346, 0.0541, 0.0415]
+ ],
+ [
+ [0.0415, 0.0547, 0.0447, 0.0440, 0.0490, 0.0182, 0.0053],
+ [0.0547, 0.0688, 0.0557, 0.0549, 0.0610, 0.0229, 0.0066],
+ [0.0447, 0.0557, 0.0444, 0.0437, 0.0489, 0.0168, 0.0035],
+ [0.0440, 0.0549, 0.0437, 0.0431, 0.0481, 0.0166, 0.0034],
+ [0.0490, 0.0610, 0.0489, 0.0481, 0.0541, 0.0205, 0.0060],
+ [0.0182, 0.0229, 0.0168, 0.0166, 0.0205, 0.0081, 0.0025],
+ [0.0053, 0.0066, 0.0035, 0.0034, 0.0060, 0.0025, 0.0008]
+ ]
+ ],
+ device=device
+ ).repeat(2, 1, 1, 1) / 10.
scores = kornia.feature.harris_response(inp, k=0.04)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
@@ -86,14 +113,15 @@ class TestCornerHarris:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.harris_response, (img, k),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(kornia.feature.harris_response, (img, k), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
+
@torch.jit.script
def op_script(input, k):
return kornia.feature.harris_response(input, k)
+
k = torch.tensor(0.04)
img = torch.rand(2, 3, 4, 5, device=device)
actual = op_script(img, k)
@@ -102,6 +130,7 @@ class TestCornerHarris:
class TestCornerGFTT:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
shi_tomasi = kornia.feature.CornerGFTT().to(device)
@@ -113,63 +142,90 @@ class TestCornerGFTT:
assert shi_tomasi(inp).shape == (2, 6, 4, 4)
def test_corners(self, device):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]]], device=device).float()
-
- expected = torch.tensor([[[
- [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379],
- [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
- [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
- [0.0121, 0.0168, 0.0245, 0.0276, 0.0245, 0.0168, 0.0121],
- [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
- [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
- [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379]]]], device=device).float()
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device
+ ).float()
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0121, 0.0168, 0.0245, 0.0276, 0.0245, 0.0168, 0.0121],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379]
+ ]
+ ]
+ ],
+ device=device
+ ).float()
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
def test_corners_batch(self, device):
- inp = torch.tensor([[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]], device=device).repeat(2, 1, 1, 1)
- expected = torch.tensor([[
- [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379],
- [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
- [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
- [0.0121, 0.0168, 0.0245, 0.0276, 0.0245, 0.0168, 0.0121],
- [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
- [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
- [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379]
- ], [
- [0.0379, 0.0462, 0.0349, 0.0345, 0.0443, 0.0248, 0.0112],
- [0.0462, 0.0608, 0.0488, 0.0483, 0.0581, 0.0274, 0.0119],
- [0.0349, 0.0488, 0.0669, 0.0664, 0.0460, 0.0191, 0.0084],
- [0.0345, 0.0483, 0.0664, 0.0660, 0.0455, 0.0189, 0.0083],
- [0.0443, 0.0581, 0.0460, 0.0455, 0.0555, 0.0262, 0.0114],
- [0.0248, 0.0274, 0.0191, 0.0189, 0.0262, 0.0172, 0.0084],
- [0.0112, 0.0119, 0.0084, 0.0083, 0.0114, 0.0084, 0.0046]
- ]], device=device).repeat(2, 1, 1, 1)
+ inp = torch.tensor(
+ [
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]
+ ],
+ device=device
+ ).repeat(2, 1, 1, 1)
+ expected = torch.tensor(
+ [
+ [
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0121, 0.0168, 0.0245, 0.0276, 0.0245, 0.0168, 0.0121],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379]
+ ],
+ [
+ [0.0379, 0.0462, 0.0349, 0.0345, 0.0443, 0.0248, 0.0112],
+ [0.0462, 0.0608, 0.0488, 0.0483, 0.0581, 0.0274, 0.0119],
+ [0.0349, 0.0488, 0.0669, 0.0664, 0.0460, 0.0191, 0.0084],
+ [0.0345, 0.0483, 0.0664, 0.0660, 0.0455, 0.0189, 0.0083],
+ [0.0443, 0.0581, 0.0460, 0.0455, 0.0555, 0.0262, 0.0114],
+ [0.0248, 0.0274, 0.0191, 0.0189, 0.0262, 0.0172, 0.0084],
+ [0.0112, 0.0119, 0.0084, 0.0083, 0.0114, 0.0084, 0.0046]
+ ]
+ ],
+ device=device
+ ).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
@@ -178,14 +234,15 @@ class TestCornerGFTT:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.gftt_response, (img),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(kornia.feature.gftt_response, (img), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
+
@torch.jit.script
def op_script(input):
return kornia.feature.gftt_response(input)
+
img = torch.rand(2, 3, 4, 5, device=device)
actual = op_script(img)
expected = kornia.feature.gftt_response(img)
@@ -193,6 +250,7 @@ class TestCornerGFTT:
class TestBlobHessian:
+
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
shi_tomasi = kornia.feature.BlobHessian().to(device)
@@ -204,40 +262,52 @@ class TestBlobHessian:
assert shi_tomasi(inp).shape == (2, 6, 4, 4)
def test_blobs_batch(self, device):
- inp = torch.tensor([[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 0., 0., 0.],
- [0., 1., 1., 1., 0., 0., 0.],
- [0., 1., 1., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 0., 0., 0., 0.],
- [0., 1., 1., 0., 0., 0., 0.],
- [0., 0., 0., 1., 1., 0., 0.],
- [0., 0., 0., 1., 1., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]], device=device).repeat(2, 1, 1, 1)
- expected = torch.tensor([[
- [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],
- [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],
- [-0.0342, 0.0752, 0.1914, 0.0752, -0.0342, -0.0068, 0.0000],
- [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],
- [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],
- [-0.0057, -0.0096, -0.0068, -0.0096, -0.0057, -0.0005, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
- ], [
- [-0.0564, -0.0522, -0.0522, -0.0564, -0.0057, 0.0000, 0.0000],
- [-0.0522, 0.0688, 0.0688, -0.0123, 0.0033, -0.0057, -0.0005],
- [-0.0522, 0.0688, -0.0755, -0.1111, -0.0123, -0.0564, -0.0057],
- [-0.0564, -0.0123, -0.1111, -0.0755, 0.0688, -0.0522, -0.0080],
- [-0.0057, 0.0033, -0.0123, 0.0688, 0.0688, -0.0522, -0.0080],
- [0.0000, -0.0057, -0.0564, -0.0522, -0.0522, -0.0564, -0.0057],
- [0.0000, -0.0005, -0.0057, -0.0080, -0.0080, -0.0057, -0.0005]
- ]], device=device).repeat(2, 1, 1, 1)
+ inp = torch.tensor(
+ [
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 0., 0., 0.],
+ [0., 1., 1., 1., 0., 0., 0.],
+ [0., 1., 1., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 0., 0., 0., 0.],
+ [0., 1., 1., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 1., 0., 0.],
+ [0., 0., 0., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]
+ ],
+ device=device
+ ).repeat(2, 1, 1, 1)
+ expected = torch.tensor(
+ [
+ [
+ [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],
+ [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],
+ [-0.0342, 0.0752, 0.1914, 0.0752, -0.0342, -0.0068, 0.0000],
+ [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],
+ [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],
+ [-0.0057, -0.0096, -0.0068, -0.0096, -0.0057, -0.0005, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ],
+ [
+ [-0.0564, -0.0522, -0.0522, -0.0564, -0.0057, 0.0000, 0.0000],
+ [-0.0522, 0.0688, 0.0688, -0.0123, 0.0033, -0.0057, -0.0005],
+ [-0.0522, 0.0688, -0.0755, -0.1111, -0.0123, -0.0564, -0.0057],
+ [-0.0564, -0.0123, -0.1111, -0.0755, 0.0688, -0.0522, -0.0080],
+ [-0.0057, 0.0033, -0.0123, 0.0688, 0.0688, -0.0522, -0.0080],
+ [0.0000, -0.0057, -0.0564, -0.0522, -0.0522, -0.0564, -0.0057],
+ [0.0000, -0.0005, -0.0057, -0.0080, -0.0080, -0.0057, -0.0005]
+ ]
+ ],
+ device=device
+ ).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.BlobHessian().to(device)
scores = shi_tomasi(inp)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
@@ -246,14 +316,15 @@ class TestBlobHessian:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.hessian_response, (img),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(kornia.feature.hessian_response, (img), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
def test_jit(self, device):
+
@torch.jit.script
def op_script(input):
return kornia.feature.hessian_response(input)
+
img = torch.rand(2, 3, 4, 5, device=device)
actual = op_script(img)
expected = kornia.feature.hessian_response(img)
diff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.py
index 06cb88ada..6ee428779 100644
--- a/test/feature/test_scale_space_detector.py
+++ b/test/feature/test_scale_space_detector.py
@@ -9,6 +9,7 @@ from kornia.feature.scale_space_detector import *
class TestScaleSpaceDetector:
+
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
n_feats = 10
@@ -33,9 +34,7 @@ class TestScaleSpaceDetector:
inp = torch.zeros(1, 1, 33, 33, device=device)
inp[:, :, 13:-13, 13:-13] = 1.0
n_feats = 1
- det = ScaleSpaceDetector(n_feats,
- resp_module=kornia.feature.BlobHessian(),
- mr_size=3.0).to(device)
+ det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device)
lafs, resps = det(inp)
expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device)
expected_resp = torch.tensor([[0.0857]], device=device)
@@ -53,9 +52,7 @@ class TestScaleSpaceDetector:
mask[:, :, 1:-1, 3:-3] = 1.0
n_feats = 1
- det = ScaleSpaceDetector(n_feats,
- resp_module=kornia.feature.BlobHessian(),
- mr_size=3.0).to(device)
+ det = ScaleSpaceDetector(n_feats, resp_module=kornia.feature.BlobHessian(), mr_size=3.0).to(device)
lafs, resps = det(inp, mask)
expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device)
expected_resp = torch.tensor([[0.0857]], device=device)
@@ -66,5 +63,4 @@ class TestScaleSpaceDetector:
batch_size, channels, height, width = 1, 1, 31, 21
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(ScaleSpaceDetector(2).to(device), patches,
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(ScaleSpaceDetector(2).to(device), patches, raise_exception=True, nondet_tol=1e-4)
diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.py
index 82d1e6bd2..c049da191 100644
--- a/test/feature/test_siftdesc.py
+++ b/test/feature/test_siftdesc.py
@@ -12,19 +12,14 @@ def test_get_sift_pooling_kernel(ksize):
assert kernel.shape == (ksize, ksize)
[email protected]("ps,n_bins,ksize,stride,pad",
- [(41, 3, 20, 13, 5),
- (32, 4, 12, 8, 3)])
-def test_get_sift_bin_ksize_stride_pad(ps,
- n_bins,
- ksize,
- stride,
- pad):
[email protected]("ps,n_bins,ksize,stride,pad", [(41, 3, 20, 13, 5), (32, 4, 12, 8, 3)])
+def test_get_sift_bin_ksize_stride_pad(ps, n_bins, ksize, stride, pad):
out = get_sift_bin_ksize_stride_pad(ps, n_bins)
assert out == (ksize, stride, pad)
class TestSIFTDescriptor:
+
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
sift = SIFTDescriptor(32).to(device)
@@ -41,7 +36,7 @@ class TestSIFTDescriptor:
inp = torch.ones(3, 1, 19, 19, device=device)
sift = SIFTDescriptor(19, 5, 3).to(device)
out = sift(inp)
- assert out.shape == (3, (3 ** 2) * 5)
+ assert out.shape == (3, (3**2) * 5)
def test_print(self, device):
sift = SIFTDescriptor(41)
@@ -50,11 +45,7 @@ class TestSIFTDescriptor:
def test_toy(self, device):
patch = torch.ones(1, 1, 6, 6, device=device).float()
patch[0, 0, :, 3:] = 0
- sift = SIFTDescriptor(6,
- num_ang_bins=4,
- num_spatial_bins=1,
- clipval=0.2,
- rootsift=False).to(device)
+ sift = SIFTDescriptor(6, num_ang_bins=4, num_spatial_bins=1, clipval=0.2, rootsift=False).to(device)
out = sift(patch)
expected = torch.tensor([[0, 0, 1., 0]], device=device)
assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
@@ -64,8 +55,7 @@ class TestSIFTDescriptor:
batch_size, channels, height, width = 1, 1, 13, 13
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(sift_describe, (patches, 13),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(sift_describe, (patches, 13), raise_exception=True, nondet_tol=1e-4)
@pytest.mark.jit
@pytest.mark.skip("Compiled functions can't take variable number")
diff --git a/test/feature/test_sosnet.py b/test/feature/test_sosnet.py
index 329ceeeb4..d040845f8 100644
--- a/test/feature/test_sosnet.py
+++ b/test/feature/test_sosnet.py
@@ -9,6 +9,7 @@ import kornia.testing as utils # test utils
class TestSOSNet:
+
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
sosnet = SOSNet(pretrained=False).to(device)
@@ -27,8 +28,13 @@ class TestSOSNet:
patches = torch.rand(2, 1, 32, 32, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
sosnet = SOSNet(pretrained=False).to(patches.device, patches.dtype)
- assert gradcheck(sosnet, (patches,), eps=1e-4, atol=1e-4,
- raise_exception=True, )
+ assert gradcheck(
+ sosnet,
+ (patches, ),
+ eps=1e-4,
+ atol=1e-4,
+ raise_exception=True,
+ )
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/feature/test_tfeat.py b/test/feature/test_tfeat.py
index 634498814..dcdb1e829 100644
--- a/test/feature/test_tfeat.py
+++ b/test/feature/test_tfeat.py
@@ -9,6 +9,7 @@ import kornia.testing as utils # test utils
class TestTFeat:
+
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
tfeat = TFeat().to(device)
@@ -34,8 +35,13 @@ class TestTFeat:
patches = torch.rand(2, 1, 32, 32, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
tfeat = TFeat().to(patches.device, patches.dtype)
- assert gradcheck(tfeat, (patches,), eps=1e-2, atol=1e-2,
- raise_exception=True, )
+ assert gradcheck(
+ tfeat,
+ (patches, ),
+ eps=1e-2,
+ atol=1e-2,
+ raise_exception=True,
+ )
@pytest.mark.jit
def test_jit(self, device, dtype):
diff --git a/test/filters/test_blur.py b/test/filters/test_blur.py
index fba0483a1..b879c2da1 100644
--- a/test/filters/test_blur.py
+++ b/test/filters/test_blur.py
@@ -11,6 +11,7 @@ from torch.autograd import gradcheck
class TestBoxBlur:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
blur = kornia.filters.BoxBlur((3, 3))
@@ -22,13 +23,18 @@ class TestBoxBlur:
assert blur(inp).shape == (2, 6, 4, 4)
def test_kernel_3x3(self, device, dtype):
- inp = torch.tensor([[[
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [2., 2., 2., 2., 2.],
- [2., 2., 2., 2., 2.]
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.],
+ [2., 2., 2., 2., 2.]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
kernel_size = (3, 3)
actual = kornia.filters.box_blur(inp, kernel_size)
@@ -38,13 +44,18 @@ class TestBoxBlur:
# TODO(dmytro): normalized does not make any effect
def test_kernel_3x3_nonormalize(self, device, dtype):
- inp = torch.tensor([[[
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [2., 2., 2., 2., 2.],
- [2., 2., 2., 2., 2.]
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.],
+ [2., 2., 2., 2., 2.]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
kernel_size = (3, 3)
actual = kornia.filters.box_blur(inp, kernel_size, normalized=False)
@@ -53,13 +64,18 @@ class TestBoxBlur:
assert_allclose(actual.sum(), torch.tensor(35.).to(actual), rtol=tol_val, atol=tol_val)
def test_kernel_5x5(self, device, dtype):
- inp = torch.tensor([[[
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [2., 2., 2., 2., 2.],
- [2., 2., 2., 2., 2.]
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.],
+ [2., 2., 2., 2., 2.]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
kernel_size = (5, 5)
expected = inp.sum((1, 2, 3)) / torch.mul(*kernel_size)
@@ -71,13 +87,18 @@ class TestBoxBlur:
def test_kernel_5x5_batch(self, device, dtype):
batch_size = 3
- inp = torch.tensor([[[
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [1., 1., 1., 1., 1.],
- [2., 2., 2., 2., 2.],
- [2., 2., 2., 2., 2.]
- ]]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [1., 1., 1., 1., 1.], [2., 2., 2., 2., 2.],
+ [2., 2., 2., 2., 2.]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).repeat(batch_size, 1, 1, 1)
kernel_size = (5, 5)
expected = inp.sum((1, 2, 3)) / torch.mul(*kernel_size)
@@ -100,8 +121,10 @@ class TestBoxBlur:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.box_blur, (img, (3, 3),),
- raise_exception=True)
+ assert gradcheck(kornia.filters.box_blur, (
+ img,
+ (3, 3),
+ ), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filters.box_blur
diff --git a/test/filters/test_blur_pool.py b/test/filters/test_blur_pool.py
index 1a2a5869d..71a07ba23 100644
--- a/test/filters/test_blur_pool.py
+++ b/test/filters/test_blur_pool.py
@@ -11,6 +11,7 @@ from torch.autograd import gradcheck
class TestMaxBlurPool:
+
@pytest.mark.parametrize("ceil_mode", [True, False])
def test_shape(self, ceil_mode, device, dtype):
inp = torch.zeros(1, 4, 4, 8, device=device, dtype=dtype)
@@ -36,8 +37,10 @@ class TestMaxBlurPool:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.max_blur_pool2d, (img, 3,),
- raise_exception=True)
+ assert gradcheck(kornia.filters.max_blur_pool2d, (
+ img,
+ 3,
+ ), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filters.max_blur_pool2d
@@ -61,6 +64,7 @@ class TestMaxBlurPool:
class TestBlurPool:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 4, 4, 8, device=device, dtype=dtype)
blur = kornia.filters.BlurPool2D(3, stride=1)
@@ -88,8 +92,10 @@ class TestBlurPool:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.blur_pool2d, (img, 3,),
- raise_exception=True)
+ assert gradcheck(kornia.filters.blur_pool2d, (
+ img,
+ 3,
+ ), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filters.blur_pool2d
diff --git a/test/filters/test_filters.py b/test/filters/test_filters.py
index be4e71fca..8cbe14da4 100644
--- a/test/filters/test_filters.py
+++ b/test/filters/test_filters.py
@@ -9,6 +9,7 @@ from torch.testing import assert_allclose
class TestFilter2D:
+
def test_smoke(self, device, dtype):
kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
input = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)
@@ -23,63 +24,111 @@ class TestFilter2D:
def test_mean_filter(self, device, dtype):
kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
- expected = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
actual = kornia.filter2D(input, kernel)
assert_allclose(actual, expected)
def test_mean_filter_2batch_2ch(self, device, dtype):
kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)
-
- expected = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).expand(2, 2, -1, -1)
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).expand(2, 2, -1, -1)
actual = kornia.filter2D(input, kernel)
assert_allclose(actual, expected)
def test_normalized_mean_filter(self, device, dtype):
kernel = torch.ones(1, 3, 3).to(device)
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).expand(2, 2, -1, -1)
nv: float = 5. / 9 # normalization value
- expected = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype).expand(2, 2, -1, -1)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).expand(2, 2, -1, -1)
actual = kornia.filter2D(input, kernel, normalized=True)
@@ -88,21 +137,37 @@ class TestFilter2D:
def test_even_sized_filter(self, device, dtype):
kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 0., 0.],
- [0., 5., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 0., 0.],
+ [0., 5., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
actual = kornia.filter2D(input, kernel)
assert_allclose(actual, expected)
@@ -123,8 +188,7 @@ class TestFilter2D:
# evaluate function gradient
input = utils.tensor_to_gradcheck_var(input) # to var
kernel = utils.tensor_to_gradcheck_var(kernel) # to var
- assert gradcheck(kornia.filter2D, (input, kernel),
- raise_exception=True)
+ assert gradcheck(kornia.filter2D, (input, kernel), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filter2D
@@ -138,6 +202,7 @@ class TestFilter2D:
class TestFilter3D:
+
def test_smoke(self, device, dtype):
kernel = torch.rand(1, 3, 3, 3).to(device)
input = torch.ones(1, 1, 6, 7, 8).to(device)
@@ -152,91 +217,139 @@ class TestFilter3D:
def test_mean_filter(self, device, dtype):
kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
actual = kornia.filter3D(input, kernel)
assert_allclose(actual, expected)
def test_mean_filter_2batch_2ch(self, device, dtype):
kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
input = input.expand(2, 2, -1, -1, -1)
- expected = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 5., 5., 5., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 5., 5., 5., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
expected = expected.expand(2, 2, -1, -1, -1)
actual = kornia.filter3D(input, kernel)
@@ -244,47 +357,71 @@ class TestFilter3D:
def test_normalized_mean_filter(self, device, dtype):
kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
input = input.expand(2, 2, -1, -1, -1)
nv = 5. / 27 # normalization value
- expected = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., nv, nv, nv, 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., nv, nv, nv, 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
expected = expected.expand(2, 2, -1, -1, -1)
actual = kornia.filter3D(input, kernel, normalized=True)
@@ -294,53 +431,76 @@ class TestFilter3D:
def test_even_sized_filter(self, device, dtype):
kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 0., 0.],
- [0., 5., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 5., 5., 0., 0.],
- [0., 5., 5., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 0., 0.],
+ [0., 5., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 5., 5., 0., 0.],
+ [0., 5., 5., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ],
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
actual = kornia.filter3D(input, kernel)
assert_allclose(actual, expected)
def test_noncontiguous(self, device, dtype):
batch_size = 3
- inp = torch.rand(3, 5, 5, 5, device=device, dtype=dtype).expand(
- batch_size, -1, -1, -1, -1)
+ inp = torch.rand(3, 5, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1, -1)
kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)
actual = kornia.filter3D(inp, kernel)
@@ -354,8 +514,7 @@ class TestFilter3D:
# evaluate function gradient
input = utils.tensor_to_gradcheck_var(input) # to var
kernel = utils.tensor_to_gradcheck_var(kernel) # to var
- assert gradcheck(kornia.filter3D, (input, kernel),
- raise_exception=True)
+ assert gradcheck(kornia.filter3D, (input, kernel), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filter3D
diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.py
index 05c8ffbb6..5f12abb7c 100644
--- a/test/filters/test_gaussian.py
+++ b/test/filters/test_gaussian.py
@@ -12,7 +12,7 @@ from torch.testing import assert_allclose
@pytest.mark.parametrize("sigma", [1.5, 5.0])
def test_get_gaussian_kernel(window_size, sigma):
kernel = kornia.get_gaussian_kernel1d(window_size, sigma)
- assert kernel.shape == (window_size,)
+ assert kernel.shape == (window_size, )
assert kernel.sum().item() == pytest.approx(1.0)
@@ -20,7 +20,7 @@ def test_get_gaussian_kernel(window_size, sigma):
@pytest.mark.parametrize("sigma", [1.5, 5.0])
def test_get_gaussian_discrete_kernel(window_size, sigma):
kernel = kornia.get_gaussian_discrete_kernel1d(window_size, sigma)
- assert kernel.shape == (window_size,)
+ assert kernel.shape == (window_size, )
assert kernel.sum().item() == pytest.approx(1.0)
@@ -28,7 +28,7 @@ def test_get_gaussian_discrete_kernel(window_size, sigma):
@pytest.mark.parametrize("sigma", [1.5, 5.0])
def test_get_gaussian_erf_kernel(window_size, sigma):
kernel = kornia.get_gaussian_erf_kernel1d(window_size, sigma)
- assert kernel.shape == (window_size,)
+ assert kernel.shape == (window_size, )
assert kernel.sum().item() == pytest.approx(1.0)
@@ -42,6 +42,7 @@ def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):
class TestGaussianBlur2d:
+
@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
def test_cardinality(self, batch_shape, device, dtype):
kernel_size = (5, 7)
diff --git a/test/filters/test_laplacian.py b/test/filters/test_laplacian.py
index 26a8b1ac3..266479511 100644
--- a/test/filters/test_laplacian.py
+++ b/test/filters/test_laplacian.py
@@ -11,7 +11,7 @@ from torch.testing import assert_allclose
@pytest.mark.parametrize("window_size", [5])
def test_get_laplacian_kernel(window_size):
kernel = kornia.get_laplacian_kernel1d(window_size)
- assert kernel.shape == (window_size,)
+ assert kernel.shape == (window_size, )
assert kernel.sum().item() == pytest.approx(0.0)
@@ -35,6 +35,7 @@ def test_get_laplacian_kernel2d(window_size):
class TestLaplacian:
+
@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
def test_cardinality(self, batch_shape, device, dtype):
kernel_size = 5
@@ -59,8 +60,7 @@ class TestLaplacian:
# evaluate function gradient
input = torch.rand(batch_shape, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input)
- assert gradcheck(
- kornia.laplacian, (input, kernel_size), raise_exception=True)
+ assert gradcheck(kornia.laplacian, (input, kernel_size), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filters.laplacian
diff --git a/test/filters/test_median.py b/test/filters/test_median.py
index 8e3925161..fe0485ef4 100644
--- a/test/filters/test_median.py
+++ b/test/filters/test_median.py
@@ -11,6 +11,7 @@ from torch.autograd import gradcheck
class TestMedianBlur:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
assert kornia.filters.median_blur(inp, (3, 3)).shape == (1, 3, 4, 4)
@@ -20,19 +21,20 @@ class TestMedianBlur:
assert kornia.filters.median_blur(inp, (3, 3)).shape == (2, 6, 4, 4)
def test_kernel_3x3(self, device, dtype):
- inp = torch.tensor([[
- [0., 0., 0., 0., 0.],
- [0., 3., 7., 5., 0.],
- [0., 3., 1., 1., 0.],
- [0., 6., 9., 2., 0.],
- [0., 0., 0., 0., 0.]
- ], [
- [36., 7.0, 25., 0., 0.],
- [3.0, 14., 1.0, 0., 0.],
- [65., 59., 2.0, 0., 0.],
- [0.0, 0.0, 0.0, 0., 0.],
- [0.0, 0.0, 0.0, 0., 0.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor(
+ [
+ [
+ [0., 0., 0., 0., 0.], [0., 3., 7., 5., 0.], [0., 3., 1., 1., 0.], [0., 6., 9., 2., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [36., 7.0, 25., 0., 0.], [3.0, 14., 1.0, 0., 0.], [65., 59., 2.0, 0., 0.], [0.0, 0.0, 0.0, 0., 0.],
+ [0.0, 0.0, 0.0, 0., 0.]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ).repeat(2, 1, 1, 1)
kernel_size = (3, 3)
actual = kornia.filters.median_blur(inp, kernel_size)
@@ -53,8 +55,10 @@ class TestMedianBlur:
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.median_blur, (img, (5, 3),),
- raise_exception=True)
+ assert gradcheck(kornia.filters.median_blur, (
+ img,
+ (5, 3),
+ ), raise_exception=True)
def test_jit(self, device, dtype):
kernel_size = (3, 5)
diff --git a/test/filters/test_motion.py b/test/filters/test_motion.py
index 283b7a484..2635265be 100644
--- a/test/filters/test_motion.py
+++ b/test/filters/test_motion.py
@@ -24,6 +24,7 @@ def test_get_motion_kernel2d(batch_size, ksize, angle, direction):
class TestMotionBlur:
+
@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
def test_motion_blur(self, batch_shape, device, dtype):
ksize = 5
diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.py
index d18e2b1d5..40a3d0b3d 100644
--- a/test/filters/test_sobel.py
+++ b/test/filters/test_sobel.py
@@ -9,6 +9,7 @@ from torch.autograd import gradcheck
class TestSpatialGradient:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
sobel = kornia.filters.SpatialGradient()
@@ -20,109 +21,171 @@ class TestSpatialGradient:
assert sobel(inp).shape == (2, 6, 2, 4, 4)
def test_edges(self, device, dtype):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 1., 0., -1., 0.],
- [1., 3., 0., -3., -1.],
- [2., 4., 0., -4., -2.],
- [1., 3., 0., -3., -1.],
- [0., 1., 0., -1., 0.],
- ], [
- [0., 1., 2., 1., 0.],
- [1., 3., 4., 3., 1.],
- [0., 0., 0., 0., 0],
- [-1., -3., -4., -3., -1],
- [0., -1., -2., -1., 0.],
- ]]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 1., 0., -1., 0.],
+ [1., 3., 0., -3., -1.],
+ [2., 4., 0., -4., -2.],
+ [1., 3., 0., -3., -1.],
+ [0., 1., 0., -1., 0.],
+ ],
+ [
+ [0., 1., 2., 1., 0.],
+ [1., 3., 4., 3., 1.],
+ [0., 0., 0., 0., 0],
+ [-1., -3., -4., -3., -1],
+ [0., -1., -2., -1., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
edges = kornia.filters.spatial_gradient(inp, normalized=False)
assert_allclose(edges, expected)
def test_edges_norm(self, device, dtype):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 1., 0., -1., 0.],
- [1., 3., 0., -3., -1.],
- [2., 4., 0., -4., -2.],
- [1., 3., 0., -3., -1.],
- [0., 1., 0., -1., 0.],
- ], [
- [0., 1., 2., 1., 0.],
- [1., 3., 4., 3., 1.],
- [0., 0., 0., 0., 0],
- [-1., -3., -4., -3., -1],
- [0., -1., -2., -1., 0.],
- ]]]], device=device, dtype=dtype) / 8.0
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 1., 0., -1., 0.],
+ [1., 3., 0., -3., -1.],
+ [2., 4., 0., -4., -2.],
+ [1., 3., 0., -3., -1.],
+ [0., 1., 0., -1., 0.],
+ ],
+ [
+ [0., 1., 2., 1., 0.],
+ [1., 3., 4., 3., 1.],
+ [0., 0., 0., 0., 0],
+ [-1., -3., -4., -3., -1],
+ [0., -1., -2., -1., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) / 8.0
edges = kornia.filters.spatial_gradient(inp, normalized=True)
assert_allclose(edges, expected)
def test_edges_sep(self, device, dtype):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., -1., 0.],
- [1., 1., 0., -1., -1.],
- [0., 1., 0., -1., 0.],
- [0., 0., 0., 0., 0.]
- ], [
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0.],
- [0., -1., -1., -1., 0.],
- [0., 0., -1., 0., 0.]
- ]]]], device=device, dtype=dtype)
-
- edges = kornia.filters.spatial_gradient(inp, 'diff',
- normalized=False)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.], [0., 1., 0., -1., 0.], [1., 1., 0., -1., -1.], [0., 1., 0., -1., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 1., 0., 0.], [0., 1., 1., 1., 0.], [0., 0., 0., 0., 0.], [0., -1., -1., -1., 0.],
+ [0., 0., -1., 0., 0.]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ edges = kornia.filters.spatial_gradient(inp, 'diff', normalized=False)
assert_allclose(edges, expected)
def test_edges_sep_norm(self, device, dtype):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., -1., 0.],
- [1., 1., 0., -1., -1.],
- [0., 1., 0., -1., 0.],
- [0., 0., 0., 0., 0.]
- ], [
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0.],
- [0., -1., -1., -1., 0.],
- [0., 0., -1., 0., 0.]
- ]]]], device=device, dtype=dtype) / 2.0
-
- edges = kornia.filters.spatial_gradient(inp, 'diff',
- normalized=True)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.], [0., 1., 0., -1., 0.], [1., 1., 0., -1., -1.], [0., 1., 0., -1., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 1., 0., 0.], [0., 1., 1., 1., 0.], [0., 0., 0., 0., 0.], [0., -1., -1., -1., 0.],
+ [0., 0., -1., 0., 0.]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) / 2.0
+
+ edges = kornia.filters.spatial_gradient(inp, 'diff', normalized=True)
assert_allclose(edges, expected)
def test_noncontiguous(self, device, dtype):
@@ -139,8 +202,7 @@ class TestSpatialGradient:
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.spatial_gradient, (img,),
- raise_exception=True)
+ assert gradcheck(kornia.filters.spatial_gradient, (img, ), raise_exception=True)
def test_jit(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
@@ -160,6 +222,7 @@ class TestSpatialGradient:
class TestSpatialGradient3d:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 2, 4, 5, 6, device=device, dtype=dtype)
sobel = kornia.filters.SpatialGradient3d()
@@ -172,70 +235,90 @@ class TestSpatialGradient3d:
@pytest.mark.skip("fix due to bug in kernel_flip")
def test_edges(self, device, dtype):
- inp = torch.tensor([[[
- [[0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]],
- [[0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.]],
- [[0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([
- [[[[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
- [0.5000, 0.5000, 0.0000, -0.5000, -0.5000],
- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],
- [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
- [0.0000, 0.5000, 0.5000, 0.5000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, -0.5000, -0.5000, -0.5000, 0.0000],
- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],
- [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
- [0.0000, 0.5000, 0.0000, 0.5000, 0.0000],
- [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
- [0.0000, -0.5000, 0.0000, -0.5000, 0.0000],
- [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 1., 1., 1., 0.], [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ [
+ [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 1., 0., 0.], [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]
+ ],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ],
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
+ [0.5000, 0.5000, 0.0000, -0.5000, -0.5000], [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ],
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ]
+ ],
+ [
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ],
+ [
+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000], [0.0000, 0.5000, 0.5000, 0.5000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, -0.5000, -0.5000, -0.5000, 0.0000],
+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000]
+ ],
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ]
+ ],
+ [
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.0000, 0.5000, 0.0000], [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ],
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ],
+ [
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, -0.5000, 0.0000, -0.5000, 0.0000], [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
+ ]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
edges = kornia.filters.spatial_gradient3d(inp)
assert_allclose(edges, expected)
@@ -243,8 +326,7 @@ class TestSpatialGradient3d:
def test_gradcheck(self, device, dtype):
img = torch.rand(1, 1, 1, 3, 4, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.spatial_gradient3d, (img,),
- raise_exception=True)
+ assert gradcheck(kornia.filters.spatial_gradient3d, (img, ), raise_exception=True)
@pytest.mark.skip("issue with device in kernel generation")
def test_jit(self, device, dtype):
@@ -265,6 +347,7 @@ class TestSpatialGradient3d:
class TestSobel:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
sobel = kornia.filters.Sobel()
@@ -276,21 +359,37 @@ class TestSobel:
assert sobel(inp).shape == (3, 2, 4, 4)
def test_magnitude(self, device, dtype):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 0., 1., 0., 0.],
- [0., 1., 1., 1., 0.],
- [0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[
- [0., 1.4142, 2.0, 1.4142, 0.],
- [1.4142, 4.2426, 4.00, 4.2426, 1.4142],
- [2.0, 4.0000, 0.00, 4.0000, 2.0],
- [1.4142, 4.2426, 4.00, 4.2426, 1.4142],
- [0., 1.4142, 2.0, 1.4142, 0.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0., 1.4142, 2.0, 1.4142, 0.],
+ [1.4142, 4.2426, 4.00, 4.2426, 1.4142],
+ [2.0, 4.0000, 0.00, 4.0000, 2.0],
+ [1.4142, 4.2426, 4.00, 4.2426, 1.4142],
+ [0., 1.4142, 2.0, 1.4142, 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
edges = kornia.filters.sobel(inp, normalized=False, eps=0.)
assert_allclose(edges, expected)
@@ -312,8 +411,7 @@ class TestSobel:
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.sobel, (img, False),
- raise_exception=True)
+ assert gradcheck(kornia.filters.sobel, (img, False), raise_exception=True)
def test_gradcheck(self, device, dtype):
if "cuda" in str(device):
@@ -321,8 +419,7 @@ class TestSobel:
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.sobel, (img, True),
- raise_exception=True)
+ assert gradcheck(kornia.filters.sobel, (img, True), raise_exception=True)
def test_jit(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
diff --git a/test/filters/test_unsharp_mask.py b/test/filters/test_unsharp_mask.py
index c76e08580..2ce399cfe 100644
--- a/test/filters/test_unsharp_mask.py
+++ b/test/filters/test_unsharp_mask.py
@@ -9,6 +9,7 @@ from torch.testing import assert_allclose
class Testunsharp:
+
@pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
def test_cardinality(self, batch_shape, device, dtype):
kernel_size = (5, 7)
diff --git a/test/geometry/epipolar/test_common.py b/test/geometry/epipolar/test_common.py
index c8681f75a..7ac1cfd61 100644
--- a/test/geometry/epipolar/test_common.py
+++ b/test/geometry/epipolar/test_common.py
@@ -4,10 +4,8 @@ import torch
import kornia.geometry.epipolar as epi
-def generate_two_view_random_scene(
- device: torch.device = torch.device("cpu"),
- dtype: torch.dtype = torch.float32
-) -> Dict[str, torch.Tensor]:
+def generate_two_view_random_scene(device: torch.device = torch.device("cpu"),
+ dtype: torch.dtype = torch.float32) -> Dict[str, torch.Tensor]:
num_views: int = 2
num_points: int = 30
@@ -31,8 +29,7 @@ def generate_two_view_random_scene(
P2 = scene['P'][1:2].to(device, dtype)
# fundamental matrix
- F_mat = epi.fundamental_from_projections(
- P1[..., :3, :], P2[..., :3, :])
+ F_mat = epi.fundamental_from_projections(P1[..., :3, :], P2[..., :3, :])
F_mat = epi.normalize_transformation(F_mat)
diff --git a/test/geometry/epipolar/test_epipolar_metrics.py b/test/geometry/epipolar/test_epipolar_metrics.py
index 1c04fb200..a1b2f0a00 100644
--- a/test/geometry/epipolar/test_epipolar_metrics.py
+++ b/test/geometry/epipolar/test_epipolar_metrics.py
@@ -29,8 +29,7 @@ class TestSymmetricalEpipolarDistance:
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)
- assert gradcheck(epi.symmetrical_epipolar_distance, (points1, points2, Fm),
- raise_exception=True)
+ assert gradcheck(epi.symmetrical_epipolar_distance, (points1, points2, Fm), raise_exception=True)
class TestSampsonEpipolarDistance:
@@ -54,5 +53,4 @@ class TestSampsonEpipolarDistance:
points1 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(batch_size, num_points, num_dims, device=device, dtype=torch.float64)
Fm = utils.create_random_fundamental_matrix(batch_size).type_as(points2)
- assert gradcheck(epi.sampson_epipolar_distance, (points1, points2, Fm),
- raise_exception=True)
+ assert gradcheck(epi.sampson_epipolar_distance, (points1, points2, Fm), raise_exception=True)
diff --git a/test/geometry/epipolar/test_essential.py b/test/geometry/epipolar/test_essential.py
index 6fe76b419..559c64761 100644
--- a/test/geometry/epipolar/test_essential.py
+++ b/test/geometry/epipolar/test_essential.py
@@ -10,6 +10,7 @@ import test_common as utils
class TestEssentialFromFundamental:
+
def test_smoke(self, device, dtype):
F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -62,11 +63,15 @@ class TestEssentialFromFundamental:
F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
K1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.essential_from_fundamental,
- (F_mat, K1, K2,), raise_exception=True)
+ assert gradcheck(epi.essential_from_fundamental, (
+ F_mat,
+ K1,
+ K2,
+ ), raise_exception=True)
class TestRelativeCameraMotion:
+
def test_smoke(self, device, dtype):
R1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
t1 = torch.rand(1, 3, 1, device=device, dtype=dtype)
@@ -76,7 +81,12 @@ class TestRelativeCameraMotion:
assert R.shape == (1, 3, 3)
assert t.shape == (1, 3, 1)
- @pytest.mark.parametrize("batch_size", [1, 3, 5, 8, ])
+ @pytest.mark.parametrize("batch_size", [
+ 1,
+ 3,
+ 5,
+ 8,
+ ])
def test_shape(self, batch_size, device, dtype):
B: int = batch_size
R1 = torch.rand(B, 3, 3, device=device, dtype=dtype)
@@ -134,11 +144,16 @@ class TestRelativeCameraMotion:
R2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
t1 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
t2 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
- assert gradcheck(epi.relative_camera_motion,
- (R1, t1, R2, t2,), raise_exception=True)
+ assert gradcheck(epi.relative_camera_motion, (
+ R1,
+ t1,
+ R2,
+ t2,
+ ), raise_exception=True)
class TestEssentalFromRt:
+
def test_smoke(self, device, dtype):
R1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
t1 = torch.rand(1, 3, 1, device=device, dtype=dtype)
@@ -147,7 +162,12 @@ class TestEssentalFromRt:
E_mat = epi.essential_from_Rt(R1, t1, R2, t2)
assert E_mat.shape == (1, 3, 3)
- @pytest.mark.parametrize("batch_size", [1, 3, 5, 8, ])
+ @pytest.mark.parametrize("batch_size", [
+ 1,
+ 3,
+ 5,
+ 8,
+ ])
def test_shape(self, batch_size, device, dtype):
B: int = batch_size
R1 = torch.rand(B, 3, 3, device=device, dtype=dtype)
@@ -162,11 +182,9 @@ class TestEssentalFromRt:
scene = utils.generate_two_view_random_scene(device, dtype)
- E_from_Rt = epi.essential_from_Rt(
- scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+ E_from_Rt = epi.essential_from_Rt(scene['R1'], scene['t1'], scene['R2'], scene['t2'])
- E_from_F = epi.essential_from_fundamental(
- scene['F'], scene['K1'], scene['K2'])
+ E_from_F = epi.essential_from_fundamental(scene['F'], scene['K1'], scene['K2'])
E_from_Rt_norm = epi.normalize_transformation(E_from_Rt)
E_from_F_norm = epi.normalize_transformation(E_from_F)
@@ -178,11 +196,16 @@ class TestEssentalFromRt:
R2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
t1 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
t2 = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
- assert gradcheck(epi.essential_from_Rt,
- (R1, t1, R2, t2,), raise_exception=True)
+ assert gradcheck(epi.essential_from_Rt, (
+ R1,
+ t1,
+ R2,
+ t2,
+ ), raise_exception=True)
class TestDecomposeEssentialMatrix:
+
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
R1, R2, t = epi.decompose_essential_matrix(E_mat)
@@ -191,14 +214,17 @@ class TestDecomposeEssentialMatrix:
assert t.shape == (1, 3, 1)
@pytest.mark.parametrize("batch_shape", [
- (1, 3, 3), (2, 3, 3), (2, 1, 3, 3), (3, 2, 1, 3, 3),
+ (1, 3, 3),
+ (2, 3, 3),
+ (2, 1, 3, 3),
+ (3, 2, 1, 3, 3),
])
def test_shape(self, batch_shape, device, dtype):
E_mat = torch.rand(batch_shape, device=device, dtype=dtype)
R1, R2, t = epi.decompose_essential_matrix(E_mat)
assert R1.shape == batch_shape
assert R2.shape == batch_shape
- assert t.shape == batch_shape[:-1] + (1,)
+ assert t.shape == batch_shape[:-1] + (1, )
def test_gradcheck(self, device):
E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
@@ -212,12 +238,13 @@ class TestDecomposeEssentialMatrix:
def eval_vec(input):
return epi.decompose_essential_matrix(input)[2]
- assert gradcheck(eval_rot1, (E_mat,), raise_exception=True)
- assert gradcheck(eval_rot2, (E_mat,), raise_exception=True)
- assert gradcheck(eval_vec, (E_mat,), raise_exception=True)
+ assert gradcheck(eval_rot1, (E_mat, ), raise_exception=True)
+ assert gradcheck(eval_rot2, (E_mat, ), raise_exception=True)
+ assert gradcheck(eval_vec, (E_mat, ), raise_exception=True)
class TestMotionFromEssential:
+
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
Rs, Ts = epi.motion_from_essential(E_mat)
@@ -225,7 +252,10 @@ class TestMotionFromEssential:
assert Ts.shape == (1, 4, 3, 1)
@pytest.mark.parametrize("batch_shape", [
- (1, 3, 3), (2, 3, 3), (2, 1, 3, 3), (3, 2, 1, 3, 3),
+ (1, 3, 3),
+ (2, 3, 3),
+ (2, 1, 3, 3),
+ (3, 2, 1, 3, 3),
])
def test_shape(self, batch_shape, device, dtype):
E_mat = torch.rand(batch_shape, device=device, dtype=dtype)
@@ -261,11 +291,12 @@ class TestMotionFromEssential:
def eval_vec(input):
return epi.motion_from_essential(input)[1]
- assert gradcheck(eval_rot, (E_mat,), raise_exception=True)
- assert gradcheck(eval_vec, (E_mat,), raise_exception=True)
+ assert gradcheck(eval_rot, (E_mat, ), raise_exception=True)
+ assert gradcheck(eval_vec, (E_mat, ), raise_exception=True)
class TestMotionFromEssentialChooseSolution:
+
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -278,7 +309,10 @@ class TestMotionFromEssentialChooseSolution:
assert X.shape == (1, 1, 3)
@pytest.mark.parametrize("batch_size, num_points", [
- (1, 3), (2, 3), (2, 8), (3, 2),
+ (1, 3),
+ (2, 3),
+ (2, 8),
+ (3, 2),
])
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
@@ -335,15 +369,14 @@ class TestMotionFromEssentialChooseSolution:
scene = utils.generate_two_view_random_scene(device, dtype)
- E_mat = epi.essential_from_Rt(
- scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+ E_mat = epi.essential_from_Rt(scene['R1'], scene['t1'], scene['R2'], scene['t2'])
- R, t = epi.relative_camera_motion(
- scene['R1'], scene['t1'], scene['R2'], scene['t2'])
+ R, t = epi.relative_camera_motion(scene['R1'], scene['t1'], scene['R2'], scene['t2'])
t = torch.nn.functional.normalize(t, dim=1)
R_hat, t_hat, X_hat = epi.motion_from_essential_choose_solution(
- E_mat, scene['K1'], scene['K2'], scene['x1'], scene['x2'])
+ E_mat, scene['K1'], scene['K2'], scene['x1'], scene['x2']
+ )
assert_allclose(t, t_hat)
assert_allclose(R, R_hat, rtol=1e-4, atol=1e-4)
@@ -355,5 +388,10 @@ class TestMotionFromEssentialChooseSolution:
x1 = torch.rand(1, 2, 2, device=device, dtype=torch.float64)
x2 = torch.rand(1, 2, 2, device=device, dtype=torch.float64)
- assert gradcheck(epi.motion_from_essential_choose_solution,
- (E_mat, K1, K2, x1, x2,), raise_exception=True)
+ assert gradcheck(epi.motion_from_essential_choose_solution, (
+ E_mat,
+ K1,
+ K2,
+ x1,
+ x2,
+ ), raise_exception=True)
diff --git a/test/geometry/epipolar/test_fundamental.py b/test/geometry/epipolar/test_fundamental.py
index d43aae06f..efb4b1b1f 100644
--- a/test/geometry/epipolar/test_fundamental.py
+++ b/test/geometry/epipolar/test_fundamental.py
@@ -10,6 +10,7 @@ import test_common as utils
class TestNormalizePoints:
+
def test_smoke(self, device, dtype):
points = torch.rand(1, 1, 2, device=device, dtype=dtype)
output = epi.normalize_points(points)
@@ -18,7 +19,8 @@ class TestNormalizePoints:
assert output[1].shape == (1, 3, 3)
@pytest.mark.parametrize(
- "batch_size, num_points", [(1, 2), (2, 3), (3, 2)],
+ "batch_size, num_points",
+ [(1, 2), (2, 3), (3, 2)],
)
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
@@ -28,9 +30,7 @@ class TestNormalizePoints:
assert output[1].shape == (B, 3, 3)
def test_mean_std(self, device, dtype):
- points = torch.tensor([[
- [0., 0.], [0., 2.], [1., 1.], [1., 3.]
- ]], device=device, dtype=dtype)
+ points = torch.tensor([[[0., 0.], [0., 2.], [1., 1.], [1., 3.]]], device=device, dtype=dtype)
points_norm, trans = epi.normalize_points(points)
points_std, points_mean = torch.std_mean(points_norm, dim=1)
@@ -39,19 +39,20 @@ class TestNormalizePoints:
assert (points_std < 2.).all()
def test_gradcheck(self, device):
- points = torch.rand(2, 3, 2,
- device=device, requires_grad=True, dtype=torch.float64)
- assert gradcheck(epi.normalize_points, (points,), raise_exception=True)
+ points = torch.rand(2, 3, 2, device=device, requires_grad=True, dtype=torch.float64)
+ assert gradcheck(epi.normalize_points, (points, ), raise_exception=True)
class TestNormalizeTransformation:
+
def test_smoke(self, device, dtype):
trans = torch.rand(2, 2, device=device, dtype=dtype)
trans_norm = epi.normalize_transformation(trans)
assert trans_norm.shape == (2, 2)
@pytest.mark.parametrize(
- "batch_size, rows, cols", [(1, 2, 2), (2, 3, 3), (3, 4, 4), (2, 1, 2)],
+ "batch_size, rows, cols",
+ [(1, 2, 2), (2, 3, 3), (3, 4, 4), (2, 1, 2)],
)
def test_shape(self, batch_size, rows, cols, device, dtype):
B, N, M = batch_size, rows, cols
@@ -60,27 +61,15 @@ class TestNormalizeTransformation:
assert trans_norm.shape == (B, N, M)
def test_check_last_val(self, device, dtype):
- trans = torch.tensor([[
- [0.0, 0.0, 1.0],
- [0.0, 2.0, 0.0],
- [0.5, 0.0, 0.5]
- ]], device=device, dtype=dtype)
+ trans = torch.tensor([[[0.0, 0.0, 1.0], [0.0, 2.0, 0.0], [0.5, 0.0, 0.5]]], device=device, dtype=dtype)
- trans_expected = torch.tensor([[
- [0.0, 0.0, 2.0],
- [0.0, 4.0, 0.0],
- [1.0, 0.0, 1.0]
- ]], device=device, dtype=dtype)
+ trans_expected = torch.tensor([[[0.0, 0.0, 2.0], [0.0, 4.0, 0.0], [1.0, 0.0, 1.0]]], device=device, dtype=dtype)
trans_norm = epi.normalize_transformation(trans)
assert_allclose(trans_norm, trans_expected, atol=1e-4, rtol=1e-4)
def test_check_corner_case(self, device, dtype):
- trans = torch.tensor([[
- [0.0, 0.0, 1.0],
- [0.0, 2.0, 0.0],
- [0.5, 0.0, 0.0]
- ]], device=device, dtype=dtype)
+ trans = torch.tensor([[[0.0, 0.0, 1.0], [0.0, 2.0, 0.0], [0.5, 0.0, 0.0]]], device=device, dtype=dtype)
trans_expected = trans.clone()
@@ -88,12 +77,12 @@ class TestNormalizeTransformation:
assert_allclose(trans_norm, trans_expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
- trans = torch.rand(2, 3, 3,
- device=device, requires_grad=True, dtype=torch.float64)
- assert gradcheck(epi.normalize_transformation, (trans,), raise_exception=True)
+ trans = torch.rand(2, 3, 3, device=device, requires_grad=True, dtype=torch.float64)
+ assert gradcheck(epi.normalize_transformation, (trans, ), raise_exception=True)
class TestFindFundamental:
+
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 1, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 1, 2, device=device, dtype=dtype)
@@ -102,7 +91,8 @@ class TestFindFundamental:
assert F_mat.shape == (1, 3, 3)
@pytest.mark.parametrize(
- "batch_size, num_points", [(1, 2), (2, 3), (3, 2)],
+ "batch_size, num_points",
+ [(1, 2), (2, 3), (3, 2)],
)
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
@@ -113,29 +103,27 @@ class TestFindFundamental:
assert F_mat.shape == (B, 3, 3)
def test_opencv(self, device, dtype):
- points1 = torch.tensor([[
- [0.8569, 0.5982],
- [0.0059, 0.9649],
- [0.1968, 0.8846],
- [0.6084, 0.3467],
- [0.9633, 0.5274],
- [0.8941, 0.8939],
- [0.0863, 0.5133],
- [0.2645, 0.8882],
- [0.2411, 0.3045],
- [0.8199, 0.4107]]], device=device, dtype=dtype)
-
- points2 = torch.tensor([[
- [0.0928, 0.3013],
- [0.0989, 0.9649],
- [0.0341, 0.4827],
- [0.8294, 0.4469],
- [0.2230, 0.2998],
- [0.1722, 0.8182],
- [0.5264, 0.8869],
- [0.8908, 0.1233],
- [0.2338, 0.7663],
- [0.4466, 0.5696]]], device=device, dtype=dtype)
+ points1 = torch.tensor(
+ [
+ [
+ [0.8569, 0.5982], [0.0059, 0.9649], [0.1968, 0.8846], [0.6084, 0.3467], [0.9633, 0.5274],
+ [0.8941, 0.8939], [0.0863, 0.5133], [0.2645, 0.8882], [0.2411, 0.3045], [0.8199, 0.4107]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ points2 = torch.tensor(
+ [
+ [
+ [0.0928, 0.3013], [0.0989, 0.9649], [0.0341, 0.4827], [0.8294, 0.4469], [0.2230, 0.2998],
+ [0.1722, 0.8182], [0.5264, 0.8869], [0.8908, 0.1233], [0.2338, 0.7663], [0.4466, 0.5696]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
weights = torch.ones(1, 10, device=device, dtype=dtype)
@@ -145,10 +133,16 @@ class TestFindFundamental:
# points1.detach().numpy().reshape(-1, 1, 2),
# points2.detach().numpy().reshape(-1, 1, 2), cv2.FM_8POINT)
- Fm_expected = torch.tensor([[
- [-0.47408533, 0.22033807, -0.00346677],
- [0.54935973, 1.31080955, -1.25028275],
- [-0.36690215, -1.08143769, 1.]]], device=device, dtype=dtype)
+ Fm_expected = torch.tensor(
+ [
+ [
+ [-0.47408533, 0.22033807, -0.00346677], [0.54935973, 1.31080955, -1.25028275],
+ [-0.36690215, -1.08143769, 1.]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
F_mat = epi.find_fundamental(points1, points2, weights)
assert_allclose(F_mat, Fm_expected, rtol=1e-4, atol=1e-4)
@@ -171,11 +165,15 @@ class TestFindFundamental:
points1 = torch.rand(1, 10, 2, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(1, 10, 2, device=device, dtype=torch.float64)
weights = torch.ones(1, 10, device=device, dtype=torch.float64)
- assert gradcheck(epi.find_fundamental,
- (points1, points2, weights,), raise_exception=True)
+ assert gradcheck(epi.find_fundamental, (
+ points1,
+ points2,
+ weights,
+ ), raise_exception=True)
class TestComputeCorrespondEpilimes:
+
def test_smoke(self, device, dtype):
point = torch.rand(1, 1, 2, device=device, dtype=dtype)
F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -183,7 +181,8 @@ class TestComputeCorrespondEpilimes:
assert lines.shape == (1, 1, 3)
@pytest.mark.parametrize(
- "batch_size, num_points", [(1, 2), (2, 3), (3, 2)],
+ "batch_size, num_points",
+ [(1, 2), (2, 3), (3, 2)],
)
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
@@ -201,11 +200,15 @@ class TestComputeCorrespondEpilimes:
[0.8163, 0.8500],
]], device=device, dtype=dtype)
- F_mat = torch.tensor([[
- [0.1185, 0.4438, 0.9869],
- [0.5670, 0.9447, 0.4100],
- [0.1546, 0.2554, 0.4485],
- ]], device=device, dtype=dtype)
+ F_mat = torch.tensor(
+ [[
+ [0.1185, 0.4438, 0.9869],
+ [0.5670, 0.9447, 0.4100],
+ [0.1546, 0.2554, 0.4485],
+ ]],
+ device=device,
+ dtype=dtype
+ )
# generated with OpenCV using above points
# import cv2
@@ -213,10 +216,12 @@ class TestComputeCorrespondEpilimes:
# point.detach().numpy().reshape(-1, 1, 2), 0,
# F_mat.detach().numpy()[0]).transpose(1, 0, 2)
- lines_expected = torch.tensor([[
- [0.64643687, 0.7629675, 0.35658622],
- [0.65710586, 0.7537983, 0.35616538],
- ]], device=device, dtype=dtype)
+ lines_expected = torch.tensor(
+ [[
+ [0.64643687, 0.7629675, 0.35658622],
+ [0.65710586, 0.7537983, 0.35616538],
+ ]], device=device, dtype=dtype
+ )
lines_est = epi.compute_correspond_epilines(point, F_mat)
assert_allclose(lines_est, lines_expected, rtol=1e-4, atol=1e-4)
@@ -224,11 +229,14 @@ class TestComputeCorrespondEpilimes:
def test_gradcheck(self, device):
point = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.compute_correspond_epilines,
- (point, F_mat,), raise_exception=True)
+ assert gradcheck(epi.compute_correspond_epilines, (
+ point,
+ F_mat,
+ ), raise_exception=True)
class TestFundamentlFromEssential:
+
def test_smoke(self, device, dtype):
E_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
K1 = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -267,11 +275,15 @@ class TestFundamentlFromEssential:
E_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
K1 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
K2 = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.fundamental_from_essential,
- (E_mat, K1, K2,), raise_exception=True)
+ assert gradcheck(epi.fundamental_from_essential, (
+ E_mat,
+ K1,
+ K2,
+ ), raise_exception=True)
class TestFundamentalFromProjections:
+
def test_smoke(self, device, dtype):
P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
@@ -316,32 +328,66 @@ class TestFundamentalFromProjections:
def test_gradcheck(self, device):
P1 = torch.rand(1, 3, 4, device=device, dtype=torch.float64, requires_grad=True)
P2 = torch.rand(1, 3, 4, device=device, dtype=torch.float64)
- assert gradcheck(epi.fundamental_from_projections,
- (P1, P2,), raise_exception=True)
+ assert gradcheck(epi.fundamental_from_projections, (
+ P1,
+ P2,
+ ), raise_exception=True)
def test_batch_support_check(self, device, dtype):
- P1_batch = torch.tensor([[[9.4692e+02, -9.6658e+02, 6.0862e+02, -2.3076e+05],
- [-2.1829e+02, 5.4163e+02, 1.3445e+03, -6.4387e+05],
- [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e+02]],
-
- [[9.4692e+02, -9.6658e+02, 6.0862e+02, -2.3076e+05],
- [-2.1829e+02, 5.4163e+02, 1.3445e+03, -6.4387e+05],
- [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e+02]]], device=device, dtype=dtype)
- P1 = torch.tensor([[[9.4692e+02, -9.6658e+02, 6.0862e+02, -2.3076e+05],
- [-2.1829e+02, 5.4163e+02, 1.3445e+03, -6.4387e+05],
- [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e+02]],
- ], device=device, dtype=dtype)
- P2_batch = torch.tensor([[[1.1518e+03, -7.5822e+02, 5.4764e+02, -1.9764e+05],
- [-2.1548e+02, 5.3102e+02, 1.3492e+03, -6.4731e+05],
- [-4.3727e-01, -7.8632e-01, 4.3646e-01, 3.4515e+02]],
-
- [[9.9595e+02, -8.6464e+02, 6.7959e+02, -2.7517e+05],
- [-8.1716e+01, 7.7826e+02, 1.2395e+03, -5.8137e+05],
- [-5.7090e-01, -6.0416e-01, 5.5594e-01, 2.8111e+02]]], device=device, dtype=dtype)
- P2 = torch.tensor([[[1.1518e+03, -7.5822e+02, 5.4764e+02, -1.9764e+05],
- [-2.1548e+02, 5.3102e+02, 1.3492e+03, -6.4731e+05],
- [-4.3727e-01, -7.8632e-01, 4.3646e-01, 3.4515e+02]],
- ], device=device, dtype=dtype)
+ P1_batch = torch.tensor(
+ [
+ [
+ [9.4692e+02, -9.6658e+02, 6.0862e+02, -2.3076e+05],
+ [-2.1829e+02, 5.4163e+02, 1.3445e+03, -6.4387e+05],
+ [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e+02]
+ ],
+ [
+ [9.4692e+02, -9.6658e+02, 6.0862e+02, -2.3076e+05],
+ [-2.1829e+02, 5.4163e+02, 1.3445e+03, -6.4387e+05],
+ [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e+02]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ P1 = torch.tensor(
+ [
+ [
+ [9.4692e+02, -9.6658e+02, 6.0862e+02, -2.3076e+05],
+ [-2.1829e+02, 5.4163e+02, 1.3445e+03, -6.4387e+05],
+ [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e+02]
+ ],
+ ],
+ device=device,
+ dtype=dtype
+ )
+ P2_batch = torch.tensor(
+ [
+ [
+ [1.1518e+03, -7.5822e+02, 5.4764e+02, -1.9764e+05],
+ [-2.1548e+02, 5.3102e+02, 1.3492e+03, -6.4731e+05],
+ [-4.3727e-01, -7.8632e-01, 4.3646e-01, 3.4515e+02]
+ ],
+ [
+ [9.9595e+02, -8.6464e+02, 6.7959e+02, -2.7517e+05],
+ [-8.1716e+01, 7.7826e+02, 1.2395e+03, -5.8137e+05],
+ [-5.7090e-01, -6.0416e-01, 5.5594e-01, 2.8111e+02]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ P2 = torch.tensor(
+ [
+ [
+ [1.1518e+03, -7.5822e+02, 5.4764e+02, -1.9764e+05],
+ [-2.1548e+02, 5.3102e+02, 1.3492e+03, -6.4731e+05],
+ [-4.3727e-01, -7.8632e-01, 4.3646e-01, 3.4515e+02]
+ ],
+ ],
+ device=device,
+ dtype=dtype
+ )
F_batch = epi.fundamental_from_projections(P1_batch, P2_batch)
F = epi.fundamental_from_projections(P1, P2)
diff --git a/test/geometry/epipolar/test_numeric.py b/test/geometry/epipolar/test_numeric.py
index 0ccf4084d..54ede06b4 100644
--- a/test/geometry/epipolar/test_numeric.py
+++ b/test/geometry/epipolar/test_numeric.py
@@ -8,6 +8,7 @@ import kornia.geometry.epipolar as epi
class TestSkewSymmetric:
+
def test_smoke(self, device, dtype):
vec = torch.rand(1, 3, device=device, dtype=dtype)
cross_product_matrix = epi.cross_product_matrix(vec)
@@ -29,10 +30,11 @@ class TestSkewSymmetric:
def test_gradcheck(self, device):
vec = torch.ones(2, 3, device=device, requires_grad=True, dtype=torch.float64)
- assert gradcheck(epi.cross_product_matrix, (vec,), raise_exception=True)
+ assert gradcheck(epi.cross_product_matrix, (vec, ), raise_exception=True)
class TestEyeLike:
+
def test_smoke(self, device, dtype):
image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
identity = epi.eye_like(3, image)
@@ -41,7 +43,8 @@ class TestEyeLike:
assert identity.dtype == image.dtype
@pytest.mark.parametrize(
- "batch_size, eye_size", [(1, 2), (2, 3), (3, 3), (2, 4)],
+ "batch_size, eye_size",
+ [(1, 2), (2, 3), (3, 3), (2, 4)],
)
def test_shape(self, batch_size, eye_size, device, dtype):
B, N = batch_size, eye_size
@@ -53,6 +56,7 @@ class TestEyeLike:
class TestVecLike:
+
def test_smoke(self, device, dtype):
image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
vec = epi.vec_like(3, image)
@@ -61,7 +65,8 @@ class TestVecLike:
assert vec.dtype == image.dtype
@pytest.mark.parametrize(
- "batch_size, eye_size", [(1, 2), (2, 3), (3, 3), (2, 4)],
+ "batch_size, eye_size",
+ [(1, 2), (2, 3), (3, 3), (2, 4)],
)
def test_shape(self, batch_size, eye_size, device, dtype):
B, N = batch_size, eye_size
diff --git a/test/geometry/epipolar/test_projection.py b/test/geometry/epipolar/test_projection.py
index 889bd9b86..5be1d7125 100644
--- a/test/geometry/epipolar/test_projection.py
+++ b/test/geometry/epipolar/test_projection.py
@@ -8,6 +8,7 @@ import kornia.geometry.epipolar as epi
class TestIntrinsicsLike:
+
def test_smoke(self, device, dtype):
image = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
focal = torch.rand(1, device=device, dtype=dtype)
@@ -26,6 +27,7 @@ class TestIntrinsicsLike:
class TestScaleIntrinsics:
+
def test_smoke_float(self, device, dtype):
scale_factor: float = 1.0
camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -54,11 +56,13 @@ class TestScaleIntrinsics:
[0., 0., 1.],
]], device=device, dtype=dtype)
- camera_matrix_expected = torch.tensor([[
- [50., 0., 25.],
- [0., 50., 25.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix_expected = torch.tensor(
+ [[
+ [50., 0., 25.],
+ [0., 50., 25.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype
+ )
camera_matrix_scale = epi.scale_intrinsics(camera_matrix, scale_factor)
assert_allclose(camera_matrix_scale, camera_matrix_expected, atol=1e-4, rtol=1e-4)
@@ -66,11 +70,14 @@ class TestScaleIntrinsics:
def test_gradcheck(self, device):
scale_factor = torch.ones(1, device=device, dtype=torch.float64, requires_grad=True)
camera_matrix = torch.ones(1, 3, 3, device=device, dtype=torch.float64)
- assert gradcheck(epi.scale_intrinsics,
- (camera_matrix, scale_factor,), raise_exception=True)
+ assert gradcheck(epi.scale_intrinsics, (
+ camera_matrix,
+ scale_factor,
+ ), raise_exception=True)
class TestProjectionFromKRt:
+
def test_smoke(self, device, dtype):
K = torch.rand(1, 3, 3, device=device, dtype=dtype)
R = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -104,21 +111,25 @@ class TestProjectionFromKRt:
[[1.], [2.], [3.]],
], device=device, dtype=dtype)
- P_expected = torch.tensor([[
- [10., 0., 30., 100.],
- [0., 20., 40., 160.],
- [0., 0., 1., 3.],
- ]], device=device, dtype=dtype)
+ P_expected = torch.tensor(
+ [[
+ [10., 0., 30., 100.],
+ [0., 20., 40., 160.],
+ [0., 0., 1., 3.],
+ ]], device=device, dtype=dtype
+ )
P_estimated = epi.projection_from_KRt(K, R, t)
assert_allclose(P_estimated, P_expected, atol=1e-4, rtol=1e-4)
def test_krt_from_projection(self, device, dtype):
- P = torch.tensor([[
- [10., 0., 30., 100.],
- [0., 20., 40., 160.],
- [0., 0., 1., 3.],
- ]], device=device, dtype=dtype)
+ P = torch.tensor(
+ [[
+ [10., 0., 30., 100.],
+ [0., 20., 40., 160.],
+ [0., 0., 1., 3.],
+ ]], device=device, dtype=dtype
+ )
K_expected = torch.tensor([[
[10., 0., 30.],
@@ -132,9 +143,7 @@ class TestProjectionFromKRt:
[0., 0., 1.],
]], device=device, dtype=dtype)
- t_expected = torch.tensor([
- [[1.], [2.], [3.]]
- ], device=device, dtype=dtype)
+ t_expected = torch.tensor([[[1.], [2.], [3.]]], device=device, dtype=dtype)
K_estimated, R_estimated, t_estimated = epi.KRt_from_projection(P)
assert_allclose(K_estimated, K_expected, atol=1e-4, rtol=1e-4)
@@ -145,11 +154,15 @@ class TestProjectionFromKRt:
K = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
R = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
t = torch.rand(1, 3, 1, device=device, dtype=torch.float64)
- assert gradcheck(epi.projection_from_KRt,
- (K, R, t,), raise_exception=True)
+ assert gradcheck(epi.projection_from_KRt, (
+ K,
+ R,
+ t,
+ ), raise_exception=True)
class TestProjectionsFromFundamental:
+
def test_smoke(self, device, dtype):
F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
P = epi.projections_from_fundamental(F_mat)
@@ -164,11 +177,11 @@ class TestProjectionsFromFundamental:
def test_gradcheck(self, device):
F_mat = torch.rand(1, 3, 3, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(epi.projections_from_fundamental,
- (F_mat,), raise_exception=True)
+ assert gradcheck(epi.projections_from_fundamental, (F_mat, ), raise_exception=True)
class TestKRtFromProjection:
+
def test_smoke(self, device, dtype):
P = torch.randn(1, 3, 4, device=device, dtype=dtype)
K, R, t = epi.KRt_from_projection(P)
@@ -187,27 +200,23 @@ class TestKRtFromProjection:
assert t.shape == (B, 3, 1)
def test_simple(self, device, dtype):
- P = torch.tensor([[
- [308., 139., 231., 84.],
- [481., 161., 358., 341.],
- [384., 387., 459., 102.]
- ]], device=device, dtype=dtype)
+ P = torch.tensor(
+ [[[308., 139., 231., 84.], [481., 161., 358., 341.], [384., 387., 459., 102.]]], device=device, dtype=dtype
+ )
- K_expected = torch.tensor([[
- [17.006138, 122.441254, 390.211426],
- [0.0, 228.743622, 577.167480],
- [0.0, 0.0, 712.675232]
- ]], device=device, dtype=dtype)
+ K_expected = torch.tensor(
+ [[[17.006138, 122.441254, 390.211426], [0.0, 228.743622, 577.167480], [0.0, 0.0, 712.675232]]],
+ device=device,
+ dtype=dtype
+ )
- R_expected = torch.tensor([[
- [0.396559, 0.511023, -0.762625],
- [0.743249, -0.666318, -0.060006],
- [0.538815, 0.543024, 0.644052]
- ]], device=device, dtype=dtype)
+ R_expected = torch.tensor(
+ [[[0.396559, 0.511023, -0.762625], [0.743249, -0.666318, -0.060006], [0.538815, 0.543024, 0.644052]]],
+ device=device,
+ dtype=dtype
+ )
- t_expected = torch.tensor([
- [[-6.477699], [1.129624], [0.143123]]
- ], device=device, dtype=dtype)
+ t_expected = torch.tensor([[[-6.477699], [1.129624], [0.143123]]], device=device, dtype=dtype)
K_estimated, R_estimated, t_estimated = epi.KRt_from_projection(P)
assert_allclose(K_estimated, K_expected, atol=1e-4, rtol=1e-4)
@@ -215,32 +224,29 @@ class TestKRtFromProjection:
assert_allclose(t_estimated, t_expected, atol=1e-4, rtol=1e-4)
def test_projection_from_krt(self, device, dtype):
- K = torch.tensor([[
- [17.006138, 122.441254, 390.211426],
- [0.0, 228.743622, 577.167480],
- [0.0, 0.0, 712.675232]
- ]], device=device, dtype=dtype)
-
- R = torch.tensor([[
- [0.396559, 0.511023, -0.762625],
- [0.743249, -0.666318, -0.060006],
- [0.538815, 0.543024, 0.644052]
- ]], device=device, dtype=dtype)
+ K = torch.tensor(
+ [[[17.006138, 122.441254, 390.211426], [0.0, 228.743622, 577.167480], [0.0, 0.0, 712.675232]]],
+ device=device,
+ dtype=dtype
+ )
+
+ R = torch.tensor(
+ [[[0.396559, 0.511023, -0.762625], [0.743249, -0.666318, -0.060006], [0.538815, 0.543024, 0.644052]]],
+ device=device,
+ dtype=dtype
+ )
t = torch.tensor([
[[-6.477699], [1.129624], [0.143123]],
], device=device, dtype=dtype)
- P_expected = torch.tensor([[
- [308., 139., 231., 84.],
- [481., 161., 358., 341.],
- [384., 387., 459., 102.]
- ]], device=device, dtype=dtype)
+ P_expected = torch.tensor(
+ [[[308., 139., 231., 84.], [481., 161., 358., 341.], [384., 387., 459., 102.]]], device=device, dtype=dtype
+ )
P_estimated = epi.projection_from_KRt(K, R, t)
assert_allclose(P_estimated, P_expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
P_mat = torch.rand(1, 3, 4, device=device, dtype=torch.float64, requires_grad=True)
- assert gradcheck(epi.KRt_from_projection,
- (P_mat,), raise_exception=True)
+ assert gradcheck(epi.KRt_from_projection, (P_mat, ), raise_exception=True)
diff --git a/test/geometry/epipolar/test_triangulation.py b/test/geometry/epipolar/test_triangulation.py
index 5c1a41fcb..c544f798c 100644
--- a/test/geometry/epipolar/test_triangulation.py
+++ b/test/geometry/epipolar/test_triangulation.py
@@ -9,6 +9,7 @@ import kornia.geometry.epipolar as epi
class TestTriangulation:
+
def test_smoke(self, device, dtype):
P1 = torch.rand(1, 3, 4, device=device, dtype=dtype)
P2 = torch.rand(1, 3, 4, device=device, dtype=dtype)
@@ -51,5 +52,9 @@ class TestTriangulation:
P1 = torch.nn.functional.pad(P1, [0, 1])
P2 = epi.eye_like(3, points2)
P2 = torch.nn.functional.pad(P2, [0, 1])
- assert gradcheck(epi.triangulate_points,
- (P1, P2, points1, points2,), raise_exception=True)
+ assert gradcheck(epi.triangulate_points, (
+ P1,
+ P2,
+ points1,
+ points2,
+ ), raise_exception=True)
diff --git a/test/geometry/subpix/test_dsnt.py b/test/geometry/subpix/test_dsnt.py
index 1750bccbc..c3a8fdb32 100644
--- a/test/geometry/subpix/test_dsnt.py
+++ b/test/geometry/subpix/test_dsnt.py
@@ -7,15 +7,20 @@ from torch.testing import assert_allclose
class TestRenderGaussian2d:
+
@pytest.fixture
def gaussian(self, device, dtype):
- return torch.tensor([
- [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
- [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
- [0.021938, 0.098320, 0.162103, 0.098320, 0.021938],
- [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
- [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
- ], dtype=dtype, device=device)
+ return torch.tensor(
+ [
+ [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
+ [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
+ [0.021938, 0.098320, 0.162103, 0.098320, 0.021938],
+ [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
+ [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
+ ],
+ dtype=dtype,
+ device=device
+ )
def test_pixel_coordinates(self, gaussian, device, dtype):
mean = torch.tensor([2.0, 2.0], dtype=dtype, device=device)
@@ -38,8 +43,10 @@ class TestRenderGaussian2d:
assert_allclose(op(*args), op_jit(*args), rtol=0, atol=1e-5)
def test_jit_trace(self, device, dtype):
+
def op(mean, std):
return kornia.geometry.dsnt.render_gaussian2d(mean, std, (5, 5), True)
+
mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)
std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)
args = (mean, std)
@@ -48,6 +55,7 @@ class TestRenderGaussian2d:
class TestSpatialSoftmax2d:
+
@pytest.fixture(params=[
torch.ones(1, 1, 5, 7),
torch.randn(2, 3, 16, 16),
@@ -68,21 +76,24 @@ class TestSpatialSoftmax2d:
def test_jit_trace(self, input):
op = kornia.geometry.dsnt.spatial_softmax2d
- op_jit = torch.jit.trace(op, (input,))
+ op_jit = torch.jit.trace(op, (input, ))
assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
class TestSpatialExpectation2d:
- @pytest.fixture(params=[
- (
- torch.tensor([[[
- [0.0, 0.0, 1.0],
- [0.0, 0.0, 0.0],
- ]]]),
- torch.tensor([[[1.0, -1.0]]]),
- torch.tensor([[[2.0, 0.0]]]),
- ),
- ])
+
+ @pytest.fixture(
+ params=[
+ (
+ torch.tensor([[[
+ [0.0, 0.0, 1.0],
+ [0.0, 0.0, 0.0],
+ ]]]),
+ torch.tensor([[[1.0, -1.0]]]),
+ torch.tensor([[[2.0, 0.0]]]),
+ ),
+ ]
+ )
def example(self, request, device, dtype):
input, expected_norm, expected_px = request.param
return input.to(device, dtype), expected_norm.to(device, dtype), expected_px.to(device, dtype)
@@ -103,5 +114,5 @@ class TestSpatialExpectation2d:
def test_jit_trace(self, example):
input = example[0]
op = kornia.geometry.dsnt.spatial_expectation2d
- op_jit = torch.jit.trace(op, (input,))
+ op_jit = torch.jit.trace(op, (input, ))
assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
diff --git a/test/geometry/subpix/test_spatial_softargmax.py b/test/geometry/subpix/test_spatial_softargmax.py
index 68d873721..2a1c93daa 100644
--- a/test/geometry/subpix/test_spatial_softargmax.py
+++ b/test/geometry/subpix/test_spatial_softargmax.py
@@ -11,25 +11,21 @@ from kornia.geometry.subpix.spatial_soft_argmax import _get_center_kernel2d, _ge
class TestCenterKernel2d:
+
def test_smoke(self, device, dtype):
kernel = _get_center_kernel2d(3, 4, device=device).to(dtype=dtype)
assert kernel.shape == (2, 2, 3, 4)
def test_odd(self, device, dtype):
kernel = _get_center_kernel2d(3, 3, device=device).to(dtype=dtype)
- expected = torch.tensor([
- [[[0., 0., 0.],
- [0., 1., 0.],
- [0., 0., 0.]],
- [[0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.]]],
- [[[0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.]],
- [[0., 0., 0.],
- [0., 1., 0.],
- [0., 0., 0.]]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [[[0., 0., 0.], [0., 1., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]],
+ [[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]], [[0., 0., 0.], [0., 1., 0.], [0., 0., 0.]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(kernel, expected, atol=1e-4, rtol=1e-4)
def test_even(self, device, dtype):
@@ -41,6 +37,7 @@ class TestCenterKernel2d:
class TestCenterKernel3d:
+
def test_smoke(self, device, dtype):
kernel = _get_center_kernel3d(6, 3, 4, device=device).to(dtype=dtype)
assert kernel.shape == (3, 3, 6, 3, 4)
@@ -63,6 +60,7 @@ class TestCenterKernel3d:
class TestSpatialSoftArgmax2d:
+
def test_smoke(self, device, dtype):
input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)
m = kornia.SpatialSoftArgmax2d()
@@ -125,8 +123,7 @@ class TestSpatialSoftArgmax2d:
def test_gradcheck(self, device, dtype):
input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.spatial_soft_argmax2d,
- (input), raise_exception=True)
+ assert gradcheck(kornia.spatial_soft_argmax2d, (input), raise_exception=True)
def test_end_to_end(self, device, dtype):
input = torch.full((1, 2, 7, 7), 1.0, requires_grad=True, device=device, dtype=dtype)
@@ -135,19 +132,19 @@ class TestSpatialSoftArgmax2d:
hm = kornia.geometry.dsnt.spatial_softmax2d(input)
assert_allclose(
- hm.sum(-1).sum(-1), torch.tensor([[1.0, 1.0]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ hm.sum(-1).sum(-1), torch.tensor([[1.0, 1.0]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4
+ )
pred = kornia.geometry.dsnt.spatial_expectation2d(hm)
assert_allclose(
- pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]], device=device, dtype=dtype), atol=1e-4, rtol=1e-4
+ )
- loss1 = mse_loss(pred, target, size_average=None, reduce=None,
- reduction='none').mean(-1, keepdim=False)
+ loss1 = mse_loss(pred, target, size_average=None, reduce=None, reduction='none').mean(-1, keepdim=False)
expected_loss1 = torch.as_tensor([[0.0, 1.0]], device=device, dtype=dtype)
assert_allclose(loss1, expected_loss1, atol=1e-4, rtol=1e-4)
- target_hm = kornia.geometry.dsnt.render_gaussian2d(
- target, std, input.shape[-2:]).contiguous()
+ target_hm = kornia.geometry.dsnt.render_gaussian2d(target, std, input.shape[-2:]).contiguous()
loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, reduction='none')
expected_loss2 = torch.as_tensor([[0.0087, 0.0818]], device=device, dtype=dtype)
@@ -165,11 +162,12 @@ class TestSpatialSoftArgmax2d:
def test_jit_trace(self, device, dtype):
input = torch.rand((2, 3, 7, 7), dtype=dtype, device=device)
op = kornia.spatial_soft_argmax2d
- op_jit = torch.jit.trace(op, (input,))
+ op_jit = torch.jit.trace(op, (input, ))
assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
class TestConvSoftArgmax2d:
+
def test_smoke(self, device, dtype):
input = torch.zeros(1, 1, 3, 3, device=device, dtype=dtype)
m = kornia.ConvSoftArgmax2d((3, 3))
@@ -197,99 +195,115 @@ class TestConvSoftArgmax2d:
def test_gradcheck(self, device, dtype):
input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.conv_soft_argmax2d,
- (input), raise_exception=True)
+ assert gradcheck(kornia.conv_soft_argmax2d, (input), raise_exception=True)
def test_cold_diag(self, device, dtype):
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
- temperature=0.05,
- normalized_coordinates=False,
- output_value=True)
- expected_val = torch.tensor([[[[1., 0.],
- [0., 1.]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[[[1., 3.],
- [1., 3.]],
- [[1., 1.],
- [3., 3.]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax2d(
+ (3, 3), (2, 2), (0, 0), temperature=0.05, normalized_coordinates=False, output_value=True
+ )
+ expected_val = torch.tensor([[[[1., 0.], [0., 1.]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor([[[[[1., 3.], [1., 3.]], [[1., 1.], [3., 3.]]]]], device=device, dtype=dtype)
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag(self, device, dtype):
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
- temperature=10.,
- normalized_coordinates=False,
- output_value=True)
- expected_val = torch.tensor([[[[0.1214, 0.],
- [0., 0.1214]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[[[1., 3.],
- [1., 3.]],
- [[1., 1.],
- [3., 3.]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax2d(
+ (3, 3), (2, 2), (0, 0), temperature=10., normalized_coordinates=False, output_value=True
+ )
+ expected_val = torch.tensor([[[[0.1214, 0.], [0., 0.1214]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor([[[[[1., 3.], [1., 3.]], [[1., 1.], [3., 3.]]]]], device=device, dtype=dtype)
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_cold_diag_norm(self, device, dtype):
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
- temperature=0.05,
- normalized_coordinates=True,
- output_value=True)
- expected_val = torch.tensor([[[[1., 0.],
- [0., 1.]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[[[-0.5, 0.5],
- [-0.5, 0.5]],
- [[-0.5, -0.5],
- [0.5, 0.5]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax2d(
+ (3, 3), (2, 2), (0, 0), temperature=0.05, normalized_coordinates=True, output_value=True
+ )
+ expected_val = torch.tensor([[[[1., 0.], [0., 1.]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[-0.5, 0.5], [-0.5, 0.5]], [[-0.5, -0.5], [0.5, 0.5]]]]], device=device, dtype=dtype
+ )
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag_norm(self, device, dtype):
- input = torch.tensor([[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
- temperature=10.,
- normalized_coordinates=True,
- output_value=True)
- expected_val = torch.tensor([[[[0.1214, 0.],
- [0., 0.1214]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[[[-0.5, 0.5],
- [-0.5, 0.5]],
- [[-0.5, -0.5],
- [0.5, 0.5]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax2d(
+ (3, 3), (2, 2), (0, 0), temperature=10., normalized_coordinates=True, output_value=True
+ )
+ expected_val = torch.tensor([[[[0.1214, 0.], [0., 0.1214]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[-0.5, 0.5], [-0.5, 0.5]], [[-0.5, -0.5], [0.5, 0.5]]]]], device=device, dtype=dtype
+ )
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
class TestConvSoftArgmax3d:
+
def test_smoke(self, device, dtype):
input = torch.zeros(1, 1, 3, 3, 3, device=device, dtype=dtype)
m = kornia.ConvSoftArgmax3d((3, 3, 3), output_value=False)
@@ -305,105 +319,124 @@ class TestConvSoftArgmax3d:
def test_gradcheck(self, device, dtype):
input = torch.rand(1, 2, 3, 5, 5, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.conv_soft_argmax3d,
- (input), raise_exception=True)
+ assert gradcheck(kornia.conv_soft_argmax3d, (input), raise_exception=True)
def test_cold_diag(self, device, dtype):
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
- temperature=0.05,
- normalized_coordinates=False,
- output_value=True)
- expected_val = torch.tensor([[[[[1., 0.],
- [0., 1.]]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[
- [[[0., 0.],
- [0., 0.]]],
- [[[1., 3.],
- [1., 3.]]],
- [[[1., 1.],
- [3., 3.]]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax3d(
+ (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=0.05, normalized_coordinates=False, output_value=True
+ )
+ expected_val = torch.tensor([[[[[1., 0.], [0., 1.]]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[[0., 0.], [0., 0.]]], [[[1., 3.], [1., 3.]]], [[[1., 1.], [3., 3.]]]]]], device=device, dtype=dtype
+ )
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag(self, device, dtype):
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
- temperature=10.,
- normalized_coordinates=False,
- output_value=True)
- expected_val = torch.tensor([[[[[0.1214, 0.],
- [0., 0.1214]]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[
- [[[0., 0.],
- [0., 0.]]],
- [[[1., 3.],
- [1., 3.]]],
- [[[1., 1.],
- [3., 3.]]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax3d(
+ (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10., normalized_coordinates=False, output_value=True
+ )
+ expected_val = torch.tensor([[[[[0.1214, 0.], [0., 0.1214]]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[[0., 0.], [0., 0.]]], [[[1., 3.], [1., 3.]]], [[[1., 1.], [3., 3.]]]]]], device=device, dtype=dtype
+ )
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_cold_diag_norm(self, device, dtype):
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
- temperature=0.05,
- normalized_coordinates=True,
- output_value=True)
- expected_val = torch.tensor([[[[[1., 0.],
- [0., 1.]]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[
- [[[-1., -1.],
- [-1., -1.]]],
- [[[-0.5, 0.5],
- [-0.5, 0.5]]],
- [[[-0.5, -0.5],
- [0.5, 0.5]]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax3d(
+ (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=0.05, normalized_coordinates=True, output_value=True
+ )
+ expected_val = torch.tensor([[[[[1., 0.], [0., 1.]]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[[-1., -1.], [-1., -1.]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
+ device=device,
+ dtype=dtype
+ )
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
def test_hot_diag_norm(self, device, dtype):
- input = torch.tensor([[[[
- [0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0.],
- ]]]], device=device, dtype=dtype)
- softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
- temperature=10.,
- normalized_coordinates=True,
- output_value=True)
- expected_val = torch.tensor([[[[[0.1214, 0.],
- [0., 0.1214]]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[
- [[[-1., -1.],
- [-1., -1.]]],
- [[[-0.5, 0.5],
- [-0.5, 0.5]]],
- [[[-0.5, -0.5],
- [0.5, 0.5]]]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0., 0.],
+ [0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ softargmax = kornia.ConvSoftArgmax3d(
+ (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10., normalized_coordinates=True, output_value=True
+ )
+ expected_val = torch.tensor([[[[[0.1214, 0.], [0., 0.1214]]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[[-1., -1.], [-1., -1.]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
+ device=device,
+ dtype=dtype
+ )
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
@@ -423,102 +456,116 @@ class TestConvQuadInterp3d:
input = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)
input[0, 0, 1, 2, 2] += 20.
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.geometry.ConvQuadInterp3d(strict_maxima_bonus=0),
- (input), raise_exception=True, atol=1e-3, rtol=1e-3)
+ assert gradcheck(
+ kornia.geometry.ConvQuadInterp3d(strict_maxima_bonus=0), (input),
+ raise_exception=True,
+ atol=1e-3,
+ rtol=1e-3
+ )
def test_diag(self, device, dtype):
- input = torch.tensor([[
- [[0., 0., 0., 0, 0],
- [0., 0., 0.0, 0, 0.],
- [0., 0, 0., 0, 0.],
- [0., 0., 0, 0, 0.],
- [0., 0., 0., 0, 0.]],
-
- [[0., 0., 0., 0, 0],
- [0., 0., 1, 0, 0.],
- [0., 1, 1.2, 1.1, 0.],
- [0., 0., 1., 0, 0.],
- [0., 0., 0., 0, 0.]],
-
- [[0., 0., 0., 0, 0],
- [0., 0., 0.0, 0, 0.],
- [0., 0, 0., 0, 0.],
- [0., 0., 0, 0, 0.],
- [0., 0., 0., 0, 0.],
- ]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0., 0, 0], [0., 0., 0.0, 0, 0.], [0., 0, 0., 0, 0.], [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.]
+ ],
+ [
+ [0., 0., 0., 0, 0], [0., 0., 1, 0, 0.], [0., 1, 1.2, 1.1, 0.], [0., 0., 1., 0, 0.],
+ [0., 0., 0., 0, 0.]
+ ],
+ [
+ [0., 0., 0., 0, 0],
+ [0., 0., 0.0, 0, 0.],
+ [0., 0, 0., 0, 0.],
+ [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
input = kornia.gaussian_blur2d(input, (5, 5), (0.5, 0.5)).unsqueeze(0)
softargmax = kornia.geometry.ConvQuadInterp3d(10)
- expected_val = torch.tensor([[[
- [[0., 0., 0., 0, 0],
- [0., 0., 0.0, 0, 0.],
- [0., 0, 0., 0, 0.],
- [0., 0., 0, 0, 0.],
- [0., 0., 0., 0, 0.]],
- [[2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04],
- [2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
- [1.6807e-01, 7.4227e-01, 1.1086e+01, 8.0414e-01, 1.8482e-01],
- [2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
- [2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04]],
- [[0., 0., 0., 0, 0],
- [0., 0., 0.0, 0, 0.],
- [0., 0, 0., 0, 0.],
- [0., 0., 0, 0, 0.],
- [0., 0., 0., 0, 0.]]]]], device=device, dtype=dtype)
- expected_coord = torch.tensor([[[[[[0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0]],
-
- [[1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0]],
-
- [[2.0, 2.0, 2.0, 2.0, 2.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- [2.0, 2.0, 2.0, 2.0, 2.0]]],
-
-
- [[[0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0]],
-
- [[0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0]],
-
- [[0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0],
- [0.0, 1.0, 2.0, 3.0, 4.0]]],
-
-
- [[[0.0, 0.0, 0.0, 0.0, 0.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- [3.0, 3.0, 3.0, 3.0, 3.0],
- [4.0, 4.0, 4.0, 4.0, 4.0]],
-
- [[0.0, 0.0, 0.0, 0.0, 0.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [2.0, 2.0, 2.0495, 2.0, 2.0],
- [3.0, 3.0, 3.0, 3.0, 3.0],
- [4.0, 4.0, 4.0, 4.0, 4.0]],
-
- [[0.0, 0.0, 0.0, 0.0, 0.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- [3.0, 3.0, 3.0, 3.0, 3.0],
- [4.0, 4.0, 4.0, 4.0, 4.0]]]]]], device=device, dtype=dtype)
+ expected_val = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0., 0, 0], [0., 0., 0.0, 0, 0.], [0., 0, 0., 0, 0.], [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.]
+ ],
+ [
+ [2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04],
+ [2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
+ [1.6807e-01, 7.4227e-01, 1.1086e+01, 8.0414e-01, 1.8482e-01],
+ [2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
+ [2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04]
+ ],
+ [
+ [0., 0., 0., 0, 0], [0., 0., 0.0, 0, 0.], [0., 0, 0., 0, 0.], [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+ expected_coord = torch.tensor(
+ [
+ [
+ [
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]
+ ],
+ [
+ [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0]
+ ],
+ [
+ [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0]
+ ]
+ ],
+ [
+ [
+ [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0]
+ ],
+ [
+ [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0]
+ ],
+ [
+ [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0], [0.0, 1.0, 2.0, 3.0, 4.0]
+ ]
+ ],
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0], [4.0, 4.0, 4.0, 4.0, 4.0]
+ ],
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0495, 2.0, 2.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0], [4.0, 4.0, 4.0, 4.0, 4.0]
+ ],
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0], [1.0, 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0], [4.0, 4.0, 4.0, 4.0, 4.0]
+ ]
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
assert_allclose(coords, expected_coord, atol=1e-4, rtol=1e-4)
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index f2b5c05fa..591bf263d 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -32,27 +32,25 @@ def rtol(device, dtype):
# based on:
# https://github.com/ceres-solver/ceres-solver/blob/master/internal/ceres/rotation_test.cc#L271
+
class TestAngleAxisToQuaternion:
def test_smoke_xyzw(self, device, dtype):
angle_axis = torch.zeros(3, dtype=dtype, device=device)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
- assert quaternion.shape == (4,)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
+ assert quaternion.shape == (4, )
def test_smoke(self, device, dtype):
angle_axis = torch.zeros(3, dtype=dtype, device=device)
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.WXYZ)
- assert quaternion.shape == (4,)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
+ assert quaternion.shape == (4, )
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
angle_axis = torch.zeros(batch_size, 3, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert quaternion.shape == (batch_size, 4)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
@@ -65,8 +63,7 @@ class TestAngleAxisToQuaternion:
angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_zero_angle(self, device, dtype, atol, rtol):
@@ -78,54 +75,50 @@ class TestAngleAxisToQuaternion:
def test_small_angle_x_xyzw(self, device, dtype, atol, rtol):
theta = 1.e-2
angle_axis = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((np.sin(theta / 2.), 0., 0., np.cos(theta / 2.)),
- device=device, dtype=dtype)
+ expected = torch.tensor((np.sin(theta / 2.), 0., 0., np.cos(theta / 2.)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_x(self, device, dtype, atol, rtol):
theta = 1.e-2
angle_axis = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((np.cos(theta / 2.), np.sin(theta / 2.), 0., 0.),
- device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.), np.sin(theta / 2.), 0., 0.), device=device, dtype=dtype)
quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_y_xyzw(self, device, dtype, atol, rtol):
theta = 1.e-2
angle_axis = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
- expected = torch.tensor((0., np.sin(theta / 2.), 0., np.cos(theta / 2.)),
- device=device, dtype=dtype)
+ expected = torch.tensor((0., np.sin(theta / 2.), 0., np.cos(theta / 2.)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_y(self, device, dtype, atol, rtol):
theta = 1.e-2
angle_axis = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
- expected = torch.tensor((np.cos(theta / 2.), 0., np.sin(theta / 2.), 0.,),
- device=device, dtype=dtype)
+ expected = torch.tensor((
+ np.cos(theta / 2.),
+ 0.,
+ np.sin(theta / 2.),
+ 0.,
+ ), device=device, dtype=dtype)
quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_z_xyzw(self, device, dtype, atol, rtol):
theta = 1.e-2
angle_axis = torch.tensor((0., 0., theta), device=device, dtype=dtype)
- expected = torch.tensor((0., 0., np.sin(theta / 2.), np.cos(theta / 2.)),
- device=device, dtype=dtype)
+ expected = torch.tensor((0., 0., np.sin(theta / 2.), np.cos(theta / 2.)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_small_angle_z(self, device, dtype, atol, rtol):
theta = 1.e-2
angle_axis = torch.tensor((0., 0., theta), device=device, dtype=dtype)
- expected = torch.tensor((np.cos(theta / 2.), 0., 0., np.sin(theta / 2.)),
- device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.), 0., 0., np.sin(theta / 2.)), device=device, dtype=dtype)
quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
@@ -134,8 +127,7 @@ class TestAngleAxisToQuaternion:
angle_axis = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((half_sqrt2, 0., 0., half_sqrt2), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_x_rotation(self, device, dtype, atol, rtol):
@@ -150,8 +142,7 @@ class TestAngleAxisToQuaternion:
angle_axis = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., half_sqrt2, 0., half_sqrt2), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_y_rotation(self, device, dtype, atol, rtol):
@@ -166,8 +157,7 @@ class TestAngleAxisToQuaternion:
angle_axis = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., half_sqrt2, half_sqrt2), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_z_rotation(self, device, dtype, atol, rtol):
@@ -183,19 +173,20 @@ class TestAngleAxisToQuaternion:
angle_axis = tensor_to_gradcheck_var(angle_axis)
# evaluate function gradient
with pytest.warns(UserWarning):
- assert gradcheck(partial(kornia.angle_axis_to_quaternion,
- order=QuaternionCoeffOrder.XYZW),
- (angle_axis,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.angle_axis_to_quaternion, order=QuaternionCoeffOrder.XYZW), (angle_axis, ),
+ raise_exception=True
+ )
def test_gradcheck(self, device, dtype):
eps = torch.finfo(dtype).eps
angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype) + eps
angle_axis = tensor_to_gradcheck_var(angle_axis)
# evaluate function gradient
- assert gradcheck(partial(kornia.angle_axis_to_quaternion, order=QuaternionCoeffOrder.WXYZ),
- (angle_axis,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.angle_axis_to_quaternion, order=QuaternionCoeffOrder.WXYZ), (angle_axis, ),
+ raise_exception=True
+ )
class TestQuaternionToAngleAxis:
@@ -203,145 +194,122 @@ class TestQuaternionToAngleAxis:
def test_smoke_xyzw(self, device, dtype):
quaternion = torch.zeros(4, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
- assert angle_axis.shape == (3,)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
+ assert angle_axis.shape == (3, )
def test_smoke(self, device, dtype):
quaternion = torch.zeros(4, device=device, dtype=dtype)
angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
- assert angle_axis.shape == (3,)
+ assert angle_axis.shape == (3, )
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert angle_axis.shape == (batch_size, 3)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert angle_axis.shape == (batch_size, 3)
def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_unit_quaternion(self, device, dtype, atol, rtol):
quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_x_rotation_xyzw(self, device, dtype, atol, rtol):
quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((kornia.pi, 0., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_x_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((kornia.pi, 0., 0.), device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_y_rotation_xyzw(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., kornia.pi, 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_y_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., kornia.pi, 0.), device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_z_rotation_xyzw(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0., 0., 0.5, np.sqrt(3.) / 2.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., kornia.pi / 3.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_z_rotation(self, device, dtype, atol, rtol):
quaternion = torch.tensor((np.sqrt(3.) / 2., 0., 0., 0.5), device=device, dtype=dtype)
expected = torch.tensor((0., 0., kornia.pi / 3.), device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_small_angle_x_xyzw(self, device, dtype, atol, rtol):
theta = 1.e-2
- quaternion = torch.tensor((np.sin(theta / 2.), 0., 0., np.cos(theta / 2.)), device=device,
- dtype=dtype)
+ quaternion = torch.tensor((np.sin(theta / 2.), 0., 0., np.cos(theta / 2.)), device=device, dtype=dtype)
expected = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_small_angle_x(self, device, dtype, atol, rtol):
theta = 1.e-2
- quaternion = torch.tensor((np.cos(theta / 2.), np.sin(theta / 2.), 0., 0.), device=device,
- dtype=dtype)
+ quaternion = torch.tensor((np.cos(theta / 2.), np.sin(theta / 2.), 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_small_angle_y_xyzw(self, device, dtype, atol, rtol):
theta = 1.e-2
- quaternion = torch.tensor((0., np.sin(theta / 2), 0., np.cos(theta / 2)), device=device,
- dtype=dtype)
+ quaternion = torch.tensor((0., np.sin(theta / 2), 0., np.cos(theta / 2)), device=device, dtype=dtype)
expected = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_small_angle_y(self, device, dtype, atol, rtol):
theta = 1.e-2
- quaternion = torch.tensor((np.cos(theta / 2), 0., np.sin(theta / 2), 0.), device=device,
- dtype=dtype)
+ quaternion = torch.tensor((np.cos(theta / 2), 0., np.sin(theta / 2), 0.), device=device, dtype=dtype)
expected = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_small_angle_z_xyzw(self, device, dtype, atol, rtol):
theta = 1.e-2
- quaternion = torch.tensor((0., 0., np.sin(theta / 2), np.cos(theta / 2)), device=device,
- dtype=dtype)
+ quaternion = torch.tensor((0., 0., np.sin(theta / 2), np.cos(theta / 2)), device=device, dtype=dtype)
expected = torch.tensor((0., 0., theta), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_small_angle_z(self, device, dtype, atol, rtol):
theta = 1.e-2
- quaternion = torch.tensor((np.cos(theta / 2), 0., 0., np.sin(theta / 2)), device=device,
- dtype=dtype)
+ quaternion = torch.tensor((np.cos(theta / 2), 0., 0., np.sin(theta / 2)), device=device, dtype=dtype)
expected = torch.tensor((0., 0., theta), device=device, dtype=dtype)
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis, expected, atol=atol, rtol=rtol)
def test_gradcheck_xyzw(self, device, dtype):
@@ -350,19 +318,20 @@ class TestQuaternionToAngleAxis:
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
with pytest.warns(UserWarning):
- assert gradcheck(partial(kornia.quaternion_to_angle_axis,
- order=QuaternionCoeffOrder.XYZW),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_to_angle_axis, order=QuaternionCoeffOrder.XYZW), (quaternion, ),
+ raise_exception=True
+ )
def test_gradcheck(self, device, dtype):
eps = torch.finfo(dtype).eps
quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype) + eps
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(partial(kornia.quaternion_to_angle_axis, order=QuaternionCoeffOrder.WXYZ),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_to_angle_axis, order=QuaternionCoeffOrder.WXYZ), (quaternion, ),
+ raise_exception=True
+ )
class TestRotationMatrixToQuaternion:
@@ -371,8 +340,7 @@ class TestRotationMatrixToQuaternion:
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
matrix = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(matrix,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.XYZW)
assert quaternion.shape == (batch_size, 4)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
@@ -389,8 +357,7 @@ class TestRotationMatrixToQuaternion:
), device=device, dtype=dtype)
expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(matrix,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_identity(self, device, dtype, atol, rtol):
@@ -412,8 +379,7 @@ class TestRotationMatrixToQuaternion:
pi_half2 = torch.cos(kornia.pi / 4.).to(device=device, dtype=dtype)
expected = torch.tensor((pi_half2, 0., 0., pi_half2), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(matrix,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_rot_x_45(self, device, dtype, atol, rtol):
@@ -435,10 +401,8 @@ class TestRotationMatrixToQuaternion:
(0., 1., 0.),
), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
- matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.XYZW)
+ matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(matrix, matrix_hat, atol=atol, rtol=rtol)
def test_back_and_forth(self, device, dtype, atol, rtol):
@@ -448,41 +412,42 @@ class TestRotationMatrixToQuaternion:
(0., 0., -1.),
(0., 1., 0.),
), device=device, dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
- matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.WXYZ)
+ matrix_hat = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(matrix, matrix_hat, atol=atol, rtol=rtol)
def test_corner_case_xyzw(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- matrix = torch.tensor((
- (-0.7799533010, -0.5432914495, 0.3106555045),
- (0.0492402576, -0.5481169224, -0.8349509239),
- (0.6238971353, -0.6359263659, 0.4542570710)
- ), device=device, dtype=dtype)
+ matrix = torch.tensor(
+ (
+ (-0.7799533010, -0.5432914495, 0.3106555045), (0.0492402576, -0.5481169224, -0.8349509239),
+ (0.6238971353, -0.6359263659, 0.4542570710)
+ ),
+ device=device,
+ dtype=dtype
+ )
quaternion_true = torch.tensor(
- (0.280136495828629, -0.440902262926102, 0.834015488624573, 0.177614107728004),
- device=device, dtype=dtype)
+ (0.280136495828629, -0.440902262926102, 0.834015488624573, 0.177614107728004), device=device, dtype=dtype
+ )
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(matrix,
- eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.XYZW)
torch.set_printoptions(precision=10)
assert_allclose(quaternion_true, quaternion, atol=atol, rtol=rtol)
def test_corner_case(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- matrix = torch.tensor((
- (-0.7799533010, -0.5432914495, 0.3106555045),
- (0.0492402576, -0.5481169224, -0.8349509239),
- (0.6238971353, -0.6359263659, 0.4542570710)
- ), device=device, dtype=dtype)
+ matrix = torch.tensor(
+ (
+ (-0.7799533010, -0.5432914495, 0.3106555045), (0.0492402576, -0.5481169224, -0.8349509239),
+ (0.6238971353, -0.6359263659, 0.4542570710)
+ ),
+ device=device,
+ dtype=dtype
+ )
quaternion_true = torch.tensor(
- (0.177614107728004, 0.280136495828629, -0.440902262926102, 0.834015488624573),
- device=device, dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(matrix,
- eps=eps, order=QuaternionCoeffOrder.WXYZ)
+ (0.177614107728004, 0.280136495828629, -0.440902262926102, 0.834015488624573), device=device, dtype=dtype
+ )
+ quaternion = kornia.rotation_matrix_to_quaternion(matrix, eps=eps, order=QuaternionCoeffOrder.WXYZ)
torch.set_printoptions(precision=10)
assert_allclose(quaternion_true, quaternion, atol=atol, rtol=rtol)
@@ -492,20 +457,20 @@ class TestRotationMatrixToQuaternion:
matrix = tensor_to_gradcheck_var(matrix)
# evaluate function gradient
with pytest.warns(UserWarning):
- assert gradcheck(partial(kornia.rotation_matrix_to_quaternion,
- eps=eps, order=QuaternionCoeffOrder.XYZW),
- (matrix,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW), (matrix, ),
+ raise_exception=True
+ )
def test_gradcheck(self, device, dtype):
eps = torch.finfo(dtype).eps
matrix = torch.eye(3, device=device, dtype=dtype)
matrix = tensor_to_gradcheck_var(matrix)
# evaluate function gradient
- assert gradcheck(partial(kornia.rotation_matrix_to_quaternion,
- eps=eps, order=QuaternionCoeffOrder.WXYZ),
- (matrix,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ), (matrix, ),
+ raise_exception=True
+ )
@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit_xyzw(self, device, dtype):
@@ -535,8 +500,7 @@ class TestQuaternionToRotationMatrix:
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
quaternion = torch.zeros(batch_size, 4, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- matrix = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
assert matrix.shape == (batch_size, 3, 3)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
@@ -553,8 +517,7 @@ class TestQuaternionToRotationMatrix:
(0., 0., 1.),
), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- matrix = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(matrix, expected, atol=atol, rtol=rtol)
def test_unit_quaternion(self, device, dtype, atol, rtol):
@@ -575,8 +538,7 @@ class TestQuaternionToRotationMatrix:
(0., 0., -1.),
), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- matrix = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(matrix, expected, atol=atol, rtol=rtol)
def test_x_rotation(self, device, dtype, atol, rtol):
@@ -598,8 +560,7 @@ class TestQuaternionToRotationMatrix:
), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- matrix = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(matrix, expected, atol=atol, rtol=rtol)
def test_y_rotation(self, device, dtype, atol, rtol):
@@ -620,8 +581,7 @@ class TestQuaternionToRotationMatrix:
(0., 0., 1.),
), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- matrix = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(matrix, expected, atol=atol, rtol=rtol)
def test_z_rotation(self, device, dtype, atol, rtol):
@@ -639,19 +599,19 @@ class TestQuaternionToRotationMatrix:
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
with pytest.warns(UserWarning):
- assert gradcheck(partial(kornia.quaternion_to_rotation_matrix,
- order=QuaternionCoeffOrder.XYZW),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_to_rotation_matrix, order=QuaternionCoeffOrder.XYZW), (quaternion, ),
+ raise_exception=True
+ )
def test_gradcheck(self, device, dtype):
quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(partial(kornia.quaternion_to_rotation_matrix,
- order=QuaternionCoeffOrder.WXYZ),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_to_rotation_matrix, order=QuaternionCoeffOrder.WXYZ), (quaternion, ),
+ raise_exception=True
+ )
@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit_xyzw(self, device, dtype):
@@ -666,8 +626,9 @@ class TestQuaternionToRotationMatrix:
op = kornia.geometry.conversions.quaternion_to_rotation_matrix
op_jit = torch.jit.script(op)
quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
- assert_allclose(op(quaternion, order=QuaternionCoeffOrder.WXYZ),
- op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ))
+ assert_allclose(
+ op(quaternion, order=QuaternionCoeffOrder.WXYZ), op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ )
class TestQuaternionLogToExp:
@@ -676,15 +637,13 @@ class TestQuaternionLogToExp:
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
quaternion_log = torch.zeros(batch_size, 3, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, order=QuaternionCoeffOrder.XYZW)
assert quaternion_exp.shape == (batch_size, 4)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
quaternion_log = torch.zeros(batch_size, 3, device=device, dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, order=QuaternionCoeffOrder.WXYZ)
assert quaternion_exp.shape == (batch_size, 4)
def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
@@ -692,80 +651,66 @@ class TestQuaternionLogToExp:
quaternion_log = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_unit_quaternion(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_log = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_x_xyzw(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
one = torch.tensor(1., device=device, dtype=dtype)
quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((torch.sin(one), 0., 0., torch.cos(one)), device=device,
- dtype=dtype)
+ expected = torch.tensor((torch.sin(one), 0., 0., torch.cos(one)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_x(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
one = torch.tensor(1., device=device, dtype=dtype)
quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((torch.cos(one), torch.sin(one), 0., 0.), device=device,
- dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ expected = torch.tensor((torch.cos(one), torch.sin(one), 0., 0.), device=device, dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_y_xyzw(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
one = torch.tensor(1., device=device, dtype=dtype)
quaternion_log = torch.tensor((0., 1., 0.), device=device, dtype=dtype)
- expected = torch.tensor((0., torch.sin(one), 0., torch.cos(one)), device=device,
- dtype=dtype)
+ expected = torch.tensor((0., torch.sin(one), 0., torch.cos(one)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_y(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
one = torch.tensor(1., device=device, dtype=dtype)
quaternion_log = torch.tensor((0., 1., 0.), device=device, dtype=dtype)
- expected = torch.tensor((torch.cos(one), 0., torch.sin(one), 0.), device=device,
- dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ expected = torch.tensor((torch.cos(one), 0., torch.sin(one), 0.), device=device, dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_z_xyzw(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
one = torch.tensor(1., device=device, dtype=dtype)
quaternion_log = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
- expected = torch.tensor((0., 0., torch.sin(one), torch.cos(one)), device=device,
- dtype=dtype)
+ expected = torch.tensor((0., 0., torch.sin(one), torch.cos(one)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_z(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
one = torch.tensor(1., device=device, dtype=dtype)
quaternion_log = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
- expected = torch.tensor((torch.cos(one), 0., 0., torch.sin(one)), device=device,
- dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ expected = torch.tensor((torch.cos(one), 0., 0., torch.sin(one)), device=device, dtype=dtype)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_exp, expected, atol=atol, rtol=rtol)
def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):
@@ -773,21 +718,17 @@ class TestQuaternionLogToExp:
quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)
with pytest.warns(UserWarning):
- quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)
def test_back_and_forth(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
- quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
- quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log_hat = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_log, quaternion_log_hat, atol=atol, rtol=rtol)
def test_gradcheck_xyzw(self, device, dtype):
@@ -796,20 +737,20 @@ class TestQuaternionLogToExp:
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
with pytest.warns(UserWarning):
- assert gradcheck(partial(kornia.quaternion_log_to_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_log_to_exp, eps=eps, order=QuaternionCoeffOrder.XYZW), (quaternion, ),
+ raise_exception=True
+ )
def test_gradcheck(self, device, dtype):
eps = torch.finfo(dtype).eps
quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(partial(kornia.quaternion_log_to_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_log_to_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ), (quaternion, ),
+ raise_exception=True
+ )
@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit_xyzw(self, device, dtype):
@@ -817,16 +758,18 @@ class TestQuaternionLogToExp:
op_jit = torch.jit.script(op)
quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- assert_allclose(op(quaternion, order=QuaternionCoeffOrder.XYZW),
- op_jit(quaternion, order=QuaternionCoeffOrder.XYZW))
+ assert_allclose(
+ op(quaternion, order=QuaternionCoeffOrder.XYZW), op_jit(quaternion, order=QuaternionCoeffOrder.XYZW)
+ )
@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit(self, device, dtype):
op = kornia.geometry.conversions.quaternion_log_to_exp
op_jit = torch.jit.script(op)
quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
- assert_allclose(op(quaternion, order=QuaternionCoeffOrder.WXYZ),
- op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ))
+ assert_allclose(
+ op(quaternion, order=QuaternionCoeffOrder.WXYZ), op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ)
+ )
class TestQuaternionExpToLog:
@@ -836,16 +779,14 @@ class TestQuaternionExpToLog:
eps = torch.finfo(dtype).eps
quaternion_exp = torch.zeros(batch_size, 4, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert quaternion_log.shape == (batch_size, 3)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch(self, batch_size, device, dtype):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.zeros(batch_size, 4, device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert quaternion_log.shape == (batch_size, 3)
def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
@@ -853,16 +794,14 @@ class TestQuaternionExpToLog:
quaternion_exp = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_unit_quaternion(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_x_xyzw(self, device, dtype, atol, rtol):
@@ -870,16 +809,14 @@ class TestQuaternionExpToLog:
quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_x(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_y_xyzw(self, device, dtype, atol, rtol):
@@ -887,16 +824,14 @@ class TestQuaternionExpToLog:
quaternion_exp = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_y(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_z_xyzw(self, device, dtype, atol, rtol):
@@ -904,16 +839,14 @@ class TestQuaternionExpToLog:
quaternion_exp = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_pi_quaternion_z(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
expected = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_log, expected, atol=atol, rtol=rtol)
def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):
@@ -921,20 +854,16 @@ class TestQuaternionExpToLog:
quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.XYZW)
with pytest.warns(UserWarning):
- quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)
def test_back_and_forth(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
quaternion_exp = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
- quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
- quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_log = kornia.quaternion_exp_to_log(quaternion_exp, eps=eps, order=QuaternionCoeffOrder.WXYZ)
+ quaternion_exp_hat = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)
def test_gradcheck_xyzw(self, device, dtype):
@@ -943,20 +872,20 @@ class TestQuaternionExpToLog:
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
with pytest.warns(UserWarning):
- assert gradcheck(partial(kornia.quaternion_exp_to_log, eps=eps,
- order=QuaternionCoeffOrder.XYZW),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_exp_to_log, eps=eps, order=QuaternionCoeffOrder.XYZW), (quaternion, ),
+ raise_exception=True
+ )
def test_gradcheck(self, device, dtype):
eps = torch.finfo(dtype).eps
quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
quaternion = tensor_to_gradcheck_var(quaternion)
# evaluate function gradient
- assert gradcheck(partial(kornia.quaternion_exp_to_log, eps=eps,
- order=QuaternionCoeffOrder.WXYZ),
- (quaternion,),
- raise_exception=True)
+ assert gradcheck(
+ partial(kornia.quaternion_exp_to_log, eps=eps, order=QuaternionCoeffOrder.WXYZ), (quaternion, ),
+ raise_exception=True
+ )
@pytest.mark.skipif(torch.__version__.startswith('1.6'), reason='JIT Enum not handled.')
def test_jit_xyzw(self, device, dtype, atol, rtol):
@@ -993,18 +922,27 @@ class TestAngleAxisToRotationMatrix:
# evaluate function gradient
angle_axis = tensor_to_gradcheck_var(angle_axis) # to var
- assert gradcheck(kornia.angle_axis_to_rotation_matrix, (angle_axis,),
- raise_exception=True)
+ assert gradcheck(kornia.angle_axis_to_rotation_matrix, (angle_axis, ), raise_exception=True)
def test_angle_axis_to_rotation_matrix(self, device, dtype, atol, rtol):
- rmat_1 = torch.tensor(((-0.30382753, -0.95095137, -0.05814062),
- (-0.71581715, 0.26812278, -0.64476041),
- (0.62872461, -0.15427791, -0.76217038)), device=device, dtype=dtype)
+ rmat_1 = torch.tensor(
+ (
+ (-0.30382753, -0.95095137, -0.05814062), (-0.71581715, 0.26812278, -0.64476041),
+ (0.62872461, -0.15427791, -0.76217038)
+ ),
+ device=device,
+ dtype=dtype
+ )
rvec_1 = torch.tensor((1.50485376, -2.10737739, 0.7214174), device=device, dtype=dtype)
- rmat_2 = torch.tensor(((0.6027768, -0.79275544, -0.09054801),
- (-0.67915707, -0.56931658, 0.46327563),
- (-0.41881476, -0.21775548, -0.88157628)), device=device, dtype=dtype)
+ rmat_2 = torch.tensor(
+ (
+ (0.6027768, -0.79275544, -0.09054801), (-0.67915707, -0.56931658, 0.46327563),
+ (-0.41881476, -0.21775548, -0.88157628)
+ ),
+ device=device,
+ dtype=dtype
+ )
rvec_2 = torch.tensor((-2.44916812, 1.18053411, 0.4085298), device=device, dtype=dtype)
rmat = torch.stack((rmat_2, rmat_1), dim=0)
rvec = torch.stack((rvec_2, rvec_1), dim=0)
@@ -1019,8 +957,7 @@ class TestRotationMatrixToAngleAxis:
# generate input data
quaternion = torch.rand(batch_size, 4, device=device, dtype=dtype)
quaternion = kornia.normalize_quaternion(quaternion)
- rotation_matrix = kornia.quaternion_to_rotation_matrix(quaternion=quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ rotation_matrix = kornia.quaternion_to_rotation_matrix(quaternion=quaternion, order=QuaternionCoeffOrder.WXYZ)
eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)
rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))
@@ -1029,18 +966,27 @@ class TestRotationMatrixToAngleAxis:
# evaluate function gradient
rotation_matrix = tensor_to_gradcheck_var(rotation_matrix) # to var
- assert gradcheck(kornia.rotation_matrix_to_angle_axis,
- (rotation_matrix,), raise_exception=True)
+ assert gradcheck(kornia.rotation_matrix_to_angle_axis, (rotation_matrix, ), raise_exception=True)
def test_rotation_matrix_to_angle_axis(self, device, dtype, atol, rtol):
- rmat_1 = torch.tensor(((-0.30382753, -0.95095137, -0.05814062),
- (-0.71581715, 0.26812278, -0.64476041),
- (0.62872461, -0.15427791, -0.76217038)), device=device, dtype=dtype)
+ rmat_1 = torch.tensor(
+ (
+ (-0.30382753, -0.95095137, -0.05814062), (-0.71581715, 0.26812278, -0.64476041),
+ (0.62872461, -0.15427791, -0.76217038)
+ ),
+ device=device,
+ dtype=dtype
+ )
rvec_1 = torch.tensor((1.50485376, -2.10737739, 0.7214174), device=device, dtype=dtype)
- rmat_2 = torch.tensor(((0.6027768, -0.79275544, -0.09054801),
- (-0.67915707, -0.56931658, 0.46327563),
- (-0.41881476, -0.21775548, -0.88157628)), device=device, dtype=dtype)
+ rmat_2 = torch.tensor(
+ (
+ (0.6027768, -0.79275544, -0.09054801), (-0.67915707, -0.56931658, 0.46327563),
+ (-0.41881476, -0.21775548, -0.88157628)
+ ),
+ device=device,
+ dtype=dtype
+ )
rvec_2 = torch.tensor((-2.44916812, 1.18053411, 0.4085298), device=device, dtype=dtype)
rmat = torch.stack((rmat_2, rmat_1), dim=0)
rvec = torch.stack((rvec_2, rvec_1), dim=0)
@@ -1053,7 +999,11 @@ def test_pi():
@pytest.mark.parametrize("batch_shape", [
- (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ (2, 3),
+ (1, 2, 3),
+ (2, 3, 3),
+ (5, 5, 3),
+])
def test_rad2deg(batch_shape, device, dtype):
# generate input data
x_rad = kornia.pi * torch.rand(batch_shape, device=device, dtype=dtype)
@@ -1066,12 +1016,15 @@ def test_rad2deg(batch_shape, device, dtype):
assert_allclose(x_rad, x_deg_to_rad)
# evaluate function gradient
- assert gradcheck(kornia.rad2deg, (tensor_to_gradcheck_var(x_rad),),
- raise_exception=True)
+ assert gradcheck(kornia.rad2deg, (tensor_to_gradcheck_var(x_rad), ), raise_exception=True)
@pytest.mark.parametrize("batch_shape", [
- (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ (2, 3),
+ (1, 2, 3),
+ (2, 3, 3),
+ (5, 5, 3),
+])
def test_deg2rad(batch_shape, device, dtype, atol, rtol):
# generate input data
x_deg = 180. * torch.rand(batch_shape, device=device, dtype=dtype)
@@ -1083,18 +1036,22 @@ def test_deg2rad(batch_shape, device, dtype, atol, rtol):
assert_allclose(x_deg, x_rad_to_deg, atol=atol, rtol=rtol)
eps = torch.finfo(dtype).eps
- assert gradcheck(kornia.deg2rad, (tensor_to_gradcheck_var(x_deg),),
- raise_exception=True)
+ assert gradcheck(kornia.deg2rad, (tensor_to_gradcheck_var(x_deg), ), raise_exception=True)
class TestPolCartConversions:
+
def test_smoke(self, device, dtype):
x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
assert kornia.pol2cart(x, x) is not None
assert kornia.cart2pol(x, x) is not None
@pytest.mark.parametrize("batch_shape", [
- (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ (2, 3),
+ (1, 2, 3),
+ (2, 3, 3),
+ (5, 5, 3),
+ ])
def test_pol2cart(self, batch_shape, device, dtype):
# generate input data
rho = torch.rand(batch_shape, dtype=dtype)
@@ -1109,11 +1066,19 @@ class TestPolCartConversions:
assert_allclose(rho, rho_pol2cart)
assert_allclose(phi, phi_pol2cart)
- assert gradcheck(kornia.pol2cart, (tensor_to_gradcheck_var(rho),
- tensor_to_gradcheck_var(phi),), raise_exception=True)
+ assert gradcheck(
+ kornia.pol2cart, (
+ tensor_to_gradcheck_var(rho),
+ tensor_to_gradcheck_var(phi),
+ ), raise_exception=True
+ )
@pytest.mark.parametrize("batch_shape", [
- (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ (2, 3),
+ (1, 2, 3),
+ (2, 3, 3),
+ (5, 5, 3),
+ ])
def test_cart2pol(self, batch_shape, device, dtype):
# generate input data
x = torch.rand(batch_shape, dtype=dtype)
@@ -1128,28 +1093,39 @@ class TestPolCartConversions:
assert_allclose(x, x_cart2pol)
assert_allclose(y, y_cart2pol)
- assert gradcheck(kornia.cart2pol, (tensor_to_gradcheck_var(x),
- tensor_to_gradcheck_var(y),), raise_exception=True)
+ assert gradcheck(
+ kornia.cart2pol, (
+ tensor_to_gradcheck_var(x),
+ tensor_to_gradcheck_var(y),
+ ), raise_exception=True
+ )
class TestConvertPointsToHomogeneous:
+
def test_convert_points(self, device, dtype):
# generate input data
- points_h = torch.tensor([
- [1., 2., 1.],
- [0., 1., 2.],
- [2., 1., 0.],
- [-1., -2., -1.],
- [0., 1., -2.],
- ], device=device, dtype=dtype)
-
- expected = torch.tensor([
- [1., 2., 1., 1.],
- [0., 1., 2., 1.],
- [2., 1., 0., 1.],
- [-1., -2., -1., 1.],
- [0., 1., -2., 1.],
- ], device=device, dtype=dtype)
+ points_h = torch.tensor(
+ [
+ [1., 2., 1.],
+ [0., 1., 2.],
+ [2., 1., 0.],
+ [-1., -2., -1.],
+ [0., 1., -2.],
+ ], device=device, dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [1., 2., 1., 1.],
+ [0., 1., 2., 1.],
+ [2., 1., 0., 1.],
+ [-1., -2., -1., 1.],
+ [0., 1., -2., 1.],
+ ],
+ device=device,
+ dtype=dtype
+ )
# to euclidean
points = kornia.convert_points_to_homogeneous(points_h)
@@ -1165,27 +1141,32 @@ class TestConvertPointsToHomogeneous:
[0., 1., -2.],
]], device=device, dtype=dtype)
- expected = torch.tensor([[
- [2., 1., 0., 1.],
- ], [
- [0., 1., 2., 1.],
- ], [
- [0., 1., -2., 1.],
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[
+ [2., 1., 0., 1.],
+ ], [
+ [0., 1., 2., 1.],
+ ], [
+ [0., 1., -2., 1.],
+ ]], device=device, dtype=dtype
+ )
# to euclidean
points = kornia.convert_points_to_homogeneous(points_h)
assert_allclose(points, expected, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_shape", [
- (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ (2, 3),
+ (1, 2, 3),
+ (2, 3, 3),
+ (5, 5, 3),
+ ])
def test_gradcheck(self, batch_shape, device, dtype):
points_h = torch.rand(batch_shape, device=device, dtype=dtype)
# evaluate function gradient
points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(kornia.convert_points_to_homogeneous, (points_h,),
- raise_exception=True)
+ assert gradcheck(kornia.convert_points_to_homogeneous, (points_h, ), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.geometry.conversions.convert_points_to_homogeneous
@@ -1195,6 +1176,7 @@ class TestConvertPointsToHomogeneous:
class TestConvertAtoH:
+
def test_convert_points(self, device, dtype):
# generate input data
A = torch.tensor([
@@ -1212,15 +1194,13 @@ class TestConvertAtoH:
H = kornia.geometry.conversions.convert_affinematrix_to_homography(A)
assert_allclose(H, expected)
- @pytest.mark.parametrize("batch_shape", [
- (10, 2, 3), (16, 2, 3)])
+ @pytest.mark.parametrize("batch_shape", [(10, 2, 3), (16, 2, 3)])
def test_gradcheck(self, batch_shape, device, dtype):
points_h = torch.rand(batch_shape, device=device, dtype=dtype)
# evaluate function gradient
points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(kornia.convert_affinematrix_to_homography, (points_h,),
- raise_exception=True)
+ assert gradcheck(kornia.convert_affinematrix_to_homography, (points_h, ), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.geometry.conversions.convert_affinematrix_to_homography
@@ -1230,22 +1210,29 @@ class TestConvertAtoH:
class TestConvertPointsFromHomogeneous:
+
@pytest.mark.parametrize("batch_shape", [
- (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ (2, 3),
+ (1, 2, 3),
+ (2, 3, 3),
+ (5, 5, 3),
+ ])
def test_cardinality(self, device, dtype, batch_shape):
points_h = torch.rand(batch_shape, device=device, dtype=dtype)
points = kornia.convert_points_from_homogeneous(points_h)
- assert points.shape == points.shape[:-1] + (2,)
+ assert points.shape == points.shape[:-1] + (2, )
def test_points(self, device, dtype):
# generate input data
- points_h = torch.tensor([
- [1., 2., 1.],
- [0., 1., 2.],
- [2., 1., 0.],
- [-1., -2., -1.],
- [0., 1., -2.],
- ], device=device, dtype=dtype)
+ points_h = torch.tensor(
+ [
+ [1., 2., 1.],
+ [0., 1., 2.],
+ [2., 1., 0.],
+ [-1., -2., -1.],
+ [0., 1., -2.],
+ ], device=device, dtype=dtype
+ )
expected = torch.tensor([
[1., 2.],
@@ -1286,8 +1273,7 @@ class TestConvertPointsFromHomogeneous:
# evaluate function gradient
points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(kornia.convert_points_from_homogeneous, (points_h,),
- raise_exception=True)
+ assert gradcheck(kornia.convert_points_from_homogeneous, (points_h, ), raise_exception=True)
@pytest.mark.skip("RuntimeError: Jacobian mismatch for output 0 with respect to input 0,")
def test_gradcheck_zvec_zeros(self, device, dtype):
@@ -1300,8 +1286,7 @@ class TestConvertPointsFromHomogeneous:
# evaluate function gradient
points_h = tensor_to_gradcheck_var(points_h) # to var
- assert gradcheck(kornia.convert_points_from_homogeneous, (points_h,),
- raise_exception=True)
+ assert gradcheck(kornia.convert_points_from_homogeneous, (points_h, ), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.geometry.conversions.convert_points_from_homogeneous
@@ -1311,33 +1296,30 @@ class TestConvertPointsFromHomogeneous:
class TestNormalizePixelCoordinates:
+
def test_tensor_bhw2(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
- expected = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True,
+ device=device).to(dtype=dtype)
- grid_norm = kornia.normalize_pixel_coordinates(
- grid, height, width, eps=eps)
+ grid_norm = kornia.normalize_pixel_coordinates(grid, height, width, eps=eps)
assert_allclose(grid_norm, expected, atol=atol, rtol=rtol)
def test_list(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
grid = grid.contiguous().view(-1, 2)
- expected = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True,
+ device=device).to(dtype=dtype)
expected = expected.contiguous().view(-1, 2)
- grid_norm = kornia.normalize_pixel_coordinates(
- grid, height, width, eps=eps)
+ grid_norm = kornia.normalize_pixel_coordinates(grid, height, width, eps=eps)
assert_allclose(grid_norm, expected, atol=atol, rtol=rtol)
@@ -1346,8 +1328,7 @@ class TestNormalizePixelCoordinates:
op_script = torch.jit.script(op)
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
actual = op_script(grid, height, width)
expected = op(grid, height, width)
@@ -1355,31 +1336,28 @@ class TestNormalizePixelCoordinates:
class TestDenormalizePixelCoordinates:
+
def test_tensor_bhw2(self, device, dtype):
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
- expected = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
+ expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False,
+ device=device).to(dtype=dtype)
- grid_norm = kornia.denormalize_pixel_coordinates(
- grid, height, width)
+ grid_norm = kornia.denormalize_pixel_coordinates(grid, height, width)
assert_allclose(grid_norm, expected, atol=1e-4, rtol=1e-4)
def test_list(self, device, dtype):
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
grid = grid.contiguous().view(-1, 2)
- expected = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype=dtype)
+ expected = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False,
+ device=device).to(dtype=dtype)
expected = expected.contiguous().view(-1, 2)
- grid_norm = kornia.denormalize_pixel_coordinates(
- grid, height, width)
+ grid_norm = kornia.denormalize_pixel_coordinates(grid, height, width)
assert_allclose(grid_norm, expected, atol=1e-4, rtol=1e-4)
@@ -1388,8 +1366,7 @@ class TestDenormalizePixelCoordinates:
op_script = torch.jit.script(op)
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device).to(dtype=dtype)
actual = op_script(grid, height, width)
expected = op(grid, height, width)
diff --git a/test/geometry/test_depth.py b/test/geometry/test_depth.py
index 99f312bb3..cbe46df8d 100644
--- a/test/geometry/test_depth.py
+++ b/test/geometry/test_depth.py
@@ -9,6 +9,7 @@ from torch.testing import assert_allclose
class TestDepthTo3d:
+
def test_smoke(self, device, dtype):
depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -34,12 +35,14 @@ class TestDepthTo3d:
def test_unproject_denormalized(self, device, dtype):
# this is for default normalize_points=False
- depth = 2 * torch.tensor([[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
+ depth = 2 * torch.tensor(
+ [[[
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ )
camera_matrix = torch.tensor([[
[1., 0., 0.],
@@ -47,34 +50,44 @@ class TestDepthTo3d:
[0., 0., 1.],
]], device=device, dtype=dtype)
- points3d_expected = torch.tensor([[[
- [0., 2., 4.],
- [0., 2., 4.],
- [0., 2., 4.],
- [0., 2., 4.],
- ], [
- [0., 0., 0.],
- [2., 2., 2.],
- [4., 4., 4.],
- [6., 6., 6.],
- ], [
- [2., 2., 2.],
- [2., 2., 2.],
- [2., 2., 2.],
- [2., 2., 2.],
- ]]], device=device, dtype=dtype)
+ points3d_expected = torch.tensor(
+ [
+ [
+ [
+ [0., 2., 4.],
+ [0., 2., 4.],
+ [0., 2., 4.],
+ [0., 2., 4.],
+ ], [
+ [0., 0., 0.],
+ [2., 2., 2.],
+ [4., 4., 4.],
+ [6., 6., 6.],
+ ], [
+ [2., 2., 2.],
+ [2., 2., 2.],
+ [2., 2., 2.],
+ [2., 2., 2.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
points3d = kornia.depth_to_3d(depth, camera_matrix) # default is normalize_points=False
assert_allclose(points3d, points3d_expected, atol=1e-4, rtol=1e-4)
def test_unproject_normalized(self, device, dtype):
# this is for normalize_points=True
- depth = 2 * torch.tensor([[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
+ depth = 2 * torch.tensor(
+ [[[
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ )
camera_matrix = torch.tensor([[
[1., 0., 0.],
@@ -82,33 +95,45 @@ class TestDepthTo3d:
[0., 0., 1.],
]], device=device, dtype=dtype)
- points3d_expected = torch.tensor([[[
- [0.0000, 1.4142, 1.7889],
- [0.0000, 1.1547, 1.6330],
- [0.0000, 0.8165, 1.3333],
- [0.0000, 0.6030, 1.0690],
- ], [
- [0.0000, 0.0000, 0.0000],
- [1.4142, 1.1547, 0.8165],
- [1.7889, 1.6330, 1.3333],
- [1.8974, 1.8091, 1.6036],
- ], [
- [2.0000, 1.4142, 0.8944],
- [1.4142, 1.1547, 0.8165],
- [0.8944, 0.8165, 0.6667],
- [0.6325, 0.6030, 0.5345],
- ]]], device=device, dtype=dtype)
+ points3d_expected = torch.tensor(
+ [
+ [
+ [
+ [0.0000, 1.4142, 1.7889],
+ [0.0000, 1.1547, 1.6330],
+ [0.0000, 0.8165, 1.3333],
+ [0.0000, 0.6030, 1.0690],
+ ],
+ [
+ [0.0000, 0.0000, 0.0000],
+ [1.4142, 1.1547, 0.8165],
+ [1.7889, 1.6330, 1.3333],
+ [1.8974, 1.8091, 1.6036],
+ ],
+ [
+ [2.0000, 1.4142, 0.8944],
+ [1.4142, 1.1547, 0.8165],
+ [0.8944, 0.8165, 0.6667],
+ [0.6325, 0.6030, 0.5345],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
points3d = kornia.depth_to_3d(depth, camera_matrix, normalize_points=True)
assert_allclose(points3d, points3d_expected, atol=1e-4, rtol=1e-4)
def test_unproject_and_project(self, device, dtype):
- depth = 2 * torch.tensor([[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
+ depth = 2 * torch.tensor(
+ [[[
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ )
camera_matrix = torch.tensor([[
[1., 0., 0.],
@@ -117,10 +142,7 @@ class TestDepthTo3d:
]], device=device, dtype=dtype)
points3d = kornia.depth_to_3d(depth, camera_matrix)
- points2d = kornia.project_points(
- points3d.permute(0, 2, 3, 1),
- camera_matrix[:, None, None]
- )
+ points2d = kornia.project_points(points3d.permute(0, 2, 3, 1), camera_matrix[:, None, None])
points2d_expected = kornia.create_meshgrid(4, 3, False, device=device).to(dtype=dtype)
assert_allclose(points2d, points2d_expected, atol=1e-4, rtol=1e-4)
@@ -133,11 +155,14 @@ class TestDepthTo3d:
camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var
# evaluate function gradient
- assert gradcheck(kornia.depth_to_3d, (depth, camera_matrix,),
- raise_exception=True)
+ assert gradcheck(kornia.depth_to_3d, (
+ depth,
+ camera_matrix,
+ ), raise_exception=True)
class TestDepthToNormals:
+
def test_smoke(self, device, dtype):
depth = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
camera_matrix = torch.rand(1, 3, 3, device=device, dtype=dtype)
@@ -163,12 +188,14 @@ class TestDepthToNormals:
def test_simple(self, device, dtype):
# this is for default normalize_points=False
- depth = 2 * torch.tensor([[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
+ depth = 2 * torch.tensor(
+ [[[
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ )
camera_matrix = torch.tensor([[
[1., 0., 0.],
@@ -176,34 +203,44 @@ class TestDepthToNormals:
[0., 0., 1.],
]], device=device, dtype=dtype)
- normals_expected = torch.tensor([[[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ], [
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
+ normals_expected = torch.tensor(
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
normals = kornia.depth_to_normals(depth, camera_matrix) # default is normalize_points=False
assert_allclose(normals, normals_expected, 1e-3, 1e-3)
def test_simple_normalized(self, device, dtype):
# this is for default normalize_points=False
- depth = 2 * torch.tensor([[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
+ depth = 2 * torch.tensor(
+ [[[
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ )
camera_matrix = torch.tensor([[
[1., 0., 0.],
@@ -211,22 +248,32 @@ class TestDepthToNormals:
[0., 0., 1.],
]], device=device, dtype=dtype)
- normals_expected = torch.tensor([[[
- [0.3432, 0.4861, 0.7628],
- [0.2873, 0.4260, 0.6672],
- [0.2284, 0.3683, 0.5596],
- [0.1695, 0.2980, 0.4496],
- ], [
- [0.3432, 0.2873, 0.2363],
- [0.4861, 0.4260, 0.3785],
- [0.8079, 0.7261, 0.6529],
- [0.8948, 0.8237, 0.7543],
- ], [
- [0.8743, 0.8253, 0.6019],
- [0.8253, 0.7981, 0.6415],
- [0.5432, 0.5807, 0.5105],
- [0.4129, 0.4824, 0.4784],
- ]]], device=device, dtype=dtype)
+ normals_expected = torch.tensor(
+ [
+ [
+ [
+ [0.3432, 0.4861, 0.7628],
+ [0.2873, 0.4260, 0.6672],
+ [0.2284, 0.3683, 0.5596],
+ [0.1695, 0.2980, 0.4496],
+ ],
+ [
+ [0.3432, 0.2873, 0.2363],
+ [0.4861, 0.4260, 0.3785],
+ [0.8079, 0.7261, 0.6529],
+ [0.8948, 0.8237, 0.7543],
+ ],
+ [
+ [0.8743, 0.8253, 0.6019],
+ [0.8253, 0.7981, 0.6415],
+ [0.5432, 0.5807, 0.5105],
+ [0.4129, 0.4824, 0.4784],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
normals = kornia.depth_to_normals(depth, camera_matrix, normalize_points=True)
assert_allclose(normals, normals_expected, 1e-3, 1e-3)
@@ -240,11 +287,14 @@ class TestDepthToNormals:
camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var
# evaluate function gradient
- assert gradcheck(kornia.depth_to_normals, (depth, camera_matrix,),
- raise_exception=True)
+ assert gradcheck(kornia.depth_to_normals, (
+ depth,
+ camera_matrix,
+ ), raise_exception=True)
class TestWarpFrameDepth:
+
def test_smoke(self, device, dtype):
image_src = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
depth_dst = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
@@ -267,26 +317,32 @@ class TestWarpFrameDepth:
def test_translation(self, device, dtype):
# this is for normalize_points=False
- image_src = torch.tensor([[[
- [1., 2., 3.],
- [1., 2., 3.],
- [1., 2., 3.],
- [1., 2., 3.],
- ]]], device=device, dtype=dtype)
-
- depth_dst = torch.tensor([[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
-
- src_trans_dst = torch.tensor([[
- [1., 0., 0., 1.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.],
- ]], device=device, dtype=dtype)
+ image_src = torch.tensor(
+ [[[
+ [1., 2., 3.],
+ [1., 2., 3.],
+ [1., 2., 3.],
+ [1., 2., 3.],
+ ]]], device=device, dtype=dtype
+ )
+
+ depth_dst = torch.tensor(
+ [[[
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ )
+
+ src_trans_dst = torch.tensor(
+ [[
+ [1., 0., 0., 1.],
+ [0., 1., 0., 0.],
+ [0., 0., 1., 0.],
+ [0., 0., 0., 1.],
+ ]], device=device, dtype=dtype
+ )
h, w = image_src.shape[-2:]
camera_matrix = torch.tensor([[
@@ -295,39 +351,48 @@ class TestWarpFrameDepth:
[0., 0., 1.],
]], device=device, dtype=dtype)
- image_dst_expected = torch.tensor([[[
- [2., 3., 0.],
- [2., 3., 0.],
- [2., 3., 0.],
- [2., 3., 0.],
- ]]], device=device, dtype=dtype)
+ image_dst_expected = torch.tensor(
+ [[[
+ [2., 3., 0.],
+ [2., 3., 0.],
+ [2., 3., 0.],
+ [2., 3., 0.],
+ ]]], device=device, dtype=dtype
+ )
image_dst = kornia.warp_frame_depth(
- image_src, depth_dst, src_trans_dst, camera_matrix) # default is normalize_points=False
+ image_src, depth_dst, src_trans_dst, camera_matrix
+ ) # default is normalize_points=False
assert_allclose(image_dst, image_dst_expected, 1e-3, 1e-3)
def test_translation_normalized(self, device, dtype):
# this is for normalize_points=True
- image_src = torch.tensor([[[
- [1., 2., 3.],
- [1., 2., 3.],
- [1., 2., 3.],
- [1., 2., 3.],
- ]]], device=device, dtype=dtype)
-
- depth_dst = torch.tensor([[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype)
-
- src_trans_dst = torch.tensor([[
- [1., 0., 0., 1.],
- [0., 1., 0., 0.],
- [0., 0., 1., 0.],
- [0., 0., 0., 1.],
- ]], device=device, dtype=dtype)
+ image_src = torch.tensor(
+ [[[
+ [1., 2., 3.],
+ [1., 2., 3.],
+ [1., 2., 3.],
+ [1., 2., 3.],
+ ]]], device=device, dtype=dtype
+ )
+
+ depth_dst = torch.tensor(
+ [[[
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ [1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ )
+
+ src_trans_dst = torch.tensor(
+ [[
+ [1., 0., 0., 1.],
+ [0., 1., 0., 0.],
+ [0., 0., 1., 0.],
+ [0., 0., 0., 1.],
+ ]], device=device, dtype=dtype
+ )
h, w = image_src.shape[-2:]
camera_matrix = torch.tensor([[
@@ -336,15 +401,22 @@ class TestWarpFrameDepth:
[0., 0., 1.],
]], device=device, dtype=dtype)
- image_dst_expected = torch.tensor([[[
- [0.9223, 0.0000, 0.0000],
- [2.8153, 1.5000, 0.0000],
- [2.8028, 2.6459, 0.0000],
- [2.8153, 1.5000, 0.0000],
- ]]], device=device, dtype=dtype)
+ image_dst_expected = torch.tensor(
+ [
+ [
+ [
+ [0.9223, 0.0000, 0.0000],
+ [2.8153, 1.5000, 0.0000],
+ [2.8028, 2.6459, 0.0000],
+ [2.8153, 1.5000, 0.0000],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
- image_dst = kornia.warp_frame_depth(
- image_src, depth_dst, src_trans_dst, camera_matrix, normalize_points=True)
+ image_dst = kornia.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix, normalize_points=True)
assert_allclose(image_dst, image_dst_expected, 1e-3, 1e-3)
def test_gradcheck(self, device, dtype):
@@ -361,5 +433,11 @@ class TestWarpFrameDepth:
camera_matrix = utils.tensor_to_gradcheck_var(camera_matrix) # to var
# evaluate function gradient
- assert gradcheck(kornia.warp_frame_depth, (image_src, depth_dst, src_trans_dst, camera_matrix,),
- raise_exception=True)
+ assert gradcheck(
+ kornia.warp_frame_depth, (
+ image_src,
+ depth_dst,
+ src_trans_dst,
+ camera_matrix,
+ ), raise_exception=True
+ )
diff --git a/test/geometry/test_depth_warper.py b/test/geometry/test_depth_warper.py
index c169652ac..8afe6946f 100644
--- a/test/geometry/test_depth_warper.py
+++ b/test/geometry/test_depth_warper.py
@@ -21,12 +21,17 @@ class TestDepthWarper:
# create pinhole cameras
pinhole_src = kornia.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device=device, dtype=dtype)
+ fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device=device, dtype=dtype
+ )
pinhole_dst = kornia.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device=device, dtype=dtype)
+ fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device=device, dtype=dtype
+ )
return pinhole_src, pinhole_dst
- @pytest.mark.parametrize("batch_size", (1, 2,))
+ @pytest.mark.parametrize("batch_size", (
+ 1,
+ 2,
+ ))
def test_compute_projection_matrix(self, batch_size, device, dtype):
height, width = 3, 5 # output shape
pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)
@@ -48,7 +53,10 @@ class TestDepthWarper:
dst_proj_src_expected[..., 0, -1] += 1. # offset to x-axis
assert_allclose(dst_proj_src, dst_proj_src_expected)
- @pytest.mark.parametrize("batch_size", (1, 2,))
+ @pytest.mark.parametrize("batch_size", (
+ 1,
+ 2,
+ ))
def test_warp_grid_offset_x1_depth1(self, batch_size, device, dtype):
height, width = 3, 5 # output shape
pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)
@@ -69,13 +77,14 @@ class TestDepthWarper:
grid_norm = normalize_pixel_coordinates(grid, height, width)
# check offset in x-axis
- assert_allclose(
- grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
+ assert_allclose(grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
# check that y-axis remain the same
- assert_allclose(
- grid_warped[..., -1, 1], grid_norm[..., -1, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4)
+ assert_allclose(grid_warped[..., -1, 1], grid_norm[..., -1, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4)
- @pytest.mark.parametrize("batch_size", (1, 2,))
+ @pytest.mark.parametrize("batch_size", (
+ 1,
+ 2,
+ ))
def test_warp_grid_offset_x1y1_depth1(self, batch_size, device, dtype):
height, width = 3, 5 # output shape
pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)
@@ -97,13 +106,16 @@ class TestDepthWarper:
grid_norm = normalize_pixel_coordinates(grid, height, width)
# check offset in x-axis
- assert_allclose(
- grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
+ assert_allclose(grid_warped[..., -2, 0], grid_norm[..., -1, 0].repeat(batch_size, 1), atol=1e-4, rtol=1e-4)
# check that y-axis remain the same
assert_allclose(
- grid_warped[..., -2, :, 1], grid_norm[..., -1, :, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4)
+ grid_warped[..., -2, :, 1], grid_norm[..., -1, :, 1].repeat(batch_size, 1), rtol=1e-4, atol=1e-4
+ )
- @pytest.mark.parametrize("batch_size", (1, 2,))
+ @pytest.mark.parametrize("batch_size", (
+ 1,
+ 2,
+ ))
def test_warp_tensor_offset_x1y1(self, batch_size, device, dtype):
channels, height, width = 3, 3, 5 # output shape
pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)
@@ -118,17 +130,19 @@ class TestDepthWarper:
warper.compute_projection_matrix(pinhole_src)
# create patch to warp
- patch_dst = torch.arange(float(height * width), device=device, dtype=dtype).view(
- 1, 1, height, width).expand(batch_size, channels, -1, -1)
+ patch_dst = torch.arange(float(height * width), device=device,
+ dtype=dtype).view(1, 1, height, width).expand(batch_size, channels, -1, -1)
# warpd source patch by depth
patch_src = warper(depth_src, patch_dst)
# compare patches
- assert_allclose(
- patch_dst[..., 1:, 1:], patch_src[..., :2, :4], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_dst[..., 1:, 1:], patch_src[..., :2, :4], atol=1e-4, rtol=1e-4)
- @pytest.mark.parametrize("batch_size", (1, 2,))
+ @pytest.mark.parametrize("batch_size", (
+ 1,
+ 2,
+ ))
def test_compute_projection(self, batch_size, device, dtype):
height, width = 3, 5 # output shape
pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)
@@ -141,7 +155,10 @@ class TestDepthWarper:
xy_projected = warper._compute_projection(0.0, 0.0, 1.0)
assert xy_projected.shape == (batch_size, 2)
- @pytest.mark.parametrize("batch_size", (1, 2,))
+ @pytest.mark.parametrize("batch_size", (
+ 1,
+ 2,
+ ))
def test_compute_subpixel_step(self, batch_size, device, dtype):
height, width = 3, 5 # output shape
pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size, device, dtype)
@@ -169,15 +186,16 @@ class TestDepthWarper:
img_dst = utils.tensor_to_gradcheck_var(img_dst) # to var
# evaluate function gradient
- assert gradcheck(kornia.depth_warp,
- (pinhole_dst,
- pinhole_src,
- depth_src,
- img_dst,
- height,
- width,
- ),
- raise_exception=True)
+ assert gradcheck(
+ kornia.depth_warp, (
+ pinhole_dst,
+ pinhole_src,
+ depth_src,
+ img_dst,
+ height,
+ width,
+ ), raise_exception=True
+ )
# TODO(edgar): we should include a test showing some kind of occlusion
# def test_warp_with_occlusion(self):
diff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.py
index d9a8cf2b9..729bc9818 100644
--- a/test/geometry/test_homography.py
+++ b/test/geometry/test_homography.py
@@ -11,6 +11,7 @@ from kornia.geometry.homography import find_homography_dlt, find_homography_dlt_
class TestFindHomographyDLT:
+
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -19,7 +20,8 @@ class TestFindHomographyDLT:
assert H.shape == (1, 3, 3)
@pytest.mark.parametrize(
- "batch_size, num_points", [(1, 4), (2, 5), (3, 6)],
+ "batch_size, num_points",
+ [(1, 4), (2, 5), (3, 6)],
)
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
@@ -29,7 +31,10 @@ class TestFindHomographyDLT:
H = find_homography_dlt(points1, points2, weights)
assert H.shape == (B, 3, 3)
- @pytest.mark.parametrize("batch_size, num_points", [(1, 4), (2, 5), (3, 6)],)
+ @pytest.mark.parametrize(
+ "batch_size, num_points",
+ [(1, 4), (2, 5), (3, 6)],
+ )
def test_shape_noweights(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
@@ -37,7 +42,10 @@ class TestFindHomographyDLT:
H = find_homography_dlt(points1, points2, None)
assert H.shape == (B, 3, 3)
- @pytest.mark.parametrize("batch_size, num_points", [(1, 4), (2, 5), (3, 6)], )
+ @pytest.mark.parametrize(
+ "batch_size, num_points",
+ [(1, 4), (2, 5), (3, 6)],
+ )
def test_points_noweights(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
@@ -62,8 +70,7 @@ class TestFindHomographyDLT:
# compute transform from source to target
dst_homo_src = find_homography_dlt(points_src, points_dst, weights)
- assert_allclose(
- kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+ assert_allclose(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
@pytest.mark.grad
@pytest.mark.skipif(torch.__version__ < '1.7', reason="pytorch bug of incopatible types: #33546 fixed in v1.7")
@@ -80,16 +87,21 @@ class TestFindHomographyDLT:
points_dst = torch.rand_like(points_src)
weights = torch.ones_like(points_src)[..., 0]
try:
- gradcheck(find_homography_dlt, (points_src, points_dst, weights), rtol=1e-6, atol=1e-6,
- raise_exception=True)
+ gradcheck(
+ find_homography_dlt, (points_src, points_dst, weights), rtol=1e-6, atol=1e-6, raise_exception=True
+ )
# Gradcheck failed
except RuntimeError:
# All iterations failed
if i == max_number_of_checks - 1:
- assert gradcheck(find_homography_dlt, (points_src, points_dst, weights), rtol=1e-6, atol=1e-6,
- raise_exception=True)
+ assert gradcheck(
+ find_homography_dlt, (points_src, points_dst, weights),
+ rtol=1e-6,
+ atol=1e-6,
+ raise_exception=True
+ )
# Next iteration
else:
current_seed = random.randrange(0xffffffffffffffff)
@@ -101,6 +113,7 @@ class TestFindHomographyDLT:
class TestFindHomographyDLTIter:
+
def test_smoke(self, device, dtype):
points1 = torch.rand(1, 4, 2, device=device, dtype=dtype)
points2 = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -109,7 +122,8 @@ class TestFindHomographyDLTIter:
assert H.shape == (1, 3, 3)
@pytest.mark.parametrize(
- "batch_size, num_points", [(1, 4), (2, 5), (3, 6)],
+ "batch_size, num_points",
+ [(1, 4), (2, 5), (3, 6)],
)
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
@@ -133,8 +147,7 @@ class TestFindHomographyDLTIter:
# compute transform from source to target
dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 10)
- assert_allclose(
- kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
+ assert_allclose(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-3, atol=1e-4)
@pytest.mark.grad
@pytest.mark.skipif(torch.__version__ < '1.7', reason="pytorch bug of incopatible types: #33546 fixed in v1.7")
@@ -152,16 +165,24 @@ class TestFindHomographyDLTIter:
points_dst = torch.rand_like(points_src)
weights = torch.ones_like(points_src)[..., 0]
try:
- gradcheck(find_homography_dlt_iterated, (points_src, points_dst, weights), rtol=1e-6, atol=1e-6,
- raise_exception=True)
+ gradcheck(
+ find_homography_dlt_iterated, (points_src, points_dst, weights),
+ rtol=1e-6,
+ atol=1e-6,
+ raise_exception=True
+ )
# Gradcheck failed
except RuntimeError:
# All iterations failed
if i == max_number_of_checks - 1:
- assert gradcheck(find_homography_dlt_iterated, (points_src, points_dst, weights), rtol=1e-6,
- atol=1e-6, raise_exception=True)
+ assert gradcheck(
+ find_homography_dlt_iterated, (points_src, points_dst, weights),
+ rtol=1e-6,
+ atol=1e-6,
+ raise_exception=True
+ )
# Next iteration
else:
current_seed = random.randrange(0xffffffffffffffff)
@@ -192,5 +213,5 @@ class TestFindHomographyDLTIter:
dst_homo_src = find_homography_dlt_iterated(points_src, points_dst, weights, 0.5, 10)
assert_allclose(
- kornia.transform_points(dst_homo_src, points_src[:, :-1]),
- points_dst[:, :-1], rtol=1e-3, atol=1e-3)
+ kornia.transform_points(dst_homo_src, points_src[:, :-1]), points_dst[:, :-1], rtol=1e-3, atol=1e-3
+ )
diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.py
index 79ac8f497..0288636e3 100644
--- a/test/geometry/test_linalg.py
+++ b/test/geometry/test_linalg.py
@@ -20,24 +20,25 @@ def euler_angles_to_rotation_matrix(x, y, z):
ones, zeros = torch.ones_like(x), torch.zeros_like(x)
# the rotation matrix for the x-axis
rx_tmp = [
- ones, zeros, zeros, zeros,
- zeros, torch.cos(x), -torch.sin(x), zeros,
- zeros, torch.sin(x), torch.cos(x), zeros,
- zeros, zeros, zeros, ones]
+ ones, zeros, zeros, zeros, zeros,
+ torch.cos(x), -torch.sin(x), zeros, zeros,
+ torch.sin(x),
+ torch.cos(x), zeros, zeros, zeros, zeros, ones
+ ]
rx = torch.stack(rx_tmp, dim=-1).view(-1, 4, 4)
# the rotation matrix for the y-axis
ry_tmp = [
- torch.cos(y), zeros, torch.sin(y), zeros,
- zeros, ones, zeros, zeros,
- -torch.sin(y), zeros, torch.cos(y), zeros,
- zeros, zeros, zeros, ones]
+ torch.cos(y), zeros,
+ torch.sin(y), zeros, zeros, ones, zeros, zeros, -torch.sin(y), zeros,
+ torch.cos(y), zeros, zeros, zeros, zeros, ones
+ ]
ry = torch.stack(ry_tmp, dim=-1).view(-1, 4, 4)
# the rotation matrix for the z-axis
rz_tmp = [
torch.cos(z), -torch.sin(z), zeros, zeros,
- torch.sin(z), torch.cos(z), zeros, zeros,
- zeros, zeros, ones, zeros,
- zeros, zeros, zeros, ones]
+ torch.sin(z),
+ torch.cos(z), zeros, zeros, zeros, zeros, ones, zeros, zeros, zeros, zeros, ones
+ ]
rz = torch.stack(rz_tmp, dim=-1).view(-1, 4, 4)
return torch.matmul(rz, torch.matmul(ry, rx)) # Bx4x4
@@ -47,8 +48,7 @@ class TestTransformPoints:
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@pytest.mark.parametrize("num_points", [2, 3, 5])
@pytest.mark.parametrize("num_dims", [2, 3])
- def test_transform_points(
- self, batch_size, num_points, num_dims, device, dtype):
+ def test_transform_points(self, batch_size, num_points, num_dims, device, dtype):
# generate input data
eye_size = num_dims + 1
points_src = torch.rand(batch_size, num_points, num_dims, device=device, dtype=dtype)
@@ -75,8 +75,10 @@ class TestTransformPoints:
# evaluate function gradient
points_src = utils.tensor_to_gradcheck_var(points_src) # to var
dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src) # to var
- assert gradcheck(kornia.geometry.transform_points, (dst_homo_src, points_src,),
- raise_exception=True)
+ assert gradcheck(kornia.geometry.transform_points, (
+ dst_homo_src,
+ points_src,
+ ), raise_exception=True)
def test_jit(self, device, dtype):
points = torch.ones(1, 2, 2, device=device, dtype=dtype)
@@ -96,72 +98,85 @@ class TestTransformBoxes:
expected = torch.tensor([[372.7360, 103.0150, 114.6880, 410.5225]], device=device, dtype=dtype)
- trans_mat = torch.tensor([[[-1., 0., 512.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype)
+ trans_mat = torch.tensor([[[-1., 0., 512.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype)
out = kornia.transform_boxes(trans_mat, boxes)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_transform_multiple_boxes(self, device, dtype):
- boxes = torch.tensor([[139.2640, 103.0150, 397.3120, 410.5225],
- [1.0240, 80.5547, 512.0000, 512.0000],
- [165.2053, 262.1440, 510.6347, 508.9280],
- [119.8080, 144.2067, 257.0240, 410.1292]], device=device, dtype=dtype)
+ boxes = torch.tensor(
+ [
+ [139.2640, 103.0150, 397.3120, 410.5225], [1.0240, 80.5547, 512.0000, 512.0000],
+ [165.2053, 262.1440, 510.6347, 508.9280], [119.8080, 144.2067, 257.0240, 410.1292]
+ ],
+ device=device,
+ dtype=dtype
+ )
boxes = boxes.repeat(2, 1, 1) # 2 x 4 x 4 two images 4 boxes each
- expected = torch.tensor([[[372.7360, 103.0150, 114.6880, 410.5225],
- [510.9760, 80.5547, 0.0000, 512.0000],
- [346.7947, 262.1440, 1.3653, 508.9280],
- [392.1920, 144.2067, 254.9760, 410.1292]],
-
- [[139.2640, 103.0150, 397.3120, 410.5225],
- [1.0240, 80.5547, 512.0000, 512.0000],
- [165.2053, 262.1440, 510.6347, 508.9280],
- [119.8080, 144.2067, 257.0240, 410.1292]]], device=device, dtype=dtype)
-
- trans_mat = torch.tensor([[[-1., 0., 512.],
- [0., 1., 0.],
- [0., 0., 1.]],
-
- [[1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [372.7360, 103.0150, 114.6880, 410.5225], [510.9760, 80.5547, 0.0000, 512.0000],
+ [346.7947, 262.1440, 1.3653, 508.9280], [392.1920, 144.2067, 254.9760, 410.1292]
+ ],
+ [
+ [139.2640, 103.0150, 397.3120, 410.5225], [1.0240, 80.5547, 512.0000, 512.0000],
+ [165.2053, 262.1440, 510.6347, 508.9280], [119.8080, 144.2067, 257.0240, 410.1292]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ trans_mat = torch.tensor(
+ [[[-1., 0., 512.], [0., 1., 0.], [0., 0., 1.]], [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]],
+ device=device,
+ dtype=dtype
+ )
out = kornia.transform_boxes(trans_mat, boxes)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_transform_boxes_wh(self, device, dtype):
- boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075],
- [1.0240, 80.5547, 510.9760, 431.4453],
- [165.2053, 262.1440, 345.4293, 246.7840],
- [119.8080, 144.2067, 137.2160, 265.9225]], device=device, dtype=dtype)
-
- expected = torch.tensor([[372.7360, 103.0150, -258.0480, 307.5075],
- [510.9760, 80.5547, -510.9760, 431.4453],
- [346.7947, 262.1440, -345.4293, 246.7840],
- [392.1920, 144.2067, -137.2160, 265.9225]], device=device, dtype=dtype)
-
- trans_mat = torch.tensor([[[-1., 0., 512.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype)
+ boxes = torch.tensor(
+ [
+ [139.2640, 103.0150, 258.0480, 307.5075], [1.0240, 80.5547, 510.9760, 431.4453],
+ [165.2053, 262.1440, 345.4293, 246.7840], [119.8080, 144.2067, 137.2160, 265.9225]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [372.7360, 103.0150, -258.0480, 307.5075], [510.9760, 80.5547, -510.9760, 431.4453],
+ [346.7947, 262.1440, -345.4293, 246.7840], [392.1920, 144.2067, -137.2160, 265.9225]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ trans_mat = torch.tensor([[[-1., 0., 512.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype)
out = kornia.transform_boxes(trans_mat, boxes, mode='xywh')
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device, dtype):
- boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075],
- [1.0240, 80.5547, 510.9760, 431.4453],
- [165.2053, 262.1440, 345.4293, 246.7840],
- [119.8080, 144.2067, 137.2160, 265.9225]], device=device, dtype=dtype)
+ boxes = torch.tensor(
+ [
+ [139.2640, 103.0150, 258.0480, 307.5075], [1.0240, 80.5547, 510.9760, 431.4453],
+ [165.2053, 262.1440, 345.4293, 246.7840], [119.8080, 144.2067, 137.2160, 265.9225]
+ ],
+ device=device,
+ dtype=dtype
+ )
- trans_mat = torch.tensor([[[-1., 0., 512.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype)
+ trans_mat = torch.tensor([[[-1., 0., 512.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype)
trans_mat = utils.tensor_to_gradcheck_var(trans_mat)
boxes = utils.tensor_to_gradcheck_var(boxes)
@@ -170,9 +185,7 @@ class TestTransformBoxes:
def test_jit(self, device, dtype):
boxes = torch.tensor([[139.2640, 103.0150, 258.0480, 307.5075]], device=device, dtype=dtype)
- trans_mat = torch.tensor([[[-1., 0., 512.],
- [0., 1., 0.],
- [0., 0., 1.]]], device=device, dtype=dtype)
+ trans_mat = torch.tensor([[[-1., 0., 512.], [0., 1., 0.], [0., 0., 1.]]], device=device, dtype=dtype)
args = (boxes, trans_mat)
op = kornia.geometry.transform_points
op_jit = torch.jit.script(op)
@@ -207,8 +220,10 @@ class TestComposeTransforms:
trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to var
trans_12 = utils.tensor_to_gradcheck_var(trans_12) # to var
- assert gradcheck(kornia.compose_transformations, (trans_01, trans_12,),
- raise_exception=True)
+ assert gradcheck(kornia.compose_transformations, (
+ trans_01,
+ trans_12,
+ ), raise_exception=True)
class TestInverseTransformation:
@@ -251,8 +266,7 @@ class TestInverseTransformation:
def test_gradcheck(self, batch_size, device, dtype):
trans_01 = identity_matrix(batch_size, device=device, dtype=dtype)
trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to var
- assert gradcheck(kornia.inverse_transformation, (trans_01,),
- raise_exception=True)
+ assert gradcheck(kornia.inverse_transformation, (trans_01, ), raise_exception=True)
class TestRelativeTransformation:
@@ -290,16 +304,17 @@ class TestRelativeTransformation:
trans_01 = utils.tensor_to_gradcheck_var(trans_01) # to var
trans_02 = utils.tensor_to_gradcheck_var(trans_02) # to var
- assert gradcheck(kornia.relative_transformation, (trans_01, trans_02,),
- raise_exception=True)
+ assert gradcheck(kornia.relative_transformation, (
+ trans_01,
+ trans_02,
+ ), raise_exception=True)
class TestTransformLAFs:
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@pytest.mark.parametrize("num_points", [2, 3, 5])
- def test_transform_points(
- self, batch_size, num_points, device, dtype):
+ def test_transform_points(self, batch_size, num_points, device, dtype):
# generate input data
eye_size = 3
lafs_src = torch.rand(batch_size, num_points, 2, 3, device=device, dtype=dtype)
@@ -325,5 +340,7 @@ class TestTransformLAFs:
# evaluate function gradient
points_src = utils.tensor_to_gradcheck_var(points_src) # to var
dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src) # to var
- assert gradcheck(kornia.perspective_transform_lafs, (dst_homo_src, points_src,),
- raise_exception=True)
+ assert gradcheck(kornia.perspective_transform_lafs, (
+ dst_homo_src,
+ points_src,
+ ), raise_exception=True)
diff --git a/test/geometry/test_perspective.py b/test/geometry/test_perspective.py
index 312dcbe55..bbb483270 100644
--- a/test/geometry/test_perspective.py
+++ b/test/geometry/test_perspective.py
@@ -9,6 +9,7 @@ from torch.testing import assert_allclose
class TestProjectPoints:
+
def test_smoke(self, device, dtype):
point_3d = torch.zeros(1, 3, device=device, dtype=dtype)
camera_matrix = torch.eye(3, device=device, dtype=dtype).expand(1, -1, -1)
@@ -30,11 +31,13 @@ class TestProjectPoints:
def test_project_and_unproject(self, device, dtype):
point_3d = torch.tensor([[10., 2., 30.]], device=device, dtype=dtype)
depth = point_3d[..., -1:]
- camera_matrix = torch.tensor([[
- [2746., 0., 991.],
- [0., 2748., 619.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor(
+ [[
+ [2746., 0., 991.],
+ [0., 2748., 619.],
+ [0., 0., 1.],
+ ]], device=device, dtype=dtype
+ )
point_2d = kornia.geometry.camera.project_points(point_3d, camera_matrix)
point_3d_hat = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix)
assert_allclose(point_3d, point_3d_hat, atol=1e-4, rtol=1e-4)
@@ -47,9 +50,7 @@ class TestProjectPoints:
# evaluate function gradient
points_3d = tensor_to_gradcheck_var(points_3d)
camera_matrix = tensor_to_gradcheck_var(camera_matrix)
- assert gradcheck(kornia.geometry.camera.project_points,
- (points_3d, camera_matrix),
- raise_exception=True)
+ assert gradcheck(kornia.geometry.camera.project_points, (points_3d, camera_matrix), raise_exception=True)
def test_jit(self, device, dtype):
points_3d = torch.zeros(1, 3, device=device, dtype=dtype)
@@ -60,6 +61,7 @@ class TestProjectPoints:
class TestUnprojectPoints:
+
def test_smoke(self, device, dtype):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
depth = torch.ones(1, 1, device=device, dtype=dtype)
@@ -126,9 +128,9 @@ class TestUnprojectPoints:
points_2d = tensor_to_gradcheck_var(points_2d)
depth = tensor_to_gradcheck_var(depth)
camera_matrix = tensor_to_gradcheck_var(camera_matrix)
- assert gradcheck(kornia.geometry.camera.unproject_points,
- (points_2d, depth, camera_matrix),
- raise_exception=True)
+ assert gradcheck(
+ kornia.geometry.camera.unproject_points, (points_2d, depth, camera_matrix), raise_exception=True
+ )
def test_jit(self, device, dtype):
points_2d = torch.zeros(1, 2, device=device, dtype=dtype)
diff --git a/test/geometry/test_pinhole.py b/test/geometry/test_pinhole.py
index 7432fa719..a8be5df37 100644
--- a/test/geometry/test_pinhole.py
+++ b/test/geometry/test_pinhole.py
@@ -9,6 +9,7 @@ from torch.testing import assert_allclose
class TestPinholeCamera:
+
def _create_intrinsics(self, batch_size, fx, fy, cx, cy, device, dtype):
intrinsics = torch.eye(4, device=device, dtype=dtype)
intrinsics[..., 0, 0] = fx
@@ -140,23 +141,19 @@ class TestPinholeCamera:
pinhole_scale = pinhole.scale(scale_factor)
assert_allclose(
- pinhole_scale.intrinsics[..., 0, 0],
- pinhole.intrinsics[..., 0, 0] * scale_val, atol=1e-4, rtol=1e-4) # fx
- assert_allclose(
- pinhole_scale.intrinsics[..., 1, 1],
- pinhole.intrinsics[..., 1, 1] * scale_val, atol=1e-4, rtol=1e-4) # fy
- assert_allclose(
- pinhole_scale.intrinsics[..., 0, 2],
- pinhole.intrinsics[..., 0, 2] * scale_val, atol=1e-4, rtol=1e-4) # cx
+ pinhole_scale.intrinsics[..., 0, 0], pinhole.intrinsics[..., 0, 0] * scale_val, atol=1e-4, rtol=1e-4
+ ) # fx
assert_allclose(
- pinhole_scale.intrinsics[..., 1, 2],
- pinhole.intrinsics[..., 1, 2] * scale_val, atol=1e-4, rtol=1e-4) # cy
+ pinhole_scale.intrinsics[..., 1, 1], pinhole.intrinsics[..., 1, 1] * scale_val, atol=1e-4, rtol=1e-4
+ ) # fy
assert_allclose(
- pinhole_scale.height,
- pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
+ pinhole_scale.intrinsics[..., 0, 2], pinhole.intrinsics[..., 0, 2] * scale_val, atol=1e-4, rtol=1e-4
+ ) # cx
assert_allclose(
- pinhole_scale.width,
- pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
+ pinhole_scale.intrinsics[..., 1, 2], pinhole.intrinsics[..., 1, 2] * scale_val, atol=1e-4, rtol=1e-4
+ ) # cy
+ assert_allclose(pinhole_scale.height, pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
+ assert_allclose(pinhole_scale.width, pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
def test_pinhole_camera_scale_inplace(self, device, dtype):
batch_size = 2
@@ -176,21 +173,19 @@ class TestPinholeCamera:
pinhole_scale.scale_(scale_factor)
assert_allclose(
- pinhole_scale.intrinsics[..., 0, 0],
- pinhole.intrinsics[..., 0, 0] * scale_val, atol=1e-4, rtol=1e-4) # fx
- assert_allclose(
- pinhole_scale.intrinsics[..., 1, 1],
- pinhole.intrinsics[..., 1, 1] * scale_val, atol=1e-4, rtol=1e-4) # fy
- assert_allclose(
- pinhole_scale.intrinsics[..., 0, 2],
- pinhole.intrinsics[..., 0, 2] * scale_val, atol=1e-4, rtol=1e-4) # cx
+ pinhole_scale.intrinsics[..., 0, 0], pinhole.intrinsics[..., 0, 0] * scale_val, atol=1e-4, rtol=1e-4
+ ) # fx
assert_allclose(
- pinhole_scale.intrinsics[..., 1, 2],
- pinhole.intrinsics[..., 1, 2] * scale_val, atol=1e-4, rtol=1e-4) # cy
+ pinhole_scale.intrinsics[..., 1, 1], pinhole.intrinsics[..., 1, 1] * scale_val, atol=1e-4, rtol=1e-4
+ ) # fy
assert_allclose(
- pinhole_scale.height, pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
+ pinhole_scale.intrinsics[..., 0, 2], pinhole.intrinsics[..., 0, 2] * scale_val, atol=1e-4, rtol=1e-4
+ ) # cx
assert_allclose(
- pinhole_scale.width, pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
+ pinhole_scale.intrinsics[..., 1, 2], pinhole.intrinsics[..., 1, 2] * scale_val, atol=1e-4, rtol=1e-4
+ ) # cy
+ assert_allclose(pinhole_scale.height, pinhole.height * scale_val, atol=1e-4, rtol=1e-4)
+ assert_allclose(pinhole_scale.width, pinhole.width * scale_val, atol=1e-4, rtol=1e-4)
'''@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])
diff --git a/test/geometry/transform/crop/test_crop2d.py b/test/geometry/transform/crop/test_crop2d.py
index f70f4b9c1..38afdc7ef 100644
--- a/test/geometry/transform/crop/test_crop2d.py
+++ b/test/geometry/transform/crop/test_crop2d.py
@@ -11,6 +11,7 @@ from torch.autograd import gradcheck
class TestBoundingBoxInferring:
+
def test_bounding_boxes_dim_inferring(self, device, dtype):
boxes = torch.tensor([[
[1., 1.],
@@ -23,17 +24,21 @@ class TestBoundingBoxInferring:
assert (h, w) == (2, 3)
def test_bounding_boxes_dim_inferring_batch(self, device, dtype):
- boxes = torch.tensor([[
- [1., 1.],
- [3., 1.],
- [3., 2.],
- [1., 2.],
- ], [
- [2., 2.],
- [4., 2.],
- [4., 3.],
- [2., 3.],
- ]], device=device, dtype=dtype)
+ boxes = torch.tensor(
+ [[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ], [
+ [2., 2.],
+ [4., 2.],
+ [4., 3.],
+ [2., 3.],
+ ]],
+ device=device,
+ dtype=dtype
+ )
h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
assert (h.unique().item(), w.unique().item()) == (2, 3)
@@ -45,8 +50,7 @@ class TestBoundingBoxInferring:
[1., 2.],
]], device=device, dtype=dtype)
boxes = utils.tensor_to_gradcheck_var(boxes)
- assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape,
- (boxes,), raise_exception=True)
+ assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape, (boxes, ), raise_exception=True)
def test_jit(self, device, dtype):
# Define script
@@ -66,19 +70,22 @@ class TestBoundingBoxInferring:
class TestCropAndResize:
+
def test_align_corners_true(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
height, width = 2, 3
- expected = torch.tensor(
- [[[[6.0000, 6.5000, 7.0000],
- [10.0000, 10.5000, 11.0000]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[6.0000, 6.5000, 7.0000], [10.0000, 10.5000, 11.0000]]]], device=device, dtype=dtype)
boxes = torch.tensor([[
[1., 1.],
@@ -92,17 +99,19 @@ class TestCropAndResize:
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_align_corners_false(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
height, width = 2, 3
- expected = torch.tensor(
- [[[[6.7222, 7.1667, 7.6111],
- [9.3889, 9.8333, 10.2778]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[6.7222, 7.1667, 7.6111], [9.3889, 9.8333, 10.2778]]]], device=device, dtype=dtype)
boxes = torch.tensor([[
[1., 1.],
@@ -115,17 +124,23 @@ class TestCropAndResize:
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_batch(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]], [[
- [1., 5., 9., 13.],
- [2., 6., 10., 14.],
- [3., 7., 11., 15.],
- [4., 8., 12., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]], [[
+ [1., 5., 9., 13.],
+ [2., 6., 10., 14.],
+ [3., 7., 11., 15.],
+ [4., 8., 12., 16.],
+ ]]
+ ],
+ device=device,
+ dtype=dtype
+ )
expected = torch.tensor([[[
[6., 7.],
@@ -135,33 +150,43 @@ class TestCropAndResize:
[8., 16.],
]]], device=device, dtype=dtype)
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ], [
- [1., 2.],
- [3., 2.],
- [3., 3.],
- [1., 3.],
- ]], device=device, dtype=dtype) # 2x4x2
+ boxes = torch.tensor(
+ [[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ], [
+ [1., 2.],
+ [3., 2.],
+ [3., 3.],
+ [1., 3.],
+ ]],
+ device=device,
+ dtype=dtype
+ ) # 2x4x2
patches = kornia.crop_and_resize(inp, boxes, (2, 2))
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_batch_broadcast(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]], [[
- [1., 5., 9., 13.],
- [2., 6., 10., 14.],
- [3., 7., 11., 15.],
- [4., 8., 12., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]], [[
+ [1., 5., 9., 13.],
+ [2., 6., 10., 14.],
+ [3., 7., 11., 15.],
+ [4., 8., 12., 16.],
+ ]]
+ ],
+ device=device,
+ dtype=dtype
+ )
expected = torch.tensor([[[
[6., 7.],
@@ -193,21 +218,27 @@ class TestCropAndResize:
]], device=device, dtype=dtype) # 1x4x2
boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var
- assert gradcheck(kornia.crop_and_resize,
- (img, boxes, (4, 2),),
- raise_exception=True)
+ assert gradcheck(kornia.crop_and_resize, (
+ img,
+ boxes,
+ (4, 2),
+ ), raise_exception=True)
def test_jit(self, device, dtype):
# Define script
op = kornia.crop_and_resize
op_script = torch.jit.script(op)
# Define input
- img = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ img = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
boxes = torch.tensor([[
[1., 1.],
[2., 1.],
@@ -222,13 +253,18 @@ class TestCropAndResize:
class TestCenterCrop:
+
def test_center_crop_h2_w4(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
expected = torch.tensor([[[
[5., 6., 7., 8.],
@@ -239,12 +275,16 @@ class TestCenterCrop:
assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)
def test_center_crop_h4_w2(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
height, width = 4, 2
expected = torch.tensor([[[
@@ -258,28 +298,30 @@ class TestCenterCrop:
assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)
def test_center_crop_h4_w2_batch(self, device, dtype):
- inp = torch.tensor([
- [[[1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.]]],
- [[[1., 5., 9., 13.],
- [2., 6., 10., 14.],
- [3., 7., 11., 15.],
- [4., 8., 12., 16.]]]
- ], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [
+ [[[1., 2., 3., 4.], [5., 6., 7., 8.], [9., 10., 11., 12.], [13., 14., 15., 16.]]],
+ [[[1., 5., 9., 13.], [2., 6., 10., 14.], [3., 7., 11., 15.], [4., 8., 12., 16.]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
- expected = torch.tensor([[[
- [2., 3.],
- [6., 7.],
- [10., 11.],
- [14., 15.],
- ]], [[
- [5., 9.],
- [6., 10.],
- [7., 11.],
- [8., 12.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[
+ [2., 3.],
+ [6., 7.],
+ [10., 11.],
+ [14., 15.],
+ ]], [[
+ [5., 9.],
+ [6., 10.],
+ [7., 11.],
+ [8., 12.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
out_crop = kornia.center_crop(inp, (4, 2))
assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)
@@ -288,7 +330,10 @@ class TestCenterCrop:
img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.center_crop, (img, (4, 2),), raise_exception=True)
+ assert gradcheck(kornia.center_crop, (
+ img,
+ (4, 2),
+ ), raise_exception=True)
def test_jit(self, device, dtype):
# Define script
@@ -316,13 +361,18 @@ class TestCenterCrop:
class TestCropByBoxes:
+
def test_crop_by_boxes_no_resizing(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
src = torch.tensor([[
[1., 1.],
@@ -347,12 +397,16 @@ class TestCropByBoxes:
assert_allclose(patches, expected)
def test_crop_by_boxes_resizing(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
src = torch.tensor([[
[1., 1.],
@@ -378,32 +432,31 @@ class TestCropByBoxes:
def test_gradcheck(self, device, dtype):
inp = torch.randn((1, 1, 3, 3), device=device, dtype=dtype)
- src = torch.tensor([[
- [1., 0.],
- [2., 0.],
- [2., 1.],
- [1., 1.]]], device=device, dtype=dtype)
- dst = torch.tensor([[
- [0., 0.],
- [1., 0.],
- [1., 1.],
- [0., 1.]]], device=device, dtype=dtype)
+ src = torch.tensor([[[1., 0.], [2., 0.], [2., 1.], [1., 1.]]], device=device, dtype=dtype)
+ dst = torch.tensor([[[0., 0.], [1., 0.], [1., 1.], [0., 1.]]], device=device, dtype=dtype)
inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
- assert gradcheck(kornia.geometry.transform.crop.crop_by_boxes,
- (inp, src, dst,),
- raise_exception=True)
+ assert gradcheck(kornia.geometry.transform.crop.crop_by_boxes, (
+ inp,
+ src,
+ dst,
+ ), raise_exception=True)
class TestCropByTransform:
+
def test_crop_by_transform_no_resizing(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
transform = torch.tensor([[
[1., 0., -1.],
@@ -420,12 +473,16 @@ class TestCropByTransform:
assert_allclose(patches, expected)
def test_crop_by_boxes_resizing(self, device, dtype):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
transform = torch.tensor([[
[2., 0., -2.],
@@ -451,6 +508,10 @@ class TestCropByTransform:
inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
- assert gradcheck(kornia.geometry.transform.crop.crop_by_transform_mat,
- (inp, transform, (2, 2),),
- raise_exception=True)
+ assert gradcheck(
+ kornia.geometry.transform.crop.crop_by_transform_mat, (
+ inp,
+ transform,
+ (2, 2),
+ ), raise_exception=True
+ )
diff --git a/test/geometry/transform/crop/test_crop3d.py b/test/geometry/transform/crop/test_crop3d.py
index 9f34469c2..368618495 100644
--- a/test/geometry/transform/crop/test_crop3d.py
+++ b/test/geometry/transform/crop/test_crop3d.py
@@ -11,25 +11,16 @@ from torch.autograd import gradcheck
class TestBoundingBoxInferring3D:
+
def test_bounding_boxes_dim_inferring(self, device, dtype):
- boxes = torch.tensor([
- [[0, 1, 2],
- [10, 1, 2],
- [10, 21, 2],
- [0, 21, 2],
- [0, 1, 32],
- [10, 1, 32],
- [10, 21, 32],
- [0, 21, 32]],
- [[3, 4, 5],
- [43, 4, 5],
- [43, 54, 5],
- [3, 54, 5],
- [3, 4, 65],
- [43, 4, 65],
- [43, 54, 65],
- [3, 54, 65]
- ]], device=device, dtype=dtype) # 2x8x3
+ boxes = torch.tensor(
+ [
+ [[0, 1, 2], [10, 1, 2], [10, 21, 2], [0, 21, 2], [0, 1, 32], [10, 1, 32], [10, 21, 32], [0, 21, 32]],
+ [[3, 4, 5], [43, 4, 5], [43, 54, 5], [3, 54, 5], [3, 4, 65], [43, 4, 65], [43, 54, 65], [3, 54, 65]]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x8x3
d, h, w = kornia.geometry.transform.crop.infer_box_shape3d(boxes)
assert_allclose(d, torch.tensor([31., 61.], device=device, dtype=dtype))
@@ -37,35 +28,33 @@ class TestBoundingBoxInferring3D:
assert_allclose(w, torch.tensor([11., 41.], device=device, dtype=dtype))
def test_gradcheck(self, device, dtype):
- boxes = torch.tensor([[
- [0, 1, 2],
- [10, 1, 2],
- [10, 21, 2],
- [0, 21, 2],
- [0, 1, 32],
- [10, 1, 32],
- [10, 21, 32],
- [0, 21, 32]
- ]], device=device, dtype=dtype)
+ boxes = torch.tensor(
+ [[[0, 1, 2], [10, 1, 2], [10, 21, 2], [0, 21, 2], [0, 1, 32], [10, 1, 32], [10, 21, 32], [0, 21, 32]]],
+ device=device,
+ dtype=dtype
+ )
boxes = utils.tensor_to_gradcheck_var(boxes)
- assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape3d,
- (boxes,), raise_exception=True)
+ assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape3d, (boxes, ), raise_exception=True)
def test_jit(self, device, dtype):
# Define script
op = kornia.infer_box_shape3d
op_script = torch.jit.script(op)
- boxes = torch.tensor([[
- [0, 0, 1],
- [3, 0, 1],
- [3, 2, 1],
- [0, 2, 1],
- [0, 0, 3],
- [3, 0, 3],
- [3, 2, 3],
- [0, 2, 3],
- ]], device=device, dtype=dtype) # 1x8x3
+ boxes = torch.tensor(
+ [[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
actual = op_script(boxes)
expected = op(boxes)
@@ -73,67 +62,79 @@ class TestBoundingBoxInferring3D:
class TestCropAndResize3D:
+
def test_crop(self, device, dtype):
inp = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
depth, height, width = 2, 2, 2
- expected = torch.tensor([[[
- [[25.1667, 27.1667],
- [30.5000, 32.5000]],
- [[46.5000, 48.5000],
- [51.8333, 53.8333]]]]], device=device, dtype=dtype)
-
- boxes = torch.tensor([[
- [0, 0, 1],
- [3, 0, 1],
- [3, 2, 1],
- [0, 2, 1],
- [0, 0, 3],
- [3, 0, 3],
- [3, 2, 3],
- [0, 2, 3],
- ]], device=device, dtype=dtype) # 1x8x3
+ expected = torch.tensor(
+ [[[[[25.1667, 27.1667], [30.5000, 32.5000]], [[46.5000, 48.5000], [51.8333, 53.8333]]]]],
+ device=device,
+ dtype=dtype
+ )
+
+ boxes = torch.tensor(
+ [[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width))
assert_allclose(patches, expected)
def test_crop_batch(self, device, dtype):
- inp = torch.cat([
- torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4),
- torch.arange(0., 128., step=2, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
- ], dim=0)
+ inp = torch.cat(
+ [
+ torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4),
+ torch.arange(0., 128., step=2, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ ],
+ dim=0
+ )
depth, height, width = 2, 2, 2
- expected = torch.tensor([
- [[[[16.0000, 19.0000],
- [24.0000, 27.0000]],
- [[48.0000, 51.0000],
- [56.0000, 59.0000]]]],
- [[[[0.0000, 6.0000],
- [16.0000, 22.0000]],
- [[64.0000, 70.0000],
- [80.0000, 86.0000]]]]
- ], device=device, dtype=dtype)
-
- boxes = torch.tensor([[
- [0, 0, 1],
- [3, 0, 1],
- [3, 2, 1],
- [0, 2, 1],
- [0, 0, 3],
- [3, 0, 3],
- [3, 2, 3],
- [0, 2, 3],
- ], [
- [0, 0, 0],
- [3, 0, 0],
- [3, 2, 0],
- [0, 2, 0],
- [0, 0, 2],
- [3, 0, 2],
- [3, 2, 2],
- [0, 2, 2],
- ]], device=device, dtype=dtype) # 2x8x3
+ expected = torch.tensor(
+ [
+ [[[[16.0000, 19.0000], [24.0000, 27.0000]], [[48.0000, 51.0000], [56.0000, 59.0000]]]],
+ [[[[0.0000, 6.0000], [16.0000, 22.0000]], [[64.0000, 70.0000], [80.0000, 86.0000]]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ boxes = torch.tensor(
+ [
+ [
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ], [
+ [0, 0, 0],
+ [3, 0, 0],
+ [3, 2, 0],
+ [0, 2, 0],
+ [0, 0, 2],
+ [3, 0, 2],
+ [3, 2, 2],
+ [0, 2, 2],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 2x8x3
patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width), align_corners=True)
assert_allclose(patches, expected)
@@ -142,19 +143,27 @@ class TestCropAndResize3D:
img = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
img = utils.tensor_to_gradcheck_var(img) # to var
- boxes = torch.tensor([[
- [0, 0, 1],
- [3, 0, 1],
- [3, 2, 1],
- [0, 2, 1],
- [0, 0, 3],
- [3, 0, 3],
- [3, 2, 3],
- [0, 2, 3],
- ]], device=device, dtype=dtype) # 1x8x3
+ boxes = torch.tensor(
+ [[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var
- assert gradcheck(kornia.crop_and_resize3d, (img, boxes, (4, 3, 2),), raise_exception=True)
+ assert gradcheck(kornia.crop_and_resize3d, (
+ img,
+ boxes,
+ (4, 3, 2),
+ ), raise_exception=True)
def test_jit(self, device, dtype):
# Define script
@@ -163,16 +172,20 @@ class TestCropAndResize3D:
img = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
- boxes = torch.tensor([[
- [0, 0, 1],
- [3, 0, 1],
- [3, 2, 1],
- [0, 2, 1],
- [0, 0, 3],
- [3, 0, 3],
- [3, 2, 3],
- [0, 2, 3],
- ]], device=device, dtype=dtype) # 1x8x3
+ boxes = torch.tensor(
+ [[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
actual = op_script(img, boxes, (4, 3, 2))
expected = op(img, boxes, (4, 3, 2))
@@ -180,30 +193,27 @@ class TestCropAndResize3D:
class TestCenterCrop3D:
+
@pytest.mark.parametrize("crop_size", [(3, 5, 7), (5, 3, 7), (7, 3, 5)])
def test_center_crop_357(self, crop_size, device, dtype):
inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
- expected = inp[
- :, :,
- (inp.size(2) // 2 - crop_size[0] // 2):(inp.size(2) // 2 + crop_size[0] // 2 + 1),
- (inp.size(3) // 2 - crop_size[1] // 2):(inp.size(3) // 2 + crop_size[1] // 2 + 1),
- (inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)
- ]
+ expected = inp[:, :, (inp.size(2) // 2 - crop_size[0] // 2):(inp.size(2) // 2 + crop_size[0] // 2 + 1),
+ (inp.size(3) // 2 - crop_size[1] // 2):(inp.size(3) // 2 + crop_size[1] // 2 + 1),
+ (inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)]
out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)
assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("crop_size", [(3, 5, 7), (5, 3, 7), (7, 3, 5)])
def test_center_crop_357_batch(self, crop_size, device, dtype):
- inp = torch.cat([
- torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7),
- torch.arange(343., 686., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
- ])
- expected = inp[
- :, :,
- (inp.size(2) // 2 - crop_size[0] // 2):(inp.size(2) // 2 + crop_size[0] // 2 + 1),
- (inp.size(3) // 2 - crop_size[1] // 2):(inp.size(3) // 2 + crop_size[1] // 2 + 1),
- (inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)
- ]
+ inp = torch.cat(
+ [
+ torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7),
+ torch.arange(343., 686., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ ]
+ )
+ expected = inp[:, :, (inp.size(2) // 2 - crop_size[0] // 2):(inp.size(2) // 2 + crop_size[0] // 2 + 1),
+ (inp.size(3) // 2 - crop_size[1] // 2):(inp.size(3) // 2 + crop_size[1] // 2 + 1),
+ (inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)]
out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)
assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)
@@ -211,7 +221,10 @@ class TestCenterCrop3D:
img = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.center_crop3d, (img, (3, 5, 7),), raise_exception=True)
+ assert gradcheck(kornia.center_crop3d, (
+ img,
+ (3, 5, 7),
+ ), raise_exception=True)
def test_jit(self, device, dtype):
# Define script
@@ -225,28 +238,41 @@ class TestCenterCrop3D:
class TestCropByBoxes3D:
+
def test_crop_by_boxes_no_resizing(self, device, dtype):
inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
- src_box = torch.tensor([[
- [1., 1., 1.],
- [3., 1., 1.],
- [3., 3., 1.],
- [1., 3., 1.],
- [1., 1., 2.],
- [3., 1., 2.],
- [3., 3., 2.],
- [1., 3., 2.],
- ]], device=device, dtype=dtype) # 1x8x3
- dst_box = torch.tensor([[
- [0., 0., 0.],
- [2., 0., 0.],
- [2., 2., 0.],
- [0., 2., 0.],
- [0., 0., 1.],
- [2., 0., 1.],
- [2., 2., 1.],
- [0., 2., 1.],
- ]], device=device, dtype=dtype) # 1x8x3
+ src_box = torch.tensor(
+ [
+ [
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
+ dst_box = torch.tensor(
+ [
+ [
+ [0., 0., 0.],
+ [2., 0., 0.],
+ [2., 2., 0.],
+ [0., 2., 0.],
+ [0., 0., 1.],
+ [2., 0., 1.],
+ [2., 2., 1.],
+ [0., 2., 1.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
expected = inp[:, :, 1:3, 1:4, 1:4]
@@ -255,33 +281,44 @@ class TestCropByBoxes3D:
def test_crop_by_boxes_resizing(self, device, dtype):
inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
- src_box = torch.tensor([[
- [1., 1., 1.],
- [3., 1., 1.],
- [3., 3., 1.],
- [1., 3., 1.],
- [1., 1., 2.],
- [3., 1., 2.],
- [3., 3., 2.],
- [1., 3., 2.],
- ]], device=device, dtype=dtype) # 1x8x3
- dst_box = torch.tensor([[
- [0., 0., 0.],
- [1., 0., 0.],
- [1., 1., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- [1., 0., 1.],
- [1., 1., 1.],
- [0., 1., 1.],
- ]], device=device, dtype=dtype) # 1x8x3
-
- expected = torch.tensor([[[
- [[57.0000, 59.0000],
- [71.0000, 73.0000]],
- [[106.0000, 108.0000],
- [120.0000, 122.0000]]
- ]]], device=device, dtype=dtype)
+ src_box = torch.tensor(
+ [
+ [
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
+ dst_box = torch.tensor(
+ [
+ [
+ [0., 0., 0.],
+ [1., 0., 0.],
+ [1., 1., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ [1., 0., 1.],
+ [1., 1., 1.],
+ [0., 1., 1.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
+
+ expected = torch.tensor(
+ [[[[[57.0000, 59.0000], [71.0000, 73.0000]], [[106.0000, 108.0000], [120.0000, 122.0000]]]]],
+ device=device,
+ dtype=dtype
+ )
patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
@@ -292,26 +329,38 @@ class TestCropByBoxes3D:
op_script = torch.jit.script(op)
# Define input
inp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)
- src_box = torch.tensor([[
- [1., 1., 1.],
- [3., 1., 1.],
- [3., 3., 1.],
- [1., 3., 1.],
- [1., 1., 2.],
- [3., 1., 2.],
- [3., 3., 2.],
- [1., 3., 2.],
- ]], device=device, dtype=dtype) # 1x8x3
- dst_box = torch.tensor([[
- [0., 0., 0.],
- [1., 0., 0.],
- [1., 1., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- [1., 0., 1.],
- [1., 1., 1.],
- [0., 1., 1.],
- ]], device=device, dtype=dtype) # 1x8x3
+ src_box = torch.tensor(
+ [
+ [
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
+ dst_box = torch.tensor(
+ [
+ [
+ [0., 0., 0.],
+ [1., 0., 0.],
+ [1., 1., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ [1., 0., 1.],
+ [1., 1., 1.],
+ [0., 1., 1.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
actual = op_script(inp, src_box, dst_box, align_corners=True)
expected = op(inp, src_box, dst_box, align_corners=True)
@@ -319,28 +368,45 @@ class TestCropByBoxes3D:
def test_gradcheck(self, device, dtype):
inp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)
- src_box = torch.tensor([[
- [1., 1., 1.],
- [3., 1., 1.],
- [3., 3., 1.],
- [1., 3., 1.],
- [1., 1., 2.],
- [3., 1., 2.],
- [3., 3., 2.],
- [1., 3., 2.],
- ]], device=device, dtype=dtype) # 1x8x3
- dst_box = torch.tensor([[
- [0., 0., 0.],
- [1., 0., 0.],
- [1., 1., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- [1., 0., 1.],
- [1., 1., 1.],
- [0., 1., 1.],
- ]], device=device, dtype=dtype) # 1x8x3
+ src_box = torch.tensor(
+ [
+ [
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
+ dst_box = torch.tensor(
+ [
+ [
+ [0., 0., 0.],
+ [1., 0., 0.],
+ [1., 1., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ [1., 0., 1.],
+ [1., 1., 1.],
+ [0., 1., 1.],
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ ) # 1x8x3
inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
- assert gradcheck(kornia.geometry.transform.crop.crop_by_boxes3d,
- (inp, src_box, dst_box,), raise_exception=True)
+ assert gradcheck(
+ kornia.geometry.transform.crop.crop_by_boxes3d, (
+ inp,
+ src_box,
+ dst_box,
+ ), raise_exception=True
+ )
diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.py
index 95ceac49a..50e92c783 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -8,6 +8,7 @@ from torch.testing import assert_allclose
class TestResize:
+
def test_smoke(self, device, dtype):
inp = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
out = kornia.resize(inp, (3, 4))
@@ -62,6 +63,7 @@ class TestResize:
class TestRescale:
+
def test_smoke(self, device, dtype):
input = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
output = kornia.rescale(input, (1.0, 1.0))
@@ -82,12 +84,19 @@ class TestRescale:
inp = inp_x[None].T @ inp_x[None]
inp = inp[None, None]
out = kornia.rescale(inp, (0.25, 0.25), antialias=False)
- expected = torch.tensor([[[[0.0056, 0.0206, 0.0356, 0.0506, 0.0656],
- [0.0206, 0.0756, 0.1306, 0.1856, 0.2406],
- [0.0356, 0.1306, 0.2256, 0.3206, 0.4156],
- [0.0506, 0.1856, 0.3206, 0.4556, 0.5906],
- [0.0656, 0.2406, 0.4156, 0.5906, 0.7656]]]],
- device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.0056, 0.0206, 0.0356, 0.0506, 0.0656], [0.0206, 0.0756, 0.1306, 0.1856, 0.2406],
+ [0.0356, 0.1306, 0.2256, 0.3206, 0.4156], [0.0506, 0.1856, 0.3206, 0.4556, 0.5906],
+ [0.0656, 0.2406, 0.4156, 0.5906, 0.7656]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
def test_downscale_values_AA(self, device, dtype):
@@ -95,12 +104,19 @@ class TestRescale:
inp = inp_x[None].T @ inp_x[None]
inp = inp[None, None]
out = kornia.rescale(inp, (0.25, 0.25), antialias=True)
- expected = torch.tensor([[[[0.0255, 0.0453, 0.0759, 0.1065, 0.1263],
- [0.0453, 0.0804, 0.1347, 0.1890, 0.2240],
- [0.0759, 0.1347, 0.2256, 0.3166, 0.3753],
- [0.1065, 0.1890, 0.3166, 0.4442, 0.5266],
- [0.1263, 0.2240, 0.3753, 0.5266, 0.6244]]]],
- device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.0255, 0.0453, 0.0759, 0.1065, 0.1263], [0.0453, 0.0804, 0.1347, 0.1890, 0.2240],
+ [0.0759, 0.1347, 0.2256, 0.3166, 0.3753], [0.1065, 0.1890, 0.3166, 0.4442, 0.5266],
+ [0.1263, 0.2240, 0.3753, 0.5266, 0.6244]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
def test_one_param(self, device, dtype):
@@ -115,6 +131,7 @@ class TestRescale:
class TestRotate:
+
def test_angle90(self, device, dtype):
# prepare input data
inp = torch.tensor([[
@@ -142,17 +159,21 @@ class TestRotate:
[5., 6.],
[7., 8.],
]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [0., 0.],
- [4., 6.],
- [3., 5.],
- [0., 0.],
- ]], [[
- [0., 0.],
- [5., 3.],
- [6., 4.],
- [0., 0.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[
+ [0., 0.],
+ [4., 6.],
+ [3., 5.],
+ [0., 0.],
+ ]], [[
+ [0., 0.],
+ [5., 3.],
+ [6., 4.],
+ [0., 0.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
# prepare transformation
angle = torch.tensor([90., -90.], device=device, dtype=dtype)
transform = kornia.Rotate(angle, align_corners=True)
@@ -166,17 +187,21 @@ class TestRotate:
[5., 6.],
[7., 8.],
]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [0., 0.],
- [4., 6.],
- [3., 5.],
- [0., 0.],
- ]], [[
- [0., 0.],
- [4., 6.],
- [3., 5.],
- [0., 0.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[
+ [0., 0.],
+ [4., 6.],
+ [3., 5.],
+ [0., 0.],
+ ]], [[
+ [0., 0.],
+ [4., 6.],
+ [3., 5.],
+ [0., 0.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
# prepare transformation
angle = torch.tensor([90.], device=device, dtype=dtype)
transform = kornia.Rotate(angle, align_corners=True)
@@ -185,13 +210,15 @@ class TestRotate:
def test_gradcheck(self, device, dtype):
# test parameters
angle = torch.tensor([90.], device=device, dtype=dtype)
- angle = utils.tensor_to_gradcheck_var(
- angle, requires_grad=False) # to var
+ angle = utils.tensor_to_gradcheck_var(angle, requires_grad=False) # to var
# evaluate function gradient
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.rotate, (input, angle,), raise_exception=True)
+ assert gradcheck(kornia.rotate, (
+ input,
+ angle,
+ ), raise_exception=True)
@pytest.mark.skip('Need deep look into it since crashes everywhere.')
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -205,6 +232,7 @@ class TestRotate:
class TestTranslate:
+
def test_dxdy(self, device, dtype):
# prepare input data
inp = torch.tensor([[
@@ -232,17 +260,21 @@ class TestTranslate:
[5., 6.],
[7., 8.],
]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [0., 1.],
- [0., 3.],
- [0., 5.],
- [0., 7.],
- ]], [[
- [0., 0.],
- [0., 1.],
- [0., 3.],
- [0., 5.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[
+ [0., 1.],
+ [0., 3.],
+ [0., 5.],
+ [0., 7.],
+ ]], [[
+ [0., 0.],
+ [0., 1.],
+ [0., 3.],
+ [0., 5.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
# prepare transformation
translation = torch.tensor([[1., 0.], [1., 1.]], device=device, dtype=dtype)
transform = kornia.Translate(translation, align_corners=True)
@@ -256,17 +288,21 @@ class TestTranslate:
[5., 6.],
[7., 8.],
]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [0., 1.],
- [0., 3.],
- [0., 5.],
- [0., 7.],
- ]], [[
- [0., 1.],
- [0., 3.],
- [0., 5.],
- [0., 7.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[
+ [0., 1.],
+ [0., 3.],
+ [0., 5.],
+ [0., 7.],
+ ]], [[
+ [0., 1.],
+ [0., 3.],
+ [0., 5.],
+ [0., 7.],
+ ]]],
+ device=device,
+ dtype=dtype
+ )
# prepare transformation
translation = torch.tensor([[1., 0.]], device=device, dtype=dtype)
transform = kornia.Translate(translation, align_corners=True)
@@ -275,14 +311,15 @@ class TestTranslate:
def test_gradcheck(self, device, dtype):
# test parameters
translation = torch.tensor([[1., 0.]], device=device, dtype=dtype)
- translation = utils.tensor_to_gradcheck_var(
- translation, requires_grad=False) # to var
+ translation = utils.tensor_to_gradcheck_var(translation, requires_grad=False) # to var
# evaluate function gradient
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.translate, (input, translation,),
- raise_exception=True)
+ assert gradcheck(kornia.translate, (
+ input,
+ translation,
+ ), raise_exception=True)
@pytest.mark.skip('Need deep look into it since crashes everywhere.')
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -296,14 +333,12 @@ class TestTranslate:
class TestScale:
+
def test_scale_factor_2(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [0., 0., 0., 0.],
- [0., 1., 1., 0.],
- [0., 1., 1., 0.],
- [0., 0., 0., 0.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[0., 0., 0., 0.], [0., 1., 1., 0.], [0., 1., 1., 0.], [0., 0., 0., 0.]]], device=device, dtype=dtype
+ )
# prepare transformation
scale_factor = torch.tensor([[2., 2.]], device=device, dtype=dtype)
transform = kornia.Scale(scale_factor)
@@ -311,18 +346,12 @@ class TestScale:
def test_scale_factor_05(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]], device=device, dtype=dtype)
- expected = torch.tensor([[
- [0., 0., 0., 0.],
- [0., 1., 1., 0.],
- [0., 1., 1., 0.],
- [0., 0., 0., 0.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]], device=device, dtype=dtype
+ )
+ expected = torch.tensor(
+ [[[0., 0., 0., 0.], [0., 1., 1., 0.], [0., 1., 1., 0.], [0., 0., 0., 0.]]], device=device, dtype=dtype
+ )
# prepare transformation
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
transform = kornia.Scale(scale_factor)
@@ -330,18 +359,12 @@ class TestScale:
def test_scale_factor_05_batch2(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[
- [0., 0., 0., 0.],
- [0., 1., 1., 0.],
- [0., 1., 1., 0.],
- [0., 0., 0., 0.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor(
+ [[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
+ expected = torch.tensor(
+ [[[0., 0., 0., 0.], [0., 1., 1., 0.], [0., 1., 1., 0.], [0., 0., 0., 0.]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
# prepare transformation
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
transform = kornia.Scale(scale_factor)
@@ -349,18 +372,12 @@ class TestScale:
def test_scale_factor_05_batch2_broadcast(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[
- [0., 0., 0., 0.],
- [0., 1., 1., 0.],
- [0., 1., 1., 0.],
- [0., 0., 0., 0.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor(
+ [[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
+ expected = torch.tensor(
+ [[[0., 0., 0., 0.], [0., 1., 1., 0.], [0., 1., 1., 0.], [0., 0., 0., 0.]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
# prepare transformation
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
transform = kornia.Scale(scale_factor)
@@ -369,14 +386,15 @@ class TestScale:
def test_gradcheck(self, device, dtype):
# test parameters
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
- scale_factor = utils.tensor_to_gradcheck_var(
- scale_factor, requires_grad=False) # to var
+ scale_factor = utils.tensor_to_gradcheck_var(scale_factor, requires_grad=False) # to var
# evaluate function gradient
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.scale, (input, scale_factor,),
- raise_exception=True)
+ assert gradcheck(kornia.scale, (
+ input,
+ scale_factor,
+ ), raise_exception=True)
@pytest.mark.skip('Need deep look into it since crashes everywhere.')
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -390,19 +408,17 @@ class TestScale:
class TestShear:
+
def test_shear_x(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]], device=device, dtype=dtype
+ )
expected = torch.tensor(
- [[[0.75, 1., 1., 1.],
- [0.25, 1., 1., 1.],
- [0., 0.75, 1., 1.],
- [0., 0.25, 1., 1.]]], device=device, dtype=dtype)
+ [[[0.75, 1., 1., 1.], [0.25, 1., 1., 1.], [0., 0.75, 1., 1.], [0., 0.25, 1., 1.]]],
+ device=device,
+ dtype=dtype
+ )
# prepare transformation
shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
@@ -411,17 +427,14 @@ class TestShear:
def test_shear_y(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]], device=device, dtype=dtype
+ )
expected = torch.tensor(
- [[[0.75, 0.25, 0., 0.],
- [1., 1., 0.75, 0.25],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]]], device=device, dtype=dtype)
+ [[[0.75, 0.25, 0., 0.], [1., 1., 0.75, 0.25], [1., 1., 1., 1.], [1., 1., 1., 1.]]],
+ device=device,
+ dtype=dtype
+ )
# prepare transformation
shear = torch.tensor([[0.0, 0.5]], device=device, dtype=dtype)
@@ -430,22 +443,18 @@ class TestShear:
def test_shear_batch2(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor(
+ [[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
expected = torch.tensor(
- [[[[0.75, 1., 1., 1.],
- [0.25, 1., 1., 1.],
- [0., 0.75, 1., 1.],
- [0., 0.25, 1., 1.]]],
- [[[0.75, 0.25, 0., 0.],
- [1., 1., 0.75, 0.25],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]]]], device=device, dtype=dtype)
+ [
+ [[[0.75, 1., 1., 1.], [0.25, 1., 1., 1.], [0., 0.75, 1., 1.], [0., 0.25, 1., 1.]]],
+ [[[0.75, 0.25, 0., 0.], [1., 1., 0.75, 0.25], [1., 1., 1., 1.], [1., 1., 1., 1.]]]
+ ],
+ device=device,
+ dtype=dtype
+ )
# prepare transformation
shear = torch.tensor([[0.5, 0.0], [0.0, 0.5]], device=device, dtype=dtype)
@@ -454,18 +463,15 @@ class TestShear:
def test_shear_batch2_broadcast(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.]
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor(
+ [[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [0.75, 1., 1., 1.],
- [0.25, 1., 1., 1.],
- [0., 0.75, 1., 1.],
- [0., 0.25, 1., 1.]]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ expected = torch.tensor(
+ [[[[0.75, 1., 1., 1.], [0.25, 1., 1., 1.], [0., 0.75, 1., 1.], [0., 0.25, 1., 1.]]]],
+ device=device,
+ dtype=dtype
+ ).repeat(2, 1, 1, 1)
# prepare transformation
shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
@@ -475,13 +481,15 @@ class TestShear:
def test_gradcheck(self, device, dtype):
# test parameters
shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
- shear = utils.tensor_to_gradcheck_var(
- shear, requires_grad=False) # to var
+ shear = utils.tensor_to_gradcheck_var(shear, requires_grad=False) # to var
# evaluate function gradient
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.shear, (input, shear,), raise_exception=True)
+ assert gradcheck(kornia.shear, (
+ input,
+ shear,
+ ), raise_exception=True)
@pytest.mark.skip('Need deep look into it since crashes everywhere.')
@pytest.mark.skip(reason="turn off all jit for a while")
@@ -495,6 +503,7 @@ class TestShear:
class TestAffine2d:
+
def test_affine_no_args(self):
with pytest.raises(RuntimeError):
kornia.Affine()
@@ -508,10 +517,7 @@ class TestAffine2d:
def test_affine_rotate(self, device, dtype):
# TODO: Remove when #666 is implemented
if device.type == 'cuda':
- pytest.skip(
- "Currently breaks in CUDA."
- "See https://github.com/kornia/kornia/issues/666"
- )
+ pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
torch.manual_seed(0)
angle = torch.rand(1, device=device, dtype=dtype) * 90.0
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -524,10 +530,7 @@ class TestAffine2d:
def test_affine_translate(self, device, dtype):
# TODO: Remove when #666 is implemented
if device.type == 'cuda':
- pytest.skip(
- "Currently breaks in CUDA."
- "See https://github.com/kornia/kornia/issues/666"
- )
+ pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
torch.manual_seed(0)
translation = torch.rand(1, 2, device=device, dtype=dtype) * 2.0
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -540,10 +543,7 @@ class TestAffine2d:
def test_affine_scale(self, device, dtype):
# TODO: Remove when #666 is implemented
if device.type == 'cuda':
- pytest.skip(
- "Currently breaks in CUDA."
- "See https://github.com/kornia/kornia/issues/666"
- )
+ pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
torch.manual_seed(0)
_scale_factor = torch.rand(1, device=device, dtype=dtype) * 2.0
scale_factor = torch.stack([_scale_factor, _scale_factor], dim=1)
@@ -571,15 +571,13 @@ class TestAffine2d:
def test_affine_rotate_translate(self, device, dtype):
# TODO: Remove when #666 is implemented
if device.type == 'cuda':
- pytest.skip(
- "Currently breaks in CUDA."
- "See https://github.com/kornia/kornia/issues/666"
- )
+ pytest.skip("Currently breaks in CUDA." "See https://github.com/kornia/kornia/issues/666")
batch_size = 2
input = torch.tensor(
[[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]],
- device=device, dtype=dtype
+ device=device,
+ dtype=dtype
).repeat(batch_size, 1, 1, 1)
angle = torch.tensor(180.0, device=device, dtype=dtype).repeat(batch_size)
@@ -587,11 +585,12 @@ class TestAffine2d:
expected = torch.tensor(
[[[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0]]],
- device=device, dtype=dtype
+ device=device,
+ dtype=dtype
).repeat(batch_size, 1, 1, 1)
- transform = kornia.Affine(
- angle=angle, translation=translation, align_corners=True).to(device=device, dtype=dtype)
+ transform = kornia.Affine(angle=angle, translation=translation,
+ align_corners=True).to(device=device, dtype=dtype)
actual = transform(input)
assert_allclose(actual, expected, atol=1e-4, rtol=1e-4)
@@ -629,16 +628,15 @@ class TestAffine2d:
batch_size, ch, height, width = 1, 1, 96, 96
angle, translations = 6.971339922894188, (0.0, -4.0)
scale, shear = [0.7785685905190581, 0.7785685905190581], [11.8235607082617, 7.06797949691645]
- matrix_expected = T([[1.27536969, 4.26828945e-01, -3.2876e+01],
- [2.18297196e-03, 1.29424165e+00, -1.1717e+01]])
+ matrix_expected = T([[1.27536969, 4.26828945e-01, -3.2876e+01], [2.18297196e-03, 1.29424165e+00, -1.1717e+01]])
center = T([float(width), float(height)]).view(1, 2) / 2. + 0.5
center = center.expand(batch_size, -1)
matrix_kornia = kornia.get_affine_matrix2d(
- T(translations).view(-1, 2),
- center,
+ T(translations).view(-1, 2), center,
T([scale]).view(-1, 2),
T([angle]).view(-1),
T([math.radians(shear[0])]).view(-1, 1),
- T([math.radians(shear[1])]).view(-1, 1))
+ T([math.radians(shear[1])]).view(-1, 1)
+ )
matrix_kornia = matrix_kornia.inverse()[0, :2].detach().cpu()
assert_allclose(matrix_kornia, matrix_expected, atol=1e-4, rtol=1e-4)
diff --git a/test/geometry/transform/test_elastic_transform.py b/test/geometry/transform/test_elastic_transform.py
index 1098c4dd7..2ddf06786 100644
--- a/test/geometry/transform/test_elastic_transform.py
+++ b/test/geometry/transform/test_elastic_transform.py
@@ -15,8 +15,7 @@ class TestElasticTransform:
noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)
assert elastic_transform2d(image, noise) is not None
- @pytest.mark.parametrize(
- "batch, channels, height, width", [(1, 3, 3, 4), (2, 2, 2, 4), (1, 5, 4, 1)])
+ @pytest.mark.parametrize("batch, channels, height, width", [(1, 3, 3, 4), (2, 2, 2, 4), (1, 5, 4, 1)])
def test_cardinality(self, device, dtype, batch, channels, height, width):
shape = batch, channels, height, width
img = torch.ones(shape, device=device, dtype=dtype)
@@ -40,11 +39,13 @@ class TestElasticTransform:
noise = torch.ones(1, 3, 1, 1, device=device, dtype=dtype)
assert elastic_transform2d(img, noise)
- @pytest.mark.parametrize("kernel_size, sigma, alpha", [
- [(3, 3), (4., 4.), (32., 32.)],
- [(5, 3), (4., 8.), (16., 32.)],
- [(5, 5), torch.tensor([2., 8.]), torch.tensor([16., 64.])],
- ])
+ @pytest.mark.parametrize(
+ "kernel_size, sigma, alpha", [
+ [(3, 3), (4., 4.), (32., 32.)],
+ [(5, 3), (4., 8.), (16., 32.)],
+ [(5, 5), torch.tensor([2., 8.]), torch.tensor([16., 64.])],
+ ]
+ )
def test_valid_paramters(self, device, dtype, kernel_size, sigma, alpha):
image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)
noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)
@@ -55,19 +56,19 @@ class TestElasticTransform:
assert elastic_transform2d(image, noise, kernel_size, sigma, alpha) is not None
def test_values(self, device, dtype):
- image = torch.tensor([[
- [[0.0018, 0.7521, 0.7550],
- [0.2053, 0.4249, 0.1369],
- [0.1027, 0.3992, 0.8773]]
- ]], device=device, dtype=dtype)
+ image = torch.tensor(
+ [[[[0.0018, 0.7521, 0.7550], [0.2053, 0.4249, 0.1369], [0.1027, 0.3992, 0.8773]]]],
+ device=device,
+ dtype=dtype
+ )
noise = torch.ones(1, 2, 3, 3, device=device, dtype=dtype)
- expected = torch.tensor([[
- [[0.0005, 0.3795, 0.1905],
- [0.1034, 0.4235, 0.0702],
- [0.0259, 0.2007, 0.2193]]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[[0.0005, 0.3795, 0.1905], [0.1034, 0.4235, 0.0702], [0.0259, 0.2007, 0.2193]]]],
+ device=device,
+ dtype=dtype
+ )
actual = elastic_transform2d(image, noise)
assert_allclose(actual, expected, atol=1e-3, rtol=1e-3)
@@ -76,7 +77,10 @@ class TestElasticTransform:
def test_gradcheck(self, device, dtype, requires_grad):
image = torch.rand(1, 1, 3, 3, device=device, dtype=torch.float64, requires_grad=requires_grad)
noise = torch.rand(1, 2, 3, 3, device=device, dtype=torch.float64, requires_grad=not requires_grad)
- assert gradcheck(elastic_transform2d, (image, noise,), raise_exception=True)
+ assert gradcheck(elastic_transform2d, (
+ image,
+ noise,
+ ), raise_exception=True)
def test_jit(self, device, dtype):
image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)
diff --git a/test/geometry/transform/test_flip.py b/test/geometry/transform/test_flip.py
index 032417774..d69197a38 100644
--- a/test/geometry/transform/test_flip.py
+++ b/test/geometry/transform/test_flip.py
@@ -9,6 +9,7 @@ from torch.autograd import gradcheck
class TestVflip:
+
def smoke_test(self, device, dtype):
f = kornia.Vflip()
repr = "Vflip()"
@@ -17,28 +18,20 @@ class TestVflip:
def test_vflip(self, device, dtype):
f = kornia.Vflip()
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
- expected = torch.tensor([[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
assert (f(input) == expected).all()
def test_batch_vflip(self, device, dtype):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
f = kornia.Vflip()
- expected = torch.tensor([[[0., 1., 1.],
- [0., 0., 0.],
- [0., 0., 0.]]], device=device, dtype=dtype) # 1 x 3 x 3
+ expected = torch.tensor([[[0., 1., 1.], [0., 0., 0.], [0., 0., 0.]]], device=device, dtype=dtype) # 1 x 3 x 3
expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
@@ -46,28 +39,23 @@ class TestVflip:
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(data: torch.Tensor) -> torch.Tensor:
return kornia.vflip(data)
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [5., 5., 0.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [5., 5., 0.]], device=device, dtype=dtype) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[5., 5., 0.],
- [0., 0., 0.],
- [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[[5., 5., 0.], [0., 0., 0.], [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -77,13 +65,11 @@ class TestVflip:
def test_gradcheck(self, device, dtype):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.Vflip(), (input,), raise_exception=True)
+ assert gradcheck(kornia.Vflip(), (input, ), raise_exception=True)
class TestHflip:
@@ -96,28 +82,20 @@ class TestHflip:
def test_hflip(self, device, dtype):
f = kornia.Hflip()
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
- expected = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [1., 1., 0.]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]], device=device, dtype=dtype) # 3 x 3
assert (f(input) == expected).all()
def test_batch_hflip(self, device, dtype):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 1 x 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 1 x 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
f = kornia.Hflip()
- expected = torch.tensor([[[0., 0., 0.],
- [0., 0., 0.],
- [1., 1., 0.]]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[[0., 0., 0.], [0., 0., 0.], [1., 1., 0.]]], device=device, dtype=dtype) # 3 x 3
expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
@@ -125,28 +103,23 @@ class TestHflip:
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(data: torch.Tensor) -> torch.Tensor:
return kornia.hflip(data)
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[0., 0., 0.],
- [5., 5., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [5., 5., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[0., 0., 0.],
- [0., 5., 5.],
- [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[[0., 0., 0.], [0., 5., 5.], [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -156,13 +129,11 @@ class TestHflip:
def test_gradcheck(self, device, dtype):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.Hflip(), (input,), raise_exception=True)
+ assert gradcheck(kornia.Hflip(), (input, ), raise_exception=True)
class TestRot180:
@@ -175,28 +146,20 @@ class TestRot180:
def test_rot180(self, device, dtype):
f = kornia.Rot180()
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
- expected = torch.tensor([[1., 1., 0.],
- [0., 0., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[1., 1., 0.], [0., 0., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 3 x 3
assert (f(input) == expected).all()
def test_batch_rot180(self, device, dtype):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
f = kornia.Rot180()
- expected = torch.tensor([[1., 1., 0.],
- [0., 0., 0.],
- [0., 0., 0.]], device=device, dtype=dtype) # 1 x 3 x 3
+ expected = torch.tensor([[1., 1., 0.], [0., 0., 0.], [0., 0., 0.]], device=device, dtype=dtype) # 1 x 3 x 3
expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
@@ -204,28 +167,23 @@ class TestRot180:
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(data: torch.Tensor) -> torch.Tensor:
return kornia.rot180(data)
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
op_trace = torch.jit.trace(op_script, (input, ))
# Create new inputs
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [5., 5., 0.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [5., 5., 0.]], device=device, dtype=dtype) # 3 x 3
input = input.repeat(2, 1, 1) # 2 x 3 x 3
- expected = torch.tensor([[[0., 5., 5.],
- [0., 0., 0.],
- [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor([[[0., 5., 5.], [0., 0., 0.], [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -235,10 +193,8 @@ class TestRot180:
def test_gradcheck(self, device, dtype):
- input = torch.tensor([[0., 0., 0.],
- [0., 0., 0.],
- [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
+ input = torch.tensor([[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.Rot180(), (input,), raise_exception=True)
+ assert gradcheck(kornia.Rot180(), (input, ), raise_exception=True)
diff --git a/test/geometry/transform/test_homography_warper.py b/test/geometry/transform/test_homography_warper.py
index fce7f2011..bb568ec03 100644
--- a/test/geometry/transform/test_homography_warper.py
+++ b/test/geometry/transform/test_homography_warper.py
@@ -32,26 +32,19 @@ class TestHomographyWarper:
height, width = 2, 5
dst_homo_src = utils.create_eye_batch(batch_size=batch_size, eye_size=3, device=device, dtype=dtype)
- res = torch.tensor([[[0.5, 0.0, -1.0],
- [0.0, 2.0, -1.0],
- [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ res = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
assert (kornia.normal_transform_pixel(height, width, device=device, dtype=dtype) == res).all()
norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))
assert (norm_homo == dst_homo_src).all()
- norm_homo = kornia.normalize_homography(dst_homo_src,
- (height, width),
- (height, width))
+ norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))
assert (norm_homo == dst_homo_src).all()
# change output scale
- norm_homo = kornia.normalize_homography(dst_homo_src,
- (height, width),
- (height * 2, width // 2))
- res = torch.tensor([[[4.0, 0.0, 3.0],
- [0.0, 1 / 3, -2 / 3],
- [0.0, 0.0, 1.0]]], device=device, dtype=dtype).repeat(batch_size, 1, 1)
+ norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height * 2, width // 2))
+ res = torch.tensor([[[4.0, 0.0, 3.0], [0.0, 1 / 3, -2 / 3], [0.0, 0.0, 1.0]]], device=device,
+ dtype=dtype).repeat(batch_size, 1, 1)
assert_allclose(norm_homo, res, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 3])
@@ -66,14 +59,16 @@ class TestHomographyWarper:
dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)
norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))
- res = torch.tensor([[[0.5, 0.0, 0.0],
- [0.0, 2.0, 5.0],
- [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ res = torch.tensor([[[0.5, 0.0, 0.0], [0.0, 2.0, 5.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
assert (norm_homo == res).all()
@pytest.mark.parametrize("offset", [1, 3, 7])
@pytest.mark.parametrize("shape", [
- (4, 5), (2, 6), (4, 3), (5, 7), ])
+ (4, 5),
+ (2, 6),
+ (4, 3),
+ (5, 7),
+ ])
def test_warp_grid_translation(self, shape, offset, device, dtype):
# create input data
height, width = shape
@@ -84,13 +79,14 @@ class TestHomographyWarper:
# the grid the src plus the offset should be equal to the flow
# on the x-axis, y-axis remains the same.
- assert_allclose(
- grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0])
- assert_allclose(
- grid[..., 1].to(device=device, dtype=dtype), flow[..., 1])
+ assert_allclose(grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0])
+ assert_allclose(grid[..., 1].to(device=device, dtype=dtype), flow[..., 1])
@pytest.mark.parametrize("batch_shape", [
- (1, 1, 4, 5), (2, 2, 4, 6), (3, 1, 5, 7), ])
+ (1, 1, 4, 5),
+ (2, 2, 4, 6),
+ (3, 1, 5, 7),
+ ])
def test_identity_resize(self, batch_shape, device, dtype):
# create input data
batch_size, channels, height, width = batch_shape
@@ -102,17 +98,17 @@ class TestHomographyWarper:
patch_dst = warper(patch_src, dst_homo_src)
# check the corners
- assert_allclose(
- patch_src[..., 0, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
- assert_allclose(
- patch_src[..., 0, -1], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
- assert_allclose(
- patch_src[..., -1, 0], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
- assert_allclose(
- patch_src[..., -1, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., 0, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., 0, -1], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., -1, 0], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., -1, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("shape", [
- (4, 5), (2, 6), (4, 3), (5, 7), ])
+ (4, 5),
+ (2, 6),
+ (4, 3),
+ (5, 7),
+ ])
def test_translation(self, shape, device, dtype):
# create input data
offset = 2. # in pixel
@@ -127,7 +123,10 @@ class TestHomographyWarper:
assert_allclose(patch_src[..., 1:], patch_dst[..., :-1], atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_shape", [
- (1, 1, 3, 5), (2, 2, 4, 3), (3, 1, 2, 3), ])
+ (1, 1, 3, 5),
+ (2, 2, 4, 3),
+ (3, 1, 2, 3),
+ ])
def test_rotation(self, batch_shape, device, dtype):
# create input data
batch_size, channels, height, width = batch_shape
@@ -145,14 +144,10 @@ class TestHomographyWarper:
patch_dst = warper(patch_src, dst_homo_src)
# check the corners
- assert_allclose(
- patch_src[..., 0, 0], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
- assert_allclose(
- patch_src[..., 0, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
- assert_allclose(
- patch_src[..., -1, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
- assert_allclose(
- patch_src[..., -1, -1], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., 0, 0], patch_dst[..., 0, -1], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., 0, -1], patch_dst[..., -1, -1], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., -1, 0], patch_dst[..., 0, 0], atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_src[..., -1, -1], patch_dst[..., -1, 0], atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 2, 3])
def test_homography_warper(self, batch_size, device, dtype):
@@ -162,8 +157,9 @@ class TestHomographyWarper:
# create checkerboard
board = utils.create_checkerboard(height, width, 4)
- patch_src = torch.from_numpy(board).to(device=device, dtype=dtype).view(
- 1, 1, height, width).expand(batch_size, 1, height, width)
+ patch_src = torch.from_numpy(board).to(device=device,
+ dtype=dtype).view(1, 1, height,
+ width).expand(batch_size, 1, height, width)
# create base homography
dst_homo_src = utils.create_eye_batch(batch_size, eye_size, device=device, dtype=dtype)
@@ -187,20 +183,22 @@ class TestHomographyWarper:
assert (patch_dst_to_src_precomputed == patch_dst_to_src).all()
# projected should be equal as initial
- error = utils.compute_patch_error(
- patch_src, patch_dst_to_src, height, width)
+ error = utils.compute_patch_error(patch_src, patch_dst_to_src, height, width)
assert error.item() < self.threshold
# check functional api
patch_dst_to_src_functional = kornia.homography_warp(
- patch_dst, _torch_inverse_cast(dst_homo_src_i), (height, width), align_corners=True)
+ patch_dst, _torch_inverse_cast(dst_homo_src_i), (height, width), align_corners=True
+ )
- assert_allclose(
- patch_dst_to_src, patch_dst_to_src_functional, atol=1e-4, rtol=1e-4)
+ assert_allclose(patch_dst_to_src, patch_dst_to_src_functional, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize("batch_shape", [
- (1, 1, 7, 5), (2, 3, 8, 5), (1, 1, 7, 16), ])
+ (1, 1, 7, 5),
+ (2, 3, 8, 5),
+ (1, 1, 7, 16),
+ ])
def test_gradcheck(self, batch_shape, device, dtype):
# generate input data
eye_size = 3 # identity 3x3
@@ -212,15 +210,16 @@ class TestHomographyWarper:
# create base homography
batch_size, _, height, width = patch_src.shape
dst_homo_src = utils.create_eye_batch(batch_size, eye_size, device=device, dtype=dtype)
- dst_homo_src = utils.tensor_to_gradcheck_var(
- dst_homo_src, requires_grad=False) # to var
+ dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src, requires_grad=False) # to var
# instantiate warper
warper = kornia.HomographyWarper(height, width, align_corners=True)
# evaluate function gradient
- assert gradcheck(warper, (patch_src, dst_homo_src,),
- raise_exception=True)
+ assert gradcheck(warper, (
+ patch_src,
+ dst_homo_src,
+ ), raise_exception=True)
@pytest.mark.parametrize("batch_size", [1, 2, 3])
@pytest.mark.parametrize("align_corners", [True, False])
@@ -232,8 +231,9 @@ class TestHomographyWarper:
# create checkerboard
board = utils.create_checkerboard(height, width, 4)
- patch_src = torch.from_numpy(board).to(device=device, dtype=dtype).view(
- 1, 1, height, width).expand(batch_size, 1, height, width)
+ patch_src = torch.from_numpy(board).to(device=device,
+ dtype=dtype).view(1, 1, height,
+ width).expand(batch_size, 1, height, width)
# create base homography
dst_homo_src = utils.create_eye_batch(batch_size, eye_size, device=device, dtype=dtype)
@@ -246,44 +246,45 @@ class TestHomographyWarper:
# transform the points with and without jit
patch_dst = kornia.homography_warp(
- patch_src, dst_homo_src_i, (height, width), align_corners=align_corners,
- normalized_coordinates=normalized_coordinates)
+ patch_src,
+ dst_homo_src_i, (height, width),
+ align_corners=align_corners,
+ normalized_coordinates=normalized_coordinates
+ )
patch_dst_jit = torch.jit.script(kornia.homography_warp)(
- patch_src, dst_homo_src_i, (height, width), align_corners=align_corners,
- normalized_coordinates=normalized_coordinates)
+ patch_src,
+ dst_homo_src_i, (height, width),
+ align_corners=align_corners,
+ normalized_coordinates=normalized_coordinates
+ )
assert_allclose(patch_dst, patch_dst_jit, atol=1e-4, rtol=1e-4)
class TestHomographyNormalTransform:
- expected_2d_0 = torch.tensor([[
- [0.5, 0.0, -1.],
- [0.0, 2.0, -1.],
- [0.0, 0.0, 1.]]])
-
- expected_2d_1 = torch.tensor([[
- [0.5, 0.0, -1.],
- [0.0, 2e14, -1.],
- [0.0, 0.0, 1.]]])
-
- expected_3d_0 = expected = torch.tensor([[
- [0.4, 0.0, 0.0, -1.],
- [0.0, 2.0, 0.0, -1.],
- [0.0, 0.0, 0.6667, -1.],
- [0.0, 0.0, 0.0, 1.],
- ]])
-
- expected_3d_1 = torch.tensor([[
- [0.4, 0.0, 0.0, -1.],
- [0.0, 2e14, 0.0, -1.],
- [0.0, 0.0, 0.6667, -1.],
- [0.0, 0.0, 0.0, 1.],
- ]])
-
- @pytest.mark.parametrize("height,width,expected", [
- (2, 5, expected_2d_0),
- (1, 5, expected_2d_1)
- ])
+ expected_2d_0 = torch.tensor([[[0.5, 0.0, -1.], [0.0, 2.0, -1.], [0.0, 0.0, 1.]]])
+
+ expected_2d_1 = torch.tensor([[[0.5, 0.0, -1.], [0.0, 2e14, -1.], [0.0, 0.0, 1.]]])
+
+ expected_3d_0 = expected = torch.tensor(
+ [[
+ [0.4, 0.0, 0.0, -1.],
+ [0.0, 2.0, 0.0, -1.],
+ [0.0, 0.0, 0.6667, -1.],
+ [0.0, 0.0, 0.0, 1.],
+ ]]
+ )
+
+ expected_3d_1 = torch.tensor(
+ [[
+ [0.4, 0.0, 0.0, -1.],
+ [0.0, 2e14, 0.0, -1.],
+ [0.0, 0.0, 0.6667, -1.],
+ [0.0, 0.0, 0.0, 1.],
+ ]]
+ )
+
+ @pytest.mark.parametrize("height,width,expected", [(2, 5, expected_2d_0), (1, 5, expected_2d_1)])
def test_transform2d(self, height, width, expected, device, dtype):
output = kornia.normal_transform_pixel(height, width, device=device, dtype=dtype)
@@ -303,10 +304,7 @@ class TestHomographyNormalTransform:
output = kornia.transform_points(transform, input)
assert_allclose(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
- @pytest.mark.parametrize("height,width,depth,expected", [
- (2, 6, 4, expected_3d_0),
- (1, 6, 4, expected_3d_1)
- ])
+ @pytest.mark.parametrize("height,width,depth,expected", [(2, 6, 4, expected_3d_0), (1, 6, 4, expected_3d_1)])
def test_transform3d(self, height, width, depth, expected, device, dtype):
output = kornia.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)
assert_allclose(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
@@ -337,30 +335,30 @@ class TestHomographyWarper3D:
input_shape = (4, 8, 5)
dst_homo_src = utils.create_eye_batch(batch_size=batch_size, eye_size=4).to(device=device, dtype=dtype)
- res = torch.tensor([[[0.5000, 0.0, 0.0, -1.0],
- [0.0, 0.2857, 0.0, -1.0],
- [0.0, 0.0, 0.6667, -1.0],
- [0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- norm = kornia.normal_transform_pixel3d(
- input_shape[0], input_shape[1], input_shape[2]).to(device=device, dtype=dtype)
+ res = torch.tensor(
+ [[[0.5000, 0.0, 0.0, -1.0], [0.0, 0.2857, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype
+ )
+ norm = kornia.normal_transform_pixel3d(input_shape[0], input_shape[1],
+ input_shape[2]).to(device=device, dtype=dtype)
assert_allclose(norm, res, rtol=1e-4, atol=1e-4)
- norm_homo = kornia.normalize_homography3d(
- dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)
+ norm_homo = kornia.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)
assert_allclose(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
- norm_homo = kornia.normalize_homography3d(
- dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)
+ norm_homo = kornia.normalize_homography3d(dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)
assert_allclose(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
# change output scale
norm_homo = kornia.normalize_homography3d(
dst_homo_src, input_shape, (input_shape[0] // 2, input_shape[1] * 2, input_shape[2] // 2)
).to(device=device, dtype=dtype)
- res = torch.tensor([[[4.0, 0.0, 0.0, 3.0],
- [0.0, 0.4667, 0.0, -0.5333],
- [0.0, 0.0, 3.0, 2.0],
- [0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype).repeat(batch_size, 1, 1)
+ res = torch.tensor(
+ [[[4.0, 0.0, 0.0, 3.0], [0.0, 0.4667, 0.0, -0.5333], [0.0, 0.0, 3.0, 2.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype
+ ).repeat(batch_size, 1, 1)
assert_allclose(norm_homo, res, rtol=1e-4, atol=1e-4)
@pytest.mark.parametrize("batch_size", [1, 3])
@@ -376,10 +374,11 @@ class TestHomographyWarper3D:
dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)
norm_homo = kornia.normalize_homography3d(dst_homo_src, (2, 2, 5), (2, 2, 5))
- res = torch.tensor([[[0.5, 0.0, 0.0, 0.0],
- [0.0, 0.5, 0.0, 3.5],
- [0.0, 0.0, 2.0, 7.0],
- [0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ res = torch.tensor(
+ [[[0.5, 0.0, 0.0, 0.0], [0.0, 0.5, 0.0, 3.5], [0.0, 0.0, 2.0, 7.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype
+ )
assert (norm_homo == res).all()
@pytest.mark.parametrize("offset", [1, 3, 7])
@@ -394,9 +393,6 @@ class TestHomographyWarper3D:
# the grid the src plus the offset should be equal to the flow
# on the x-axis, y-axis remains the same.
- assert_allclose(
- grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0], atol=1e-4, rtol=1e-4)
- assert_allclose(
- grid[..., 1].to(device=device, dtype=dtype), flow[..., 1], atol=1e-4, rtol=1e-4)
- assert_allclose(
- grid[..., 2].to(device=device, dtype=dtype), flow[..., 2], atol=1e-4, rtol=1e-4)
+ assert_allclose(grid[..., 0].to(device=device, dtype=dtype) + offset, flow[..., 0], atol=1e-4, rtol=1e-4)
+ assert_allclose(grid[..., 1].to(device=device, dtype=dtype), flow[..., 1], atol=1e-4, rtol=1e-4)
+ assert_allclose(grid[..., 2].to(device=device, dtype=dtype), flow[..., 2], atol=1e-4, rtol=1e-4)
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index f2d2a5c23..51de07977 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -26,18 +26,15 @@ def test_get_perspective_transform(batch_size, device, dtype):
# compute transform from source to target
dst_homo_src = kornia.get_perspective_transform(points_src, points_dst)
- assert_allclose(
- kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4)
+ assert_allclose(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4)
# compute gradient check
points_src = utils.tensor_to_gradcheck_var(points_src) # to var
points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
- assert gradcheck(
- kornia.get_perspective_transform, (
- points_src,
- points_dst,
- ),
- raise_exception=True)
+ assert gradcheck(kornia.get_perspective_transform, (
+ points_src,
+ points_dst,
+ ), raise_exception=True)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@@ -87,12 +84,11 @@ def test_rotation_matrix2d(batch_size, device, dtype):
center = utils.tensor_to_gradcheck_var(center) # to var
angle = utils.tensor_to_gradcheck_var(angle) # to var
scale = utils.tensor_to_gradcheck_var(scale) # to var
- assert gradcheck(
- kornia.get_rotation_matrix2d, (center, angle, scale),
- raise_exception=True)
+ assert gradcheck(kornia.get_rotation_matrix2d, (center, angle, scale), raise_exception=True)
class TestWarpAffine:
+
def test_smoke(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] # 1x2x3
@@ -100,12 +96,8 @@ class TestWarpAffine:
img_a = kornia.warp_affine(img_b, aff_ab, (height, width))
assert_allclose(img_b, img_a)
- @pytest.mark.parametrize("batch_shape", (
- [1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]
- ))
- @pytest.mark.parametrize("out_shape", (
- [2, 5], [3, 4], [6, 2]
- ))
+ @pytest.mark.parametrize("batch_shape", ([1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]))
+ @pytest.mark.parametrize("out_shape", ([2, 5], [3, 4], [6, 2]))
def test_cardinality(self, device, dtype, batch_shape, out_shape):
batch_size, channels, height, width = batch_shape
h_out, w_out = out_shape
@@ -182,11 +174,15 @@ class TestWarpAffine:
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
aff_ab = utils.tensor_to_gradcheck_var(aff_ab) # to var
img_b = utils.tensor_to_gradcheck_var(img_b) # to var
- assert gradcheck(kornia.warp_affine, (img_b, aff_ab, (height, width),),
- raise_exception=True)
+ assert gradcheck(kornia.warp_affine, (
+ img_b,
+ aff_ab,
+ (height, width),
+ ), raise_exception=True)
class TestWarpPerspective:
+
def test_smoke(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
@@ -194,12 +190,8 @@ class TestWarpPerspective:
img_a = kornia.warp_perspective(img_b, H_ab, (height, width))
assert_allclose(img_b, img_a)
- @pytest.mark.parametrize("batch_shape", (
- [1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]
- ))
- @pytest.mark.parametrize("out_shape", (
- [2, 5], [3, 4], [6, 2]
- ))
+ @pytest.mark.parametrize("batch_shape", ([1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]))
+ @pytest.mark.parametrize("out_shape", ([2, 5], [3, 4], [6, 2]))
def test_cardinality(self, device, dtype, batch_shape, out_shape):
batch_size, channels, height, width = batch_shape
h_out, w_out = out_shape
@@ -273,40 +265,43 @@ class TestWarpPerspective:
# [x, y] origin
# top-left, top-right, bottom-right, bottom-left
- points_src = torch.tensor([[
- [0, 0],
- [0, src_w - 1],
- [src_h - 1, src_w - 1],
- [src_h - 1, 0],
- ]], device=device, dtype=dtype)
+ points_src = torch.tensor(
+ [[
+ [0, 0],
+ [0, src_w - 1],
+ [src_h - 1, src_w - 1],
+ [src_h - 1, 0],
+ ]], device=device, dtype=dtype
+ )
# [x, y] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst = torch.tensor([[
- [0, 0],
- [0, dst_w - 1],
- [dst_h - 1, dst_w - 1],
- [dst_h - 1, 0],
- ]], device=device, dtype=dtype)
+ points_dst = torch.tensor(
+ [[
+ [0, 0],
+ [0, dst_w - 1],
+ [dst_h - 1, dst_w - 1],
+ [dst_h - 1, 0],
+ ]], device=device, dtype=dtype
+ )
# compute transformation between points
- dst_trans_src = kornia.get_perspective_transform(points_src,
- points_dst).expand(
- batch_size, -1, -1)
+ dst_trans_src = kornia.get_perspective_transform(points_src, points_dst).expand(batch_size, -1, -1)
# warp tensor
- patch = torch.tensor([[[
- [1, 2, 3, 4],
- [5, 6, 7, 8],
- [9, 10, 11, 12],
- [13, 14, 15, 16],
- ]]], device=device, dtype=dtype).expand(batch_size, channels, -1, -1)
+ patch = torch.tensor(
+ [[[
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12],
+ [13, 14, 15, 16],
+ ]]], device=device, dtype=dtype
+ ).expand(batch_size, channels, -1, -1)
expected = patch[..., :3, :3]
# warp and assert
- patch_warped = kornia.warp_perspective(
- patch, dst_trans_src, (dst_h, dst_w))
+ patch_warped = kornia.warp_perspective(patch, dst_trans_src, (dst_h, dst_w))
assert_allclose(patch_warped, expected)
def test_crop_center_resize(self, device, dtype):
@@ -324,33 +319,43 @@ class TestWarpPerspective:
# [x, y] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst = torch.tensor([[
- [0, 0],
- [0, dst_w - 1],
- [dst_h - 1, dst_w - 1],
- [dst_h - 1, 0],
- ]], device=device, dtype=dtype)
+ points_dst = torch.tensor(
+ [[
+ [0, 0],
+ [0, dst_w - 1],
+ [dst_h - 1, dst_w - 1],
+ [dst_h - 1, 0],
+ ]], device=device, dtype=dtype
+ )
# compute transformation between points
dst_trans_src = kornia.get_perspective_transform(points_src, points_dst)
# warp tensor
- patch = torch.tensor([[[
- [1, 2, 3, 4],
- [5, 6, 7, 8],
- [9, 10, 11, 12],
- [13, 14, 15, 16],
- ]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[
- [6.0000, 6.3333, 6.6667, 7.0000],
- [7.3333, 7.6667, 8.0000, 8.3333],
- [8.6667, 9.0000, 9.3333, 9.6667],
- [10.0000, 10.3333, 10.6667, 11.0000]]]], device=device, dtype=dtype)
+ patch = torch.tensor(
+ [[[
+ [1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12],
+ [13, 14, 15, 16],
+ ]]], device=device, dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [6.0000, 6.3333, 6.6667, 7.0000], [7.3333, 7.6667, 8.0000, 8.3333],
+ [8.6667, 9.0000, 9.3333, 9.6667], [10.0000, 10.3333, 10.6667, 11.0000]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
# warp and assert
- patch_warped = kornia.warp_perspective(
- patch, dst_trans_src, (dst_h, dst_w))
+ patch_warped = kornia.warp_perspective(patch, dst_trans_src, (dst_h, dst_w))
assert_allclose(patch_warped, expected)
def test_jit(self, device, dtype):
@@ -368,16 +373,19 @@ class TestWarpPerspective:
img_b = utils.tensor_to_gradcheck_var(img_b) # to var
# TODO(dmytro/edgar): firgure out why gradient don't propagate for the tranaform
H_ab = utils.tensor_to_gradcheck_var(H_ab, requires_grad=False) # to var
- assert gradcheck(kornia.warp_perspective, (img_b, H_ab, (height, width),),
- raise_exception=True)
+ assert gradcheck(kornia.warp_perspective, (
+ img_b,
+ H_ab,
+ (height, width),
+ ), raise_exception=True)
class TestRemap:
+
def test_smoke(self, device, dtype):
height, width = 3, 4
input = torch.ones(1, 1, height, width, device=device, dtype=dtype)
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
input_warped = kornia.remap(input, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input, input_warped, rtol=1e-4, atol=1e-4)
@@ -388,14 +396,15 @@ class TestRemap:
[1., 1., 1., 1.],
[1., 1., 1., 1.],
]]], device=device, dtype=dtype)
- expected = torch.tensor([[[
- [1., 1., 1., 0.],
- [1., 1., 1., 0.],
- [0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
-
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
+ expected = torch.tensor(
+ [[[
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ [0., 0., 0., 0.],
+ ]]], device=device, dtype=dtype
+ )
+
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 1. # apply shift in both x/y direction
input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
@@ -409,19 +418,24 @@ class TestRemap:
[1., 1., 1., 1.],
]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [1., 1., 1., 0.],
- [1., 1., 1., 0.],
- [1., 1., 1., 0.],
- ]], [[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [0., 0., 0., 0.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [[
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ ]], [[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [0., 0., 0., 0.],
+ ]]
+ ],
+ device=device,
+ dtype=dtype
+ )
# generate a batch of grids
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid = grid.repeat(2, 1, 1, 1)
grid[0, ..., 0] += 1. # apply shift in the x direction
grid[1, ..., 1] += 1. # apply shift in the y direction
@@ -436,14 +450,15 @@ class TestRemap:
[1., 1., 1., 1.],
[1., 1., 1., 1.],
]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [1., 1., 1., 0.],
- [1., 1., 1., 0.],
- [0., 0., 0., 0.],
- ]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
-
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
+ expected = torch.tensor(
+ [[[
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ [0., 0., 0., 0.],
+ ]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
+
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 1. # apply shift in both x/y direction
input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
@@ -457,18 +472,22 @@ class TestRemap:
[1., 1., 1., 1.],
[1., 1., 1., 1.],
]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
- expected = torch.tensor([[[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- ]]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ expected = torch.tensor(
+ [[[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ ]]], device=device, dtype=dtype
+ ).repeat(2, 1, 1, 1)
grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=normalized_coordinates, device=device).to(dtype)
+ height, width, normalized_coordinates=normalized_coordinates, device=device
+ ).to(dtype)
# Normalized input coordinates
- input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True,
- normalized_coordinates=normalized_coordinates)
+ input_warped = kornia.remap(
+ inp, grid[..., 0], grid[..., 1], align_corners=True, normalized_coordinates=normalized_coordinates
+ )
assert_allclose(input_warped, expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device, dtype):
@@ -476,41 +495,48 @@ class TestRemap:
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
- grid = utils.tensor_to_gradcheck_var(
- grid, requires_grad=False) # to var
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = utils.tensor_to_gradcheck_var(grid, requires_grad=False) # to var
- assert gradcheck(kornia.remap, (img, grid[..., 0], grid[..., 1],),
- raise_exception=True)
+ assert gradcheck(kornia.remap, (
+ img,
+ grid[..., 0],
+ grid[..., 1],
+ ), raise_exception=True)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(input, map1, map2):
return kornia.remap(input, map1, map2)
+
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 1. # apply some shift
- input = (img, grid[..., 0], grid[..., 1],)
+ input = (
+ img,
+ grid[..., 0],
+ grid[..., 1],
+ )
actual = op_script(*input)
expected = kornia.remap(*input)
assert_allclose(actual, expected, rtol=1e-4, atol=1e-4)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit_trace(self, device, dtype):
+
@torch.jit.script
def op_script(input, map1, map2):
return kornia.remap(input, map1, map2)
+
# 1. Trace op
batch_size, channels, height, width = 1, 1, 3, 4
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 1. # apply some shift
input_tuple = (img, grid[..., 0], grid[..., 1])
op_traced = torch.jit.trace(op_script, input_tuple)
@@ -518,8 +544,7 @@ class TestRemap:
# 2. Generate different input
batch_size, channels, height, width = 2, 2, 2, 5
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False, device=device).to(dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(dtype)
grid += 2. # apply some shift
# 3. Apply to different input
@@ -530,6 +555,7 @@ class TestRemap:
class TestInvertAffineTransform:
+
def test_smoke(self, device, dtype):
matrix = torch.eye(2, 3, device=device, dtype=dtype)[None]
matrix_inv = kornia.invert_affine_transform(matrix)
@@ -555,22 +581,22 @@ class TestInvertAffineTransform:
[0., -1., 0.],
[1., 0., 0.],
]], device=device, dtype=dtype).repeat(2, 1, 1)
- matrix = kornia.get_rotation_matrix2d(
- center, angle, scale).repeat(2, 1, 1)
+ matrix = kornia.get_rotation_matrix2d(center, angle, scale).repeat(2, 1, 1)
matrix_inv = kornia.invert_affine_transform(matrix)
assert_allclose(matrix_inv, expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device, dtype):
matrix = torch.eye(2, 3, device=device, dtype=dtype)[None]
matrix = utils.tensor_to_gradcheck_var(matrix) # to var
- assert gradcheck(kornia.invert_affine_transform, (matrix,),
- raise_exception=True)
+ assert gradcheck(kornia.invert_affine_transform, (matrix, ), raise_exception=True)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device, dtype):
+
@torch.jit.script
def op_script(input):
return kornia.invert_affine_transform(input)
+
matrix = torch.eye(2, 3, device=device, dtype=dtype)
op_traced = torch.jit.trace(op_script, matrix)
actual = op_traced(matrix)
@@ -579,9 +605,11 @@ class TestInvertAffineTransform:
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit_trace(self, device, dtype):
+
@torch.jit.script
def op_script(input):
return kornia.invert_affine_transform(input)
+
matrix = torch.eye(2, 3, device=device, dtype=dtype)
matrix_2 = torch.eye(2, 3, device=device, dtype=dtype).repeat(2, 1, 1)
op_traced = torch.jit.trace(op_script, matrix)
diff --git a/test/geometry/transform/test_projwarp.py b/test/geometry/transform/test_projwarp.py
index 09465f3dc..e82006daf 100644
--- a/test/geometry/transform/test_projwarp.py
+++ b/test/geometry/transform/test_projwarp.py
@@ -10,6 +10,7 @@ import kornia.geometry.transform.projwarp as proj
class TestWarpAffine3d:
+
def test_smoke(self, device, dtype):
input = torch.rand(1, 3, 3, 4, 5, device=device, dtype=dtype)
P = torch.rand(1, 3, 4, device=device, dtype=dtype)
@@ -42,37 +43,56 @@ class TestWarpAffine3d:
assert_allclose(output, input, rtol=1e-4, atol=1e-4)
def test_rotate_x(self, device, dtype):
- input = torch.tensor([[[[
- [0., 0., 0.],
- [0., 2., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 1., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 1., 0.],
- [0., 2., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 2., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 0.],
+ [0., 2., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
_, _, D, H, W = input.shape
- center = torch.tensor([
- [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+ center = torch.tensor([[(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
angles = torch.tensor([[90., 0., 0.]], device=device, dtype=dtype)
@@ -82,37 +102,56 @@ class TestWarpAffine3d:
assert_allclose(output, expected, rtol=1e-4, atol=1e-4)
def test_rotate_y(self, device, dtype):
- input = torch.tensor([[[[
- [0., 0., 0.],
- [0., 2., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 1., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [2., 1., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 2., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [2., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
_, _, D, H, W = input.shape
- center = torch.tensor([
- [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+ center = torch.tensor([[(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
angles = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
@@ -122,37 +161,56 @@ class TestWarpAffine3d:
assert_allclose(output, expected, rtol=1e-4, atol=1e-4)
def test_rotate_z(self, device, dtype):
- input = torch.tensor([[[[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ], [
- [0., 2., 0.],
- [0., 1., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 1., 2.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 2., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 2.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
_, _, D, H, W = input.shape
- center = torch.tensor([
- [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+ center = torch.tensor([[(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
angles = torch.tensor([[0., 0., 90.]], device=device, dtype=dtype)
@@ -163,61 +221,86 @@ class TestWarpAffine3d:
def test_rotate_y_large(self, device, dtype):
"""Rotates 90deg anti-clockwise."""
- input = torch.tensor([[[[
- [0., 4., 0.],
- [0., 3., 0.],
- [0., 0., 0.],
- ], [
- [0., 2., 0.],
- [0., 1., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]], [[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 9., 0.],
- ], [
- [0., 0., 0.],
- [0., 6., 7.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 8., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
-
- expected = torch.tensor([[[[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ], [
- [4., 2., 0.],
- [3., 1., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]], [[
- [0., 0., 0.],
- [0., 7., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 6., 8.],
- [9., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 0.],
- ]]]], device=device, dtype=dtype)
+ input = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 4., 0.],
+ [0., 3., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 2., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ],
+ [
+ [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 9., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 6., 7.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 8., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
+
+ expected = torch.tensor(
+ [
+ [
+ [
+ [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [4., 2., 0.],
+ [3., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ],
+ [
+ [
+ [0., 0., 0.],
+ [0., 7., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 6., 8.],
+ [9., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
_, _, D, H, W = input.shape
- center = torch.tensor([
- [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+ center = torch.tensor([[(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
angles = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
@@ -228,6 +311,7 @@ class TestWarpAffine3d:
class TestGetRotationMatrix3d:
+
def test_smoke(self, device, dtype):
center = torch.rand(1, 3, device=device, dtype=dtype)
angle = torch.rand(1, 3, device=device, dtype=dtype)
@@ -261,11 +345,13 @@ class TestGetRotationMatrix3d:
angle = torch.tensor([[90., 0., 0.]], device=device, dtype=dtype)
scales: torch.Tensor = torch.ones_like(angle, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angle, scales)
- P_expected = torch.tensor([
- [1., 0., 0., 0.],
- [0., 0., -1., 0.],
- [0., 1., 0., 0.],
- ], device=device, dtype=dtype).unsqueeze(0)
+ P_expected = torch.tensor(
+ [
+ [1., 0., 0., 0.],
+ [0., 0., -1., 0.],
+ [0., 1., 0., 0.],
+ ], device=device, dtype=dtype
+ ).unsqueeze(0)
assert_allclose(P, P_expected, atol=1e-4, rtol=1e-4)
def test_rot90y(self, device, dtype):
@@ -273,11 +359,13 @@ class TestGetRotationMatrix3d:
angle = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
scales: torch.Tensor = torch.ones_like(angle, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angle, scales)
- P_expected = torch.tensor([
- [0., 0., 1., 0.],
- [0., 1., 0., 0.],
- [-1., 0., 0., 0.],
- ], device=device, dtype=dtype).unsqueeze(0)
+ P_expected = torch.tensor(
+ [
+ [0., 0., 1., 0.],
+ [0., 1., 0., 0.],
+ [-1., 0., 0., 0.],
+ ], device=device, dtype=dtype
+ ).unsqueeze(0)
assert_allclose(P, P_expected, atol=1e-4, rtol=1e-4)
def test_rot90z(self, device, dtype):
@@ -285,11 +373,13 @@ class TestGetRotationMatrix3d:
angle = torch.tensor([[0., 0., 90.]], device=device, dtype=dtype)
scales: torch.Tensor = torch.ones_like(angle, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angle, scales)
- P_expected = torch.tensor([
- [0., -1., 0., 0.],
- [1., 0., 0., 0.],
- [0., 0., 1., 0.],
- ], device=device, dtype=dtype).unsqueeze(0)
+ P_expected = torch.tensor(
+ [
+ [0., -1., 0., 0.],
+ [1., 0., 0., 0.],
+ [0., 0., 1., 0.],
+ ], device=device, dtype=dtype
+ ).unsqueeze(0)
assert_allclose(P, P_expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device, dtype):
@@ -301,6 +391,7 @@ class TestGetRotationMatrix3d:
class TestPerspectiveTransform3D:
+
@pytest.mark.skip("Not working")
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_get_perspective_transform3d(self, batch_size, device, dtype):
@@ -319,18 +410,15 @@ class TestPerspectiveTransform3D:
# TODO: get_perspective_transform3d seems to be correct since it would result in the
# expected output for cropping volumes. Not sure what is going on here.
- assert_allclose(
- kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4)
+ assert_allclose(kornia.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4)
# compute gradient check
points_src = utils.tensor_to_gradcheck_var(points_src) # to var
points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
- assert gradcheck(
- kornia.get_perspective_transform3d, (
- points_src,
- points_dst,
- ),
- raise_exception=True)
+ assert gradcheck(kornia.get_perspective_transform3d, (
+ points_src,
+ points_dst,
+ ), raise_exception=True)
@pytest.mark.parametrize("batch_size", [1, 2])
def test_get_perspective_transform3d_2(self, batch_size, device, dtype):
@@ -339,45 +427,52 @@ class TestPerspectiveTransform3D:
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1, ), dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1, ), dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1, ), dtype=dtype).repeat(batch_size),
).to(device=device, dtype=dtype)
dst = kornia.bbox_generator3d(
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
torch.randint_like(torch.ones(batch_size), 0, 50, dtype=dtype),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
- torch.randint(0, 50, (1,), dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1, ), dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1, ), dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1, ), dtype=dtype).repeat(batch_size),
).to(device=device, dtype=dtype)
out = kornia.get_perspective_transform3d(src, dst)
if batch_size == 1:
- expected = torch.tensor([[
- [3.3000, 0.0000, 0.0000, -118.2000],
- [0.0000, 0.0769, 0.0000, 0.0000],
- [0.0000, 0.0000, 0.5517, 28.7930],
- [0.0000, 0.0000, 0.0000, 1.0000]
- ]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [3.3000, 0.0000, 0.0000, -118.2000], [0.0000, 0.0769, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.5517, 28.7930], [0.0000, 0.0000, 0.0000, 1.0000]
+ ]
+ ],
+ device=device,
+ dtype=dtype
+ )
if batch_size == 2:
- expected = torch.tensor([
- [[0.9630, 0.0000, 0.0000, -9.3702],
- [0.0000, 2.0000, 0.0000, -49.9999],
- [0.0000, 0.0000, 0.3830, 44.0213],
- [0.0000, 0.0000, 0.0000, 1.0000]],
- [[0.9630, 0.0000, 0.0000, -36.5555],
- [0.0000, 2.0000, 0.0000, -14.0000],
- [0.0000, 0.0000, 0.3830, 16.8940],
- [0.0000, 0.0000, 0.0000, 1.0000]],
- ], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [
+ [
+ [0.9630, 0.0000, 0.0000, -9.3702], [0.0000, 2.0000, 0.0000, -49.9999],
+ [0.0000, 0.0000, 0.3830, 44.0213], [0.0000, 0.0000, 0.0000, 1.0000]
+ ],
+ [
+ [0.9630, 0.0000, 0.0000, -36.5555], [0.0000, 2.0000, 0.0000, -14.0000],
+ [0.0000, 0.0000, 0.3830, 16.8940], [0.0000, 0.0000, 0.0000, 1.0000]
+ ],
+ ],
+ device=device,
+ dtype=dtype
+ )
assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
# compute gradient check
points_src = utils.tensor_to_gradcheck_var(src) # to var
points_dst = utils.tensor_to_gradcheck_var(dst) # to var
- assert gradcheck(
- kornia.get_perspective_transform3d, (
- points_src,
- points_dst,
- ), raise_exception=True)
+ assert gradcheck(kornia.get_perspective_transform3d, (
+ points_src,
+ points_dst,
+ ), raise_exception=True)
diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.py
index e6737f704..11e1ace93 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -9,6 +9,7 @@ from torch.autograd import gradcheck
class TestPyrUp:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 2, 4, 4, device=device, dtype=dtype)
pyr = kornia.geometry.PyrUp()
@@ -22,7 +23,7 @@ class TestPyrUp:
def test_gradcheck(self, device, dtype):
img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.geometry.pyrup, (img,), raise_exception=True)
+ assert gradcheck(kornia.geometry.pyrup, (img, ), raise_exception=True)
def test_jit(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
@@ -32,6 +33,7 @@ class TestPyrUp:
class TestPyrDown:
+
def test_shape(self, device, dtype):
inp = torch.zeros(1, 2, 4, 4, device=device, dtype=dtype)
pyr = kornia.geometry.PyrDown()
@@ -52,7 +54,7 @@ class TestPyrDown:
def test_gradcheck(self, device, dtype):
img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.geometry.pyrdown, (img,), raise_exception=True)
+ assert gradcheck(kornia.geometry.pyrdown, (img, ), raise_exception=True)
def test_jit(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
@@ -62,6 +64,7 @@ class TestPyrDown:
class TestScalePyramid:
+
def test_shape_tuple(self, device, dtype):
inp = torch.zeros(3, 2, 41, 41, device=device, dtype=dtype)
SP = kornia.geometry.ScalePyramid(n_levels=1, min_size=30)
@@ -122,10 +125,12 @@ class TestScalePyramid:
def sp_tuple(img):
sp, sigmas, pd = SP()(img)
return tuple(sp)
- assert gradcheck(sp_tuple, (img,), raise_exception=True, nondet_tol=1e-4)
+
+ assert gradcheck(sp_tuple, (img, ), raise_exception=True, nondet_tol=1e-4)
class TestBuildPyramid:
+
def test_smoke(self, device, dtype):
input = torch.ones(1, 2, 4, 5, device=device, dtype=dtype)
pyramid = kornia.build_pyramid(input, max_level=1)
@@ -142,7 +147,7 @@ class TestBuildPyramid:
assert len(pyramid) == max_level
for i in range(1, max_level):
img = pyramid[i]
- denom = 2 ** i
+ denom = 2**i
expected_shape = (batch_size, channels, height // denom, width // denom)
assert img.shape == expected_shape
@@ -151,4 +156,7 @@ class TestBuildPyramid:
batch_size, channels, height, width = 1, 2, 7, 9
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.build_pyramid, (img, max_level,), raise_exception=True)
+ assert gradcheck(kornia.build_pyramid, (
+ img,
+ max_level,
+ ), raise_exception=True)
diff --git a/test/geometry/transform/test_thin_plate_spline.py b/test/geometry/transform/test_thin_plate_spline.py
index 7e7d1ac9b..d2e781453 100644
--- a/test/geometry/transform/test_thin_plate_spline.py
+++ b/test/geometry/transform/test_thin_plate_spline.py
@@ -8,17 +8,14 @@ from torch.testing import assert_allclose
def _sample_points(batch_size, device, dtype=torch.float32):
- src = torch.tensor([[[0., 0.],
- [0., 10.],
- [10., 0.],
- [10., 10.],
- [5., 5.]]], device=device, dtype=dtype)
+ src = torch.tensor([[[0., 0.], [0., 10.], [10., 0.], [10., 10.], [5., 5.]]], device=device, dtype=dtype)
src = src.repeat(batch_size, 1, 1)
dst = src + torch.rand_like(src) * 2.5
return src, dst
class TestTransformParameters:
+
@pytest.mark.parametrize('batch_size', [1, 3])
def test_smoke(self, batch_size, device, dtype):
src = torch.rand(batch_size, 4, 2, device=device)
@@ -81,6 +78,7 @@ class TestTransformParameters:
class TestWarpPoints:
+
@pytest.mark.parametrize('batch_size', [1, 3])
def test_smoke(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
@@ -151,6 +149,7 @@ class TestWarpPoints:
class TestWarpImage:
+
@pytest.mark.parametrize('batch_size', [1, 3])
def test_smoke(self, batch_size, device, dtype):
src, dst = _sample_points(batch_size, device)
@@ -224,8 +223,9 @@ class TestWarpImage:
src, dst = _sample_points(batch_size, **opts)
kernel, affine = kornia.get_tps_transform(src, dst)
image = torch.rand(batch_size, 3, 8, 8, requires_grad=True, **opts)
- assert gradcheck(kornia.warp_image_tps, (image, dst, kernel, affine),
- raise_exception=True, atol=1e-4, rtol=1e-4)
+ assert gradcheck(
+ kornia.warp_image_tps, (image, dst, kernel, affine), raise_exception=True, atol=1e-4, rtol=1e-4
+ )
@pytest.mark.jit
@pytest.mark.parametrize('batch_size', [1, 3])
diff --git a/test/integration/test_conversions.py b/test/integration/test_conversions.py
index efab59604..a4366385c 100644
--- a/test/integration/test_conversions.py
+++ b/test/integration/test_conversions.py
@@ -26,11 +26,11 @@ def rtol(device, dtype):
class TestAngleAxisToQuaternionToAngleAxis:
+
def test_zero_angle(self, device, dtype, atol, rtol):
angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -40,8 +40,7 @@ class TestAngleAxisToQuaternionToAngleAxis:
array[axis] = theta
angle_axis = torch.tensor(array, device=device, dtype=dtype)
quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -51,27 +50,24 @@ class TestAngleAxisToQuaternionToAngleAxis:
array[axis] = kornia.pi / 2.
angle_axis = torch.tensor(array, device=device, dtype=dtype)
quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
class TestQuaternionToAngleAxisToQuaternion:
+
def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
with pytest.warns(UserWarning):
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
def test_unit_quaternion(self, device, dtype, atol, rtol):
quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -80,11 +76,9 @@ class TestQuaternionToAngleAxisToQuaternion:
array[axis] = 1.
quaternion = torch.tensor(array, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
with pytest.warns(UserWarning):
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -93,14 +87,12 @@ class TestQuaternionToAngleAxisToQuaternion:
array[1 + axis] = 1.
quaternion = torch.tensor(array, device=device, dtype=dtype)
angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
# just to be sure, check that mixing orders fails
with pytest.warns(UserWarning):
- quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert not torch.allclose(quaternion_hat_wrong, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -110,11 +102,9 @@ class TestQuaternionToAngleAxisToQuaternion:
array[axis] = np.sin(theta / 2.)
quaternion = torch.tensor(array, device=device, dtype=dtype)
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
with pytest.warns(UserWarning):
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -124,18 +114,17 @@ class TestQuaternionToAngleAxisToQuaternion:
array[1 + axis] = np.sin(theta / 2.)
quaternion = torch.tensor(array, device=device, dtype=dtype)
angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
# just to be sure, check that mixing orders fails
with pytest.warns(UserWarning):
- quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_hat_wrong = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert not torch.allclose(quaternion_hat_wrong, quaternion, atol=atol, rtol=rtol)
class TestQuaternionToRotationMatrixToAngleAxis:
+
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_qma_xyzw(self, axis, device, dtype, atol, rtol):
array = [[0., 0., 0., 0.]]
@@ -156,8 +145,7 @@ class TestQuaternionToRotationMatrixToAngleAxis:
assert_allclose(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)
with pytest.warns(UserWarning):
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -178,8 +166,7 @@ class TestQuaternionToRotationMatrixToAngleAxis:
angle_axis_expected = torch.tensor(angle_axis_expected, device=device, dtype=dtype)
assert_allclose(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)
- quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -190,8 +177,7 @@ class TestQuaternionToRotationMatrixToAngleAxis:
assert quaternion.shape[-1] == 4
with pytest.warns(UserWarning):
- angle_axis = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert angle_axis.shape[-1] == 3
rot_m = kornia.angle_axis_to_rotation_matrix(angle_axis)
@@ -199,8 +185,7 @@ class TestQuaternionToRotationMatrixToAngleAxis:
assert rot_m.shape[-2] == 3
with pytest.warns(UserWarning):
- quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.XYZW)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -217,8 +202,7 @@ class TestQuaternionToRotationMatrixToAngleAxis:
assert rot_m.shape[-1] == 3
assert rot_m.shape[-2] == 3
- quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion_hat = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -233,13 +217,11 @@ class TestQuaternionToRotationMatrixToAngleAxis:
assert rot_m.shape[-2] == 3
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(rot_m,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.XYZW)
assert quaternion.shape[-1] == 4
with pytest.warns(UserWarning):
- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -253,12 +235,10 @@ class TestQuaternionToRotationMatrixToAngleAxis:
assert rot_m.shape[-1] == 3
assert rot_m.shape[-2] == 3
- quaternion = kornia.rotation_matrix_to_quaternion(rot_m,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, order=QuaternionCoeffOrder.WXYZ)
assert quaternion.shape[-1] == 4
- angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ angle_axis_hat = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
@@ -269,13 +249,11 @@ class TestQuaternionToRotationMatrixToAngleAxis:
assert angle_axis.shape[-1] == 3
with pytest.warns(UserWarning):
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.XYZW)
assert quaternion.shape[-1] == 4
with pytest.warns(UserWarning):
- rot_m = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.XYZW)
+ rot_m = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.XYZW)
assert rot_m.shape[-1] == 3
assert rot_m.shape[-2] == 3
@@ -289,12 +267,10 @@ class TestQuaternionToRotationMatrixToAngleAxis:
angle_axis = torch.tensor(array, device=device, dtype=dtype)
assert angle_axis.shape[-1] == 3
- quaternion = kornia.angle_axis_to_quaternion(angle_axis,
- order=QuaternionCoeffOrder.WXYZ)
+ quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
assert quaternion.shape[-1] == 4
- rot_m = kornia.quaternion_to_rotation_matrix(quaternion,
- order=QuaternionCoeffOrder.WXYZ)
+ rot_m = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert rot_m.shape[-1] == 3
assert rot_m.shape[-2] == 3
@@ -344,10 +320,10 @@ class TestAngleOfRotations:
@pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
def test_axis_angle_to_rotation_matrix(self, axis_name, device, dtype, atol, rtol):
# Random angle in [-pi..pi]
- angle = torch.tensor((np.random.random(size=(2, 1)) * 2. * np.pi - np.pi), device=device,
- dtype=dtype)
+ angle = torch.tensor((np.random.random(size=(2, 1)) * 2. * np.pi - np.pi), device=device, dtype=dtype)
rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
- axis_name=axis_name, angle=angle, device=device, dtype=dtype)
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype
+ )
assert rot_m.dim() == 3
assert rot_m.shape[-1] == 3
assert rot_m.shape[-2] == 3
@@ -357,46 +333,36 @@ class TestAngleOfRotations:
# Make sure the returned axis matches the named one, and the appropriate column
if axis_name == 'x':
- assert_allclose(axis, torch.tensor(((1., 0., 0.),) * angle.numel(), device=device,
- dtype=dtype))
+ assert_allclose(axis, torch.tensor(((1., 0., 0.), ) * angle.numel(), device=device, dtype=dtype))
assert_allclose(axis, rot_m[..., :3, 0])
elif axis_name == 'y':
- assert_allclose(axis, torch.tensor(((0., 1., 0.),) * angle.numel(), device=device,
- dtype=dtype))
+ assert_allclose(axis, torch.tensor(((0., 1., 0.), ) * angle.numel(), device=device, dtype=dtype))
assert_allclose(axis, rot_m[..., :3, 1])
elif axis_name == 'z':
- assert_allclose(axis, torch.tensor(((0., 0., 1.),) * angle.numel(), device=device,
- dtype=dtype))
+ assert_allclose(axis, torch.tensor(((0., 0., 1.), ) * angle.numel(), device=device, dtype=dtype))
assert_allclose(axis, rot_m[..., :3, 2])
else:
raise NotImplementedError(f'Not prepared for axis_name {axis_name}')
# Make sure axes are perpendicular
zero = torch.zeros_like(angle).unsqueeze(-1)
- assert_allclose(rot_m[..., :3, 1:2].permute((0, 2, 1)) @ rot_m[..., :3, 0:1], zero,
- atol=atol, rtol=rtol)
- assert_allclose(rot_m[..., :3, 2:3].permute((0, 2, 1)) @ rot_m[..., :3, 1:2], zero,
- atol=atol, rtol=rtol)
- assert_allclose(rot_m[..., :3, 2:3].permute((0, 2, 1)) @ rot_m[..., :3, 0:1], zero,
- atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 1:2].permute((0, 2, 1)) @ rot_m[..., :3, 0:1], zero, atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 2:3].permute((0, 2, 1)) @ rot_m[..., :3, 1:2], zero, atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 2:3].permute((0, 2, 1)) @ rot_m[..., :3, 0:1], zero, atol=atol, rtol=rtol)
# Make sure axes are unit norm
one = torch.ones_like(angle)
- assert_allclose(rot_m[..., :3, 0].norm(p=2, dim=-1, keepdim=True), one,
- atol=atol, rtol=rtol)
- assert_allclose(rot_m[..., :3, 1].norm(p=2, dim=-1, keepdim=True), one,
- atol=atol, rtol=rtol)
- assert_allclose(rot_m[..., :3, 2].norm(p=2, dim=-1, keepdim=True), one,
- atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 0].norm(p=2, dim=-1, keepdim=True), one, atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 1].norm(p=2, dim=-1, keepdim=True), one, atol=atol, rtol=rtol)
+ assert_allclose(rot_m[..., :3, 2].norm(p=2, dim=-1, keepdim=True), one, atol=atol, rtol=rtol)
@pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
@pytest.mark.parametrize("angle_deg", (-179.9, -135., -90., -45., 0., 45, 90, 135, 179.9))
def test_matrix_angle(self, axis_name, angle_deg, device, dtype):
angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).view(1, 1)
- rot_m, _ = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
- angle=angle,
- device=device,
- dtype=dtype)
+ rot_m, _ = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype
+ )
matrix_angle_abs = TestAngleOfRotations.matrix_angle_abs(rot_m)
assert_allclose(torch.abs(angle), matrix_angle_abs)
@@ -408,17 +374,14 @@ class TestAngleOfRotations:
.repeat(2, 1)
pi = torch.ones_like(angle) * kornia.pi
assert 2 <= len(angle.shape)
- rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
- angle=angle,
- device=device,
- dtype=dtype)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype
+ )
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.XYZW)
# compute quaternion rotation angle
# See Section 2.4.4 Equation (105a) in https://arxiv.org/pdf/1711.02508.pdf
- angle_hat = 2. * torch.atan2(quaternion[..., :3].norm(p=2, dim=-1, keepdim=True),
- quaternion[..., 3:4])
+ angle_hat = 2. * torch.atan2(quaternion[..., :3].norm(p=2, dim=-1, keepdim=True), quaternion[..., 3:4])
# make sure it lands between [-pi..pi)
mask = pi < angle_hat
while torch.any(mask):
@@ -441,16 +404,13 @@ class TestAngleOfRotations:
.repeat(2, 1)
pi = torch.ones_like(angle) * kornia.pi
assert 2 <= len(angle.shape)
- rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
- angle=angle,
- device=device,
- dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype
+ )
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.WXYZ)
# compute quaternion rotation angle
# See Section 2.4.4 Equation (105a) in https://arxiv.org/pdf/1711.02508.pdf
- angle_hat = 2. * torch.atan2(quaternion[..., 1:4].norm(p=2, dim=-1, keepdim=True),
- quaternion[..., 0:1])
+ angle_hat = 2. * torch.atan2(quaternion[..., 1:4].norm(p=2, dim=-1, keepdim=True), quaternion[..., 0:1])
# make sure it lands between [-pi..pi)
mask = pi < angle_hat
while torch.any(mask):
@@ -469,10 +429,9 @@ class TestAngleOfRotations:
@pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0, 45, 90, 179.9))
def test_angle_axis(self, axis_name, angle_deg, device, dtype, atol, rtol):
angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
- rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
- angle=angle,
- device=device,
- dtype=dtype)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype
+ )
angle_axis = kornia.rotation_matrix_to_angle_axis(rot_m)
# compute angle_axis rotation angle
angle_hat = angle_axis.norm(p=2, dim=-1, keepdim=True)
@@ -491,16 +450,13 @@ class TestAngleOfRotations:
eps = torch.finfo(dtype).eps
angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
pi = torch.ones_like(angle) * kornia.pi
- rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
- angle=angle,
- device=device,
- dtype=dtype)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype
+ )
with pytest.warns(UserWarning):
- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.XYZW)
with pytest.warns(UserWarning):
- log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps,
- order=QuaternionCoeffOrder.XYZW)
+ log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW)
# compute angle_axis rotation angle
angle_hat = 2. * log_q.norm(p=2, dim=-1, keepdim=True)
# make sure it lands between [-pi..pi)
@@ -523,14 +479,11 @@ class TestAngleOfRotations:
eps = torch.finfo(dtype).eps
angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
pi = torch.ones_like(angle) * kornia.pi
- rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(axis_name=axis_name,
- angle=angle,
- device=device,
- dtype=dtype)
- quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
- log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps,
- order=QuaternionCoeffOrder.WXYZ)
+ rot_m, axis = TestAngleOfRotations.axis_and_angle_to_rotation_matrix(
+ axis_name=axis_name, angle=angle, device=device, dtype=dtype
+ )
+ quaternion = kornia.rotation_matrix_to_quaternion(rot_m, eps=eps, order=QuaternionCoeffOrder.WXYZ)
+ log_q = kornia.quaternion_exp_to_log(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)
# compute angle_axis rotation angle
angle_hat = 2. * log_q.norm(p=2, dim=-1, keepdim=True)
# make sure it lands between [-pi..pi)
diff --git a/test/integration/test_focal.py b/test/integration/test_focal.py
index a8e7783ae..c8d630e0d 100644
--- a/test/integration/test_focal.py
+++ b/test/integration/test_focal.py
@@ -47,8 +47,7 @@ class TestIntegrationFocalLoss:
optimizer = optim.Adam(m.parameters(), lr=self.lr)
- criterion = kornia.losses.FocalLoss(
- alpha=self.alpha, gamma=self.gamma, reduction='mean')
+ criterion = kornia.losses.FocalLoss(alpha=self.alpha, gamma=self.gamma, reduction='mean')
# NOTE: uncomment to compare against vanilla cross entropy
# criterion = nn.CrossEntropyLoss()
diff --git a/test/integration/test_soft_argmax2d.py b/test/integration/test_soft_argmax2d.py
index 71f844498..7b0e485aa 100644
--- a/test/integration/test_soft_argmax2d.py
+++ b/test/integration/test_soft_argmax2d.py
@@ -44,11 +44,10 @@ class TestIntegrationSoftArgmax2d:
criterion = nn.MSELoss()
# spatial soft-argmax2d module
- soft_argmax2d = kornia.geometry.SpatialSoftArgmax2d(
- normalized_coordinates=False)
+ soft_argmax2d = kornia.geometry.SpatialSoftArgmax2d(normalized_coordinates=False)
# NOTE: check where this comes from
- temperature = (self.height * self.width) ** (0.5)
+ temperature = (self.height * self.width)**(0.5)
for iter_id in range(self.num_iterations):
x = params
diff --git a/test/integration/test_warp.py b/test/integration/test_warp.py
index 08a4b0fca..998ee4d5e 100644
--- a/test/integration/test_warp.py
+++ b/test/integration/test_warp.py
@@ -30,11 +30,7 @@ class TestWarping:
img_dst_t: torch.Tensor = torch.rand(1, 3, 120, 120).to(device)
init_homo: torch.Tensor = torch.from_numpy(
- np.array([
- [0.0415, 1.2731, -1.1731],
- [-0.9094, 0.5072, 0.4272],
- [0.0762, 1.3981, 1.0646]
- ])
+ np.array([[0.0415, 1.2731, -1.1731], [-0.9094, 0.5072, 0.4272], [0.0762, 1.3981, 1.0646]])
).float()
height, width = img_dst_t.shape[-2:]
diff --git a/test/morphology/test_bottom_hat.py b/test/morphology/test_bottom_hat.py
index 904dc3ebc..37fbee48f 100644
--- a/test/morphology/test_bottom_hat.py
+++ b/test/morphology/test_bottom_hat.py
@@ -11,21 +11,19 @@ class TestBlackHat:
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
- @pytest.mark.parametrize(
- "kernel", [(3, 3), (5, 5)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize("kernel", [(3, 3), (5, 5)])
def test_cardinality(self, device, dtype, shape, kernel):
img = torch.ones(shape, device=device, dtype=dtype)
krnl = torch.ones(kernel, device=device, dtype=dtype)
assert bottom_hat(img, krnl).shape == shape
def test_value(self, device, dtype):
- input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[None,
+ None, :, :]
kernel = torch.tensor([[-1., 0., -1.], [0., 0., 0.], [-1., 0., -1.]], device=device, dtype=dtype)
- expected = torch.tensor([[0.2, 0., 0.5], [0., 0.4, 0.], [0.3, 0., 0.6]],
- device=device, dtype=dtype)[None, None, :, :]
+ expected = torch.tensor([[0.2, 0., 0.5], [0., 0.4, 0.], [0.3, 0., 0.6]], device=device, dtype=dtype)[None,
+ None, :, :]
assert_allclose(bottom_hat(input, kernel), expected)
def test_exception(self, device, dtype):
diff --git a/test/morphology/test_closing.py b/test/morphology/test_closing.py
index 24c956782..e25f57d97 100644
--- a/test/morphology/test_closing.py
+++ b/test/morphology/test_closing.py
@@ -11,21 +11,19 @@ class TestClosing:
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
- @pytest.mark.parametrize(
- "kernel", [(3, 3), (5, 5)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize("kernel", [(3, 3), (5, 5)])
def test_cardinality(self, device, dtype, shape, kernel):
img = torch.ones(shape, device=device, dtype=dtype)
krnl = torch.ones(kernel, device=device, dtype=dtype)
assert closing(img, krnl).shape == shape
def test_value(self, device, dtype):
- tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device,
+ dtype=dtype)[None, None, :, :]
kernel = torch.tensor([[-1., 0., -1.], [0., 0., 0.], [-1., 0., -1.]], device=device, dtype=dtype)
- expected = torch.tensor([[0.7, 1., 0.8], [0.7, 0.7, 0.8], [0.7, 0.9, 0.8]],
- device=device, dtype=dtype)[None, None, :, :]
+ expected = torch.tensor([[0.7, 1., 0.8], [0.7, 0.7, 0.8], [0.7, 0.9, 0.8]], device=device,
+ dtype=dtype)[None, None, :, :]
assert_allclose(closing(tensor, kernel), expected)
def test_exception(self, device, dtype):
diff --git a/test/morphology/test_dilation.py b/test/morphology/test_dilation.py
index 3f2653494..ae737a965 100644
--- a/test/morphology/test_dilation.py
+++ b/test/morphology/test_dilation.py
@@ -11,21 +11,19 @@ class TestDilate:
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
- @pytest.mark.parametrize(
- "kernel", [(3, 3), (5, 5), (3, 5), (5, 3)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize("kernel", [(3, 3), (5, 5), (3, 5), (5, 3)])
def test_cardinality(self, device, dtype, shape, kernel):
img = torch.ones(shape, device=device, dtype=dtype)
krnl = torch.ones(kernel, device=device, dtype=dtype)
assert dilation(img, krnl).shape == shape
def test_value(self, device, dtype):
- tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device,
+ dtype=dtype)[None, None, :, :]
kernel = torch.tensor([[-1., 0., -1.], [0., 0., 0.], [-1., 0., -1.]], device=device, dtype=dtype)
- expected = torch.tensor([[1., 1., 1.], [0.7, 1., 0.8], [0.9, 0.9, 0.9]],
- device=device, dtype=dtype)[None, None, :, :]
+ expected = torch.tensor([[1., 1., 1.], [0.7, 1., 0.8], [0.9, 0.9, 0.9]], device=device, dtype=dtype)[None,
+ None, :, :]
assert_allclose(dilation(tensor, kernel), expected)
def test_exception(self, device, dtype):
diff --git a/test/morphology/test_erosion.py b/test/morphology/test_erosion.py
index af810e397..cb1243558 100644
--- a/test/morphology/test_erosion.py
+++ b/test/morphology/test_erosion.py
@@ -11,21 +11,19 @@ class TestErode:
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
- @pytest.mark.parametrize(
- "kernel", [(3, 3), (5, 5), (3, 5), (5, 3)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize("kernel", [(3, 3), (5, 5), (3, 5), (5, 3)])
def test_cardinality(self, device, dtype, shape, kernel):
img = torch.ones(shape, device=device, dtype=dtype)
krnl = torch.ones(kernel, device=device, dtype=dtype)
assert erosion(img, krnl).shape == shape
def test_value(self, device, dtype):
- tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device,
+ dtype=dtype)[None, None, :, :]
kernel = torch.tensor([[-1., 0., -1.], [0., 0., 0.], [-1., 0., -1.]], device=device, dtype=dtype)
- expected = torch.tensor([[0.5, 0.3, 0.3], [0.3, 0.3, 0.2], [0.4, 0.2, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ expected = torch.tensor([[0.5, 0.3, 0.3], [0.3, 0.3, 0.2], [0.4, 0.2, 0.2]], device=device,
+ dtype=dtype)[None, None, :, :]
assert_allclose(erosion(tensor, kernel), expected)
def test_exception(self, device, dtype):
diff --git a/test/morphology/test_gradient.py b/test/morphology/test_gradient.py
index 24dc1f136..cb5f6f07c 100644
--- a/test/morphology/test_gradient.py
+++ b/test/morphology/test_gradient.py
@@ -11,21 +11,19 @@ class TestGradient:
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
- @pytest.mark.parametrize(
- "kernel", [(3, 3), (5, 5)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize("kernel", [(3, 3), (5, 5)])
def test_cardinality(self, device, dtype, shape, kernel):
img = torch.ones(shape, device=device, dtype=dtype)
krnl = torch.ones(kernel, device=device, dtype=dtype)
assert gradient(img, krnl).shape == shape
def test_value(self, device, dtype):
- tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device,
+ dtype=dtype)[None, None, :, :]
kernel = torch.tensor([[-1., 0., -1.], [0., 0., 0.], [-1., 0., -1.]], device=device, dtype=dtype)
- expected = torch.tensor([[0.5, 0.7, 0.7], [0.4, 0.7, 0.6], [0.5, 0.7, 0.7]],
- device=device, dtype=dtype)[None, None, :, :]
+ expected = torch.tensor([[0.5, 0.7, 0.7], [0.4, 0.7, 0.6], [0.5, 0.7, 0.7]], device=device,
+ dtype=dtype)[None, None, :, :]
assert_allclose(gradient(tensor, kernel), expected)
def test_exception(self, device, dtype):
diff --git a/test/morphology/test_opening.py b/test/morphology/test_opening.py
index d7b9aff8d..2a72b82ee 100644
--- a/test/morphology/test_opening.py
+++ b/test/morphology/test_opening.py
@@ -11,21 +11,19 @@ class TestOpening:
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
- @pytest.mark.parametrize(
- "kernel", [(3, 3), (5, 5)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize("kernel", [(3, 3), (5, 5)])
def test_cardinality(self, device, dtype, shape, kernel):
img = torch.ones(shape, device=device, dtype=dtype)
krnl = torch.ones(kernel, device=device, dtype=dtype)
assert opening(img, krnl).shape == shape
def test_value(self, device, dtype):
- tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ tensor = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device,
+ dtype=dtype)[None, None, :, :]
kernel = torch.tensor([[-1., 0., -1.], [0., 0., 0.], [-1., 0., -1.]], device=device, dtype=dtype)
- expected = torch.tensor([[0.5, 0.5, 0.3], [0.5, 0.3, 0.3], [0.4, 0.4, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ expected = torch.tensor([[0.5, 0.5, 0.3], [0.5, 0.3, 0.3], [0.4, 0.4, 0.2]], device=device,
+ dtype=dtype)[None, None, :, :]
assert_allclose(opening(tensor, kernel), expected)
def test_exception(self, device, dtype):
diff --git a/test/morphology/test_top_hat.py b/test/morphology/test_top_hat.py
index 0ef9e2309..25ab8aee1 100644
--- a/test/morphology/test_top_hat.py
+++ b/test/morphology/test_top_hat.py
@@ -11,21 +11,19 @@ class TestTopHat:
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
- @pytest.mark.parametrize(
- "shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
- @pytest.mark.parametrize(
- "kernel", [(3, 3), (5, 5)])
+ @pytest.mark.parametrize("shape", [(1, 3, 4, 4), (2, 3, 2, 4), (3, 3, 4, 1), (3, 2, 5, 5)])
+ @pytest.mark.parametrize("kernel", [(3, 3), (5, 5)])
def test_cardinality(self, device, dtype, shape, kernel):
img = torch.ones(shape, device=device, dtype=dtype)
krnl = torch.ones(kernel, device=device, dtype=dtype)
assert top_hat(img, krnl).shape == shape
def test_value(self, device, dtype):
- input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]],
- device=device, dtype=dtype)[None, None, :, :]
+ input = torch.tensor([[0.5, 1., 0.3], [0.7, 0.3, 0.8], [0.4, 0.9, 0.2]], device=device, dtype=dtype)[None,
+ None, :, :]
kernel = torch.tensor([[-1., 0., -1.], [0., 0., 0.], [-1., 0., -1.]], device=device, dtype=dtype)
- expected = torch.tensor([[0., 0.5, 0.], [0.2, 0., 0.5], [0., 0.5, 0.]],
- device=device, dtype=dtype)[None, None, :, :]
+ expected = torch.tensor([[0., 0.5, 0.], [0.2, 0., 0.5], [0., 0.5, 0.]], device=device, dtype=dtype)[None,
+ None, :, :]
assert_allclose(top_hat(input, kernel), expected)
def test_exception(self, device, dtype):
diff --git a/test/performance/test_imgwarp_speed.py b/test/performance/test_imgwarp_speed.py
index 930562065..b9560b8f0 100644
--- a/test/performance/test_imgwarp_speed.py
+++ b/test/performance/test_imgwarp_speed.py
@@ -4,7 +4,6 @@ from time import time
import torch
import kornia as kornia
-
shapes = [(512, 3, 256, 256), (256, 1, 64, 64)]
PSs = [224, 32]
diff --git a/test/performance/test_project_points_speed.py b/test/performance/test_project_points_speed.py
index 0412021e7..2756f159e 100644
--- a/test/performance/test_project_points_speed.py
+++ b/test/performance/test_project_points_speed.py
@@ -4,7 +4,6 @@ from time import time
import torch
import kornia as kornia
-
points_shapes = [(64, 1024**2, 3), (8192, 8192, 3), (1024**2, 64, 3)]
# TODO: remove xfail once we have enough gpu bandwith in the CI
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 204b11393..968e4b6db 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -9,6 +9,7 @@ import kornia.testing as utils # test utils
class TestMaxBlurPool2d:
+
def test_shape(self, device):
input = torch.rand(1, 2, 4, 6).to(device)
pool = kornia.contrib.MaxBlurPool2d(kernel_size=3)
@@ -22,14 +23,18 @@ class TestMaxBlurPool2d:
def test_gradcheck(self, device):
input = torch.rand(2, 3, 4, 4).to(device)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.contrib.max_blur_pool2d,
- (input, 3,), raise_exception=True)
+ assert gradcheck(kornia.contrib.max_blur_pool2d, (
+ input,
+ 3,
+ ), raise_exception=True)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
+
@torch.jit.script
def op_script(input: torch.Tensor, kernel_size: int) -> torch.Tensor:
return kornia.contrib.max_blur_pool2d(input, kernel_size)
+
img = torch.rand(2, 3, 4, 5).to(device)
actual = op_script(img, kernel_size=3)
expected = kornia.contrib.max_blur_pool2d(img, kernel_size=3)
@@ -37,6 +42,7 @@ class TestMaxBlurPool2d:
class TestExtractTensorPatches:
+
def test_smoke(self, device):
input = torch.arange(16.).view(1, 1, 4, 4).to(device)
m = kornia.contrib.ExtractTensorPatches(3)
@@ -111,14 +117,10 @@ class TestExtractTensorPatches:
patches = m(input)
assert patches.shape == (batch_size, 16, 1, 2, 2)
for i in range(batch_size):
- assert_allclose(
- input[i, :, 0:2, 0:2], patches[i, 5])
- assert_allclose(
- input[i, :, 0:2, 1:3], patches[i, 6])
- assert_allclose(
- input[i, :, 1:3, 0:2], patches[i, 9])
- assert_allclose(
- input[i, :, 1:3, 1:3], patches[i, 10])
+ assert_allclose(input[i, :, 0:2, 0:2], patches[i, 5])
+ assert_allclose(input[i, :, 0:2, 1:3], patches[i, 6])
+ assert_allclose(input[i, :, 1:3, 0:2], patches[i, 9])
+ assert_allclose(input[i, :, 1:3, 1:3], patches[i, 10])
def test_b1_ch1_h3w3_ws23(self, device):
input = torch.arange(9.).view(1, 1, 3, 3).to(device)
@@ -140,22 +142,23 @@ class TestExtractTensorPatches:
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
+
@torch.jit.script
- def op_script(input: torch.Tensor, height: int,
- width: int) -> torch.Tensor:
+ def op_script(input: torch.Tensor, height: int, width: int) -> torch.Tensor:
return kornia.denormalize_pixel_coordinates(input, height, width)
+
height, width = 3, 4
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True).to(device)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True).to(device)
actual = op_script(grid, height, width)
- expected = kornia.denormalize_pixel_coordinates(
- grid, height, width)
+ expected = kornia.denormalize_pixel_coordinates(grid, height, width)
assert_allclose(actual, expected)
def test_gradcheck(self, device):
input = torch.rand(2, 3, 4, 4).to(device)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.contrib.extract_tensor_patches,
- (input, 3,), raise_exception=True)
+ assert gradcheck(kornia.contrib.extract_tensor_patches, (
+ input,
+ 3,
+ ), raise_exception=True)
diff --git a/test/test_losses.py b/test/test_losses.py
index 0407b9998..26fd3b82b 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -10,14 +10,14 @@ from torch.testing import assert_allclose
class TestBinaryFocalLossWithLogits:
+
def test_smoke_none(self, device, dtype):
num_classes = 1
logits = torch.rand(2, num_classes, 3, 2, dtype=dtype, device=device)
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
- assert kornia.losses.binary_focal_loss_with_logits(
- logits, labels, alpha=0.5, gamma=2.0, reduction="none"
- ).shape == (2, 3, 2)
+ assert kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0,
+ reduction="none").shape == (2, 3, 2)
def test_smoke_sum(self, device, dtype):
num_classes = 1
@@ -25,9 +25,8 @@ class TestBinaryFocalLossWithLogits:
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
assert (
- kornia.losses.binary_focal_loss_with_logits(
- logits, labels, alpha=0.5, gamma=2.0, reduction="sum"
- ).shape == ()
+ kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0,
+ reduction="sum").shape == ()
)
def test_smoke_mean(self, device, dtype):
@@ -36,9 +35,8 @@ class TestBinaryFocalLossWithLogits:
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
assert (
- kornia.losses.binary_focal_loss_with_logits(
- logits, labels, alpha=0.5, gamma=2.0, reduction="mean"
- ).shape == ()
+ kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0,
+ reduction="mean").shape == ()
)
def test_smoke_mean_flat(self, device, dtype):
@@ -47,9 +45,8 @@ class TestBinaryFocalLossWithLogits:
labels = torch.rand(2, 3, 2, dtype=dtype, device=device)
assert (
- kornia.losses.binary_focal_loss_with_logits(
- logits, labels, alpha=0.5, gamma=2.0, reduction="mean"
- ).shape == ()
+ kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0,
+ reduction="mean").shape == ()
)
def test_jit(self, device, dtype):
@@ -89,15 +86,14 @@ class TestBinaryFocalLossWithLogits:
class TestFocalLoss:
+
def test_smoke_none(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
labels = torch.rand(2, 3, 2) * num_classes
labels = labels.to(device).long()
- assert kornia.losses.focal_loss(
- logits, labels, alpha=0.5, gamma=2.0, reduction="none"
- ).shape == (2, 3, 2)
+ assert kornia.losses.focal_loss(logits, labels, alpha=0.5, gamma=2.0, reduction="none").shape == (2, 3, 2)
def test_smoke_sum(self, device, dtype):
num_classes = 3
@@ -105,11 +101,7 @@ class TestFocalLoss:
labels = torch.rand(2, 3, 2) * num_classes
labels = labels.to(device).long()
- assert (
- kornia.losses.focal_loss(
- logits, labels, alpha=0.5, gamma=2.0, reduction="sum"
- ).shape == ()
- )
+ assert (kornia.losses.focal_loss(logits, labels, alpha=0.5, gamma=2.0, reduction="sum").shape == ())
def test_smoke_mean(self, device, dtype):
num_classes = 3
@@ -117,22 +109,14 @@ class TestFocalLoss:
labels = torch.rand(2, 3, 2) * num_classes
labels = labels.to(device).long()
- assert (
- kornia.losses.focal_loss(
- logits, labels, alpha=0.5, gamma=2.0, reduction="mean"
- ).shape == ()
- )
+ assert (kornia.losses.focal_loss(logits, labels, alpha=0.5, gamma=2.0, reduction="mean").shape == ())
def test_smoke_mean_flat(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, device=device, dtype=dtype)
labels = torch.rand(2) * num_classes
labels = labels.to(device).long()
- assert (
- kornia.losses.focal_loss(
- logits, labels, alpha=0.5, gamma=2.0, reduction="mean"
- ).shape == ()
- )
+ assert (kornia.losses.focal_loss(logits, labels, alpha=0.5, gamma=2.0, reduction="mean").shape == ())
def test_gradcheck(self, device, dtype):
num_classes = 3
@@ -178,6 +162,7 @@ class TestFocalLoss:
class TestTverskyLoss:
+
def test_smoke(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -243,6 +228,7 @@ class TestTverskyLoss:
class TestDiceLoss:
+
def test_smoke(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -271,9 +257,7 @@ class TestDiceLoss:
labels = labels.to(device).long()
logits = utils.tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(
- kornia.losses.dice_loss, (logits, labels), raise_exception=True
- )
+ assert gradcheck(kornia.losses.dice_loss, (logits, labels), raise_exception=True)
def test_jit(self, device, dtype):
num_classes = 3
@@ -299,6 +283,7 @@ class TestDiceLoss:
class TestDepthSmoothnessLoss:
+
@pytest.mark.parametrize("data_shape", [(1, 1, 10, 16), (2, 4, 8, 15)])
def test_smoke(self, device, dtype, data_shape):
image = torch.rand(data_shape, device=device, dtype=dtype)
@@ -338,6 +323,7 @@ class TestDepthSmoothnessLoss:
class TestSSIMLoss:
+
def test_ssim_equal_none(self, device, dtype):
# input data
img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
@@ -360,8 +346,7 @@ class TestSSIMLoss:
# input data
img = torch.rand(batch_shape, device=device, dtype=dtype)
- loss = kornia.losses.ssim_loss(
- img, img, window_size, reduction=reduction_type)
+ loss = kornia.losses.ssim_loss(img, img, window_size, reduction=reduction_type)
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
assert_allclose(loss.item(), 0.0, rtol=tol_val, atol=tol_val)
@@ -399,70 +384,69 @@ class TestSSIMLoss:
img2 = utils.tensor_to_gradcheck_var(img2) # to var
# TODO: review method since it needs `nondet_tol` in cuda sometimes.
- assert gradcheck(kornia.losses.ssim_loss,
- (img1, img2, window_size), raise_exception=True, nondet_tol=1e-8)
+ assert gradcheck(kornia.losses.ssim_loss, (img1, img2, window_size), raise_exception=True, nondet_tol=1e-8)
class TestDivergenceLoss:
- @pytest.mark.parametrize('input,target,expected', [
- (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.346574),
- (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
- ])
+
+ @pytest.mark.parametrize(
+ 'input,target,expected', [
+ (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.346574),
+ (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
+ ]
+ )
def test_js_div_loss_2d(self, device, dtype, input, target, expected):
- actual = kornia.losses.js_div_loss_2d(
- input.to(device, dtype), target.to(device, dtype))
+ actual = kornia.losses.js_div_loss_2d(input.to(device, dtype), target.to(device, dtype))
assert_allclose(actual.item(), expected)
- @pytest.mark.parametrize('input,target,expected', [
- (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.0),
- (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
- ])
+ @pytest.mark.parametrize(
+ 'input,target,expected', [
+ (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.0),
+ (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
+ ]
+ )
def test_kl_div_loss_2d(self, device, dtype, input, target, expected):
- actual = kornia.losses.kl_div_loss_2d(
- input.to(device, dtype), target.to(device, dtype))
+ actual = kornia.losses.kl_div_loss_2d(input.to(device, dtype), target.to(device, dtype))
assert_allclose(actual.item(), expected)
- @pytest.mark.parametrize('input,target,expected', [
- (torch.full((1, 1, 2, 4), 0.125),
- torch.full((1, 1, 2, 4), 0.125),
- torch.full((1, 1), 0.0)),
- (torch.full((1, 7, 2, 4), 0.125),
- torch.full((1, 7, 2, 4), 0.125),
- torch.full((1, 7), 0.0)),
- (torch.full((1, 7, 2, 4), 0.125),
- torch.zeros((1, 7, 2, 4)),
- torch.full((1, 7), 0.0)),
- (torch.zeros((1, 7, 2, 4)),
- torch.full((1, 7, 2, 4), 0.125),
- torch.full((1, 7), math.inf)),
- ])
+ @pytest.mark.parametrize(
+ 'input,target,expected', [
+ (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1), 0.0)),
+ (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7), 0.0)),
+ (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), torch.full((1, 7), 0.0)),
+ (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7), math.inf)),
+ ]
+ )
def test_kl_div_loss_2d_without_reduction(self, device, dtype, input, target, expected):
- actual = kornia.losses.kl_div_loss_2d(
- input.to(device, dtype), target.to(device, dtype), reduction='none')
+ actual = kornia.losses.kl_div_loss_2d(input.to(device, dtype), target.to(device, dtype), reduction='none')
assert_allclose(actual, expected.to(device, dtype))
- @pytest.mark.parametrize('input,target,expected', [
- (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.0),
- (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
- ])
+ @pytest.mark.parametrize(
+ 'input,target,expected', [
+ (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.0),
+ (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
+ ]
+ )
def test_noncontiguous_kl(self, device, dtype, input, target, expected):
input = input.to(device, dtype).view(input.shape[::-1]).T
target = target.to(device, dtype).view(target.shape[::-1]).T
actual = kornia.losses.kl_div_loss_2d(input, target).item()
assert_allclose(actual, expected)
- @pytest.mark.parametrize('input,target,expected', [
- (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
- (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.346574),
- (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
- ])
+ @pytest.mark.parametrize(
+ 'input,target,expected', [
+ (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.346574),
+ (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
+ ]
+ )
def test_noncontiguous_js(self, device, dtype, input, target, expected):
input = input.to(device, dtype).view(input.shape[::-1]).T
target = target.to(device, dtype).view(target.shape[::-1]).T
@@ -476,8 +460,7 @@ class TestDivergenceLoss:
# evaluate function gradient
input = utils.tensor_to_gradcheck_var(input) # to var
target = utils.tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.kl_div_loss_2d, (input, target),
- raise_exception=True)
+ assert gradcheck(kornia.losses.kl_div_loss_2d, (input, target), raise_exception=True)
def test_gradcheck_js(self, device, dtype):
input = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
@@ -486,8 +469,7 @@ class TestDivergenceLoss:
# evaluate function gradient
input = utils.tensor_to_gradcheck_var(input) # to var
target = utils.tensor_to_gradcheck_var(target) # to var
- assert gradcheck(kornia.losses.js_div_loss_2d, (input, target),
- raise_exception=True)
+ assert gradcheck(kornia.losses.js_div_loss_2d, (input, target), raise_exception=True)
def test_jit_kl(self, device, dtype):
input = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)
@@ -508,58 +490,81 @@ class TestDivergenceLoss:
class TestTotalVariation:
# Total variation of constant vectors is 0
- @pytest.mark.parametrize('input, expected', [
- (torch.ones(3, 4, 5), torch.zeros(())),
- (2 * torch.ones(2, 3, 4, 5), torch.zeros(2)),
- ])
+ @pytest.mark.parametrize(
+ 'input, expected', [
+ (torch.ones(3, 4, 5), torch.zeros(())),
+ (2 * torch.ones(2, 3, 4, 5), torch.zeros(2)),
+ ]
+ )
def test_tv_on_constant(self, device, dtype, input, expected):
actual = kornia.losses.total_variation(input.to(device, dtype))
assert_allclose(actual, expected.to(device, dtype))
# Total variation for 3D tensors
- @pytest.mark.parametrize('input, expected', [
- (torch.tensor([[[0.11747694, 0.5717714, 0.89223915, 0.2929412, 0.63556224],
- [0.5371079, 0.13416398, 0.7782737, 0.21392655, 0.1757018],
- [0.62360305, 0.8563448, 0.25304103, 0.68539226, 0.6956515],
- [0.9350611, 0.01694632, 0.78724295, 0.4760313, 0.73099905]],
-
- [[0.4788819, 0.45253807, 0.932798, 0.5721999, 0.7612051],
- [0.5455887, 0.8836531, 0.79551977, 0.6677338, 0.74293613],
- [0.4830376, 0.16420758, 0.15784949, 0.21445751, 0.34168917],
- [0.8675162, 0.5468113, 0.6117004, 0.01305223, 0.17554593]],
-
- [[0.6423703, 0.5561105, 0.54304767, 0.20339686, 0.8553698],
- [0.98024786, 0.31562763, 0.10122144, 0.17686582, 0.26260805],
- [0.20522952, 0.14523649, 0.8601968, 0.02593213, 0.7382898],
- [0.71935296, 0.9625162, 0.42287344, 0.07979459, 0.9149871]]]), torch.tensor(33.001236)),
- (torch.tensor([[[0.09094203, 0.32630223, 0.8066123],
- [0.10921168, 0.09534764, 0.48588026]]]), torch.tensor(1.6900232)),
- ])
+ @pytest.mark.parametrize(
+ 'input, expected', [
+ (
+ torch.tensor(
+ [
+ [
+ [0.11747694, 0.5717714, 0.89223915, 0.2929412, 0.63556224],
+ [0.5371079, 0.13416398, 0.7782737, 0.21392655, 0.1757018],
+ [0.62360305, 0.8563448, 0.25304103, 0.68539226, 0.6956515],
+ [0.9350611, 0.01694632, 0.78724295, 0.4760313, 0.73099905]
+ ],
+ [
+ [0.4788819, 0.45253807, 0.932798, 0.5721999, 0.7612051],
+ [0.5455887, 0.8836531, 0.79551977, 0.6677338, 0.74293613],
+ [0.4830376, 0.16420758, 0.15784949, 0.21445751, 0.34168917],
+ [0.8675162, 0.5468113, 0.6117004, 0.01305223, 0.17554593]
+ ],
+ [
+ [0.6423703, 0.5561105, 0.54304767, 0.20339686, 0.8553698],
+ [0.98024786, 0.31562763, 0.10122144, 0.17686582, 0.26260805],
+ [0.20522952, 0.14523649, 0.8601968, 0.02593213, 0.7382898],
+ [0.71935296, 0.9625162, 0.42287344, 0.07979459, 0.9149871]
+ ]
+ ]
+ ), torch.tensor(33.001236)
+ ),
+ (
+ torch.tensor([[[0.09094203, 0.32630223, 0.8066123], [0.10921168, 0.09534764, 0.48588026]]]
+ ), torch.tensor(1.6900232)
+ ),
+ ]
+ )
def test_tv_on_3d(self, device, dtype, input, expected):
actual = kornia.losses.total_variation(input.to(device, dtype))
assert_allclose(actual, expected.to(device, dtype))
# Total variation for 4D tensors
- @pytest.mark.parametrize('input, expected', [
- (torch.tensor([[[[0.8756, 0.0920],
- [0.8034, 0.3107]],
- [[0.3069, 0.2981],
- [0.9399, 0.7944]],
- [[0.6269, 0.1494],
- [0.2493, 0.8490]]],
- [[[0.3256, 0.9923],
- [0.2856, 0.9104]],
- [[0.4107, 0.4387],
- [0.2742, 0.0095]],
- [[0.7064, 0.3674],
- [0.6139, 0.2487]]]]), torch.tensor([5.0054283, 3.1870906])),
- (torch.tensor([[[[0.1104, 0.2284, 0.4371],
- [0.4569, 0.1906, 0.8035]]],
- [[[0.0552, 0.6831, 0.8310],
- [0.3589, 0.5044, 0.0802]]],
- [[[0.5078, 0.5703, 0.9110],
- [0.4765, 0.8401, 0.2754]]]]), torch.tensor([1.9565653, 2.5786452, 2.2681699])),
- ])
+ @pytest.mark.parametrize(
+ 'input, expected', [
+ (
+ torch.tensor(
+ [
+ [
+ [[0.8756, 0.0920], [0.8034, 0.3107]], [[0.3069, 0.2981], [0.9399, 0.7944]],
+ [[0.6269, 0.1494], [0.2493, 0.8490]]
+ ],
+ [
+ [[0.3256, 0.9923], [0.2856, 0.9104]], [[0.4107, 0.4387], [0.2742, 0.0095]],
+ [[0.7064, 0.3674], [0.6139, 0.2487]]
+ ]
+ ]
+ ), torch.tensor([5.0054283, 3.1870906])
+ ),
+ (
+ torch.tensor(
+ [
+ [[[0.1104, 0.2284, 0.4371], [0.4569, 0.1906, 0.8035]]],
+ [[[0.0552, 0.6831, 0.8310], [0.3589, 0.5044, 0.0802]]],
+ [[[0.5078, 0.5703, 0.9110], [0.4765, 0.8401, 0.2754]]]
+ ]
+ ), torch.tensor([1.9565653, 2.5786452, 2.2681699])
+ ),
+ ]
+ )
def test_tv_on_4d(self, device, dtype, input, expected):
actual = kornia.losses.total_variation(input.to(device, dtype))
assert_allclose(actual, expected.to(device, dtype), rtol=1e-4, atol=1e-4)
@@ -601,11 +606,11 @@ class TestTotalVariation:
def test_gradcheck(self, device, dtype):
image = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
image = utils.tensor_to_gradcheck_var(image) # to var
- assert gradcheck(kornia.losses.total_variation, (image,),
- raise_exception=True)
+ assert gradcheck(kornia.losses.total_variation, (image, ), raise_exception=True)
class TestPSNRLoss:
+
def test_smoke(self, device, dtype):
input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
@@ -668,6 +673,4 @@ class TestPSNRLoss:
target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
target = utils.tensor_to_gradcheck_var(target) # to var
- assert gradcheck(
- kornia.losses.psnr_loss, (input, target, 1.0), raise_exception=True
- )
+ assert gradcheck(kornia.losses.psnr_loss, (input, target, 1.0), raise_exception=True)
diff --git a/test/utils/test_draw.py b/test/utils/test_draw.py
index 475c06ae0..990b1a277 100644
--- a/test/utils/test_draw.py
+++ b/test/utils/test_draw.py
@@ -6,6 +6,7 @@ from kornia.utils import draw_rectangle
class TestDrawRectangle:
+
@pytest.mark.parametrize('batch', (4, 17))
@pytest.mark.parametrize('color', (torch.Tensor([1.0]), torch.Tensor([0.5])))
def test_smoke(self, device, batch, color):
@@ -47,10 +48,10 @@ class TestDrawRectangle:
points_list.append([])
for n in range(N):
points_list[b].append([])
- points_list[b][n].append(int(torch.randint(0, w - 1, (1,))))
- points_list[b][n].append(int(torch.randint(0, h - 1, (1,))))
- points_list[b][n].append(int(torch.randint(points_list[b][n][-2] + 1, w, (1,))))
- points_list[b][n].append(int(torch.randint(points_list[b][n][-2] + 1, h, (1,))))
+ points_list[b][n].append(int(torch.randint(0, w - 1, (1, ))))
+ points_list[b][n].append(int(torch.randint(0, h - 1, (1, ))))
+ points_list[b][n].append(int(torch.randint(points_list[b][n][-2] + 1, w, (1, ))))
+ points_list[b][n].append(int(torch.randint(points_list[b][n][-2] + 1, h, (1, ))))
points = torch.tensor(points_list).to(device)
diff --git a/test/utils/test_grid.py b/test/utils/test_grid.py
index 85e82acbf..461c69273 100644
--- a/test/utils/test_grid.py
+++ b/test/utils/test_grid.py
@@ -12,9 +12,7 @@ def test_create_meshgrid(device, dtype):
normalized_coordinates = False
# create the meshgrid and verify shape
- grid = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates,
- device=device, dtype=dtype)
+ grid = kornia.utils.create_meshgrid(height, width, normalized_coordinates, device=device, dtype=dtype)
assert grid.device == device
assert grid.dtype == dtype
@@ -22,32 +20,25 @@ def test_create_meshgrid(device, dtype):
# check grid corner values
assert tuple(grid[0, 0, 0].cpu().numpy()) == (0., 0.)
- assert tuple(
- grid[0, height - 1, width - 1].cpu().numpy()) == (width - 1, height - 1)
+ assert tuple(grid[0, height - 1, width - 1].cpu().numpy()) == (width - 1, height - 1)
def test_normalize_pixel_grid(device, dtype):
if device.type == 'cuda' and dtype == torch.float16:
- pytest.skip(
- '"inverse_cuda" not implemented for "Half"'
- )
+ pytest.skip('"inverse_cuda" not implemented for "Half"')
# generate input data
batch_size = 1
height, width = 2, 4
# create points grid
- grid_norm = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=True,
- device=device, dtype=dtype)
+ grid_norm = kornia.utils.create_meshgrid(height, width, normalized_coordinates=True, device=device, dtype=dtype)
assert grid_norm.device == device
assert grid_norm.dtype == dtype
grid_norm = torch.unsqueeze(grid_norm, dim=0)
- grid_pix = kornia.utils.create_meshgrid(
- height, width, normalized_coordinates=False,
- device=device, dtype=dtype)
+ grid_pix = kornia.utils.create_meshgrid(height, width, normalized_coordinates=False, device=device, dtype=dtype)
assert grid_pix.device == device
assert grid_pix.dtype == dtype
@@ -68,9 +59,7 @@ def test_create_meshgrid3d(device, dtype):
normalized_coordinates = False
# create the meshgrid and verify shape
- grid = kornia.utils.create_meshgrid3d(
- depth, height, width, normalized_coordinates,
- device=device, dtype=dtype)
+ grid = kornia.utils.create_meshgrid3d(depth, height, width, normalized_coordinates, device=device, dtype=dtype)
assert grid.device == device
assert grid.dtype == dtype
@@ -78,5 +67,4 @@ def test_create_meshgrid3d(device, dtype):
# check grid corner values
assert tuple(grid[0, 0, 0, 0].cpu().numpy()) == (0., 0., 0.)
- assert tuple(
- grid[0, depth - 1, height - 1, width - 1].cpu().numpy()) == (depth - 1, width - 1, height - 1)
+ assert tuple(grid[0, depth - 1, height - 1, width - 1].cpu().numpy()) == (depth - 1, width - 1, height - 1)
diff --git a/test/utils/test_helpers.py b/test/utils/test_helpers.py
index aef1eeca8..fc15fb971 100644
--- a/test/utils/test_helpers.py
+++ b/test/utils/test_helpers.py
@@ -8,22 +8,30 @@ from kornia.utils.helpers import _torch_inverse_cast, _torch_histc_cast
from kornia.utils.helpers import _torch_solve_cast, _torch_svd_cast
[email protected]("tensor_list,out_device,out_dtype,will_throw_error", [
- ([], torch.device('cpu'), torch.get_default_dtype(), False),
- ([None, None], torch.device('cpu'), torch.get_default_dtype(), False),
- ([torch.tensor(0, device='cpu', dtype=torch.float16), None], torch.device('cpu'), torch.float16, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float32), None], torch.device('cpu'), torch.float32, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float64), None], torch.device('cpu'), torch.float64, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float16)] * 2, torch.device('cpu'), torch.float16, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float32)] * 2, torch.device('cpu'), torch.float32, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float64)] * 2, torch.device('cpu'), torch.float64, False),
- ([torch.tensor(0, device='cpu', dtype=torch.float16),
- torch.tensor(0, device='cpu', dtype=torch.float64)], None, None, True),
- ([torch.tensor(0, device='cpu', dtype=torch.float32),
- torch.tensor(0, device='cpu', dtype=torch.float64)], None, None, True),
- ([torch.tensor(0, device='cpu', dtype=torch.float16),
- torch.tensor(0, device='cpu', dtype=torch.float32)], None, None, True),
-])
+ "tensor_list,out_device,out_dtype,will_throw_error", [
+ ([], torch.device('cpu'), torch.get_default_dtype(), False),
+ ([None, None], torch.device('cpu'), torch.get_default_dtype(), False),
+ ([torch.tensor(0, device='cpu', dtype=torch.float16), None], torch.device('cpu'), torch.float16, False),
+ ([torch.tensor(0, device='cpu', dtype=torch.float32), None], torch.device('cpu'), torch.float32, False),
+ ([torch.tensor(0, device='cpu', dtype=torch.float64), None], torch.device('cpu'), torch.float64, False),
+ ([torch.tensor(0, device='cpu', dtype=torch.float16)] * 2, torch.device('cpu'), torch.float16, False),
+ ([torch.tensor(0, device='cpu', dtype=torch.float32)] * 2, torch.device('cpu'), torch.float32, False),
+ ([torch.tensor(0, device='cpu', dtype=torch.float64)] * 2, torch.device('cpu'), torch.float64, False),
+ (
+ [torch.tensor(0, device='cpu', dtype=torch.float16),
+ torch.tensor(0, device='cpu', dtype=torch.float64)], None, None, True
+ ),
+ (
+ [torch.tensor(0, device='cpu', dtype=torch.float32),
+ torch.tensor(0, device='cpu', dtype=torch.float64)], None, None, True
+ ),
+ (
+ [torch.tensor(0, device='cpu', dtype=torch.float16),
+ torch.tensor(0, device='cpu', dtype=torch.float32)], None, None, True
+ ),
+ ]
+)
def test_extract_device_dtype(tensor_list, out_device, out_dtype, will_throw_error):
# Add GPU tests when GPU testing avaliable
if torch.cuda.is_available():
@@ -40,9 +48,8 @@ def test_extract_device_dtype(tensor_list, out_device, out_dtype, will_throw_err
class TestInverseCast(object):
- @pytest.mark.parametrize("input_shape",
- [(1, 3, 4, 4), (2, 4, 5, 5)]
- )
+
+ @pytest.mark.parametrize("input_shape", [(1, 3, 4, 4), (2, 4, 5, 5)])
def test_smoke(self, device, dtype, input_shape):
x = torch.rand(input_shape, device=device, dtype=dtype)
y = _torch_inverse_cast(x)
@@ -71,6 +78,7 @@ class TestInverseCast(object):
class TestHistcCast(object):
+
def test_smoke(self, device, dtype):
x = torch.tensor([1., 2., 1.], device=device, dtype=dtype)
y_expected = torch.tensor([0., 2., 1., 0.], device=device, dtype=dtype)
@@ -81,6 +89,7 @@ class TestHistcCast(object):
class TestSvdCast(object):
+
def test_smoke(self, device, dtype):
a = torch.randn(5, 3, 3, device=device, dtype=dtype)
u, s, v = _torch_svd_cast(a)
@@ -90,6 +99,7 @@ class TestSvdCast(object):
class TestSolveCast(object):
+
def test_smoke(self, device, dtype):
A = torch.randn(2, 3, 1, 4, 4, device=device, dtype=dtype)
B = torch.randn(2, 3, 1, 4, 6, device=device, dtype=dtype)
diff --git a/test/utils/test_image.py b/test/utils/test_image.py
index b65265f9a..cb5448ebf 100644
--- a/test/utils/test_image.py
+++ b/test/utils/test_image.py
@@ -8,23 +8,29 @@ import kornia as kornia
import kornia.testing as utils # test utils
[email protected]("input_dtype, expected_dtype",
- [(np.uint8, torch.uint8),
- (np.float32, torch.float32),
- (np.float64, torch.float64), ])
+ "input_dtype, expected_dtype", [
+ (np.uint8, torch.uint8),
+ (np.float32, torch.float32),
+ (np.float64, torch.float64),
+ ]
+)
def test_image_to_tensor_keep_dtype(input_dtype, expected_dtype):
image = np.ones((1, 3, 4, 5), dtype=input_dtype)
tensor = kornia.image_to_tensor(image)
assert tensor.dtype == expected_dtype
[email protected]("input_shape, expected",
- [((4, 4), (4, 4)),
- ((1, 4, 4), (4, 4)),
- ((1, 1, 4, 4), (4, 4)),
- ((3, 4, 4), (4, 4, 3)),
- ((2, 3, 4, 4), (2, 4, 4, 3)),
- ((1, 3, 4, 4), (4, 4, 3)), ])
+ "input_shape, expected", [
+ ((4, 4), (4, 4)),
+ ((1, 4, 4), (4, 4)),
+ ((1, 1, 4, 4), (4, 4)),
+ ((3, 4, 4), (4, 4, 3)),
+ ((2, 3, 4, 4), (2, 4, 4, 3)),
+ ((1, 3, 4, 4), (4, 4, 3)),
+ ]
+)
def test_tensor_to_image(device, input_shape, expected):
tensor = torch.ones(input_shape).to(device)
image = kornia.utils.tensor_to_image(tensor)
@@ -32,13 +38,16 @@ def test_tensor_to_image(device, input_shape, expected):
assert isinstance(image, np.ndarray)
[email protected]("input_shape, expected",
- [((4, 4), (1, 1, 4, 4)),
- ((1, 4, 4), (1, 4, 1, 4)),
- ((2, 3, 4), (1, 4, 2, 3)),
- ((4, 4, 3), (1, 3, 4, 4)),
- ((2, 4, 4, 3), (2, 3, 4, 4)),
- ((1, 4, 4, 3), (1, 3, 4, 4)), ])
+ "input_shape, expected", [
+ ((4, 4), (1, 1, 4, 4)),
+ ((1, 4, 4), (1, 4, 1, 4)),
+ ((2, 3, 4), (1, 4, 2, 3)),
+ ((4, 4, 3), (1, 3, 4, 4)),
+ ((2, 4, 4, 3), (2, 3, 4, 4)),
+ ((1, 4, 4, 3), (1, 3, 4, 4)),
+ ]
+)
def test_image_to_tensor(input_shape, expected):
image = np.ones(input_shape)
tensor = kornia.utils.image_to_tensor(image, keepdim=False)
@@ -49,13 +58,16 @@ def test_image_to_tensor(input_shape, expected):
assert_allclose(tensor, to_tensor(image))
[email protected]("input_shape, expected",
- [((4, 4), (1, 4, 4)),
- ((1, 4, 4), (4, 1, 4)),
- ((2, 3, 4), (4, 2, 3)),
- ((4, 4, 3), (3, 4, 4)),
- ((2, 4, 4, 3), (2, 3, 4, 4)),
- ((1, 4, 4, 3), (1, 3, 4, 4)), ])
+ "input_shape, expected", [
+ ((4, 4), (1, 4, 4)),
+ ((1, 4, 4), (4, 1, 4)),
+ ((2, 3, 4), (4, 2, 3)),
+ ((4, 4, 3), (3, 4, 4)),
+ ((2, 4, 4, 3), (2, 3, 4, 4)),
+ ((1, 4, 4, 3), (1, 3, 4, 4)),
+ ]
+)
def test_image_to_tensor_keepdim(input_shape, expected):
image = np.ones(input_shape)
tensor = kornia.utils.image_to_tensor(image, keepdim=True)
diff --git a/test/utils/test_metrics.py b/test/utils/test_metrics.py
index a310693f3..0cd1121f1 100644
--- a/test/utils/test_metrics.py
+++ b/test/utils/test_metrics.py
@@ -8,254 +8,148 @@ from torch.testing import assert_allclose
class TestMeanIoU:
+
def test_two_classes_perfect(self):
batch_size = 1
num_classes = 2
- actual = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 0]])
- predicted = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 0]])
+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])
+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])
mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)
- mean_iou_real = torch.tensor(
- [[1.0, 1.0]], dtype=torch.float32)
+ mean_iou_real = torch.tensor([[1.0, 1.0]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
assert_allclose(mean_iou, mean_iou_real)
def test_two_classes_perfect_batch2(self):
batch_size = 2
num_classes = 2
- actual = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)
- predicted = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)
+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)
+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)
mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)
- mean_iou_real = torch.tensor(
- [[1.0, 1.0], [1.0, 1.0]], dtype=torch.float32)
+ mean_iou_real = torch.tensor([[1.0, 1.0], [1.0, 1.0]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
assert_allclose(mean_iou, mean_iou_real)
def test_two_classes(self):
batch_size = 1
num_classes = 2
- actual = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 0]])
- predicted = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 1]])
+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])
+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]])
mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)
mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)
- mean_iou_real = torch.tensor(
- [[0.75, 0.80]], dtype=torch.float32)
+ mean_iou_real = torch.tensor([[0.75, 0.80]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
assert_allclose(mean_iou, mean_iou_real)
def test_four_classes_2d_perfect(self):
batch_size = 1
num_classes = 4
- actual = torch.tensor(
- [[[0, 0, 1, 1],
- [0, 0, 1, 1],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
- predicted = torch.tensor(
- [[[0, 0, 1, 1],
- [0, 0, 1, 1],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])
+ predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])
mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)
- mean_iou_real = torch.tensor(
- [[1.0, 1.0, 1.0, 1.0]], dtype=torch.float32)
+ mean_iou_real = torch.tensor([[1.0, 1.0, 1.0, 1.0]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
assert_allclose(mean_iou, mean_iou_real)
def test_four_classes_one_missing(self):
batch_size = 1
num_classes = 4
- actual = torch.tensor(
- [[[0, 0, 0, 0],
- [0, 0, 0, 0],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
- predicted = torch.tensor(
- [[[3, 3, 2, 2],
- [3, 3, 2, 2],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
+ actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]])
+ predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]])
mean_iou = kornia.utils.metrics.mean_iou(predicted, actual, num_classes)
- mean_iou_real = torch.tensor(
- [[0.0, 1.0, 0.5, 0.5]], dtype=torch.float32)
+ mean_iou_real = torch.tensor([[0.0, 1.0, 0.5, 0.5]], dtype=torch.float32)
assert mean_iou.shape == (batch_size, num_classes)
assert_allclose(mean_iou, mean_iou_real)
class TestConfusionMatrix:
+
def test_two_classes(self):
num_classes = 2
- actual = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 0]])
- predicted = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 1]])
+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])
+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]])
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [[[3, 1],
- [0, 4]]], dtype=torch.float32)
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[3, 1], [0, 4]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
def test_two_classes_batch2(self):
batch_size = 2
num_classes = 2
- actual = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)
- predicted = torch.tensor(
- [[1, 1, 1, 1, 0, 0, 0, 1]]).repeat(batch_size, 1)
+ actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]]).repeat(batch_size, 1)
+ predicted = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 1]]).repeat(batch_size, 1)
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [
- [[3, 1], [0, 4]],
- [[3, 1], [0, 4]]
- ], dtype=torch.float32)
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[3, 1], [0, 4]], [[3, 1], [0, 4]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
def test_three_classes(self):
num_classes = 3
- actual = torch.tensor(
- [[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]])
- predicted = torch.tensor(
- [[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])
+ actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]])
+ predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [[[4, 1, 2],
- [3, 0, 2],
- [1, 2, 1]]], dtype=torch.float32)
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[4, 1, 2], [3, 0, 2], [1, 2, 1]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
def test_four_classes_one_missing(self):
num_classes = 4
- actual = torch.tensor(
- [[3, 3, 1, 1, 2, 1, 1, 3, 2, 2, 1, 1, 2, 3, 2, 1]])
- predicted = torch.tensor(
- [[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]])
+ actual = torch.tensor([[3, 3, 1, 1, 2, 1, 1, 3, 2, 2, 1, 1, 2, 3, 2, 1]])
+ predicted = torch.tensor([[3, 2, 1, 1, 1, 1, 1, 2, 1, 3, 3, 2, 1, 1, 3, 3]])
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [[[0, 0, 0, 0],
- [0, 4, 1, 2],
- [0, 3, 0, 2],
- [0, 1, 2, 1]]], dtype=torch.float32)
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[0, 0, 0, 0], [0, 4, 1, 2], [0, 3, 0, 2], [0, 1, 2, 1]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
def test_three_classes_normalized(self):
num_classes = 3
normalized = True
- actual = torch.tensor(
- [[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]])
- predicted = torch.tensor(
- [[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])
+ actual = torch.tensor([[2, 2, 0, 0, 1, 0, 0, 2, 1, 1, 0, 0, 1, 2, 1, 0]])
+ predicted = torch.tensor([[2, 1, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 0, 0, 2, 2]])
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes, normalized)
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes, normalized)
conf_mat_real = torch.tensor(
- [[[0.5000, 0.3333, 0.4000],
- [0.3750, 0.0000, 0.4000],
- [0.1250, 0.6667, 0.2000]]], dtype=torch.float32)
+ [[[0.5000, 0.3333, 0.4000], [0.3750, 0.0000, 0.4000], [0.1250, 0.6667, 0.2000]]], dtype=torch.float32
+ )
assert_allclose(conf_mat, conf_mat_real)
def test_four_classes_2d_perfect(self):
num_classes = 4
- actual = torch.tensor(
- [[[0, 0, 1, 1],
- [0, 0, 1, 1],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
- predicted = torch.tensor(
- [[[0, 0, 1, 1],
- [0, 0, 1, 1],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
-
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [[[4, 0, 0, 0],
- [0, 4, 0, 0],
- [0, 0, 4, 0],
- [0, 0, 0, 4]]], dtype=torch.float32)
+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])
+ predicted = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])
+
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[4, 0, 0, 0], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
def test_four_classes_2d_one_class_nonperfect(self):
num_classes = 4
- actual = torch.tensor(
- [[[0, 0, 1, 1],
- [0, 0, 1, 1],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
- predicted = torch.tensor(
- [[[0, 0, 1, 1],
- [0, 3, 0, 1],
- [2, 2, 1, 3],
- [2, 2, 3, 3]]])
-
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [[[3, 0, 0, 1],
- [1, 3, 0, 0],
- [0, 0, 4, 0],
- [0, 1, 0, 3]]], dtype=torch.float32)
+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])
+ predicted = torch.tensor([[[0, 0, 1, 1], [0, 3, 0, 1], [2, 2, 1, 3], [2, 2, 3, 3]]])
+
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[3, 0, 0, 1], [1, 3, 0, 0], [0, 0, 4, 0], [0, 1, 0, 3]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
def test_four_classes_2d_one_class_missing(self):
num_classes = 4
- actual = torch.tensor(
- [[[0, 0, 1, 1],
- [0, 0, 1, 1],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
- predicted = torch.tensor(
- [[[3, 3, 1, 1],
- [3, 3, 1, 1],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
-
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [[[0, 0, 0, 4],
- [0, 4, 0, 0],
- [0, 0, 4, 0],
- [0, 0, 0, 4]]], dtype=torch.float32)
+ actual = torch.tensor([[[0, 0, 1, 1], [0, 0, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])
+ predicted = torch.tensor([[[3, 3, 1, 1], [3, 3, 1, 1], [2, 2, 3, 3], [2, 2, 3, 3]]])
+
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[0, 0, 0, 4], [0, 4, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
def test_four_classes_2d_one_class_no_predicted(self):
num_classes = 4
- actual = torch.tensor(
- [[[0, 0, 0, 0],
- [0, 0, 0, 0],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
- predicted = torch.tensor(
- [[[3, 3, 2, 2],
- [3, 3, 2, 2],
- [2, 2, 3, 3],
- [2, 2, 3, 3]]])
-
- conf_mat = kornia.utils.metrics.confusion_matrix(
- predicted, actual, num_classes)
- conf_mat_real = torch.tensor(
- [[[0, 0, 4, 4],
- [0, 0, 0, 0],
- [0, 0, 4, 0],
- [0, 0, 0, 4]]], dtype=torch.float32)
+ actual = torch.tensor([[[0, 0, 0, 0], [0, 0, 0, 0], [2, 2, 3, 3], [2, 2, 3, 3]]])
+ predicted = torch.tensor([[[3, 3, 2, 2], [3, 3, 2, 2], [2, 2, 3, 3], [2, 2, 3, 3]]])
+
+ conf_mat = kornia.utils.metrics.confusion_matrix(predicted, actual, num_classes)
+ conf_mat_real = torch.tensor([[[0, 0, 4, 4], [0, 0, 0, 0], [0, 0, 4, 0], [0, 0, 0, 4]]], dtype=torch.float32)
assert_allclose(conf_mat, conf_mat_real)
diff --git a/test/utils/test_one_hot.py b/test/utils/test_one_hot.py
index 068938de8..a71ec9db5 100644
--- a/test/utils/test_one_hot.py
+++ b/test/utils/test_one_hot.py
@@ -6,6 +6,7 @@ import kornia.testing as utils # test utils
class TestOneHot:
+
def test_smoke(self):
num_classes = 4
labels = torch.zeros(2, 2, 1, dtype=torch.int64)
diff --git a/test/utils/test_pointcloud_io.py b/test/utils/test_pointcloud_io.py
index 5ca8ed668..e62ab6b2c 100644
--- a/test/utils/test_pointcloud_io.py
+++ b/test/utils/test_pointcloud_io.py
@@ -7,6 +7,7 @@ from torch.testing import assert_allclose
class TestSaveLoadPointCloud:
+
def test_save_pointcloud(self):
height, width = 10, 8
xyz_save = torch.rand(height, width, 3)