Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

replace yapf with black (#1052)

Anthony Sottileef0bded787f9
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index a04fff4f8..65743c27c 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -15,21 +15,13 @@ repos:
- id: check-yaml
- id: pretty-format-json
- - repo: https://github.com/pre-commit/mirrors-yapf
- rev: v0.31.0
+ - repo: https://github.com/psf/black
+ rev: 21.5b1
hooks:
- - id: yapf
- name: formatting
- entry: yapf
- args: [--parallel]
- language: python
- types: [python]
+ - id: black
- repo: https://github.com/PyCQA/flake8
rev: 3.9.2
hooks:
- id: flake8
name: PEP8
- entry: flake8
- language: python
- types: [python]
diff --git a/conftest.py b/conftest.py
index f48ad9d4e..29bb0186d 100644
--- a/conftest.py
+++ b/conftest.py
@@ -19,6 +19,7 @@ def get_test_devices() -> Dict[str, torch.device]:
devices["cuda"] = torch.device("cuda:0")
if kornia.xla_is_available():
import torch_xla.core.xla_model as xm
+
devices["tpu"] = xm.xla_device()
return devices
@@ -72,8 +73,7 @@ def pytest_generate_tests(metafunc):
dtype_names = raw_value.split(',')
if device_names is not None and dtype_names is not None:
# Exclude any blacklisted device/dtype combinations.
- params = [combo for combo in product(device_names, dtype_names)
- if combo not in DEVICE_DTYPE_BLACKLIST]
+ params = [combo for combo in product(device_names, dtype_names) if combo not in DEVICE_DTYPE_BLACKLIST]
metafunc.parametrize('device_name,dtype_name', params)
elif device_names is not None:
metafunc.parametrize('device_name', device_names)
diff --git a/docs/source/conf.py b/docs/source/conf.py
index d9d4bb7df..3db3177bb 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -71,6 +71,7 @@ version = ''
if 'READTHEDOCS' not in os.environ:
# if developing locally, use pyro.__version__ as version
from kornia import __version__ # noqaE402
+
version = __version__
# release = 'master'
@@ -109,11 +110,7 @@ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# further. For a list of options available for each theme, see the
# documentation.
#
-html_theme_options = {
- 'collapse_navigation': False,
- 'display_version': True,
- 'logo_only': True,
-}
+html_theme_options = {'collapse_navigation': False, 'display_version': True, 'logo_only': True}
html_logo = '_static/img/kornia_logo.svg'
html_favicon = '_static/img/kornia_logo_mini.png'
@@ -124,12 +121,7 @@ html_favicon = '_static/img/kornia_logo_mini.png'
html_static_path = ['_static']
# html_style_path = 'css/pytorch_theme.css'
-html_context = {
- 'css_files': [
- 'https://fonts.googleapis.com/css?family=Lato',
- '_static/css/pytorch_theme.css'
- ],
-}
+html_context = {'css_files': ['https://fonts.googleapis.com/css?family=Lato', '_static/css/pytorch_theme.css']}
# -- Options for HTMLHelp output ------------------------------------------
@@ -143,15 +135,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
-
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
-
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
-
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
@@ -160,19 +149,14 @@ latex_elements = {
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
-latex_documents = [
- (master_doc, 'kornia.tex', u'Kornia', 'manual'),
-]
+latex_documents = [(master_doc, 'kornia.tex', u'Kornia', 'manual')]
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
-man_pages = [
- (master_doc, 'Kornia', u'Kornia Documentation',
- [author], 1)
-]
+man_pages = [(master_doc, 'Kornia', u'Kornia Documentation', [author], 1)]
# -- Options for Texinfo output -------------------------------------------
@@ -181,9 +165,15 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- (master_doc, 'kornia', 'Kornia Documentation',
- author, 'Kornia', 'Differentiable Computer Vision in Pytorch.',
- 'Miscellaneous'),
+ (
+ master_doc,
+ 'kornia',
+ 'Kornia Documentation',
+ author,
+ 'Kornia',
+ 'Differentiable Computer Vision in Pytorch.',
+ 'Miscellaneous',
+ )
]
@@ -197,7 +187,7 @@ intersphinx_mapping = {
examples_dir = os.path.join(current_path, "tutorials")
sphinx_gallery_conf = {
'doc_module': 'kornia',
- 'examples_dirs': [examples_dir], # path to your example scripts
+ 'examples_dirs': [examples_dir], # path to your example scripts
'gallery_dirs': ['tutorials'], # path where to save gallery generated output
'filename_pattern': './',
}
@@ -233,8 +223,7 @@ def patched_make_field(self, types, domain, items, **kw):
typename = typename.replace('long', 'python:long')
typename = typename.replace('float', 'python:float')
typename = typename.replace('type', 'python:type')
- par.extend(self.make_xrefs(self.typerolename, domain, typename,
- addnodes.literal_emphasis, **kw))
+ par.extend(self.make_xrefs(self.typerolename, domain, typename, addnodes.literal_emphasis, **kw))
else:
par += fieldtype
par += nodes.Text(')')
diff --git a/kornia/__init__.py b/kornia/__init__.py
index e968ca5d3..dd7259e6c 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -1,6 +1,7 @@
# Make sure that kornia is running on Python 3.6.0 or later
# (to avoid running into this bug: https://bugs.python.org/issue29246)
import sys
+
if sys.version_info < (3, 6, 0):
raise RuntimeError("Kornia requires Python 3.6.0 or later")
@@ -61,11 +62,8 @@ from kornia.enhance import (
adjust_hue,
adjust_saturation,
)
-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.contrib import extract_tensor_patches, max_blur_pool2d
+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 c7e3f58b6..ffa9078a1 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -1,4 +1,4 @@
-from .base import (AugmentationBase2D, AugmentationBase3D)
+from .base import AugmentationBase2D, AugmentationBase3D
from .augmentation import (
CenterCrop,
ColorJitter,
@@ -39,8 +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 883c53622..45f006979 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -44,15 +44,13 @@ from kornia.enhance import (
adjust_gamma,
Invert,
)
-from kornia.filters import (
- box_blur,
-)
+from kornia.filters import box_blur
from kornia.utils import _extract_device_dtype, create_meshgrid
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):
@@ -109,10 +107,7 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
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)
@@ -165,10 +160,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
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)
@@ -218,17 +210,18 @@ class ColorJitter(IntensityAugmentationBase2D):
def __init__(
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.,
+ brightness: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ contrast: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ saturation: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
+ hue: Union[torch.Tensor, float, Tuple[float, float], List[float]] = 0.0,
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 1.,
- keepdim: bool = False
+ p: float = 1.0,
+ 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
@@ -241,13 +234,13 @@ 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.0, 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.0, device=self._device, dtype=self._dtype
)
saturation: torch.Tensor = _range_bound(
- self.saturation, 'saturation', center=1., device=self._device, dtype=self._dtype
+ self.saturation, 'saturation', center=1.0, 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(
@@ -255,16 +248,13 @@ class ColorJitter(IntensityAugmentationBase2D):
)
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),
lambda img: adjust_contrast(img, params['contrast_factor']),
lambda img: adjust_saturation(img, params['saturation_factor']),
- lambda img: adjust_hue(img, params['hue_factor'] * 2 * pi)
+ lambda img: adjust_hue(img, params['hue_factor'] * 2 * pi),
]
jittered = input
@@ -315,23 +305,17 @@ class RandomGrayscale(IntensityAugmentationBase2D):
"""
def __init__(
- self,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.1,
- keepdim: bool = False
+ 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)
+ 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)
@@ -381,14 +365,15 @@ class RandomErasing(IntensityAugmentationBase2D):
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.,
+ value: float = 0.0,
return_transform: bool = False,
same_on_batch: bool = False,
p: float = 0.5,
- keepdim: bool = False
+ 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
@@ -410,14 +395,11 @@ class RandomErasing(IntensityAugmentationBase2D):
value=self.value,
same_on_batch=self.same_on_batch,
device=self.device,
- dtype=self.dtype
+ 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)
@@ -425,7 +407,7 @@ class RandomErasing(IntensityAugmentationBase2D):
bboxes = bbox_generator(params['xs'], params['ys'], params['widths'], params['heights'])
mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
- transformed = torch.where(mask == 1., values, input)
+ transformed = torch.where(mask == 1.0, values, input)
return transformed
@@ -477,10 +459,11 @@ class RandomPerspective(GeometricAugmentationBase2D):
same_on_batch: bool = False,
align_corners: bool = False,
p: float = 0.5,
- keepdim: bool = False
+ 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)
@@ -499,18 +482,20 @@ class RandomPerspective(GeometricAugmentationBase2D):
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))
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)
@@ -595,10 +580,11 @@ class RandomAffine(GeometricAugmentationBase2D):
align_corners: bool = False,
padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
p: float = 0.5,
- keepdim: bool = False
+ 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
@@ -610,7 +596,7 @@ class RandomAffine(GeometricAugmentationBase2D):
self.flags: Dict[str, torch.Tensor] = dict(
resample=torch.tensor(self.resample.value),
padding_mode=torch.tensor(self.padding_mode.value),
- align_corners=torch.tensor(align_corners)
+ align_corners=torch.tensor(align_corners),
)
def __repr__(self) -> str:
@@ -645,7 +631,7 @@ class RandomAffine(GeometricAugmentationBase2D):
bounds=(0, float('inf')),
check='singular',
device=self._device,
- dtype=self._dtype
+ dtype=self._dtype,
),
_range_bound(
scale[2:],
@@ -653,8 +639,8 @@ class RandomAffine(GeometricAugmentationBase2D):
bounds=(0, float('inf')),
check='singular',
device=self._device,
- dtype=self._dtype
- )
+ dtype=self._dtype,
+ ),
]
)
else:
@@ -666,39 +652,51 @@ class RandomAffine(GeometricAugmentationBase2D):
_range_bound(
shear if shear.dim() == 0 else shear[:2],
'shear-x',
- 0, (-360, 360),
+ 0,
+ (-360, 360),
device=self._device,
- dtype=self._dtype
+ 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)
+ 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),
+ transform[:, :2, :],
+ (height, width),
self.resample.name.lower(),
align_corners=self.align_corners,
- padding_mode=self.padding_mode.name.lower()
+ padding_mode=self.padding_mode.name.lower(),
)
@@ -754,14 +752,15 @@ class CenterCrop(GeometricAugmentationBase2D):
align_corners: bool = True,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False,
- p: float = 1.,
+ p: float = 1.0,
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.0, 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):
@@ -788,10 +787,7 @@ class CenterCrop(GeometricAugmentationBase2D):
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)
@@ -808,7 +804,7 @@ class CenterCrop(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] = input[i:i + 1, :, y1:y2, x1:x2]
+ out[i] = input[i : i + 1, :, y1:y2, x1:x2]
return out
else:
raise NotImplementedError(f"Not supported type: {self.cropping_mode}.")
@@ -818,7 +814,7 @@ class CenterCrop(GeometricAugmentationBase2D):
input: torch.Tensor,
transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- **kwargs
+ **kwargs,
) -> torch.Tensor:
if self.cropping_mode != 'resample':
raise NotImplementedError(
@@ -890,10 +886,11 @@ class RandomRotation(GeometricAugmentationBase2D):
same_on_batch: bool = False,
align_corners: bool = True,
p: float = 0.5,
- keepdim: bool = False
+ 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)
@@ -925,10 +922,7 @@ 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)
@@ -1006,7 +1000,7 @@ 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.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
)
self.size = size
self.padding = padding
@@ -1029,11 +1023,12 @@ class RandomCrop(GeometricAugmentationBase2D):
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]),
+ batch_shape[0],
+ (batch_shape[-2], batch_shape[-1]),
self.size,
same_on_batch=self.same_on_batch,
device=self.device,
- dtype=self.dtype
+ dtype=self.dtype,
)
def compute_padding(self, shape: torch.Size) -> List[int]:
@@ -1071,10 +1066,7 @@ class RandomCrop(GeometricAugmentationBase2D):
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)
@@ -1084,7 +1076,7 @@ class RandomCrop(GeometricAugmentationBase2D):
self.size,
mode=self.resample.name.lower(),
padding_mode='zeros',
- align_corners=self.align_corners
+ align_corners=self.align_corners,
)
elif self.cropping_mode == 'slice': # uses advanced slicing to crop
B, C, _, _ = input.shape
@@ -1094,7 +1086,7 @@ class RandomCrop(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] = input[i:i + 1, :, y1:y2, x1:x2]
+ out[i] = input[i : i + 1, :, y1:y2, x1:x2]
return out
else:
raise NotImplementedError(f"Not supported type: {self.flags['mode']}.")
@@ -1104,7 +1096,7 @@ class RandomCrop(GeometricAugmentationBase2D):
input: torch.Tensor,
transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- **kwargs
+ **kwargs,
) -> torch.Tensor:
if self.cropping_mode != 'resample':
raise NotImplementedError(
@@ -1122,7 +1114,7 @@ class RandomCrop(GeometricAugmentationBase2D):
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
params: Optional[Dict[str, torch.Tensor]] = None,
size: Optional[Tuple[int, int]] = None,
- **kwargs
+ **kwargs,
) -> torch.Tensor:
out = super().inverse(input, params, size, **kwargs)
if params is None:
@@ -1138,7 +1130,7 @@ class RandomCrop(GeometricAugmentationBase2D):
self,
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
params: Optional[Dict[str, torch.Tensor]] = None,
- return_transform: Optional[bool] = 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])
@@ -1152,8 +1144,9 @@ 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():
@@ -1218,18 +1211,18 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
self,
size: Tuple[int, int],
scale: Union[torch.Tensor, Tuple[float, float]] = (0.08, 1.0),
- ratio: Union[torch.Tensor, Tuple[float, float]] = (3. / 4., 4. / 3.),
+ ratio: Union[torch.Tensor, Tuple[float, float]] = (3.0 / 4.0, 4.0 / 3.0),
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False,
same_on_batch: bool = False,
align_corners: bool = True,
- p: float = 1.,
+ p: float = 1.0,
keepdim: bool = False,
cropping_mode: str = 'slice',
) -> 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.0, 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
@@ -1238,8 +1231,7 @@ class RandomResizedCrop(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
@@ -1251,16 +1243,22 @@ 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
+ 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]),
+ 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
+ dtype=self.dtype,
)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
@@ -1269,10 +1267,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
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)
@@ -1282,7 +1277,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
self.size,
mode=self.resample.name.lower(),
padding_mode='zeros',
- align_corners=self.align_corners
+ align_corners=self.align_corners,
)
elif self.cropping_mode == 'slice': # uses advanced slicing to crop
B, C, _, _ = input.shape
@@ -1293,10 +1288,10 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
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],
+ input[i : i + 1, :, y1:y2, x1:x2],
self.size,
interpolation=(self.resample.name).lower(),
- align_corners=self.align_corners
+ align_corners=self.align_corners,
)
return out
else:
@@ -1307,7 +1302,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
input: torch.Tensor,
transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- **kwargs
+ **kwargs,
) -> torch.Tensor:
if self.cropping_mode != 'resample':
raise NotImplementedError(
@@ -1350,8 +1345,8 @@ class Normalize(IntensityAugmentationBase2D):
mean: torch.Tensor,
std: torch.Tensor,
return_transform: bool = False,
- p: float = 1.,
- keepdim: bool = False
+ p: float = 1.0,
+ keepdim: bool = False,
) -> None:
super(Normalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
self.mean = mean
@@ -1362,10 +1357,7 @@ 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)
@@ -1399,8 +1391,8 @@ class Denormalize(IntensityAugmentationBase2D):
mean: torch.Tensor,
std: torch.Tensor,
return_transform: bool = False,
- p: float = 1.,
- keepdim: bool = False
+ p: float = 1.0,
+ keepdim: bool = False,
) -> None:
super(Denormalize, self).__init__(p=p, return_transform=return_transform, same_on_batch=True, keepdim=keepdim)
self.mean = mean
@@ -1411,10 +1403,7 @@ 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)
@@ -1474,10 +1463,11 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
return_transform: bool = False,
same_on_batch: bool = False,
p: float = 0.5,
- keepdim: bool = False
+ 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])
@@ -1487,28 +1477,29 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
self.resample = Resample.get(resample)
self.flags: Dict[str, torch.Tensor] = {
"border_type": torch.tensor(self.border_type.value),
- "interpolation": torch.tensor(self.resample.value)
+ "interpolation": torch.tensor(self.resample.value),
}
def __repr__(self) -> str:
- repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}, " +\
- f"border_type='{self.border_type.name.lower()}'"
+ repr = (
+ f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}, "
+ + f"border_type='{self.border_type.name.lower()}'"
+ )
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.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.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
)
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']
@@ -1519,7 +1510,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
angle,
direction,
border_type=self.border_type.name.lower(),
- mode=self.resample.name.lower()
+ mode=self.resample.name.lower(),
)
@@ -1568,7 +1559,7 @@ class RandomSolarize(IntensityAugmentationBase2D):
same_on_batch: bool = False,
return_transform: bool = False,
p: float = 0.5,
- keepdim: bool = False
+ 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])
@@ -1581,7 +1572,7 @@ 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.0, 1.0), device=self._device, dtype=self._dtype
)
additions = _range_bound(
self.additions, 'additions', bounds=(-0.5, 0.5), device=self._device, dtype=self._dtype
@@ -1591,10 +1582,7 @@ class RandomSolarize(IntensityAugmentationBase2D):
)
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]
@@ -1647,10 +1635,11 @@ class RandomPosterize(IntensityAugmentationBase2D):
same_on_batch: bool = False,
return_transform: bool = False,
p: float = 0.5,
- keepdim: bool = False
+ 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
@@ -1668,10 +1657,7 @@ 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'])
@@ -1715,10 +1701,11 @@ class RandomSharpness(IntensityAugmentationBase2D):
same_on_batch: bool = False,
return_transform: bool = False,
p: float = 0.5,
- keepdim: bool = False
+ 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
@@ -1730,16 +1717,13 @@ class RandomSharpness(IntensityAugmentationBase2D):
sharpness = torch.as_tensor(self.sharpness, device=self._device, dtype=self._dtype)
if sharpness.dim() == 0:
sharpness = sharpness.repeat(2)
- sharpness[0] = 0.
+ sharpness[0] = 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)
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)
@@ -1779,23 +1763,17 @@ 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)
@@ -1842,10 +1820,11 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
border_type: str = 'reflect',
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 0.5
+ p: float = 0.5,
) -> None:
- super(RandomGaussianBlur,
- self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ super(RandomGaussianBlur, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
self.kernel_size = kernel_size
self.sigma = sigma
self.border_type: BorderType = BorderType.get(border_type)
@@ -1854,10 +1833,7 @@ 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())
@@ -1866,7 +1842,7 @@ class GaussianBlur(RandomGaussianBlur):
warnings.warn(
"GaussianBlur is no longer maintained and will be removed from the future versions. "
"Please use RandomGaussianBlur instead.",
- category=DeprecationWarning
+ category=DeprecationWarning,
)
@@ -1895,23 +1871,21 @@ class RandomInvert(IntensityAugmentationBase2D):
def __init__(
self,
- max_val: torch.Tensor = torch.tensor(1.),
+ max_val: torch.Tensor = torch.tensor(1.0),
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 0.5
+ p: float = 0.5,
) -> None:
- super(RandomInvert,
- self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ super(RandomInvert, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
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)
@@ -1937,8 +1911,9 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
"""
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.)
+ super(RandomChannelShuffle, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
def __repr__(self) -> str:
return self.__class__.__name__ + f"({super().__repr__()})"
@@ -1949,10 +1924,7 @@ 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]):
@@ -1981,14 +1953,15 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
def __init__(
self,
- mean: float = 0.,
- std: float = 1.,
+ mean: float = 0.0,
+ std: float = 1.0,
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 0.5
+ p: float = 0.5,
) -> None:
- super(RandomGaussianNoise,
- self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ super(RandomGaussianNoise, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
self.mean = mean
self.std = std
@@ -2000,10 +1973,7 @@ 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
@@ -2037,10 +2007,11 @@ class RandomFisheye(GeometricAugmentationBase2D):
gamma: torch.Tensor,
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 0.5
+ p: float = 0.5,
) -> None:
- super(RandomFisheye,
- self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ super(RandomFisheye, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
self.center_x = self._check_tensor(center_x)
self.center_y = self._check_tensor(center_y)
self.gamma = self._check_tensor(gamma)
@@ -2069,10 +2040,7 @@ 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
@@ -2084,9 +2052,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) ** 0.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)
@@ -2116,16 +2084,17 @@ class RandomElasticTransform(GeometricAugmentationBase2D):
def __init__(
self,
kernel_size: Tuple[int, int] = (63, 63),
- sigma: Tuple[float, float] = (32., 32.),
- alpha: Tuple[float, float] = (1., 1.),
+ sigma: Tuple[float, float] = (32.0, 32.0),
+ alpha: Tuple[float, float] = (1.0, 1.0),
align_corners: bool = False,
mode: str = 'bilinear',
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 0.5
+ p: float = 0.5,
) -> None:
- super(RandomElasticTransform,
- self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ super(RandomElasticTransform, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
self.kernel_size = kernel_size
self.sigma = sigma
self.alpha = alpha
@@ -2143,10 +2112,7 @@ 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
@@ -2181,22 +2147,17 @@ class RandomThinPlateSpline(GeometricAugmentationBase2D):
align_corners: bool = False,
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 0.5
+ p: float = 0.5,
) -> None:
- super(RandomThinPlateSpline,
- self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ super(RandomThinPlateSpline, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
self.align_corners = align_corners
self.dist = torch.distributions.Uniform(-scale, scale)
def generate_parameters(self, shape: torch.Size) -> Dict[str, torch.Tensor]:
B, _, H, W = shape
- src = torch.tensor([[
- [-1., -1.],
- [-1., 1.],
- [1., -1.],
- [1., -1.],
- [0., 0.],
- ]]).repeat(B, 1, 1) # Bx5x2
+ src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, -1.0], [0.0, 0.0]]]).repeat(B, 1, 1) # Bx5x2
dst = src + self.dist.rsample((B, 5, 2))
return dict(src=src, dst=dst)
@@ -2204,10 +2165,7 @@ 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)
@@ -2243,10 +2201,11 @@ class RandomBoxBlur(GeometricAugmentationBase2D):
normalized: bool = True,
return_transform: bool = False,
same_on_batch: bool = False,
- p: float = 0.5
+ p: float = 0.5,
) -> None:
- super(RandomBoxBlur,
- self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ super(RandomBoxBlur, self).__init__(
+ p=p, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.0
+ )
self.kernel_size = kernel_size
self.border_type = border_type
self.normalized = normalized
@@ -2255,9 +2214,6 @@ 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 325829820..5fefd7480 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -4,7 +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,
@@ -17,11 +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):
@@ -66,14 +66,11 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
"""
def __init__(
- self,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
+ 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)
+ 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__()})"
@@ -86,10 +83,7 @@ class RandomHorizontalFlip3D(AugmentationBase3D):
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,14 +136,11 @@ class RandomVerticalFlip3D(AugmentationBase3D):
"""
def __init__(
- self,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
+ 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)
+ 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__()})"
@@ -162,10 +153,7 @@ class RandomVerticalFlip3D(AugmentationBase3D):
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])
@@ -219,14 +207,11 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
"""
def __init__(
- self,
- return_transform: bool = False,
- same_on_batch: bool = False,
- p: float = 0.5,
- keepdim: bool = False
+ 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)
+ 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__()})"
@@ -239,10 +224,7 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
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])
@@ -318,23 +300,43 @@ 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]]],
+ 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,
- 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,
+ 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
+ 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
@@ -343,9 +345,9 @@ 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 = (
@@ -378,30 +380,44 @@ 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]),
+ transform[:, :3, :],
+ (input.shape[-3], input.shape[-2], input.shape[-1]),
self.resample.name.lower(),
- align_corners=self.align_corners
+ align_corners=self.align_corners,
)
@@ -464,24 +480,29 @@ 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]]],
+ 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
+ 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}"
@@ -508,10 +529,7 @@ 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)
@@ -582,18 +600,22 @@ 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]]],
+ 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
+ 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.0, keepdim=keepdim
)
self._device, self._dtype = _extract_device_dtype([angle, direction])
self.kernel_size: Union[int, Tuple[int, int]] = kernel_size
@@ -607,14 +629,16 @@ class RandomMotionBlur3D(AugmentationBase3D):
}
def __repr__(self) -> str:
- repr = f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}, " +\
- f"border_type='{self.border_type.name.lower()}'"
+ repr = (
+ f"kernel_size={self.kernel_size}, angle={self.angle}, direction={self.direction}, "
+ + f"border_type='{self.border_type.name.lower()}'"
+ )
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
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.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
@@ -624,10 +648,7 @@ class RandomMotionBlur3D(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:
kernel_size: int = cast(int, params['ksize_factor'].unique().item())
angle = params['angle_factor']
@@ -690,13 +711,14 @@ class CenterCrop3D(AugmentationBase3D):
align_corners: bool = True,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False,
- p: float = 1.,
- keepdim: bool = False
+ p: float = 1.0,
+ 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.0, 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):
@@ -724,10 +746,7 @@ class CenterCrop3D(AugmentationBase3D):
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(
@@ -798,11 +817,11 @@ class RandomCrop3D(AugmentationBase3D):
same_on_batch: bool = False,
align_corners: bool = True,
p: float = 1.0,
- keepdim: bool = False
+ 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.0, return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p, keepdim=keepdim
)
self.size = size
self.padding = padding
@@ -824,11 +843,12 @@ class RandomCrop3D(AugmentationBase3D):
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]),
+ 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
+ dtype=self.dtype,
)
def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
@@ -877,10 +897,7 @@ class RandomCrop3D(AugmentationBase3D):
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(
@@ -891,7 +908,7 @@ class RandomCrop3D(AugmentationBase3D):
self,
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
params: Optional[Dict[str, torch.Tensor]] = None,
- return_transform: Optional[bool] = 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])
@@ -959,10 +976,11 @@ class RandomPerspective3D(AugmentationBase3D):
same_on_batch: bool = False,
align_corners: bool = False,
p: float = 0.5,
- keepdim: bool = False
+ 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)
@@ -981,25 +999,29 @@ class RandomPerspective3D(AugmentationBase3D):
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)
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]),
+ transform,
+ (input.shape[-3], input.shape[-2], input.shape[-1]),
flags=self.resample.name.lower(),
- align_corners=self.align_corners
+ align_corners=self.align_corners,
)
@@ -1044,14 +1066,11 @@ class RandomEqualize3D(AugmentationBase3D):
"""
def __init__(
- self,
- p: float = 0.5,
- return_transform: bool = False,
- same_on_batch: bool = False,
- keepdim: bool = False
+ 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)
+ 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__()})"
@@ -1060,9 +1079,6 @@ 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 365beeff2..b83a0f294 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -10,7 +10,11 @@ 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,
)
@@ -31,16 +35,18 @@ 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.0, same_on_batch: bool = False, keepdim: bool = False
+ ) -> None:
super(_BasicAugmentationBase, self).__init__()
self.p = p
self.p_batch = p_batch
self.same_on_batch = same_on_batch
self.keepdim = keepdim
self._params: Dict[str, torch.Tensor] = {}
- if p != 0. or p != 1.:
+ if p != 0.0 or p != 1.0:
self._p_gen = Bernoulli(self.p)
- if p_batch != 0. or p_batch != 1.:
+ if p_batch != 0.0 or p_batch != 1.0:
self._p_batch_gen = Bernoulli(self.p_batch)
self.set_rng_device_and_dtype(torch.device('cpu'), torch.get_default_dtype())
@@ -83,7 +89,7 @@ class _BasicAugmentationBase(nn.Module):
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
@@ -92,7 +98,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])
@@ -107,17 +113,13 @@ class _BasicAugmentationBase(nn.Module):
return _params
def apply_func(
- self,
- input: torch.Tensor,
- params: Dict[str, torch.Tensor],
+ 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( # type: ignore
- self,
- input: torch.Tensor,
- params: Optional[Dict[str, torch.Tensor]] = None, # 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)
@@ -155,8 +157,8 @@ class _AugmentationBase(_BasicAugmentationBase):
return_transform: bool = None,
same_on_batch: bool = False,
p: float = 0.5,
- p_batch: float = 1.,
- keepdim: bool = False
+ p_batch: float = 1.0,
+ keepdim: bool = False,
) -> None:
super(_AugmentationBase, self).__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
self.p = p
@@ -173,10 +175,7 @@ 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
@@ -196,7 +195,7 @@ class _AugmentationBase(_BasicAugmentationBase):
in_tensor: torch.Tensor,
in_transform: Optional[torch.Tensor], # type: ignore
params: Dict[str, torch.Tensor],
- return_transform: bool = False
+ return_transform: bool = False,
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
to_apply = params['batch_prob']
@@ -274,13 +273,12 @@ class AugmentationBase2D(_AugmentationBase):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
- assert len(mat.shape) == 3, 'Input tensor is in batch mode ' \
- 'but transformation matrix is not'
- assert mat.shape[0] == inp.shape[0], f'In batch dimension, input has {inp.shape[0]}' \
- f'but transformation matrix has {mat.shape[0]}'
+ assert len(mat.shape) == 3, 'Input tensor is in batch mode ' 'but transformation matrix is not'
+ assert mat.shape[0] == inp.shape[0], (
+ f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
+ )
elif len(inp.shape) == 3 or len(inp.shape) == 2:
- assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' \
- 'but transformation matrix is not'
+ assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' 'but transformation matrix is not'
else:
raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
@@ -341,15 +339,13 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
input: torch.Tensor,
transform: Optional[torch.Tensor] = None,
size: Optional[Tuple[int, int]] = None,
- **kwargs
+ **kwargs,
) -> torch.Tensor:
- """By default, the exact transformation as ``apply_transform`` will be used.
- """
+ """By default, the exact transformation as ``apply_transform`` will be used."""
return self.apply_transform(input, params=self._params, transform=transform)
def compute_inverse_transformation(self, transform: torch.Tensor):
- """Compute the inverse transform of given transformation matrices.
- """
+ """Compute the inverse transform of given transformation matrices."""
return _torch_inverse_cast(transform)
def inverse(
@@ -357,12 +353,9 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
params: Optional[Dict[str, torch.Tensor]] = None,
size: Optional[Tuple[int, int]] = None,
- **kwargs
+ **kwargs,
) -> torch.Tensor:
- if isinstance(input, (
- list,
- tuple,
- )):
+ if isinstance(input, (list, tuple)):
input, transform = input
else:
transform = self._transform_matrix
@@ -414,13 +407,12 @@ class AugmentationBase3D(_AugmentationBase):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 5:
- assert len(mat.shape) == 3, 'Input tensor is in batch mode ' \
- 'but transformation matrix is not'
- assert mat.shape[0] == inp.shape[0], f'In batch dimension, input has {inp.shape[0]}' \
- f'but transformation matrix has {mat.shape[0]}'
+ assert len(mat.shape) == 3, 'Input tensor is in batch mode ' 'but transformation matrix is not'
+ assert mat.shape[0] == inp.shape[0], (
+ f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
+ )
elif len(inp.shape) == 3 or len(inp.shape) == 4:
- assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' \
- 'but transformation matrix is not'
+ assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' 'but transformation matrix is not'
else:
raise ValueError(f'Unrecognized output shape. Expected 3, 4 or 5, got {len(inp.shape)}')
@@ -457,13 +449,12 @@ class MixAugmentationBase(_BasicAugmentationBase):
if isinstance(input, tuple):
inp, mat = input
if len(inp.shape) == 4:
- assert len(mat.shape) == 3, 'Input tensor is in batch mode ' \
- 'but transformation matrix is not'
- assert mat.shape[0] == inp.shape[0], f'In batch dimension, input has {inp.shape[0]}' \
- f'but transformation matrix has {mat.shape[0]}'
+ assert len(mat.shape) == 3, 'Input tensor is in batch mode ' 'but transformation matrix is not'
+ assert mat.shape[0] == inp.shape[0], (
+ f'In batch dimension, input has {inp.shape[0]}' f'but transformation matrix has {mat.shape[0]}'
+ )
elif len(inp.shape) == 3 or len(inp.shape) == 2:
- assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' \
- 'but transformation matrix is not'
+ assert len(mat.shape) == 2, 'Input tensor is in non-batch mode ' 'but transformation matrix is not'
else:
raise ValueError(f'Unrecognized output shape. Expected 2, 3, or 4, got {len(inp.shape)}')
@@ -473,18 +464,12 @@ class MixAugmentationBase(_BasicAugmentationBase):
return _transform_input(input)
def apply_transform( # type: ignore
- self,
- input: torch.Tensor,
- label: torch.Tensor, # type: ignore
- params: Dict[str, torch.Tensor]
+ self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
) -> Tuple[torch.Tensor, torch.Tensor]:
raise NotImplementedError
def apply_func( # type: ignore
- self,
- in_tensor: torch.Tensor,
- label: torch.Tensor, # type: ignore
- params: Dict[str, torch.Tensor]
+ self, in_tensor: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
) -> Tuple[torch.Tensor, torch.Tensor]:
to_apply = params['batch_prob']
@@ -502,10 +487,7 @@ class MixAugmentationBase(_BasicAugmentationBase):
return output, label
def forward( # type: ignore
- self,
- input: torch.Tensor,
- label: torch.Tensor, # type: ignore
- params: Optional[Dict[str, torch.Tensor]] = None,
+ self, input: torch.Tensor, label: torch.Tensor, params: Optional[Dict[str, torch.Tensor]] = None # type: ignore
) -> Tuple[torch.Tensor, torch.Tensor]:
in_tensor = self.__unpack_input__(input)
ori_shape = in_tensor.shape
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 1ec4e89b2..ecfc5765f 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -59,8 +59,7 @@ class VideoSequential(nn.Sequential):
if isinstance(aug, MixAugmentationBase):
raise NotImplementedError(f"MixAugmentations are not supported at this moment. Got {aug}.")
self.data_format = data_format.upper()
- assert self.data_format in ["BCTHW", "BTCHW"], \
- f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`."
+ assert self.data_format in ["BCTHW", "BTCHW"], f"Only `BCTHW` and `BTCHW` are supported. Got `{data_format}`."
self._temporal_channel: int
if self.data_format == "BCTHW":
self._temporal_channel = 2
@@ -70,7 +69,7 @@ class VideoSequential(nn.Sequential):
def __infer_channel_exclusive_batch_shape__(self, input: torch.Tensor) -> torch.Size:
batch_shape: torch.Size = input.shape
# Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size")
- return cast(torch.Size, batch_shape[:self._temporal_channel] + batch_shape[self._temporal_channel + 1:])
+ return cast(torch.Size, batch_shape[: self._temporal_channel] + batch_shape[self._temporal_channel + 1 :])
def __repeat_param_across_channels__(self, param: torch.Tensor, frame_num: int) -> torch.Tensor:
"""Repeat parameters across channels.
diff --git a/kornia/augmentation/functional/__temp__.py b/kornia/augmentation/functional/__temp__.py
index f89514f11..0f0550580 100644
--- a/kornia/augmentation/functional/__temp__.py
+++ b/kornia/augmentation/functional/__temp__.py
@@ -8,17 +8,16 @@ 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
+ 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)
diff --git a/kornia/augmentation/functional/functional.py b/kornia/augmentation/functional/functional.py
index fd64ef84a..5df5ad6ef 100644
--- a/kornia/augmentation/functional/functional.py
+++ b/kornia/augmentation/functional/functional.py
@@ -5,19 +5,36 @@ 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,
- sharpness
+ 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
@@ -114,8 +131,10 @@ def apply_color_jitter(input: torch.Tensor, params: Dict[str, torch.Tensor]) ->
"""
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
@@ -217,8 +236,9 @@ 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)
@@ -263,10 +283,11 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Di
out_data: torch.Tensor = warp_affine(
x_data,
- transform[:, :2, :], (height, width),
+ transform[:, :2, :],
+ (height, width),
resample_name,
align_corners=align_corners,
- padding_mode=padding_mode
+ padding_mode=padding_mode,
)
return out_data.view_as(input)
@@ -290,8 +311,12 @@ 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
@@ -428,7 +453,7 @@ def apply_erase_rectangles(input: torch.Tensor, params: Dict[str, torch.Tensor])
bboxes = bbox_generator(params['xs'], params['ys'], params['widths'], params['heights'])
mask = bbox_to_mask(bboxes, w, h) # Returns B, H, W
mask = mask.unsqueeze(1).repeat(1, c, 1, 1).to(input) # Transform to B, c, H, W
- transformed = torch.where(mask == 1., values, input)
+ transformed = torch.where(mask == 1.0, values, input)
return transformed
@@ -649,8 +674,9 @@ def apply_equalize(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
@_deprecation_wrapper
@_validate_input
-def apply_mixup(input: torch.Tensor, labels: torch.Tensor,
- params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
+def apply_mixup(
+ input: torch.Tensor, labels: torch.Tensor, params: Dict[str, torch.Tensor]
+) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Apply mixup to images in a batch.
MixUp augmentation strategy: overlap images with different alpha values.
@@ -697,17 +723,19 @@ def apply_mixup(input: torch.Tensor, labels: torch.Tensor,
labels = torch.stack(
[
labels.to(input.dtype),
- labels_permute.to(input.dtype), params['mixup_lambdas'].to(labels.device, input.dtype)
+ labels_permute.to(input.dtype),
+ params['mixup_lambdas'].to(labels.device, input.dtype),
],
- dim=-1
+ dim=-1,
).to(labels.device)
return inputs, labels
@_deprecation_wrapper
@_validate_input
-def apply_cutmix(input: torch.Tensor, labels: torch.Tensor,
- params: Dict[str, torch.Tensor]) -> Tuple[torch.Tensor, torch.Tensor]:
+def apply_cutmix(
+ input: torch.Tensor, labels: torch.Tensor, params: Dict[str, torch.Tensor]
+) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Apply cutmix to images in a batch.
CutMix augmentation strategy: patches are cut and pasted among training images where the ground
@@ -770,9 +798,7 @@ def apply_cutmix(input: torch.Tensor, labels: torch.Tensor,
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)
+ 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 f8247361d..f78500231 100644
--- a/kornia/augmentation/functional/functional3d.py
+++ b/kornia/augmentation/functional/functional3d.py
@@ -4,15 +4,20 @@ 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
+ crop_by_boxes3d,
+ warp_perspective3d,
+ get_perspective_transform3d,
+ rotate3d,
+ get_affine_matrix3d,
+ deg2rad,
)
-from kornia.enhance import (equalize3d)
+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
@@ -200,9 +205,16 @@ 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
@@ -407,8 +419,9 @@ 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 9df7f9d97..640c66c75 100644
--- a/kornia/augmentation/mix_augmentation.py
+++ b/kornia/augmentation/mix_augmentation.py
@@ -8,10 +8,7 @@ from kornia.constants import Resample, BorderType
from kornia.geometry import infer_box_shape, bbox_to_mask
from . import random_generator as rg
from .base import MixAugmentationBase
-from .utils import (
- _infer_batch_shape,
- _shape_validation,
-)
+from .utils import _infer_batch_shape, _shape_validation
class RandomMixUp(MixAugmentationBase):
@@ -86,9 +83,9 @@ class RandomMixUp(MixAugmentationBase):
lambda_val: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
same_on_batch: bool = False,
p: float = 1.0,
- keepdim: bool = False
+ keepdim: bool = False,
) -> None:
- super(RandomMixUp, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
+ super(RandomMixUp, self).__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.lambda_val = lambda_val
def __repr__(self) -> str:
@@ -97,17 +94,17 @@ class RandomMixUp(MixAugmentationBase):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
if self.lambda_val is None:
- lambda_val = torch.tensor([0., 1.], device=self.device, dtype=self.dtype)
+ lambda_val = torch.tensor([0.0, 1.0], device=self.device, dtype=self.dtype)
else:
- lambda_val = cast(torch.Tensor, self.lambda_val) if isinstance(self.lambda_val, torch.Tensor) else \
- torch.tensor(self.lambda_val, device=self.device, dtype=self.dtype)
+ lambda_val = (
+ cast(torch.Tensor, self.lambda_val)
+ if isinstance(self.lambda_val, torch.Tensor)
+ else 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( # type: ignore
- self,
- input: torch.Tensor,
- label: torch.Tensor, # type: ignore
- params: Dict[str, torch.Tensor]
+ self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
) -> 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))
@@ -117,9 +114,10 @@ class RandomMixUp(MixAugmentationBase):
out_labels = torch.stack(
[
label.to(input.dtype),
- labels_permute.to(input.dtype), params['mixup_lambdas'].to(label.device, input.dtype)
+ labels_permute.to(input.dtype),
+ params['mixup_lambdas'].to(label.device, input.dtype),
],
- dim=-1
+ dim=-1,
).to(label.device)
return inputs, out_labels
@@ -209,10 +207,10 @@ class RandomCutMix(MixAugmentationBase):
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
+ p: float = 1.0,
+ keepdim: bool = False,
) -> None:
- super(RandomCutMix, self).__init__(p=1., p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
+ super(RandomCutMix, self).__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim)
self.height = height
self.width = width
self.num_mix = num_mix
@@ -228,15 +226,21 @@ class RandomCutMix(MixAugmentationBase):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
if self.beta is None:
- beta = torch.tensor(1., device=self.device, dtype=self.dtype)
+ beta = torch.tensor(1.0, device=self.device, dtype=self.dtype)
else:
- beta = cast(torch.Tensor, self.beta) if isinstance(self.beta, torch.Tensor) else \
- torch.tensor(self.beta, device=self.device, dtype=self.dtype)
+ beta = (
+ cast(torch.Tensor, self.beta)
+ if isinstance(self.beta, torch.Tensor)
+ else torch.tensor(self.beta, device=self.device, dtype=self.dtype)
+ )
if self.cut_size is None:
- cut_size = torch.tensor([0., 1.], device=self.device, dtype=self.dtype)
+ cut_size = torch.tensor([0.0, 1.0], device=self.device, dtype=self.dtype)
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)
+ 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,
@@ -245,14 +249,11 @@ class RandomCutMix(MixAugmentationBase):
cut_size=cut_size,
num_mix=self.num_mix,
beta=beta,
- same_on_batch=self.same_on_batch
+ 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]
+ self, input: torch.Tensor, label: torch.Tensor, params: Dict[str, torch.Tensor] # type: ignore
) -> Tuple[torch.Tensor, torch.Tensor]:
height, width = input.size(2), input.size(3)
num_mixes = params['mix_pairs'].size(0)
@@ -272,9 +273,7 @@ class RandomCutMix(MixAugmentationBase):
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)
+ 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 8cd67f89f..628e5fa2f 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -6,13 +6,7 @@ from torch.distributions import Bernoulli
from kornia.constants import Resample, BorderType, SamplePadding
from kornia.geometry import bbox_generator
-from ..utils import (
- _adapted_sampling,
- _adapted_uniform,
- _adapted_beta,
- _joint_range_check,
- _common_param_check,
-)
+from ..utils import _adapted_sampling, _adapted_uniform, _adapted_beta, _joint_range_check, _common_param_check
from kornia.utils import _extract_device_dtype
@@ -21,7 +15,7 @@ def random_prob_generator(
p: float = 0.5,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
r"""Generate random probabilities for a batch of inputs.
@@ -44,7 +38,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
@@ -57,7 +51,7 @@ def random_color_jitter_generator(
hue: Optional[torch.Tensor] = None,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Generate random color jiter parameters for a batch of images.
@@ -90,27 +84,27 @@ def random_color_jitter_generator(
"""
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([brightness, contrast, hue, saturation])
- brightness = torch.as_tensor([0., 0.] if brightness is None else brightness, device=device, dtype=dtype)
- contrast = torch.as_tensor([0., 0.] if contrast is None else contrast, device=device, dtype=dtype)
- hue = torch.as_tensor([0., 0.] if hue is None else hue, device=device, dtype=dtype)
- saturation = torch.as_tensor([0., 0.] if saturation is None else saturation, device=device, dtype=dtype)
+ brightness = torch.as_tensor([0.0, 0.0] if brightness is None else brightness, device=device, dtype=dtype)
+ contrast = torch.as_tensor([0.0, 0.0] if contrast is None else contrast, device=device, dtype=dtype)
+ hue = torch.as_tensor([0.0, 0.0] if hue is None else hue, device=device, dtype=dtype)
+ saturation = torch.as_tensor([0.0, 0.0] if saturation is None else saturation, device=device, dtype=dtype)
_joint_range_check(brightness, "brightness", (0, 2))
_joint_range_check(contrast, "contrast", (0, float('inf')))
_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()
+ order=torch.randperm(4, device=_device, dtype=_dtype).long(),
)
@@ -121,7 +115,7 @@ def random_perspective_generator(
distortion_scale: torch.Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``perspective`` for a random perspective transform.
@@ -143,20 +137,17 @@ def random_perspective_generator(
The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
- assert distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1, \
- f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}."
- 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 (
+ distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1
+ ), f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}."
+ 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],
- ]],
+ [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
device=distortion_scale.device,
- dtype=distortion_scale.dtype
+ dtype=distortion_scale.dtype,
).expand(batch_size, -1, -1)
# generate random offset not larger than half of the image
@@ -167,8 +158,10 @@ 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(
@@ -189,7 +182,7 @@ def random_affine_generator(
shear: Optional[torch.Tensor] = None,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``affine`` for a random affine transform.
@@ -225,54 +218,57 @@ def random_affine_generator(
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(degrees, "degrees")
- assert isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0, \
- f"`width` and `height` must be positive integers. Got {width}, {height}."
+ assert (
+ isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0
+ ), f"`width` and `height` must be positive integers. Got {width}, {height}."
_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
if scale is not None:
scale = scale.to(device=device, dtype=dtype)
- assert len(scale.shape) == 1 and (len(scale) == 2 or len(scale) == 4), \
- f"`scale` shall have 2 or 4 elements. Got {scale}."
+ 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)
if translate is not None:
translate = translate.to(device=device, dtype=dtype)
- assert 0. <= translate[0] <= 1. and 0. <= translate[1] <= 1. and translate.shape == torch.Size([2]), \
- f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}."
+ assert (
+ 0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])
+ ), 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)
+ _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
+ _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
],
- dim=-1
+ 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 - 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:
@@ -286,7 +282,7 @@ def random_rotation_generator(
degrees: torch.Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``rotate`` for a random rotate transform.
@@ -308,8 +304,10 @@ def random_rotation_generator(
_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
+ (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)
@@ -323,7 +321,7 @@ def random_crop_generator(
resize_to: Optional[Tuple[int, int]] = None,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
@@ -391,8 +389,9 @@ def random_crop_generator(
"If `size` is a tensor, it must be shaped as (B, 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}."
+ 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()
x_diff = input_size[1] - size[:, 1] + 1
@@ -410,36 +409,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}."
+ 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],
- ]],
+ [[[0, 0], [resize_to[1] - 1, 0], [resize_to[1] - 1, resize_to[0] - 1], [0, resize_to[0] - 1]]],
device=_device,
- dtype=_dtype
+ dtype=_dtype,
).repeat(batch_size, 1, 1)
_input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
@@ -454,7 +454,7 @@ def random_crop_size_generator(
ratio: torch.Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
@@ -484,8 +484,9 @@ def random_crop_size_generator(
_common_param_check(batch_size, same_on_batch)
_joint_range_check(scale, "scale")
_joint_range_check(ratio, "ratio")
- assert len(size) == 2 and type(size[0]) == int and size[1] > 0 and type(size[1]) == int and size[1] > 0, \
- f"'height' and 'width' must be integers. Got {size}."
+ assert (
+ len(size) == 2 and type(size[0]) == int and size[1] > 0 and type(size[1]) == int and size[1] > 0
+ ), f"'height' and 'width' must be integers. Got {size}."
_device, _dtype = _extract_device_dtype([scale, ratio])
@@ -513,10 +514,10 @@ def random_crop_size_generator(
if not cond_bool.all():
# Fallback to center crop
in_ratio = float(size[0]) / float(size[1])
- if (in_ratio < ratio.min()):
+ if in_ratio < ratio.min():
h_ct = torch.tensor(size[0], device=device, dtype=dtype)
w_ct = torch.round(h_ct / ratio.min())
- elif (in_ratio > ratio.min()):
+ elif in_ratio > ratio.min():
w_ct = torch.tensor(size[1], device=device, dtype=dtype)
h_ct = torch.round(w_ct * ratio.min())
else: # whole image
@@ -537,10 +538,10 @@ def random_rectangles_params_generator(
width: int,
scale: torch.Tensor,
ratio: torch.Tensor,
- value: float = 0.,
+ value: float = 0.0,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```erasing``` transformation for erasing transform.
@@ -568,60 +569,86 @@ def random_rectangles_params_generator(
"""
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([ratio, scale])
- 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 isinstance(value, (int, float)) and value >= 0 and value <= 1, \
- f"'value' must be a number between 0 - 1. Got {value}."
+ 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 (
+ isinstance(value, (int, float)) and value >= 0 and value <= 1
+ ), f"'value' must be a number between 0 - 1. Got {value}."
_joint_range_check(scale, 'scale', bounds=(0, float('inf')))
_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)
+ if ratio[0] < 1.0 and ratio[1] > 1.0:
+ 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
+ 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()
+ .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
+ (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.tensor(height, device=device, dtype=dtype)
+ torch.max(
+ torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, 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.tensor(width, device=device, dtype=dtype)
+ torch.max(
+ torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, 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
+ (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
+ (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)
@@ -632,7 +659,7 @@ def random_rectangles_params_generator(
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)
+ values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype),
)
@@ -657,15 +684,14 @@ 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:
+ 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], \
- f"Crop size must be smaller than input size. Got ({height}, {width}) and {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]
+ ), f"Crop size must be smaller than input size. Got ({height}, {width}) and {size}."
# unpack input sizes
dst_h, dst_w = size
@@ -686,23 +712,13 @@ 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
+ [[[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
+ [[[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)
@@ -717,7 +733,7 @@ def random_motion_blur_generator(
direction: torch.Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for motion blur.
@@ -749,30 +765,34 @@ def random_motion_blur_generator(
_device, _dtype = _extract_device_dtype([angle, direction])
if isinstance(kernel_size, int):
- assert kernel_size >= 3 and kernel_size % 2 == 1, \
- f"`kernel_size` must be odd and greater than 3. Got {kernel_size}."
+ assert (
+ kernel_size >= 3 and kernel_size % 2 == 1
+ ), f"`kernel_size` must be odd and greater than 3. Got {kernel_size}."
ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype)
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)
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
)
@@ -782,7 +802,7 @@ def random_solarize_generator(
additions: torch.Tensor = torch.tensor([-0.1, 0.1]),
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Generate random solarize parameters for a batch of images.
@@ -813,18 +833,22 @@ 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),
- additions_factor=additions_factor.to(device=_device, dtype=_dtype)
+ additions_factor=additions_factor.to(device=_device, dtype=_dtype),
)
@@ -833,7 +857,7 @@ def random_posterize_generator(
bits: torch.Tensor = torch.tensor([3, 5]),
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Generate random posterize parameters for a batch of images.
@@ -854,7 +878,7 @@ 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
+ (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))
@@ -862,10 +886,10 @@ def random_posterize_generator(
def random_sharpness_generator(
batch_size: int,
- sharpness: torch.Tensor = torch.tensor([0, 1.]),
+ sharpness: torch.Tensor = torch.tensor([0, 1.0]),
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Generate random sharpness parameters for a batch of images.
@@ -887,8 +911,10 @@ def random_sharpness_generator(
_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
+ (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))
@@ -900,7 +926,7 @@ def random_mixup_generator(
lambda_val: Optional[torch.Tensor] = None,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Generate mixup indexes and lambdas for a batch of inputs.
@@ -928,7 +954,7 @@ def random_mixup_generator(
"""
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([lambda_val])
- lambda_val = torch.as_tensor([0., 1.] if lambda_val is None else lambda_val, device=device, dtype=dtype)
+ lambda_val = torch.as_tensor([0.0, 1.0] if lambda_val is None else lambda_val, device=device, dtype=dtype)
_joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))
batch_probs: torch.Tensor = random_prob_generator(
@@ -936,13 +962,13 @@ 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(
mixup_pairs=mixup_pairs.to(device=_device, dtype=torch.long),
- mixup_lambdas=mixup_lambdas.to(device=_device, dtype=_dtype)
+ mixup_lambdas=mixup_lambdas.to(device=_device, dtype=_dtype),
)
@@ -956,7 +982,7 @@ def random_cutmix_generator(
cut_size: Optional[torch.Tensor] = None,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Generate cutmix indexes and lambdas for a batch of inputs.
@@ -1018,49 +1044,61 @@ def random_cutmix_generator(
[ 97., 69.]]]])}
"""
_device, _dtype = _extract_device_dtype([beta, cut_size])
- beta = torch.as_tensor(1. if beta is None else beta, device=device, dtype=dtype)
- cut_size = torch.as_tensor([0., 1.] if cut_size is None else cut_size, device=device, dtype=dtype)
- assert num_mix >= 1 and isinstance(num_mix, (int,)), \
- f"`num_mix` must be an integer greater than 1. Got {num_mix}."
- assert type(height) == int and height > 0 and type(width) == int and width > 0, \
- f"'height' and 'width' must be integers. Got {height}, {width}."
+ beta = torch.as_tensor(1.0 if beta is None else beta, device=device, dtype=dtype)
+ cut_size = torch.as_tensor([0.0, 1.0] if cut_size is None else cut_size, device=device, dtype=dtype)
+ assert num_mix >= 1 and isinstance(num_mix, (int,)), f"`num_mix` must be an integer greater than 1. Got {num_mix}."
+ assert (
+ type(height) == int and height > 0 and type(width) == int and width > 0
+ ), f"'height' and 'width' must be integers. Got {height}, {width}."
_joint_range_check(cut_size, 'cut_size', bounds=(0, 1))
_common_param_check(batch_size, same_on_batch)
if batch_size == 0:
return dict(
mix_pairs=torch.zeros([0, 3], device=_device, dtype=torch.long),
- crop_src=torch.zeros([0, 4, 2], device=_device, dtype=torch.long)
+ crop_src=torch.zeros([0, 4, 2], device=_device, dtype=torch.long),
)
batch_probs: torch.Tensor = random_prob_generator(
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])
- cutmix_rate = torch.sqrt(1. - cutmix_betas) * batch_probs
+ cutmix_rate = torch.sqrt(1.0 - cutmix_betas) * batch_probs
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]
# Reserve at least 1 pixel for cropping.
- x_start = _adapted_uniform(
- _gen_shape, torch.zeros_like(cut_width, device=device, dtype=dtype),
- (width - cut_width - 1).to(device=device, dtype=dtype), same_on_batch
- ).floor().to(device=device, dtype=_dtype)
- y_start = _adapted_uniform(
- _gen_shape, torch.zeros_like(cut_height, device=device, dtype=dtype),
- (height - cut_height - 1).to(device=device, dtype=dtype), same_on_batch
- ).floor().to(device=device, dtype=_dtype)
+ x_start = (
+ _adapted_uniform(
+ _gen_shape,
+ torch.zeros_like(cut_width, device=device, dtype=dtype),
+ (width - cut_width - 1).to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+ .floor()
+ .to(device=device, dtype=_dtype)
+ )
+ y_start = (
+ _adapted_uniform(
+ _gen_shape,
+ torch.zeros_like(cut_height, device=device, dtype=dtype),
+ (height - cut_height - 1).to(device=device, dtype=dtype),
+ same_on_batch,
+ )
+ .floor()
+ .to(device=device, dtype=_dtype)
+ )
crop_src = bbox_generator(x_start.squeeze(), y_start.squeeze(), cut_width, cut_height)
@@ -1069,5 +1107,5 @@ def random_cutmix_generator(
return dict(
mix_pairs=mix_pairs.to(device=_device, dtype=torch.long),
- crop_src=crop_src.floor().to(device=_device, dtype=_dtype)
+ crop_src=crop_src.floor().to(device=_device, dtype=_dtype),
)
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 8f9b1ce90..a8596e196 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -6,11 +6,7 @@ import torch
from kornia.constants import Resample, BorderType
from kornia.geometry import bbox_generator3d
-from ..utils import (
- _adapted_uniform,
- _joint_range_check,
- _tuple_range_reader,
-)
+from ..utils import _adapted_uniform, _joint_range_check, _tuple_range_reader
from kornia.utils import _extract_device_dtype
@@ -19,7 +15,7 @@ def random_rotation_generator3d(
degrees: torch.Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``rotate`` for a random rotate transform.
@@ -39,14 +35,14 @@ 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)
+ roll=roll.to(device=_device, dtype=_dtype),
)
@@ -96,16 +92,16 @@ def random_affine_generator3d(
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
- 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}."
+ 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}."
_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
@@ -114,11 +110,11 @@ def random_affine_generator3d(
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),
+ _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
+ dim=1,
)
else:
scale = torch.ones(batch_size, device=device, dtype=dtype).repeat(1, 3)
@@ -132,28 +128,28 @@ def random_affine_generator3d(
# 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)
+ _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
+ 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 - 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)
@@ -167,7 +163,7 @@ def random_affine_generator3d(
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)
+ szy=szy.to(device=_device, dtype=_dtype),
)
@@ -178,7 +174,7 @@ def random_motion_blur_generator3d(
direction: torch.Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for motion blur.
@@ -206,32 +202,35 @@ def random_motion_blur_generator3d(
_device, _dtype = _extract_device_dtype([angle, direction])
_joint_range_check(direction, 'direction', (-1, 1))
if isinstance(kernel_size, int):
- assert kernel_size >= 3 and kernel_size % 2 == 1, \
- f"`kernel_size` must be odd and greater than 3. Got {kernel_size}."
+ assert (
+ kernel_size >= 3 and kernel_size % 2 == 1
+ ), f"`kernel_size` must be odd and greater than 3. Got {kernel_size}."
ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype).int()
elif isinstance(kernel_size, tuple):
- 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}."
+ 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,
- 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)}")
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)
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype),
)
@@ -241,7 +240,7 @@ def center_crop_generator3d(
height: int,
width: int,
size: Tuple[int, int, int],
- device: torch.device = torch.device('cpu')
+ device: torch.device = torch.device('cpu'),
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
@@ -261,22 +260,17 @@ def center_crop_generator3d(
Note:
No random number will be generated.
"""
- if not isinstance(size, (
- tuple,
- list,
- )) and len(size) == 3:
+ 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}."
- assert depth >= size[0] and height >= size[1] and width >= size[2], \
- f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {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}."
+ assert (
+ depth >= size[0] and height >= size[1] and width >= size[2]
+ ), f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}."
if batch_size == 0:
- return dict(
- src=torch.zeros([0, 8, 3]),
- dst=torch.zeros([0, 8, 3]),
- )
+ return dict(src=torch.zeros([0, 8, 3]), dst=torch.zeros([0, 8, 3]))
# unpack input sizes
dst_d, dst_h, dst_w = size
src_d, src_h, src_w = (depth, height, width)
@@ -313,7 +307,7 @@ def center_crop_generator3d(
]
],
device=device,
- dtype=torch.long
+ dtype=torch.long,
).expand(batch_size, -1, -1)
# [x, y, z] destination
@@ -333,7 +327,7 @@ def center_crop_generator3d(
]
],
device=device,
- dtype=torch.long
+ dtype=torch.long,
).expand(batch_size, -1, -1)
return dict(src=points_src, dst=points_dst)
@@ -345,7 +339,7 @@ def random_crop_generator3d(
resize_to: Optional[Tuple[int, int, int]] = None,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
@@ -376,9 +370,15 @@ def random_crop_generator3d(
"If `size` is a tensor, it must be shaped as (B, 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}."
+ 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}."
x_diff = input_size[2] - size[:, 2] + 1
y_diff = input_size[1] - size[:, 1] + 1
@@ -397,33 +397,42 @@ 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}."
+ 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(
[
[
@@ -438,7 +447,7 @@ def random_crop_generator3d(
]
],
device=_device,
- dtype=_dtype
+ dtype=_dtype,
).repeat(batch_size, 1, 1)
return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
@@ -474,26 +483,27 @@ def random_perspective_generator3d(
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
- assert distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1, \
- f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}"
+ assert (
+ distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1
+ ), f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}"
_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],
+ [0.0, 0, 0],
[width - 1, 0, 0],
[width - 1, height - 1, 0],
[0, height - 1, 0],
- [0., 0, depth - 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
+ dtype=dtype,
).expand(batch_size, -1, -1)
# generate random offset not larger than half of the image
@@ -504,27 +514,20 @@ 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
+ 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],
- ]],
+ [[[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
+ 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)
+ end_points=end_points.to(device=_device, dtype=_dtype),
)
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index c6cf1f88f..e488260e6 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -6,14 +6,42 @@ 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 22728c5e6..fcb6bcdca 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -22,7 +22,7 @@ def _validate_input(f: Callable) -> Callable:
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)
@@ -55,8 +55,7 @@ def _validate_input3d(f: Callable) -> Callable:
def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
- r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)
- """
+ r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)"""
if isinstance(input, tuple):
tensor = _transform_input(input[0])
else:
@@ -65,8 +64,7 @@ def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tens
def _infer_batch_shape3d(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
- r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)
- """
+ r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)"""
if isinstance(input, tuple):
tensor = _transform_input3d(input[0])
else:
@@ -132,8 +130,9 @@ def _validate_input_dtype(input: torch.Tensor, accepted_dtypes: List) -> None:
raise TypeError(f"Expected input of {accepted_dtypes}. Got {input.dtype}")
-def _transform_output_shape(output: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
- shape: Tuple) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+def _transform_output_shape(
+ output: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], shape: Tuple
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
Args:
input: torch.Tensor
@@ -153,19 +152,19 @@ def _transform_output_shape(output: Union[torch.Tensor, Tuple[torch.Tensor, torc
if trans_matrix is not None:
if len(out_tensor.shape) > len(shape): # if output is broadcasted
- assert trans_matrix.shape[0] == 1, f'Dimension 0 of transformation matrix is ' \
- f'expected to be 1, got {trans_matrix.shape[0]}'
+ assert trans_matrix.shape[0] == 1, (
+ f'Dimension 0 of transformation matrix is ' f'expected to be 1, got {trans_matrix.shape[0]}'
+ )
trans_matrix = trans_matrix.squeeze(0)
for dim in range(len(out_tensor.shape) - len(shape)):
- assert out_tensor.shape[0] == 1, f'Dimension {dim} of input is ' \
- f'expected to be 1, got {out_tensor.shape[0]}'
+ assert out_tensor.shape[0] == 1, f'Dimension {dim} of input is ' f'expected to be 1, got {out_tensor.shape[0]}'
out_tensor = out_tensor.squeeze(0)
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
@@ -227,7 +226,7 @@ def _adapted_uniform(
low: Union[float, int, torch.Tensor],
high: Union[float, int, torch.Tensor],
same_on_batch: bool = False,
- epsilon: float = 1e-6
+ epsilon: float = 1e-6,
) -> torch.Tensor:
r"""The uniform sampling function that accepts 'same_on_batch'.
@@ -238,10 +237,7 @@ def _adapted_uniform(
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,
- ]
+ [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)
@@ -255,9 +251,9 @@ def _adapted_beta(
shape: Union[Tuple, torch.Size],
a: Union[float, int, torch.Tensor],
b: Union[float, int, torch.Tensor],
- same_on_batch: bool = False
+ same_on_batch: bool = False,
) -> torch.Tensor:
- r""" The beta sampling function that accepts 'same_on_batch'.
+ r"""The beta sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).
By default, same_on_batch is set to False.
@@ -266,10 +262,7 @@ def _adapted_beta(
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,
- ]
+ [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)
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 929e441c5..4ab49efe1 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -13,14 +13,13 @@ def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
def _range_bound(
factor: Union[torch.Tensor, float, Tuple[float, float], List[float]],
name: str,
- center: float = 0.,
+ center: float = 0.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()
+ dtype: torch.dtype = torch.get_default_dtype(),
) -> torch.Tensor:
- r"""Check inputs and compute the corresponding factor bounds
- """
+ r"""Check inputs and compute the corresponding factor bounds"""
if not isinstance(factor, (torch.Tensor)):
factor = torch.tensor(factor, device=device, dtype=dtype)
factor_bound: torch.Tensor
@@ -31,7 +30,7 @@ def _range_bound(
# Should be something other than clamp
# Currently, single value factor will not out of scope as long as the user provided it.
# Note: I personally think throw an error will be better than a coarse clamp.
- factor_bound = factor.repeat(2) * torch.tensor([-1., 1.], device=factor.device, dtype=factor.dtype) + center
+ factor_bound = factor.repeat(2) * torch.tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center
factor_bound = factor_bound.clamp(bounds[0], bounds[1])
else:
factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)
@@ -59,8 +58,7 @@ def _joint_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[
raise ValueError(f"{name}[0] should be smaller than {name}[1] got {ranged_factor}")
else:
raise TypeError(
- f"{name} should be a tensor with length 2 whose values between {bounds}. "
- f"Got {ranged_factor}."
+ f"{name} should be a tensor with length 2 whose values between {bounds}. " f"Got {ranged_factor}."
)
@@ -69,7 +67,7 @@ def _singular_range_check(
name: str,
bounds: Optional[Tuple[float, float]] = None,
skip_none: bool = False,
- mode: str = '2d'
+ mode: str = '2d',
) -> None:
"""check if bounds[0] <= ranged_factor[0] <= bounds[1] and bounds[0] <= ranged_factor[1] <= bounds[1]"""
if mode == '2d':
@@ -98,7 +96,7 @@ def _tuple_range_reader(
input_range: Union[torch.Tensor, float, tuple],
target_size: int,
device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None
+ dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
"""
Given target_size, it will generate the corresponding (target_size, 2) range tensor for element-wise params.
@@ -115,19 +113,30 @@ 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)):
+ 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)
- elif isinstance(input_range, (tuple, list)) and len(input_range) == target_shape[0] \
- and all([isinstance(x, (float, int)) for x in input_range]):
+ elif (
+ isinstance(input_range, (tuple, list))
+ and len(input_range) == target_shape[0]
+ and all([isinstance(x, (float, int)) for x in input_range])
+ ):
input_range_tmp = torch.tensor([(-s, s) for s in input_range], device=device, dtype=dtype)
- elif isinstance(input_range, (tuple, list)) and len(input_range) == target_shape[0] \
- and all([isinstance(x, (tuple, list)) for x in input_range]):
+ elif (
+ isinstance(input_range, (tuple, list))
+ and len(input_range) == target_shape[0]
+ and all([isinstance(x, (tuple, list)) for x in input_range])
+ ):
input_range_tmp = torch.tensor(input_range, device=device, dtype=dtype)
else:
@@ -143,7 +152,7 @@ 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.0, 1.0], device=input_range.device, dtype=input_range.dtype
)
input_range_tmp = input_range_tmp.repeat(target_shape[0], 1)
diff --git a/kornia/color/hls.py b/kornia/color/hls.py
index 5423a04cf..0f9f226d8 100644
--- a/kornia/color/hls.py
+++ b/kornia/color/hls.py
@@ -42,7 +42,7 @@ 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))
+ l < 0.5, deltac / (maxc + minc), deltac / (torch.tensor(2.0) - (maxc + minc))
) # saturation
hi: torch.Tensor = torch.zeros_like(deltac)
@@ -51,14 +51,14 @@ def rgb_to_hls(image: torch.Tensor) -> torch.Tensor:
hi[imax == 1] = (((b - r) / deltac) + 2)[imax == 1]
hi[imax == 2] = (((r - g) / deltac) + 4)[imax == 2]
- h: torch.Tensor = 2. * math.pi * (60. * hi) / 360. # hue [0, 2*pi]
+ h: torch.Tensor = 2.0 * math.pi * (60.0 * hi) / 360.0 # hue [0, 2*pi]
image_hls: torch.Tensor = torch.stack([h, l, s], dim=-3)
# 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.0, device=image_hls.device, dtype=image_hls.dtype), image_hls
)
return image_hls
@@ -92,21 +92,18 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:
kr = (0 + h / 30) % 12
kg = (8 + h / 30) % 12
kb = (4 + h / 30) % 12
- a = s * torch.min(l, torch.tensor(1.) - l)
+ a = s * torch.min(l, torch.tensor(1.0) - l)
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
+ torch.min(torch.min(kr - torch.tensor(3.0), torch.tensor(9.0) - 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
+ torch.min(torch.min(kg - torch.tensor(3.0), torch.tensor(9.0) - 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
+ torch.min(torch.min(kb - torch.tensor(3.0), torch.tensor(9.0) - 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 2b168c8ff..9a00048ba 100644
--- a/kornia/color/hsv.py
+++ b/kornia/color/hsv.py
@@ -47,11 +47,7 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
gc: torch.Tensor = maxc_tmp[..., 1, :, :]
bc: torch.Tensor = maxc_tmp[..., 2, :, :]
- h = torch.stack([
- bc - gc,
- 2.0 * deltac + rc - bc,
- 4.0 * deltac + gc - rc,
- ], dim=-3)
+ h = torch.stack([bc - gc, 2.0 * deltac + rc - bc, 4.0 * deltac + gc - rc], dim=-3)
h = torch.gather(h, dim=-3, index=max_indices[..., None, :, :])
h = h.squeeze(-3)
@@ -91,33 +87,14 @@ def hsv_to_rgb(image: torch.Tensor) -> torch.Tensor:
hi: torch.Tensor = torch.floor(h * 6) % 6
f: torch.Tensor = ((h * 6) % 6) - hi
- one: torch.Tensor = torch.tensor(1.).to(image.device)
+ one: torch.Tensor = torch.tensor(1.0).to(image.device)
p: torch.Tensor = v * (one - s)
q: torch.Tensor = v * (one - f * s)
t: torch.Tensor = v * (one - (one - f) * s)
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,
- ), dim=-3)
+ out = torch.stack((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)
return out
diff --git a/kornia/color/lab.py b/kornia/color/lab.py
index e5d17c8a2..2508ccee7 100644
--- a/kornia/color/lab.py
+++ b/kornia/color/lab.py
@@ -5,6 +5,7 @@ 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
@@ -41,21 +42,21 @@ 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.0, 1.08883], device=xyz_im.device, dtype=xyz_im.dtype)[..., :, None, None]
xyz_normalized = torch.div(xyz_im, xyz_ref_white)
threshold = 0.008856
- power = torch.pow(xyz_normalized.clamp(min=threshold), 1 / 3.)
- scale = 7.787 * xyz_normalized + 4. / 29.
+ power = torch.pow(xyz_normalized.clamp(min=threshold), 1 / 3.0)
+ scale = 7.787 * xyz_normalized + 4.0 / 29.0
xyz_int = torch.where(xyz_normalized > threshold, power, scale)
x: torch.Tensor = xyz_int[..., 0, :, :]
y: torch.Tensor = xyz_int[..., 1, :, :]
z: torch.Tensor = xyz_int[..., 2, :, :]
- L: torch.Tensor = (116. * y) - 16.
- a: torch.Tensor = 500. * (x - y)
- _b: torch.Tensor = 200. * (y - z)
+ L: torch.Tensor = (116.0 * y) - 16.0
+ a: torch.Tensor = 500.0 * (x - y)
+ _b: torch.Tensor = 200.0 * (y - z)
out: torch.Tensor = torch.stack([L, a, _b], dim=-3)
@@ -86,22 +87,22 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
a: torch.Tensor = image[..., 1, :, :]
_b: torch.Tensor = image[..., 2, :, :]
- fy = (L + 16.) / 116.
- fx = (a / 500.) + fy
- fz = fy - (_b / 200.)
+ fy = (L + 16.0) / 116.0
+ fx = (a / 500.0) + fy
+ fz = fy - (_b / 200.0)
# if color data out of range: Z < 0
- fz = fz.clamp(min=0.)
+ fz = fz.clamp(min=0.0)
fxyz = torch.stack([fx, fy, fz], dim=-3)
# Convert from Lab to XYZ
power = torch.pow(fxyz, 3.0)
- scale = (fxyz - 4. / 29.) / 7.787
- xyz = torch.where(fxyz > .2068966, power, scale)
+ scale = (fxyz - 4.0 / 29.0) / 7.787
+ xyz = torch.where(fxyz > 0.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.0, 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)
@@ -114,7 +115,7 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
# Clip to 0,1 https://www.w3.org/Graphics/Color/srgb
if clip:
- rgb_im = torch.clamp(rgb_im, min=0., max=1.)
+ rgb_im = torch.clamp(rgb_im, min=0.0, max=1.0)
return rgb_im
diff --git a/kornia/color/luv.py b/kornia/color/luv.py
index 2cbf98c20..1e9e1ab8e 100644
--- a/kornia/color/luv.py
+++ b/kornia/color/luv.py
@@ -5,6 +5,7 @@ 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
@@ -46,10 +47,10 @@ 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.0 * torch.pow(y.clamp(min=threshold), 1.0 / 3.0) - 16.0, 903.3 * y)
# Compute reference white point
- xyz_ref_white: Tuple[float, float, float] = (.95047, 1., 1.08883)
+ xyz_ref_white: Tuple[float, float, float] = (0.95047, 1.0, 1.08883)
u_w: float = (4 * xyz_ref_white[0]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2])
v_w: float = (9 * xyz_ref_white[1]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2])
@@ -92,7 +93,7 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
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)
+ xyz_ref_white: Tuple[float, float, float] = (0.95047, 1.0, 1.08883)
u_w: float = (4 * xyz_ref_white[0]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2])
v_w: float = (9 * xyz_ref_white[1]) / (xyz_ref_white[0] + 15 * xyz_ref_white[1] + 3 * xyz_ref_white[2])
@@ -101,7 +102,7 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
c: torch.Tensor = 3 * y * (5 * d - 3)
z: torch.Tensor = ((a - 4) * c - 15 * a * d * y) / (12 * d + eps)
- x: torch.Tensor = -(c / (d + eps) + 3. * z)
+ x: torch.Tensor = -(c / (d + eps) + 3.0 * z)
xyz_im: torch.Tensor = torch.stack([x, y, z], -3)
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index 40d617f32..5bd291420 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -141,7 +141,7 @@ def rgba_to_rgb(image: torch.Tensor) -> torch.Tensor:
r, g, b, a = torch.chunk(image, image.shape[-3], dim=-3)
# compute new channels
- a_one = torch.tensor(1.) - a
+ a_one = torch.tensor(1.0) - a
r_new: torch.Tensor = a_one * r + a * r
g_new: torch.Tensor = a_one * g + a * g
b_new: torch.Tensor = a_one * b + a * b
diff --git a/kornia/constants.py b/kornia/constants.py
index 6f1d78198..ab9089530 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -10,7 +10,6 @@ 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/__init__.py b/kornia/contrib/__init__.py
index 514c09b04..711254f4d 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,9 +1,4 @@
from .extract_patches import ExtractTensorPatches, extract_tensor_patches
from .max_blur_pool import MaxBlurPool2d, max_blur_pool2d
-__all__ = [
- "extract_tensor_patches",
- "max_blur_pool2d",
- "ExtractTensorPatches",
- "MaxBlurPool2d",
-]
+__all__ = ["extract_tensor_patches", "max_blur_pool2d", "ExtractTensorPatches", "MaxBlurPool2d"]
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 408b733fc..002280c95 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -68,7 +68,7 @@ class ExtractTensorPatches(nn.Module):
self,
window_size: Union[int, Tuple[int, int]],
stride: Optional[Union[int, Tuple[int, int]]] = 1,
- padding: Optional[Union[int, Tuple[int, int]]] = 0
+ padding: Optional[Union[int, Tuple[int, int]]] = 0,
) -> None:
super(ExtractTensorPatches, self).__init__()
self.window_size: Tuple[int, int] = _pair(window_size)
@@ -99,7 +99,7 @@ def extract_tensor_patches(
input: torch.Tensor,
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]] = 1,
- padding: Union[int, Tuple[int, int]] = 0
+ padding: Union[int, Tuple[int, int]] = 0,
) -> torch.Tensor:
r"""Function that extract patches from tensors and stack them.
diff --git a/kornia/contrib/max_blur_pool.py b/kornia/contrib/max_blur_pool.py
index 7477d9a5a..b15d471ee 100644
--- a/kornia/contrib/max_blur_pool.py
+++ b/kornia/contrib/max_blur_pool.py
@@ -3,16 +3,9 @@ from typing import Tuple
import warnings
import torch
import torch.nn as nn # For doctest
-from kornia.filters.blur_pool import (
- MaxBlurPool2D,
- BlurPool2D, # For doctest
- max_blur_pool2d as _max_blur_pool2d
-)
+from kornia.filters.blur_pool import MaxBlurPool2D, BlurPool2D, max_blur_pool2d as _max_blur_pool2d # For doctest
-__all__ = [
- "max_blur_pool2d",
- "MaxBlurPool2d",
-]
+__all__ = ["max_blur_pool2d", "MaxBlurPool2d"]
class MaxBlurPool2d(MaxBlurPool2D):
@@ -24,7 +17,7 @@ class MaxBlurPool2d(MaxBlurPool2D):
"`MaxBlurPool2d` is deprecated and will be removed after > 0.6. "
"Please use `kornia.filters.MaxBlurPool2D instead.`",
DeprecationWarning,
- stacklevel=2
+ stacklevel=2,
)
@@ -37,6 +30,6 @@ def max_blur_pool2d(input: torch.Tensor, kernel_size: int, ceil_mode: bool = Fal
"`max_blur_pool2d` is deprecated and will be removed after > 0.6. "
"Please use `kornia.filters.max_blur_pool2d instead.`",
DeprecationWarning,
- stacklevel=2
+ 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 b227a0494..b60301bf3 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -34,19 +34,14 @@ __all__ = [
def adjust_saturation_raw(input: torch.Tensor, saturation_factor: Union[float, torch.Tensor]) -> torch.Tensor:
- r"""Adjust color saturation of an image. Expecting input to be in hsv format already.
- """
+ r"""Adjust color saturation of an image. Expecting input to be in hsv format already."""
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,
- )):
+ 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)}"
+ f"The saturation_factor should be a float number or torch.Tensor." f"Got {type(saturation_factor)}"
)
if isinstance(saturation_factor, float):
@@ -121,8 +116,7 @@ def adjust_saturation(input: torch.Tensor, saturation_factor: Union[float, torch
def adjust_hue_raw(input: torch.Tensor, hue_factor: Union[float, torch.Tensor]) -> torch.Tensor:
- r"""Adjust hue of an image. Expecting input to be in hsv format already.
- """
+ r"""Adjust hue of an image. Expecting input to be in hsv format already."""
if not isinstance(input, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
@@ -207,7 +201,7 @@ def adjust_hue(input: torch.Tensor, hue_factor: Union[float, torch.Tensor]) -> t
def adjust_gamma(
- input: torch.Tensor, gamma: Union[float, torch.Tensor], gain: Union[float, torch.Tensor] = 1.
+ input: torch.Tensor, gamma: Union[float, torch.Tensor], gain: Union[float, torch.Tensor] = 1.0
) -> torch.Tensor:
r"""Perform gamma correction on an image.
@@ -306,10 +300,7 @@ def adjust_contrast(input: torch.Tensor, contrast_factor: Union[float, torch.Ten
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,
- )):
+ 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):
@@ -363,10 +354,7 @@ def adjust_brightness(input: torch.Tensor, brightness_factor: Union[float, torch
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,
- )):
+ 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):
@@ -387,7 +375,7 @@ def adjust_brightness(input: torch.Tensor, brightness_factor: Union[float, torch
def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5) -> torch.Tensor:
- r""" For each pixel in the image, select the pixel if the value is less than the threshold.
+ r"""For each pixel in the image, select the pixel if the value is less than the threshold.
Otherwise, subtract 1.0 from the pixel.
Args:
@@ -402,15 +390,13 @@ 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,
- )):
+ 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, \
- f"threshholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}"
+ assert (
+ input.size(0) == len(thresholds) and len(thresholds.shape) == 1
+ ), f"threshholds must be a 1-d vector of shape ({input.size(0)},). Got {thresholds}"
# TODO: I am not happy about this line, but no easy to do batch-wise operation
thresholds = thresholds.to(input.device).to(input.dtype)
thresholds = torch.stack([x.expand(*input.shape[1:]) for x in thresholds])
@@ -421,7 +407,7 @@ def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5)
def solarize(
input: torch.Tensor,
thresholds: Union[float, torch.Tensor] = 0.5,
- additions: Optional[Union[float, torch.Tensor]] = None
+ additions: Optional[Union[float, torch.Tensor]] = None,
) -> torch.Tensor:
r"""For each pixel in the image less than threshold.
@@ -456,36 +442,32 @@ def solarize(
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,
- )):
+ 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,
- )):
+ 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)
- assert torch.all((additions < 0.5) * (additions > -0.5)), \
- f"The value of 'addition' is between -0.5 and 0.5. Got {additions}."
+ assert torch.all(
+ (additions < 0.5) * (additions > -0.5)
+ ), f"The value of 'addition' is between -0.5 and 0.5. Got {additions}."
if isinstance(additions, torch.Tensor) and len(additions.shape) != 0:
- assert input.size(0) == len(additions) and len(additions.shape) == 1, \
- f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}"
+ assert (
+ input.size(0) == len(additions) and len(additions.shape) == 1
+ ), f"additions must be a 1-d vector of shape ({input.size(0)},). Got {additions}"
# TODO: I am not happy about this line, but no easy to do batch-wise operation
additions = additions.to(input.device).to(input.dtype)
additions = torch.stack([x.expand(*input.shape[1:]) for x in additions])
input = input + additions
- input = input.clamp(0., 1.)
+ input = input.clamp(0.0, 1.0)
return _solarize(input, thresholds)
@@ -518,10 +500,7 @@ 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):
@@ -538,10 +517,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.0
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.0
def _posterize_one(input: torch.Tensor, bits: torch.Tensor):
# Single bits value condition
@@ -559,16 +538,18 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
if len(bits.shape) == 1:
input = _to_bchw(input)
- assert bits.shape[0] == input.shape[0], \
- f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}."
+ assert (
+ bits.shape[0] == input.shape[0]
+ ), f"Batch size must be equal between bits and input. Got {bits.shape[0]}, {input.shape[0]}."
for i in range(input.shape[0]):
res.append(_posterize_one(input[i], bits[i]))
return torch.stack(res, dim=0)
- assert bits.shape == input.shape[:len(bits.shape)], \
- f"Batch and channel must be equal between bits and input. Got {bits.shape}, {input.shape[:len(bits.shape)]}."
- _input = input.view(-1, *input.shape[len(bits.shape):])
+ assert (
+ bits.shape == input.shape[: len(bits.shape)]
+ ), f"Batch and channel must be equal between bits and input. Got {bits.shape}, {input.shape[:len(bits.shape)]}."
+ _input = input.view(-1, *input.shape[len(bits.shape) :])
_bits = bits.flatten()
for i in range(input.shape[0]):
res.append(_posterize_one(_input[i], _bits[i]))
@@ -609,13 +590,17 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
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
degenerate = torch.nn.functional.conv2d(input, kernel, bias=None, stride=1, groups=input.size(1))
- degenerate = torch.clamp(degenerate, 0., 1.)
+ degenerate = torch.clamp(degenerate, 0.0, 1.0)
# For the borders of the resulting image, fill in the values of the original image.
mask = torch.ones_like(degenerate)
@@ -644,13 +629,13 @@ def _blend_one(input1: torch.Tensor, input2: torch.Tensor, factor: torch.Tensor)
if isinstance(factor, torch.Tensor):
assert len(factor.size()) == 0, f"Factor shall be a float or single element tensor. Got {factor}."
- if factor == 0.:
+ if factor == 0.0:
return input1
- if factor == 1.:
+ if factor == 1.0:
return input2
diff = (input2 - input1) * factor
res = input1 + diff
- if factor > 0. and factor < 1.:
+ if factor > 0.0 and factor < 1.0:
return res
return torch.clamp(res, 0, 1)
@@ -678,9 +663,9 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
min_ = im.min()
max_ = im.max()
- if min_.item() < 0. and not torch.isclose(min_, torch.tensor(0., dtype=min_.dtype)):
+ if min_.item() < 0.0 and not torch.isclose(min_, torch.tensor(0.0, dtype=min_.dtype)):
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)):
+ if max_.item() > 1.0 and not torch.isclose(max_, torch.tensor(1.0, dtype=max_.dtype)):
raise ValueError(f"Values in the input tensor must lower or equal to 1.0. Found {max_.item()}.")
ndims = len(im.shape)
@@ -703,7 +688,7 @@ def _scale_channel(im: torch.Tensor) -> torch.Tensor:
result = torch.gather(_build_lut(histo, step), 0, im.flatten().long())
result = result.reshape_as(im)
- return result / 255.
+ return result / 255.0
def equalize(input: torch.Tensor) -> torch.Tensor:
@@ -907,7 +892,7 @@ class AdjustGamma(nn.Module):
torch.Size([2, 5, 3, 3])
"""
- def __init__(self, gamma: Union[float, torch.Tensor], gain: Union[float, torch.Tensor] = 1.) -> None:
+ def __init__(self, gamma: Union[float, torch.Tensor], gain: Union[float, torch.Tensor] = 1.0) -> None:
super(AdjustGamma, self).__init__()
self.gamma: Union[float, torch.Tensor] = gamma
self.gain: Union[float, torch.Tensor] = gain
@@ -1011,7 +996,7 @@ class Invert(nn.Module):
torch.Size([1, 3, 4, 4])
"""
- def __init__(self, max_val: torch.Tensor = torch.tensor(1.)) -> None:
+ def __init__(self, max_val: torch.Tensor = torch.tensor(1.0)) -> None:
super(Invert, self).__init__()
if not isinstance(max_val, nn.Parameter):
self.register_buffer("max_val", max_val)
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 56b4fffaf..7ea8c4dbc 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -1,10 +1,7 @@
import torch
import torch.nn as nn
-__all__ = [
- "add_weighted",
- "AddWeighted",
-]
+__all__ = ["add_weighted", "AddWeighted"]
def add_weighted(src1: torch.Tensor, alpha: float, src2: torch.Tensor, beta: float, gamma: float) -> torch.Tensor:
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 17e43cb91..493093734 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -13,9 +13,9 @@ 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.
@@ -53,7 +53,9 @@ def _compute_tiles(imgs: torch.Tensor,
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)
+ .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]
@@ -84,9 +86,10 @@ def _compute_interpolation_tiles(padded_imgs: torch.Tensor, tile_size: Tuple[int
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)
+ 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
@@ -98,7 +101,9 @@ def _my_histc(tiles: torch.Tensor, bins: int) -> torch.Tensor:
return _torch_histc_cast(tiles, bins=bins, min=0, max=1)
-def _compute_luts(tiles_x_im: torch.Tensor, num_bins: int = 256, clip: float = 40., diff: bool = False) -> torch.Tensor:
+def _compute_luts(
+ tiles_x_im: torch.Tensor, num_bins: int = 256, clip: float = 40.0, diff: bool = False
+) -> torch.Tensor:
r"""Compute luts for a batched set of tiles.
Same approach as in OpenCV (https://github.com/opencv/opencv/blob/master/modules/imgproc/src/clahe.cpp)
@@ -128,7 +133,7 @@ def _compute_luts(tiles_x_im: torch.Tensor, num_bins: int = 256, clip: float = 4
histos = histogram(tiles, bins, torch.tensor(0.001)).squeeze()
histos *= pixels
- if clip > 0.:
+ if clip > 0.0:
max_val: float = max(clip * pixels // num_bins, 1)
histos.clamp_(max=max_val)
clipped: torch.Tensor = pixels - histos.sum(1)
@@ -182,19 +187,20 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
# create a tensor with dims: interp_patches height and width x 4 x num channels x bins in the histograms
# the tensor is init to -1 to denote non init hists
luts_x_interp_tiles: torch.Tensor = torch.full( # B x GH x GW x 4 x C x 256
- (num_imgs, gh, gw, 4, c, luts.shape[-1]), -1, dtype=interp_tiles.dtype, device=interp_tiles.device)
+ (num_imgs, gh, gw, 4, c, luts.shape[-1]), -1, dtype=interp_tiles.dtype, device=interp_tiles.device
+ )
# corner regions
- luts_x_interp_tiles[:, 0::gh - 1, 0::gw - 1, 0] = luts[:, 0::max(gh // 2 - 1, 1), 0::max(gw // 2 - 1, 1)]
+ luts_x_interp_tiles[:, 0 :: gh - 1, 0 :: gw - 1, 0] = luts[:, 0 :: max(gh // 2 - 1, 1), 0 :: max(gw // 2 - 1, 1)]
# border region (h)
- luts_x_interp_tiles[:, 1:-1, 0::gw - 1, 0] = luts[:, j_idxs[:, 0], 0::max(gw // 2 - 1, 1)]
- luts_x_interp_tiles[:, 1:-1, 0::gw - 1, 1] = luts[:, j_idxs[:, 2], 0::max(gw // 2 - 1, 1)]
+ luts_x_interp_tiles[:, 1:-1, 0 :: gw - 1, 0] = luts[:, j_idxs[:, 0], 0 :: max(gw // 2 - 1, 1)]
+ luts_x_interp_tiles[:, 1:-1, 0 :: gw - 1, 1] = luts[:, j_idxs[:, 2], 0 :: max(gw // 2 - 1, 1)]
# border region (w)
- 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]]
+ 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
@@ -223,19 +229,28 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
# equalize tiles
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)
+ preinterp_tiles_equalized = (
+ torch.gather(mapped_luts, 5, flatten_interp_tiles) # B x GH x GW x 4 x C x TH x TW
+ .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.0 * 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.0 * 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
@@ -249,7 +264,7 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
tiles_equalized[:, 1:-1, 1:-1] = torch.addcmul(b, tih, torch.sub(t, b))
# corner regions
- tiles_equalized[:, 0::gh - 1, 0::gw - 1] = preinterp_tiles_equalized[:, 0::gh - 1, 0::gw - 1, 0]
+ tiles_equalized[:, 0 :: gh - 1, 0 :: gw - 1] = preinterp_tiles_equalized[:, 0 :: gh - 1, 0 :: gw - 1, 0]
# border region (h)
t, b, _, _ = preinterp_tiles_equalized[:, 1:-1, 0].unbind(2)
@@ -264,10 +279,10 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
tiles_equalized[:, gw - 1, 1:-1] = torch.addcmul(r, tiw, torch.sub(l, r))
# same type as the input
- return tiles_equalized.div(255.)
+ return tiles_equalized.div(255.0)
-def equalize_clahe(input: torch.Tensor, clip_limit: float = 40., grid_size: Tuple[int, int] = (8, 8)) -> torch.Tensor:
+def equalize_clahe(input: torch.Tensor, clip_limit: float = 40.0, grid_size: Tuple[int, int] = (8, 8)) -> torch.Tensor:
r"""Apply clahe equalization on the input tensor.
NOTE: Lut computation uses the same approach as in OpenCV, in next versions this can change.
@@ -324,9 +339,7 @@ def equalize_clahe(input: torch.Tensor, clip_limit: float = 40., grid_size: Tupl
# the size of the tiles must be even in order to divide them into 4 tiles for the interpolation
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
+ interp_tiles: torch.Tensor = _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
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index 015665258..72a2345f9 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -2,16 +2,12 @@ from typing import Tuple
import torch
-__all__ = [
- "histogram",
- "histogram2d",
-]
+__all__ = ["histogram", "histogram2d"]
-def marginal_pdf(values: torch.Tensor,
- bins: torch.Tensor,
- sigma: torch.Tensor,
- epsilon: float = 1e-10) -> Tuple[torch.Tensor, 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.
@@ -123,11 +119,7 @@ def histogram(x: torch.Tensor, bins: torch.Tensor, bandwidth: torch.Tensor, epsi
def histogram2d(
- x1: torch.Tensor,
- x2: torch.Tensor,
- bins: torch.Tensor,
- bandwidth: torch.Tensor,
- epsilon: float = 1e-10
+ 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.
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 19a75efec..eab75b931 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -5,13 +5,7 @@ from typing import Union
import torch
import torch.nn as nn
-__all__ = [
- "normalize",
- "normalize_min_max",
- "denormalize",
- "Normalize",
- "Denormalize",
-]
+__all__ = ["normalize", "normalize_min_max", "denormalize", "Normalize", "Denormalize"]
class Normalize(nn.Module):
@@ -242,7 +236,7 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Union
return out.view(shape)
-def normalize_min_max(x: torch.Tensor, min_val: float = 0., max_val: float = 1., eps: float = 1e-6) -> torch.Tensor:
+def normalize_min_max(x: torch.Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> torch.Tensor:
r"""Normalise an image tensor by MinMax and re-scales the value between a range.
The data is normalised using the following formulation:
@@ -287,5 +281,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 7e345dbbd..86770ab25 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -6,12 +6,7 @@ import torch.nn as nn
from kornia.utils.helpers import _torch_svd_cast
-__all__ = [
- "zca_mean",
- "zca_whiten",
- "linear_transform",
- "ZCAWhitening",
-]
+__all__ = ["zca_mean", "zca_whiten", "linear_transform", "ZCAWhitening"]
class ZCAWhitening(nn.Module):
@@ -73,7 +68,7 @@ class ZCAWhitening(nn.Module):
eps: float = 1e-6,
unbiased: bool = True,
detach_transforms: bool = True,
- compute_inv: bool = False
+ compute_inv: bool = False,
) -> None:
super(ZCAWhitening, self).__init__()
@@ -104,9 +99,7 @@ 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
@@ -170,11 +163,9 @@ class ZCAWhitening(nn.Module):
return y
-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]]:
+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"""
Computes the ZCA whitening matrix and mean vector. The output can be used with
@@ -230,8 +221,7 @@ def zca_mean(inp: torch.Tensor,
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
+ -len(inp_size), len(inp_size) - 1, dim
)
)
@@ -245,7 +235,7 @@ def zca_mean(inp: torch.Tensor,
inp_permute = inp.permute(new_order)
N = inp_size[dim]
- feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1::])
+ feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
num_features: int = int(torch.prod(feature_sizes).item())
mean: torch.Tensor = torch.mean(inp_permute, dim=0, keepdim=True)
@@ -368,8 +358,7 @@ def linear_transform(
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
+ -len(inp_size), len(inp_size) - 1, dim
)
)
@@ -385,13 +374,13 @@ def linear_transform(
inv_order: List[int] = perm_inv.tolist()
N = inp_size[dim]
- feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1::])
+ feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
num_features: int = int(torch.prod(feature_sizes).item())
inp_permute = inp.permute(new_order)
inp_flat = inp_permute.reshape((-1, num_features))
- inp_center = (inp_flat - mean_vector)
+ inp_center = inp_flat - mean_vector
inp_transformed = inp_center.mm(transform_matrix)
inp_transformed = inp_transformed.reshape(inp_permute.size())
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 1d73721d3..8543dd483 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -1,17 +1,37 @@
from .responses import (
- CornerHarris, CornerGFTT, BlobHessian, BlobDoG, harris_response, gftt_response, hessian_response, dog_response
+ CornerHarris,
+ CornerGFTT,
+ BlobHessian,
+ BlobDoG,
+ harris_response,
+ gftt_response,
+ hessian_response,
+ dog_response,
)
-from .nms import (NonMaximaSuppression2d, nms2d, NonMaximaSuppression3d, nms3d)
+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
+ 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
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 3217ab483..2f68926ba 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -5,7 +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()
@@ -30,15 +30,13 @@ class PatchAffineShapeEstimator(nn.Module):
return
def __repr__(self):
- return self.__class__.__name__ + '('\
- 'patch_size=' + str(self.patch_size) + ', ' + \
- 'eps=' + str(self.eps) + ')'
+ return self.__class__.__name__ + '(' 'patch_size=' + str(self.patch_size) + ', ' + 'eps=' + str(self.eps) + ')'
def forward(self, patch: torch.Tensor) -> torch.Tensor:
"""Args:
patch: (torch.Tensor) shape [Bx1xHxW]
Returns:
- torch.Tensor: ellipse_shape shape [Bx1x3] """
+ 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)))
if not len(patch.shape) == 4:
@@ -57,16 +55,17 @@ class PatchAffineShapeEstimator(nn.Module):
# 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)
+ 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
+ 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)
# We will replace degenerate shape with circular shapes.
- circular_shape = torch.tensor([1.0, 0., 1.0]).to(ellipse_shape.device).to(ellipse_shape.dtype).view(1, 1, 3)
+ circular_shape = torch.tensor([1.0, 0.0, 1.0]).to(ellipse_shape.device).to(ellipse_shape.dtype).view(1, 1, 3)
ellipse_shape = ellipse_shape * (1.0 - bad_mask) + circular_shape * bad_mask
# normalization
ellipse_shape = ellipse_shape / ellipse_shape.max(dim=2, keepdim=True)[0]
@@ -82,7 +81,7 @@ class LAFAffineShapeEstimator(nn.Module):
Args:
patch_size: int, default = 32
- affine_shape_detector: nn.Module. Patch affine shape estimator, e.g. PatchAffineShapeEstimator. Default: None """ # noqa pylint: disable
+ 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:
super(LAFAffineShapeEstimator, self).__init__()
@@ -91,9 +90,15 @@ class LAFAffineShapeEstimator(nn.Module):
return
def __repr__(self):
- return self.__class__.__name__ + '('\
- 'patch_size=' + str(self.patch_size) + ', ' + \
- 'affine_shape_detector=' + str(self.affine_shape_detector) + ')'
+ return (
+ self.__class__.__name__ + '('
+ 'patch_size='
+ + str(self.patch_size)
+ + ', '
+ + 'affine_shape_detector='
+ + str(self.affine_shape_detector)
+ + ')'
+ )
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
"""
@@ -141,16 +146,28 @@ 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.AdaptiveAvgPool2d(1)
+ 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
# use torch.hub to load pretrained model
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 26d96d386..011745914 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -109,8 +109,7 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc
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
+ [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
@@ -137,8 +136,7 @@ def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.
continue
if var.size(i) != dim:
raise TypeError(
- "{} shape should be must be [{}]. "
- "Got {}".format(var_name, str(req_shape), var.size())
+ "{} 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)
laf: torch.Tensor = scale_laf(unscaled_laf, scale)
@@ -199,14 +197,14 @@ 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
+ 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()
+ (det / b2a2).contiguous(),
],
- dim=3
+ 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)
@@ -238,7 +236,7 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
if n_dims != 3:
raise TypeError("ellipse shape should be must be [BxNx5]. " "Got {}".format(ells.size()))
B, N, dim = ells.size()
- if (dim != 5):
+ if dim != 5:
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),
@@ -283,14 +281,14 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
[
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)
+ torch.ones(n_pts - 1, 1),
],
- dim=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 = torch.cat([torch.tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
pts = pts.to(LAF.device).to(LAF.dtype)
- aux = torch.tensor([0., 0., 1.]).view(1, 1, 3).expand(B * N, 1, 3)
+ aux = torch.tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3)
HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)
pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)
return kornia.convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))
@@ -319,7 +317,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):
"""
# TODO: Refactor doctest
raise_error_if_laf_is_not_valid(LAF)
- pts = laf_to_boundary_points(LAF[img_idx:img_idx + 1])[0]
+ pts = laf_to_boundary_points(LAF[img_idx : img_idx + 1])[0]
pts_np = pts.detach().permute(1, 0, 2).cpu().numpy()
return (pts_np[..., 0], pts_np[..., 1])
@@ -411,11 +409,7 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: 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), [B * N, ch, PS, PS], align_corners=False) # type: ignore
grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w) - 1.0
grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h) - 1.0
return grid
@@ -446,13 +440,13 @@ def extract_patches_simple(
out = []
# 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)
+ 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),
+ img[i : i + 1].expand(grid.size(0), ch, h, w),
grid, # type: ignore
padding_mode="border",
- align_corners=False
+ align_corners=False,
)
)
return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
@@ -494,12 +488,12 @@ def extract_patches_from_pyramid(
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)
+ 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),
+ cur_img[i : i + 1].expand(grid.size(0), ch, h, w),
grid, # type: ignore
padding_mode="border",
- align_corners=False
+ align_corners=False,
)
out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches)
cur_img = kornia.pyrdown(cur_img)
@@ -522,10 +516,9 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0
raise_error_if_laf_is_not_valid(laf)
n, ch, h, w = images.size()
pts: torch.Tensor = laf_to_boundary_points(laf, 12)
- good_lafs_mask: torch.Tensor = (pts[..., 0] >= border) *\
- (pts[..., 0] <= w - border) *\
- (pts[..., 1] >= border) *\
- (pts[..., 1] <= h - border)
+ good_lafs_mask: torch.Tensor = (
+ (pts[..., 0] >= border) * (pts[..., 0] <= w - border) * (pts[..., 1] >= border) * (pts[..., 1] <= h - border)
+ )
good_lafs_mask = good_lafs_mask.min(dim=2)[0]
return good_lafs_mask
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 39c4d0c56..332b2b60c 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -2,9 +2,9 @@ import torch
from typing import Tuple, Optional
-def match_nn(desc1: torch.Tensor,
- desc2: torch.Tensor,
- dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, 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.
If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
@@ -34,9 +34,9 @@ def match_nn(desc1: torch.Tensor,
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
-def match_mnn(desc1: torch.Tensor,
- desc2: torch.Tensor,
- dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, 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.
If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
@@ -77,10 +77,9 @@ def match_mnn(desc1: 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.
@@ -118,10 +117,9 @@ def match_snn(desc1: 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 1a1af1df2..a8b0e23b8 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -23,7 +23,7 @@ urls: Dict[str, str] = {
def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:
- """Gets cartesian and polar parametrizations of grid. """
+ """Gets cartesian and polar parametrizations of grid."""
kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True)
x = kgrid[0, :, :, 0]
y = kgrid[0, :, :, 1]
@@ -33,7 +33,7 @@ def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:
def get_kron_order(d1: int, d2: int) -> torch.Tensor:
- """Gets order for doing kronecker product. """
+ """Gets order for doing kronecker product."""
kron_order = torch.zeros([d1 * d2, 2], dtype=torch.int64)
for i in range(d1):
for j in range(d2):
@@ -123,8 +123,8 @@ class VonMisesKernel(nn.Module):
frange = torch.arange(n) + 1
frange = frange.reshape(-1, 1, 1)
weights = torch.zeros([2 * n + 1])
- weights[:n + 1] = torch.sqrt(b_coeffs)
- weights[n + 1:] = torch.sqrt(b_coeffs[1:])
+ weights[: n + 1] = torch.sqrt(b_coeffs)
+ weights[n + 1 :] = torch.sqrt(b_coeffs[1:])
weights = weights.reshape(-1, 1, 1)
self.register_buffer('emb0', emb0)
self.register_buffer('frange', frange)
@@ -148,11 +148,22 @@ class VonMisesKernel(nn.Module):
return embedding
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'patch_size=' + str(self.patch_size) +\
- ', ' + 'n=' + str(self.n) +\
- ', ' + 'd=' + str(self.d) +\
- ', ' + 'coeffs=' + str(self.coeffs) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'patch_size='
+ + str(self.patch_size)
+ + ', '
+ + 'n='
+ + str(self.n)
+ + ', '
+ + 'd='
+ + str(self.d)
+ + ', '
+ + 'coeffs='
+ + str(self.coeffs)
+ + ')'
+ )
class EmbedGradients(nn.Module):
@@ -189,7 +200,7 @@ class EmbedGradients(nn.Module):
self.register_buffer('phi', phi)
def emb_mags(self, mags: torch.Tensor) -> torch.Tensor:
- """Embed square roots of magnitudes with eps for numerical reasons. """
+ """Embed square roots of magnitudes with eps for numerical reasons."""
mags = torch.sqrt(mags + self.eps)
return mags
@@ -206,13 +217,20 @@ class EmbedGradients(nn.Module):
return y
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'patch_size=' + str(self.patch_size) +\
- ', ' + 'relative=' + str(self.relative) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'patch_size='
+ + str(self.patch_size)
+ + ', '
+ + 'relative='
+ + str(self.relative)
+ + ')'
+ )
def spatial_kernel_embedding(kernel_type, grids: dict) -> torch.Tensor:
- """Compute embeddings for cartesian and polar parametrizations. """
+ """Compute embeddings for cartesian and polar parametrizations."""
factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}
if kernel_type == 'cart':
coeffs_ = 'xy'
@@ -273,7 +291,7 @@ class ExplicitSpacialEncoding(nn.Module):
fmap_size: int = 32,
in_dims: int = 7,
do_gmask: bool = True,
- do_l2: bool = True
+ do_l2: bool = True,
) -> None:
super().__init__()
@@ -308,13 +326,13 @@ class ExplicitSpacialEncoding(nn.Module):
self.register_buffer('idx1', idx1)
def get_gmask(self, sigma: float) -> torch.Tensor:
- """Compute Gaussian mask. """
+ """Compute Gaussian mask."""
norm_rho = self.grid['rho'] / self.grid['rho'].max()
- gmask = torch.exp(-1 * norm_rho**2 / sigma**2)
+ gmask = torch.exp(-1 * norm_rho ** 2 / sigma ** 2)
return gmask
def init_kron(self) -> Tuple[torch.Tensor, torch.Tensor]:
- """Initialize helper variables to calculate kronecker. """
+ """Initialize helper variables to calculate kronecker."""
kron = get_kron_order(self.in_dims, self.d_emb)
_emb = torch.jit.annotate(torch.Tensor, self.emb)
emb2 = torch.index_select(_emb, 1, kron[:, 1])
@@ -334,13 +352,28 @@ class ExplicitSpacialEncoding(nn.Module):
return output
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'kernel_type=' + str(self.kernel_type) +\
- ', ' + 'fmap_size=' + str(self.fmap_size) +\
- ', ' + 'in_dims=' + str(self.in_dims) +\
- ', ' + 'out_dims=' + str(self.out_dims) +\
- ', ' + 'do_gmask=' + str(self.do_gmask) +\
- ', ' + 'do_l2=' + str(self.do_l2) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'kernel_type='
+ + str(self.kernel_type)
+ + ', '
+ + 'fmap_size='
+ + str(self.fmap_size)
+ + ', '
+ + 'in_dims='
+ + str(self.in_dims)
+ + ', '
+ + 'out_dims='
+ + str(self.out_dims)
+ + ', '
+ + 'do_gmask='
+ + str(self.do_gmask)
+ + ', '
+ + 'do_l2='
+ + str(self.do_l2)
+ + ')'
+ )
class Whitening(nn.Module):
@@ -385,7 +418,7 @@ class Whitening(nn.Module):
in_dims: int,
output_dims: int = 128,
keval: int = 40,
- t: float = 0.7
+ t: float = 0.7,
) -> None:
super().__init__()
@@ -411,34 +444,34 @@ class Whitening(nn.Module):
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]
+ 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
+ 'pcawt': self._modify_pcawt,
}
# Call modification.
modifications[self.xform]()
def _modify_pca(self) -> None:
- """ Modify powerlaw parameter."""
+ """Modify powerlaw parameter."""
self.pval = 0.5
def _modify_lw(self) -> None:
- """ No modification required."""
+ """No modification required."""
def _modify_pcaws(self) -> None:
- """ Shrinkage for eigenvalues."""
+ """Shrinkage for eigenvalues."""
alpha = self.evals[self.keval]
evals = ((1 - alpha) * self.evals) + alpha
self.evecs.data = self.evecs @ torch.diag(torch.pow(evals, -0.5))
def _modify_pcawt(self) -> None:
- """ Attenuation for eigenvalues."""
+ """Attenuation for eigenvalues."""
m = -0.5 * self.t
self.evecs.data = self.evecs @ torch.diag(torch.pow(self.evals, m))
@@ -453,10 +486,19 @@ class Whitening(nn.Module):
return F.normalize(x, dim=1)
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'xform=' + str(self.xform) +\
- ', ' + 'in_dims=' + str(self.in_dims) +\
- ', ' + 'output_dims=' + str(self.output_dims) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'xform='
+ + str(self.xform)
+ + ', '
+ + 'in_dims='
+ + str(self.in_dims)
+ + ', '
+ + 'output_dims='
+ + str(self.output_dims)
+ + ')'
+ )
class MKDDescriptor(nn.Module):
@@ -498,7 +540,7 @@ class MKDDescriptor(nn.Module):
kernel_type: str = 'concat',
whitening: str = 'pcawt',
training_set: str = 'liberty',
- output_dims: int = 128
+ output_dims: int = 128,
) -> None:
super().__init__()
@@ -569,12 +611,25 @@ class MKDDescriptor(nn.Module):
return y
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'patch_size=' + str(self.patch_size) +\
- ', ' + 'kernel_type=' + str(self.kernel_type) +\
- ', ' + 'whitening=' + str(self.whitening) +\
- ', ' + 'training_set=' + str(self.training_set) +\
- ', ' + 'output_dims=' + str(self.output_dims) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'patch_size='
+ + str(self.patch_size)
+ + ', '
+ + 'kernel_type='
+ + str(self.kernel_type)
+ + ', '
+ + 'whitening='
+ + str(self.whitening)
+ + ', '
+ + 'training_set='
+ + str(self.training_set)
+ + ', '
+ + 'output_dims='
+ + str(self.output_dims)
+ + ')'
+ )
def load_whitening_model(kernel_type: str, training_set: str) -> Dict:
@@ -584,7 +639,7 @@ def load_whitening_model(kernel_type: str, training_set: str) -> Dict:
class SimpleKD(nn.Module):
- """Example to write custom Kernel Descriptors. """
+ """Example to write custom Kernel Descriptors."""
def __init__(
self,
@@ -592,7 +647,7 @@ class SimpleKD(nn.Module):
kernel_type: str = 'polar', # 'cart' 'polar'
whitening: str = 'pcawt', # 'lw', 'pca', 'pcaws', 'pcawt
training_set: str = 'liberty', # 'liberty', 'notredame', 'yosemite'
- output_dims: int = 128
+ output_dims: int = 128,
) -> None:
super().__init__()
diff --git a/kornia/feature/nms.py b/kornia/feature/nms.py
index 495fb94e4..1d3e0c0cd 100644
--- a/kornia/feature/nms.py
+++ b/kornia/feature/nms.py
@@ -24,8 +24,7 @@ def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> torch.Tensor:
class NonMaximaSuppression2d(nn.Module):
- r"""Applies non maxima suppression to filter.
- """
+ r"""Applies non maxima suppression to filter."""
def __init__(self, kernel_size: Tuple[int, int]):
super(NonMaximaSuppression2d, self).__init__()
@@ -48,12 +47,16 @@ class NonMaximaSuppression2d(nn.Module):
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
@@ -61,8 +64,7 @@ class NonMaximaSuppression2d(nn.Module):
class NonMaximaSuppression3d(nn.Module):
- r"""Applies non maxima suppression to filter.
- """
+ r"""Applies non maxima suppression to filter."""
def __init__(self, kernel_size: Tuple[int, int, int]):
super(NonMaximaSuppression3d, self).__init__()
@@ -85,12 +87,16 @@ class NonMaximaSuppression3d(nn.Module):
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
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index ef21958bb..fda3d96e5 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -8,8 +8,12 @@ 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
+ 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
@@ -54,16 +58,24 @@ class PatchDominantGradientOrientation(nn.Module):
return
def __repr__(self):
- return self.__class__.__name__ + '('\
- 'patch_size=' + str(self.patch_size) + ', ' + \
- 'num_ang_bins=' + str(self.num_ang_bins) + ', ' + \
- 'eps=' + str(self.eps) + ')'
+ return (
+ self.__class__.__name__ + '('
+ 'patch_size='
+ + str(self.patch_size)
+ + ', '
+ + 'num_ang_bins='
+ + str(self.num_ang_bins)
+ + ', '
+ + 'eps='
+ + str(self.eps)
+ + ')'
+ )
def forward(self, patch: torch.Tensor) -> torch.Tensor:
"""Args:
patch: (torch.Tensor) shape [Bx1xHxW]
Returns:
- torch.Tensor: angle shape [B] """
+ torch.Tensor: angle shape [B]"""
if not isinstance(patch, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(patch)))
if not len(patch.shape) == 4:
@@ -100,7 +112,7 @@ class PatchDominantGradientOrientation(nn.Module):
ang_bins = torch.cat(ang_bins_list, 1).view(-1, 1, self.num_ang_bins)
ang_bins = self.angular_smooth(ang_bins)
values, indices = ang_bins.view(-1, self.num_ang_bins).max(1)
- angle = -((2. * pi * indices.to(patch.dtype) / float(self.num_ang_bins)) - pi)
+ angle = -((2.0 * pi * indices.to(patch.dtype) / float(self.num_ang_bins)) - pi)
return angle
@@ -131,16 +143,28 @@ 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.AdaptiveAvgPool2d(1)
+ 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
# use torch.hub to load pretrained model
@@ -164,7 +188,7 @@ class OriNet(nn.Module):
"""Args:
patch: (torch.Tensor) shape [Bx1xHxW]
Returns:
- patch: (torch.Tensor) shape [B] """
+ patch: (torch.Tensor) shape [B]"""
xy = self.features(self._normalize_input(patch)).view(-1, 2)
angle = torch.atan2(xy[:, 0] + 1e-8, xy[:, 1] + self.eps)
return angle
@@ -178,7 +202,7 @@ class LAFOrienter(nn.Module):
Args:
patch_size: int, default = 32
num_angular_bins: int, default is 36
- angle_detector: nn.Module. Patch orientation estimator, e.g. PatchDominantGradientOrientation or OriNet. Default: None """ # noqa pylint: disable
+ 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):
super(LAFOrienter, self).__init__()
@@ -192,9 +216,10 @@ class LAFOrienter(nn.Module):
return
def __repr__(self):
- return self.__class__.__name__ + '('\
- 'patch_size=' + str(self.patch_size) + ', ' + \
- 'angle_detector=' + str(self.angle_detector) + ')'
+ return (
+ self.__class__.__name__ + '('
+ 'patch_size=' + str(self.patch_size) + ', ' + 'angle_detector=' + str(self.angle_detector) + ')'
+ )
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
"""
@@ -203,7 +228,7 @@ class LAFOrienter(nn.Module):
img: (torch.Tensor), shape [Bx1xHxW]
Returns:
- torch.Tensor: laf_out, shape [BxNx2x3] """
+ torch.Tensor: laf_out, shape [BxNx2x3]"""
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):
@@ -215,8 +240,9 @@ class LAFOrienter(nn.Module):
"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 b4182f01a..6ce2b4929 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -10,7 +10,7 @@ def harris_response(
input: torch.Tensor,
k: Union[torch.Tensor, float] = 0.04,
grads_mode: str = 'sobel',
- sigmas: Optional[torch.Tensor] = None
+ 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:
@@ -83,14 +83,14 @@ def harris_response(
# 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.))
- dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1., 1.))
+ dx2: torch.Tensor = gaussian_blur2d(dx ** 2, (7, 7), (1.0, 1.0))
+ dy2: torch.Tensor = gaussian_blur2d(dy ** 2, (7, 7), (1.0, 1.0))
+ dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
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
@@ -159,15 +159,15 @@ def gftt_response(
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.))
- dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1., 1.))
+ dx2: torch.Tensor = gaussian_blur2d(dx ** 2, (7, 7), (1.0, 1.0))
+ dy2: torch.Tensor = gaussian_blur2d(dy ** 2, (7, 7), (1.0, 1.0))
+ dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
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:
@@ -244,7 +244,7 @@ def hessian_response(
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
@@ -284,11 +284,7 @@ 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, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
return dog_response(input) # type: ignore
@@ -307,15 +303,9 @@ class CornerHarris(nn.Module):
return
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(k=' + str(self.k) + ', ' +\
- 'grads_mode=' + self.grads_mode + ')'
-
- def forward(
- self,
- input: torch.Tensor, # type: ignore
- sigmas: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
+ return self.__class__.__name__ + '(k=' + str(self.k) + ', ' + 'grads_mode=' + self.grads_mode + ')'
+
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
return harris_response(input, self.k, self.grads_mode, sigmas) # type: ignore
@@ -330,14 +320,9 @@ class CornerGFTT(nn.Module):
return
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- 'grads_mode=' + self.grads_mode + ')'
-
- def forward(
- self,
- input: torch.Tensor, # type: ignore
- sigmas: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
+ return self.__class__.__name__ + 'grads_mode=' + self.grads_mode + ')'
+
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
return gftt_response(input, self.grads_mode, sigmas)
@@ -352,12 +337,7 @@ class BlobHessian(nn.Module):
return
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- 'grads_mode=' + self.grads_mode + ')'
-
- def forward(
- self,
- input: torch.Tensor, # type: ignore
- sigmas: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
+ return self.__class__.__name__ + 'grads_mode=' + self.grads_mode + ')'
+
+ def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
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 b8c7e0939..ce3e39bf4 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -8,7 +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
@@ -83,7 +83,7 @@ class ScaleSpaceDetector(nn.Module):
ori_module: nn.Module = PassLAF(),
aff_module: nn.Module = PassLAF(),
minima_are_also_good: bool = False,
- scale_space_response=False
+ scale_space_response=False,
):
super(ScaleSpaceDetector, self).__init__()
self.mr_size = mr_size
@@ -100,19 +100,34 @@ class ScaleSpaceDetector(nn.Module):
return
def __repr__(self):
- return self.__class__.__name__ + '('\
- 'num_features=' + str(self.num_features) + ', ' + \
- 'mr_size=' + str(self.mr_size) + ', ' + \
- 'scale_pyr=' + self.scale_pyr.__repr__() + ', ' + \
- 'resp=' + self.resp.__repr__() + ', ' + \
- 'nms=' + self.nms.__repr__() + ', ' + \
- 'ori=' + self.ori.__repr__() + ', ' + \
- 'aff=' + self.aff.__repr__() + ')'
-
- def detect(self,
- img: torch.Tensor,
- num_feats: int,
- mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ return (
+ self.__class__.__name__ + '('
+ 'num_features='
+ + str(self.num_features)
+ + ', '
+ + 'mr_size='
+ + str(self.mr_size)
+ + ', '
+ + 'scale_pyr='
+ + self.scale_pyr.__repr__()
+ + ', '
+ + 'resp='
+ + self.resp.__repr__()
+ + ', '
+ + 'nms='
+ + self.nms.__repr__()
+ + ', '
+ + 'ori='
+ + self.ori.__repr__()
+ + ', '
+ + 'aff='
+ + self.aff.__repr__()
+ + ')'
+ )
+
+ 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
sp, sigmas, pix_dists = self.scale_pyr(img)
@@ -127,8 +142,9 @@ class ScaleSpaceDetector(nn.Module):
if self.scale_space_response:
oct_resp = self.resp(octave, sigmas_oct.view(-1))
else:
- oct_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W),
- sigmas_oct.view(-1)).view(B, L, CH, H, W)
+ oct_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1)).view(
+ B, L, CH, H, W
+ )
# We want nms for scale responses, so reorder to (B, CH, L, H, W)
oct_resp = oct_resp.permute(0, 2, 1, 3, 4)
# 3rd extra level is required for DoG only
@@ -169,9 +185,9 @@ class ScaleSpaceDetector(nn.Module):
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)
+ max_coords_best[:, :, 1:3].view(B, N, 2, 1),
],
- dim=3
+ dim=3,
)
# Zero response lafs, which touch the boundary
@@ -192,9 +208,7 @@ class ScaleSpaceDetector(nn.Module):
return responses, denormalize_laf(lafs, img)
def forward( # type: ignore
- self,
- img: torch.Tensor, # type: ignore
- mask: Optional[torch.Tensor] = None
+ self, img: torch.Tensor, mask: Optional[torch.Tensor] = None # type: ignore
) -> 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 3141f3856..295bdd3b5 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -22,7 +22,7 @@ def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
"""
ks_2: float = float(ksize) / 2.0
xc2: torch.Tensor = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs() # type: ignore # noqa
- kernel: torch.Tensor = torch.ger(xc2, xc2) / (ks_2**2)
+ kernel: torch.Tensor = torch.ger(xc2, xc2) / (ks_2 ** 2)
return kernel
@@ -77,12 +77,25 @@ class SIFTDescriptor(nn.Module):
"""
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'num_ang_bins=' + str(self.num_ang_bins) +\
- ', ' + 'num_spatial_bins=' + str(self.num_spatial_bins) +\
- ', ' + 'patch_size=' + str(self.patch_size) +\
- ', ' + 'rootsift=' + str(self.rootsift) +\
- ', ' + 'clipval=' + str(self.clipval) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'num_ang_bins='
+ + str(self.num_ang_bins)
+ + ', '
+ + 'num_spatial_bins='
+ + str(self.num_spatial_bins)
+ + ', '
+ + 'patch_size='
+ + str(self.patch_size)
+ + ', '
+ + 'rootsift='
+ + str(self.rootsift)
+ + ', '
+ + 'clipval='
+ + str(self.clipval)
+ + ')'
+ )
def __init__(
self,
@@ -113,7 +126,7 @@ class SIFTDescriptor(nn.Module):
kernel_size=(nw.size(0), nw.size(1)),
stride=(self.bin_stride, self.bin_stride),
padding=(self.pad, self.pad),
- bias=False
+ bias=False,
)
self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1))) # type: ignore # noqa
return
@@ -148,7 +161,7 @@ class SIFTDescriptor(nn.Module):
o_big: torch.Tensor = float(self.num_ang_bins) * ori / (2.0 * pi)
bo0_big_: torch.Tensor = torch.floor(o_big)
- wo1_big_: torch.Tensor = (o_big - bo0_big_)
+ wo1_big_: torch.Tensor = o_big - bo0_big_
bo0_big: torch.Tensor = bo0_big_ % self.num_ang_bins
bo1_big: torch.Tensor = (bo0_big + 1) % self.num_ang_bins
wo0_big: torch.Tensor = (1.0 - wo1_big_) * mag # type: ignore
@@ -156,13 +169,12 @@ class SIFTDescriptor(nn.Module):
ang_bins = []
for i in range(0, self.num_ang_bins):
- out = self.pk((bo0_big == i).to(input.dtype) * wo0_big + # noqa
- (bo1_big == i).to(input.dtype) * wo1_big)
+ out = self.pk((bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big) # noqa
ang_bins.append(out)
ang_bins = torch.cat(ang_bins, dim=1)
ang_bins = ang_bins.view(B, -1)
ang_bins = F.normalize(ang_bins, p=2)
- ang_bins = torch.clamp(ang_bins, 0., float(self.clipval))
+ ang_bins = torch.clamp(ang_bins, 0.0, float(self.clipval))
ang_bins = F.normalize(ang_bins, p=2)
if self.rootsift:
ang_bins = torch.sqrt(F.normalize(ang_bins, p=1) + self.eps)
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index bdd279cd8..d6ee8bfb2 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -5,12 +5,15 @@ 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):
@@ -40,8 +43,12 @@ 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()
+ 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
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 1b7d9fd02..74fa25965 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -4,14 +4,11 @@ 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
+ 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.
@@ -92,10 +89,18 @@ class BoxBlur(nn.Module):
self.normalized: bool = normalized
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(kernel_size=' + str(self.kernel_size) + ', ' +\
- 'normalized=' + str(self.normalized) + ', ' + \
- 'border_type=' + self.border_type + ')'
+ return (
+ self.__class__.__name__
+ + '(kernel_size='
+ + str(self.kernel_size)
+ + ', '
+ + 'normalized='
+ + str(self.normalized)
+ + ', '
+ + 'border_type='
+ + self.border_type
+ + ')'
+ )
def forward(self, input: torch.Tensor) -> torch.Tensor:
return box_blur(input, self.kernel_size, self.border_type, self.normalized)
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index daf567e50..67c5fd22a 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -9,12 +9,7 @@ import kornia
from .kernels import get_pascal_kernel_2d
from .median import _compute_zero_padding # TODO: Move to proper place
-__all__ = [
- "BlurPool2D",
- "MaxBlurPool2D",
- "blur_pool2d",
- "max_blur_pool2d",
-]
+__all__ = ["BlurPool2D", "MaxBlurPool2D", "blur_pool2d", "max_blur_pool2d"]
class BlurPool2D(nn.Module):
@@ -145,11 +140,7 @@ 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.
@@ -178,8 +169,9 @@ def max_blur_pool2d(
def _blur_pool_by_kernel2d(input: torch.Tensor, kernel: torch.Tensor, stride: int):
"""Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2), \
- f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"
+ assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(
+ -2
+ ), f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"
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))
@@ -188,8 +180,9 @@ def _max_blur_pool_by_kernel2d(
input: torch.Tensor, kernel: torch.Tensor, stride: int, max_pool_size: int, ceil_mode: bool
):
"""Compute max_blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- assert len(kernel.shape) == 4 and kernel.size(-1) == kernel.size(-2), \
- f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}"
+ 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)
# blur and downsample
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index c24f00947..bf610c19e 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -108,10 +108,7 @@ def filter2D(
def filter3D(
- input: torch.Tensor,
- kernel: torch.Tensor,
- border_type: str = 'replicate',
- normalized: bool = False
+ input: torch.Tensor, kernel: torch.Tensor, border_type: str = 'replicate', normalized: bool = False
) -> torch.Tensor:
r"""Convolve a tensor with a 3d kernel.
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index c0dcb79a0..29e4b72f8 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -8,10 +8,7 @@ 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'
+ 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.
@@ -76,10 +73,18 @@ class GaussianBlur2d(nn.Module):
self.border_type = border_type
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(kernel_size=' + str(self.kernel_size) + ', ' +\
- 'sigma=' + str(self.sigma) + ', ' +\
- 'border_type=' + self.border_type + ')'
+ return (
+ self.__class__.__name__
+ + '(kernel_size='
+ + str(self.kernel_size)
+ + ', '
+ + 'sigma='
+ + str(self.sigma)
+ + ', '
+ + 'border_type='
+ + self.border_type
+ + ')'
+ )
def forward(self, input: torch.Tensor) -> torch.Tensor:
return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 19eae4f82..0e4ed7c33 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -8,8 +8,7 @@ from kornia.utils import _extract_device_dtype
def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:
- r"""Normalizes both derivative and smoothing kernel.
- """
+ 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()))
norm: torch.Tensor = input.abs().sum(dim=-1).sum(dim=-1)
@@ -23,7 +22,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()
@@ -52,7 +51,7 @@ 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)))
- coef = (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
@@ -121,7 +120,7 @@ def gaussian_discrete(window_size, sigma) -> torch.Tensor:
def laplacian_1d(window_size) -> torch.Tensor:
r"""One could also use the Laplacian of Gaussian formula
- to design the filter.
+ to design the filter.
"""
filter_1d = torch.ones(window_size)
@@ -134,7 +133,7 @@ def get_box_kernel2d(kernel_size: Tuple[int, int]) -> torch.Tensor:
r"""Utility function that returns a box filter."""
kx: float = float(kernel_size[0])
ky: float = float(kernel_size[1])
- scale: torch.Tensor = torch.tensor(1.) / torch.tensor([kx * ky])
+ scale: torch.Tensor = torch.tensor(1.0) / torch.tensor([kx * ky])
tmp_kernel: torch.Tensor = torch.ones(1, kernel_size[0], kernel_size[1])
return scale.to(tmp_kernel.dtype) * tmp_kernel
@@ -152,19 +151,18 @@ def get_binary_kernel2d(window_size: Tuple[int, int]) -> torch.Tensor:
def get_sobel_kernel_3x3() -> torch.Tensor:
"""Utility function that returns a sobel kernel of 3x3"""
- return torch.tensor([
- [-1., 0., 1.],
- [-2., 0., 2.],
- [-1., 0., 1.],
- ])
+ return torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]])
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.]
+ [-1.0, 0.0, 2.0, 0.0, -1.0],
+ [-4.0, 0.0, 8.0, 0.0, -4.0],
+ [-6.0, 0.0, 12.0, 0.0, -6.0],
+ [-4.0, 0.0, 8.0, 0.0, -4.0],
+ [-1.0, 0.0, 2.0, 0.0, -1.0],
]
)
@@ -173,19 +171,18 @@ 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.]
+ [-1.0, -2.0, 0.0, 2.0, 1.0],
+ [-2.0, -4.0, 0.0, 4.0, 2.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [2.0, 4.0, 0.0, -4.0, -2.0],
+ [1.0, 2.0, 0.0, -2.0, -1.0],
]
)
def get_diff_kernel_3x3() -> torch.Tensor:
"""Utility function that returns a first order derivative kernel of 3x3"""
- return torch.tensor([
- [-0., 0., 0.],
- [-1., 0., 1.],
- [-0., 0., 0.],
- ])
+ return torch.tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]])
def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
@@ -209,7 +206,7 @@ def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Te
],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
return kernel.unsqueeze(1)
@@ -250,7 +247,7 @@ def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -
],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
return kernel.unsqueeze(1)
@@ -275,17 +272,9 @@ def get_sobel_kernel2d_2nd_order() -> torch.Tensor:
def get_diff_kernel2d_2nd_order() -> torch.Tensor:
- gxx: torch.Tensor = torch.tensor([
- [0., 0., 0.],
- [1., -2., 1.],
- [0., 0., 0.],
- ])
+ gxx: torch.Tensor = torch.tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]])
gyy: torch.Tensor = gxx.transpose(0, 1)
- gxy: torch.Tensor = torch.tensor([
- [-1., 0., 1.],
- [0., 0., 0.],
- [1., 0., -1.],
- ])
+ gxy: torch.Tensor = torch.tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]])
return torch.stack([gxx, gxy, gyy])
@@ -293,11 +282,19 @@ def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:
r"""Function that returns kernel for 1st or 2nd order image gradients,
using one of the following operators: sobel, diff"""
if mode not in ['sobel', 'diff']:
- raise TypeError("mode should be either sobel\
- or diff. Got {}".format(mode))
+ raise TypeError(
+ "mode should be either sobel\
+ or diff. Got {}".format(
+ mode
+ )
+ )
if order not in [1, 2]:
- raise TypeError("order should be either 1 or 2\
- Got {}".format(order))
+ raise TypeError(
+ "order should be either 1 or 2\
+ Got {}".format(
+ order
+ )
+ )
if mode == 'sobel' and order == 1:
kernel: torch.Tensor = get_sobel_kernel2d()
elif mode == 'sobel' and order == 2:
@@ -315,11 +312,19 @@ def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cp
r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients,
using one of the following operators: sobel, diff"""
if mode not in ['sobel', 'diff']:
- raise TypeError("mode should be either sobel\
- or diff. Got {}".format(mode))
+ raise TypeError(
+ "mode should be either sobel\
+ or diff. Got {}".format(
+ mode
+ )
+ )
if order not in [1, 2]:
- raise TypeError("order should be either 1 or 2\
- Got {}".format(order))
+ raise TypeError(
+ "order should be either 1 or 2\
+ Got {}".format(
+ order
+ )
+ )
if mode == 'sobel':
raise NotImplementedError("Sobel kernel for 3d gradient is not implemented yet")
elif mode == 'diff' and order == 1:
@@ -353,7 +358,7 @@ def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = Fal
>>> 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)):
+ 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
@@ -383,7 +388,7 @@ def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: b
>>> 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)):
+ 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
@@ -413,7 +418,7 @@ def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool =
>>> 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)):
+ 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
@@ -478,8 +483,7 @@ def get_laplacian_kernel1d(kernel_size: int) -> torch.Tensor:
tensor([ 1., 1., -4., 1., 1.])
"""
- if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \
- kernel_size <= 0:
+ 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))
window_1d: torch.Tensor = laplacian_1d(kernel_size)
return window_1d
@@ -509,13 +513,12 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
"""
- if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or \
- kernel_size <= 0:
+ 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))
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
@@ -523,8 +526,8 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:
def get_motion_kernel2d(
kernel_size: int,
angle: Union[torch.Tensor, float],
- direction: Union[torch.Tensor, float] = 0.,
- mode: str = 'nearest'
+ direction: Union[torch.Tensor, float] = 0.0,
+ mode: str = 'nearest',
) -> torch.Tensor:
r"""Return 2D motion blur filter.
@@ -557,10 +560,7 @@ def get_motion_kernel2d(
[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,
- ]
+ [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:
@@ -582,12 +582,13 @@ def get_motion_kernel2d(
direction = direction.unsqueeze(0)
assert direction.dim() == 1, f"direction must be a 1-dim tensor. Got {direction}."
- assert direction.size(0) == angle.size(0), \
- f"direction and angle must have the same length. Got {direction} and {angle}."
+ assert direction.size(0) == angle.size(
+ 0
+ ), f"direction and angle must have the same length. Got {direction} and {angle}."
kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)
# direction from [-1, 1] to [0, 1] range
- direction = (torch.clamp(direction, -1., 1.) + 1.) / 2.
+ direction = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0
# kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)
# Element-wise linspace
@@ -610,8 +611,8 @@ def get_motion_kernel2d(
def get_motion_kernel3d(
kernel_size: int,
angle: Union[torch.Tensor, Tuple[float, float, float]],
- direction: Union[torch.Tensor, float] = 0.,
- mode: str = 'nearest'
+ direction: Union[torch.Tensor, float] = 0.0,
+ mode: str = 'nearest',
) -> torch.Tensor:
r"""Return 3D motion blur filter.
@@ -663,10 +664,7 @@ def get_motion_kernel3d(
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,
- ]
+ [angle if isinstance(angle, torch.Tensor) else None, direction if isinstance(direction, torch.Tensor) else None]
)
if not isinstance(angle, torch.Tensor):
@@ -685,12 +683,13 @@ def get_motion_kernel3d(
direction = direction.unsqueeze(0)
assert direction.dim() == 1, f"direction must be a 1-dim tensor. Got {direction}."
- assert direction.size(0) == angle.size(0), \
- f"direction and angle must have the same length. Got {direction} and {angle}."
+ assert direction.size(0) == angle.size(
+ 0
+ ), f"direction and angle must have the same length. Got {direction} and {angle}."
kernel_tuple: Tuple[int, int, int] = (kernel_size, kernel_size, kernel_size)
# direction from [-1, 1] to [0, 1] range
- direction = (torch.clamp(direction, -1., 1.) + 1.) / 2.
+ direction = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0
kernel = torch.zeros((direction.size(0), *kernel_tuple), device=device, dtype=dtype)
# Element-wise linspace
@@ -711,7 +710,7 @@ def get_motion_kernel3d(
def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> torch.Tensor:
- """ Generate pascal filter kernel by kernel size.
+ """Generate pascal filter kernel by kernel size.
Args:
kernel_size (int): height and width of the kernel.
@@ -743,7 +742,7 @@ def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> torch.Tensor:
def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:
- """ Generate Yang Hui triangle (Pascal's triangle) by a given number.
+ """Generate Yang Hui triangle (Pascal's triangle) by a given number.
Args:
kernel_size (int): height and width of the kernel.
@@ -769,7 +768,7 @@ def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:
pre: List[float] = []
cur: List[float] = []
for i in range(kernel_size):
- cur = [1.] * (i + 1)
+ cur = [1.0] * (i + 1)
for j in range(1, i // 2 + 1):
value = pre[j - 1] + pre[j]
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index 039ea0ff0..25a524bfc 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -73,10 +73,18 @@ class Laplacian(nn.Module):
self.normalized: bool = normalized
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(kernel_size=' + str(self.kernel_size) + ', ' +\
- 'normalized=' + str(self.normalized) + ', ' + \
- 'border_type=' + self.border_type + ')'
+ return (
+ self.__class__.__name__
+ + '(kernel_size='
+ + str(self.kernel_size)
+ + ', '
+ + 'normalized='
+ + str(self.normalized)
+ + ', '
+ + 'border_type='
+ + self.border_type
+ + ')'
+ )
def forward(self, input: torch.Tensor) -> torch.Tensor:
return laplacian(input, self.kernel_size, self.border_type, self.normalized)
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index dd06e6802..c067ce8bf 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -4,7 +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):
@@ -41,8 +41,10 @@ class MotionBlur(nn.Module):
self.border_type: str = border_type
def __repr__(self) -> str:
- return f'{self.__class__.__name__} (kernel_size={self.kernel_size}, ' \
- f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
+ return (
+ f'{self.__class__.__name__} (kernel_size={self.kernel_size}, '
+ f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
+ )
def forward(self, x: torch.Tensor):
return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)
@@ -79,7 +81,7 @@ class MotionBlur3D(nn.Module):
kernel_size: int,
angle: Union[float, Tuple[float, float, float]],
direction: float,
- border_type: str = 'constant'
+ border_type: str = 'constant',
) -> None:
super(MotionBlur3D, self).__init__()
self.kernel_size = kernel_size
@@ -94,8 +96,10 @@ class MotionBlur3D(nn.Module):
self.border_type: str = border_type
def __repr__(self) -> str:
- return f'{self.__class__.__name__} (kernel_size={self.kernel_size}, ' \
- f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
+ return (
+ f'{self.__class__.__name__} (kernel_size={self.kernel_size}, '
+ f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
+ )
def forward(self, x: torch.Tensor):
return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type)
@@ -107,7 +111,7 @@ def motion_blur(
angle: Union[float, torch.Tensor],
direction: Union[float, torch.Tensor],
border_type: str = 'constant',
- mode: str = 'nearest'
+ mode: str = 'nearest',
) -> torch.Tensor:
r"""Perform motion blur on 2D images (4D tensor).
@@ -151,7 +155,7 @@ def motion_blur3d(
angle: Union[Tuple[float, float, float], torch.Tensor],
direction: Union[float, torch.Tensor],
border_type: str = 'constant',
- mode: str = 'nearest'
+ mode: str = 'nearest',
) -> torch.Tensor:
r"""Perform motion blur on 3D volumes (5D tensor).
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 26814f3c7..37b2b485b 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -2,7 +2,7 @@ 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:
@@ -95,11 +95,12 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1)
kernel.size(3) // 2,
kernel.size(3) // 2,
kernel.size(4) // 2,
- kernel.size(4) // 2
+ 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:
@@ -166,10 +167,10 @@ class SpatialGradient(nn.Module):
self.mode: str = mode
def __repr__(self) -> str:
- return self.__class__.__name__ + '('\
- 'order=' + str(self.order) + ', ' + \
- 'normalized=' + str(self.normalized) + ', ' + \
- 'mode=' + self.mode + ')'
+ return (
+ self.__class__.__name__ + '('
+ 'order=' + str(self.order) + ', ' + 'normalized=' + str(self.normalized) + ', ' + 'mode=' + self.mode + ')'
+ )
def forward(self, input: torch.Tensor) -> torch.Tensor:
return spatial_gradient(input, self.mode, self.order, self.normalized)
@@ -205,9 +206,7 @@ class SpatialGradient3d(nn.Module):
return
def __repr__(self) -> str:
- return self.__class__.__name__ + '('\
- 'order=' + str(self.order) + ', ' + \
- 'mode=' + self.mode + ')'
+ return self.__class__.__name__ + '(' 'order=' + str(self.order) + ', ' + 'mode=' + self.mode + ')'
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
return spatial_gradient3d(input, self.mode, self.order)
@@ -238,8 +237,7 @@ class Sobel(nn.Module):
self.eps: float = eps
def __repr__(self) -> str:
- return self.__class__.__name__ + '('\
- 'normalized=' + str(self.normalized) + ')'
+ return self.__class__.__name__ + '(' 'normalized=' + str(self.normalized) + ')'
def forward(self, input: torch.Tensor) -> torch.Tensor:
return sobel(input, self.normalized, self.eps)
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index 57fbfb187..934209d3b 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -8,10 +8,7 @@ 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'
+ 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.
diff --git a/kornia/geometry/camera/__init__.py b/kornia/geometry/camera/__init__.py
index e3b90ea70..59874e1ad 100644
--- a/kornia/geometry/camera/__init__.py
+++ b/kornia/geometry/camera/__init__.py
@@ -1,10 +1,4 @@
from .pinhole import PinholeCamera, pixel2cam, cam2pixel
from .perspective import unproject_points, project_points
-__all__ = [
- "PinholeCamera",
- "pixel2cam",
- "cam2pixel",
- "unproject_points",
- "project_points",
-]
+__all__ = ["PinholeCamera", "pixel2cam", "cam2pixel", "unproject_points", "project_points"]
diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.py
index 826614959..cb5f80f37 100644
--- a/kornia/geometry/camera/perspective.py
+++ b/kornia/geometry/camera/perspective.py
@@ -4,7 +4,7 @@ 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:
@@ -121,6 +121,6 @@ def unproject_points(
xyz = convert_points_to_homogeneous(xyz)
if normalize:
- xyz = F.normalize(xyz, dim=-1, p=2.)
+ xyz = F.normalize(xyz, dim=-1, p=2.0)
return xyz * depth
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index cb3b8cee0..e38f135cf 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -49,10 +49,7 @@ class PinholeCamera:
@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?
+ 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)
@@ -63,8 +60,7 @@ class PinholeCamera:
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)
+ "Argument {0} shape must be in the following shape" " B. Got {1}".format(data_name, data.shape)
)
return True
@@ -294,7 +290,7 @@ class PinholeCamera:
tz,
batch_size=1,
device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None
+ dtype: Optional[torch.dtype] = None,
):
# create the camera matrix
intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
@@ -339,10 +335,7 @@ class PinholeCamerasList(PinholeCamera):
def _initialize_parameters(self, pinholes: Iterable[PinholeCamera]) -> 'PinholeCamerasList':
r"""Initialises the class attributes given a cameras list."""
- if not isinstance(pinholes, (
- list,
- tuple,
- )):
+ if not isinstance(pinholes, (list, tuple)):
raise TypeError("pinhole must of type list or tuple. Got {}".format(type(pinholes)))
height, width = [], []
intrinsics, extrinsics = [], []
@@ -456,10 +449,10 @@ def inverse_pinhole_matrix(pinhole, eps=1e-6):
k = torch.eye(4, device=pinhole.device, dtype=pinhole.dtype)
k = k.view(1, 4, 4).repeat(pinhole.shape[0], 1, 1) # Nx4x4
# fill output with inverse values
- k[..., 0, 0:1] = 1. / (fx + eps)
- k[..., 1, 1:2] = 1. / (fy + eps)
- k[..., 0, 2:3] = -1. * cx / (fx + eps)
- k[..., 1, 2:3] = -1. * cy / (fy + eps)
+ k[..., 0, 0:1] = 1.0 / (fx + eps)
+ k[..., 1, 1:2] = 1.0 / (fy + eps)
+ k[..., 0, 2:3] = -1.0 * cx / (fx + eps)
+ k[..., 1, 2:3] = -1.0 * cy / (fy + eps)
return k
@@ -607,8 +600,7 @@ def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: Opt
"""
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)
+ "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))
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index f7d54c9ff..10aaa063e 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -54,7 +54,7 @@ def rad2deg(tensor: torch.Tensor) -> torch.Tensor:
if not isinstance(tensor, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
- return 180. * tensor / pi.to(tensor.device).type(tensor.dtype)
+ return 180.0 * tensor / pi.to(tensor.device).type(tensor.dtype)
def deg2rad(tensor: torch.Tensor) -> torch.Tensor:
@@ -74,7 +74,7 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:
if not isinstance(tensor, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(tensor)))
- return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.
+ return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.0
def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
@@ -100,7 +100,7 @@ def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.
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.0e-8) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function that converts cartesian coordinates to polar coordinates.
Args:
@@ -119,7 +119,7 @@ def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.e-8) -> Tuple[torc
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)))
- rho = torch.sqrt(x**2 + y**2 + eps)
+ rho = torch.sqrt(x ** 2 + y ** 2 + eps)
phi = torch.atan2(y, x)
return rho, phi
@@ -145,7 +145,7 @@ def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) ->
# follow the convention of opencv:
# https://github.com/opencv/opencv/pull/14411/files
mask: torch.Tensor = torch.abs(z_vec) > eps
- scale = torch.where(mask, 1. / (z_vec + eps), torch.ones_like(z_vec))
+ scale = torch.where(mask, 1.0 / (z_vec + eps), torch.ones_like(z_vec))
return scale * points[..., :-1]
@@ -167,7 +167,7 @@ def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:
def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:
- H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.)
+ H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.0)
H[..., -1, -1] += 1.0
return H
@@ -275,8 +275,7 @@ def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:
rotation_matrix = torch.eye(3).to(angle_axis.device).type_as(angle_axis)
rotation_matrix = rotation_matrix.view(1, 3, 3).repeat(batch_size, 1, 1)
# fill output matrix with masked values
- rotation_matrix[..., :3, :3] = \
- mask_pos * rotation_matrix_normal + mask_neg * rotation_matrix_taylor
+ rotation_matrix[..., :3, :3] = mask_pos * rotation_matrix_normal + mask_neg * rotation_matrix_taylor
return rotation_matrix # Nx3x3
@@ -307,9 +306,7 @@ def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensor
def rotation_matrix_to_quaternion(
- rotation_matrix: torch.Tensor,
- eps: float = 1.e-8,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+ rotation_matrix: torch.Tensor, eps: float = 1.0e-8, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Convert 3x3 rotation matrix to 4d quaternion vector.
@@ -364,7 +361,7 @@ def rotation_matrix_to_quaternion(
trace: torch.Tensor = m00 + m11 + m22
def trace_positive_cond():
- sq = torch.sqrt(trace + 1.0) * 2. # sq = 4 * qw.
+ sq = torch.sqrt(trace + 1.0) * 2.0 # sq = 4 * qw.
qw = 0.25 * sq
qx = safe_zero_division(m21 - m12, sq)
qy = safe_zero_division(m02 - m20, sq)
@@ -375,7 +372,7 @@ def rotation_matrix_to_quaternion(
return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_1():
- sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2. # sq = 4 * qx.
+ sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2.0 # sq = 4 * qx.
qw = safe_zero_division(m21 - m12, sq)
qx = 0.25 * sq
qy = safe_zero_division(m01 + m10, sq)
@@ -386,7 +383,7 @@ def rotation_matrix_to_quaternion(
return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_2():
- sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2. # sq = 4 * qy.
+ sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2.0 # sq = 4 * qy.
qw = safe_zero_division(m02 - m20, sq)
qx = safe_zero_division(m01 + m10, sq)
qy = 0.25 * sq
@@ -397,7 +394,7 @@ def rotation_matrix_to_quaternion(
return torch.cat((qw, qx, qy, qz), dim=-1)
def cond_3():
- sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2. # sq = 4 * qz.
+ sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2.0 # sq = 4 * qz.
qw = safe_zero_division(m10 - m01, sq)
qx = safe_zero_division(m02 + m20, sq)
qy = safe_zero_division(m12 + m21, sq)
@@ -410,11 +407,11 @@ def rotation_matrix_to_quaternion(
where_2 = torch.where(m11 > m22, cond_2(), cond_3())
where_1 = torch.where((m00 > m11) & (m00 > m22), cond_1(), where_2)
- quaternion: torch.Tensor = torch.where(trace > 0., trace_positive_cond(), where_1)
+ quaternion: torch.Tensor = torch.where(trace > 0.0, trace_positive_cond(), where_1)
return quaternion
-def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.e-12) -> torch.Tensor:
+def normalize_quaternion(quaternion: torch.Tensor, eps: float = 1.0e-12) -> torch.Tensor:
r"""Normalizes a quaternion.
The quaternion should be in (x, y, z, w) format.
@@ -508,14 +505,21 @@ def quaternion_to_rotation_matrix(
tyy: torch.Tensor = ty * y
tyz: torch.Tensor = tz * y
tzz: torch.Tensor = tz * z
- one: torch.Tensor = torch.tensor(1.)
+ one: torch.Tensor = torch.tensor(1.0)
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)
+ one - (tyy + tzz),
+ txy - twz,
+ txz + twy,
+ txy + twz,
+ one - (txx + tzz),
+ tyz - twx,
+ txz - twy,
+ tyz + twx,
+ one - (txx + tyy),
),
- dim=-1
+ dim=-1,
).view(-1, 3, 3)
if len(quaternion.shape) == 1:
@@ -600,9 +604,7 @@ def quaternion_to_angle_axis(
def quaternion_log_to_exp(
- quaternion: torch.Tensor,
- eps: float = 1.e-8,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+ quaternion: torch.Tensor, eps: float = 1.0e-8, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Applies exponential map to log quaternion.
@@ -658,9 +660,7 @@ def quaternion_log_to_exp(
def quaternion_exp_to_log(
- quaternion: torch.Tensor,
- eps: float = 1.e-8,
- order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
+ quaternion: torch.Tensor, eps: float = 1.0e-8, order: QuaternionCoeffOrder = QuaternionCoeffOrder.XYZW
) -> torch.Tensor:
r"""Applies the log map to a quaternion.
@@ -714,9 +714,9 @@ def quaternion_exp_to_log(
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
+ quaternion_log: torch.Tensor = (
+ quaternion_vector * torch.acos(torch.clamp(quaternion_scalar, min=-1.0, max=1.0)) / norm_q
+ )
return quaternion_log
@@ -827,12 +827,13 @@ def normalize_pixel_coordinates(
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)
+ 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.0, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype) / (
+ hw - 1
+ ).clamp(eps)
return factor * pixel_coordinates - 1
@@ -858,12 +859,15 @@ def denormalize_pixel_coordinates(
if pixel_coordinates.shape[-1] != 2:
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)
+ factor: torch.Tensor = torch.tensor(2.0) / (hw - 1).clamp(eps)
- return torch.tensor(1.) / factor * (pixel_coordinates + 1)
+ return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
def normalize_pixel_coordinates3d(
@@ -887,11 +891,13 @@ def normalize_pixel_coordinates3d(
if pixel_coordinates.shape[-1] != 3:
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)
+ factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
return factor * pixel_coordinates - 1
@@ -919,10 +925,12 @@ def denormalize_pixel_coordinates3d(
if pixel_coordinates.shape[-1] != 3:
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)
+ factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
- return torch.tensor(1.) / factor * (pixel_coordinates + 1)
+ return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 5e9ab3df7..95755d911 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -6,20 +6,17 @@ import torch.nn as nn
import torch.nn.functional as F
from kornia.geometry.linalg import (
- transform_points, inverse_transformation, compose_transformations, convert_points_to_homogeneous
+ 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
-__all__ = [
- "depth_to_3d",
- "depth_to_normals",
- "warp_frame_depth",
- "depth_warp",
- "DepthWarper",
-]
+__all__ = ["depth_to_3d", "depth_to_normals", "warp_frame_depth", "depth_warp", "DepthWarper"]
def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:
@@ -117,7 +114,7 @@ def warp_frame_depth(
depth_dst: torch.Tensor,
src_trans_dst: torch.Tensor,
camera_matrix: torch.Tensor,
- normalize_points: bool = False
+ normalize_points: bool = False,
) -> torch.Tensor:
"""Warp a tensor from a source to destination frame by the depth in the destination.
@@ -208,7 +205,7 @@ class DepthWarper(nn.Module):
width: int,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: bool = True
+ align_corners: bool = True,
):
super(DepthWarper, self).__init__()
# constructor members
@@ -232,8 +229,7 @@ class DepthWarper(nn.Module):
return convert_points_to_homogeneous(grid) # append ones to last dim
def compute_projection_matrix(self, pinhole_src: PinholeCamera) -> 'DepthWarper':
- r"""Computes the projection matrix from the source to destination frame.
- """
+ 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 "
@@ -241,14 +237,12 @@ class DepthWarper(nn.Module):
)
if not isinstance(pinhole_src, PinholeCamera):
raise TypeError(
- "Argument pinhole_src expected to be of class "
- "PinholeCamera. Got {}".format(type(pinhole_src))
+ "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(
- self._pinhole_dst.extrinsics,
- inverse_transformation(pinhole_src.extrinsics),
+ self._pinhole_dst.extrinsics, inverse_transformation(pinhole_src.extrinsics)
)
# compute the projection matrix between the non reference cameras and
@@ -265,9 +259,9 @@ class DepthWarper(nn.Module):
[[[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)
- y = (flow[:, 1] * z)
+ z = 1.0 / flow[:, 2]
+ x = flow[:, 0] * z
+ y = flow[:, 1] * z
return torch.cat([x, y], 1)
def compute_subpixel_step(self) -> torch.Tensor:
@@ -312,8 +306,7 @@ class DepthWarper(nn.Module):
# 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
+ depth_src, self._pinhole_src.intrinsics_inverse().to(device=device, dtype=dtype), pixel_coords
) # BxHxWx3
# reproject the camera coordinates to the pixel
@@ -325,9 +318,7 @@ class DepthWarper(nn.Module):
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:
+ def forward(self, depth_src: torch.Tensor, patch_dst: torch.Tensor) -> torch.Tensor: # type: ignore
"""Warps a tensor from destination frame to reference given the depth
in the reference frame.
@@ -362,7 +353,7 @@ class DepthWarper(nn.Module):
self.warp_grid(depth_src), # type: ignore
mode=self.mode,
padding_mode=self.padding_mode,
- align_corners=self.align_corners
+ align_corners=self.align_corners,
)
@@ -373,7 +364,7 @@ def depth_warp(
patch_dst: torch.Tensor,
height: int,
width: int,
- align_corners: bool = True
+ 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 204227798..7c6e9f02e 100644
--- a/kornia/geometry/epipolar/essential.py
+++ b/kornia/geometry/epipolar/essential.py
@@ -52,16 +52,16 @@ 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.0 # fill last column with negative values
maskt = mask.transpose(-2, -1)
# avoid singularities
- U = torch.where((torch.det(U) < 0.)[..., None, None], U * mask, U)
- Vt = torch.where((torch.det(Vt) < 0.)[..., None, None], Vt * maskt, Vt)
+ U = torch.where((torch.det(U) < 0.0)[..., None, None], U * mask, U)
+ Vt = torch.where((torch.det(Vt) < 0.0)[..., None, None], Vt * maskt, Vt)
- W = numeric.cross_product_matrix(torch.tensor([[0., 0., 1.]]).type_as(E_mat))
- W[..., 2, 2] += 1.
+ W = numeric.cross_product_matrix(torch.tensor([[0.0, 0.0, 1.0]]).type_as(E_mat))
+ W[..., 2, 2] += 1.0
# reconstruct rotations and retrieve translation vector
U_W_Vt = U @ W @ Vt
@@ -100,7 +100,7 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:
# get the cross product from relative translation vector
Tx = numeric.cross_product_matrix(t[..., 0])
- return (Tx @ R)
+ return Tx @ R
def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
@@ -214,7 +214,7 @@ def motion_from_essential_choose_solution(
d2 = projection.depth(R2, t2, X)
# verify the point values that have a postive depth value
- depth_mask = ((d1 > 0.) & (d2 > 0.))
+ depth_mask = (d1 > 0.0) & (d2 > 0.0)
if mask is not None:
depth_mask &= mask.unsqueeze(1)
@@ -233,8 +233,9 @@ 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 9052c8940..bf40ef976 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -31,13 +31,12 @@ 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 = torch.sqrt(torch.tensor(2.)) / (scale + eps) # B
+ scale = torch.sqrt(torch.tensor(2.0)) / (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
+ [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
@@ -106,7 +105,7 @@ def find_fundamental(points1: torch.Tensor, points2: torch.Tensor, weights: torc
# reconstruct and force the matrix to have rank2
U, S, V = torch.svd(F_mat)
- rank_mask = torch.tensor([1., 1., 0]).to(F_mat.device)
+ rank_mask = torch.tensor([1.0, 1.0, 0]).to(F_mat.device)
F_projected = U @ (torch.diag_embed(S * rank_mask) @ V.transpose(-2, -1))
F_est = transform2.transpose(-2, -1) @ (F_projected @ transform1)
@@ -139,7 +138,7 @@ def compute_correspond_epilines(points: torch.Tensor, F_mat: torch.Tensor) -> to
# compute normal and compose equation line
nu: torch.Tensor = a * a + b * b
- nu = torch.where(nu > 0., 1. / torch.sqrt(nu), torch.ones_like(nu))
+ nu = torch.where(nu > 0.0, 1.0 / torch.sqrt(nu), torch.ones_like(nu))
line = torch.cat([a * nu, b * nu, c * nu], dim=1) # Bx3xN
return line.permute(0, 2, 1) # BxNx3
@@ -214,7 +213,7 @@ def fundamental_from_projections(P1: torch.Tensor, P2: torch.Tensor) -> torch.Te
X2Y3.det().reshape(-1, 1),
X3Y3.det().reshape(-1, 1),
],
- dim=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 b0b015a9c..e59b82933 100644
--- a/kornia/geometry/epipolar/metrics.py
+++ b/kornia/geometry/epipolar/metrics.py
@@ -102,8 +102,8 @@ def symmetrical_epipolar_distance(
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.0 / (line1_in_2[..., :2].norm(2, dim=2).pow(2)) + 1.0 / (
+ line2_in_1[..., :2].norm(2, dim=2).pow(2)
)
out: torch.Tensor = numerator * denominator_inv
if squared:
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 95fd7ef27..ed730ae2d 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -28,8 +28,8 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
intrinsics = numeric.eye_like(3, input)
intrinsics[..., 0, 0] *= focal
intrinsics[..., 1, 1] *= focal
- intrinsics[..., 0, 2] += 1. * W / 2
- intrinsics[..., 1, 2] += 1. * H / 2
+ intrinsics[..., 0, 2] += 1.0 * W / 2
+ intrinsics[..., 1, 2] += 1.0 * H / 2
return intrinsics
@@ -45,19 +45,9 @@ def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.
"""
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,
- ])
+ camera_matrix: torch.Tensor = torch.cat([fx, zeros, cx, zeros, fy, cy, zeros, zeros, ones])
return camera_matrix.view(1, 3, 3)
@@ -103,11 +93,11 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> to
assert len(K.shape) == len(R.shape) == len(t.shape)
Rt: torch.Tensor = torch.cat([R, t], dim=-1) # 3x4
- Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], "constant", 0.) # 4x4
- Rt_h[..., -1, -1] += 1.
+ Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4
+ Rt_h[..., -1, -1] += 1.0
- K_h: torch.Tensor = torch.nn.functional.pad(K, [0, 1, 0, 1], "constant", 0.) # 4x4
- K_h[..., -1, -1] += 1.
+ K_h: torch.Tensor = torch.nn.functional.pad(K, [0, 1, 0, 1], "constant", 0.0) # 4x4
+ K_h[..., -1, -1] += 1.0
return K @ Rt
diff --git a/kornia/geometry/epipolar/scene.py b/kornia/geometry/epipolar/scene.py
index b0afd4e05..0802eee49 100644
--- a/kornia/geometry/epipolar/scene.py
+++ b/kornia/geometry/epipolar/scene.py
@@ -12,10 +12,10 @@ def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
points3d = torch.rand(1, num_points, 3) # NxMx3
# Create random camera matrix
- K = epipolar.random_intrinsics(0., 100.) # 1x3x3
+ K = epipolar.random_intrinsics(0.0, 100.0) # 1x3x3
# Create random rotation per view
- ang = torch.rand(num_views, 1) * kornia.pi * 2.
+ ang = torch.rand(num_views, 1) * kornia.pi * 2.0
rvec = torch.rand(num_views, 3)
rvec = ang * rvec / torch.norm(rvec, dim=1, keepdim=True) # Nx3
@@ -31,7 +31,7 @@ def generate_scene(num_views: int, num_points: int) -> Dict[str, torch.Tensor]:
# Make sure the shape is in front of the camera
points3d_trans = (rot_mat @ points3d.transpose(-2, -1)) + tvec
min_dist = torch.min(points3d_trans[:, 2], dim=1)[0]
- tvec[:, 2, 0] = torch.where(min_dist < 0, tz - min_dist + 1., tz)
+ tvec[:, 2, 0] = torch.where(min_dist < 0, tz - min_dist + 1.0, tz)
# compute projection matrices
P = epipolar.projection_from_KRt(K, rot_mat, tvec)
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index edb6a0c1b..3a430142a 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -68,11 +68,7 @@ def find_homography_dlt(
def find_homography_dlt_iterated(
- points1: torch.Tensor,
- points2: torch.Tensor,
- weights: torch.Tensor,
- soft_inl_th: float = 3.0,
- n_iter: int = 5
+ 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).
@@ -95,6 +91,6 @@ def find_homography_dlt_iterated(
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 9fc5c15aa..ca0ea403d 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -215,7 +215,7 @@ def transform_points(trans_01: torch.Tensor, points_1: torch.Tensor) -> torch.Te
def transform_boxes(trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy") -> torch.Tensor:
- r""" Function that applies a transformation matrix to a box or batch of boxes. Boxes must
+ r"""Function that applies a transformation matrix to a box or batch of boxes. Boxes must
be a tensor of the shape (N, 4) or a batch of boxes (B, N, 4) and trans_mat must be a (3, 3)
transformation matrix or a batch of transformation matrices (B, 3, 3)
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 0d223ef3c..9cde27ee1 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -18,10 +18,7 @@ def _validate_batched_image_tensor_input(tensor):
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),
-) -> torch.Tensor:
+def spatial_softmax2d(input: torch.Tensor, temperature: torch.Tensor = torch.tensor(1.0)) -> torch.Tensor:
r"""Applies the Softmax function over features in each image channel.
Note that this function behaves differently to `torch.nn.Softmax2d`, which
@@ -59,10 +56,7 @@ def spatial_softmax2d(
return x_soft.view(batch_size, channels, height, width)
-def spatial_expectation2d(
- input: torch.Tensor,
- normalized_coordinates: bool = True,
-) -> torch.Tensor:
+def spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = True) -> torch.Tensor:
r"""Computes the expectation of coordinate values using spatial probabilities.
The input heatmap is assumed to represent a valid spatial probability
@@ -113,19 +107,12 @@ def spatial_expectation2d(
return output.view(batch_size, channels, 2) # BxNx2
-def _safe_zero_division(
- numerator: torch.Tensor,
- denominator: torch.Tensor,
- eps: float = 1e-32,
-) -> torch.Tensor:
+def _safe_zero_division(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.
@@ -160,8 +147,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 bf1fcde41..f4362b0ca 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -134,7 +134,7 @@ class ConvSoftArgmax2d(nn.Module):
temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
normalized_coordinates: bool = True,
eps: float = 1e-8,
- output_value: bool = False
+ output_value: bool = False,
) -> None:
super(ConvSoftArgmax2d, self).__init__()
self.kernel_size = kernel_size
@@ -146,19 +146,42 @@ class ConvSoftArgmax2d(nn.Module):
self.output_value = output_value
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'kernel_size=' + str(self.kernel_size) +\
- ', ' + 'stride=' + str(self.stride) +\
- ', ' + 'padding=' + str(self.padding) +\
- ', ' + 'temperature=' + str(self.temperature) +\
- ', ' + 'normalized_coordinates=' + str(self.normalized_coordinates) +\
- ', ' + 'eps=' + str(self.eps) +\
- ', ' + 'output_value=' + str(self.output_value) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'kernel_size='
+ + str(self.kernel_size)
+ + ', '
+ + 'stride='
+ + str(self.stride)
+ + ', '
+ + 'padding='
+ + str(self.padding)
+ + ', '
+ + 'temperature='
+ + str(self.temperature)
+ + ', '
+ + 'normalized_coordinates='
+ + str(self.normalized_coordinates)
+ + ', '
+ + 'eps='
+ + str(self.eps)
+ + ', '
+ + '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
+ x,
+ self.kernel_size,
+ self.stride,
+ self.padding,
+ self.temperature,
+ self.normalized_coordinates,
+ self.eps,
+ self.output_value,
)
@@ -177,7 +200,7 @@ class ConvSoftArgmax3d(nn.Module):
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
- strict_maxima_bonus: float = 0.0
+ strict_maxima_bonus: float = 0.0,
) -> None:
super(ConvSoftArgmax3d, self).__init__()
self.kernel_size = kernel_size
@@ -191,20 +214,46 @@ class ConvSoftArgmax3d(nn.Module):
return
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(' + 'kernel_size=' + str(self.kernel_size) +\
- ', ' + 'stride=' + str(self.stride) +\
- ', ' + 'padding=' + str(self.padding) +\
- ', ' + 'temperature=' + str(self.temperature) +\
- ', ' + 'normalized_coordinates=' + str(self.normalized_coordinates) +\
- ', ' + 'eps=' + str(self.eps) +\
- ', ' + 'strict_maxima_bonus=' + str(self.strict_maxima_bonus) +\
- ', ' + 'output_value=' + str(self.output_value) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'kernel_size='
+ + str(self.kernel_size)
+ + ', '
+ + 'stride='
+ + str(self.stride)
+ + ', '
+ + 'padding='
+ + str(self.padding)
+ + ', '
+ + 'temperature='
+ + str(self.temperature)
+ + ', '
+ + 'normalized_coordinates='
+ + str(self.normalized_coordinates)
+ + ', '
+ + 'eps='
+ + str(self.eps)
+ + ', '
+ + 'strict_maxima_bonus='
+ + str(self.strict_maxima_bonus)
+ + ', '
+ + '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
+ x,
+ self.kernel_size,
+ self.stride,
+ self.padding,
+ self.temperature,
+ self.normalized_coordinates,
+ self.eps,
+ self.output_value,
+ self.strict_maxima_bonus,
)
@@ -216,7 +265,7 @@ def conv_soft_argmax2d(
temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
normalized_coordinates: bool = True,
eps: float = 1e-8,
- output_value: bool = False
+ 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
@@ -328,7 +377,7 @@ def conv_soft_argmax3d(
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
- strict_maxima_bonus: float = 0.0
+ 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
@@ -430,15 +479,15 @@ def conv_soft_argmax3d(
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)
skip_levels: int = (in_levels - out_levels) // 2
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]
+ 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))
return coords_max, x_softmaxpool
@@ -448,7 +497,7 @@ def spatial_soft_argmax2d(
input: torch.Tensor,
temperature: torch.Tensor = torch.tensor(1.0),
normalized_coordinates: bool = True,
- eps: float = 1e-8
+ eps: float = 1e-8,
) -> torch.Tensor:
r"""Function that computes the Spatial Soft-Argmax 2D
of a given input heatmap.
@@ -488,10 +537,7 @@ class SpatialSoftArgmax2d(nn.Module):
"""
def __init__(
- self,
- temperature: torch.Tensor = torch.tensor(1.0),
- normalized_coordinates: bool = True,
- eps: float = 1e-8
+ 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
@@ -499,10 +545,18 @@ class SpatialSoftArgmax2d(nn.Module):
self.eps: float = eps
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(temperature=' + str(self.temperature) + ', ' +\
- 'normalized_coordinates=' + str(self.normalized_coordinates) + ', ' + \
- 'eps=' + str(self.eps) + ')'
+ return (
+ self.__class__.__name__
+ + '(temperature='
+ + str(self.temperature)
+ + ', '
+ + 'normalized_coordinates='
+ + str(self.normalized_coordinates)
+ + ', '
+ + '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)
@@ -570,7 +624,7 @@ def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, e
dx: torch.Tensor = -x_solved
# Ignore ones, which are far from window center
- mask1 = (dx.abs().max(dim=1, keepdim=True)[0] > 0.7)
+ mask1 = dx.abs().max(dim=1, keepdim=True)[0] > 0.7
dx.masked_fill_(mask1.expand_as(dx), 0)
dy: torch.Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
y_max = input + dy.view(B, CH, D, H, W)
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index f69a66646..3554a82bc 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -6,8 +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
@@ -75,8 +75,9 @@ def _compute_rotation_matrix3d(
pitch = pitch.unsqueeze(dim=1)
roll = roll.unsqueeze(dim=1)
- assert len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 2, \
- f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}."
+ assert (
+ len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 2
+ ), f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}."
angles: torch.Tensor = torch.cat([yaw, pitch, roll], dim=1)
scales: torch.Tensor = torch.ones_like(yaw)
@@ -122,7 +123,7 @@ def affine(
matrix: torch.Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Apply an affine transformation to the image.
@@ -172,7 +173,7 @@ def affine3d(
matrix: torch.Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: bool = False
+ align_corners: bool = False,
) -> torch.Tensor:
r"""Apply an affine transformation to the 3d volume.
@@ -228,7 +229,7 @@ def rotate(
center: Union[None, torch.Tensor] = None,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Rotate the tensor anti-clockwise about the centre.
@@ -264,10 +265,7 @@ def rotate(
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)))
- if len(tensor.shape) not in (
- 3,
- 4,
- ):
+ 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
@@ -292,7 +290,7 @@ def rotate3d(
center: Union[None, torch.Tensor] = None,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: bool = False
+ align_corners: bool = False,
) -> torch.Tensor:
r"""Rotate 3D the tensor anti-clockwise about the centre.
@@ -331,10 +329,7 @@ def rotate3d(
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)))
- if len(tensor.shape) not in (
- 4,
- 5,
- ):
+ 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
@@ -358,7 +353,7 @@ def translate(
translation: torch.Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Translate the tensor in pixel units.
@@ -389,10 +384,7 @@ def translate(
if not isinstance(translation, torch.Tensor):
raise TypeError("Input translation type is not a torch.Tensor. Got {}".format(type(translation)))
- if len(tensor.shape) not in (
- 3,
- 4,
- ):
+ 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
@@ -408,7 +400,7 @@ def scale(
center: Union[None, torch.Tensor] = None,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Scale the tensor by a factor.
@@ -466,7 +458,7 @@ def shear(
shear: torch.Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: bool = False
+ align_corners: bool = False,
) -> torch.Tensor:
r"""Shear the tensor.
@@ -497,10 +489,7 @@ def shear(
if not isinstance(shear, torch.Tensor):
raise TypeError("Input shear type is not a torch.Tensor. Got {}".format(type(shear)))
- if len(tensor.shape) not in (
- 3,
- 4,
- ):
+ 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
@@ -529,7 +518,7 @@ def resize(
interpolation: str = 'bilinear',
align_corners: Optional[bool] = None,
side: str = "short",
- antialias: bool = False
+ antialias: bool = False,
) -> torch.Tensor:
r"""Resize the input torch.Tensor to the given size.
@@ -600,7 +589,7 @@ def rescale(
factor: Union[float, Tuple[float, float]],
interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
- antialias: bool = False
+ antialias: bool = False,
) -> torch.Tensor:
r"""Rescale the input torch.Tensor with the given factor.
@@ -667,7 +656,7 @@ class Resize(nn.Module):
interpolation: str = 'bilinear',
align_corners: Optional[bool] = None,
side: str = "short",
- antialias: bool = False
+ antialias: bool = False,
) -> None:
super(Resize, self).__init__()
self.size: Union[int, Tuple[int, int]] = size
@@ -683,7 +672,7 @@ class Resize(nn.Module):
self.interpolation,
align_corners=self.align_corners,
side=self.side,
- antialias=self.antialias
+ antialias=self.antialias,
)
@@ -731,7 +720,7 @@ class Affine(nn.Module):
center: Optional[torch.Tensor] = None,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ 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:
@@ -811,7 +800,7 @@ class Rescale(nn.Module):
factor: Union[float, Tuple[float, float]],
interpolation: str = "bilinear",
align_corners: Optional[bool] = None,
- antialias: bool = False
+ antialias: bool = False,
) -> None:
super().__init__()
self.factor: Union[float, Tuple[float, float]] = factor
@@ -857,7 +846,7 @@ class Rotate(nn.Module):
center: Union[None, torch.Tensor] = None,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> None:
super(Rotate, self).__init__()
self.angle: torch.Tensor = angle
@@ -899,7 +888,7 @@ class Translate(nn.Module):
translation: torch.Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> None:
super(Translate, self).__init__()
self.translation: torch.Tensor = translation
@@ -945,7 +934,7 @@ class Scale(nn.Module):
center: Union[None, torch.Tensor] = None,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> None:
super(Scale, self).__init__()
self.scale_factor: torch.Tensor = scale_factor
@@ -984,11 +973,7 @@ class Shear(nn.Module):
"""
def __init__(
- self,
- shear: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = False
+ 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
diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.py
index 0c40ffd7b..cf15bb698 100644
--- a/kornia/geometry/transform/crop/crop2d.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -2,7 +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",
@@ -22,7 +22,7 @@ def crop_and_resize(
size: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Extract crops from 2D images (4D tensor) and resize given a bounding box.
@@ -66,10 +66,7 @@ def crop_and_resize(
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) == 2:
+ 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}."
@@ -84,12 +81,7 @@ def crop_and_resize(
# [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
+ [[[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)
@@ -100,7 +92,7 @@ def center_crop(
size: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Crop the 2D images (4D tensor) from the center.
@@ -131,10 +123,7 @@ def center_crop(
if not isinstance(tensor, torch.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:
+ 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}."
@@ -158,25 +147,15 @@ def center_crop(
# [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],
- ]],
+ [[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]],
device=tensor.device,
- dtype=tensor.dtype
+ 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
+ [[[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)
@@ -188,7 +167,7 @@ def crop_by_boxes(
dst_box: torch.Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
"""Perform crop transform on 2D images (4D tensor) given two bounding boxes.
@@ -248,8 +227,7 @@ def crop_by_boxes(
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"Cropping height, width and depth must be exact same in a batch. " f"Got height {bbox[0]} and width {bbox[1]}."
)
h_out: int = int(bbox[0][0].item())
@@ -266,7 +244,7 @@ def crop_by_transform_mat(
out_size: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
"""Perform crop transform on 2D images (4D tensor) given a perspective transformation matrix.
@@ -324,8 +302,8 @@ def infer_box_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
(tensor([2., 2.]), tensor([2., 3.]))
"""
validate_bboxes(boxes)
- width: torch.Tensor = (boxes[:, 1, 0] - boxes[:, 0, 0] + 1)
- height: torch.Tensor = (boxes[:, 2, 1] - boxes[:, 0, 1] + 1)
+ width: torch.Tensor = boxes[:, 1, 0] - boxes[:, 0, 0] + 1
+ height: torch.Tensor = boxes[:, 2, 1] - boxes[:, 0, 1] + 1
return (height, width)
@@ -344,14 +322,14 @@ def validate_bboxes(boxes: torch.Tensor) -> bool:
"""
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))
+ "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))
+ "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
@@ -441,10 +419,14 @@ def bbox_generator(
[3, 3],
[1, 3]]])
"""
- assert x_start.shape == y_start.shape and x_start.dim() in [0, 1], \
- f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."
- assert width.shape == height.shape and width.dim() in [0, 1], \
- f"`width` and `height` must be a scalar or (B,). Got {width}, {height}."
+ assert x_start.shape == y_start.shape and x_start.dim() in [
+ 0,
+ 1,
+ ], f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."
+ assert width.shape == height.shape and width.dim() in [
+ 0,
+ 1,
+ ], f"`width` and `height` must be a scalar or (B,). Got {width}, {height}."
assert x_start.dtype == y_start.dtype == width.dtype == height.dtype, (
"All tensors must be in the same dtype. Got "
f"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype})."
@@ -454,12 +436,9 @@ def bbox_generator(
f"`x_start`({x_start.device}), `y_start`({x_start.device}), `width`({width.device}), `height`({height.device})."
)
- bbox = torch.tensor([[
- [0, 0],
- [0, 0],
- [0, 0],
- [0, 0],
- ]], device=x_start.device, dtype=x_start.dtype).repeat(1 if x_start.dim() == 0 else len(x_start), 1, 1)
+ bbox = torch.tensor([[[0, 0], [0, 0], [0, 0], [0, 0]]], device=x_start.device, dtype=x_start.dtype).repeat(
+ 1 if x_start.dim() == 0 else len(x_start), 1, 1
+ )
bbox[:, :, 0] += x_start.view(-1, 1)
bbox[:, :, 1] += y_start.view(-1, 1)
diff --git a/kornia/geometry/transform/crop/crop3d.py b/kornia/geometry/transform/crop/crop3d.py
index 0dffa139a..981b1e69c 100644
--- a/kornia/geometry/transform/crop/crop3d.py
+++ b/kornia/geometry/transform/crop/crop3d.py
@@ -2,7 +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",
@@ -21,7 +21,7 @@ def crop_and_resize3d(
boxes: torch.Tensor,
size: Tuple[int, int, int],
interpolation: str = 'bilinear',
- align_corners: bool = False
+ align_corners: bool = False,
) -> torch.Tensor:
r"""Extract crops from 3D volumes (5D tensor) and resize them.
@@ -83,10 +83,7 @@ def crop_and_resize3d(
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:
+ 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
@@ -114,17 +111,14 @@ def crop_and_resize3d(
]
],
dtype=tensor.dtype,
- device=tensor.device
+ 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
+ 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.
@@ -173,10 +167,7 @@ def center_crop3d(
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:
+ 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
@@ -214,7 +205,7 @@ def center_crop3d(
[start_x, end_y, end_z],
]
],
- device=tensor.device
+ device=tensor.device,
)
# [x, y, z] destination
@@ -233,7 +224,7 @@ def center_crop3d(
[0, dst_h - 1, dst_d - 1],
]
],
- device=tensor.device
+ device=tensor.device,
).expand(points_src.shape[0], -1, -1)
return crop_by_boxes3d(
@@ -246,7 +237,7 @@ def crop_by_boxes3d(
src_box: torch.Tensor,
dst_box: torch.Tensor,
interpolation: str = 'bilinear',
- align_corners: bool = False
+ align_corners: bool = False,
) -> torch.Tensor:
"""Perform crop transform on 3D volumes (5D tensor) by bounding boxes.
@@ -335,9 +326,10 @@ def crop_by_boxes3d(
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())),
+ dst_trans_src,
+ (int(bbox[0][0].item()), int(bbox[1][0].item()), int(bbox[2][0].item())),
mode=interpolation,
- align_corners=align_corners
+ align_corners=align_corners,
)
return patches
@@ -349,7 +341,7 @@ def crop_by_transform_mat3d(
out_size: Tuple[int, int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
"""Perform crop transform on 3D volumes (5D tensor) given a perspective transformation matrix.
@@ -436,24 +428,28 @@ def validate_bboxes3d(boxes: torch.Tensor) -> None:
order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in the x, y, z order.
"""
- assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size([8, 3]), \
- f"Box shape must be (B, 8, 3). Got {boxes.shape}."
+ assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size(
+ [8, 3]
+ ), f"Box shape must be (B, 8, 3). Got {boxes.shape}."
left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6], device=boxes.device, dtype=torch.long))[:, :, 0]
right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7], device=boxes.device, dtype=torch.long))[:, :, 0]
- widths = (left - right + 1)
- assert torch.allclose(widths.permute(1, 0), widths[:, 0]), \
- f"Boxes must have be cube, while get different widths {widths}."
+ widths = left - right + 1
+ assert torch.allclose(
+ widths.permute(1, 0), widths[:, 0]
+ ), f"Boxes must have be cube, while get different widths {widths}."
bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7], device=boxes.device, dtype=torch.long))[:, :, 1]
upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5], device=boxes.device, dtype=torch.long))[:, :, 1]
- heights = (bot - upper + 1)
- assert torch.allclose(heights.permute(1, 0), heights[:, 0]), \
- f"Boxes must have be cube, while get different heights {heights}."
+ heights = bot - upper + 1
+ assert torch.allclose(
+ heights.permute(1, 0), heights[:, 0]
+ ), f"Boxes must have be cube, while get different heights {heights}."
- depths = (boxes[:, 4:, 2] - boxes[:, :4, 2] + 1)
- assert torch.allclose(depths.permute(1, 0), depths[:, 0]), \
- f"Boxes must have be cube, while get different depths {depths}."
+ depths = boxes[:, 4:, 2] - boxes[:, :4, 2] + 1
+ assert torch.allclose(
+ depths.permute(1, 0), depths[:, 0]
+ ), f"Boxes must have be cube, while get different depths {depths}."
def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Tensor:
@@ -512,16 +508,19 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Ten
# 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)
+ 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)
+ 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)
+ 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)
@@ -534,8 +533,12 @@ 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.
@@ -582,10 +585,14 @@ def bbox_generator3d(
[43, 54, 65],
[ 3, 54, 65]]])
"""
- assert x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [0, 1], \
- f"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}."
- assert width.shape == height.shape == depth.shape and width.dim() in [0, 1], \
- f"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}."
+ assert x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [
+ 0,
+ 1,
+ ], f"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}."
+ assert width.shape == height.shape == depth.shape and width.dim() in [
+ 0,
+ 1,
+ ], f"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}."
assert x_start.dtype == y_start.dtype == z_start.dtype == width.dtype == height.dtype == depth.dtype, (
"All tensors must be in the same dtype. "
f"Got `x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `z_start`({x_start.dtype}), "
@@ -598,12 +605,9 @@ def bbox_generator3d(
)
# front
- bbox = torch.tensor([[
- [0, 0, 0],
- [0, 0, 0],
- [0, 0, 0],
- [0, 0, 0],
- ]], device=x_start.device, dtype=x_start.dtype).repeat(len(x_start), 1, 1)
+ bbox = torch.tensor(
+ [[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]], device=x_start.device, dtype=x_start.dtype
+ ).repeat(len(x_start), 1, 1)
bbox[:, :, 0] += x_start.view(-1, 1)
bbox[:, :, 1] += y_start.view(-1, 1)
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index ae7fa7ef5..0ba526a36 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -13,10 +13,10 @@ 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.),
+ sigma: Tuple[float, float] = (32.0, 32.0),
+ alpha: Tuple[float, float] = (1.0, 1.0),
align_corners: bool = False,
- mode: str = 'bilinear'
+ mode: str = 'bilinear',
) -> torch.Tensor:
r"""Applies elastic transform of images as described in :cite:`Simard2003BestPF`.
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index c959f0d60..3ea7912e3 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -78,7 +78,7 @@ def homography_warp(
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
- normalized_coordinates: bool = True
+ normalized_coordinates: bool = True,
) -> torch.Tensor:
r"""Warp image patchs or tensors by normalized 2D homographies.
@@ -111,7 +111,9 @@ def homography_warp(
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)
+ Got patch.device: {} src_H_dst.device: {}.".format(
+ patch_src.device, src_homo_dst.device
+ )
)
height, width = dsize
@@ -128,7 +130,7 @@ def homography_warp3d(
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
- normalized_coordinates: bool = True
+ normalized_coordinates: bool = True,
) -> torch.Tensor:
r"""Warp image patchs or tensors by normalized 3D homographies.
@@ -159,7 +161,9 @@ def homography_warp3d(
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)
+ Got patch.device: {} src_H_dst.device: {}.".format(
+ patch_src.device, src_homo_dst.device
+ )
)
depth, height, width = dsize
@@ -200,7 +204,7 @@ class HomographyWarper(nn.Module):
mode: str = 'bilinear',
padding_mode: str = 'zeros',
normalized_coordinates: bool = True,
- align_corners: bool = False
+ align_corners: bool = False,
) -> None:
super(HomographyWarper, self).__init__()
self.width: int = width
@@ -226,7 +230,7 @@ class HomographyWarper(nn.Module):
has to be :math:`(1, 3, 3)` or :math:`(N, 1, 3, 3)`.
The homography assumes normalized coordinates [-1, 1] if
normalized_coordinates is True.
- """
+ """
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:
@@ -260,11 +264,12 @@ class HomographyWarper(nn.Module):
if src_homo_dst is not None:
warped_patch = homography_warp(
patch_src,
- src_homo_dst, (self.height, self.width),
+ 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
+ normalized_coordinates=self.normalized_coordinates,
)
elif _warped_grid is not None:
if not _warped_grid.device == patch_src.device:
@@ -281,7 +286,7 @@ class HomographyWarper(nn.Module):
_warped_grid,
mode=self.mode,
padding_mode=self.padding_mode,
- align_corners=self.align_corners
+ align_corners=self.align_corners,
)
else:
raise RuntimeError(
@@ -298,7 +303,7 @@ def normal_transform_pixel(
width: int,
eps: float = 1e-14,
device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None
+ dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
@@ -328,7 +333,7 @@ def normal_transform_pixel3d(
width: int,
eps: float = 1e-14,
device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None
+ dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
@@ -344,7 +349,7 @@ def normal_transform_pixel3d(
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
+ dtype=dtype,
) # 4x4
# prevent divide by zero bugs
@@ -391,7 +396,7 @@ def normalize_homography(
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
@@ -428,5 +433,5 @@ def normalize_homography3d(
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)
# 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 64cbb8788..d17eaf7c5 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -4,19 +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
+ 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",
]
@@ -26,7 +37,7 @@ def warp_perspective(
dsize: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Applies a perspective transformation to an image.
@@ -98,8 +109,9 @@ def warp_perspective(
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm) # Bx3x3
# this piece of code substitutes F.affine_grid since it does not support 3x3
- grid = create_meshgrid(h_out, w_out, normalized_coordinates=True,
- device=src.device).to(src.dtype).repeat(B, 1, 1, 1)
+ grid = (
+ create_meshgrid(h_out, w_out, normalized_coordinates=True, 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)
@@ -111,7 +123,7 @@ def warp_affine(
dsize: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Applies an affine transformation to a tensor.
@@ -264,7 +276,7 @@ def get_perspective_transform(src, dst):
dst[:, 3:4, 0],
dst[:, 3:4, 1],
],
- dim=1
+ dim=1,
)
# solve the system Ax = b
@@ -393,8 +405,11 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
# 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
@@ -407,7 +422,7 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
# create output tensor
batch_size: int = center.shape[0]
- one = torch.tensor(1., device=center.device, dtype=center.dtype)
+ one = torch.tensor(1.0, 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
@@ -423,7 +438,7 @@ def remap(
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: Optional[bool] = None,
- normalized_coordinates: bool = False
+ normalized_coordinates: bool = False,
) -> torch.Tensor:
r"""Applies a generic geometrical transformation to a tensor.
@@ -535,7 +550,7 @@ def get_affine_matrix2d(
scale: torch.Tensor,
angle: torch.Tensor,
sx: Optional[torch.Tensor] = None,
- sy: Optional[torch.Tensor] = None
+ sy: Optional[torch.Tensor] = None,
) -> torch.Tensor:
r"""Composes affine matrix from the components.
@@ -599,8 +614,8 @@ def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None,
.. note::
This function is often used in conjuntion with :func:`warp_affine`, :func:`warp_perspective`.
"""
- sx = torch.tensor([0.]).repeat(center.size(0)) if sx is None else sx
- sy = torch.tensor([0.]).repeat(center.size(0)) if sy is None else sy
+ sx = torch.tensor([0.0]).repeat(center.size(0)) if sx is None else sx
+ sy = torch.tensor([0.0]).repeat(center.size(0)) if sy is None else sy
x, y = torch.split(center, 1, dim=-1)
x, y = x.view(-1), y.view(-1)
@@ -615,9 +630,9 @@ def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None,
sx_tan * y, # type: ignore # noqa: E241
-sy_tan,
ones + sx_tan * sy_tan,
- sy_tan * (sx_tan * y + x) # noqa: E241
+ sy_tan * (sx_tan * y + x), # noqa: E241
],
- dim=-1
+ dim=-1,
).view(-1, 2, 3)
shear_mat = convert_affinematrix_to_homography(shear_mat)
@@ -634,7 +649,7 @@ def get_affine_matrix3d(
syx: Optional[torch.Tensor] = None,
syz: Optional[torch.Tensor] = None,
szx: Optional[torch.Tensor] = None,
- szy: Optional[torch.Tensor] = None
+ szy: Optional[torch.Tensor] = None,
) -> torch.Tensor:
r"""Composes 3d affine matrix from the components.
@@ -726,12 +741,12 @@ def get_shear_matrix3d(
.. note::
This function is often used in conjuntion with :func:`warp_perspective3d`.
"""
- sxy = torch.tensor([0.]).repeat(center.size(0)) if sxy is None else sxy
- sxz = torch.tensor([0.]).repeat(center.size(0)) if sxz is None else sxz
- syx = torch.tensor([0.]).repeat(center.size(0)) if syx is None else syx
- syz = torch.tensor([0.]).repeat(center.size(0)) if syz is None else syz
- szx = torch.tensor([0.]).repeat(center.size(0)) if szx is None else szx
- szy = torch.tensor([0.]).repeat(center.size(0)) if szy is None else szy
+ sxy = torch.tensor([0.0]).repeat(center.size(0)) if sxy is None else sxy
+ sxz = torch.tensor([0.0]).repeat(center.size(0)) if sxz is None else sxz
+ syx = torch.tensor([0.0]).repeat(center.size(0)) if syx is None else syx
+ syz = torch.tensor([0.0]).repeat(center.size(0)) if syz is None else syz
+ szx = torch.tensor([0.0]).repeat(center.size(0)) if szx is None else szx
+ szy = torch.tensor([0.0]).repeat(center.size(0)) if szy is None else szy
x, y, z = torch.split(center, 1, dim=-1)
x, y, z = x.view(-1), y.view(-1), z.view(-1)
@@ -753,8 +768,7 @@ def get_shear_matrix3d(
m23 = m20 * x + m21 * y + m22 * z - z
# shear matrix is implemented with negative values
- sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan = \
- - sxy_tan, - sxz_tan, - syx_tan, - syz_tan, - szx_tan, - szy_tan
+ 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
)
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index 5d45a6e40..b243c1893 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -11,8 +11,11 @@ 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_perspective3d"
+ "warp_affine3d",
+ "get_projective_transform",
+ "projection_from_Rt",
+ "get_perspective_transform3d",
+ "warp_perspective3d",
]
@@ -22,7 +25,7 @@ def warp_affine3d(
dsize: Tuple[int, int, int],
flags: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: Optional[bool] = None
+ align_corners: Optional[bool] = None,
) -> torch.Tensor:
r"""Applies a projective transformation a to 3d tensor.
@@ -147,7 +150,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
# chain 4x4 transforms
proj_mat = convert_affinematrix_to_homography3d(proj_mat) # Bx4x4
- proj_mat = (from_origin_mat @ proj_mat @ to_origin_mat)
+ proj_mat = from_origin_mat @ proj_mat @ to_origin_mat
return proj_mat[..., :3, :] # Bx3x4
@@ -279,7 +282,7 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
dst[:, 7:8, 1],
dst[:, 7:8, 2],
],
- dim=1
+ dim=1,
)
# solve the system Ax = b
@@ -299,28 +302,67 @@ def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> t
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]
+ 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
+ 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]
+ 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
+ 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]
+ 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
+ dim=1,
)
raise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")
@@ -332,7 +374,7 @@ def warp_perspective3d(
dsize: Tuple[int, int, int],
flags: str = 'bilinear',
border_mode: str = 'zeros',
- align_corners: bool = False
+ align_corners: bool = False,
) -> torch.Tensor:
r"""Applies a perspective transformation to an image.
@@ -376,11 +418,15 @@ def warp_perspective3d(
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
+ 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.
- """
+ """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)
src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 17009dbc6..ac92cecc0 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -8,26 +8,25 @@ import torch.nn.functional as F
from kornia.filters import gaussian_blur2d, filter2D
-__all__ = [
- "PyrDown",
- "PyrUp",
- "ScalePyramid",
- "pyrdown",
- "pyrup",
- "build_pyramid",
-]
+__all__ = ["PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyramid"]
def _get_pyramid_gaussian_kernel() -> torch.Tensor:
"""Utility function that return a pre-computed gaussian kernel."""
- return torch.tensor(
- [
+ 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.]
+ [
+ [1.0, 4.0, 6.0, 4.0, 1.0],
+ [4.0, 16.0, 24.0, 16.0, 4.0],
+ [6.0, 24.0, 36.0, 24.0, 6.0],
+ [4.0, 16.0, 24.0, 16.0, 4.0],
+ [1.0, 4.0, 6.0, 4.0, 1.0],
+ ]
]
- ]
- ) / 256.
+ )
+ / 256.0
+ )
class PyrDown(nn.Module):
@@ -126,19 +125,35 @@ 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.0 / float(self.n_levels))
self.double_image = double_image
return
def __repr__(self) -> str:
- return self.__class__.__name__ +\
- '(n_levels=' + str(self.n_levels) + ', ' +\
- 'init_sigma=' + str(self.init_sigma) + ', ' + \
- 'min_size=' + str(self.min_size) + ', ' + \
- 'extra_levels=' + str(self.extra_levels) + ', ' + \
- 'border=' + str(self.border) + ', ' + \
- 'sigma_step=' + str(self.sigma_step) + ', ' + \
- 'double_image=' + str(self.double_image) + ')'
+ return (
+ self.__class__.__name__
+ + '(n_levels='
+ + str(self.n_levels)
+ + ', '
+ + 'init_sigma='
+ + str(self.init_sigma)
+ + ', '
+ + 'min_size='
+ + str(self.min_size)
+ + ', '
+ + 'extra_levels='
+ + str(self.extra_levels)
+ + ', '
+ + 'border='
+ + str(self.border)
+ + ', '
+ + 'sigma_step='
+ + str(self.sigma_step)
+ + ', '
+ + 'double_image='
+ + str(self.double_image)
+ + ')'
+ )
def get_kernel_size(self, sigma: float):
ksize = int(2.0 * 4.0 * sigma + 1.0)
@@ -162,7 +177,7 @@ class ScalePyramid(nn.Module):
else:
x = input
if self.init_sigma > cur_sigma:
- sigma = max(math.sqrt(self.init_sigma**2 - cur_sigma**2), 0.01)
+ sigma = max(math.sqrt(self.init_sigma ** 2 - cur_sigma ** 2), 0.01)
ksize = self.get_kernel_size(sigma)
cur_level = gaussian_blur2d(x, (ksize, ksize), (sigma, sigma))
cur_sigma = self.init_sigma
@@ -181,7 +196,7 @@ class ScalePyramid(nn.Module):
while True:
cur_level = pyr[-1][0]
for level_idx in range(1, self.n_levels + self.extra_levels):
- sigma = cur_sigma * math.sqrt(self.sigma_step**2 - 1.0)
+ sigma = cur_sigma * math.sqrt(self.sigma_step ** 2 - 1.0)
ksize = self.get_kernel_size(sigma)
# Hack, because PyTorch does not allow to pad more than original size.
@@ -202,7 +217,7 @@ class ScalePyramid(nn.Module):
) # 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))
@@ -283,10 +298,9 @@ def pyrup(input: torch.Tensor, border_type: str = 'reflect', align_corners: bool
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 d834d841f..2146e336e 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -161,7 +161,7 @@ def warp_image_tps(
kernel_centers: torch.Tensor,
kernel_weights: torch.Tensor,
affine_weights: torch.Tensor,
- align_corners: bool = False
+ 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 699b57b82..dde1d90db 100644
--- a/kornia/geometry/warp/depth_warper.py
+++ b/kornia/geometry/warp/depth_warper.py
@@ -3,13 +3,10 @@ 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",
- "DepthWarper",
-]
+__all__ = ["depth_warp", "DepthWarper"]
class DepthWarper(_DepthWarper):
@@ -22,7 +19,7 @@ class DepthWarper(_DepthWarper):
width: int,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: bool = True
+ align_corners: bool = True,
):
super(DepthWarper, self).__init__(
pinhole_dst=pinhole_dst,
@@ -30,13 +27,13 @@ class DepthWarper(_DepthWarper):
width=width,
mode=mode,
padding_mode=padding_mode,
- align_corners=align_corners
+ 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
+ stacklevel=2,
)
@@ -47,12 +44,12 @@ def depth_warp(
patch_dst: torch.Tensor,
height: int,
width: int,
- align_corners: bool = True
+ 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
+ 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 ad32a85c0..31f6a4a7d 100644
--- a/kornia/geometry/warp/homography_warper.py
+++ b/kornia/geometry/warp/homography_warper.py
@@ -27,7 +27,7 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
"`warp_grid` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.warp_grid instead.`",
DeprecationWarning,
- stacklevel=2
+ stacklevel=2,
)
return HMW.warp_grid(grid, src_homo_dst)
@@ -37,7 +37,7 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
warnings.warn(
"`warp_grid3d` is deprecated. Please use `kornia.geometry.transform.warp_grid3d instead.`",
DeprecationWarning,
- stacklevel=2
+ stacklevel=2,
)
return HMW.warp_grid3d(grid, src_homo_dst)
@@ -50,14 +50,14 @@ def homography_warp(
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
- normalized_coordinates: bool = True
+ 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
+ stacklevel=2,
)
return HMW.homography_warp(
patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates
@@ -71,14 +71,14 @@ def homography_warp3d(
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
- normalized_coordinates: bool = True
+ 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
+ stacklevel=2,
)
return HMW.homography_warp3d(
patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates
@@ -95,14 +95,14 @@ class HomographyWarper(HMW.HomographyWarper):
mode: str = 'bilinear',
padding_mode: str = 'zeros',
normalized_coordinates: bool = True,
- align_corners: bool = False
+ 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
+ stacklevel=2,
)
@@ -111,14 +111,14 @@ def normal_transform_pixel(
width: int,
eps: float = 1e-14,
device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = 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
+ stacklevel=2,
)
return HMW.normal_transform_pixel(height, width, eps, device, dtype)
@@ -129,14 +129,14 @@ def normal_transform_pixel3d(
width: int,
eps: float = 1e-14,
device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = 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
+ stacklevel=2,
)
return HMW.normal_transform_pixel3d(depth, height, width, eps, device=device, dtype=dtype)
@@ -149,7 +149,7 @@ def normalize_homography(
"`normalize_homography` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.normalize_homography instead.`",
DeprecationWarning,
- stacklevel=2
+ stacklevel=2,
)
return HMW.normalize_homography(dst_pix_trans_src_pix, dsize_src, dsize_dst)
@@ -162,6 +162,6 @@ def normalize_homography3d(
"`normalize_homography3d` is deprecated and will be removed > 0.6.0. "
"Please use `kornia.geometry.transform.normalize_homography3d instead.`",
DeprecationWarning,
- stacklevel=2
+ 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 42ba78057..25ea23dc2 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -2,7 +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/dice.py b/kornia/losses/dice.py
index 5d20c2227..a8d183d84 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -73,9 +73,9 @@ def dice_loss(input: torch.Tensor, target: torch.Tensor, eps: float = 1e-8) -> t
intersection = torch.sum(input_soft * target_one_hot, dims)
cardinality = torch.sum(input_soft + target_one_hot, dims)
- dice_score = 2. * intersection / (cardinality + eps)
+ dice_score = 2.0 * intersection / (cardinality + eps)
- return torch.mean(-dice_score + 1.)
+ return torch.mean(-dice_score + 1.0)
class DiceLoss(nn.Module):
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 44e1ab315..58cab1ea1 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -8,9 +8,7 @@ def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
# D_KL(P || Q)
batch, chans, height, width = p.shape
unsummed_kl = F.kl_div(
- q.reshape(batch * chans, height * width).log(),
- p.reshape(batch * chans, height * width),
- reduction='none',
+ q.reshape(batch * chans, height * width).log(), p.reshape(batch * chans, height * width), reduction='none'
)
kl_values = unsummed_kl.sum(-1).view(batch, chans)
return kl_values
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 4d7d9f1ce..439362e27 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -16,7 +16,7 @@ def focal_loss(
alpha: float,
gamma: float = 2.0,
reduction: str = 'none',
- eps: float = 1e-8
+ eps: float = 1e-8,
) -> torch.Tensor:
r"""Criterion that computes Focal loss.
@@ -62,7 +62,7 @@ def focal_loss(
)
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()))
@@ -78,7 +78,7 @@ def focal_loss(
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)
+ weight = torch.pow(-input_soft + 1.0, gamma)
focal = -alpha * weight * torch.log(input_soft)
loss_tmp = torch.sum(target_one_hot * focal, dim=1)
@@ -144,10 +144,10 @@ class FocalLoss(nn.Module):
def binary_focal_loss_with_logits(
input: torch.Tensor,
target: torch.Tensor,
- alpha: float = .25,
+ alpha: float = 0.25,
gamma: float = 2.0,
reduction: str = 'none',
- eps: float = 1e-8
+ eps: float = 1e-8,
) -> torch.Tensor:
r"""Function that computes Binary Focal loss.
@@ -191,8 +191,9 @@ def binary_focal_loss_with_logits(
probs = torch.sigmoid(input)
target = target.unsqueeze(dim=1)
- loss_tmp = - alpha * torch.pow((1. - probs + eps), gamma) * target * torch.log(probs + eps) \
- - (1 - alpha) * torch.pow(probs + eps, gamma) * (1. - target) * torch.log(1. - probs + eps)
+ loss_tmp = -alpha * torch.pow((1.0 - probs + eps), gamma) * target * torch.log(probs + eps) - (
+ 1 - alpha
+ ) * torch.pow(probs + eps, gamma) * (1.0 - target) * torch.log(1.0 - probs + eps)
loss_tmp = loss_tmp.squeeze(dim=1)
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index b45b37e4f..1d88effcb 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.0 * torch.log10(max_val ** 2 / mse(input, target, reduction='mean'))
def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torch.Tensor:
@@ -75,7 +75,7 @@ def psnr_loss(input: torch.Tensor, target: torch.Tensor, max_val: float) -> torc
tensor(-20.0000)
"""
- return -1. * psnr(input, target, max_val)
+ return -1.0 * psnr(input, target, max_val)
class PSNRLoss(nn.Module):
diff --git a/kornia/losses/ssim.py b/kornia/losses/ssim.py
index 106928428..e4c6e9500 100644
--- a/kornia/losses/ssim.py
+++ b/kornia/losses/ssim.py
@@ -61,28 +61,28 @@ def ssim(
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))
+ num: torch.Tensor = (2.0 * mu1_mu2 + C1) * (2.0 * sigma12 + C2)
+ den: torch.Tensor = (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)
return num / (den + eps)
@@ -93,7 +93,7 @@ def ssim_loss(
window_size: int,
max_val: float = 1.0,
eps: float = 1e-12,
- reduction: str = 'mean'
+ reduction: str = 'mean',
) -> torch.Tensor:
r"""Function that computes a loss based on the SSIM measurement.
@@ -128,7 +128,7 @@ def ssim_loss(
ssim_map: torch.Tensor = ssim(img1, img2, window_size, max_val, eps)
# compute and reduce the loss
- loss = torch.clamp((1. - ssim_map) / 2, min=0, max=1)
+ loss = torch.clamp((1.0 - ssim_map) / 2, min=0, max=1)
if reduction == "mean":
loss = torch.mean(loss)
diff --git a/kornia/losses/tversky.py b/kornia/losses/tversky.py
index 978ae2a8a..f8cf1f5f1 100644
--- a/kornia/losses/tversky.py
+++ b/kornia/losses/tversky.py
@@ -74,14 +74,14 @@ def tversky_loss(
# compute the actual dice score
dims = (1, 2, 3)
intersection = torch.sum(input_soft * target_one_hot, dims)
- fps = torch.sum(input_soft * (-target_one_hot + 1.), dims)
- fns = torch.sum((-input_soft + 1.) * target_one_hot, dims)
+ fps = torch.sum(input_soft * (-target_one_hot + 1.0), dims)
+ fns = torch.sum((-input_soft + 1.0) * target_one_hot, dims)
numerator = intersection
denominator = intersection + alpha * fps + beta * fns
tversky_loss = numerator / (denominator + eps)
- return torch.mean(-tversky_loss + 1.)
+ return torch.mean(-tversky_loss + 1.0)
class TverskyLoss(nn.Module):
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 5942621f8..1fc92401a 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -44,7 +44,7 @@ def dilation(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List[i
# pad
pad_e: List[int] = [origin[1], se_w - origin[1] - 1, origin[0], se_h - origin[0] - 1]
- output: torch.Tensor = F.pad(tensor, pad_e, mode='constant', value=0.)
+ output: torch.Tensor = F.pad(tensor, pad_e, mode='constant', value=0.0)
# computation
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
@@ -94,7 +94,7 @@ def erosion(tensor: torch.Tensor, kernel: torch.Tensor, origin: Optional[List[in
# pad
pad_e: List[int] = [origin[1], se_w - origin[1] - 1, origin[0], se_h - origin[0] - 1]
- output: torch.Tensor = F.pad(tensor, pad_e, mode='constant', value=1.)
+ output: torch.Tensor = F.pad(tensor, pad_e, mode='constant', value=1.0)
# computation
output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index f03da3d6d..e8964fe78 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -20,21 +20,18 @@ def xla_is_available() -> bool:
def create_checkerboard(h, w, nw):
- """Creates a synthetic checkered board of shape HxW and window size `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)
# 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
- """
+ """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)
def create_random_homography(batch_size, eye_size, std_val=1e-3):
- """Creates a batch of random homographies of shape Bx3x3
- """
+ """Creates a batch of random homographies of shape Bx3x3"""
std = torch.FloatTensor(batch_size, eye_size, eye_size)
eye = create_eye_batch(batch_size, eye_size)
return eye + std.uniform_(-std_val, std_val)
@@ -42,36 +39,32 @@ def create_random_homography(batch_size, eye_size, std_val=1e-3):
def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
"""Converts the input tensor to a valid variable to check the gradient.
- `gradcheck` needs 64-bit floating point and requires gradient.
+ `gradcheck` needs 64-bit floating point and requires gradient.
"""
assert torch.is_tensor(tensor), type(tensor)
return tensor.requires_grad_(requires_grad).type(dtype)
def compute_patch_error(x, y, h, w):
- """Compute the absolute error between patches.
- """
- return torch.abs(x - y)[..., h // 4:-h // 4, w // 4:-w // 4].mean()
+ """Compute the absolute error between patches."""
+ return torch.abs(x - y)[..., h // 4 : -h // 4, w // 4 : -w // 4].mean()
def check_is_tensor(obj):
- """Checks whether the supplied object is a tensor.
- """
+ """Checks whether the supplied object is a tensor."""
if not isinstance(obj, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(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)
+ """Creates a batch of rectified fundamental matrices of shape Bx3x3"""
+ F_rect = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
F_repeat = F_rect.repeat(batch_size, 1, 1)
return F_repeat
def create_random_fundamental_matrix(batch_size, std_val=1e-3):
- """Creates a batch of random fundamental matrices of shape Bx3x3
- """
+ """Creates a batch of random fundamental matrices of shape Bx3x3"""
F_rect = create_rectified_fundamental_matrix(batch_size)
H_left = create_random_homography(batch_size, 3, std_val)
H_right = create_random_homography(batch_size, 3, std_val)
@@ -79,7 +72,6 @@ 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.")
@@ -106,8 +98,7 @@ class BaseTester(ABC):
def cartesian_product_of_parameters(**possible_parameters):
- """Creates cartesian product of given parameters
- """
+ """Creates cartesian product of given parameters"""
parameter_names = possible_parameters.keys()
possible_values = [possible_parameters[parameter_name] for parameter_name in parameter_names]
diff --git a/kornia/utils/draw.py b/kornia/utils/draw.py
index c0b7a9599..6c15b00f1 100644
--- a/kornia/utils/draw.py
+++ b/kornia/utils/draw.py
@@ -7,27 +7,27 @@ def draw_rectangle(
rectangle: torch.Tensor,
color: Optional[torch.Tensor] = None,
fill: Optional[bool] = None,
- width: int = 1
+ width: int = 1,
) -> torch.Tensor:
r"""Draws N rectangles on a batch of image tensors.
- Args:
- image (torch.Tensor): is tensor of BxCxHxW.
- rectangle (torch.Tensor): represents number of rectangles to draw in BxNx4
- N is the number of boxes to draw per batch index[x1, y1, x2, y2]
- 4 is in (top_left.x, top_left.y, bot_right.x, bot_right.y).
- color (torch.Tensor, optional): a size 1, size 3, BxNx1, or BxNx3 tensor.
- If C is 3, and color is 1 channel it will be broadcasted Default: None (black).
- fill (bool, optional): is a flag used to fill the boxes with color if True. Default: False.
- width (int): The line width. Default: 1. (Not implemented yet).
- Returns:
- torch.Tensor: This operation modifies image inplace but also returns the drawn tensor for
- convenience with same shape the of the input BxCxHxW.
+ Args:
+ image (torch.Tensor): is tensor of BxCxHxW.
+ rectangle (torch.Tensor): represents number of rectangles to draw in BxNx4
+ N is the number of boxes to draw per batch index[x1, y1, x2, y2]
+ 4 is in (top_left.x, top_left.y, bot_right.x, bot_right.y).
+ color (torch.Tensor, optional): a size 1, size 3, BxNx1, or BxNx3 tensor.
+ If C is 3, and color is 1 channel it will be broadcasted Default: None (black).
+ fill (bool, optional): is a flag used to fill the boxes with color if True. Default: False.
+ width (int): The line width. Default: 1. (Not implemented yet).
+ Returns:
+ torch.Tensor: This operation modifies image inplace but also returns the drawn tensor for
+ convenience with same shape the of the input BxCxHxW.
- Example:
- >>> img = torch.rand(2, 3, 10, 12)
- >>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 10, 10]]])
- >>> out = draw_rectangle(img, rect)
+ Example:
+ >>> img = torch.rand(2, 3, 10, 12)
+ >>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 10, 10]]])
+ >>> out = draw_rectangle(img, rect)
"""
batch, c, h, w = image.shape
@@ -59,17 +59,24 @@ 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),
- int(rectangle[b, n, 0]):int(rectangle[b, n, 2] + 1)] = color[b, n, :, None, None]
+ 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 19a664ca3..f25faaf98 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -9,7 +9,7 @@ def create_meshgrid(
width: int,
normalized_coordinates: bool = True,
device: Optional[torch.device] = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
"""Generates a coordinate grid for an image.
@@ -54,7 +54,7 @@ def create_meshgrid3d(
width: int,
normalized_coordinates: bool = True,
device: Optional[torch.device] = torch.device('cpu'),
- dtype: torch.dtype = torch.float32
+ dtype: torch.dtype = torch.float32,
) -> torch.Tensor:
"""Generates a coordinate grid for an image.
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 8839f6bcc..006078b9c 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
@@ -43,10 +43,7 @@ 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)
@@ -60,10 +57,7 @@ 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)
@@ -79,10 +73,7 @@ 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))
@@ -99,10 +90,7 @@ 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 84a74422a..3d8dad49d 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -18,7 +18,7 @@ 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, )):
+ 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:
diff --git a/kornia/utils/metrics/__init__.py b/kornia/utils/metrics/__init__.py
index c8c223086..a29a9d4e1 100644
--- a/kornia/utils/metrics/__init__.py
+++ b/kornia/utils/metrics/__init__.py
@@ -1,7 +1,4 @@
from .confusion_matrix import confusion_matrix
from .mean_iou import mean_iou
-__all__ = [
- "confusion_matrix",
- "mean_iou",
-]
+__all__ = ["confusion_matrix", "mean_iou"]
diff --git a/kornia/utils/metrics/confusion_matrix.py b/kornia/utils/metrics/confusion_matrix.py
index 5bd222554..b062d9681 100644
--- a/kornia/utils/metrics/confusion_matrix.py
+++ b/kornia/utils/metrics/confusion_matrix.py
@@ -31,13 +31,11 @@ def confusion_matrix(
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))
+ "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)
+ "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))
@@ -53,7 +51,7 @@ def confusion_matrix(
confusion_list = []
for iter_id in range(batch_size):
pb: torch.Tensor = pre_bincount_vec[iter_id]
- bin_count: torch.Tensor = torch.bincount(pb, minlength=num_classes**2)
+ bin_count: torch.Tensor = torch.bincount(pb, minlength=num_classes ** 2)
confusion_list.append(bin_count)
confusion_vec: torch.Tensor = torch.stack(confusion_list)
diff --git a/kornia/utils/metrics/mean_iou.py b/kornia/utils/metrics/mean_iou.py
index d5e887906..5dbb7bfc7 100644
--- a/kornia/utils/metrics/mean_iou.py
+++ b/kornia/utils/metrics/mean_iou.py
@@ -27,13 +27,11 @@ def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: O
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))
+ "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)
+ "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))
diff --git a/kornia/utils/one_hot.py b/kornia/utils/one_hot.py
index 839a8b048..6e56d93ab 100644
--- a/kornia/utils/one_hot.py
+++ b/kornia/utils/one_hot.py
@@ -8,7 +8,7 @@ def one_hot(
num_classes: int,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
- eps: float = 1e-6
+ eps: float = 1e-6,
) -> torch.Tensor:
r"""Converts an integer label x-D tensor to a one-hot (x+1)-D tensor.
diff --git a/kornia/utils/pointcloud_io.py b/kornia/utils/pointcloud_io.py
index 526b4a468..504daf87b 100644
--- a/kornia/utils/pointcloud_io.py
+++ b/kornia/utils/pointcloud_io.py
@@ -73,11 +73,7 @@ def load_pointcloud_ply(filename: str, header_size: Optional[int] = 8) -> torch.
# iterate over the points
for line in lines:
x_str, y_str, z_str = line.split()
- points.append((
- torch.tensor(float(x_str)),
- torch.tensor(float(y_str)),
- torch.tensor(float(z_str)),
- ))
+ points.append((torch.tensor(float(x_str)), torch.tensor(float(y_str)), torch.tensor(float(z_str))))
# create tensor from list
pointcloud: torch.Tensor = torch.tensor(points)
diff --git a/pyproject.toml b/pyproject.toml
new file mode 100644
index 000000000..b2bc7352d
--- /dev/null
+++ b/pyproject.toml
@@ -0,0 +1,4 @@
+[tool.black]
+line-length = 120
+skip-string-normalization = true
+skip-magic-trailing-comma = true
diff --git a/setup.cfg b/setup.cfg
index 5006de78c..43a5faa16 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -20,7 +20,8 @@ license_file = LICENSE
[flake8]
max-line-length = 120
ignore =
- W504
+ W503
+ E203
E305
E402
E721
@@ -31,8 +32,6 @@ ignore =
F405
F821
F841
- F999
- W605
F811
exclude = docs/src
@@ -51,17 +50,3 @@ 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/setup.py b/setup.py
index 916a85ce0..a8a03f330 100644
--- a/setup.py
+++ b/setup.py
@@ -77,10 +77,7 @@ def write_version_file():
def read(*names, **kwargs):
- with io.open(
- os.path.join(os.path.dirname(__file__), *names),
- encoding=kwargs.get("encoding", "utf8")
- ) as fp:
+ with io.open(os.path.join(os.path.dirname(__file__), *names), encoding=kwargs.get("encoding", "utf8")) as fp:
return fp.read()
@@ -102,13 +99,12 @@ class clean(distutils.command.clean.clean):
# It's an old-style class in Python 2.7...
distutils.command.clean.clean.run(self)
+
# remove compiled and temporary files
subprocess.call(['rm -rf dist/ build/ kornia.egg*'], shell=True)
-requirements = [
- 'numpy',
- 'torch' + kornia_pt_dependencies[dep_version(version)],
-]
+
+requirements = ['numpy', 'torch' + kornia_pt_dependencies[dep_version(version)]]
if __name__ == '__main__':
@@ -125,18 +121,12 @@ if __name__ == '__main__':
long_description_content_type='text/markdown',
license='Apache License 2.0',
python_requires='>=3.6',
-
# Test
setup_requires=['pytest-runner'],
tests_require=['pytest'],
-
# Package info
- packages=find_packages(exclude=('docs', 'test', 'examples',)),
-
- package_data={
- "kornia": ["py.typed"],
- },
-
+ packages=find_packages(exclude=('docs', 'test', 'examples')),
+ package_data={"kornia": ["py.typed"]},
zip_safe=True,
install_requires=requirements,
classifiers=[
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 7ee802aca..299d63671 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -71,7 +71,7 @@ class CommonTests(BaseTester):
@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))]
+ [((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(
@@ -207,7 +207,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)
@@ -278,7 +278,7 @@ class CommonTests(BaseTester):
torch.manual_seed(42)
input_tensor = torch.zeros((1, 3, 50, 100), device=self.device, dtype=self.dtype)
- input_tensor[:, :, 20:30, 40:60] = 1.
+ input_tensor[:, :, 20:30, 40:60] = 1.0
augmentation = self._create_augmentation_from_params(**params, p=1.0, return_transform=True)
output, transform = augmentation(input_tensor)
@@ -306,8 +306,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.0, return_transform=False),
+ (input_tensor,),
+ raise_exception=True,
)
@@ -323,16 +324,34 @@ class TestRandomEqualizeAlternative(CommonTests):
return request.param
def test_random_p_1(self):
- input_tensor = torch.arange(20., device=self.device, dtype=self.dtype) / 20
+ input_tensor = torch.arange(20.0, 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
+ 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
+ dtype=self.dtype,
)
expected_output = expected_output.repeat(1, 2, 20, 1)
@@ -355,20 +374,38 @@ 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 = torch.arange(20.0, 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
+ 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
+ dtype=self.dtype,
)
expected_output = expected_output.repeat(2, 3, 20, 1)
@@ -378,13 +415,13 @@ 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.)(
+ self._create_augmentation_from_params(p=1.0)(
torch.ones((1, 3, 4, 5) * 200, device=self.device, dtype=self.dtype)
)
@@ -406,16 +443,13 @@ class TestCenterCropAlternative(CommonTests):
@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))]
+ [((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
- }
+ 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.")
@@ -425,12 +459,7 @@ class TestCenterCropAlternative(CommonTests):
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,
- ],
- ]]], device=self.device, dtype=self.dtype)
+ expected_output = torch.tensor([[[[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(
@@ -443,31 +472,16 @@ class TestCenterCropAlternative(CommonTests):
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_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
+ [[[1.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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):
@@ -476,18 +490,14 @@ class TestCenterCropAlternative(CommonTests):
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,
- )
+ [[[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], 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.")
@@ -522,34 +532,10 @@ class TestRandomHorizontalFlipAlternative(CommonTests):
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
+ [[[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
+ [[[[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 = {}
@@ -561,34 +547,10 @@ class TestRandomHorizontalFlipAlternative(CommonTests):
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
+ [[[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
+ [[[[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
@@ -598,51 +560,31 @@ class TestRandomHorizontalFlipAlternative(CommonTests):
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
+ [[[[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
+ [[[[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
+ ).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.")
@@ -663,34 +605,10 @@ class TestRandomVerticalFlipAlternative(CommonTests):
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
+ [[[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
+ [[[[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 = {}
@@ -702,34 +620,10 @@ class TestRandomVerticalFlipAlternative(CommonTests):
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
+ [[[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
+ [[[[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
@@ -739,51 +633,31 @@ class TestRandomVerticalFlipAlternative(CommonTests):
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
+ [[[[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
+ [[[[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
+ ).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.")
@@ -793,12 +667,12 @@ class TestRandomVerticalFlipAlternative(CommonTests):
class TestRandomRotationAlternative(CommonTests):
possible_params: Dict["str", Tuple] = {
- "degrees": (0., (-360., 360.), [0., 0.], torch.tensor((-180., 180))),
+ "degrees": (0.0, (-360.0, 360.0), [0.0, 0.0], torch.tensor((-180.0, 180))),
"resample": (0, Resample.BILINEAR.name, Resample.BILINEAR),
"align_corners": (False, True),
}
_augmentation_cls = RandomRotation
- _default_param_set: Dict["str", Any] = {"degrees": (30., 30.), "align_corners": True}
+ _default_param_set: Dict["str", Any] = {"degrees": (30.0, 30.0), "align_corners": True}
@pytest.fixture(
params=default_with_one_parameter_changed(default=_default_param_set, **possible_params), scope="class"
@@ -810,37 +684,13 @@ class TestRandomRotationAlternative(CommonTests):
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
+ [[[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}
+ [[[[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.0, 90.0), "align_corners": True}
self._test_random_p_1_implementation(
input_tensor=input_tensor, expected_output=expected_output, params=parameters
)
@@ -849,72 +699,36 @@ class TestRandomRotationAlternative(CommonTests):
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
+ [[[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
+ [[[[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}
+ parameters = {"degrees": (-90.0, -90.0), "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
+ [[[[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}
+ parameters = {"degrees": (-360.0, -360.0), "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,
)
@pytest.mark.xfail(reason="No input validation is implemented yet.")
@@ -931,11 +745,11 @@ class TestRandomRotationAlternative(CommonTests):
with pytest.raises(ValueError):
self._create_augmentation_from_params(degrees=-361.0)
with pytest.raises(ValueError):
- self._create_augmentation_from_params(degrees=(-361.0, 360.))
+ self._create_augmentation_from_params(degrees=(-361.0, 360.0))
with pytest.raises(ValueError):
- self._create_augmentation_from_params(degrees=(-360.0, 361.))
+ self._create_augmentation_from_params(degrees=(-360.0, 361.0))
with pytest.raises(ValueError):
- self._create_augmentation_from_params(degrees=(360.0, -360.))
+ self._create_augmentation_from_params(degrees=(360.0, -360.0))
class TestRandomGrayscaleAlternative(CommonTests):
@@ -964,8 +778,10 @@ class TestRandomGrayscaleAlternative(CommonTests):
[[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(
@@ -979,8 +795,10 @@ class TestRandomGrayscaleAlternative(CommonTests):
[[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 = {}
@@ -988,7 +806,7 @@ class TestRandomGrayscaleAlternative(CommonTests):
input_tensor=input_tensor,
expected_output=expected_output,
expected_transformation=expected_transformation,
- params=parameters
+ params=parameters,
)
def test_batch(self):
@@ -998,8 +816,10 @@ class TestRandomGrayscaleAlternative(CommonTests):
[[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 = {}
@@ -1007,7 +827,7 @@ 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.")
@@ -1015,9 +835,9 @@ class TestRandomGrayscaleAlternative(CommonTests):
torch.manual_seed(42)
with pytest.raises(ValueError):
- self._create_augmentation_from_params(p=0.)(torch.rand((1, 1, 4, 5), device=self.device, dtype=self.dtype))
+ self._create_augmentation_from_params(p=0.0)(torch.rand((1, 1, 4, 5), device=self.device, dtype=self.dtype))
with pytest.raises(ValueError):
- self._create_augmentation_from_params(p=1.)(torch.rand((1, 4, 4, 5), device=self.device, dtype=self.dtype))
+ self._create_augmentation_from_params(p=1.0)(torch.rand((1, 4, 4, 5), device=self.device, dtype=self.dtype))
class TestRandomHorizontalFlip:
@@ -1033,25 +853,27 @@ class TestRandomHorizontalFlip:
def test_random_hflip(self, device, dtype):
f = RandomHorizontalFlip(p=1.0, return_transform=True)
- f1 = RandomHorizontalFlip(p=0., return_transform=True)
- f2 = RandomHorizontalFlip(p=1.)
- f3 = RandomHorizontalFlip(p=0.)
+ f1 = RandomHorizontalFlip(p=0.0, return_transform=True)
+ f2 = RandomHorizontalFlip(p=1.0)
+ f3 = RandomHorizontalFlip(p=0.0)
input = torch.tensor(
- [[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 2.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
+ [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [2.0, 1.0, 0.0, 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
+ [[-1.0, 0.0, 3.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], 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, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype
+ ) # 3 x 3
assert (f(input)[0] == expected).all()
assert (f(input)[1] == expected_transform).all()
@@ -1070,18 +892,20 @@ class TestRandomHorizontalFlip:
f1 = RandomHorizontalFlip(p=0.0, return_transform=True)
input = torch.tensor(
- [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 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
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.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.0, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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
@@ -1105,20 +929,16 @@ class TestRandomHorizontalFlip:
def test_sequential(self, device, dtype):
f = nn.Sequential(
- RandomHorizontalFlip(p=1.0, return_transform=True),
- RandomHorizontalFlip(p=1.0, return_transform=True),
- )
- f1 = nn.Sequential(
- RandomHorizontalFlip(p=1.0, return_transform=True),
- RandomHorizontalFlip(p=1.0),
+ RandomHorizontalFlip(p=1.0, return_transform=True), RandomHorizontalFlip(p=1.0, return_transform=True)
)
+ f1 = nn.Sequential(RandomHorizontalFlip(p=1.0, return_transform=True), RandomHorizontalFlip(p=1.0))
input = torch.tensor(
- [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 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.0, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
) # 1 x 3 x 3
expected_transform_1 = expected_transform @ expected_transform
@@ -1134,7 +954,7 @@ class TestRandomHorizontalFlip:
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.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 4
input_coordinates = torch.tensor(
@@ -1142,15 +962,15 @@ class TestRandomHorizontalFlip:
[
[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]
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
]
],
device=device,
- dtype=dtype
+ 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
+ [[[[4.0, 3.0, 2.0, 1.0], [8.0, 7.0, 6.0, 5.0], [12.0, 11.0, 10.0, 9.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 4
output, transform = f(input)
@@ -1173,29 +993,30 @@ class TestRandomHorizontalFlip:
# 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, :]]
+ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 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, 0.0], [0.0, 5.0, 5.0], [0.0, 0.0, 0.0]]], device=device, dtype=dtype
+ ) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -1206,7 +1027,7 @@ class TestRandomHorizontalFlip:
def test_gradcheck(self, device, dtype):
input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomHorizontalFlip(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomHorizontalFlip(p=1.0), (input,), raise_exception=True)
class TestRandomVerticalFlip:
@@ -1222,23 +1043,25 @@ class TestRandomVerticalFlip:
def test_random_vflip(self, device, dtype):
f = RandomVerticalFlip(p=1.0, return_transform=True)
- f1 = RandomVerticalFlip(p=0., return_transform=True)
- f2 = RandomVerticalFlip(p=1.)
- f3 = RandomVerticalFlip(p=0.)
+ f1 = RandomVerticalFlip(p=0.0, return_transform=True)
+ f2 = RandomVerticalFlip(p=1.0)
+ f3 = RandomVerticalFlip(p=0.0)
input = torch.tensor(
- [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.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
+ [[[[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [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.0, 0.0, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]], 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, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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)
@@ -1258,18 +1081,20 @@ class TestRandomVerticalFlip:
f1 = RandomVerticalFlip(p=0.0, return_transform=True)
input = torch.tensor(
- [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.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
+ [[[[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [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.0, 0.0, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]], 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, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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
@@ -1293,20 +1118,16 @@ class TestRandomVerticalFlip:
def test_sequential(self, device, dtype):
f = nn.Sequential(
- RandomVerticalFlip(p=1.0, return_transform=True),
- RandomVerticalFlip(p=1.0, return_transform=True),
- )
- f1 = nn.Sequential(
- RandomVerticalFlip(p=1.0, return_transform=True),
- RandomVerticalFlip(p=1.0),
+ RandomVerticalFlip(p=1.0, return_transform=True), RandomVerticalFlip(p=1.0, return_transform=True)
)
+ f1 = nn.Sequential(RandomVerticalFlip(p=1.0, return_transform=True), RandomVerticalFlip(p=1.0))
input = torch.tensor(
- [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.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.0, 0.0, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
) # 1 x 3 x 3
expected_transform_1 = expected_transform @ expected_transform
@@ -1321,7 +1142,7 @@ 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.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 4
input_coordinates = torch.tensor(
@@ -1329,15 +1150,15 @@ class TestRandomVerticalFlip:
[
[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]
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
]
],
device=device,
- dtype=dtype
+ 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
+ [[[[9.0, 10.0, 11.0, 12.0], [5.0, 6.0, 7.0, 8.0], [1.0, 2.0, 3.0, 4.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 4
output, transform = f(input)
@@ -1360,28 +1181,29 @@ class TestRandomVerticalFlip:
# 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, :]]
+ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 0.0, 0.0]]], device=device, dtype=dtype
+ ) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -1392,7 +1214,7 @@ class TestRandomVerticalFlip:
def test_gradcheck(self, device, dtype):
input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomVerticalFlip(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomVerticalFlip(p=1.0), (input,), raise_exception=True)
class TestColorJitter:
@@ -1402,9 +1224,11 @@ class TestColorJitter:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
f = ColorJitter(brightness=0.5, contrast=0.3, saturation=[0.2, 1.2], hue=0.1)
- repr = "ColorJitter(brightness=tensor([0.5000, 1.5000]), contrast=tensor([0.7000, 1.3000]), "\
- "saturation=tensor([0.2000, 1.2000]), hue=tensor([-0.1000, 0.1000]), "\
- "p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ repr = (
+ "ColorJitter(brightness=tensor([0.5000, 1.5000]), contrast=tensor([0.7000, 1.3000]), "
+ "saturation=tensor([0.2000, 1.2000]), hue=tensor([-0.1000, 0.1000]), "
+ "p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
def test_color_jitter(self, device, dtype):
@@ -1446,16 +1270,16 @@ class TestColorJitter:
[
[[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.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]]
- ]
+ [[0.2660, 0.3660, 0.4660], [0.7660, 0.6660, 0.5660], [0.8660, 0.9660, 1.0000]],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
def test_random_brightness(self, device, dtype):
@@ -1463,7 +1287,7 @@ class TestColorJitter:
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
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
@@ -1476,7 +1300,7 @@ class TestColorJitter:
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
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
@@ -1490,16 +1314,16 @@ class TestColorJitter:
[
[[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.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]]
- ]
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
def test_random_contrast(self, device, dtype):
@@ -1507,7 +1331,7 @@ class TestColorJitter:
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
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
@@ -1520,7 +1344,7 @@ class TestColorJitter:
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
+ [[[[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]]]], device=device, dtype=dtype
) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
@@ -1534,16 +1358,16 @@ class TestColorJitter:
[
[[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.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]]
- ]
+ [[0.5556, 0.8000, 0.7000], [0.9000, 0.2765, 0.1765], [0.8000, 0.3530, 0.4413]],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
def test_random_saturation(self, device, dtype):
@@ -1553,13 +1377,13 @@ class TestColorJitter:
input = torch.tensor(
[
[
- [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
@@ -1573,13 +1397,13 @@ class TestColorJitter:
input = torch.tensor(
[
[
- [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
@@ -1594,13 +1418,13 @@ class TestColorJitter:
input = torch.tensor(
[
[
- [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
@@ -1614,16 +1438,16 @@ class TestColorJitter:
[
[[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.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]]
- ]
+ [[0.6347, 0.8000, 0.7000], [0.9000, 0.3000, 0.2000], [0.8000, 0.3730, 0.4692]],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
def test_random_hue(self, device, dtype):
@@ -1633,13 +1457,13 @@ class TestColorJitter:
input = torch.tensor(
[
[
- [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
@@ -1654,13 +1478,13 @@ class TestColorJitter:
input = torch.tensor(
[
[
- [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
@@ -1675,13 +1499,13 @@ class TestColorJitter:
input = torch.tensor(
[
[
- [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1 x 1 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
@@ -1691,10 +1515,7 @@ class TestColorJitter:
def test_sequential(self, device, dtype):
- f = nn.Sequential(
- ColorJitter(return_transform=True),
- ColorJitter(return_transform=True),
- )
+ f = nn.Sequential(ColorJitter(return_transform=True), ColorJitter(return_transform=True))
input = torch.rand(3, 5, 5, device=device, dtype=dtype).unsqueeze(0) # 1 x 3 x 5 x 5
@@ -1706,10 +1527,7 @@ class TestColorJitter:
assert_allclose(f(input)[1], expected_transform, atol=1e-4, rtol=1e-5)
def test_color_jitter_batch_sequential(self, device, dtype):
- f = nn.Sequential(
- ColorJitter(return_transform=True),
- ColorJitter(return_transform=True),
- )
+ f = nn.Sequential(ColorJitter(return_transform=True), ColorJitter(return_transform=True))
input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5
expected = input
@@ -1723,29 +1541,28 @@ class TestColorJitter:
def test_gradcheck(self, device, dtype):
input = torch.rand((3, 5, 5), device=device, dtype=dtype).unsqueeze(0) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.augmentation.ColorJitter(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(kornia.augmentation.ColorJitter(p=1.0), (input,), raise_exception=True)
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("erase_scale_range", [(0.001, 0.001), (1.0, 1.0)])
+ @pytest.mark.parametrize("aspect_ratio_range", [(0.1, 0.1), (10.0, 10.0)])
@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):
input = torch.rand(batch_shape)
- rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=1.)
+ rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=1.0)
assert rand_rec(input).shape == batch_shape
- @pytest.mark.parametrize("erase_scale_range", [(.001, .001), (1., 1.)])
- @pytest.mark.parametrize("aspect_ratio_range", [(.1, .1), (10., 10.)])
+ @pytest.mark.parametrize("erase_scale_range", [(0.001, 0.001), (1.0, 1.0)])
+ @pytest.mark.parametrize("aspect_ratio_range", [(0.1, 0.1), (10.0, 10.0)])
@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):
input = torch.rand(batch_shape)
- rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=0.)
+ rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=0.0)
assert rand_rec(input).equal(input)
- @pytest.mark.parametrize("erase_scale_range", [(.001, .001), (1., 1.)])
- @pytest.mark.parametrize("aspect_ratio_range", [(.1, .1), (10., 10.)])
+ @pytest.mark.parametrize("erase_scale_range", [(0.001, 0.001), (1.0, 1.0)])
+ @pytest.mark.parametrize("aspect_ratio_range", [(0.1, 0.1), (10.0, 10.0)])
@pytest.mark.parametrize("shape", [(3, 11, 7)])
def test_same_on_batch(self, shape, erase_scale_range, aspect_ratio_range):
f = RandomErasing(erase_scale_range, aspect_ratio_range, same_on_batch=True, p=0.5)
@@ -1756,8 +1573,8 @@ class TestRectangleRandomErasing:
def test_gradcheck(self, device, dtype):
# test parameters
batch_shape = (2, 3, 11, 7)
- erase_scale_range = (.2, .4)
- aspect_ratio_range = (.3, .5)
+ erase_scale_range = (0.2, 0.4)
+ aspect_ratio_range = (0.3, 0.5)
rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=1.0)
rect_params = rand_rec.forward_parameters(batch_shape)
@@ -1765,22 +1582,17 @@ class TestRectangleRandomErasing:
# evaluate function gradient
input = torch.rand(batch_shape, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- rand_rec,
- (input, rect_params),
- raise_exception=True,
- )
+ assert gradcheck(rand_rec, (input, rect_params), 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(img):
- return kornia.augmentation.random_rectangle_erase(img, (.2, .4), (.3, .5))
+ return kornia.augmentation.random_rectangle_erase(img, (0.2, 0.4), (0.3, 0.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, (0.2, 0.4), (0.3, 0.5))(img)
actual = op_script(img)
assert_allclose(actual, expected, atol=1e-4, rtol=1e-4)
@@ -1820,26 +1632,26 @@ class TestRandomGrayscale:
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
@@ -1851,29 +1663,29 @@ class TestRandomGrayscale:
[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.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.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.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- img_gray = kornia.augmentation.RandomGrayscale(p=1.)(data)
+ img_gray = kornia.augmentation.RandomGrayscale(p=1.0)(data)
assert_allclose(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_opencv_false(self, device, dtype):
@@ -1885,31 +1697,31 @@ class TestRandomGrayscale:
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = data
- img_gray = kornia.augmentation.RandomGrayscale(p=0.)(data)
+ img_gray = kornia.augmentation.RandomGrayscale(p=0.0)(data)
assert_allclose(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_opencv_true_batch(self, device, dtype):
@@ -1920,25 +1732,25 @@ class TestRandomGrayscale:
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
data = data.unsqueeze(0).repeat(4, 1, 1, 1)
@@ -1950,29 +1762,29 @@ class TestRandomGrayscale:
[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.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.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.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = expected.unsqueeze(0).repeat(4, 1, 1, 1)
- img_gray = kornia.augmentation.RandomGrayscale(p=1.)(data)
+ img_gray = kornia.augmentation.RandomGrayscale(p=1.0)(data)
assert_allclose(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_opencv_false_batch(self, device, dtype):
@@ -1983,38 +1795,35 @@ class TestRandomGrayscale:
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
data = data.unsqueeze(0).repeat(4, 1, 1, 1)
expected = data
- img_gray = kornia.augmentation.RandomGrayscale(p=0.)(data)
+ img_gray = kornia.augmentation.RandomGrayscale(p=0.0)(data)
assert_allclose(img_gray, expected, atol=1e-4, rtol=1e-4)
def test_random_grayscale_sequential_batch(self, device, dtype):
- f = nn.Sequential(
- RandomGrayscale(p=0., return_transform=True),
- RandomGrayscale(p=0., return_transform=True),
- )
+ f = nn.Sequential(RandomGrayscale(p=0.0, return_transform=True), RandomGrayscale(p=0.0, return_transform=True))
input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5
expected = input
@@ -2028,12 +1837,11 @@ 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.0), (input,), raise_exception=True)
+ assert gradcheck(kornia.augmentation.RandomGrayscale(p=0.0), (input,), raise_exception=True)
class TestCenterCrop:
-
def test_no_transform(self, device, dtype):
inp = torch.rand(1, 2, 4, 4, device=device, dtype=dtype)
out = kornia.augmentation.CenterCrop(2)(inp)
@@ -2078,7 +1886,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:
@@ -2090,51 +1898,59 @@ class TestRandomRotation:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
f = RandomRotation(degrees=45.5)
- repr = "RandomRotation(degrees=tensor([-45.5000, 45.5000]), interpolation=BILINEAR, p=0.5, "\
- "p_batch=1.0, same_on_batch=False, return_transform=False)"
+ repr = (
+ "RandomRotation(degrees=tensor([-45.5000, 45.5000]), interpolation=BILINEAR, p=0.5, "
+ "p_batch=1.0, same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
def test_random_rotation(self, device, dtype):
# This is included in doctest
torch.manual_seed(0) # for random reproductibility
- f = RandomRotation(degrees=45.0, return_transform=True, p=1.)
- f1 = RandomRotation(degrees=45.0, p=1.)
+ f = RandomRotation(degrees=45.0, return_transform=True, p=1.0)
+ f1 = RandomRotation(degrees=45.0, p=1.0)
input = torch.tensor(
- [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ 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]
+ [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
+ 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
+ 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]
+ [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
+ dtype=dtype,
) # 1 x 4 x 4
out, mat = f(input)
@@ -2146,38 +1962,44 @@ class TestRandomRotation:
torch.manual_seed(0) # for random reproductibility
- f = RandomRotation(degrees=45.0, return_transform=True, p=1.)
+ f = RandomRotation(degrees=45.0, return_transform=True, p=1.0)
input = torch.tensor(
- [[[[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]]]], device=device, dtype=dtype
+ [[[[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]]]],
+ 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.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]
+ [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
+ 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]]
+ [[0.9125, 0.4090, -0.4823], [-0.4090, 0.9125, 0.7446], [0.0000, 0.0000, 1.0000]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 5 x 3 x 3 x 3
@@ -2197,41 +2019,44 @@ class TestRandomRotation:
torch.manual_seed(0) # for random reproductibility
f = nn.Sequential(
- RandomRotation(torch.tensor([-45.0, 90]), return_transform=True, p=1.),
- RandomRotation(10.4, return_transform=True, p=1.),
+ RandomRotation(torch.tensor([-45.0, 90]), return_transform=True, p=1.0),
+ RandomRotation(10.4, return_transform=True, p=1.0),
)
f1 = nn.Sequential(
- RandomRotation(torch.tensor([-45.0, 90]), return_transform=True, p=1.),
- RandomRotation(10.4, p=1.),
+ RandomRotation(torch.tensor([-45.0, 90]), return_transform=True, p=1.0), RandomRotation(10.4, p=1.0)
)
input = torch.tensor(
- [[1., 0., 0., 2.], [0., 0., 0., 0.], [0., 1., 2., 0.], [0., 0., 1., 2.]], device=device, dtype=dtype
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ 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]
+ [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
+ 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
+ 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
+ dtype=dtype,
) # 1 x 3 x 3
out, mat = f(input)
@@ -2251,19 +2076,19 @@ class TestRandomRotation:
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
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ device=device,
+ dtype=dtype,
) # 4 x 4
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 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
+ [[[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)
@@ -2276,7 +2101,7 @@ class TestRandomRotation:
input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomRotation(degrees=(15.0, 15.0), p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomRotation(degrees=(15.0, 15.0), p=1.0), (input,), raise_exception=True)
class TestRandomCrop:
@@ -2284,16 +2109,18 @@ class TestRandomCrop:
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
- f = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, pad_if_needed=False, p=1.)
- repr = "RandomCrop(crop_size=(2, 3), padding=(0, 1), fill=10, pad_if_needed=False, padding_mode=constant, "\
- "resample=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ f = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, pad_if_needed=False, p=1.0)
+ repr = (
+ "RandomCrop(crop_size=(2, 3), padding=(0, 1), fill=10, pad_if_needed=False, padding_mode=constant, "
+ "resample=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
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)
- rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.)
+ inp = torch.tensor([[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype)
+ rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.0)
out = rc(inp)
torch.manual_seed(0)
@@ -2302,8 +2129,8 @@ 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)
- aug = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1., cropping_mode="resample")
+ inversed = torch.tensor([[[[0.0, 0.0, 0.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype)
+ aug = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.0, 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)
@@ -2311,37 +2138,41 @@ 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)
+ inp = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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
+ [[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]], [[[3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype
)
- rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.)
+ rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.0)
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.]]]],
+ [
+ [[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- aug = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1., cropping_mode="resample")
+ aug = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.0, 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_same_on_batch(self, device, dtype):
- f = RandomCrop(size=(2, 3), padding=1, same_on_batch=True, align_corners=True, p=1.)
+ f = RandomCrop(size=(2, 3), padding=1, same_on_batch=True, align_corners=True, p=1.0)
input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
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)
- rc = RandomCrop(size=(2, 3), padding=1, padding_mode='reflect', align_corners=True, p=1.)
+ inp = torch.tensor([[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[7.0, 8.0, 7.0], [4.0, 5.0, 4.0]]]], device=device, dtype=dtype)
+ rc = RandomCrop(size=(2, 3), padding=1, padding_mode='reflect', align_corners=True, p=1.0)
out = rc(inp)
torch.manual_seed(42)
@@ -2350,9 +2181,9 @@ 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.0, 0.0, 0.0], [0.0, 7.0, 8.0]]]], 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.0, cropping_mode="resample"
)
out = aug(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -2361,23 +2192,27 @@ 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)
+ inp = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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
+ [[[[1.0, 2.0, 0.0], [4.0, 5.0, 0.0]]], [[[7.0, 8.0, 0.0], [0.0, 0.0, 0.0]]]], device=device, dtype=dtype
)
- rc = RandomCrop(size=(2, 3), padding=1, align_corners=True, p=1.)
+ rc = RandomCrop(size=(2, 3), padding=1, align_corners=True, p=1.0)
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.]]]],
+ [
+ [[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 7.0, 8.0]]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- aug = RandomCrop(size=(2, 3), padding=1, align_corners=True, p=1., cropping_mode="resample")
+ aug = RandomCrop(size=(2, 3), padding=1, align_corners=True, p=1.0, 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)
@@ -2385,25 +2220,26 @@ 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)
+ inp = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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
+ [[[[1.0, 2.0, 10.0], [4.0, 5.0, 10.0]]], [[[4.0, 5.0, 10.0], [7.0, 8.0, 10.0]]]], device=device, dtype=dtype
)
- rc = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1.)
+ rc = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1.0)
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.]]]],
+ [
+ [[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 4.0, 5.0], [0.0, 7.0, 8.0]]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- aug = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1., cropping_mode="resample")
+ aug = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1.0, 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)
@@ -2411,33 +2247,37 @@ 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)
+ inp = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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
+ [[[[8.0, 8.0, 8.0], [8.0, 0.0, 1.0]]], [[[8.0, 8.0, 8.0], [1.0, 2.0, 8.0]]]], device=device, dtype=dtype
)
- rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1.)
+ rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1.0)
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.]]]],
+ [
+ [[[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 1.0, 2.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- aug = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1., cropping_mode="resample")
+ aug = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1.0, 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.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], device=device, dtype=dtype)
+ trans = torch.tensor([[[1.0, 2.0, 3.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], device=device, dtype=dtype)
# Not return transform
- rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=9, align_corners=True, p=0.)
+ rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=9, align_corners=True, p=0.0)
out = rc(inp)
assert_allclose(out, inp, atol=1e-4, rtol=1e-4)
@@ -2447,7 +2287,7 @@ class TestRandomCrop:
assert_allclose(out[1], trans, atol=1e-4, rtol=1e-4)
# with return transform
- rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=9, align_corners=True, p=0., return_transform=True)
+ rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=9, align_corners=True, p=0.0, return_transform=True)
out = rc(inp)
assert_allclose(out[0], inp, atol=1e-4, rtol=1e-4)
@@ -2458,27 +2298,25 @@ class TestRandomCrop:
def test_pad_if_needed(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
- inp = torch.tensor([[
- [0., 1., 2.],
- ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
+ inp = torch.tensor([[[0.0, 1.0, 2.0]]], 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
+ [[[[9.0, 9.0, 9.0], [0.0, 1.0, 2.0]]], [[[9.0, 9.0, 9.0], [0.0, 1.0, 2.0]]]], device=device, dtype=dtype
)
- rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1.)
+ rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1.0)
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.0, 1.0, 2.0]]], [[[0.0, 1.0, 2.0]]]], device=device, dtype=dtype)
+ aug = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1.0, 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.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], device=device, dtype=dtype)
op1 = RandomCrop(size=(2, 2), cropping_mode='resample')
out = op1(img)
@@ -2491,12 +2329,12 @@ class TestRandomCrop:
torch.manual_seed(0) # for random reproductibility
inp = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3
inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(RandomCrop(size=(3, 3), p=1.), (inp, ), raise_exception=True)
+ assert gradcheck(RandomCrop(size=(3, 3), p=1.0), (inp,), raise_exception=True)
@pytest.mark.skip("Need to fix Union type")
def test_jit(self, device, dtype):
# Define script
- op = RandomCrop(size=(3, 3), p=1.).forward
+ op = RandomCrop(size=(3, 3), p=1.0).forward
op_script = torch.jit.script(op)
img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
@@ -2507,12 +2345,12 @@ class TestRandomCrop:
@pytest.mark.skip("Need to fix Union type")
def test_jit_trace(self, device, dtype):
# Define script
- op = RandomCrop(size=(3, 3), p=1.).forward
+ op = RandomCrop(size=(3, 3), p=1.0).forward
op_script = torch.jit.script(op)
# 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)
@@ -2528,38 +2366,41 @@ class TestRandomResizedCrop:
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
- f = RandomResizedCrop(size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0))
- repr = "RandomResizedCrop(size=(2, 3), scale=tensor([1., 1.]), ratio=tensor([1., 1.]), "\
- "interpolation=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ f = RandomResizedCrop(size=(2, 3), scale=(1.0, 1.0), ratio=(1.0, 1.0))
+ repr = (
+ "RandomResizedCrop(size=(2, 3), scale=tensor([1., 1.]), ratio=tensor([1., 1.]), "
+ "interpolation=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
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.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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.0, 1.0), 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.0, 1.0), 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.0, 1.0), ratio=(1.0, 1.0), same_on_batch=True)
+ input = torch.tensor([[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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.0, 1.0), ratio=(1.0, 1.0), same_on_batch=True, cropping_mode="resample"
)
out = aug(input)
inversed = aug.inverse(out)
@@ -2568,21 +2409,21 @@ 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.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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
+ dtype=dtype,
)
- rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
+ rrc = RandomResizedCrop(size=(3, 3), scale=(3.0, 3.0), ratio=(2.0, 2.0))
# 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)
- aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), cropping_mode="resample")
+ inversed = torch.tensor([[[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 7.0, 8.0]]]], device=device, dtype=dtype)
+ aug = RandomResizedCrop(size=(3, 3), scale=(3.0, 3.0), ratio=(2.0, 2.0), 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)
@@ -2590,30 +2431,32 @@ 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.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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]
+ [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
+ dtype=dtype,
)
- rrc = RandomResizedCrop(size=(4, 4), scale=(3., 3.), ratio=(2., 2.))
+ rrc = RandomResizedCrop(size=(4, 4), scale=(3.0, 3.0), ratio=(2.0, 2.0))
# It will crop a size of (3, 3) from the aspect ratio implementation of torch
out = rrc(inp)
assert out.shape == torch.Size([1, 1, 4, 4])
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)
- aug = RandomResizedCrop(size=(4, 4), scale=(3., 3.), ratio=(2., 2.), cropping_mode="resample")
+ inversed = torch.tensor([[[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 7.0, 8.0]]]], device=device, dtype=dtype)
+ aug = RandomResizedCrop(size=(4, 4), scale=(3.0, 3.0), ratio=(2.0, 2.0), cropping_mode="resample")
out = aug(inp)
assert_allclose(out, exp, atol=1e-4, rtol=1e-4)
assert_allclose(aug.inverse(out), inversed, atol=1e-4, rtol=1e-4)
@@ -2621,36 +2464,40 @@ 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.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], 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]]]
+ [[[0.0000, 0.5000, 1.0000], [3.0000, 3.5000, 4.0000], [6.0000, 6.5000, 7.0000]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
+ rrc = RandomResizedCrop(size=(3, 3), scale=(3.0, 3.0), ratio=(2.0, 2.0))
# 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.]]]],
+ [
+ [[[0.0, 1.0, 2.0], [0.0, 4.0, 5.0], [0.0, 7.0, 8.0]]],
+ [[[0.0, 1.0, 0.0], [3.0, 4.0, 0.0], [6.0, 7.0, 0.0]]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), cropping_mode="resample")
+ aug = RandomResizedCrop(size=(3, 3), scale=(3.0, 3.0), ratio=(2.0, 2.0), 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.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]], device=device, dtype=dtype)
op1 = RandomResizedCrop(size=(4, 4), cropping_mode='resample')
out = op1(img)
@@ -2663,7 +2510,9 @@ 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.0, 1.0), ratio=(1.0, 1.0)), (inp,), raise_exception=True
+ )
class TestRandomEqualize:
@@ -2677,9 +2526,9 @@ class TestRandomEqualize:
def test_random_equalize(self, device, dtype):
f = RandomEqualize(p=1.0, return_transform=True)
- f1 = RandomEqualize(p=0., return_transform=True)
- f2 = RandomEqualize(p=1.)
- f3 = RandomEqualize(p=0.)
+ f1 = RandomEqualize(p=0.0, return_transform=True)
+ f2 = RandomEqualize(p=1.0)
+ f3 = RandomEqualize(p=0.0)
bs, channels, height, width = 1, 3, 20, 20
@@ -2687,8 +2536,26 @@ class TestRandomEqualize:
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
+ 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)
@@ -2703,9 +2570,9 @@ class TestRandomEqualize:
def test_batch_random_equalize(self, device, dtype):
f = RandomEqualize(p=1.0, return_transform=True)
- f1 = RandomEqualize(p=0., return_transform=True)
- f2 = RandomEqualize(p=1.)
- f3 = RandomEqualize(p=0.)
+ f1 = RandomEqualize(p=0.0, return_transform=True)
+ f2 = RandomEqualize(p=1.0)
+ f3 = RandomEqualize(p=0.0)
bs, channels, height, width = 2, 3, 20, 20
@@ -2713,8 +2580,26 @@ class TestRandomEqualize:
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
+ 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)
@@ -2741,7 +2626,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):
@@ -2761,39 +2646,38 @@ class TestGaussianBlur:
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
- f = GaussianBlur((3, 3), (0.1, 2.0), p=1.)
+ f = GaussianBlur((3, 3), (0.1, 2.0), p=1.0)
repr = "GaussianBlur(p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
assert str(f) == repr
class TestRandomInvert:
-
def test_smoke(self, device, dtype):
img = torch.ones(1, 3, 4, 5, device=device, dtype=dtype)
assert_allclose(RandomInvert(p=1.0)(img), torch.zeros_like(img))
class TestRandomChannelShuffle:
-
def test_smoke(self, device, dtype):
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
+ [[[[8.0, 9.0], [10.0, 11.0]], [[0.0, 1.0], [2.0, 3.0]], [[4.0, 5.0], [6.0, 7.0]]]],
+ device=device,
+ dtype=dtype,
)
- aug = RandomChannelShuffle(p=1.)
+ aug = RandomChannelShuffle(p=1.0)
out = aug(img)
assert_allclose(out, out_expected)
class TestRandomGaussianNoise:
-
def test_smoke(self, device, dtype):
torch.manual_seed(0)
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
- aug = RandomGaussianNoise(p=1.)
+ aug = RandomGaussianNoise(p=1.0)
assert img.shape == aug(img).shape
@@ -2802,7 +2686,7 @@ class TestNormalize:
# return values such a torch.Tensor variable.
@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.]))
+ f = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([1.0]))
repr = (
"Normalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
"same_on_batch=False, return_transform=False)"
@@ -2810,12 +2694,12 @@ class TestNormalize:
assert str(f) == repr
def test_random_normalize(self, device, dtype):
- f = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)
- f1 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)
- f2 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)
- f3 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)
+ f = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0, return_transform=True)
+ f1 = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0, return_transform=True)
+ f2 = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0)
+ f3 = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0)
- inputs = torch.arange(0., 16., step=1, device=device, dtype=dtype).reshape(1, 4, 4).unsqueeze(0)
+ inputs = torch.arange(0.0, 16.0, step=1, device=device, dtype=dtype).reshape(1, 4, 4).unsqueeze(0)
expected = (inputs - 1) * 2
@@ -2829,12 +2713,12 @@ class TestNormalize:
assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)
def test_batch_random_normalize(self, device, dtype):
- f = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)
- f1 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)
- f2 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)
- f3 = Normalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)
+ f = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0, return_transform=True)
+ f1 = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0, return_transform=True)
+ f2 = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0)
+ f3 = Normalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0)
- inputs = torch.arange(0., 16. * 2, step=1, device=device, dtype=dtype).reshape(2, 1, 4, 4)
+ inputs = torch.arange(0.0, 16.0 * 2, step=1, device=device, dtype=dtype).reshape(2, 1, 4, 4)
expected = (inputs - 1) * 2
@@ -2854,7 +2738,7 @@ 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.0]), std=torch.tensor([1.0]), p=1.0), (input,), raise_exception=True
)
@@ -2863,7 +2747,7 @@ class TestDenormalize:
# return values such a torch.Tensor variable.
@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.]))
+ f = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([1.0]))
repr = (
"Denormalize(mean=torch.tensor([1.]), std=torch.tensor([1.]), p=1., p_batch=1.0, "
"same_on_batch=False, return_transform=False)"
@@ -2871,12 +2755,12 @@ class TestDenormalize:
assert str(f) == repr
def test_random_denormalize(self, device, dtype):
- f = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)
- f1 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)
- f2 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)
- f3 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)
+ f = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0, return_transform=True)
+ f1 = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0, return_transform=True)
+ f2 = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0)
+ f3 = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0)
- inputs = torch.arange(0., 16., step=1, device=device, dtype=dtype).reshape(1, 4, 4).unsqueeze(0)
+ inputs = torch.arange(0.0, 16.0, step=1, device=device, dtype=dtype).reshape(1, 4, 4).unsqueeze(0)
expected = inputs / 2 + 1
@@ -2890,12 +2774,12 @@ class TestDenormalize:
assert_allclose(f3(inputs), inputs, rtol=1e-4, atol=1e-4)
def test_batch_random_denormalize(self, device, dtype):
- f = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1., return_transform=True)
- f1 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0., return_transform=True)
- f2 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=1.)
- f3 = Denormalize(mean=torch.tensor([1.]), std=torch.tensor([.5]), p=0.)
+ f = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0, return_transform=True)
+ f1 = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0, return_transform=True)
+ f2 = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=1.0)
+ f3 = Denormalize(mean=torch.tensor([1.0]), std=torch.tensor([0.5]), p=0.0)
- inputs = torch.arange(0., 16. * 2, step=1, device=device, dtype=dtype).reshape(2, 1, 4, 4)
+ inputs = torch.arange(0.0, 16.0 * 2, step=1, device=device, dtype=dtype).reshape(2, 1, 4, 4)
expected = inputs / 2 + 1
@@ -2915,53 +2799,49 @@ 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.0]), std=torch.tensor([1.0]), p=1.0), (input,), raise_exception=True
)
class TestRandomFisheye:
-
def test_smoke(self, device, dtype):
torch.manual_seed(0)
- center_x = torch.tensor([-.3, .3])
- center_y = torch.tensor([-.3, .3])
- gamma = torch.tensor([-1., 1.])
+ center_x = torch.tensor([-0.3, 0.3])
+ center_y = torch.tensor([-0.3, 0.3])
+ gamma = torch.tensor([-1.0, 1.0])
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
- aug = RandomFisheye(center_x, center_y, gamma, p=1.)
+ aug = RandomFisheye(center_x, center_y, gamma, p=1.0)
assert img.shape == aug(img).shape
@pytest.mark.skip(reason="RuntimeError: Jacobian mismatch for output 0 with respect to input 0")
def test_gradcheck(self, device, dtype):
img = torch.rand(1, 1, 3, 3, device=device, dtype=dtype)
- center_x = torch.tensor([-.3, .3], device=device, dtype=dtype)
- center_y = torch.tensor([-.3, .3], device=device, dtype=dtype)
- gamma = torch.tensor([-1., 1.], device=device, dtype=dtype)
+ center_x = torch.tensor([-0.3, 0.3], device=device, dtype=dtype)
+ center_y = torch.tensor([-0.3, 0.3], device=device, dtype=dtype)
+ gamma = torch.tensor([-1.0, 1.0], device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
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:
-
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
- aug = RandomElasticTransform(p=1.)
+ aug = RandomElasticTransform(p=1.0)
assert img.shape == aug(img).shape
class TestRandomThinPlateSpline:
-
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
- aug = RandomThinPlateSpline(p=1.)
+ aug = RandomThinPlateSpline(p=1.0)
assert img.shape == aug(img).shape
class TestRandomBoxBlur:
-
def test_smoke(self, device, dtype):
img = torch.rand(1, 1, 2, 2, device=device, dtype=dtype)
- aug = RandomBoxBlur(p=1.)
+ aug = RandomBoxBlur(p=1.0)
assert img.shape == aug(img).shape
diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.py
index 2e68d098e..84a5c5304 100644
--- a/test/augmentation/test_augmentation_3d.py
+++ b/test/augmentation/test_augmentation_3d.py
@@ -31,14 +31,14 @@ class TestRandomHorizontalFlip3D:
def test_random_hflip(self, device):
f = RandomHorizontalFlip3D(p=1.0, return_transform=True)
- f1 = RandomHorizontalFlip3D(p=0., return_transform=True)
- f2 = RandomHorizontalFlip3D(p=1.)
- f3 = RandomHorizontalFlip3D(p=0.)
+ f1 = RandomHorizontalFlip3D(p=0.0, return_transform=True)
+ f2 = RandomHorizontalFlip3D(p=1.0)
+ f3 = RandomHorizontalFlip3D(p=0.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.]]
+ [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 2.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]],
]
) # 2 x 3 x 4
@@ -46,20 +46,22 @@ class TestRandomHorizontalFlip3D:
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.]]
+ [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.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], [2.0, 1.0, 0.0, 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.]]
+ [[-1.0, 0.0, 0.0, 3.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
) # 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.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
+ ) # 4 x 4
identity = identity.to(device)
assert (f(input)[0] == expected).all()
@@ -74,18 +76,20 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]]]) # 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], [0.0, 0.0, 0.0], [1.0, 1.0, 0.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.0, 0.0, 0.0, 2.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]]
) # 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.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]]
+ ) # 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
@@ -107,19 +111,15 @@ class TestRandomHorizontalFlip3D:
def test_sequential(self, device):
f = nn.Sequential(
- RandomHorizontalFlip3D(p=1.0, return_transform=True),
- RandomHorizontalFlip3D(p=1.0, return_transform=True),
- )
- f1 = nn.Sequential(
- RandomHorizontalFlip3D(p=1.0, return_transform=True),
- RandomHorizontalFlip3D(p=1.0),
+ RandomHorizontalFlip3D(p=1.0, return_transform=True), RandomHorizontalFlip3D(p=1.0, return_transform=True)
)
+ f1 = nn.Sequential(RandomHorizontalFlip3D(p=1.0, return_transform=True), 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]]) # 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.0, 0.0, 0.0, 2.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]]
) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
@@ -133,23 +133,22 @@ class TestRandomHorizontalFlip3D:
@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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]) # 1 x 3 x 3
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 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, 0.0], [0.0, 5.0, 5.0], [0.0, 0.0, 0.0]]]) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -160,7 +159,7 @@ class TestRandomHorizontalFlip3D:
def test_gradcheck(self, device):
input = torch.rand((1, 3, 3)).to(device) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomHorizontalFlip3D(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomHorizontalFlip3D(p=1.0), (input,), raise_exception=True)
class TestRandomVerticalFlip3D:
@@ -176,28 +175,46 @@ class TestRandomVerticalFlip3D:
def test_random_vflip(self, device, dtype):
f = RandomVerticalFlip3D(p=1.0, return_transform=True)
- f1 = RandomVerticalFlip3D(p=0., return_transform=True)
- f2 = RandomVerticalFlip3D(p=1.)
- f3 = RandomVerticalFlip3D(p=0.)
+ f1 = RandomVerticalFlip3D(p=0.0, return_transform=True)
+ f2 = RandomVerticalFlip3D(p=1.0)
+ f3 = RandomVerticalFlip3D(p=0.0)
input = torch.tensor(
- [[[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]], [[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]]],
+ [
+ [
+ [
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.0]],
+ ]
+ ]
+ ],
device=device,
- dtype=dtype
+ 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.]]]]],
+ [
+ [
+ [
+ [[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ ]
+ ]
+ ],
device=device,
- dtype=dtype
+ 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
+ [[[1.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 2.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ 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.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
) # 1 x 4 x 4
assert_allclose(f(input)[0], expected)
@@ -212,18 +229,20 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]]]) # 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.0, 1.0, 1.0], [0.0, 0.0, 0.0], [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.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 2.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]]
) # 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.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]]
+ ) # 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
@@ -245,19 +264,15 @@ class TestRandomVerticalFlip3D:
def test_sequential(self, device):
f = nn.Sequential(
- RandomVerticalFlip3D(p=1.0, return_transform=True),
- RandomVerticalFlip3D(p=1.0, return_transform=True),
- )
- f1 = nn.Sequential(
- RandomVerticalFlip3D(p=1.0, return_transform=True),
- RandomVerticalFlip3D(p=1.0),
+ RandomVerticalFlip3D(p=1.0, return_transform=True), RandomVerticalFlip3D(p=1.0, return_transform=True)
)
+ f1 = nn.Sequential(RandomVerticalFlip3D(p=1.0, return_transform=True), 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]]]) # 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.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 2.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]]
) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
@@ -270,22 +285,21 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]) # 4 x 4
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 0.0, 0.0]]]]) # 1 x 4 x 4
expected = expected.repeat(2, 1, 1)
@@ -296,7 +310,7 @@ class TestRandomVerticalFlip3D:
def test_gradcheck(self, device):
input = torch.rand((1, 3, 3)).to(device) # 4 x 4
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomVerticalFlip3D(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomVerticalFlip3D(p=1.0), (input,), raise_exception=True)
class TestRandomDepthicalFlip3D:
@@ -312,42 +326,46 @@ class TestRandomDepthicalFlip3D:
def test_random_dflip(self, device, dtype):
f = RandomDepthicalFlip3D(p=1.0, return_transform=True)
- f1 = RandomDepthicalFlip3D(p=0., return_transform=True)
- f2 = RandomDepthicalFlip3D(p=1.)
- f3 = RandomDepthicalFlip3D(p=0.)
+ f1 = RandomDepthicalFlip3D(p=0.0, return_transform=True)
+ f2 = RandomDepthicalFlip3D(p=1.0)
+ f3 = RandomDepthicalFlip3D(p=0.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.]]
+ [[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], [0.0, 0.0, 0.0, 2.0]],
]
]
],
device=device,
- dtype=dtype
+ 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.]]
+ [[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, 1.0]],
]
]
],
device=device,
- dtype=dtype
+ 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
+ [[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]],
+ 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.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
) # 4 x 4
assert_allclose(f(input)[0], expected)
@@ -364,8 +382,8 @@ class TestRandomDepthicalFlip3D:
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.]]
+ [[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], [0.0, 0.0, 0.0, 2.0]],
]
) # 2 x 3 x 4
@@ -373,18 +391,20 @@ class TestRandomDepthicalFlip3D:
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.]]
+ [[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, 1.0]],
]
) # 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.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]]
) # 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.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]]
+ ) # 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
@@ -406,20 +426,16 @@ class TestRandomDepthicalFlip3D:
def test_sequential(self, device):
f = nn.Sequential(
- RandomDepthicalFlip3D(p=1.0, return_transform=True),
- RandomDepthicalFlip3D(p=1.0, return_transform=True),
- )
- f1 = nn.Sequential(
- RandomDepthicalFlip3D(p=1.0, return_transform=True),
- RandomDepthicalFlip3D(p=1.0),
+ RandomDepthicalFlip3D(p=1.0, return_transform=True), RandomDepthicalFlip3D(p=1.0, return_transform=True)
)
+ f1 = nn.Sequential(RandomDepthicalFlip3D(p=1.0, return_transform=True), 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.]]
+ [[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], [0.0, 0.0, 0.0, 2.0]],
]
]
]
@@ -427,7 +443,7 @@ class TestRandomDepthicalFlip3D:
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.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 1.0], [0.0, 0.0, 0.0, 1.0]]]
) # 1 x 4 x 4
expected_transform = expected_transform.to(device)
@@ -440,22 +456,21 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]) # 4 x 4
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 0.0, 0.0]]]]) # 1 x 4 x 4
expected = expected.repeat(2, 1, 1)
@@ -466,7 +481,7 @@ class TestRandomDepthicalFlip3D:
def test_gradcheck(self, device):
input = torch.rand((1, 3, 3)).to(device) # 4 x 4
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomDepthicalFlip3D(p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomDepthicalFlip3D(p=1.0), (input,), raise_exception=True)
class TestRandomRotation3D:
@@ -478,10 +493,12 @@ class TestRandomRotation3D:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
f = RandomRotation3D(degrees=45.5)
- repr = """RandomRotation3D(degrees=tensor([[-45.5000, 45.5000],
+ repr = (
+ """RandomRotation3D(degrees=tensor([[-45.5000, 45.5000],
[-45.5000, 45.5000],
- [-45.5000, 45.5000]]), resample=BILINEAR, align_corners=False, p=0.5, """\
- """p_batch=1.0, same_on_batch=False, return_transform=False)"""
+ [-45.5000, 45.5000]]), resample=BILINEAR, align_corners=False, p=0.5, """
+ """p_batch=1.0, same_on_batch=False, return_transform=False)"""
+ )
assert str(f) == repr
def test_random_rotation(self, device, dtype):
@@ -493,12 +510,12 @@ class TestRandomRotation3D:
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.]]
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 3 x 4 x 4
expected = torch.tensor(
@@ -506,33 +523,41 @@ class TestRandomRotation3D:
[
[
[
- [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.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.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]
- ]
+ [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
+ 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]
+ [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
+ dtype=dtype,
)
out, mat = f(input)
@@ -551,13 +576,13 @@ class TestRandomRotation3D:
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.]]
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1 x 1 x 4 x 4
expected = torch.tensor(
@@ -565,53 +590,69 @@ class TestRandomRotation3D:
[
[
[
- [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]
+ [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.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.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]
- ]
+ [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
+ 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]
+ [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]
- ]
+ [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
+ dtype=dtype,
)
input = input.repeat(2, 1, 1, 1, 1) # 5 x 4 x 4 x 3
@@ -634,19 +675,16 @@ class TestRandomRotation3D:
RandomRotation3D(torch.tensor([-45.0, 90]), return_transform=True),
RandomRotation3D(10.4, return_transform=True),
)
- f1 = nn.Sequential(
- RandomRotation3D(torch.tensor([-45.0, 90]), return_transform=True),
- RandomRotation3D(10.4),
- )
+ f1 = nn.Sequential(RandomRotation3D(torch.tensor([-45.0, 90]), return_transform=True), 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.]]
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 3 x 4 x 4
expected = torch.tensor(
@@ -654,44 +692,54 @@ class TestRandomRotation3D:
[
[
[
- [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.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.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]
- ]
+ [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
+ 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]
+ [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
+ 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]
+ [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
+ dtype=dtype,
)
out, mat = f(input)
@@ -712,20 +760,21 @@ class TestRandomRotation3D:
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.]]
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
+ [[1.0, 0.0, 0.0, 2.0], [0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 2.0, 0.0], [0.0, 0.0, 1.0, 2.0]],
]
) # 3 x 4 x 4
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.]]
+ [[0.0, 0.0, 0.0], [5.0, 5.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [5.0, 5.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [5.0, 5.0, 0.0], [0.0, 0.0, 0.0]],
]
) # 3 x 3 x 3
@@ -741,7 +790,7 @@ class TestRandomRotation3D:
input = torch.rand((3, 3, 3)).to(device) # 3 x 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(RandomRotation3D(degrees=(15.0, 15.0), p=1.), (input, ), raise_exception=True)
+ assert gradcheck(RandomRotation3D(degrees=(15.0, 15.0), p=1.0), (input,), raise_exception=True)
class TestRandomCrop3D:
@@ -749,10 +798,12 @@ class TestRandomCrop3D:
# return values such a torch.Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
- f = RandomCrop3D(size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, p=1.)
- repr = "RandomCrop3D(crop_size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, "\
- "padding_mode=constant, resample=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, "\
+ f = RandomCrop3D(size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, p=1.0)
+ repr = (
+ "RandomCrop3D(crop_size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, "
+ "padding_mode=constant, resample=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, "
"return_transform=False)"
+ )
assert str(f) == repr
@pytest.mark.parametrize("batch_size", [1, 2])
@@ -763,16 +814,19 @@ class TestRandomCrop3D:
[
[
[
- [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]
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [5.0, 6.0, 7.0, 8.0, 9.0],
+ [10, 11, 12, 13, 14],
+ [15, 16, 17, 18, 19],
+ [20, 21, 22, 23, 24],
]
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
).repeat(batch_size, 1, 5, 1, 1)
- f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.)
+ f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.0)
out = f(inp)
if batch_size == 1:
expected = torch.tensor(
@@ -784,36 +838,40 @@ class TestRandomCrop3D:
[
[
[
- [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],
],
[
- [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],
],
[
- [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
+ dtype=dtype,
)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
- f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1., same_on_batch=True)
+ f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.0, same_on_batch=True)
input = torch.eye(6).unsqueeze(dim=0).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 5, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
@@ -822,49 +880,48 @@ 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)
+ inp = torch.tensor([[[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]]]], 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.]],
+ [[0.0, 1.0, 2.0, 10.0], [3.0, 4.0, 5.0, 10.0], [6.0, 7.0, 8.0, 10.0]],
+ [[0.0, 1.0, 2.0, 10.0], [3.0, 4.0, 5.0, 10.0], [6.0, 7.0, 8.0, 10.0]],
]
],
[
[
- [[3., 4., 5., 10.], [6., 7., 8., 10.], [10, 10, 10, 10.]],
- [[3., 4., 5., 10.], [6., 7., 8., 10.], [10, 10, 10, 10.]],
+ [[3.0, 4.0, 5.0, 10.0], [6.0, 7.0, 8.0, 10.0], [10, 10, 10, 10.0]],
+ [[3.0, 4.0, 5.0, 10.0], [6.0, 7.0, 8.0, 10.0], [10, 10, 10, 10.0]],
]
- ]
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- f = RandomCrop3D(size=(2, 3, 4), fill=10., padding=padding, align_corners=True, p=1.)
+ f = RandomCrop3D(size=(2, 3, 4), fill=10.0, padding=padding, align_corners=True, p=1.0)
out = f(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_pad_if_needed(self, device, dtype):
torch.manual_seed(42)
- inp = torch.tensor([[
- [0., 1., 2.],
- ]], device=device, dtype=dtype)
+ inp = torch.tensor([[[0.0, 1.0, 2.0]]], 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.]],
+ [[9.0, 9.0, 9.0, 9.0], [9.0, 9.0, 9.0, 9.0], [9.0, 9.0, 9.0, 9.0]],
+ [[0.0, 1.0, 2.0, 9.0], [9.0, 9.0, 9.0, 9.0], [9.0, 9.0, 9.0, 9.0]],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- rc = RandomCrop3D(size=(2, 3, 4), pad_if_needed=True, fill=9, align_corners=True, p=1.)
+ rc = RandomCrop3D(size=(2, 3, 4), pad_if_needed=True, fill=9, align_corners=True, p=1.0)
out = rc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -873,12 +930,12 @@ class TestRandomCrop3D:
torch.manual_seed(0) # for random reproductibility
inp = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3
inp = utils.tensor_to_gradcheck_var(inp) # to var
- assert gradcheck(RandomCrop3D(size=(3, 3, 3), p=1.), (inp, ), raise_exception=True)
+ assert gradcheck(RandomCrop3D(size=(3, 3, 3), p=1.0), (inp,), raise_exception=True)
@pytest.mark.skip("Need to fix Union type")
def test_jit(self, device, dtype):
# Define script
- op = RandomCrop(size=(3, 3), p=1.).forward
+ op = RandomCrop(size=(3, 3), p=1.0).forward
op_script = torch.jit.script(op)
img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
@@ -889,12 +946,12 @@ class TestRandomCrop3D:
@pytest.mark.skip("Need to fix Union type")
def test_jit_trace(self, device, dtype):
# Define script
- op = RandomCrop(size=(3, 3), p=1.).forward
+ op = RandomCrop(size=(3, 3), p=1.0).forward
op_script = torch.jit.script(op)
# 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)
@@ -906,7 +963,6 @@ class TestRandomCrop3D:
class TestCenterCrop3D:
-
def test_no_transform(self, device, dtype):
inp = torch.rand(1, 2, 4, 4, 4, device=device, dtype=dtype)
out = kornia.augmentation.CenterCrop3D(2)(inp)
@@ -927,7 +983,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:
@@ -941,9 +997,9 @@ class TestRandomEqualize3D:
def test_random_equalize(self, device, dtype):
f = RandomEqualize3D(p=1.0, return_transform=True)
- f1 = RandomEqualize3D(p=0., return_transform=True)
- f2 = RandomEqualize3D(p=1.)
- f3 = RandomEqualize3D(p=0.)
+ f1 = RandomEqualize3D(p=0.0, return_transform=True)
+ f2 = RandomEqualize3D(p=1.0)
+ f3 = RandomEqualize3D(p=0.0)
bs, channels, depth, height, width = 1, 3, 6, 10, 10
@@ -952,7 +1008,7 @@ class TestRandomEqualize3D:
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
+ dtype=dtype,
)
expected = self.build_input(channels, depth, height, width, bs=1, row=row_expected, device=device, dtype=dtype)
@@ -967,9 +1023,9 @@ class TestRandomEqualize3D:
def test_batch_random_equalize(self, device, dtype):
f = RandomEqualize3D(p=1.0, return_transform=True)
- f1 = RandomEqualize3D(p=0., return_transform=True)
- f2 = RandomEqualize3D(p=1.)
- f3 = RandomEqualize3D(p=0.)
+ f1 = RandomEqualize3D(p=0.0, return_transform=True)
+ f2 = RandomEqualize3D(p=1.0)
+ f3 = RandomEqualize3D(p=0.0)
bs, channels, depth, height, width = 2, 3, 6, 10, 10
@@ -999,7 +1055,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 2665faff4..fd049aab2 100644
--- a/test/augmentation/test_augmentation_mix.py
+++ b/test/augmentation/test_augmentation_mix.py
@@ -1,11 +1,10 @@
import torch
from torch.testing import assert_allclose
-from kornia.augmentation import (RandomMixUp, RandomCutMix)
+from kornia.augmentation import RandomMixUp, RandomCutMix
class TestRandomMixUp:
-
def test_smoke(self, device, dtype):
f = RandomMixUp()
repr = "RandomMixUp(lambda_val=None, p=1.0, p_batch=1.0, same_on_batch=False)"
@@ -13,11 +12,10 @@ class TestRandomMixUp:
def test_random_mixup_p1(self, device, dtype):
torch.manual_seed(0)
- f = RandomMixUp(p=1.)
+ f = RandomMixUp(p=1.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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)
@@ -25,7 +23,7 @@ class TestRandomMixUp:
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]
+ torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1],
]
)
@@ -38,14 +36,13 @@ class TestRandomMixUp:
def test_random_mixup_p0(self, device, dtype):
torch.manual_seed(0)
- f = RandomMixUp(p=0.)
+ f = RandomMixUp(p=0.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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)
+ lam = torch.tensor([0.0, 0.0], device=device, dtype=dtype)
expected = input.clone()
@@ -56,14 +53,13 @@ class TestRandomMixUp:
def test_random_mixup_lam0(self, device, dtype):
torch.manual_seed(0)
- f = RandomMixUp(lambda_val=(0., 0.), p=1.)
+ f = RandomMixUp(lambda_val=(0.0, 0.0), p=1.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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)
+ lam = torch.tensor([0.0, 0.0], device=device, dtype=dtype)
expected = input.clone()
@@ -76,11 +72,10 @@ class TestRandomMixUp:
def test_random_mixup_same_on_batch(self, device, dtype):
torch.manual_seed(0)
- f = RandomMixUp(same_on_batch=True, p=1.)
+ f = RandomMixUp(same_on_batch=True, p=1.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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)
@@ -88,7 +83,7 @@ class TestRandomMixUp:
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]
+ torch.ones(1, 3, 4, device=device, dtype=dtype) * lam[1],
]
)
@@ -100,7 +95,6 @@ class TestRandomMixUp:
class TestRandomCutMix:
-
def test_smoke(self, device, dtype):
f = RandomCutMix(width=3, height=3)
repr = (
@@ -111,22 +105,21 @@ class TestRandomCutMix:
def test_random_mixup_p1(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMix(width=4, height=3, p=1.)
+ f = RandomCutMix(width=4, height=3, p=1.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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.]]]
+ [[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
+ [[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
out_image, out_label = f(input, label)
@@ -138,11 +131,10 @@ class TestRandomCutMix:
def test_random_mixup_p0(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMix(p=0., width=4, height=3)
+ f = RandomCutMix(p=0.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)]
+ [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)
@@ -157,21 +149,20 @@ class TestRandomCutMix:
torch.manual_seed(76)
# beta 0 => resample 0.5 area
# beta cannot be 0 after torch 1.8.0
- f = RandomCutMix(beta=1e-7, width=4, height=3, p=1.)
+ f = RandomCutMix(beta=1e-7, width=4, height=3, p=1.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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.]]]
+ [[[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
+ [[[1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
out_image, out_label = f(input, label)
@@ -184,21 +175,20 @@ class TestRandomCutMix:
def test_random_mixup_num2(self, device, dtype):
torch.manual_seed(76)
- f = RandomCutMix(width=4, height=3, num_mix=5, p=1.)
+ f = RandomCutMix(width=4, height=3, num_mix=5, p=1.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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.]]]
+ [[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
+ [[[1.0, 1.0, 0.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
out_image, out_label = f(input, label)
@@ -209,32 +199,31 @@ class TestRandomCutMix:
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]],
+ [[0.0833, 0.3333], [0.0, 0.1667], [0.5, 0.0833], [0.0833, 0.0], [0.5, 0.3333]],
device=device,
- dtype=dtype
+ dtype=dtype,
),
rtol=1e-4,
- atol=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.)
+ f = RandomCutMix(same_on_batch=True, width=4, height=3, p=1.0)
input = torch.stack(
- [torch.ones(1, 3, 4, device=device, dtype=dtype),
- torch.zeros(1, 3, 4, device=device, dtype=dtype)]
+ [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.]]]
+ [[[0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
+ [[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
out_image, out_label = f(input, label)
diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.py
index b11c0b061..aeb6161c0 100644
--- a/test/augmentation/test_backward.py
+++ b/test/augmentation/test_backward.py
@@ -3,33 +3,46 @@ import torch
import torch.nn as nn
from kornia.augmentation import (
- ColorJitter, RandomAffine, RandomErasing, RandomRotation, RandomPerspective, RandomSharpness, RandomResizedCrop,
- RandomMotionBlur
+ ColorJitter,
+ RandomAffine,
+ RandomErasing,
+ RandomRotation,
+ RandomPerspective,
+ RandomSharpness,
+ RandomResizedCrop,
+ RandomMotionBlur,
)
class TestColorJitterBackward:
-
- @pytest.mark.parametrize("brightness", [0.8, torch.tensor(.8), torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize("contrast", [0.8, torch.tensor(.8), torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize("saturation", [0.8, torch.tensor(.8), torch.tensor([0.8, 1.2])])
- @pytest.mark.parametrize("hue", [0.1, torch.tensor(.1), torch.tensor([-0.1, 0.1])])
+ @pytest.mark.parametrize("brightness", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("contrast", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("saturation", [0.8, torch.tensor(0.8), torch.tensor([0.8, 1.2])])
+ @pytest.mark.parametrize("hue", [0.1, torch.tensor(0.1), torch.tensor([-0.1, 0.1])])
@pytest.mark.parametrize("return_transform", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, brightness, contrast, saturation, hue, return_transform, same_on_batch, device, dtype):
count = 0
- _brightness = brightness if isinstance(brightness, (int, float)) else \
- nn.Parameter(brightness.clone().to(device=device, dtype=dtype))
- _contrast = contrast if isinstance(contrast, (int, float)) else \
- nn.Parameter(contrast.clone().to(device=device, dtype=dtype))
- _saturation = saturation if isinstance(saturation, (int, float)) else \
- nn.Parameter(saturation.clone().to(device=device, dtype=dtype))
- _hue = hue if isinstance(hue, (int, float)) else \
- nn.Parameter(hue.clone().to(device=device, dtype=dtype))
+ _brightness = (
+ brightness
+ if isinstance(brightness, (int, float))
+ else nn.Parameter(brightness.clone().to(device=device, dtype=dtype))
+ )
+ _contrast = (
+ contrast
+ if isinstance(contrast, (int, float))
+ else nn.Parameter(contrast.clone().to(device=device, dtype=dtype))
+ )
+ _saturation = (
+ saturation
+ if isinstance(saturation, (int, float))
+ else nn.Parameter(saturation.clone().to(device=device, dtype=dtype))
+ )
+ _hue = hue if isinstance(hue, (int, float)) else nn.Parameter(hue.clone().to(device=device, dtype=dtype))
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = ColorJitter(_brightness, _contrast, _saturation, _hue, return_transform, same_on_batch)
if return_transform:
@@ -63,18 +76,13 @@ class TestColorJitterBackward:
class TestRandomAffineBackward:
-
- @pytest.mark.parametrize("degrees", [10, [10., 20.], (10, 20), torch.tensor(10.), torch.tensor([10, 20])])
+ @pytest.mark.parametrize("degrees", [10, [10.0, 20.0], (10, 20), torch.tensor(10.0), 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])]
+ "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])]
+ "shear", [[10.0, 20.0], [10.0, 20.0, 30.0, 40.0], 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])
@@ -84,17 +92,29 @@ class TestRandomAffineBackward:
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))
- _translate = translate if isinstance(translate, (int, float, list, tuple)) else \
- nn.Parameter(translate.clone().to(device=device, dtype=dtype))
- _scale = scale if isinstance(scale, (int, float, list, tuple)) else \
- nn.Parameter(scale.clone().to(device=device, dtype=dtype))
- _shear = shear if isinstance(shear, (int, float, list, tuple)) else \
- nn.Parameter(shear.clone().to(device=device, dtype=dtype))
+ _degrees = (
+ degrees
+ if isinstance(degrees, (int, float, list, tuple))
+ else nn.Parameter(degrees.clone().to(device=device, dtype=dtype))
+ )
+ _translate = (
+ translate
+ if isinstance(translate, (int, float, list, tuple))
+ else nn.Parameter(translate.clone().to(device=device, dtype=dtype))
+ )
+ _scale = (
+ scale
+ if isinstance(scale, (int, float, list, tuple))
+ else nn.Parameter(scale.clone().to(device=device, dtype=dtype))
+ )
+ _shear = (
+ shear
+ if isinstance(shear, (int, float, list, tuple))
+ else nn.Parameter(shear.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomAffine(
_degrees,
_translate,
@@ -104,7 +124,7 @@ class TestRandomAffineBackward:
align_corners=align_corners,
return_transform=return_transform,
same_on_batch=same_on_batch,
- p=1.
+ p=1.0,
)
if return_transform:
@@ -125,7 +145,7 @@ class TestRandomAffineBackward:
if resample == 'nearest' and aug.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
@@ -137,7 +157,7 @@ class TestRandomAffineBackward:
if resample == 'nearest' and aug.translate.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.translate._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.translate._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() == 0
@@ -149,7 +169,7 @@ class TestRandomAffineBackward:
if resample == 'nearest' and aug.scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.scale._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0
@@ -161,7 +181,7 @@ class TestRandomAffineBackward:
if resample == 'nearest' and aug.shear.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.shear._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.shear._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (shear.to(device=device, dtype=dtype) - aug.shear.data).sum() == 0
@@ -170,25 +190,27 @@ class TestRandomAffineBackward:
class TestRandomRotationBackward:
-
- @pytest.mark.parametrize("degrees", [10, [10., 20.], (10, 20), torch.tensor(10.), torch.tensor([10, 20])])
+ @pytest.mark.parametrize("degrees", [10, [10.0, 20.0], (10, 20), torch.tensor(10.0), torch.tensor([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])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, degrees, 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))
+ _degrees = (
+ degrees
+ if isinstance(degrees, (int, float, list, tuple))
+ else nn.Parameter(degrees.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomRotation(
_degrees,
resample,
align_corners=align_corners,
return_transform=return_transform,
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
if return_transform:
@@ -209,7 +231,7 @@ class TestRandomRotationBackward:
if resample == 'nearest' and aug.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
@@ -218,7 +240,6 @@ class TestRandomRotationBackward:
class TestRandomPerspectiveBackward:
-
@pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@@ -226,18 +247,21 @@ class TestRandomPerspectiveBackward:
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, distortion_scale, resample, align_corners, return_transform, same_on_batch, device, dtype):
- _distortion_scale = distortion_scale if isinstance(distortion_scale, (float, int)) else \
- nn.Parameter(distortion_scale.clone().to(device=device, dtype=dtype))
+ _distortion_scale = (
+ distortion_scale
+ if isinstance(distortion_scale, (float, int))
+ else nn.Parameter(distortion_scale.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomPerspective(
_distortion_scale,
resample=resample,
return_transform=return_transform,
same_on_batch=same_on_batch,
align_corners=align_corners,
- p=1.
+ p=1.0,
)
if return_transform:
@@ -258,7 +282,7 @@ class TestRandomPerspectiveBackward:
if resample == 'nearest' and aug.distortion_scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() == 0
@@ -267,8 +291,7 @@ class TestRandomPerspectiveBackward:
class TestRandomMotionBlurBackward:
-
- @pytest.mark.parametrize("angle", [20., torch.tensor([-20., 20.])])
+ @pytest.mark.parametrize("angle", [20.0, torch.tensor([-20.0, 20.0])])
@pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])
@pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@@ -276,14 +299,22 @@ class TestRandomMotionBlurBackward:
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, angle, direction, border_type, resample, return_transform, same_on_batch, device, dtype):
- _angle = angle if isinstance(angle, (float, int, list, tuple)) else \
- nn.Parameter(angle.clone().to(device=device, dtype=dtype))
- _direction = direction if isinstance(direction, (list, tuple)) else \
- nn.Parameter(direction.clone().to(device=device, dtype=dtype))
+ _angle = (
+ angle
+ if isinstance(angle, (float, int, list, tuple))
+ else nn.Parameter(angle.clone().to(device=device, dtype=dtype))
+ )
+ _direction = (
+ direction
+ if isinstance(direction, (list, tuple))
+ else nn.Parameter(direction.clone().to(device=device, dtype=dtype))
+ )
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.)
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
+ aug = RandomMotionBlur(
+ (3, 3), _angle, _direction, border_type, resample, return_transform, same_on_batch, p=1.0
+ )
if return_transform:
output, _ = aug(input)
@@ -302,7 +333,7 @@ class TestRandomMotionBlurBackward:
if resample == 'nearest' and aug.angle.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.angle._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.angle._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() == 0
@@ -311,7 +342,7 @@ class TestRandomMotionBlurBackward:
assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() != 0
if not isinstance(direction, (list, tuple)):
assert isinstance(aug.direction, torch.Tensor)
- if torch.all(aug.direction._grad == 0.):
+ if torch.all(aug.direction._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() == 0
@@ -321,17 +352,19 @@ class TestRandomMotionBlurBackward:
class TestRandomSharpnessBackward:
-
@pytest.mark.parametrize("sharpness", [0.5, [0, 0.5], torch.tensor([0, 0.5])])
@pytest.mark.parametrize("return_transform", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, sharpness, return_transform, same_on_batch, device, dtype):
- _sharpness = sharpness if isinstance(sharpness, (float, int, list, tuple)) else \
- nn.Parameter(sharpness.clone().to(device=device, dtype=dtype))
+ _sharpness = (
+ sharpness
+ if isinstance(sharpness, (float, int, list, tuple))
+ else nn.Parameter(sharpness.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomSharpness(_sharpness, return_transform=return_transform, same_on_batch=same_on_batch)
if return_transform:
@@ -353,23 +386,24 @@ class TestRandomSharpnessBackward:
class TestRandomResizedCropBackward:
-
@pytest.mark.skip("Param gen is probably breaking grads.")
- @pytest.mark.parametrize("scale", [[0.08, 1.], torch.tensor([0.08, 1.])])
- @pytest.mark.parametrize("ratio", [[3. / 4., 4. / 3.], torch.tensor([3. / 4., 4. / 3.])])
+ @pytest.mark.parametrize("scale", [[0.08, 1.0], torch.tensor([0.08, 1.0])])
+ @pytest.mark.parametrize("ratio", [[3.0 / 4.0, 4.0 / 3.0], torch.tensor([3.0 / 4.0, 4.0 / 3.0])])
@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, scale, ratio, resample, align_corners, return_transform, same_on_batch, device, dtype):
- _scale = scale if isinstance(scale, (list, tuple)) else \
- nn.Parameter(scale.clone().to(device=device, dtype=dtype))
- _ratio = ratio if isinstance(ratio, (list, tuple)) else \
- nn.Parameter(ratio.clone().to(device=device, dtype=dtype))
+ _scale = (
+ scale if isinstance(scale, (list, tuple)) else nn.Parameter(scale.clone().to(device=device, dtype=dtype))
+ )
+ _ratio = (
+ ratio if isinstance(ratio, (list, tuple)) else nn.Parameter(ratio.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomResizedCrop(
(8, 8),
_scale,
@@ -377,7 +411,7 @@ class TestRandomResizedCropBackward:
resample=resample,
return_transform=return_transform,
same_on_batch=same_on_batch,
- align_corners=align_corners
+ align_corners=align_corners,
)
if return_transform:
@@ -403,22 +437,23 @@ class TestRandomResizedCropBackward:
class TestRandomErasingBackward:
-
@pytest.mark.skip("Need differentiable indexing.")
@pytest.mark.parametrize("scale", [[0.02, 0.33], torch.tensor([0.02, 0.33])])
@pytest.mark.parametrize("ratio", [[0.3, 3.3], torch.tensor([0.3, 3.3])])
- @pytest.mark.parametrize("value", [0.])
+ @pytest.mark.parametrize("value", [0.0])
@pytest.mark.parametrize("return_transform", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, scale, ratio, value, return_transform, same_on_batch, device, dtype):
- _scale = scale if isinstance(scale, (list, tuple)) else \
- nn.Parameter(scale.clone().to(device=device, dtype=dtype))
- _ratio = ratio if isinstance(ratio, (list, tuple)) else \
- nn.Parameter(ratio.clone().to(device=device, dtype=dtype))
+ _scale = (
+ scale if isinstance(scale, (list, tuple)) else nn.Parameter(scale.clone().to(device=device, dtype=dtype))
+ )
+ _ratio = (
+ ratio if isinstance(ratio, (list, tuple)) else nn.Parameter(ratio.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomErasing(_scale, _ratio, value, return_transform, same_on_batch)
if return_transform:
@@ -435,7 +470,7 @@ class TestRandomErasingBackward:
if not isinstance(scale, (list, tuple)):
assert isinstance(aug.scale, torch.Tensor)
- if torch.all(aug.scale._grad == 0.):
+ if torch.all(aug.scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0
@@ -444,7 +479,7 @@ class TestRandomErasingBackward:
assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() != 0
if not isinstance(ratio, (list, tuple)):
assert isinstance(aug.ratio, torch.Tensor)
- if torch.all(aug.ratio._grad == 0.):
+ if torch.all(aug.ratio._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (ratio.to(device=device, dtype=dtype) - aug.ratio.data).sum() == 0
diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.py
index 1103f7e60..620711e70 100644
--- a/test/augmentation/test_backward_3d.py
+++ b/test/augmentation/test_backward_3d.py
@@ -2,37 +2,45 @@ import pytest
import torch
import torch.nn as nn
-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.]),
+ "degrees",
+ [
+ 10,
+ [10.0, 20.0],
+ [10.0, 20.0, 30.0],
+ [(10, 20), (10, 20), (10, 20)],
+ torch.tensor(10.0),
+ torch.tensor([10.0, 20.0]),
torch.tensor([10, 20, 30]),
- torch.tensor([(10, 20), (10, 20), (10, 20)])
- ]
+ 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)],
+ "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)])
- ]
+ 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.)],
+ "shear",
+ [
+ 10.0,
+ [10.0, 20.0],
+ [10.0, 20.0, 30.0, 40.0, 50.0, 60.0],
+ [(-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0)],
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.)])
- ]
+ torch.tensor([10.0, 20.0, 30.0, 40.0, 50.0, 60.0]),
+ torch.tensor([(-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0)]),
+ ],
)
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@@ -42,17 +50,29 @@ class TestRandomAffine3DBackward:
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))
- _translate = translate if isinstance(translate, (int, float, list, tuple)) else \
- nn.Parameter(translate.clone().to(device=device, dtype=dtype))
- _scale = scale if isinstance(scale, (int, float, list, tuple)) else \
- nn.Parameter(scale.clone().to(device=device, dtype=dtype))
- _shear = shear if isinstance(shear, (int, float, list, tuple)) else \
- nn.Parameter(shear.clone().to(device=device, dtype=dtype))
+ _degrees = (
+ degrees
+ if isinstance(degrees, (int, float, list, tuple))
+ else nn.Parameter(degrees.clone().to(device=device, dtype=dtype))
+ )
+ _translate = (
+ translate
+ if isinstance(translate, (int, float, list, tuple))
+ else nn.Parameter(translate.clone().to(device=device, dtype=dtype))
+ )
+ _scale = (
+ scale
+ if isinstance(scale, (int, float, list, tuple))
+ else nn.Parameter(scale.clone().to(device=device, dtype=dtype))
+ )
+ _shear = (
+ shear
+ if isinstance(shear, (int, float, list, tuple))
+ else nn.Parameter(shear.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomAffine3D(
_degrees,
_translate,
@@ -62,7 +82,7 @@ class TestRandomAffine3DBackward:
align_corners=align_corners,
return_transform=return_transform,
same_on_batch=same_on_batch,
- p=1.
+ p=1.0,
)
if return_transform:
@@ -83,7 +103,7 @@ class TestRandomAffine3DBackward:
if resample == 'nearest' and aug.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
@@ -95,7 +115,7 @@ class TestRandomAffine3DBackward:
if resample == 'nearest' and aug.translate.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.translate._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.translate._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (translate.to(device=device, dtype=dtype) - aug.translate.data).sum() == 0
@@ -107,7 +127,7 @@ class TestRandomAffine3DBackward:
if resample == 'nearest' and aug.scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.scale._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (scale.to(device=device, dtype=dtype) - aug.scale.data).sum() == 0
@@ -119,7 +139,7 @@ class TestRandomAffine3DBackward:
if resample == 'nearest' and aug.shears.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.shears._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.shears._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (shear.to(device=device, dtype=dtype) - aug.shears.data).sum() == 0
@@ -128,15 +148,18 @@ 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.]),
+ "degrees",
+ [
+ 10,
+ [10.0, 20.0],
+ [10.0, 20.0, 30.0],
+ [(10, 20), (10, 20), (10, 20)],
+ torch.tensor(10.0),
+ torch.tensor([10.0, 20.0]),
torch.tensor([10, 20, 30]),
- torch.tensor([(10, 20), (10, 20), (10, 20)])
- ]
+ 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])
@@ -144,18 +167,21 @@ class TestRandomRotation3DBackward:
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, degrees, 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))
+ _degrees = (
+ degrees
+ if isinstance(degrees, (int, float, list, tuple))
+ else nn.Parameter(degrees.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomRotation3D(
_degrees,
resample,
align_corners=align_corners,
return_transform=return_transform,
same_on_batch=same_on_batch,
- p=1.
+ p=1.0,
)
if return_transform:
@@ -176,7 +202,7 @@ class TestRandomRotation3DBackward:
if resample == 'nearest' and aug.degrees.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.degrees._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (degrees.to(device=device, dtype=dtype) - aug.degrees.data).sum() == 0
@@ -185,7 +211,6 @@ class TestRandomRotation3DBackward:
class TestRandomPerspective3DBackward:
-
@pytest.mark.parametrize("distortion_scale", [0.5, torch.tensor(0.5)])
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@@ -193,18 +218,21 @@ class TestRandomPerspective3DBackward:
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, distortion_scale, resample, align_corners, return_transform, same_on_batch, device, dtype):
- _distortion_scale = distortion_scale if isinstance(distortion_scale, (float, int)) else \
- nn.Parameter(distortion_scale.clone().to(device=device, dtype=dtype))
+ _distortion_scale = (
+ distortion_scale
+ if isinstance(distortion_scale, (float, int))
+ else nn.Parameter(distortion_scale.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomPerspective3D(
_distortion_scale,
resample=resample,
return_transform=return_transform,
same_on_batch=same_on_batch,
align_corners=align_corners,
- p=1.
+ p=1.0,
)
if return_transform:
@@ -225,7 +253,7 @@ class TestRandomPerspective3DBackward:
if resample == 'nearest' and aug.distortion_scale.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.distortion_scale._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (distortion_scale.to(device=device, dtype=dtype) - aug.distortion_scale.data).sum() == 0
@@ -234,8 +262,7 @@ class TestRandomPerspective3DBackward:
class TestRandomMotionBlur3DBackward:
-
- @pytest.mark.parametrize("angle", [20., torch.tensor(20.), torch.tensor([20.])])
+ @pytest.mark.parametrize("angle", [20.0, torch.tensor(20.0), torch.tensor([20.0])])
@pytest.mark.parametrize("direction", [[-0.5, 0.5], torch.tensor([-0.5, 0.5])])
# 'reflect' is not implemented by torch.
@pytest.mark.parametrize("border_type", ['constant', 'replicate', 'circular'])
@@ -244,15 +271,21 @@ class TestRandomMotionBlur3DBackward:
@pytest.mark.parametrize("same_on_batch", [True, False])
def test_param(self, angle, direction, border_type, resample, return_transform, same_on_batch, device, dtype):
- _angle = angle if isinstance(angle, (float, int, list, tuple)) else \
- nn.Parameter(angle.clone().to(device=device, dtype=dtype))
- _direction = direction if isinstance(direction, (list, tuple)) else \
- nn.Parameter(direction.clone().to(device=device, dtype=dtype))
+ _angle = (
+ angle
+ if isinstance(angle, (float, int, list, tuple))
+ else nn.Parameter(angle.clone().to(device=device, dtype=dtype))
+ )
+ _direction = (
+ direction
+ if isinstance(direction, (list, tuple))
+ else nn.Parameter(direction.clone().to(device=device, dtype=dtype))
+ )
torch.manual_seed(0)
- input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.
+ input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.0
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.0
)
if return_transform:
@@ -272,7 +305,7 @@ class TestRandomMotionBlur3DBackward:
if resample == 'nearest' and aug.angle.is_cuda:
# grid_sample in nearest mode and cuda device returns nan than 0
pass
- elif resample == 'nearest' or torch.all(aug.angle._grad == 0.):
+ elif resample == 'nearest' or torch.all(aug.angle._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() == 0
@@ -281,7 +314,7 @@ class TestRandomMotionBlur3DBackward:
assert (angle.to(device=device, dtype=dtype) - aug.angle.data).sum() != 0
if not isinstance(direction, (list, tuple)):
assert isinstance(aug.direction, torch.Tensor)
- if torch.all(aug.direction._grad == 0.):
+ if torch.all(aug.direction._grad == 0.0):
# grid_sample will return grad = 0 for resample nearest
# https://discuss.pytorch.org/t/autograd-issue-with-f-grid-sample/76894
assert (direction.to(device=device, dtype=dtype) - aug.direction.data).sum() == 0
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index 326991b3a..661048907 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -10,15 +10,14 @@ from kornia.augmentation.base import _BasicAugmentationBase, AugmentationBase2D
class TestBasicAugmentationBase:
-
def test_smoke(self, device, dtype):
- base = _BasicAugmentationBase(p=0.5, p_batch=1., same_on_batch=True)
+ base = _BasicAugmentationBase(p=0.5, p_batch=1.0, same_on_batch=True)
__repr__ = "p=0.5, p_batch=1.0, same_on_batch=True"
assert str(base) == __repr__
def test_infer_input(self, device, dtype):
input = torch.rand((2, 3, 4, 5), device=device, dtype=dtype)
- augmentation = _BasicAugmentationBase(p=1., p_batch=1)
+ augmentation = _BasicAugmentationBase(p=1.0, p_batch=1)
with patch.object(augmentation, "transform_tensor", autospec=True) as transform_tensor:
transform_tensor.side_effect = lambda x: x.unsqueeze(dim=2)
output = augmentation.transform_tensor(input)
@@ -26,19 +25,20 @@ class TestBasicAugmentationBase:
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),
- ]
+ "p,p_batch,same_on_batch,num,seed",
+ [
+ (1.0, 1.0, False, 12, 1),
+ (1.0, 0.0, False, 0, 1),
+ (0.0, 1.0, False, 0, 1),
+ (0.0, 0.0, False, 0, 1),
+ (0.5, 0.1, False, 7, 3),
+ (0.5, 0.1, True, 12, 3),
+ (0.3, 1.0, False, 2, 1),
+ (0.3, 1.0, 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:
@@ -54,11 +54,14 @@ class TestBasicAugmentationBase:
torch.manual_seed(42)
input = torch.rand((12, 3, 4, 5), device=device, dtype=dtype)
expected_output = input[..., :2, :2] if keepdim else input.unsqueeze(dim=0)[..., :2, :2]
- augmentation = _BasicAugmentationBase(p=.3, p_batch=1., keepdim=keepdim)
- with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, \
- patch.object(augmentation, "generate_parameters", autospec=True) as generate_parameters, \
- patch.object(augmentation, "transform_tensor", autospec=True) as transform_tensor, \
- patch.object(augmentation, "__check_batching__", autospec=True) as check_batching:
+ augmentation = _BasicAugmentationBase(p=0.3, p_batch=1.0, keepdim=keepdim)
+ with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, patch.object(
+ augmentation, "generate_parameters", autospec=True
+ ) as generate_parameters, patch.object(
+ augmentation, "transform_tensor", autospec=True
+ ) as transform_tensor, patch.object(
+ augmentation, "__check_batching__", autospec=True
+ ) as check_batching:
generate_parameters.side_effect = lambda shape: {
'degrees': torch.arange(0, shape[0], device=device, dtype=dtype)
@@ -72,21 +75,21 @@ class TestBasicAugmentationBase:
class TestAugmentationBase2D:
-
@pytest.mark.parametrize(
- 'input_shape, in_trans_shape', [
+ '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)
- augmentation = AugmentationBase2D(p=1., p_batch=1)
+ augmentation = AugmentationBase2D(p=1.0, p_batch=1)
augmentation.__check_batching__(input)
augmentation.__check_batching__((input, in_trans))
@@ -96,11 +99,13 @@ class TestAugmentationBase2D:
input_transform = torch.rand((2, 3, 3), device=device, dtype=dtype)
expected_output = torch.rand((2, 3, 4, 5), device=device, dtype=dtype)
expected_transform = torch.rand((2, 3, 3), device=device, dtype=dtype)
- augmentation = AugmentationBase2D(return_transform=False, p=1.)
+ augmentation = AugmentationBase2D(return_transform=False, p=1.0)
- with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, \
- patch.object(augmentation, "generate_parameters", autospec=True) as generate_parameters, \
- patch.object(augmentation, "compute_transformation", autospec=True) as compute_transformation:
+ with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, patch.object(
+ augmentation, "generate_parameters", autospec=True
+ ) as generate_parameters, patch.object(
+ augmentation, "compute_transformation", autospec=True
+ ) as compute_transformation:
# Calling the augmentation with a single tensor shall return the expected tensor using the generated params.
params = {'params': {}, 'flags': {'foo': 0}}
@@ -155,11 +160,13 @@ class TestAugmentationBase2D:
input_param = {'batch_prob': torch.tensor([True]), 'params': {'x': input_transform}, 'flags': {}}
- augmentation = AugmentationBase2D(return_transform=True, p=1.)
+ augmentation = AugmentationBase2D(return_transform=True, p=1.0)
- with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, \
- patch.object(augmentation, "generate_parameters", autospec=True) as generate_parameters, \
- patch.object(augmentation, "compute_transformation", autospec=True) as compute_transformation:
+ with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform, patch.object(
+ augmentation, "generate_parameters", autospec=True
+ ) as generate_parameters, patch.object(
+ augmentation, "compute_transformation", autospec=True
+ ) as compute_transformation:
apply_transform.return_value = output
compute_transformation.return_value = other_transform
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index 895378bc1..17bf3eb02 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -5,7 +5,6 @@ import kornia.augmentation as K
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):
@@ -15,38 +14,36 @@ class TestVideoSequential:
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.),
- ]
+ 'augmentation',
+ [
+ K.RandomAffine(360, p=1.0),
+ K.CenterCrop((3, 3), p=1.0),
+ K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0),
+ K.RandomCrop((5, 5), p=1.0),
+ K.RandomErasing(p=1.0),
+ K.RandomGrayscale(p=1.0),
+ K.RandomHorizontalFlip(p=1.0),
+ K.RandomVerticalFlip(p=1.0),
+ K.RandomPerspective(p=1.0),
+ K.RandomResizedCrop((5, 5), p=1.0),
+ K.RandomRotation(360.0, p=1.0),
+ K.RandomSolarize(p=1.0),
+ K.RandomPosterize(p=1.0),
+ K.RandomSharpness(p=1.0),
+ K.RandomEqualize(p=1.0),
+ K.RandomMotionBlur(3, 35.0, 0.5, p=1.0),
+ K.Normalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.0),
+ K.Denormalize(torch.tensor([0.5, 0.5, 0.5]), torch.tensor([0.5, 0.5, 0.5]), p=1.0),
+ ],
)
@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.
+ input = torch.randint(255, (1, 3, 3, 5, 6), device=device, dtype=dtype).repeat(2, 1, 1, 1, 1) / 255.0
torch.manual_seed(21)
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=0.5), K.RandomAffine(360, p=0.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 +55,15 @@ class TestVideoSequential:
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.)],
- ]
+ 'augmentations',
+ [
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)],
+ [K.RandomAffine(360, p=1.0)],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0), K.RandomAffine(360, p=0.0)],
+ [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=0.0)],
+ [K.RandomAffine(360, p=0.0)],
+ ],
)
@pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])
def test_same_on_frame(self, augmentations, data_format, device, dtype):
@@ -90,7 +82,9 @@ 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.0)], [K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)]]
+ )
@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 c63408140..b55326e8a 100644
--- a/test/augmentation/test_functional.py
+++ b/test/augmentation/test_functional.py
@@ -6,14 +6,13 @@ from kornia.constants import pi
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
+ [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 2.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
+ [[0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [2.0, 1.0, 0.0, 0.0]], device=device, dtype=dtype
) # 3 x 4
assert (F.apply_hflip(input[None, None]) == expected).all()
@@ -21,11 +20,11 @@ class TestHorizontalFlipFn:
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
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 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
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.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
@@ -34,11 +33,12 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.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
+ expected = torch.tensor(
+ [[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype
+ ) # 3 x 3
assert (F.apply_vflip(input[None, None]) == expected).all()
@@ -46,11 +46,11 @@ class TestVerticalFlipFn:
batch_size = 5
input = torch.tensor(
- [[[[0., 0., 0.], [0., 0., 0.], [0., 1., 1.]]]], device=device, dtype=dtype
+ [[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 1.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
+ [[[[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [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
@@ -60,15 +60,14 @@ class TestVerticalFlipFn:
class TestColorJitter:
-
def test_color_jitter(self):
jitter_param = {
- 'brightness_factor': torch.tensor(1.),
- 'contrast_factor': torch.tensor(1.),
- 'saturation_factor': torch.tensor(1.),
- 'hue_factor': torch.tensor(0.),
- 'order': torch.tensor([2, 3, 0, 1])
+ 'brightness_factor': torch.tensor(1.0),
+ 'contrast_factor': torch.tensor(1.0),
+ 'saturation_factor': torch.tensor(1.0),
+ 'hue_factor': torch.tensor(0.0),
+ 'order': torch.tensor([2, 3, 0, 1]),
}
input = torch.rand(3, 5, 5) # 3 x 5 x 5
@@ -80,11 +79,11 @@ class TestColorJitter:
def test_color_jitter_batch(self):
batch_size = 2
jitter_param = {
- 'brightness_factor': torch.tensor([1.] * batch_size),
- 'contrast_factor': torch.tensor([1.] * batch_size),
- 'saturation_factor': torch.tensor([1.] * batch_size),
- 'hue_factor': torch.tensor([0.] * batch_size),
- 'order': torch.tensor([2, 3, 0, 1])
+ 'brightness_factor': torch.tensor([1.0] * batch_size),
+ 'contrast_factor': torch.tensor([1.0] * batch_size),
+ 'saturation_factor': torch.tensor([1.0] * batch_size),
+ 'hue_factor': torch.tensor([0.0] * batch_size),
+ 'order': torch.tensor([2, 3, 0, 1]),
}
input = torch.rand(batch_size, 3, 5, 5) # 2 x 3 x 5 x 5
@@ -96,13 +95,13 @@ class TestColorJitter:
torch.manual_seed(42)
jitter_param = {
'brightness_factor': torch.tensor([1.1529, 1.1660]),
- 'contrast_factor': torch.tensor([1., 1.]),
- 'hue_factor': torch.tensor([0., 0.]),
- 'saturation_factor': torch.tensor([1., 1.]),
- 'order': torch.tensor([2, 3, 0, 1])
+ 'contrast_factor': torch.tensor([1.0, 1.0]),
+ 'hue_factor': torch.tensor([0.0, 0.0]),
+ 'saturation_factor': torch.tensor([1.0, 1.0]),
+ '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.0]]]]) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
expected = torch.tensor(
@@ -110,13 +109,13 @@ class TestColorJitter:
[
[[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.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]]
- ]
+ [[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
@@ -125,14 +124,14 @@ class TestColorJitter:
def test_random_contrast(self):
torch.manual_seed(42)
jitter_param = {
- 'brightness_factor': torch.tensor([1., 1.]),
+ 'brightness_factor': torch.tensor([1.0, 1.0]),
'contrast_factor': torch.tensor([0.9531, 1.1837]),
- 'hue_factor': torch.tensor([0., 0.]),
- 'saturation_factor': torch.tensor([1., 1.]),
- 'order': torch.tensor([2, 3, 0, 1])
+ 'hue_factor': torch.tensor([0.0, 0.0]),
+ 'saturation_factor': torch.tensor([1.0, 1.0]),
+ '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.0]]]]) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
expected = torch.tensor(
@@ -140,13 +139,13 @@ class TestColorJitter:
[
[[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.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]]
- ]
+ [[0.1184, 0.2367, 0.3551], [0.7102, 0.5919, 0.4735], [0.8286, 0.9470, 1.0000]],
+ ],
]
)
@@ -155,19 +154,19 @@ class TestColorJitter:
def test_random_saturation(self):
torch.manual_seed(42)
jitter_param = {
- 'brightness_factor': torch.tensor([1., 1.]),
- 'contrast_factor': torch.tensor([1., 1.]),
- 'hue_factor': torch.tensor([0., 0.]),
+ 'brightness_factor': torch.tensor([1.0, 1.0]),
+ 'contrast_factor': torch.tensor([1.0, 1.0]),
+ 'hue_factor': torch.tensor([0.0, 0.0]),
'saturation_factor': torch.tensor([0.9026, 1.1175]),
- 'order': torch.tensor([2, 3, 0, 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.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
]
) # 1 x 1 x 3 x 3
@@ -177,32 +176,38 @@ class TestColorJitter:
[
[
[
- [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.8763e-01, 2.5842e-01, 3.3895e-01],
+ [6.2921e-01, 5.0000e-01, 4.0000e-01],
+ [7.0974e-01, 8.0000e-01, 1.0000e00],
],
[
- [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]
+ [1.0000e00, 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]
- ]
+ [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.1921e-07, 1.2953e-01, 2.5302e-01],
+ [5.6476e-01, 5.0000e-01, 4.0000e-01],
+ [6.8825e-01, 8.0000e-01, 1.0000e00],
],
[
- [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]
+ [1.0000e00, 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]
- ]
- ]
+ [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],
+ ],
+ ],
]
)
@@ -211,18 +216,18 @@ class TestColorJitter:
def test_random_hue(self):
torch.manual_seed(42)
jitter_param = {
- 'brightness_factor': torch.tensor([1., 1.]),
- 'contrast_factor': torch.tensor([1., 1.]),
+ 'brightness_factor': torch.tensor([1.0, 1.0]),
+ 'contrast_factor': torch.tensor([1.0, 1.0]),
'hue_factor': torch.tensor([-0.0438 / 2 / pi, 0.0404 / 2 / pi]),
- 'saturation_factor': torch.tensor([1., 1.]),
- 'order': torch.tensor([2, 3, 0, 1])
+ 'saturation_factor': torch.tensor([1.0, 1.0]),
+ '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.]],
+ [[0.1, 0.2, 0.3], [0.6, 0.5, 0.4], [0.7, 0.8, 1.0]],
[[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]]
+ [[0.6, 0.8, 0.7], [0.9, 0.3, 0.2], [0.8, 0.4, 0.5]],
]
]
) # 1 x 1 x 3 x 3
@@ -233,13 +238,13 @@ class TestColorJitter:
[
[[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.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]]
- ]
+ [[0.6347, 0.8000, 0.7000], [0.9000, 0.3000, 0.2000], [0.8000, 0.3730, 0.4692]],
+ ],
]
)
@@ -247,7 +252,6 @@ class TestColorJitter:
class TestRandomGrayscale:
-
def test_opencv_true(self, device):
data = torch.tensor(
[
@@ -256,22 +260,22 @@ class TestRandomGrayscale:
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
]
)
data = data.to(device)
@@ -283,22 +287,22 @@ class TestRandomGrayscale:
[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.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.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.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805],
+ ],
]
)
expected = expected.to(device)
@@ -314,22 +318,22 @@ class TestRandomGrayscale:
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
]
)
data = data.to(device)
@@ -343,22 +347,22 @@ class TestRandomGrayscale:
[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.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.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.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805],
+ ],
]
)
expected = expected.to(device)
@@ -368,7 +372,6 @@ class TestRandomGrayscale:
class TestRandomRectangleEarasing:
-
def test_rectangle_erasing1(self, device):
inputs = torch.ones(1, 1, 10, 10).to(device)
rect_params = {
@@ -376,17 +379,22 @@ class TestRandomRectangleEarasing:
"heights": torch.tensor([5]),
"xs": torch.tensor([5]),
"ys": torch.tensor([5]),
- "values": torch.tensor([0.])
+ "values": torch.tensor([0.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.]
+ [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, 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],
+ [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0],
]
]
]
@@ -400,22 +408,25 @@ class TestRandomRectangleEarasing:
"heights": torch.tensor([3, 2, 1]),
"xs": torch.tensor([0, 1, 2]),
"ys": torch.tensor([0, 1, 2]),
- "values": torch.tensor([0., 0., 0.])
+ "values": torch.tensor([0.0, 0.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.]]
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [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.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]],
+ [[1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]],
+ [[1.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 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.]]
- ]
+ [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0]],
+ [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0]],
+ [[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 0.0]],
+ ],
]
).to(device)
diff --git a/test/augmentation/test_motionblur.py b/test/augmentation/test_motionblur.py
index 44bf7c29c..80a2269c1 100644
--- a/test/augmentation/test_motionblur.py
+++ b/test/augmentation/test_motionblur.py
@@ -4,14 +4,8 @@ from torch.autograd import gradcheck
from torch.testing import assert_allclose
import kornia
-from kornia.augmentation import (
- RandomMotionBlur,
- RandomMotionBlur3D,
-)
-from kornia.filters import (
- motion_blur,
- motion_blur3d,
-)
+from kornia.augmentation import RandomMotionBlur, RandomMotionBlur3D
+from kornia.filters import motion_blur, motion_blur3d
from kornia.testing import tensor_to_gradcheck_var
@@ -22,13 +16,15 @@ class TestRandomMotionBlur:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self, device):
f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5)
- repr = "RandomMotionBlur(kernel_size=(3, 5), angle=tensor([10., 30.]), direction=tensor([-0.5000, 0.5000]), "\
+ repr = (
+ "RandomMotionBlur(kernel_size=(3, 5), angle=tensor([10., 30.]), direction=tensor([-0.5000, 0.5000]), "
"border_type='constant', p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
@pytest.mark.parametrize("same_on_batch", [True, False])
@pytest.mark.parametrize("return_transform", [True, False])
- @pytest.mark.parametrize("p", [0., 1.])
+ @pytest.mark.parametrize("p", [0.0, 1.0])
def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):
f = RandomMotionBlur(
kernel_size=(3, 5),
@@ -36,7 +32,7 @@ class TestRandomMotionBlur:
direction=0.5,
same_on_batch=same_on_batch,
return_transform=return_transform,
- p=p
+ p=p,
)
torch.manual_seed(0)
batch_size = 2
@@ -64,12 +60,15 @@ class TestRandomMotionBlur:
input = torch.randn(*input_shape)
- f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.)
+ f = RandomMotionBlur(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.0)
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()
+ 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,13 +81,14 @@ class TestRandomMotionBlur:
params = {
'batch_prob': torch.tensor([True]),
'ksize_factor': torch.tensor([31]),
- 'angle_factor': torch.tensor([30.]),
+ 'angle_factor': torch.tensor([30.0]),
'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
+ RandomMotionBlur(kernel_size=3, angle=(10, 30), direction=(-0.5, 0.5), p=1.0),
+ (inp, params),
+ raise_exception=True,
)
@@ -98,14 +98,16 @@ class TestRandomMotionBlur3D:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self, device, dtype):
f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5)
- repr = "RandomMotionBlur3D(kernel_size=(3, 5), angle=tensor([[10., 30.],"\
- "\n [10., 30.],\n [10., 30.]]), direction=tensor([-0.5000, 0.5000]), " \
+ repr = (
+ "RandomMotionBlur3D(kernel_size=(3, 5), angle=tensor([[10., 30.],"
+ "\n [10., 30.],\n [10., 30.]]), direction=tensor([-0.5000, 0.5000]), "
"border_type='constant', p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"
+ )
assert str(f) == repr
@pytest.mark.parametrize("same_on_batch", [True, False])
@pytest.mark.parametrize("return_transform", [True, False])
- @pytest.mark.parametrize("p", [0., 1.])
+ @pytest.mark.parametrize("p", [0.0, 1.0])
def test_random_motion_blur(self, same_on_batch, return_transform, p, device, dtype):
f = RandomMotionBlur3D(
kernel_size=(3, 5),
@@ -113,7 +115,7 @@ class TestRandomMotionBlur3D:
direction=0.5,
same_on_batch=same_on_batch,
return_transform=return_transform,
- p=p
+ p=p,
)
batch_size = 2
input = torch.randn(1, 3, 5, 6, 7, device=device, dtype=dtype).repeat(batch_size, 1, 1, 1, 1)
@@ -140,12 +142,15 @@ class TestRandomMotionBlur3D:
input = torch.randn(*input_shape)
- f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.)
+ f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5, p=1.0)
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()
+ 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)
@@ -157,11 +162,12 @@ class TestRandomMotionBlur3D:
params = {
'batch_prob': torch.tensor([True]),
'ksize_factor': torch.tensor([31]),
- 'angle_factor': torch.tensor([[30., 30., 30.]]),
+ 'angle_factor': torch.tensor([[30.0, 30.0, 30.0]]),
'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
+ 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 aed7ca76b..d0919934e 100644
--- a/test/augmentation/test_perspective.py
+++ b/test/augmentation/test_perspective.py
@@ -9,7 +9,6 @@ import kornia.testing as utils # test utils
class TestPerspective:
-
def test_smoke(self, device):
x_data = torch.rand(1, 2, 3, 4).to(device)
batch_prob = torch.rand(1, device=device) < 0.5
@@ -34,11 +33,7 @@ class TestPerspective:
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)
+ assert gradcheck(F.apply_perspective, (input, params, flags), raise_exception=True)
class TestRandomPerspective:
@@ -89,7 +84,7 @@ class TestRandomPerspective:
torch.manual_seed(0)
x_data = torch.rand(1, 2, 4, 5).to(device)
- aug = kornia.augmentation.RandomPerspective(p=0., return_transform=True)
+ aug = kornia.augmentation.RandomPerspective(p=0.0, return_transform=True)
out_perspective = aug(x_data)
assert isinstance(out_perspective, tuple)
@@ -108,26 +103,30 @@ class TestRandomPerspective:
[
[
[
- [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.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]
- ]
+ [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
+ 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
+ dtype=x_data.dtype,
)
- aug = kornia.augmentation.RandomPerspective(p=.99999999, return_transform=True) # step one the random state
+ aug = kornia.augmentation.RandomPerspective(p=0.99999999, return_transform=True) # step one the random state
out_perspective = aug(x_data)
@@ -143,7 +142,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.0), (input,), raise_exception=True)
class TestRandomAffine:
@@ -152,32 +151,33 @@ class TestRandomAffine:
def test_smoke_no_transform(self, device):
x_data = torch.rand(1, 2, 8, 9).to(device)
- aug = kornia.augmentation.RandomAffine(0.)
+ aug = kornia.augmentation.RandomAffine(0.0)
out = aug(x_data)
assert out.shape == x_data.shape
assert aug.inverse(out).shape == x_data.shape
def test_smoke_no_transform_batch(self, device):
x_data = torch.rand(2, 2, 8, 9).to(device)
- aug = kornia.augmentation.RandomAffine(0.)
+ aug = kornia.augmentation.RandomAffine(0.0)
out = aug(x_data)
assert out.shape == x_data.shape
assert aug.inverse(out).shape == x_data.shape
- @pytest.mark.parametrize("degrees", [45., (-45., 45.), torch.tensor([45., 45.])])
+ @pytest.mark.parametrize("degrees", [45.0, (-45.0, 45.0), torch.tensor([45.0, 45.0])])
@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])]
+ "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.])
- ]
+ "shear",
+ [
+ 5.0,
+ (-5.0, 5.0),
+ (-5.0, 5.0, -3.0, 3.0),
+ torch.tensor(5.0),
+ torch.tensor([-5.0, 5.0]),
+ torch.tensor([-5.0, 5.0, -3.0, 3.0]),
+ ],
)
def test_batch_multi_params(self, degrees, translate, scale, shear, device, dtype):
x_data = torch.rand(2, 2, 8, 9).to(device)
@@ -188,7 +188,7 @@ class TestRandomAffine:
def test_smoke_transform(self, device):
x_data = torch.rand(1, 2, 4, 5).to(device)
- aug = kornia.augmentation.RandomAffine(0., return_transform=True)
+ aug = kornia.augmentation.RandomAffine(0.0, return_transform=True)
out = aug(x_data)
assert isinstance(out, tuple)
@@ -201,4 +201,4 @@ class TestRandomAffine:
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.RandomAffine(10, p=0.), (input, ), raise_exception=True)
+ assert gradcheck(kornia.augmentation.RandomAffine(10, p=0.0), (input,), raise_exception=True)
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index f701a3f29..aded9def4 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -21,8 +21,7 @@ from kornia.augmentation.random_generator import (
)
-class RandomGeneratorBaseTests():
-
+class RandomGeneratorBaseTests:
def test_valid_param_combinations(self, device, dtype):
raise NotImplementedError
@@ -37,8 +36,7 @@ class RandomGeneratorBaseTests():
class TestRandomProbGen(RandomGeneratorBaseTests):
-
- @pytest.mark.parametrize('p', [0., 0.5, 1.])
+ @pytest.mark.parametrize('p', [0.0, 0.5, 1.0])
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, p, batch_size, same_on_batch, device, dtype):
@@ -48,9 +46,9 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
'p',
[
# Should be failed if p > 1. or p < 0.
- (-1.),
- (2.)
- ]
+ (-1.0),
+ (2.0),
+ ],
)
def test_invalid_param_combinations(self, p, device, dtype):
with pytest.raises(Exception):
@@ -58,7 +56,7 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize(
'p,expected',
- [(0., [False] * 8), (0.5, [False, False, True, False, True, False, True, False]), (1., [True] * 8)]
+ [(0.0, [False] * 8), (0.5, [False, False, True, False, True, False, True, False]), (1.0, [True] * 8)],
)
def test_random_gen(self, p, expected, device, dtype):
torch.manual_seed(42)
@@ -66,19 +64,15 @@ class TestRandomProbGen(RandomGeneratorBaseTests):
res = random_prob_generator(batch_size=batch_size, p=p)
assert (res == torch.tensor(expected)).long().sum() == batch_size
- @pytest.mark.parametrize("seed,expected", [
- (42, [False] * 8),
- (0, [True] * 8),
- ])
+ @pytest.mark.parametrize("seed,expected", [(42, [False] * 8), (0, [True] * 8)])
def test_same_on_batch(self, seed, expected, device, dtype):
torch.manual_seed(seed)
batch_size = 8
- res = random_prob_generator(batch_size=batch_size, p=.5, same_on_batch=True)
+ res = random_prob_generator(batch_size=batch_size, p=0.5, same_on_batch=True)
assert (res == torch.tensor(expected)).long().sum() == batch_size
class TestColorJitterGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('brightness', [None, torch.tensor([0.8, 1.2])])
@pytest.mark.parametrize('contrast', [None, torch.tensor([0.8, 1.2])])
@pytest.mark.parametrize('saturation', [None, torch.tensor([0.8, 1.2])])
@@ -93,32 +87,33 @@ 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.])),
- ]
+ (torch.tensor([-1.0, 2.0]), None, None, None),
+ (torch.tensor([0.0, 3.0]), None, None, None),
+ (torch.tensor(0.0), None, None, None),
+ (torch.tensor([0.0]), None, None, None),
+ (torch.tensor([0.0, 1.0, 2.0]), None, None, None),
+ (None, torch.tensor([-1.0, 2.0]), None, None),
+ (None, torch.tensor(0.0), None, None),
+ (None, torch.tensor([0.0]), None, None),
+ (None, torch.tensor([0.0, 1.0, 2.0]), None, None),
+ (None, None, torch.tensor([-1.0, 2.0]), None),
+ (None, None, torch.tensor(0.0), None),
+ (None, None, torch.tensor([0.0]), None),
+ (None, None, torch.tensor([0.0, 1.0, 2.0]), None),
+ (None, None, None, torch.tensor([-1.0, 0.0])),
+ (None, None, None, torch.tensor([0, 1.0])),
+ (None, None, None, torch.tensor(0.0)),
+ (None, None, None, torch.tensor([0.0])),
+ (None, None, None, torch.tensor([0.0, 1.0, 2.0])),
+ ],
)
def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):
with pytest.raises(Exception):
@@ -127,7 +122,7 @@ 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
+ hue.to(device=device, dtype=dtype) if hue is not None else None,
)
def test_random_gen(self, device, dtype):
@@ -138,7 +133,7 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
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 = {
@@ -154,12 +149,12 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
'saturation_factor': torch.tensor(
[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)
+ 'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype),
}
- assert set(list(jitter_params.keys())) == set([
- 'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order']), \
- "Redundant keys found apart from \
+ assert set(list(jitter_params.keys())) == set(
+ ['brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order']
+ ), "Redundant keys found apart from \
'brightness_factor', 'contrast_factor', 'hue_factor', 'saturation_factor', 'order'"
assert_allclose(
@@ -183,7 +178,7 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
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
+ same_on_batch=True,
)
expected_res = {
@@ -191,7 +186,7 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
'contrast_factor': torch.tensor([1.2490] * batch_size, device=device, dtype=dtype),
'hue_factor': torch.tensor([-0.0234] * batch_size, device=device, dtype=dtype),
'saturation_factor': torch.tensor([1.3674] * batch_size, device=device, dtype=dtype),
- 'order': torch.tensor([2, 3, 0, 1], device=device, dtype=dtype)
+ '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)
@@ -202,9 +197,8 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('height,width', [(200, 200)])
- @pytest.mark.parametrize('distortion_scale', [torch.tensor(0.), torch.tensor(0.5), torch.tensor(1.)])
+ @pytest.mark.parametrize('distortion_scale', [torch.tensor(0.0), torch.tensor(0.5), torch.tensor(1.0)])
@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):
@@ -213,7 +207,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
height=height,
width=width,
distortion_scale=distortion_scale.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
@@ -224,8 +218,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
(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])),
- ]
+ (100, 100, torch.tensor([0.0, 0.5])),
+ ],
)
def test_invalid_param_combinations(self, height, width, distortion_scale, device, dtype):
with pytest.raises(Exception):
@@ -233,7 +227,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
batch_size=8,
height=height,
width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype)
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype),
)
def test_random_gen(self, device, dtype):
@@ -242,17 +236,20 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
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.]]],
+ [
+ [[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],
+ [[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]],
+ ],
device=device,
- dtype=dtype
+ 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]]
+ [[47.0386, 6.6593], [152.2701, 29.6790], [155.5298, 170.6142], [37.0547, 177.5298]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
),
)
assert res.keys() == expected.keys()
@@ -266,12 +263,13 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
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),
+ start_points=torch.tensor(
+ [[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]]], 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
+ dtype=dtype,
).repeat(2, 1, 1),
)
assert res.keys() == expected.keys()
@@ -280,7 +278,6 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
class TestRandomAffineGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 4])
@pytest.mark.parametrize('height', [200])
@pytest.mark.parametrize('width', [300])
@@ -300,11 +297,12 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
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
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'height,width,degrees,translate,scale,shear', [
+ '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),
@@ -318,7 +316,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
(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):
@@ -329,7 +327,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
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):
@@ -346,7 +344,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
translate=translate,
scale=scale,
shear=shear,
- same_on_batch=False
+ same_on_batch=False,
)
expected = dict(
translations=torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),
@@ -354,7 +352,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
scale=torch.tensor([[0.8914, 0.8914], [1.1797, 1.1797]], device=device, dtype=dtype),
angle=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype),
sx=torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),
- sy=torch.tensor([19.3460, 15.9358], device=device, dtype=dtype)
+ sy=torch.tensor([19.3460, 15.9358], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
@@ -378,7 +376,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
translate=translate,
scale=scale,
shear=shear,
- same_on_batch=True
+ same_on_batch=True,
)
expected = dict(
translations=torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),
@@ -386,7 +384,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
scale=torch.tensor([[1.1575, 1.1575], [1.1575, 1.1575]], device=device, dtype=dtype),
angle=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype),
sx=torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),
- sy=torch.tensor([16.0090, 16.0090], device=device, dtype=dtype)
+ sy=torch.tensor([16.0090, 16.0090], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
@@ -398,7 +396,6 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
class TestRandomRotationGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('degrees', [torch.tensor([0, 30])])
@pytest.mark.parametrize('same_on_batch', [True, False])
@@ -435,7 +432,6 @@ class TestRandomRotationGen(RandomGeneratorBaseTests):
class TestRandomCropGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('input_size', [(200, 200)])
@pytest.mark.parametrize('size', [(100, 100), torch.tensor([50, 50])])
@@ -451,14 +447,12 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
resize_to=resize_to,
same_on_batch=same_on_batch,
device=device,
- dtype=dtype
+ dtype=dtype,
)
@pytest.mark.parametrize(
- 'input_size,size,resize_to', [
- ((-300, 300), (200, 200), (100, 100)),
- ((200, 200), torch.tensor([50, 50]), (100, 100)),
- ]
+ '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
@@ -467,7 +461,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
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):
@@ -477,20 +471,20 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
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
+ 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
+ dtype=dtype,
),
- input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
+ input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'], expected['src'])
@@ -504,20 +498,20 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
input_size=(100, 100),
size=torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype),
resize_to=(200, 200),
- same_on_batch=True
+ 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
+ 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
+ dtype=dtype,
),
- input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
+ input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'], expected['src'])
@@ -525,11 +519,10 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
class TestRandomCropSizeGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('size', [(200, 200)])
- @pytest.mark.parametrize('scale', [torch.tensor([.7, 1.3])])
- @pytest.mark.parametrize('ratio', [torch.tensor([.9, 1.1])])
+ @pytest.mark.parametrize('scale', [torch.tensor([0.7, 1.3])])
+ @pytest.mark.parametrize('ratio', [torch.tensor([0.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):
random_crop_size_generator(
@@ -537,18 +530,19 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
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,
)
@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])),
- ]
+ 'size,scale,ratio',
+ [
+ ((100), torch.tensor([0.7, 1.3]), torch.tensor([0.9, 1.1])),
+ ((100, 100, 100), torch.tensor([0.7, 1.3]), torch.tensor([0.9, 1.1])),
+ ((100, 100), torch.tensor([0.7]), torch.tensor([0.9, 1.1])),
+ ((100, 100), torch.tensor([0.7, 1.3, 1.5]), torch.tensor([0.9, 1.1])),
+ ((100, 100), torch.tensor([0.7, 1.3]), torch.tensor([0.9])),
+ ((100, 100), torch.tensor([0.7, 1.3]), torch.tensor([0.9, 1.1, 1.3])),
+ ],
)
def test_invalid_param_combinations(self, size, scale, ratio, device, dtype):
batch_size = 2
@@ -558,7 +552,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
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):
@@ -568,13 +562,13 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
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
+ dtype=dtype,
)
)
assert res.keys() == expected.keys()
@@ -583,9 +577,9 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
res = random_crop_size_generator(
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
+ scale=torch.tensor([0.999, 1.0], device=device, dtype=dtype),
+ ratio=torch.tensor([1.0, 1.0], device=device, dtype=dtype),
+ same_on_batch=False,
)
expected = dict(size=torch.tensor([[100, 100]], device=device, dtype=dtype).repeat(100, 1))
assert res.keys() == expected.keys()
@@ -599,26 +593,25 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
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
- ),
+ dtype=dtype,
+ )
)
assert res.keys() == expected.keys()
assert_allclose(res['size'], expected['size'])
class TestRandomRectangleGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('height', [200])
@pytest.mark.parametrize('width', [300])
- @pytest.mark.parametrize('scale', [torch.tensor([.7, 1.1])])
- @pytest.mark.parametrize('ratio', [torch.tensor([.7, 1.1])])
+ @pytest.mark.parametrize('scale', [torch.tensor([0.7, 1.1])])
+ @pytest.mark.parametrize('ratio', [torch.tensor([0.7, 1.1])])
@pytest.mark.parametrize('value', [0])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
@@ -631,11 +624,12 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
scale=scale.to(device=device, dtype=dtype),
ratio=ratio.to(device=device, dtype=dtype),
value=value,
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'height,width,scale,ratio,value', [
+ '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),
@@ -644,8 +638,8 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
(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)),
- ]
+ (100, 100, torch.tensor([0.5, 0.7]), torch.tensor([0.7, 0.9]), torch.tensor(0.5)),
+ ],
)
def test_invalid_param_combinations(self, height, width, scale, ratio, value, device, dtype):
batch_size = 8
@@ -657,7 +651,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
scale=scale.to(device=device, dtype=dtype),
ratio=ratio.to(device=device, dtype=dtype),
value=value,
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
def test_random_gen(self, device, dtype):
@@ -674,7 +668,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
heights=torch.tensor([0, 0], device=device, dtype=dtype),
xs=torch.tensor([0, 0], device=device, dtype=dtype),
ys=torch.tensor([6, 8], device=device, dtype=dtype),
- values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype)
+ values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['widths'], expected['widths'])
@@ -697,7 +691,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
heights=torch.tensor([0, 0], device=device, dtype=dtype),
xs=torch.tensor([0, 0], device=device, dtype=dtype),
ys=torch.tensor([10, 10], device=device, dtype=dtype),
- values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype)
+ values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['widths'], expected['widths'])
@@ -708,7 +702,6 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
class TestCenterCropGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('height', [200])
@pytest.mark.parametrize('width', [200])
@@ -717,13 +710,14 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
center_crop_generator(batch_size=batch_size, height=height, width=width, size=size)
@pytest.mark.parametrize(
- 'height,width,size', [
+ '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
@@ -737,14 +731,14 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
src=torch.tensor(
[[[25, 40], [174, 40], [174, 159], [25, 159]], [[25, 40], [174, 40], [174, 159], [25, 159]]],
device=device,
- dtype=torch.long
+ 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
+ dtype=torch.long,
),
- input_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long)
+ input_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'].to(device=device), expected['src'])
@@ -755,7 +749,6 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
class TestRandomMotionBlur(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('kernel_size', [3, (3, 5)])
@pytest.mark.parametrize('angle', [torch.tensor([10, 30])])
@@ -767,17 +760,18 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'kernel_size,angle,direction', [
+ '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):
@@ -785,7 +779,7 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
batch_size=8,
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype)
+ direction=direction.to(device=device, dtype=dtype),
)
def test_random_gen(self, device, dtype):
@@ -797,12 +791,12 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
kernel_size=3,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=False
+ 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),
- direction_factor=torch.tensor([-0.2343, 0.9186], device=device, dtype=dtype)
+ direction_factor=torch.tensor([-0.2343, 0.9186], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
@@ -818,12 +812,12 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
kernel_size=3,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=True
+ 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),
- direction_factor=torch.tensor([0.8300, 0.8300], device=device, dtype=dtype)
+ direction_factor=torch.tensor([0.8300, 0.8300], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
@@ -832,7 +826,6 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
class TestRandomSolarizeGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('thresholds', [torch.tensor([0, 1]), torch.tensor([0.4, 0.6])])
@pytest.mark.parametrize('additions', [torch.tensor([-0.5, 0.5])])
@@ -842,25 +835,26 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
batch_size=batch_size,
thresholds=thresholds.to(device=device, dtype=dtype),
additions=additions.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'thresholds,additions', [
+ '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)
+ additions=additions.to(device=device, dtype=dtype),
)
def test_random_gen(self, device, dtype):
@@ -870,7 +864,7 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
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
+ same_on_batch=False,
)
expected = dict(
thresholds_factor=torch.tensor(
@@ -891,7 +885,7 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
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
+ same_on_batch=True,
)
expected = dict(
thresholds_factor=torch.tensor(
@@ -907,7 +901,6 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
class TestRandomPosterizeGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('bits', [torch.tensor([0, 8])])
@pytest.mark.parametrize('same_on_batch', [True, False])
@@ -916,14 +909,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
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(
@@ -952,20 +938,15 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
class TestRandomSharpnessGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('sharpness', [torch.tensor([0., 1.])])
+ @pytest.mark.parametrize('sharpness', [torch.tensor([0.0, 1.0])])
@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
)
- @pytest.mark.parametrize('sharpness', [
- (torch.tensor([-1, 5])),
- (torch.tensor([3])),
- ([0, 1.]),
- ])
+ @pytest.mark.parametrize('sharpness', [(torch.tensor([-1, 5])), (torch.tensor([3])), ([0, 1.0])])
def test_invalid_param_combinations(self, sharpness, device, dtype):
with pytest.raises(Exception):
random_sharpness_generator(
@@ -976,11 +957,12 @@ 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=False
+ batch_size=batch_size, sharpness=torch.tensor([0.0, 1.0], 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)
@@ -989,38 +971,34 @@ 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.0, 1.0], 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)
class TestRandomMixUpGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('p', [0., 0.5, 1.])
- @pytest.mark.parametrize('lambda_val', [None, torch.tensor([0., 1.])])
+ @pytest.mark.parametrize('p', [0.0, 0.5, 1.0])
+ @pytest.mark.parametrize('lambda_val', [None, torch.tensor([0.0, 1.0])])
@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
+ 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.]),
- ]
+ 'lambda_val', [(torch.tensor([-1, 1])), (torch.tensor([0, 2])), (torch.tensor([0, 0.5, 1])), ([0.0, 1.0])]
)
def test_invalid_param_combinations(self, lambda_val, device, dtype):
with pytest.raises(Exception):
@@ -1032,14 +1010,14 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
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
+ lambda_val=torch.tensor([0.0, 1.0], 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
- )
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
@@ -1050,15 +1028,15 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
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
+ p=0.9999,
+ lambda_val=torch.tensor([0.0, 1.0], 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
- )
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
@@ -1066,13 +1044,12 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
class TestRandomCutMixGen(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('p', [0, 0.5, 1.])
+ @pytest.mark.parametrize('p', [0, 0.5, 1.0])
@pytest.mark.parametrize('width,height', [(200, 200)])
@pytest.mark.parametrize('num_mix', [1, 3])
- @pytest.mark.parametrize('beta', [None, torch.tensor(1e-15), torch.tensor(1.)])
- @pytest.mark.parametrize('cut_size', [None, torch.tensor([0., 1.]), torch.tensor([0.3, 0.6])])
+ @pytest.mark.parametrize('beta', [None, torch.tensor(1e-15), torch.tensor(1.0)])
+ @pytest.mark.parametrize('cut_size', [None, torch.tensor([0.0, 1.0]), torch.tensor([0.3, 0.6])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
self, batch_size, p, width, height, num_mix, beta, cut_size, same_on_batch, device, dtype
@@ -1085,19 +1062,20 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
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
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'width,height,num_mix,beta,cut_size', [
+ '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.])),
- ]
+ (200, 200, 1, torch.tensor([0.0, 1.0]), None),
+ (200, 200, 1, None, torch.tensor([-1.0, 1.0])),
+ (200, 200, 1, None, torch.tensor([0.0, 2.0])),
+ ],
)
@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):
@@ -1110,7 +1088,7 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
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):
@@ -1122,17 +1100,17 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
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
+ beta=torch.tensor(1.0, device=device, dtype=dtype),
+ cut_size=torch.tensor([0.0, 1.0], 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
- )
+ dtype=dtype,
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
@@ -1147,17 +1125,17 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
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
+ beta=torch.tensor(1.0, device=device, dtype=dtype),
+ cut_size=torch.tensor([0.0, 1.0], 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
- )
+ 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 02c5673de..0ac8744c2 100644
--- a/test/augmentation/test_random_generator_3d.py
+++ b/test/augmentation/test_random_generator_3d.py
@@ -12,8 +12,7 @@ from kornia.augmentation.random_generator import (
)
-class RandomGeneratorBaseTests():
-
+class RandomGeneratorBaseTests:
def test_valid_param_combinations(self, device, dtype):
raise NotImplementedError
@@ -28,10 +27,9 @@ class RandomGeneratorBaseTests():
class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('depth,height,width', [(200, 200, 200)])
- @pytest.mark.parametrize('distortion_scale', [torch.tensor(0.), torch.tensor(0.5), torch.tensor(1.)])
+ @pytest.mark.parametrize('distortion_scale', [torch.tensor(0.0), torch.tensor(0.5), torch.tensor(1.0)])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
self, depth, height, width, distortion_scale, batch_size, same_on_batch, device, dtype
@@ -42,7 +40,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
height=height,
width=width,
distortion_scale=distortion_scale.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
@@ -53,8 +51,8 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
(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])),
- ]
+ (100, 100, 100, torch.tensor([0.0, 0.5])),
+ ],
)
def test_invalid_param_combinations(self, depth, height, width, distortion_scale, device, dtype):
with pytest.raises(Exception):
@@ -62,7 +60,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
batch_size=8,
height=height,
width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype)
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype),
)
def test_random_gen(self, device, dtype):
@@ -73,32 +71,54 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
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.0, 0.0],
+ [199.0, 0.0, 0.0],
+ [199.0, 199.0, 0.0],
+ [0.0, 199.0, 0.0],
+ [0.0, 0.0, 199.0],
+ [199.0, 0.0, 199.0],
+ [199.0, 199.0, 199.0],
+ [0.0, 199.0, 199.0],
],
[
- [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.0, 0.0],
+ [199.0, 0.0, 0.0],
+ [199.0, 199.0, 0.0],
+ [0.0, 199.0, 0.0],
+ [0.0, 0.0, 199.0],
+ [199.0, 0.0, 199.0],
+ [199.0, 199.0, 199.0],
+ [0.0, 199.0, 199.0],
+ ],
],
device=device,
- dtype=dtype
+ 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],
],
[
- [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]
- ]
+ [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
+ dtype=dtype,
),
)
assert res.keys() == expected.keys()
@@ -115,33 +135,55 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
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.0, 0.0],
+ [199.0, 0.0, 0.0],
+ [199.0, 199.0, 0.0],
+ [0.0, 199.0, 0.0],
+ [0.0, 0.0, 199.0],
+ [199.0, 0.0, 199.0],
+ [199.0, 199.0, 199.0],
+ [0.0, 199.0, 199.0],
],
[
- [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.0, 0.0],
+ [199.0, 0.0, 0.0],
+ [199.0, 199.0, 0.0],
+ [0.0, 199.0, 0.0],
+ [0.0, 0.0, 199.0],
+ [199.0, 0.0, 199.0],
+ [199.0, 199.0, 199.0],
+ [0.0, 199.0, 199.0],
+ ],
],
device=device,
- dtype=dtype
+ 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],
],
[
- [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
- )
+ dtype=dtype,
+ ),
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)
@@ -149,7 +191,6 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
class TestRandomAffineGen3D(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('depth,height,width', [(200, 300, 400)])
@pytest.mark.parametrize('degrees', [torch.tensor([(0, 30), (0, 30), (0, 30)])])
@@ -169,11 +210,12 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
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
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'depth,height,width,degrees,translate,scale,shear', [
+ '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),
@@ -185,7 +227,7 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
(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):
@@ -197,7 +239,7 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
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):
@@ -214,7 +256,7 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
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(
@@ -257,7 +299,7 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
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(
@@ -287,7 +329,6 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
class TestRandomRotationGen3D(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('degrees', [torch.tensor([[0, 30], [0, 30], [0, 30]])])
@pytest.mark.parametrize('same_on_batch', [True, False])
@@ -297,12 +338,8 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
)
@pytest.mark.parametrize(
- 'degrees', [
- (torch.tensor(10)),
- (torch.tensor([10])),
- (torch.tensor([[0, 30]])),
- (torch.tensor([[0, 30], [0, 30]])),
- ]
+ '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):
@@ -317,7 +354,7 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
expected = dict(
yaw=torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),
pitch=torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),
- roll=torch.tensor([11.7134, 18.0269], device=device, dtype=dtype)
+ roll=torch.tensor([11.7134, 18.0269], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)
@@ -333,7 +370,7 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
expected = dict(
yaw=torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),
pitch=torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),
- roll=torch.tensor([11.4859, 11.4859], device=device, dtype=dtype)
+ roll=torch.tensor([11.4859, 11.4859], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)
@@ -342,7 +379,6 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
class TestRandomCropGen3D(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('input_size', [(200, 200, 200)])
@pytest.mark.parametrize('size', [(100, 100, 100), torch.tensor([50, 60, 70])])
@@ -356,16 +392,17 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
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
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'input_size,size,resize_to', [
+ '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):
@@ -373,7 +410,7 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
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):
@@ -382,36 +419,60 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
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]
+ [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]
- ]
+ [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
+ 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],
],
[
- [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
+ dtype=dtype,
),
)
assert res.keys() == expected.keys()
@@ -425,36 +486,60 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
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
+ 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],
],
[
- [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
+ 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],
],
[
- [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
+ dtype=dtype,
),
)
assert res.keys() == expected.keys()
@@ -463,7 +548,6 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
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)])
@@ -471,13 +555,14 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
center_crop_generator3d(batch_size=batch_size, depth=depth, height=height, width=width, size=size)
@pytest.mark.parametrize(
- 'depth,height,width,size', [
+ '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):
@@ -490,22 +575,34 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
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]
+ [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
+ 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]
+ [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
+ dtype=torch.long,
).repeat(2, 1, 1),
)
assert res.keys() == expected.keys()
@@ -517,7 +614,6 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
-
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('kernel_size', [3, (3, 5)])
@pytest.mark.parametrize('angle', [torch.tensor([(10, 30), (30, 60), (60, 90)])])
@@ -529,17 +625,18 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch
+ same_on_batch=same_on_batch,
)
@pytest.mark.parametrize(
- 'kernel_size,angle,direction', [
+ '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):
@@ -547,7 +644,7 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
batch_size=8,
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype)
+ direction=direction.to(device=device, dtype=dtype),
)
def test_random_gen(self, device, dtype):
@@ -559,14 +656,14 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
kernel_size=3,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=False
+ 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
),
- direction_factor=torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype)
+ direction_factor=torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
@@ -582,14 +679,14 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
kernel_size=3,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=True
+ 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
),
- direction_factor=torch.tensor([0.9186, 0.9186], device=device, dtype=dtype)
+ direction_factor=torch.tensor([0.9186, 0.9186], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
diff --git a/test/augmentation/test_transformation_matrix.py b/test/augmentation/test_transformation_matrix.py
index a6f23a6b2..d296dd099 100644
--- a/test/augmentation/test_transformation_matrix.py
+++ b/test/augmentation/test_transformation_matrix.py
@@ -5,22 +5,21 @@ import kornia.augmentation.functional as F
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, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 2.0]]) # 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, 0.0, 3.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) # 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]]) # 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, 0.0, 2.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]]) # 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
@@ -29,23 +28,22 @@ class TestHorizontalFlipFn:
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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]) # 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, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]) # 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]]]]) # 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, 0.0], [0.0, -1.0, 2.0], [0.0, 0.0, 1.0]]]) # 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
@@ -54,7 +52,6 @@ class TestVerticalFlipFn:
class TestIntensityTransformation:
-
def test_intensity_transformation(self):
input = torch.rand(3, 5, 5) # 3 x 5 x 5
@@ -74,7 +71,6 @@ class TestIntensityTransformation:
class TestPerspective:
-
def test_smoke_transform(self, device):
x_data = torch.rand(1, 2, 3, 4).to(device)
batch_prob = torch.rand(1) < 0.5
diff --git a/test/color/test_gray.py b/test/color/test_gray.py
index f4951b740..66a9104dc 100644
--- a/test/color/test_gray.py
+++ b/test/color/test_gray.py
@@ -8,7 +8,6 @@ from kornia.testing import BaseTester # test utils
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)
@@ -21,7 +20,7 @@ class TestRgbToGrayscale(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_grayscale([0.])
+ assert kornia.color.rgb_to_grayscale([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -44,25 +43,25 @@ class TestRgbToGrayscale(BaseTester):
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_RGB2GRAY)
@@ -73,11 +72,11 @@ class TestRgbToGrayscale(BaseTester):
[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.6988886, 0.5897652, 0.6532392, 0.7234108, 0.7218805],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
img_gray = kornia.rgb_to_grayscale(data)
@@ -96,7 +95,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):
@@ -116,7 +115,6 @@ 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)
@@ -129,7 +127,7 @@ class TestBgrToGrayscale(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.bgr_to_grayscale([0.])
+ assert kornia.color.bgr_to_grayscale([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -147,25 +145,25 @@ class TestBgrToGrayscale(BaseTester):
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Output data generated with OpenCV 4.1.1: cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
@@ -180,7 +178,7 @@ class TestBgrToGrayscale(BaseTester):
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
img_gray = kornia.bgr_to_grayscale(data)
@@ -190,7 +188,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 796c2c1e4..339592953 100644
--- a/test/color/test_hls.py
+++ b/test/color/test_hls.py
@@ -10,7 +10,6 @@ from kornia.testing import BaseTester
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)
@@ -23,7 +22,7 @@ class TestRgbToHls(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_hls([0.])
+ assert kornia.color.rgb_to_hls([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -41,25 +40,25 @@ class TestRgbToHls(BaseTester):
[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.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.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]
- ]
+ [0.2281681, 0.2560037, 0.5134379, 0.5800887, 0.8685090],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# OpenCV
@@ -70,25 +69,25 @@ class TestRgbToHls(BaseTester):
[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.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.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]
- ]
+ [0.87768690, 0.96239233, 0.91754496, 0.55295944, 0.46453667],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kornia.color.rgb_to_hls(data), expected)
@@ -101,9 +100,9 @@ class TestRgbToHls(BaseTester):
[
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)
+ torch.zeros(2, 1, 5, 5, device=device, dtype=dtype),
],
- dim=1
+ dim=1,
)
assert_allclose(kornia.color.rgb_to_hls(data), expected)
@@ -112,7 +111,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):
@@ -132,7 +131,6 @@ 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)
@@ -145,7 +143,7 @@ class TestHlsToRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.hls_to_rgb([0.])
+ assert kornia.color.hls_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -164,26 +162,26 @@ class TestHlsToRgb(BaseTester):
[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.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.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]
- ]
+ [0.1058410, 0.0816052, 0.5792874, 0.9578886, 0.6281684],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
data[:, 0] = 2 * math.pi * data[:, 0]
@@ -197,26 +195,26 @@ class TestHlsToRgb(BaseTester):
[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.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.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]
- ]
+ [0.08502806, 0.63717590, 0.99679226, 0.98403690, 0.16492467],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
f = kornia.color.hls_to_rgb
@@ -232,7 +230,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 fea6b55f4..409d2f032 100644
--- a/test/color/test_hsv.py
+++ b/test/color/test_hsv.py
@@ -10,7 +10,6 @@ from kornia.testing import BaseTester
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)
@@ -23,7 +22,7 @@ class TestRgbToHsv(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_hsv([0.])
+ assert kornia.color.rgb_to_hsv([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -41,25 +40,25 @@ class TestRgbToHsv(BaseTester):
[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.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.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]
- ]
+ [0.7708948, 0.4509611, 0.0481175, 0.2358997, 0.6900532],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# OpenCV
@@ -70,25 +69,25 @@ class TestRgbToHsv(BaseTester):
[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]
+ [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.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]
- ]
+ [0.8932794, 0.85178390, 0.76217470, 0.89838010, 0.99185926],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kornia.color.rgb_to_hsv(data), expected)
@@ -104,7 +103,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):
@@ -124,7 +123,6 @@ 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)
@@ -137,7 +135,7 @@ class TestHsvToRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.hsv_to_rgb([0.])
+ assert kornia.color.hsv_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -156,26 +154,26 @@ class TestHsvToRgb(BaseTester):
[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.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.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]
- ]
+ [0.3236262, 0.0999796, 0.3614958, 0.5117705, 0.8194097],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# OpenCV
@@ -187,26 +185,26 @@ class TestHsvToRgb(BaseTester):
[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.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.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]
- ]
+ [0.11245217, 0.09997964, 0.36149580, 0.46373847, 0.48655340],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
f = kornia.color.hsv_to_rgb
@@ -222,7 +220,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 9659fe872..81e194e89 100644
--- a/test/color/test_lab.py
+++ b/test/color/test_lab.py
@@ -9,7 +9,6 @@ from kornia.testing import BaseTester
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)
@@ -22,7 +21,7 @@ class TestRgbToLab(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_lab([0.])
+ assert kornia.color.rgb_to_lab([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -36,52 +35,52 @@ class TestRgbToLab(BaseTester):
data = torch.tensor(
[
[
- [0., 1., 0.69396782, 0.63581685, 0.09902618],
+ [0.0, 1.0, 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.40908658, 0.10261389, 0.01691456, 0.76006799, 0.32971736],
],
[
- [0., 1., 0.79009938, 0.91742945, 0.60044175],
+ [0.0, 1.0, 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.39861023, 0.80680277, 0.82823833, 0.54438462, 0.22063386],
],
[
- [0., 1., 0.84317145, 0.59529881, 0.15297393],
+ [0.0, 1.0, 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]
- ]
+ [0.58402964, 0.89597990, 0.98276161, 0.25019163, 0.69285921],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Reference output generated using skimage: rgb2lab(data)
expected = torch.tensor(
[
[
- [0., 100., 79.75208576, 86.38913217, 55.25164186],
+ [0.0, 100.0, 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]
+ [45.02897165, 75.98315061, 78.257619, 61.85069778, 33.77972627],
],
[
- [0., -0.002454937, -5.40909568, -37.74958445, -55.02172792],
+ [0.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]
+ [12.32708756, -33.04781428, -29.29282657, 13.46090338, 42.98737069],
],
[
- [0., 0.00465342, -9.49591204, 32.9931831, 47.80929165],
+ [0.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]
- ]
+ [-25.45166461, -22.94347485, -31.32259433, 47.2621717, -60.05694598],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
@@ -100,7 +99,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):
@@ -120,7 +119,6 @@ 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)
@@ -133,7 +131,7 @@ class TestLabToRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.lab_to_rgb([0.])
+ assert kornia.color.lab_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -151,24 +149,24 @@ class TestLabToRgb(BaseTester):
[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]
+ [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]
+ [-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]
- ]
+ [92.31149292, -85.91405487, -32.83668518, -23.45091820, 69.99038696],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Reference output generated using skimage: lab2rgb(data)
@@ -176,26 +174,27 @@ class TestLabToRgb(BaseTester):
[
[
[
- [0.63513142, 0., 0.10660624, 0.79048697, 0.26823414],
+ [0.63513142, 0.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]
+ [1.0, 0.36069696, 0.29236125, 0.55744393, 0.0],
+ [0.41710863, 0.3198324, 0.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.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]
- ]
+ [0.28233233, 0.20235374, 0.19803933, 0.55069441, 0.0],
+ [0.50205101, 0.0, 0.79745394, 0.25376936, 0.6114783],
+ [0.0, 1.0, 0.80867314, 1.0, 0.28778443],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected_unclipped = torch.tensor(
@@ -205,24 +204,24 @@ class TestLabToRgb(BaseTester):
[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.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.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]
- ]
+ [-0.55802926, 1.0223477, 0.80867314, 1.07334156, 0.28778443],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
@@ -243,7 +242,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 a0e640102..603b85cd0 100644
--- a/test/color/test_luv.py
+++ b/test/color/test_luv.py
@@ -8,7 +8,6 @@ from kornia.testing import BaseTester, _get_precision
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)
@@ -21,7 +20,7 @@ class TestRgbToLuv(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_luv([0.])
+ assert kornia.color.rgb_to_luv([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -35,52 +34,52 @@ class TestRgbToLuv(BaseTester):
data = torch.tensor(
[
[
- [0., 1., 0.69396782, 0.63581685, 0.09902618],
+ [0.0, 1.0, 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.40908658, 0.10261389, 0.01691456, 0.76006799, 0.32971736],
],
[
- [0., 1., 0.79009938, 0.91742945, 0.60044175],
+ [0.0, 1.0, 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.39861023, 0.80680277, 0.82823833, 0.54438462, 0.22063386],
],
[
- [0., 1., 0.84317145, 0.59529881, 0.15297393],
+ [0.0, 1.0, 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]
- ]
+ [0.58402964, 0.89597990, 0.98276161, 0.25019163, 0.69285921],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Reference output generated using skimage: rgb2luv(data)
expected = torch.tensor(
[
[
- [0., 100., 79.75208282, 86.38912964, 55.25164032],
+ [0.0, 100.0, 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]
+ [45.02897263, 75.98315430, 78.25762177, 61.85069656, 33.77972794],
],
[
- [-0., -0.00054950, -13.54032803, -35.42317200, -49.27433014],
+ [-0.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]
+ [-1.55336237, -55.22497559, -56.21067810, 43.76751328, 1.46367633],
],
[
- [-0., 0.00766720, -13.74480152, 52.17128372, 60.92724228],
+ [-0.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]
- ]
+ [-38.39783859, -31.71204376, -46.63606644, 50.16629410, -84.74416351],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
tol_val: float = _get_precision(device, dtype)
@@ -98,7 +97,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):
@@ -118,7 +117,6 @@ 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)
@@ -131,7 +129,7 @@ class TestLuvToRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.luv_to_rgb([0.])
+ assert kornia.color.luv_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -149,24 +147,24 @@ class TestLuvToRgb(BaseTester):
[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]
+ [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]
+ [-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]
- ]
+ [92.31149292, -85.91405487, -32.83668518, -23.45091820, 69.99038696],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Reference output generated using skimage: luv2rgb(data)
@@ -178,24 +176,24 @@ class TestLuvToRgb(BaseTester):
[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.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.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]
- ]
+ [0.06325728, 0.78878325, 0.74280596, 0.99514300, 0.47176042],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kornia.color.luv_to_rgb(data), expected, rtol=1e-4, atol=1e-4)
@@ -213,7 +211,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 0db6b9b38..6095cd85b 100644
--- a/test/color/test_rgb.py
+++ b/test/color/test_rgb.py
@@ -8,7 +8,6 @@ from kornia.testing import BaseTester
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)
@@ -21,7 +20,7 @@ class TestRgbToBgr(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_bgr([0.])
+ assert kornia.color.rgb_to_bgr([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -32,7 +31,7 @@ class TestRgbToBgr(BaseTester):
assert kornia.color.rgb_to_bgr(img)
with pytest.raises(TypeError):
- assert kornia.color.bgr_to_rgb([0.])
+ assert kornia.color.bgr_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -50,11 +49,11 @@ class TestRgbToBgr(BaseTester):
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
+ [[[1.0, 1.0], [1.0, 1.0]], [[2.0, 2.0], [2.0, 2.0]], [[3.0, 3.0], [3.0, 3.0]]], device=device, dtype=dtype
) # 3x2x2
expected = torch.tensor(
- [[[3., 3.], [3., 3.]], [[2., 2.], [2., 2.]], [[1., 1.], [1., 1.]]], device=device, dtype=dtype
+ [[[3.0, 3.0], [3.0, 3.0]], [[2.0, 2.0], [2.0, 2.0]], [[1.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype
) # 3x2x2
f = kornia.color.rgb_to_bgr
@@ -64,7 +63,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):
@@ -92,23 +91,22 @@ 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)
+ assert isinstance(kornia.color.rgb_to_rgba(img, 0.0), torch.Tensor)
@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
img = torch.ones(shape, device=device, dtype=dtype)
- assert kornia.color.rgb_to_rgba(img, 0.).shape == tuple(out_shape)
+ assert kornia.color.rgb_to_rgba(img, 0.0).shape == tuple(out_shape)
def test_exception(self, device, dtype):
# rgb to rgba
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_rgba([0.], 0.)
+ assert kornia.color.rgb_to_rgba([0.0], 0.0)
with pytest.raises(TypeError):
img = torch.ones(1, 3, 1, 1, device=device, dtype=dtype)
@@ -116,11 +114,11 @@ class TestRgbToRgba(BaseTester):
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
- assert kornia.color.rgb_to_rgba(img, 0.)
+ assert kornia.color.rgb_to_rgba(img, 0.0)
with pytest.raises(ValueError):
img = torch.ones(2, 1, 1, device=device, dtype=dtype)
- assert kornia.color.rgb_to_rgba(img, 0.)
+ assert kornia.color.rgb_to_rgba(img, 0.0)
with pytest.raises(TypeError):
img = torch.ones(3, 1, 1, device=device, dtype=dtype)
@@ -128,7 +126,7 @@ class TestRgbToRgba(BaseTester):
# rgba to rgb
with pytest.raises(TypeError):
- assert kornia.color.rgba_to_rgb(0.)
+ assert kornia.color.rgba_to_rgb(0.0)
with pytest.raises(ValueError):
img = torch.ones(1, 3, 1, 1, device=device, dtype=dtype)
@@ -139,53 +137,57 @@ class TestRgbToRgba(BaseTester):
assert kornia.color.rgba_to_rgb(img)
def test_back_and_forth_rgb(self, device, dtype):
- a_val: float = 1.
+ a_val: float = 1.0
x_rgb = torch.ones(3, 4, 4, device=device, dtype=dtype)
x_rgba = kornia.color.rgb_to_rgba(x_rgb, a_val)
x_rgb_new = kornia.color.rgba_to_rgb(x_rgba)
assert_allclose(x_rgb, x_rgb_new)
def test_back_and_forth_bgr(self, device, dtype):
- a_val: float = 1.
+ a_val: float = 1.0
x_bgr = torch.ones(3, 4, 4, device=device, dtype=dtype)
x_rgba = kornia.color.bgr_to_rgba(x_bgr, a_val)
x_bgr_new = kornia.color.rgba_to_bgr(x_rgba)
assert_allclose(x_bgr, x_bgr_new)
- @pytest.mark.parametrize("aval", [0.4, 45.])
+ @pytest.mark.parametrize("aval", [0.4, 45.0])
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
+ [[[[1.0, 1.0], [1.0, 1.0]], [[2.0, 2.0], [2.0, 2.0]], [[3.0, 3.0], [3.0, 3.0]]]], 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]]
+ [[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
+ dtype=dtype,
) # Bx4x2x2
assert_allclose(kornia.rgb_to_rgba(data, aval), expected)
- @pytest.mark.parametrize("aval", [0.4, 45.])
+ @pytest.mark.parametrize("aval", [0.4, 45.0])
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
+ [[[[1.0, 1.0], [1.0, 1.0]], [[2.0, 2.0], [2.0, 2.0]], [[3.0, 3.0], [3.0, 3.0]]]], 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]]
+ [[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
+ dtype=dtype,
) # Bx4x2x2
aval = torch.full_like(data[:, :1], aval) # Bx1xHxW
@@ -195,7 +197,7 @@ class TestRgbToRgba(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_rgba, (img, 1.), raise_exception=True)
+ assert gradcheck(kornia.color.rgb_to_rgba, (img, 1.0), raise_exception=True)
@pytest.mark.grad
def test_gradcheck_th(self, device, dtype):
@@ -211,7 +213,7 @@ class TestRgbToRgba(BaseTester):
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
op = kornia.color.rgb_to_rgba
op_jit = torch.jit.script(op)
- assert_allclose(op(img, 1.), op_jit(img, 1.))
+ assert_allclose(op(img, 1.0), op_jit(img, 1.0))
aval = torch.ones(B, 1, H, W, device=device, dtype=dtype)
assert_allclose(op(img, aval), op_jit(img, aval))
@@ -219,17 +221,17 @@ class TestRgbToRgba(BaseTester):
def test_module(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
- ops = kornia.color.RgbToRgba(1.).to(device, dtype)
+ ops = kornia.color.RgbToRgba(1.0).to(device, dtype)
fcn = kornia.color.rgb_to_rgba
- assert_allclose(ops(img), fcn(img, 1.))
+ assert_allclose(ops(img), fcn(img, 1.0))
@pytest.mark.nn
def test_module_bgr(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
- ops = kornia.color.BgrToRgba(1.).to(device, dtype)
+ ops = kornia.color.BgrToRgba(1.0).to(device, dtype)
fcn = kornia.color.bgr_to_rgba
- assert_allclose(ops(img), fcn(img, 1.))
+ assert_allclose(ops(img), fcn(img, 1.0))
@pytest.mark.nn
def test_module_bgra2rgb(self, device, dtype):
@@ -249,7 +251,6 @@ 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)
@@ -264,7 +265,7 @@ class TestLinearRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_linear_rgb([0.])
+ assert kornia.color.rgb_to_linear_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -275,7 +276,7 @@ class TestLinearRgb(BaseTester):
assert kornia.color.rgb_to_linear_rgb(img)
with pytest.raises(TypeError):
- assert kornia.color.linear_rgb_to_rgb([0.])
+ assert kornia.color.linear_rgb_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -293,17 +294,17 @@ class TestLinearRgb(BaseTester):
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
+ [[[1.0, 0.0], [0.5, 0.1]], [[1.0, 0.0], [0.5, 0.2]], [[1.0, 0.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]]
+ [[1.00000000, 0.00000000], [0.21404116, 0.07323898]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 3x2x2
f = kornia.color.rgb_to_linear_rgb
@@ -314,14 +315,14 @@ class TestLinearRgb(BaseTester):
[
[[1.00000000, 0.00000000], [0.21404116, 0.01002283]],
[[1.00000000, 0.00000000], [0.21404116, 0.03310477]],
- [[1.00000000, 0.00000000], [0.21404116, 0.07323898]]
+ [[1.00000000, 0.00000000], [0.21404116, 0.07323898]],
],
device=device,
- dtype=dtype
+ 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
+ [[[1.0, 0.0], [0.5, 0.1]], [[1.0, 0.0], [0.5, 0.2]], [[1.0, 0.0], [0.5, 0.3]]], device=device, dtype=dtype
) # 3x2x2
f = kornia.color.linear_rgb_to_rgb
@@ -331,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 646db1049..0e37e6c85 100644
--- a/test/color/test_xyz.py
+++ b/test/color/test_xyz.py
@@ -8,7 +8,6 @@ from kornia.testing import BaseTester
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)
@@ -21,7 +20,7 @@ class TestRgbToXyz(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_xyz([0.])
+ assert kornia.color.rgb_to_xyz([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -36,21 +35,27 @@ class TestRgbToXyz(BaseTester):
[
[
[
- [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.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.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]
- ]
+ [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
+ dtype=dtype,
)
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
@@ -61,24 +66,24 @@ class TestRgbToXyz(BaseTester):
[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.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.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]
- ]
+ [0.29514894, 0.6179093, 0.12908883, 0.20075734, 0.3649534],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kornia.color.rgb_to_xyz(data), expected)
@@ -95,7 +100,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):
@@ -115,7 +120,6 @@ 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)
@@ -128,7 +132,7 @@ class TestXyzToRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.xyz_to_rgb([0.])
+ assert kornia.color.xyz_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -146,24 +150,24 @@ class TestXyzToRgb(BaseTester):
[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.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.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]
- ]
+ [0.6738866, 0.47461915, 0.91508406, 0.44147202, 0.14099535],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
@@ -174,24 +178,24 @@ class TestXyzToRgb(BaseTester):
[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.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.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]
- ]
+ [0.6330101, 0.3715171, 0.90575427, 0.36752605, 0.03138365],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kornia.color.xyz_to_rgb(data), expected, atol=1e-4, rtol=1e-4)
@@ -208,7 +212,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 e49cb61ba..9f934f439 100644
--- a/test/color/test_ycbcr.py
+++ b/test/color/test_ycbcr.py
@@ -8,7 +8,6 @@ from kornia.testing import BaseTester
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)
@@ -21,7 +20,7 @@ class TestRgbToYcbcr(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_ycbcr([0.])
+ assert kornia.color.rgb_to_ycbcr([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -36,24 +35,30 @@ class TestRgbToYcbcr(BaseTester):
[
[
[
- [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.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.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]
- ]
+ [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
+ dtype=dtype,
)
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
@@ -65,26 +70,26 @@ class TestRgbToYcbcr(BaseTester):
[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.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.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]
- ]
+ [0.65009415, 0.6246666, 0.13107029, 0.35291404, 0.6800583],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kornia.color.rgb_to_ycbcr(data), expected, atol=1e-4, rtol=1e-4)
@@ -97,7 +102,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):
@@ -117,7 +122,6 @@ 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)
@@ -130,7 +134,7 @@ class TestYcbcrToRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.ycbcr_to_rgb([0.])
+ assert kornia.color.ycbcr_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -145,24 +149,30 @@ class TestYcbcrToRgb(BaseTester):
[
[
[
- [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.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.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]
- ]
+ [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
+ dtype=dtype,
)
# Reference output generated using OpenCV: cv2.cvtColor(data, cv2.COLOR_RGB2XYZ)
@@ -174,26 +184,26 @@ class TestYcbcrToRgb(BaseTester):
[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.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.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]
- ]
+ [1.4082898, -0.21875012, 0.6804801, 0.9795798, 0.24646705],
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kornia.color.ycbcr_to_rgb(data), expected, atol=1e-4, rtol=1e-4)
@@ -206,7 +216,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 39e61cfe6..e7ffaf11b 100644
--- a/test/color/test_yuv.py
+++ b/test/color/test_yuv.py
@@ -8,7 +8,6 @@ from kornia.testing import BaseTester
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)
@@ -21,7 +20,7 @@ class TestRgbToYuv(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.rgb_to_yuv([0.])
+ assert kornia.color.rgb_to_yuv([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -48,7 +47,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):
@@ -68,7 +67,6 @@ 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)
@@ -81,7 +79,7 @@ class TestYuvToRgb(BaseTester):
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert kornia.color.yuv_to_rgb([0.])
+ assert kornia.color.yuv_to_rgb([0.0])
with pytest.raises(ValueError):
img = torch.ones(1, 1, device=device, dtype=dtype)
@@ -108,7 +106,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 7a07ace7f..c1b9a5817 100644
--- a/test/enhance/test_adjust.py
+++ b/test/enhance/test_adjust.py
@@ -10,7 +10,6 @@ from kornia.testing import tensor_to_gradcheck_var, BaseTester
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
@@ -18,7 +17,7 @@ class TestInvert:
@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.))
+ out = kornia.enhance.invert(img, torch.tensor(1.0))
assert out.shape == shape
def test_max_val_1(self, device, dtype):
@@ -27,15 +26,15 @@ class TestInvert:
assert_allclose(out, torch.zeros_like(out))
def test_max_val_255(self, device, dtype):
- img = 255. * torch.ones(1, 3, 4, 4, device=device, dtype=dtype)
- out = kornia.enhance.invert(img, torch.tensor(255.))
+ img = 255.0 * torch.ones(1, 3, 4, 4, device=device, dtype=dtype)
+ out = kornia.enhance.invert(img, torch.tensor(255.0))
assert_allclose(out, torch.zeros_like(out))
@pytest.mark.grad
def test_gradcheck(self, device, dtype):
B, C, H, W = 1, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=torch.float64, requires_grad=True)
- max_val = torch.tensor(1., device=device, dtype=torch.float64, requires_grad=True)
+ max_val = torch.tensor(1.0, device=device, dtype=torch.float64, requires_grad=True)
assert gradcheck(kornia.enhance.invert, (img, max_val), raise_exception=True)
@pytest.mark.jit
@@ -56,25 +55,26 @@ 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
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = data.clone()
- f = kornia.enhance.AdjustSaturation(1.)
+ f = kornia.enhance.AdjustSaturation(1.0)
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]]]
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x3x2x2
expected = data
@@ -85,29 +85,30 @@ 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.0), 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
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = data.clone()
- f = kornia.enhance.AdjustHue(0.)
+ f = kornia.enhance.AdjustHue(0.0)
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]]]
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x3x2x2
expected = data
@@ -117,11 +118,11 @@ class TestAdjustHue:
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]]]
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x3x2x2
pi_t = torch.tensor([-pi, pi], device=device, dtype=dtype)
@@ -134,77 +135,84 @@ 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.0), 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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = torch.ones_like(data)
- f = kornia.enhance.AdjustGamma(0.)
+ f = kornia.enhance.AdjustGamma(0.0)
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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = data.clone()
- f = kornia.enhance.AdjustGamma(1.)
+ f = kornia.enhance.AdjustGamma(1.0)
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]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.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
+ [[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]]], device=device, dtype=dtype
) # 3x2x2
- f = kornia.enhance.AdjustGamma(1., 2.)
+ f = kornia.enhance.AdjustGamma(1.0, 2.0)
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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = torch.tensor(
- [[[1., 1.], [1., 1.]], [[.25, .25], [.25, .25]], [[.0625, .0625], [.0625, .0625]]],
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.25, 0.25], [0.25, 0.25]], [[0.0625, 0.0625], [0.0625, 0.0625]]],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 3x2x2
- f = kornia.enhance.AdjustGamma(2.)
+ f = kornia.enhance.AdjustGamma(2.0)
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]]]
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
],
device=device,
- dtype=dtype
+ 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]]]
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.25, 0.25], [0.25, 0.25]], [[0.0625, 0.0625], [0.0625, 0.0625]]],
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.25, 0.25], [0.25, 0.25]], [[0.0625, 0.0625], [0.0625, 0.0625]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x3x2x2
- p1 = torch.tensor([2., 2.], device=device, dtype=dtype)
+ p1 = torch.tensor([2.0, 2.0], device=device, dtype=dtype)
p2 = torch.ones(2, device=device, dtype=dtype)
f = kornia.enhance.AdjustGamma(p1, gain=p2)
@@ -214,58 +222,73 @@ 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.0, 2.0), 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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = torch.zeros_like(data)
- f = kornia.enhance.AdjustContrast(0.)
+ f = kornia.enhance.AdjustContrast(0.0)
assert_allclose(f(data), expected)
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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = data.clone()
- f = kornia.enhance.AdjustContrast(1.)
+ f = kornia.enhance.AdjustContrast(1.0)
assert_allclose(f(data), expected)
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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.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
+ [[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]]], device=device, dtype=dtype
) # 3x2x2
- f = kornia.enhance.AdjustContrast(2.)
+ f = kornia.enhance.AdjustContrast(2.0)
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]]],
+ [
+ [[1.0, 1.0], [1.0, 1.0]],
+ [[0.5, 0.5], [0.5, 0.5]],
+ [[0.25, 0.25], [0.25, 0.25]],
+ [[0.5, 0.5], [0.5, 0.5]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 4x2x2
expected = torch.tensor(
- [[[0., 0.], [0., 0.]], [[.5, .5], [.5, .5]], [[.375, .375], [.375, .375]], [[1., 1.], [1., 1.]]],
+ [
+ [[0.0, 0.0], [0.0, 0.0]],
+ [[0.5, 0.5], [0.5, 0.5]],
+ [[0.375, 0.375], [0.375, 0.375]],
+ [[1.0, 1.0], [1.0, 1.0]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 4x2x2
factor = torch.tensor([0, 1, 1.5, 2], device=device, dtype=dtype)
@@ -277,20 +300,20 @@ class TestAdjustContrast:
# 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]]]
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ [[[0.0, 0.0], [0.0, 0.0]], [[0.3, 0.3], [0.3, 0.3]], [[0.6, 0.6], [0.6, 0.6]]],
],
device=device,
- dtype=dtype
+ 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.]]]
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ [[[0.0, 0.0], [0.0, 0.0]], [[0.6, 0.6], [0.6, 0.6]], [[1.0, 1.0], [1.0, 1.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x3x2x2
factor = torch.tensor([1, 2], device=device, dtype=dtype)
@@ -302,25 +325,39 @@ class TestAdjustContrast:
# 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]]]
+ [
+ [[1.0, 1.0, 0.5], [1.0, 1.0, 0.5]],
+ [[0.5, 0.5, 0.25], [0.5, 0.5, 0.25]],
+ [[0.25, 0.25, 0.25], [0.6, 0.6, 0.3]],
+ ],
+ [
+ [[0.0, 0.0, 1.0], [0.0, 0.0, 0.25]],
+ [[0.3, 0.3, 0.4], [0.3, 0.3, 0.4]],
+ [[0.6, 0.6, 0.0], [0.3, 0.2, 0.1]],
+ ],
],
device=device,
- dtype=dtype
+ 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]]]
+ [[1.0, 1.0, 0.75], [1.0, 1.0, 0.75]],
+ [[0.75, 0.75, 0.375], [0.75, 0.75, 0.375]],
+ [[0.375, 0.375, 0.375], [0.9, 0.9, 0.45]],
+ ],
+ [
+ [[0.0, 0.0, 1.0], [0.0, 0.0, 0.5]],
+ [[0.6, 0.6, 0.8], [0.6, 0.6, 0.8]],
+ [[1.0, 1.0, 0.0], [0.6, 0.4, 0.2]],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x3x2x3
- factor = torch.tensor([1.5, 2.], device=device, dtype=dtype)
+ factor = torch.tensor([1.5, 2.0], device=device, dtype=dtype)
f = kornia.enhance.AdjustContrast(factor)
assert_allclose(f(data), expected)
@@ -329,41 +366,48 @@ 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.0), 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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = data.clone()
- f = kornia.enhance.AdjustBrightness(0.)
+ f = kornia.enhance.AdjustBrightness(0.0)
assert_allclose(f(data), expected)
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
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
expected = torch.ones_like(data)
- f = kornia.enhance.AdjustBrightness(1.)
+ f = kornia.enhance.AdjustBrightness(1.0)
assert_allclose(f(data), expected)
def test_factor_minus(self, device, dtype):
# prepare input data
data = torch.tensor(
- [[[1., 1.], [1., 1.]], [[.75, .75], [.75, .75]], [[.25, .25], [.25, .25]]], device=device, dtype=dtype
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.75, 0.75], [0.75, 0.75]], [[0.25, 0.25], [0.25, 0.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
+ [[[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]], [[0.0, 0.0], [0.0, 0.0]]],
+ device=device,
+ dtype=dtype,
) # 3x2x2
f = kornia.enhance.AdjustBrightness(-0.5)
@@ -372,9 +416,14 @@ class TestAdjustBrightness:
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]]],
+ [
+ [[1.0, 1.0], [1.0, 1.0]],
+ [[0.5, 0.5], [0.5, 0.5]],
+ [[0.25, 0.25], [0.25, 0.25]],
+ [[0.5, 0.5], [0.5, 0.5]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 4x2x2
factor = torch.tensor([0, 0.5, 0.75, 2], device=device, dtype=dtype)
@@ -388,20 +437,20 @@ class TestAdjustBrightness:
# 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]]]
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.5, 0.5], [0.5, 0.5]], [[0.25, 0.25], [0.25, 0.25]]],
+ [[[0.0, 0.0], [0.0, 0.0]], [[0.3, 0.3], [0.3, 0.3]], [[0.6, 0.6], [0.6, 0.6]]],
],
device=device,
- dtype=dtype
+ 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]]]
+ [[[1.0, 1.0], [1.0, 1.0]], [[0.75, 0.75], [0.75, 0.75]], [[0.5, 0.5], [0.5, 0.5]]],
+ [[[0.1, 0.1], [0.1, 0.1]], [[0.4, 0.4], [0.4, 0.4]], [[0.7, 0.7], [0.7, 0.7]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x3x2x2
factor = torch.tensor([0.25, 0.1], device=device, dtype=dtype)
@@ -413,11 +462,10 @@ 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.0), raise_exception=True)
class TestEqualize:
-
def test_shape_equalize(self, device, dtype):
bs, channels, height, width = 1, 3, 4, 5
@@ -441,11 +489,29 @@ class TestEqualize:
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
+ 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
+ dtype=dtype,
)
expected = self.build_input(bs, channels, height, width, device=device, dtype=dtype, row=row_expected)
@@ -461,11 +527,29 @@ class TestEqualize:
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
+ 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
+ dtype=dtype,
)
expected = self.build_input(bs, channels, height, width, device=device, dtype=dtype, row=row_expected)
@@ -478,7 +562,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
@@ -502,7 +586,6 @@ class TestEqualize:
class TestEqualize3D:
-
def test_shape_equalize3d(self, device, dtype):
bs, channels, depth, height, width = 1, 3, 6, 10, 10
@@ -527,7 +610,7 @@ class TestEqualize3D:
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
+ dtype=dtype,
)
expected = self.build_input(bs, channels, depth, height, width, device, dtype, row=row_expected)
@@ -544,7 +627,7 @@ class TestEqualize3D:
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
+ dtype=dtype,
)
expected = self.build_input(bs, channels, depth, height, width, device, dtype, row=row_expected)
@@ -557,7 +640,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
@@ -591,10 +674,15 @@ class TestSharpness(BaseTester):
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]))
- ]
+ "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):
@@ -622,13 +710,13 @@ class TestSharpness(BaseTester):
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
+ dtype=dtype,
)
# If factor == 1, shall return original
# TODO(jian): add test for this case
# assert_allclose(TestSharpness.f(inputs, 0.), inputs, rtol=1e-4, atol=1e-4)
- assert_allclose(TestSharpness.f(inputs, 1.), inputs, rtol=1e-4, atol=1e-4)
+ assert_allclose(TestSharpness.f(inputs, 1.0), inputs, rtol=1e-4, atol=1e-4)
assert_allclose(TestSharpness.f(inputs, 0.8), expected, rtol=1e-4, atol=1e-4)
def test_value_batch(self, device, dtype):
@@ -643,25 +731,25 @@ class TestSharpness(BaseTester):
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]]]
+ [[[0.6323, 0.3489, 0.4017], [0.0223, 0.2052, 0.2939], [0.5185, 0.6977, 0.8000]]],
],
device=device,
- dtype=dtype
+ 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]]]
+ [[[0.6323, 0.3489, 0.4017], [0.0223, 0.1143, 0.2939], [0.5185, 0.6977, 0.8000]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# If factor == 1, shall return original
tol_val: float = utils._get_precision(device, dtype)
assert_allclose(TestSharpness.f(inputs, 1), inputs, rtol=tol_val, atol=tol_val)
- assert_allclose(TestSharpness.f(inputs, torch.tensor([1., 1.])), inputs, rtol=tol_val, atol=tol_val)
+ assert_allclose(TestSharpness.f(inputs, torch.tensor([1.0, 1.0])), inputs, rtol=tol_val, atol=tol_val)
assert_allclose(TestSharpness.f(inputs, 0.8), expected_08, rtol=tol_val, atol=tol_val)
assert_allclose(TestSharpness.f(inputs, torch.tensor([0.8, 1.3])), expected_08_13, rtol=tol_val, atol=tol_val)
@@ -700,11 +788,16 @@ class TestSolarize(BaseTester):
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]))
- ]
+ "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, 0.4])),
+ ],
)
@pytest.mark.parametrize("channels", [1, 3, 5])
def test_cardinality(self, batch_size, channels, height, width, thresholds, additions, device, dtype):
@@ -716,7 +809,7 @@ class TestSolarize(BaseTester):
img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert TestSolarize.f([1.], 0.)
+ assert TestSolarize.f([1.0], 0.0)
with pytest.raises(TypeError):
assert TestSolarize.f(img, 1)
@@ -738,13 +831,14 @@ class TestSolarize(BaseTester):
[
[
[
- [0.49411765, 0.23529412, 0.08627451], [0.12941176, 0.30588235, 0.36862745],
- [0.48627451, 0.10588235, 0.45490196]
+ [0.49411765, 0.23529412, 0.08627451],
+ [0.12941176, 0.30588235, 0.36862745],
+ [0.48627451, 0.10588235, 0.45490196],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# TODO(jian): precision is very bad compared to PIL
@@ -786,10 +880,16 @@ class TestPosterize(BaseTester):
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]))
- ]
+ "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):
@@ -801,10 +901,10 @@ class TestPosterize(BaseTester):
img = torch.ones(2, 3, 4, 5, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert TestPosterize.f([1.], 0.)
+ assert TestPosterize.f([1.0], 0.0)
with pytest.raises(TypeError):
- assert TestPosterize.f(img, 1.)
+ assert TestPosterize.f(img, 1.0)
# TODO(jian): add better cases
@pytest.mark.skipif(kornia.xla_is_available(), reason="issues with xla device")
@@ -818,7 +918,7 @@ class TestPosterize(BaseTester):
# 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
+ [[[[0.0, 0.50196078, 0.0], [0.0, 0.0, 0.50196078], [0.0, 0.50196078, 0.0]]]], device=device, dtype=dtype
)
assert_allclose(TestPosterize.f(inputs, 1), expected)
diff --git a/test/enhance/test_equalization.py b/test/enhance/test_equalization.py
index b993689ce..8a51b396f 100644
--- a/test/enhance/test_equalization.py
+++ b/test/enhance/test_equalization.py
@@ -8,7 +8,6 @@ from kornia.testing import tensor_to_gradcheck_var, BaseTester
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)
@@ -28,7 +27,7 @@ class TestEqualization(BaseTester):
res = enhance.equalize_clahe(img)
assert res.shape == img.shape
- @pytest.mark.parametrize("clip, grid", [(0., None), (None, (2, 2)), (2., (2, 2))])
+ @pytest.mark.parametrize("clip, grid", [(0.0, None), (None, (2, 2)), (2.0, (2, 2))])
def test_optional_params(self, clip, grid, device, dtype):
C, H, W = 1, 10, 20
img = torch.rand(C, H, W, device=device, dtype=dtype)
@@ -42,10 +41,15 @@ class TestEqualization(BaseTester):
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)
- ]
+ "B, clip, grid, exception_type",
+ [
+ (0, 1.0, (2, 2), ValueError),
+ (1, 1, (2, 2), TypeError),
+ (1, 2.0, 2, TypeError),
+ (1, 2.0, (2, 2, 2), TypeError),
+ (1, 2.0, (2, 2.0), TypeError),
+ (1, 2.0, (2, 0), ValueError),
+ ],
)
def test_exception(self, B, clip, grid, exception_type):
C, H, W = 1, 10, 20
@@ -65,13 +69,13 @@ class TestEqualization(BaseTester):
@pytest.mark.xfail(
raises=RuntimeError,
- reason="Sometimes generates the error: 'Numerical gradient for function expected to be zero'"
+ 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.0, (2, 2)), raise_exception=True)
def test_jit(self, device, dtype):
batch_size, channels, height, width = 1, 2, 10, 20
@@ -93,7 +97,7 @@ class TestEqualization(BaseTester):
def test_he(self, img):
# should be similar to enhance.equalize but slower. Similar because the lut is computed in a different way.
- clip_limit: float = 0.
+ clip_limit: float = 0.0
grid_size: Tuple = (1, 1)
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
@@ -104,20 +108,38 @@ class TestEqualization(BaseTester):
[
[
[
- 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
+ 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
+ device=res.device,
),
atol=1e-04,
- rtol=1e-04
+ rtol=1e-04,
)
def test_ahe(self, img):
- clip_limit: float = 0.
+ clip_limit: float = 0.0
grid_size: Tuple = (8, 8)
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
@@ -128,20 +150,38 @@ class TestEqualization(BaseTester):
[
[
[
- 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
+ 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
+ device=res.device,
),
atol=1e-04,
- rtol=1e-04
+ rtol=1e-04,
)
def test_clahe(self, img):
- clip_limit: float = 2.
+ clip_limit: float = 2.0
grid_size: Tuple = (8, 8)
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
@@ -152,14 +192,32 @@ class TestEqualization(BaseTester):
[
[
[
- 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
+ 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
+ device=res.device,
),
atol=1e-04,
- rtol=1e-04
+ rtol=1e-04,
)
diff --git a/test/enhance/test_histogram.py b/test/enhance/test_histogram.py
index 5beec3879..212a4d06c 100644
--- a/test/enhance/test_histogram.py
+++ b/test/enhance/test_histogram.py
@@ -36,7 +36,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
@@ -47,7 +47,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)
@@ -89,7 +89,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
@@ -101,7 +101,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 bfb703c6f..0a8308557 100644
--- a/test/enhance/test_normalize.py
+++ b/test/enhance/test_normalize.py
@@ -9,7 +9,6 @@ from kornia.testing import BaseTester
class TestNormalize:
-
def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
@@ -95,7 +94,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
@@ -121,7 +120,6 @@ class TestNormalize:
class TestDenormalize:
-
def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
@@ -209,7 +207,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):
@@ -236,7 +234,6 @@ 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
@@ -245,20 +242,20 @@ class TestNormalizeMinMax(BaseTester):
def test_exception(self, device, dtype):
x = torch.ones(1, 1, 3, 4, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert kornia.normalize_min_max(0.)
+ assert kornia.normalize_min_max(0.0)
with pytest.raises(TypeError):
assert kornia.normalize_min_max(x, '', '')
with pytest.raises(TypeError):
- assert kornia.normalize_min_max(x, 2., '')
+ assert kornia.normalize_min_max(x, 2.0, '')
@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.0, 2.0), (2.0, 3.0), (5.0, 20.0), (40.0, 1000.0)])
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)
@@ -266,21 +263,13 @@ class TestNormalizeMinMax(BaseTester):
assert_allclose(out.max().item(), max_val)
def test_values(self, device, dtype):
- x = torch.tensor([[[
- [0., 1., 3.],
- [-1., 4., 3.],
- [9., 5., 2.],
- ]]], device=device, dtype=dtype)
+ x = torch.tensor([[[[0.0, 1.0, 3.0], [-1.0, 4.0, 3.0], [9.0, 5.0, 2.0]]]], 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
+ [[[[-0.8, -0.6, -0.2], [-1.0, 0.0, -0.2], [1.0, 0.2, -0.4]]]], device=device, dtype=dtype
)
- actual = kornia.normalize_min_max(x, min_val=-1., max_val=1.)
+ actual = kornia.normalize_min_max(x, min_val=-1.0, max_val=1.0)
assert_allclose(actual, expected, atol=1e-6, rtol=1e-6)
@pytest.mark.jit
@@ -293,7 +282,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 a1f6c51ab..c479a0fd1 100644
--- a/test/enhance/test_zca.py
+++ b/test/enhance/test_zca.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
class TestZCA:
-
@pytest.mark.parametrize("unbiased", [True, False])
def test_zca_unbiased(self, unbiased, device, dtype):
@@ -44,16 +43,11 @@ class TestZCA:
[0.35353088, -0.35353088],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
elif dim == 0:
expected = torch.tensor(
- [
- [0., 1.2247448],
- [1.2247448, 0.],
- [-1.2247448, 0.],
- [0., -1.2247448],
- ], device=device, dtype=dtype
+ [[0.0, 1.2247448], [1.2247448, 0.0], [-1.2247448, 0.0], [0.0, -1.2247448]], device=device, dtype=dtype
)
zca = kornia.enhance.ZCAWhitening(dim=dim)
@@ -62,7 +56,7 @@ class TestZCA:
tol_val: float = utils._get_precision(device, dtype)
assert_allclose(actual, expected, rtol=tol_val, atol=tol_val)
- @pytest.mark.parametrize("input_shape,eps", [((15, 2, 2, 2), 1e-6), ((10, 4), .1), ((20, 3, 2, 2), 1e-3)])
+ @pytest.mark.parametrize("input_shape,eps", [((15, 2, 2, 2), 1e-6), ((10, 4), 0.1), ((20, 3, 2, 2), 1e-3)])
def test_identity(self, input_shape, eps, device, dtype):
"""
@@ -101,9 +95,9 @@ 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):
@@ -115,7 +109,7 @@ 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):
@@ -126,7 +120,7 @@ class TestZCA:
zca.fit(data)
- assert gradcheck(zca, (data, ), raise_exception=True)
+ assert gradcheck(zca, (data,), raise_exception=True)
def test_not_fitted(self, device, dtype):
diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.py
index ff0ed959d..3075a2d88 100644
--- a/test/feature/test_affine_shape_estimator.py
+++ b/test/feature/test_affine_shape_estimator.py
@@ -7,7 +7,6 @@ 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,7 +36,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):
@@ -49,7 +48,6 @@ 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)
@@ -72,23 +70,24 @@ class TestLAFAffineShapeEstimator:
aff = LAFAffineShapeEstimator(32).to(device)
inp = torch.zeros(1, 1, 32, 32, device=device)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20., 0., 16.], [0., 20., 16.]]]], device=device)
+ laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[36.643, 0., 16.], [0., 10.916, 16.]]]], device=device)
+ expected = torch.tensor([[[[36.643, 0.0, 16.0], [0.0, 10.916, 16.0]]]], device=device)
assert_allclose(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 40, 40
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- laf = torch.tensor([[[[5., 0., 26.], [0., 5., 26.]]]], device=device)
+ laf = torch.tensor([[[[5.0, 0.0, 26.0], [0.0, 5.0, 26.0]]]], device=device)
laf = utils.tensor_to_gradcheck_var(laf) # to var
assert gradcheck(
- LAFAffineShapeEstimator(11).to(device), (laf, patches),
+ LAFAffineShapeEstimator(11).to(device),
+ (laf, patches),
raise_exception=True,
rtol=1e-3,
atol=1e-3,
- nondet_tol=1e-4
+ nondet_tol=1e-4,
)
@pytest.mark.jit
@@ -97,14 +96,13 @@ class TestLAFAffineShapeEstimator:
B, C, H, W = 1, 1, 13, 13
inp = torch.zeros(B, C, H, W, device=device)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20., 0., 16.], [0., 20., 16.]]]], device=device)
+ laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device)
tfeat = LAFAffineShapeEstimator(W).to(inp.device, inp.dtype).eval()
tfeat_jit = torch.jit.script(LAFAffineShapeEstimator(W).to(inp.device, inp.dtype).eval())
assert_allclose(tfeat_jit(laf, inp), tfeat(laf, inp))
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)
@@ -134,9 +132,9 @@ class TestLAFAffNetShapeEstimator:
aff = LAFAffNetShapeEstimator(True).to(device).eval()
inp = torch.zeros(1, 1, 32, 32, device=device)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20., 0., 16.], [0., 20., 16.]]]], device=device)
+ laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[40.8758, 0., 16.], [-0.3824, 9.7857, 16.]]]], device=device)
+ expected = torch.tensor([[[[40.8758, 0.0, 16.0], [-0.3824, 9.7857, 16.0]]]], device=device)
assert_allclose(new_laf, expected, atol=1e-4, rtol=1e-4)
@pytest.mark.skip("jacobian not well computed")
@@ -144,14 +142,15 @@ class TestLAFAffNetShapeEstimator:
batch_size, channels, height, width = 1, 1, 35, 35
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- laf = torch.tensor([[[[8., 0., 16.], [0., 8., 16.]]]], device=device)
+ laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device)
laf = utils.tensor_to_gradcheck_var(laf) # to var
assert gradcheck(
- LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype), (laf, patches),
+ LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype),
+ (laf, patches),
raise_exception=True,
rtol=1e-3,
atol=1e-3,
- nondet_tol=1e-4
+ nondet_tol=1e-4,
)
@pytest.mark.jit
@@ -159,7 +158,7 @@ class TestLAFAffNetShapeEstimator:
def test_jit(self, device, dtype):
B, C, H, W = 1, 1, 32, 32
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
- laf = torch.tensor([[[[8., 0., 16.], [0., 8., 16.]]]], device=device)
+ laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device)
laf_estimator = LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype).eval()
laf_estimator_jit = torch.jit.script(LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype).eval())
assert_allclose(laf_estimator(laf, patches), laf_estimator_jit(laf, patches))
diff --git a/test/feature/test_hardnet.py b/test/feature/test_hardnet.py
index c7d1095f9..bb0fd4780 100644
--- a/test/feature/test_hardnet.py
+++ b/test/feature/test_hardnet.py
@@ -8,7 +8,6 @@ from kornia.feature import HardNet, HardNet8
class TestHardNet:
-
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
hardnet = HardNet().to(device)
@@ -27,13 +26,7 @@ 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):
@@ -45,7 +38,6 @@ class TestHardNet:
class TestHardNet8:
-
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
hardnet = HardNet8().to(device)
@@ -64,13 +56,7 @@ 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 fa1d5465f..597d94d06 100644
--- a/test/feature/test_laf.py
+++ b/test/feature/test_laf.py
@@ -9,15 +9,14 @@ import kornia.testing as utils # test utils
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)
assert rotmat.shape == (1, 3, 4, 4, 2, 2)
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)
+ ang_deg = torch.tensor([0, 90.0], device=device)
+ expected = torch.tensor([[[1.0, 0.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)
@@ -25,7 +24,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")
@@ -38,14 +37,13 @@ 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)
assert rotmat.shape == (1, 3, 1, 1)
def test_scale(self, device):
- inp = torch.tensor([[5., 1, 0], [1, 1, 0]], device=device).float()
+ inp = torch.tensor([[5.0, 1, 0], [1, 1, 0]], device=device).float()
inp = inp.view(1, 1, 2, 3)
expected = torch.tensor([[[[2]]]], device=device).float()
rotmat = kornia.feature.get_laf_scale(inp)
@@ -55,7 +53,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):
@@ -67,14 +65,13 @@ 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)
assert xy.shape == (1, 3, 2)
def test_center(self, device):
- inp = torch.tensor([[5., 1, 2], [1, 1, 3]], device=device).float()
+ inp = torch.tensor([[5.0, 1, 2], [1, 1, 3]], device=device).float()
inp = inp.view(1, 1, 2, 3)
expected = torch.tensor([[[2, 3]]], device=device).float()
xy = kornia.feature.get_laf_center(inp)
@@ -84,7 +81,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):
@@ -96,7 +93,6 @@ 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)
@@ -105,7 +101,7 @@ class TestGetLAFOri:
def test_ori(self, device):
inp = torch.tensor([[1, 1, 2], [1, 1, 3]], device=device).float()
inp = inp.view(1, 1, 2, 3)
- expected = torch.tensor([[[45.]]], device=device).float()
+ expected = torch.tensor([[[45.0]]], device=device).float()
angle = kornia.feature.get_laf_orientation(inp)
assert_allclose(angle, expected)
@@ -113,7 +109,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")
@@ -126,10 +122,9 @@ class TestGetLAFOri:
class TestScaleLAF:
-
def test_shape_float(self, device):
inp = torch.ones(7, 3, 2, 3, device=device).float()
- scale = 23.
+ scale = 23.0
assert kornia.feature.scale_laf(inp, scale).shape == inp.shape
def test_shape_tensor(self, device):
@@ -138,11 +133,11 @@ class TestScaleLAF:
assert kornia.feature.scale_laf(inp, scale).shape == inp.shape
def test_scale(self, device):
- inp = torch.tensor([[5., 1, 0.8], [1, 1, -4.]], device=device).float()
+ inp = torch.tensor([[5.0, 1, 0.8], [1, 1, -4.0]], device=device).float()
inp = inp.view(1, 1, 2, 3)
- scale = torch.tensor([[[[2.]]]], device=device).float()
+ scale = torch.tensor([[[[2.0]]]], device=device).float()
out = kornia.feature.scale_laf(inp, scale)
- expected = torch.tensor([[[[10., 2, 0.8], [2, 2, -4.]]]], device=device).float()
+ expected = torch.tensor([[[[10.0, 2, 0.8], [2, 2, -4.0]]]], device=device).float()
assert_allclose(out, expected)
def test_gradcheck(self, device):
@@ -165,18 +160,17 @@ 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()
assert kornia.feature.set_laf_orientation(inp, ori).shape == inp.shape
def test_ori(self, device):
- inp = torch.tensor([[0., 5., 0.8], [-5., 0, -4.]], device=device).float()
+ inp = torch.tensor([[0.0, 5.0, 0.8], [-5.0, 0, -4.0]], device=device).float()
inp = inp.view(1, 1, 2, 3)
ori = torch.zeros(1, 1, 1, 1, device=device).float()
out = kornia.feature.set_laf_orientation(inp, ori)
- expected = torch.tensor([[[[5., 0., 0.8], [0., 5., -4.]]]], device=device).float()
+ expected = torch.tensor([[[[5.0, 0.0, 0.8], [0.0, 5.0, -4.0]]]], device=device).float()
assert_allclose(out, expected)
def test_gradcheck(self, device):
@@ -199,7 +193,6 @@ class TestSetLAFOri:
class TestMakeUpright:
-
def test_shape(self, device):
inp = torch.ones(5, 3, 2, 3, device=device)
rotmat = kornia.feature.make_upright(inp)
@@ -229,7 +222,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")
@@ -242,7 +235,6 @@ class TestMakeUpright:
class TestELL2LAF:
-
def test_shape(self, device):
inp = torch.ones(5, 3, 5, device=device)
inp[:, :, 3] = 0
@@ -252,7 +244,7 @@ class TestELL2LAF:
def test_conversion(self, device):
inp = torch.tensor([[10, -20, 0.01, 0, 0.01]], device=device).float()
inp = inp.view(1, 1, 5)
- expected = torch.tensor([[10, 0, 10.], [0, 10, -20]], device=device).float()
+ expected = torch.tensor([[10, 0, 10.0], [0, 10, -20]], device=device).float()
expected = expected.view(1, 1, 2, 3)
laf = kornia.feature.ellipse_to_laf(inp)
assert_allclose(laf, expected)
@@ -261,24 +253,23 @@ class TestELL2LAF:
batch_size, channels, height = 1, 2, 5
img = torch.rand(batch_size, channels, height, device=device).abs()
img[:, :, 2] = img[:, :, 3].abs() + 0.3
- img[:, :, 4] += 1.
+ img[:, :, 4] += 1.0
# 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):
batch_size, channels, height = 1, 2, 5
img = torch.rand(batch_size, channels, height, device=device).abs()
img[:, :, 2] = img[:, :, 3].abs() + 0.3
- img[:, :, 4] += 1.
+ img[:, :, 4] += 1.0
model = kornia.feature.ellipse_to_laf
model_jit = torch.jit.script(kornia.feature.ellipse_to_laf)
assert_allclose(model(img), model_jit(img))
class TestNormalizeLAF:
-
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3)
img = torch.rand(5, 3, 10, 10)
@@ -300,10 +291,7 @@ 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):
@@ -317,7 +305,6 @@ class TestNormalizeLAF:
class TestLAF2pts:
-
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)
n_pts = 13
@@ -347,7 +334,6 @@ 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)
@@ -369,10 +355,7 @@ 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):
@@ -386,12 +369,12 @@ 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)
PS = 3
from kornia.feature.laf import generate_patch_grid_from_normalized_LAF
+
grid = generate_patch_grid_from_normalized_LAF(img, laf, PS)
assert grid.shape == (15, 3, 3, 2)
@@ -400,17 +383,13 @@ class TestGenPatchGrid:
img = torch.rand(5, 3, 10, 10, device=device)
PS = 3
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)
@@ -431,7 +410,6 @@ class TestExtractPatchesSimple:
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)
@@ -452,7 +430,6 @@ class TestExtractPatchesPyr:
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)
@@ -476,7 +453,6 @@ class TestLAFIsTouchingBoundary:
class TestGetCreateLAF:
-
def test_shape(self, device):
xy = torch.ones(1, 3, 2, device=device)
ori = torch.ones(1, 3, 1, device=device)
@@ -510,11 +486,7 @@ 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
@@ -529,7 +501,6 @@ 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)
@@ -550,7 +521,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):
@@ -562,7 +533,6 @@ 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)
@@ -590,7 +560,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 2501e0c69..fc3984838 100644
--- a/test/feature/test_local_features_orientation.py
+++ b/test/feature/test_local_features_orientation.py
@@ -8,7 +8,6 @@ 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)
@@ -43,7 +42,6 @@ class TestPassLAF:
class TestPatchDominantGradientOrientation:
-
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
ori = PatchDominantGradientOrientation(32).to(device)
@@ -65,7 +63,7 @@ class TestPatchDominantGradientOrientation:
inp = torch.zeros(1, 1, 19, 19, device=device)
inp[:, :, :10, :] = 1
ang = ori(inp)
- expected = torch.tensor([90.], device=device)
+ expected = torch.tensor([90.0], device=device)
assert_allclose(kornia.rad2deg(ang), expected)
def test_gradcheck(self, device):
@@ -73,7 +71,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,7 +84,6 @@ 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()
@@ -123,7 +120,7 @@ class TestOriNet:
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
ori = OriNet().to(device=device, dtype=patches.dtype)
- assert gradcheck(ori, (patches, ), raise_exception=True)
+ assert gradcheck(ori, (patches,), raise_exception=True)
@pytest.mark.jit
def test_jit(self, device, dtype):
@@ -135,7 +132,6 @@ 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)
@@ -158,9 +154,9 @@ class TestLAFOrienter:
ori = LAFOrienter(32).to(device)
inp = torch.zeros(1, 1, 19, 19, device=device)
inp[:, :, :, :10] = 1
- laf = torch.tensor([[[[0, 5., 8.], [5.0, 0., 8.]]]], device=device)
+ laf = torch.tensor([[[[0, 5.0, 8.0], [5.0, 0.0, 8.0]]]], device=device)
new_laf = ori(laf, inp)
- expected = torch.tensor([[[[0., 5., 8.], [-5.0, 0, 8.]]]], device=device)
+ expected = torch.tensor([[[[0.0, 5.0, 8.0], [-5.0, 0, 8.0]]]], device=device)
assert_allclose(new_laf, expected)
def test_gradcheck(self, device):
diff --git a/test/feature/test_matching.py b/test/feature/test_matching.py
index 0544360d6..c70dcbc31 100644
--- a/test/feature/test_matching.py
+++ b/test/feature/test_matching.py
@@ -7,11 +7,7 @@ from kornia.feature.matching import *
class TestMatchNN:
-
- @pytest.mark.parametrize(
- "num_desc1, num_desc2, dim",
- [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
- )
+ @pytest.mark.parametrize("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)
desc2 = torch.rand(num_desc2, dim, device=device)
@@ -21,8 +17,8 @@ class TestMatchNN:
assert dists.shape == (num_desc1, 1)
def test_matching(self, device):
- desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
- desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+ desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)
dists, idxs = match_nn(desc1, desc2)
expected_dists = torch.tensor([0, 0, 0.5, 0, 0], device=device).view(-1, 1)
@@ -39,11 +35,7 @@ class TestMatchNN:
class TestMatchMNN:
-
- @pytest.mark.parametrize(
- "num_desc1, num_desc2, dim",
- [(1, 4, 4), (2, 5, 128), (6, 2, 32)],
- )
+ @pytest.mark.parametrize("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)
desc2 = torch.rand(num_desc2, dim, device=device)
@@ -55,8 +47,8 @@ class TestMatchMNN:
assert dists.shape[0] <= num_desc1
def test_matching(self, device):
- desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
- desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+ desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)
dists, idxs = match_mnn(desc1, desc2)
expected_dists = torch.tensor([0, 0, 0.5, 0, 0], device=device).view(-1, 1)
@@ -73,11 +65,7 @@ class TestMatchMNN:
class TestMatchSNN:
-
- @pytest.mark.parametrize(
- "num_desc1, num_desc2, dim",
- [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
- )
+ @pytest.mark.parametrize("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)
desc2 = torch.rand(num_desc2, dim, device=device)
@@ -89,8 +77,8 @@ class TestMatchSNN:
assert dists.shape[0] <= num_desc1
def test_matching1(self, device):
- desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
- desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+ desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)
dists, idxs = match_snn(desc1, desc2, 0.8)
expected_dists = torch.tensor([0, 0, 0.35355339059327373, 0, 0], device=device).view(-1, 1)
@@ -99,11 +87,11 @@ class TestMatchSNN:
assert_allclose(idxs, expected_idx)
def test_matching2(self, device):
- desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
- desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+ desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)
dists, idxs = match_snn(desc1, desc2, 0.1)
- expected_dists = torch.tensor([0., 0, 0, 0], device=device).view(-1, 1)
+ expected_dists = torch.tensor([0.0, 0, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
assert_allclose(dists, expected_dists)
assert_allclose(idxs, expected_idx)
@@ -117,11 +105,7 @@ class TestMatchSNN:
class TestMatchSMNN:
-
- @pytest.mark.parametrize(
- "num_desc1, num_desc2, dim",
- [(2, 4, 4), (2, 5, 128), (6, 2, 32)],
- )
+ @pytest.mark.parametrize("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)
desc2 = torch.rand(num_desc2, dim, device=device)
@@ -134,8 +118,8 @@ class TestMatchSMNN:
assert dists.shape[0] <= num_desc2
def test_matching1(self, device):
- desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
- desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+ desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)
dists, idxs = match_smnn(desc1, desc2, 0.8)
expected_dists = torch.tensor([0, 0, 0.5423, 0, 0], device=device).view(-1, 1)
@@ -144,11 +128,11 @@ class TestMatchSMNN:
assert_allclose(idxs, expected_idx)
def test_matching2(self, device):
- desc1 = torch.tensor([[0, 0.], [1, 1], [2, 2], [3, 3.], [5, 5.]], device=device)
- desc2 = torch.tensor([[5, 5.], [3, 3.], [2.3, 2.4], [1, 1], [0, 0.]], device=device)
+ desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
+ desc2 = torch.tensor([[5, 5.0], [3, 3.0], [2.3, 2.4], [1, 1], [0, 0.0]], device=device)
dists, idxs = match_smnn(desc1, desc2, 0.1)
- expected_dists = torch.tensor([0., 0, 0, 0], device=device).view(-1, 1)
+ expected_dists = torch.tensor([0.0, 0, 0, 0], device=device).view(-1, 1)
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
assert_allclose(dists, expected_dists)
assert_allclose(idxs, expected_idx)
diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.py
index 5fc94e6a5..766a3f387 100644
--- a/test/feature/test_mkd.py
+++ b/test/feature/test_mkd.py
@@ -23,7 +23,6 @@ def test_get_kron_order(d1, d2):
class TestMKDGradients:
-
@pytest.mark.parametrize("ps", [5, 13, 25])
def test_shape(self, ps, device):
inp = torch.ones(1, 1, ps, ps).to(device)
@@ -47,7 +46,7 @@ class TestMKDGradients:
patch[0, 0, :, 3:] = 0
gradients = MKDGradients().to(device)
out = gradients(patch)
- expected_mags_1 = torch.Tensor([0, 0, 1., 1., 0, 0]).to(device)
+ expected_mags_1 = torch.Tensor([0, 0, 1.0, 1.0, 0, 0]).to(device)
expected_mags = expected_mags_1.unsqueeze(0).repeat(6, 1)
expected_oris_1 = torch.Tensor([-pi, -pi, 0, 0, -pi, -pi]).to(device)
expected_oris = expected_oris_1.unsqueeze(0).repeat(6, 1)
@@ -76,7 +75,6 @@ class TestMKDGradients:
class TestVonMisesKernel:
-
@pytest.mark.parametrize("ps", [5, 13, 25])
def test_shape(self, ps, device):
inp = torch.ones(1, 1, ps, ps).to(device)
@@ -134,8 +132,9 @@ class TestVonMisesKernel:
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 = (
+ 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
@@ -143,7 +142,6 @@ class TestVonMisesKernel:
class TestEmbedGradients:
-
@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)
@@ -168,7 +166,7 @@ class TestEmbedGradients:
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.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
@@ -204,7 +202,6 @@ 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)]
)
@@ -262,8 +259,9 @@ class TestExplicitSpacialEncoding:
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 = (
+ 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
@@ -271,12 +269,16 @@ class TestExplicitSpacialEncoding:
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)
- ]
+ "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
@@ -339,10 +341,15 @@ class TestMKDDescriptor:
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')
- ]
+ "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)
@@ -436,8 +443,9 @@ class TestSimpleKD:
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 = (
+ 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
diff --git a/test/feature/test_nms.py b/test/feature/test_nms.py
index 2f9a79b01..85e55a305 100644
--- a/test/feature/test_nms.py
+++ b/test/feature/test_nms.py
@@ -7,7 +7,6 @@ import kornia.testing as utils # test utils
class TestNMS2d:
-
def test_shape(self, device):
inp = torch.ones(1, 3, 4, 4, device=device)
nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)
@@ -23,28 +22,28 @@ class TestNMS2d:
[
[
[
- [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.],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.1, 1.0, 0.0, 1.0, 1.0, 0.0],
+ [0.0, 0.7, 1.1, 0.0, 1.0, 2.0, 0.0],
+ [0.0, 0.8, 1.0, 0.0, 1.0, 1.0, 0.0],
]
]
],
- device=device
+ 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.],
+ [0.0, 0.0, 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, 2.0, 0.0],
+ [0.0, 0, 0, 0.0, 0.0, 0.0, 0.0],
]
]
],
- device=device
+ device=device,
).float()
nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)
scores = nms(inp)
@@ -59,7 +58,6 @@ class TestNMS2d:
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)
@@ -76,16 +74,25 @@ class TestNMS3d:
[
[
[
- [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.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., 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, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 2.0, 1.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., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]
+ [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, 0.0, 0.0, 0.0, 0.0],
],
]
]
@@ -97,17 +104,26 @@ class TestNMS3d:
[
[
[
- [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 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, 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., 0., 0., 0.], [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
]
]
]
diff --git a/test/feature/test_responces_local_features.py b/test/feature/test_responces_local_features.py
index 6cf75d2f1..b02bbe662 100644
--- a/test/feature/test_responces_local_features.py
+++ b/test/feature/test_responces_local_features.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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)
@@ -24,17 +23,17 @@ class TestCornerHarris:
[
[
[
- [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, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
- device=device
+ device=device,
).float()
expected = torch.tensor(
@@ -47,11 +46,11 @@ class TestCornerHarris:
[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]
+ [0.0042, 0.0054, 0.0035, 0.0006, 0.0035, 0.0054, 0.0042],
]
]
],
- device=device
+ device=device,
).float()
harris = kornia.feature.CornerHarris(k=0.04).to(device)
scores = harris(inp)
@@ -61,49 +60,52 @@ class TestCornerHarris:
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, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.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., 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.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.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
+ device=device,
).repeat(2, 1, 1, 1)
- expected = torch.tensor(
- [
+ 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.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],
+ ],
],
- [
- [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.
+ device=device,
+ ).repeat(2, 1, 1, 1)
+ / 10.0
+ )
scores = kornia.feature.harris_response(inp, k=0.04)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
@@ -116,7 +118,6 @@ class TestCornerHarris:
@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)
@@ -129,7 +130,6 @@ 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)
@@ -145,17 +145,17 @@ class TestCornerGFTT:
[
[
[
- [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, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
- device=device
+ device=device,
).float()
expected = torch.tensor(
@@ -168,11 +168,11 @@ class TestCornerGFTT:
[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.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379],
]
]
],
- device=device
+ device=device,
).float()
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
@@ -182,25 +182,25 @@ class TestCornerGFTT:
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, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.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., 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.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.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
+ device=device,
).repeat(2, 1, 1, 1)
expected = torch.tensor(
[
@@ -211,7 +211,7 @@ class TestCornerGFTT:
[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.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],
@@ -220,10 +220,10 @@ class TestCornerGFTT:
[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]
- ]
+ [0.0112, 0.0119, 0.0084, 0.0083, 0.0114, 0.0084, 0.0046],
+ ],
],
- device=device
+ device=device,
).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
@@ -237,7 +237,6 @@ class TestCornerGFTT:
@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)
@@ -249,7 +248,6 @@ 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)
@@ -264,25 +262,25 @@ class TestBlobHessian:
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, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.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, 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.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.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
+ device=device,
).repeat(2, 1, 1, 1)
expected = torch.tensor(
[
@@ -293,7 +291,7 @@ class TestBlobHessian:
[-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.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],
@@ -302,10 +300,10 @@ class TestBlobHessian:
[-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]
- ]
+ [0.0000, -0.0005, -0.0057, -0.0080, -0.0080, -0.0057, -0.0005],
+ ],
],
- device=device
+ device=device,
).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.BlobHessian().to(device)
scores = shi_tomasi(inp)
@@ -319,7 +317,6 @@ class TestBlobHessian:
@pytest.mark.jit
def test_jit(self, device):
-
@torch.jit.script
def op_script(input):
return kornia.feature.hessian_response(input)
diff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.py
index f5b57036a..ea17f02f0 100644
--- a/test/feature/test_scale_space_detector.py
+++ b/test/feature/test_scale_space_detector.py
@@ -8,7 +8,6 @@ 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
diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.py
index 58339fc42..9af3f5e27 100644
--- a/test/feature/test_siftdesc.py
+++ b/test/feature/test_siftdesc.py
@@ -19,7 +19,6 @@ def test_get_sift_bin_ksize_stride_pad(ps, n_bins, ksize, stride, pad):
class TestSIFTDescriptor:
-
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
sift = SIFTDescriptor(32).to(device)
@@ -36,7 +35,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)
@@ -47,7 +46,7 @@ class TestSIFTDescriptor:
patch[0, 0, :, 3:] = 0
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)
+ expected = torch.tensor([[0, 0, 1.0, 0]], device=device)
assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
@pytest.mark.xfail(reason='May raise checkIfNumericalAnalyticAreClose.')
diff --git a/test/feature/test_sosnet.py b/test/feature/test_sosnet.py
index 72ce92d6a..473dbd48b 100644
--- a/test/feature/test_sosnet.py
+++ b/test/feature/test_sosnet.py
@@ -8,7 +8,6 @@ from kornia.feature import SOSNet
class TestSOSNet:
-
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
sosnet = SOSNet(pretrained=False).to(device)
@@ -27,13 +26,7 @@ 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 ead4b50c8..97769a6f6 100644
--- a/test/feature/test_tfeat.py
+++ b/test/feature/test_tfeat.py
@@ -8,7 +8,6 @@ from kornia.feature import TFeat
class TestTFeat:
-
def test_shape(self, device):
inp = torch.ones(1, 1, 32, 32, device=device)
tfeat = TFeat().to(device)
@@ -34,13 +33,7 @@ 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 c1386998f..e369776af 100644
--- a/test/filters/test_blur.py
+++ b/test/filters/test_blur.py
@@ -7,7 +7,6 @@ import kornia.testing as utils # test utils
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))
@@ -23,20 +22,23 @@ class TestBoxBlur:
[
[
[
- [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.]
+ [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],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
kernel_size = (3, 3)
actual = kornia.filters.box_blur(inp, kernel_size)
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_allclose(actual.sum(), torch.tensor(35.).to(actual), rtol=tol_val, atol=tol_val)
+ assert_allclose(actual.sum(), torch.tensor(35.0).to(actual), rtol=tol_val, atol=tol_val)
# TODO(dmytro): normalized does not make any effect
def test_kernel_3x3_nonormalize(self, device, dtype):
@@ -44,33 +46,39 @@ class TestBoxBlur:
[
[
[
- [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.]
+ [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],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
kernel_size = (3, 3)
actual = kornia.filters.box_blur(inp, kernel_size, normalized=False)
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_allclose(actual.sum(), torch.tensor(35.).to(actual), rtol=tol_val, atol=tol_val)
+ assert_allclose(actual.sum(), torch.tensor(35.0).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.]
+ [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],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
kernel_size = (5, 5)
@@ -87,13 +95,16 @@ class TestBoxBlur:
[
[
[
- [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.]
+ [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],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
).repeat(batch_size, 1, 1, 1)
kernel_size = (5, 5)
@@ -117,10 +128,7 @@ 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 e4e5090cf..fdddb422b 100644
--- a/test/filters/test_blur_pool.py
+++ b/test/filters/test_blur_pool.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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)
@@ -34,10 +33,7 @@ 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,7 +57,6 @@ 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)
@@ -89,10 +84,7 @@ 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 c2a78c27e..f21e84c1b 100644
--- a/test/filters/test_filters.py
+++ b/test/filters/test_filters.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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)
@@ -27,31 +26,31 @@ class TestFilter2D:
[
[
[
- [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, 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],
]
]
],
device=device,
- dtype=dtype
+ 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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
actual = kornia.filter2D(input, kernel)
@@ -63,32 +62,32 @@ class TestFilter2D:
[
[
[
- [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, 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],
]
]
],
device=device,
- dtype=dtype
+ 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.],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
).expand(2, 2, -1, -1)
actual = kornia.filter2D(input, kernel)
@@ -100,33 +99,33 @@ class TestFilter2D:
[
[
[
- [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, 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],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
).expand(2, 2, -1, -1)
- nv: float = 5. / 9 # normalization value
+ nv: float = 5.0 / 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.],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
).expand(2, 2, -1, -1)
actual = kornia.filter2D(input, kernel, normalized=True)
@@ -140,32 +139,32 @@ class TestFilter2D:
[
[
[
- [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, 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],
]
]
],
device=device,
- dtype=dtype
+ 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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 0.0, 0.0],
+ [0.0, 5.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],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
actual = kornia.filter2D(input, kernel)
@@ -201,7 +200,6 @@ 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)
@@ -221,31 +219,31 @@ class TestFilter3D:
[
[
[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 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, 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.],
- [0., 0., 0., 0., 0.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 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
+ dtype=dtype,
)
expected = torch.tensor(
@@ -253,31 +251,31 @@ class TestFilter3D:
[
[
[
- [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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
actual = kornia.filter3D(input, kernel)
@@ -290,31 +288,31 @@ class TestFilter3D:
[
[
[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 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, 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.],
- [0., 0., 0., 0., 0.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 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
+ dtype=dtype,
)
input = input.expand(2, 2, -1, -1, -1)
@@ -323,31 +321,31 @@ class TestFilter3D:
[
[
[
- [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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 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, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = expected.expand(2, 2, -1, -1, -1)
@@ -361,65 +359,65 @@ class TestFilter3D:
[
[
[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 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, 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.],
- [0., 0., 0., 0., 0.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 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
+ dtype=dtype,
)
input = input.expand(2, 2, -1, -1, -1)
- nv = 5. / 27 # normalization value
+ nv = 5.0 / 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, 0.0, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, 0.0, 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, 0.0, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, 0.0, 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, 0.0, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = expected.expand(2, 2, -1, -1, -1)
@@ -435,31 +433,31 @@ class TestFilter3D:
[
[
[
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 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, 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.],
- [0., 0., 0., 0., 0.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 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
+ dtype=dtype,
)
expected = torch.tensor(
@@ -467,31 +465,31 @@ class TestFilter3D:
[
[
[
- [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, 5.0, 5.0, 0.0, 0.0],
+ [0.0, 5.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., 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, 5.0, 5.0, 0.0, 0.0],
+ [0.0, 5.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.],
- [0., 0., 0., 0., 0.],
- ]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 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
+ dtype=dtype,
)
actual = kornia.filter3D(input, kernel)
diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.py
index 1b4409241..a96a02dc3 100644
--- a/test/filters/test_gaussian.py
+++ b/test/filters/test_gaussian.py
@@ -11,7 +11,7 @@ import kornia.testing as utils # test utils
@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)
@@ -19,7 +19,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)
@@ -27,7 +27,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)
@@ -41,7 +41,6 @@ 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)
@@ -69,11 +68,7 @@ class TestGaussianBlur2d:
# evaluate function gradient
input = torch.rand(batch_shape, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- kornia.gaussian_blur2d,
- (input, kernel_size, sigma, "replicate"),
- raise_exception=True,
- )
+ assert gradcheck(kornia.gaussian_blur2d, (input, kernel_size, sigma, "replicate"), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filters.gaussian_blur2d
diff --git a/test/filters/test_laplacian.py b/test/filters/test_laplacian.py
index ea737eba9..c6d57f5c3 100644
--- a/test/filters/test_laplacian.py
+++ b/test/filters/test_laplacian.py
@@ -10,7 +10,7 @@ import kornia.testing as utils # test utils
@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)
@@ -34,7 +34,6 @@ 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
diff --git a/test/filters/test_median.py b/test/filters/test_median.py
index c66c081f0..2869e2ac1 100644
--- a/test/filters/test_median.py
+++ b/test/filters/test_median.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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)
@@ -21,22 +20,28 @@ class TestMedianBlur:
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.]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 3.0, 7.0, 5.0, 0.0],
+ [0.0, 3.0, 1.0, 1.0, 0.0],
+ [0.0, 6.0, 9.0, 2.0, 0.0],
+ [0.0, 0.0, 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.]
- ]
+ [36.0, 7.0, 25.0, 0.0, 0.0],
+ [3.0, 14.0, 1.0, 0.0, 0.0],
+ [65.0, 59.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],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
).repeat(2, 1, 1, 1)
kernel_size = (3, 3)
actual = kornia.filters.median_blur(inp, kernel_size)
- assert_allclose(actual[0, 0, 2, 2], torch.tensor(3.).to(actual))
- assert_allclose(actual[0, 1, 1, 1], torch.tensor(14.).to(actual))
+ assert_allclose(actual[0, 0, 2, 2], torch.tensor(3.0).to(actual))
+ assert_allclose(actual[0, 1, 1, 1], torch.tensor(14.0).to(actual))
def test_noncontiguous(self, device, dtype):
batch_size = 3
@@ -52,10 +57,7 @@ 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 b5f611084..a1bcd7e04 100644
--- a/test/filters/test_motion.py
+++ b/test/filters/test_motion.py
@@ -9,8 +9,8 @@ import kornia.testing as utils # test utils
@pytest.mark.parametrize("batch_size", [0, 1, 5])
@pytest.mark.parametrize("ksize", [3, 11])
[email protected]("angle", [0., 360.])
[email protected]("direction", [-1., 1.])
[email protected]("angle", [0.0, 360.0])
[email protected]("direction", [-1.0, 1.0])
def test_get_motion_kernel2d(batch_size, ksize, angle, direction):
if batch_size != 0:
angle = torch.tensor([angle] * batch_size)
@@ -23,11 +23,10 @@ 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
- angle = 200.
+ angle = 200.0
direction = 0.3
input = torch.rand(batch_shape, device=device, dtype=dtype)
@@ -39,7 +38,7 @@ class TestMotionBlur:
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
kernel_size = 3
- angle = 200.
+ angle = 200.0
direction = 0.3
actual = kornia.filters.motion_blur(inp, kernel_size, angle, direction)
expected = actual
@@ -48,23 +47,19 @@ class TestMotionBlur:
def test_gradcheck(self, device, dtype):
batch_shape = (1, 3, 4, 5)
ksize = 9
- angle = 34.
+ angle = 34.0
direction = -0.2
input = torch.rand(batch_shape, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input)
- assert gradcheck(
- kornia.motion_blur,
- (input, ksize, angle, direction, "replicate"),
- raise_exception=True,
- )
+ assert gradcheck(kornia.motion_blur, (input, ksize, angle, direction, "replicate"), raise_exception=True)
@pytest.mark.skip("angle can be Union")
def test_jit(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
ksize = 5
- angle = 65.
- direction = .1
+ angle = 65.0
+ direction = 0.1
op = kornia.filters.motion_blur
op_script = torch.jit.script(op)
actual = op_script(img, ksize, angle, direction)
diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.py
index 0c3fc916c..24a779778 100644
--- a/test/filters/test_sobel.py
+++ b/test/filters/test_sobel.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
class TestSpatialGradient:
-
def test_shape(self, device, dtype):
inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
sobel = kornia.filters.SpatialGradient()
@@ -24,16 +23,16 @@ class TestSpatialGradient:
[
[
[
- [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, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = torch.tensor(
@@ -41,24 +40,24 @@ class TestSpatialGradient:
[
[
[
- [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.0, 1.0, 0.0, -1.0, 0.0],
+ [1.0, 3.0, 0.0, -3.0, -1.0],
+ [2.0, 4.0, 0.0, -4.0, -2.0],
+ [1.0, 3.0, 0.0, -3.0, -1.0],
+ [0.0, 1.0, 0.0, -1.0, 0.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.],
- ]
+ [0.0, 1.0, 2.0, 1.0, 0.0],
+ [1.0, 3.0, 4.0, 3.0, 1.0],
+ [0.0, 0.0, 0.0, 0.0, 0],
+ [-1.0, -3.0, -4.0, -3.0, -1],
+ [0.0, -1.0, -2.0, -1.0, 0.0],
+ ],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
edges = kornia.filters.spatial_gradient(inp, normalized=False)
@@ -69,42 +68,45 @@ class TestSpatialGradient:
[
[
[
- [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, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- expected = torch.tensor(
- [
+ 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.],
+ [
+ [0.0, 1.0, 0.0, -1.0, 0.0],
+ [1.0, 3.0, 0.0, -3.0, -1.0],
+ [2.0, 4.0, 0.0, -4.0, -2.0],
+ [1.0, 3.0, 0.0, -3.0, -1.0],
+ [0.0, 1.0, 0.0, -1.0, 0.0],
+ ],
+ [
+ [0.0, 1.0, 2.0, 1.0, 0.0],
+ [1.0, 3.0, 4.0, 3.0, 1.0],
+ [0.0, 0.0, 0.0, 0.0, 0],
+ [-1.0, -3.0, -4.0, -3.0, -1],
+ [0.0, -1.0, -2.0, -1.0, 0.0],
+ ],
]
]
- ]
- ],
- device=device,
- dtype=dtype
- ) / 8.0
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ / 8.0
+ )
edges = kornia.filters.spatial_gradient(inp, normalized=True)
assert_allclose(edges, expected)
@@ -114,16 +116,16 @@ class TestSpatialGradient:
[
[
[
- [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, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = torch.tensor(
@@ -131,18 +133,24 @@ class TestSpatialGradient:
[
[
[
- [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, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0, -1.0, 0.0],
+ [1.0, 1.0, 0.0, -1.0, -1.0],
+ [0.0, 1.0, 0.0, -1.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., 0., 0., 0.], [0., -1., -1., -1., 0.],
- [0., 0., -1., 0., 0.]
- ]
+ [0.0, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, -1.0, -1.0, -1.0, 0.0],
+ [0.0, 0.0, -1.0, 0.0, 0.0],
+ ],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
edges = kornia.filters.spatial_gradient(inp, 'diff', normalized=False)
@@ -153,36 +161,45 @@ class TestSpatialGradient:
[
[
[
- [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, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- expected = torch.tensor(
- [
+ 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.]
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0, -1.0, 0.0],
+ [1.0, 1.0, 0.0, -1.0, -1.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, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, -1.0, -1.0, -1.0, 0.0],
+ [0.0, 0.0, -1.0, 0.0, 0.0],
+ ],
]
]
- ]
- ],
- device=device,
- dtype=dtype
- ) / 2.0
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ / 2.0
+ )
edges = kornia.filters.spatial_gradient(inp, 'diff', normalized=True)
assert_allclose(edges, expected)
@@ -201,7 +218,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)
@@ -221,7 +238,6 @@ 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()
@@ -239,22 +255,31 @@ class TestSpatialGradient3d:
[
[
[
- [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.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., 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, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.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., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0.]
+ [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, 0.0, 0.0, 0.0, 0.0],
],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = torch.tensor(
@@ -263,60 +288,78 @@ class TestSpatialGradient3d:
[
[
[
- [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.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.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.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.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.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.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.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.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]
- ]
- ]
+ [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
+ dtype=dtype,
)
edges = kornia.filters.spatial_gradient3d(inp)
@@ -325,7 +368,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):
@@ -346,7 +389,6 @@ 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()
@@ -362,35 +404,35 @@ class TestSobel:
[
[
[
- [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, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = torch.tensor(
[
[
[
- [0., 1.4142, 2.0, 1.4142, 0.],
+ [0.0, 1.4142, 2.0, 1.4142, 0.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.],
+ [0.0, 1.4142, 2.0, 1.4142, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- edges = kornia.filters.sobel(inp, normalized=False, eps=0.)
+ edges = kornia.filters.sobel(inp, normalized=False, eps=0.0)
assert_allclose(edges, expected)
def test_noncontiguous(self, device, dtype):
diff --git a/test/filters/test_unsharp_mask.py b/test/filters/test_unsharp_mask.py
index 66cf6f3b7..ee861348a 100644
--- a/test/filters/test_unsharp_mask.py
+++ b/test/filters/test_unsharp_mask.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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)
@@ -36,11 +35,7 @@ class Testunsharp:
# evaluate function gradient
input = torch.rand(batch_shape, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- kornia.filters.unsharp_mask,
- (input, kernel_size, sigma, "replicate"),
- raise_exception=True,
- )
+ assert gradcheck(kornia.filters.unsharp_mask, (input, kernel_size, sigma, "replicate"), raise_exception=True)
def test_jit(self, device, dtype):
op = kornia.filters.unsharp_mask
diff --git a/test/geometry/epipolar/test_common.py b/test/geometry/epipolar/test_common.py
index ce848a56f..f16b0c769 100644
--- a/test/geometry/epipolar/test_common.py
+++ b/test/geometry/epipolar/test_common.py
@@ -5,8 +5,9 @@ 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
diff --git a/test/geometry/epipolar/test_epipolar_metrics.py b/test/geometry/epipolar/test_epipolar_metrics.py
index 701e1e977..1a3905de1 100644
--- a/test/geometry/epipolar/test_epipolar_metrics.py
+++ b/test/geometry/epipolar/test_epipolar_metrics.py
@@ -6,7 +6,6 @@ import kornia.testing as utils
class TestSymmetricalEpipolarDistance:
-
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)
@@ -30,7 +29,6 @@ class TestSymmetricalEpipolarDistance:
class TestSampsonEpipolarDistance:
-
def test_smoke(self, device, dtype):
pts1 = torch.rand(1, 4, 3, device=device, dtype=dtype)
pts2 = torch.rand(1, 4, 3, device=device, dtype=dtype)
diff --git a/test/geometry/epipolar/test_essential.py b/test/geometry/epipolar/test_essential.py
index 68e247fcd..70b4bcd8e 100644
--- a/test/geometry/epipolar/test_essential.py
+++ b/test/geometry/epipolar/test_essential.py
@@ -8,7 +8,6 @@ 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)
@@ -61,15 +60,10 @@ 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)
@@ -79,12 +73,7 @@ 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)
@@ -96,13 +85,9 @@ class TestRelativeCameraMotion:
assert t.shape == (B, 3, 1)
def test_translation(self, device, dtype):
- R1 = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ R1 = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- t1 = torch.tensor([[[10.], [0.], [0.]]]).type_as(R1)
+ t1 = torch.tensor([[[10.0], [0.0], [0.0]]]).type_as(R1)
R2 = epi.eye_like(3, R1)
t2 = epi.vec_like(3, t1)
@@ -115,17 +100,9 @@ class TestRelativeCameraMotion:
assert_allclose(t_expected, t)
def test_rotate_z(self, device, dtype):
- R1 = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
-
- R2 = torch.tensor([[
- [0., 0., 0.],
- [0., 0., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ R1 = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+
+ R2 = torch.tensor([[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
t1 = epi.vec_like(3, R1)
t2 = epi.vec_like(3, R2)
@@ -142,16 +119,10 @@ 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)
@@ -160,12 +131,7 @@ 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)
@@ -194,16 +160,10 @@ 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)
@@ -211,18 +171,13 @@ class TestDecomposeEssentialMatrix:
assert R2.shape == (1, 3, 3)
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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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)
@@ -236,25 +191,19 @@ 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)
assert Rs.shape == (1, 4, 3, 3)
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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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)
Rs, Ts = epi.motion_from_essential(E_mat)
@@ -289,12 +238,11 @@ 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)
@@ -306,12 +254,7 @@ class TestMotionFromEssentialChooseSolution:
assert t.shape == (1, 3, 1)
assert X.shape == (1, 1, 3)
- @pytest.mark.parametrize("batch_size, num_points", [
- (1, 3),
- (2, 3),
- (2, 8),
- (3, 2),
- ])
+ @pytest.mark.parametrize("batch_size, num_points", [(1, 3), (2, 3), (2, 8), (3, 2)])
def test_shape(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
E_mat = torch.rand(B, 3, 3, device=device, dtype=dtype)
@@ -386,10 +329,4 @@ 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 d02076922..775eb1bc5 100644
--- a/test/geometry/epipolar/test_fundamental.py
+++ b/test/geometry/epipolar/test_fundamental.py
@@ -8,7 +8,6 @@ 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)
@@ -16,10 +15,7 @@ class TestNormalizePoints:
assert output[0].shape == (1, 1, 2)
assert output[1].shape == (1, 3, 3)
- @pytest.mark.parametrize(
- "batch_size, num_points",
- [(1, 2), (2, 3), (3, 2)],
- )
+ @pytest.mark.parametrize("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
points = torch.rand(B, N, 2, device=device, dtype=dtype)
@@ -28,30 +24,26 @@ 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.0], [0.0, 2.0], [1.0, 1.0], [1.0, 3.0]]], device=device, dtype=dtype)
points_norm, trans = epi.normalize_points(points)
points_std, points_mean = torch.std_mean(points_norm, dim=1)
assert_allclose(points_mean, torch.zeros_like(points_mean))
- assert (points_std < 2.).all()
+ assert (points_std < 2.0).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)
+ 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)],
- )
+ @pytest.mark.parametrize("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
trans = torch.rand(B, N, M, device=device, dtype=dtype)
@@ -76,11 +68,10 @@ class TestNormalizeTransformation:
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)
+ 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)
@@ -88,10 +79,7 @@ class TestFindFundamental:
F_mat = epi.find_fundamental(points1, points2, weights)
assert F_mat.shape == (1, 3, 3)
- @pytest.mark.parametrize(
- "batch_size, num_points",
- [(1, 2), (2, 3), (3, 2)],
- )
+ @pytest.mark.parametrize("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
points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
@@ -104,23 +92,39 @@ class TestFindFundamental:
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]
+ [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
+ 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]
+ [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
+ dtype=dtype,
)
weights = torch.ones(1, 10, device=device, dtype=dtype)
@@ -134,12 +138,13 @@ class TestFindFundamental:
Fm_expected = torch.tensor(
[
[
- [-0.47408533, 0.22033807, -0.00346677], [0.54935973, 1.31080955, -1.25028275],
- [-0.36690215, -1.08143769, 1.]
+ [-0.47408533, 0.22033807, -0.00346677],
+ [0.54935973, 1.31080955, -1.25028275],
+ [-0.36690215, -1.08143769, 1.0],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
F_mat = epi.find_fundamental(points1, points2, weights)
@@ -157,31 +162,23 @@ class TestFindFundamental:
F_est = epi.find_fundamental(x1, x2, weights)
error = epi.sampson_epipolar_distance(x1, x2, F_est)
- assert_allclose(error, torch.tensor(0., device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
+ assert_allclose(error, torch.tensor(0.0, device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
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)
lines = epi.compute_correspond_epilines(point, F_mat)
assert lines.shape == (1, 1, 3)
- @pytest.mark.parametrize(
- "batch_size, num_points",
- [(1, 2), (2, 3), (3, 2)],
- )
+ @pytest.mark.parametrize("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
point = torch.rand(B, N, 2, device=device, dtype=dtype)
@@ -193,19 +190,10 @@ class TestComputeCorrespondEpilimes:
point = torch.rand(1, 2, 2, device=device, dtype=dtype)
F_mat = torch.rand(1, 3, 3, device=device, dtype=dtype)
- point = torch.tensor([[
- [0.9794, 0.7994],
- [0.8163, 0.8500],
- ]], device=device, dtype=dtype)
+ point = torch.tensor([[[0.9794, 0.7994], [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
+ [[[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
@@ -215,10 +203,7 @@ class TestComputeCorrespondEpilimes:
# 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
+ [[[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)
@@ -227,14 +212,10 @@ 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)
@@ -273,15 +254,10 @@ 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)
@@ -303,17 +279,13 @@ class TestFundamentalFromProjections:
assert F_mat.shape == (1, 2, 3, 3)
def test_from_to_projections(self, device, dtype):
- P1 = torch.tensor([[
- [1., 0., 0., 0.],
- [0., 1., 0., 0.],
- [1., 0., 1., 0.],
- ]], device=device, dtype=dtype)
-
- P2 = torch.tensor([[
- [1., 1., 1., 3.],
- [0., 2., 0., 3.],
- [0., 1., 1., 0.],
- ]], device=device, dtype=dtype)
+ P1 = torch.tensor(
+ [[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [1.0, 0.0, 1.0, 0.0]]], device=device, dtype=dtype
+ )
+
+ P2 = torch.tensor(
+ [[[1.0, 1.0, 1.0, 3.0], [0.0, 2.0, 0.0, 3.0], [0.0, 1.0, 1.0, 0.0]]], device=device, dtype=dtype
+ )
F_mat = epi.fundamental_from_projections(P1, P2)
P_mat = epi.projections_from_fundamental(F_mat)
@@ -326,65 +298,62 @@ 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.4692e02, -9.6658e02, 6.0862e02, -2.3076e05],
+ [-2.1829e02, 5.4163e02, 1.3445e03, -6.4387e05],
+ [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e02],
],
[
- [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.4692e02, -9.6658e02, 6.0862e02, -2.3076e05],
+ [-2.1829e02, 5.4163e02, 1.3445e03, -6.4387e05],
+ [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e02],
+ ],
],
device=device,
- dtype=dtype
+ 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]
- ],
+ [9.4692e02, -9.6658e02, 6.0862e02, -2.3076e05],
+ [-2.1829e02, 5.4163e02, 1.3445e03, -6.4387e05],
+ [-6.0675e-01, -6.9807e-01, 3.8021e-01, 3.8896e02],
+ ]
],
device=device,
- dtype=dtype
+ 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]
+ [1.1518e03, -7.5822e02, 5.4764e02, -1.9764e05],
+ [-2.1548e02, 5.3102e02, 1.3492e03, -6.4731e05],
+ [-4.3727e-01, -7.8632e-01, 4.3646e-01, 3.4515e02],
],
[
- [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]
- ]
+ [9.9595e02, -8.6464e02, 6.7959e02, -2.7517e05],
+ [-8.1716e01, 7.7826e02, 1.2395e03, -5.8137e05],
+ [-5.7090e-01, -6.0416e-01, 5.5594e-01, 2.8111e02],
+ ],
],
device=device,
- dtype=dtype
+ 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]
- ],
+ [1.1518e03, -7.5822e02, 5.4764e02, -1.9764e05],
+ [-2.1548e02, 5.3102e02, 1.3492e03, -6.4731e05],
+ [-4.3727e-01, -7.8632e-01, 4.3646e-01, 3.4515e02],
+ ]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
F_batch = epi.fundamental_from_projections(P1_batch, P2_batch)
diff --git a/test/geometry/epipolar/test_numeric.py b/test/geometry/epipolar/test_numeric.py
index 74a4934f1..645508d92 100644
--- a/test/geometry/epipolar/test_numeric.py
+++ b/test/geometry/epipolar/test_numeric.py
@@ -7,7 +7,6 @@ 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)
@@ -21,7 +20,7 @@ class TestSkewSymmetric:
assert cross_product_matrix.shape == (B, 3, 3)
def test_mean_std(self, device, dtype):
- vec = torch.tensor([[1., 2., 3.]], device=device, dtype=dtype)
+ vec = torch.tensor([[1.0, 2.0, 3.0]], device=device, dtype=dtype)
cross_product_matrix = epi.cross_product_matrix(vec)
assert_allclose(cross_product_matrix[..., 0, 1], -cross_product_matrix[..., 1, 0])
assert_allclose(cross_product_matrix[..., 0, 2], -cross_product_matrix[..., 2, 0])
@@ -29,11 +28,10 @@ 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,10 +39,7 @@ class TestEyeLike:
assert identity.device == image.device
assert identity.dtype == image.dtype
- @pytest.mark.parametrize(
- "batch_size, eye_size",
- [(1, 2), (2, 3), (3, 3), (2, 4)],
- )
+ @pytest.mark.parametrize("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
image = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)
@@ -55,7 +50,6 @@ 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)
@@ -63,10 +57,7 @@ class TestVecLike:
assert vec.device == image.device
assert vec.dtype == image.dtype
- @pytest.mark.parametrize(
- "batch_size, eye_size",
- [(1, 2), (2, 3), (3, 3), (2, 4)],
- )
+ @pytest.mark.parametrize("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
image = torch.rand(B, 3, 4, 4, device=device, dtype=dtype)
diff --git a/test/geometry/epipolar/test_projection.py b/test/geometry/epipolar/test_projection.py
index a1191da1d..f62779480 100644
--- a/test/geometry/epipolar/test_projection.py
+++ b/test/geometry/epipolar/test_projection.py
@@ -7,7 +7,6 @@ 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,7 +25,6 @@ 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)
@@ -49,18 +47,12 @@ class TestScaleIntrinsics:
def test_scale_double(self, device, dtype):
scale_factor = torch.tensor(0.5)
- camera_matrix = torch.tensor([[
- [100., 0., 50.],
- [0., 100., 50.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor(
+ [[[100.0, 0.0, 50.0], [0.0, 100.0, 50.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ )
camera_matrix_expected = torch.tensor(
- [[
- [50., 0., 25.],
- [0., 50., 25.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype
+ [[[50.0, 0.0, 25.0], [0.0, 50.0, 25.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
)
camera_matrix_scale = epi.scale_intrinsics(camera_matrix, scale_factor)
@@ -69,14 +61,10 @@ 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)
@@ -94,28 +82,14 @@ class TestProjectionFromKRt:
assert P.shape == (B, 3, 4)
def test_simple(self, device, dtype):
- K = torch.tensor([[
- [10., 0., 30.],
- [0., 20., 40.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
-
- R = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
-
- t = torch.tensor([
- [[1.], [2.], [3.]],
- ], device=device, dtype=dtype)
+ K = torch.tensor([[[10.0, 0.0, 30.0], [0.0, 20.0, 40.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+
+ R = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+
+ t = torch.tensor([[[1.0], [2.0], [3.0]]], device=device, dtype=dtype)
P_expected = torch.tensor(
- [[
- [10., 0., 30., 100.],
- [0., 20., 40., 160.],
- [0., 0., 1., 3.],
- ]], device=device, dtype=dtype
+ [[[10.0, 0.0, 30.0, 100.0], [0.0, 20.0, 40.0, 160.0], [0.0, 0.0, 1.0, 3.0]]], device=device, dtype=dtype
)
P_estimated = epi.projection_from_KRt(K, R, t)
@@ -123,26 +97,14 @@ class TestProjectionFromKRt:
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
+ [[[10.0, 0.0, 30.0, 100.0], [0.0, 20.0, 40.0, 160.0], [0.0, 0.0, 1.0, 3.0]]], device=device, dtype=dtype
)
- K_expected = torch.tensor([[
- [10., 0., 30.],
- [0., 20., 40.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ K_expected = torch.tensor([[[10.0, 0.0, 30.0], [0.0, 20.0, 40.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- R_expected = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ R_expected = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
- t_expected = torch.tensor([[[1.], [2.], [3.]]], device=device, dtype=dtype)
+ t_expected = torch.tensor([[[1.0], [2.0], [3.0]]], 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)
@@ -153,15 +115,10 @@ 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)
@@ -176,11 +133,10 @@ 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)
@@ -200,19 +156,21 @@ class TestKRtFromProjection:
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
+ [[[308.0, 139.0, 231.0, 84.0], [481.0, 161.0, 358.0, 341.0], [384.0, 387.0, 459.0, 102.0]]],
+ 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
+ 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
+ dtype=dtype,
)
t_expected = torch.tensor([[[-6.477699], [1.129624], [0.143123]]], device=device, dtype=dtype)
@@ -226,21 +184,21 @@ class TestKRtFromProjection:
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
+ 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
+ dtype=dtype,
)
- t = torch.tensor([
- [[-6.477699], [1.129624], [0.143123]],
- ], 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
+ [[[308.0, 139.0, 231.0, 84.0], [481.0, 161.0, 358.0, 341.0], [384.0, 387.0, 459.0, 102.0]]],
+ device=device,
+ dtype=dtype,
)
P_estimated = epi.projection_from_KRt(K, R, t)
@@ -248,4 +206,4 @@ class TestKRtFromProjection:
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 47aa295ac..c9d31bce4 100644
--- a/test/geometry/epipolar/test_triangulation.py
+++ b/test/geometry/epipolar/test_triangulation.py
@@ -8,7 +8,6 @@ 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,9 +50,4 @@ 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 959e1b081..8b1a3e90f 100644
--- a/test/geometry/subpix/test_dsnt.py
+++ b/test/geometry/subpix/test_dsnt.py
@@ -6,7 +6,6 @@ import kornia as kornia
class TestRenderGaussian2d:
-
@pytest.fixture
def gaussian(self, device, dtype):
return torch.tensor(
@@ -18,7 +17,7 @@ class TestRenderGaussian2d:
[0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
],
dtype=dtype,
- device=device
+ device=device,
)
def test_pixel_coordinates(self, gaussian, device, dtype):
@@ -42,7 +41,6 @@ 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)
@@ -54,11 +52,7 @@ class TestRenderGaussian2d:
class TestSpatialSoftmax2d:
-
- @pytest.fixture(params=[
- torch.ones(1, 1, 5, 7),
- torch.randn(2, 3, 16, 16),
- ])
+ @pytest.fixture(params=[torch.ones(1, 1, 5, 7), torch.randn(2, 3, 16, 16)])
def input(self, request, device, dtype):
return request.param.to(device, dtype)
@@ -75,22 +69,18 @@ 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([[[[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):
@@ -113,5 +103,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 d26cd0924..c4c8d3d84 100644
--- a/test/geometry/subpix/test_spatial_softargmax.py
+++ b/test/geometry/subpix/test_spatial_softargmax.py
@@ -10,7 +10,6 @@ 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)
@@ -19,11 +18,17 @@ class TestCenterKernel2d:
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.]]]
+ [
+ [[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]],
+ ],
+ [
+ [[0.0, 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]],
+ ],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
assert_allclose(kernel, expected, atol=1e-4, rtol=1e-4)
@@ -36,7 +41,6 @@ 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)
@@ -44,9 +48,9 @@ class TestCenterKernel3d:
def test_odd(self, device, dtype):
kernel = _get_center_kernel3d(3, 5, 7, device=device).to(dtype=dtype)
expected = torch.zeros(3, 3, 3, 5, 7, device=device, dtype=dtype)
- expected[0, 0, 1, 2, 3] = 1.
- expected[1, 1, 1, 2, 3] = 1.
- expected[2, 2, 1, 2, 3] = 1.
+ expected[0, 0, 1, 2, 3] = 1.0
+ expected[1, 1, 1, 2, 3] = 1.0
+ expected[2, 2, 1, 2, 3] = 1.0
assert_allclose(kernel, expected, atol=1e-4, rtol=1e-4)
def test_even(self, device, dtype):
@@ -59,7 +63,6 @@ class TestCenterKernel3d:
class TestSpatialSoftArgmax2d:
-
def test_smoke(self, device, dtype):
input = torch.zeros(1, 1, 2, 3, device=device, dtype=dtype)
m = kornia.SpatialSoftArgmax2d()
@@ -161,12 +164,11 @@ 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))
@@ -201,22 +203,24 @@ class TestConvSoftArgmax2d:
[
[
[
- [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, 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, 0.0],
]
]
],
device=device,
- dtype=dtype
+ 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)
+ expected_val = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[1.0, 3.0], [1.0, 3.0]], [[1.0, 1.0], [3.0, 3.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)
@@ -226,22 +230,24 @@ class TestConvSoftArgmax2d:
[
[
[
- [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, 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, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
softargmax = kornia.ConvSoftArgmax2d(
- (3, 3), (2, 2), (0, 0), temperature=10., normalized_coordinates=False, output_value=True
+ (3, 3), (2, 2), (0, 0), temperature=10.0, normalized_coordinates=False, output_value=True
+ )
+ expected_val = torch.tensor([[[[0.1214, 0.0], [0.0, 0.1214]]]], device=device, dtype=dtype)
+ expected_coord = torch.tensor(
+ [[[[[1.0, 3.0], [1.0, 3.0]], [[1.0, 1.0], [3.0, 3.0]]]]], device=device, dtype=dtype
)
- 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)
@@ -251,21 +257,21 @@ class TestConvSoftArgmax2d:
[
[
[
- [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, 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, 0.0],
]
]
],
device=device,
- dtype=dtype
+ 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_val = torch.tensor([[[[1.0, 0.0], [0.0, 1.0]]]], 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
)
@@ -278,21 +284,21 @@ class TestConvSoftArgmax2d:
[
[
[
- [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, 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, 0.0],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
softargmax = kornia.ConvSoftArgmax2d(
- (3, 3), (2, 2), (0, 0), temperature=10., normalized_coordinates=True, output_value=True
+ (3, 3), (2, 2), (0, 0), temperature=10.0, normalized_coordinates=True, output_value=True
)
- expected_val = torch.tensor([[[[0.1214, 0.], [0., 0.1214]]]], device=device, dtype=dtype)
+ expected_val = torch.tensor([[[[0.1214, 0.0], [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
)
@@ -302,7 +308,6 @@ class TestConvSoftArgmax2d:
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)
@@ -326,24 +331,26 @@ class TestConvSoftArgmax3d:
[
[
[
- [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, 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, 0.0],
]
]
]
],
device=device,
- dtype=dtype
+ 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_val = torch.tensor([[[[[1.0, 0.0], [0.0, 1.0]]]]], device=device, dtype=dtype)
expected_coord = torch.tensor(
- [[[[[[0., 0.], [0., 0.]]], [[[1., 3.], [1., 3.]]], [[[1., 1.], [3., 3.]]]]]], device=device, dtype=dtype
+ [[[[[[0.0, 0.0], [0.0, 0.0]]], [[[1.0, 3.0], [1.0, 3.0]]], [[[1.0, 1.0], [3.0, 3.0]]]]]],
+ device=device,
+ dtype=dtype,
)
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
@@ -355,24 +362,26 @@ class TestConvSoftArgmax3d:
[
[
[
- [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, 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, 0.0],
]
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
softargmax = kornia.ConvSoftArgmax3d(
- (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10., normalized_coordinates=False, output_value=True
+ (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10.0, normalized_coordinates=False, output_value=True
)
- expected_val = torch.tensor([[[[[0.1214, 0.], [0., 0.1214]]]]], device=device, dtype=dtype)
+ expected_val = torch.tensor([[[[[0.1214, 0.0], [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
+ [[[[[[0.0, 0.0], [0.0, 0.0]]], [[[1.0, 3.0], [1.0, 3.0]]], [[[1.0, 1.0], [3.0, 3.0]]]]]],
+ device=device,
+ dtype=dtype,
)
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
@@ -384,26 +393,26 @@ class TestConvSoftArgmax3d:
[
[
[
- [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, 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, 0.0],
]
]
]
],
device=device,
- dtype=dtype
+ 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_val = torch.tensor([[[[[1.0, 0.0], [0.0, 1.0]]]]], 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]]]]]],
+ [[[[[[-1.0, -1.0], [-1.0, -1.0]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
@@ -415,26 +424,26 @@ class TestConvSoftArgmax3d:
[
[
[
- [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, 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, 0.0],
]
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
softargmax = kornia.ConvSoftArgmax3d(
- (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10., normalized_coordinates=True, output_value=True
+ (1, 3, 3), (1, 2, 2), (0, 0, 0), temperature=10.0, normalized_coordinates=True, output_value=True
)
- expected_val = torch.tensor([[[[[0.1214, 0.], [0., 0.1214]]]]], device=device, dtype=dtype)
+ expected_val = torch.tensor([[[[[0.1214, 0.0], [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]]]]]],
+ [[[[[[-1.0, -1.0], [-1.0, -1.0]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
@@ -453,13 +462,10 @@ class TestConvQuadInterp3d:
def test_gradcheck(self, device, dtype):
input = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)
- input[0, 0, 1, 2, 2] += 20.
+ input[0, 0, 1, 2, 2] += 20.0
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
+ kornia.geometry.ConvQuadInterp3d(strict_maxima_bonus=0), (input), raise_exception=True, atol=1e-3, rtol=1e-3
)
def test_diag(self, device, dtype):
@@ -467,24 +473,30 @@ class TestConvQuadInterp3d:
[
[
[
- [0., 0., 0., 0, 0], [0., 0., 0.0, 0, 0.], [0., 0, 0., 0, 0.], [0., 0., 0, 0, 0.],
- [0., 0., 0., 0, 0.]
+ [0.0, 0.0, 0.0, 0, 0],
+ [0.0, 0.0, 0.0, 0, 0.0],
+ [0.0, 0, 0.0, 0, 0.0],
+ [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, 1, 0, 0.0],
+ [0.0, 1, 1.2, 1.1, 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., 0, 0.],
- [0., 0., 0, 0, 0.],
- [0., 0., 0., 0, 0.],
- ]
+ [0.0, 0.0, 0.0, 0, 0],
+ [0.0, 0.0, 0.0, 0, 0.0],
+ [0.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
+ dtype=dtype,
)
input = kornia.gaussian_blur2d(input, (5, 5), (0.5, 0.5)).unsqueeze(0)
softargmax = kornia.geometry.ConvQuadInterp3d(10)
@@ -493,25 +505,31 @@ class TestConvQuadInterp3d:
[
[
[
- [0., 0., 0., 0, 0], [0., 0., 0.0, 0, 0.], [0., 0, 0., 0, 0.], [0., 0., 0, 0, 0.],
- [0., 0., 0., 0, 0.]
+ [0.0, 0.0, 0.0, 0, 0],
+ [0.0, 0.0, 0.0, 0, 0.0],
+ [0.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],
+ [1.6807e-01, 7.4227e-01, 1.1086e01, 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]
+ [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.]
- ]
+ [0.0, 0.0, 0.0, 0, 0],
+ [0.0, 0.0, 0.0, 0, 0.0],
+ [0.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
+ dtype=dtype,
)
expected_coord = torch.tensor(
[
@@ -519,51 +537,78 @@ class TestConvQuadInterp3d:
[
[
[
- [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 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]
+ [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]
- ]
+ [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, 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.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.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]
- ]
- ]
+ [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
+ dtype=dtype,
)
coords, val = softargmax(input)
assert_allclose(val, expected_val, atol=1e-4, rtol=1e-4)
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index 591bf263d..cd4d5f5e8 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -15,18 +15,18 @@ from kornia.testing import tensor_to_gradcheck_var, create_eye_batch
def atol(device, dtype):
"""Lower tolerance for cuda-float16 only"""
if 'cuda' in device.type and dtype == torch.float16:
- return 1.e-3
+ return 1.0e-3
else:
- return 1.e-4
+ return 1.0e-4
@pytest.fixture
def rtol(device, dtype):
"""Lower tolerance for cuda-float16 only"""
if 'cuda' in device.type and dtype == torch.float16:
- return 1.e-3
+ return 1.0e-3
else:
- return 1.e-4
+ return 1.0e-4
# based on:
@@ -34,17 +34,16 @@ def rtol(device, dtype):
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, )
+ 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, )
+ assert quaternion.shape == (4,)
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
@@ -60,147 +59,143 @@ class TestAngleAxisToQuaternion:
assert quaternion.shape == (batch_size, 4)
def test_zero_angle_xyzw(self, device, dtype, atol, rtol):
- angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ angle_axis = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ angle_axis = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((1.0, 0.0, 0.0, 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_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)
+ theta = 1.0e-2
+ angle_axis = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((np.sin(theta / 2.0), 0.0, 0.0, np.cos(theta / 2.0)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
+ theta = 1.0e-2
+ angle_axis = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.0), np.sin(theta / 2.0), 0.0, 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)
+ theta = 1.0e-2
+ angle_axis = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, np.sin(theta / 2.0), 0.0, np.cos(theta / 2.0)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
+ theta = 1.0e-2
+ angle_axis = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.0), 0.0, np.sin(theta / 2.0), 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_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)
+ theta = 1.0e-2
+ angle_axis = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, np.sin(theta / 2.0), np.cos(theta / 2.0)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
+ theta = 1.0e-2
+ angle_axis = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)
+ expected = torch.tensor((np.cos(theta / 2.0), 0.0, 0.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_x_rotation_xyzw(self, device, dtype, atol, rtol):
- half_sqrt2 = 0.5 * np.sqrt(2.)
- 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)
+ half_sqrt2 = 0.5 * np.sqrt(2.0)
+ angle_axis = torch.tensor((kornia.pi / 2.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, 0.0, 0.0, half_sqrt2), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- half_sqrt2 = 0.5 * np.sqrt(2.)
- angle_axis = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((half_sqrt2, half_sqrt2, 0., 0.), device=device, dtype=dtype)
+ half_sqrt2 = 0.5 * np.sqrt(2.0)
+ angle_axis = torch.tensor((kornia.pi / 2.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, half_sqrt2, 0.0, 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_y_rotation_xyzw(self, device, dtype, atol, rtol):
- half_sqrt2 = 0.5 * np.sqrt(2.)
- 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)
+ half_sqrt2 = 0.5 * np.sqrt(2.0)
+ angle_axis = torch.tensor((0.0, kornia.pi / 2.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 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)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_y_rotation(self, device, dtype, atol, rtol):
- half_sqrt2 = 0.5 * np.sqrt(2.)
- angle_axis = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
- expected = torch.tensor((half_sqrt2, 0., half_sqrt2, 0.), device=device, dtype=dtype)
+ half_sqrt2 = 0.5 * np.sqrt(2.0)
+ angle_axis = torch.tensor((0.0, kornia.pi / 2.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, 0.0, half_sqrt2, 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_z_rotation_xyzw(self, device, dtype, atol, rtol):
- half_sqrt2 = 0.5 * np.sqrt(2.)
- 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)
+ half_sqrt2 = 0.5 * np.sqrt(2.0)
+ angle_axis = torch.tensor((0.0, 0.0, kornia.pi / 2.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 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)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_z_rotation(self, device, dtype, atol, rtol):
- half_sqrt2 = 0.5 * np.sqrt(2.)
- angle_axis = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
- expected = torch.tensor((half_sqrt2, 0., 0., half_sqrt2), device=device, dtype=dtype)
+ half_sqrt2 = 0.5 * np.sqrt(2.0)
+ angle_axis = torch.tensor((0.0, 0.0, kornia.pi / 2.0), device=device, dtype=dtype)
+ expected = torch.tensor((half_sqrt2, 0.0, 0.0, half_sqrt2), 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_gradcheck_xyzw(self, device, dtype):
eps = torch.finfo(dtype).eps
- angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype) + eps
+ angle_axis = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype) + eps
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
+ 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 = torch.tensor((0.0, 0.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
+ partial(kornia.angle_axis_to_quaternion, order=QuaternionCoeffOrder.WXYZ),
+ (angle_axis,),
+ raise_exception=True,
)
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, )
+ 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):
@@ -216,126 +211,127 @@ class TestQuaternionToAngleAxis:
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)
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
+ quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
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)
+ quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi, 0.0, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
+ quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi, 0.0, 0.0), device=device, dtype=dtype)
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)
+ quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, kornia.pi, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
+ quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, kornia.pi, 0.0), device=device, dtype=dtype)
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)
+ quaternion = torch.tensor((0.0, 0.0, 0.5, np.sqrt(3.0) / 2.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, kornia.pi / 3.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
+ quaternion = torch.tensor((np.sqrt(3.0) / 2.0, 0.0, 0.0, 0.5), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, kornia.pi / 3.0), device=device, dtype=dtype)
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)
- expected = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
+ theta = 1.0e-2
+ quaternion = torch.tensor((np.sin(theta / 2.0), 0.0, 0.0, np.cos(theta / 2.0)), device=device, dtype=dtype)
+ expected = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
- expected = torch.tensor((theta, 0., 0.), device=device, dtype=dtype)
+ theta = 1.0e-2
+ quaternion = torch.tensor((np.cos(theta / 2.0), np.sin(theta / 2.0), 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((theta, 0.0, 0.0), device=device, dtype=dtype)
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)
- expected = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
+ theta = 1.0e-2
+ quaternion = torch.tensor((0.0, np.sin(theta / 2), 0.0, np.cos(theta / 2)), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
- expected = torch.tensor((0., theta, 0.), device=device, dtype=dtype)
+ theta = 1.0e-2
+ quaternion = torch.tensor((np.cos(theta / 2), 0.0, np.sin(theta / 2), 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, theta, 0.0), device=device, dtype=dtype)
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)
- expected = torch.tensor((0., 0., theta), device=device, dtype=dtype)
+ theta = 1.0e-2
+ quaternion = torch.tensor((0.0, 0.0, np.sin(theta / 2), np.cos(theta / 2)), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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)
- expected = torch.tensor((0., 0., theta), device=device, dtype=dtype)
+ theta = 1.0e-2
+ quaternion = torch.tensor((np.cos(theta / 2), 0.0, 0.0, np.sin(theta / 2)), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, theta), device=device, dtype=dtype)
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):
eps = torch.finfo(dtype).eps
- quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype) + eps
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype) + eps
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
+ 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 = torch.tensor((1.0, 0.0, 0.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
+ partial(kornia.quaternion_to_angle_axis, order=QuaternionCoeffOrder.WXYZ),
+ (quaternion,),
+ raise_exception=True,
)
class TestRotationMatrixToQuaternion:
-
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
matrix = torch.zeros(batch_size, 3, 3, device=device, dtype=dtype)
@@ -350,56 +346,36 @@ class TestRotationMatrixToQuaternion:
assert quaternion.shape == (batch_size, 4)
def test_identity_xyzw(self, device, dtype, atol, rtol):
- matrix = torch.tensor((
- (1., 0., 0.),
- (0., 1., 0.),
- (0., 0., 1.),
- ), device=device, dtype=dtype)
- expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- matrix = torch.tensor((
- (1., 0., 0.),
- (0., 1., 0.),
- (0., 0., 1.),
- ), device=device, dtype=dtype)
- expected = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
+ expected = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_rot_x_45_xyzw(self, device, dtype, atol, rtol):
- matrix = torch.tensor((
- (1., 0., 0.),
- (0., 0., -1.),
- (0., 1., 0.),
- ), device=device, dtype=dtype)
- 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)
+ matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)), device=device, dtype=dtype)
+ pi_half2 = torch.cos(kornia.pi / 4.0).to(device=device, dtype=dtype)
+ expected = torch.tensor((pi_half2, 0.0, 0.0, pi_half2), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- matrix = torch.tensor((
- (1., 0., 0.),
- (0., 0., -1.),
- (0., 1., 0.),
- ), device=device, dtype=dtype)
- pi_half2 = torch.cos(kornia.pi / 4.).to(device=device, dtype=dtype)
- expected = torch.tensor((pi_half2, pi_half2, 0., 0.), device=device, dtype=dtype)
+ matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.0)), device=device, dtype=dtype)
+ pi_half2 = torch.cos(kornia.pi / 4.0).to(device=device, dtype=dtype)
+ expected = torch.tensor((pi_half2, pi_half2, 0.0, 0.0), device=device, dtype=dtype)
quaternion = kornia.rotation_matrix_to_quaternion(matrix, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(quaternion, expected, atol=atol, rtol=rtol)
def test_back_and_forth_xyzw(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- matrix = torch.tensor((
- (1., 0., 0.),
- (0., 0., -1.),
- (0., 1., 0.),
- ), device=device, dtype=dtype)
+ matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.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)
@@ -407,11 +383,7 @@ class TestRotationMatrixToQuaternion:
def test_back_and_forth(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- matrix = torch.tensor((
- (1., 0., 0.),
- (0., 0., -1.),
- (0., 1., 0.),
- ), device=device, dtype=dtype)
+ matrix = torch.tensor(((1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (0.0, 1.0, 0.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)
assert_allclose(matrix, matrix_hat, atol=atol, rtol=rtol)
@@ -420,11 +392,12 @@ class TestRotationMatrixToQuaternion:
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)
+ (-0.7799533010, -0.5432914495, 0.3106555045),
+ (0.0492402576, -0.5481169224, -0.8349509239),
+ (0.6238971353, -0.6359263659, 0.4542570710),
),
device=device,
- dtype=dtype
+ dtype=dtype,
)
quaternion_true = torch.tensor(
(0.280136495828629, -0.440902262926102, 0.834015488624573, 0.177614107728004), device=device, dtype=dtype
@@ -438,11 +411,12 @@ class TestRotationMatrixToQuaternion:
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)
+ (-0.7799533010, -0.5432914495, 0.3106555045),
+ (0.0492402576, -0.5481169224, -0.8349509239),
+ (0.6238971353, -0.6359263659, 0.4542570710),
),
device=device,
- dtype=dtype
+ dtype=dtype,
)
quaternion_true = torch.tensor(
(0.177614107728004, 0.280136495828629, -0.440902262926102, 0.834015488624573), device=device, dtype=dtype
@@ -458,8 +432,9 @@ class TestRotationMatrixToQuaternion:
# evaluate function gradient
with pytest.warns(UserWarning):
assert gradcheck(
- partial(kornia.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW), (matrix, ),
- raise_exception=True
+ partial(kornia.rotation_matrix_to_quaternion, eps=eps, order=QuaternionCoeffOrder.XYZW),
+ (matrix,),
+ raise_exception=True,
)
def test_gradcheck(self, device, dtype):
@@ -468,15 +443,16 @@ class TestRotationMatrixToQuaternion:
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
+ 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):
op = kornia.quaternion_log_to_exp
op_script = torch.jit.script(op)
- quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
actual = op_script(quaternion)
with pytest.warns(UserWarning):
@@ -488,14 +464,13 @@ class TestRotationMatrixToQuaternion:
eps = torch.finfo(dtype).eps
op = kornia.quaternion_log_to_exp
op_script = torch.jit.script(op)
- quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
actual = op_script(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)
expected = op(quaternion, eps=eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(actual, expected)
class TestQuaternionToRotationMatrix:
-
@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)
@@ -510,114 +485,84 @@ class TestQuaternionToRotationMatrix:
assert matrix.shape == (batch_size, 3, 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((
- (1., 0., 0.),
- (0., 1., 0.),
- (0., 0., 1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
+ expected = torch.tensor(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((
- (1., 0., 0.),
- (0., 1., 0.),
- (0., 0., 1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor(((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(matrix, 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((
- (1., 0., 0.),
- (0., -1., 0.),
- (0., 0., -1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor(((1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- quaternion = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((
- (1., 0., 0.),
- (0., -1., 0.),
- (0., 0., -1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor(((1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(matrix, 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((
- (-1., 0., 0.),
- (0., 1., 0.),
- (0., 0., -1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor(((-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
- expected = torch.tensor((
- (-1., 0., 0.),
- (0., 1., 0.),
- (0., 0., -1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor(((-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, -1.0)), device=device, dtype=dtype)
matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(matrix, expected, atol=atol, rtol=rtol)
def test_z_rotation_xyzw(self, device, dtype, atol, rtol):
- quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
- expected = torch.tensor((
- (-1., 0., 0.),
- (0., -1., 0.),
- (0., 0., 1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor(((-1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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):
- quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
- expected = torch.tensor((
- (-1., 0., 0.),
- (0., -1., 0.),
- (0., 0., 1.),
- ), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
+ expected = torch.tensor(((-1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 1.0)), device=device, dtype=dtype)
matrix = kornia.quaternion_to_rotation_matrix(quaternion, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(matrix, expected, atol=atol, rtol=rtol)
def test_gradcheck_xyzw(self, device, dtype):
- quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
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
+ 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 = torch.tensor((0.0, 0.0, 0.0, 1.0), 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
+ 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):
op = kornia.geometry.conversions.quaternion_to_rotation_matrix
op_jit = torch.jit.script(op)
- quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
assert_allclose(op(quaternion), op_jit(quaternion))
@@ -625,14 +570,13 @@ class TestQuaternionToRotationMatrix:
def test_jit(self, device, dtype):
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)
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
assert_allclose(
op(quaternion, order=QuaternionCoeffOrder.WXYZ), op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ)
)
class TestQuaternionLogToExp:
-
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
quaternion_log = torch.zeros(batch_size, 3, device=device, dtype=dtype)
@@ -648,58 +592,58 @@ class TestQuaternionLogToExp:
def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- quaternion_log = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
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_log = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((1.0, 0.0, 0.0, 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_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)
+ one = torch.tensor(1.0, device=device, dtype=dtype)
+ quaternion_log = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((torch.sin(one), 0.0, 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)
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)
+ one = torch.tensor(1.0, device=device, dtype=dtype)
+ quaternion_log = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((torch.cos(one), torch.sin(one), 0.0, 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)
+ one = torch.tensor(1.0, device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0.0, 1.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 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)
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)
+ one = torch.tensor(1.0, device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0.0, 1.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((torch.cos(one), 0.0, 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_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)
+ one = torch.tensor(1.0, device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 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)
@@ -707,15 +651,15 @@ class TestQuaternionLogToExp:
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)
+ one = torch.tensor(1.0, device=device, dtype=dtype)
+ quaternion_log = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
+ expected = torch.tensor((torch.cos(one), 0.0, 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):
eps = torch.finfo(dtype).eps
- quaternion_log = torch.tensor((1., 0., 0.), device=device, dtype=dtype)
+ quaternion_log = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
quaternion_exp = kornia.quaternion_log_to_exp(quaternion_log, eps=eps, order=QuaternionCoeffOrder.XYZW)
@@ -725,7 +669,7 @@ class TestQuaternionLogToExp:
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_log = torch.tensor((1.0, 0.0, 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)
@@ -733,30 +677,32 @@ class TestQuaternionLogToExp:
def test_gradcheck_xyzw(self, device, dtype):
eps = torch.finfo(dtype).eps
- quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
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
+ 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 = torch.tensor((0.0, 0.0, 1.0), 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
+ 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):
op = kornia.geometry.conversions.quaternion_log_to_exp
op_jit = torch.jit.script(op)
- quaternion = torch.tensor((0., 0., 1.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
assert_allclose(
op(quaternion, order=QuaternionCoeffOrder.XYZW), op_jit(quaternion, order=QuaternionCoeffOrder.XYZW)
@@ -766,14 +712,13 @@ class TestQuaternionLogToExp:
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)
+ quaternion = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype)
assert_allclose(
op(quaternion, order=QuaternionCoeffOrder.WXYZ), op_jit(quaternion, order=QuaternionCoeffOrder.WXYZ)
)
class TestQuaternionExpToLog:
-
@pytest.mark.parametrize("batch_size", (1, 3, 8))
def test_smoke_batch_xyzw(self, batch_size, device, dtype):
eps = torch.finfo(dtype).eps
@@ -791,67 +736,67 @@ class TestQuaternionExpToLog:
def test_unit_quaternion_xyzw(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., 0.), device=device, dtype=dtype)
+ quaternion_exp = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.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)
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_exp = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, 0.0), device=device, dtype=dtype)
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):
eps = torch.finfo(dtype).eps
- quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((kornia.pi / 2., 0., 0.), device=device, dtype=dtype)
+ quaternion_exp = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi / 2.0, 0.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)
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_exp = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((kornia.pi / 2.0, 0.0, 0.0), device=device, dtype=dtype)
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):
eps = torch.finfo(dtype).eps
- quaternion_exp = torch.tensor((0., 1., 0., 0.), device=device, dtype=dtype)
- expected = torch.tensor((0., kornia.pi / 2., 0.), device=device, dtype=dtype)
+ quaternion_exp = torch.tensor((0.0, 1.0, 0.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, kornia.pi / 2.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)
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_exp = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, kornia.pi / 2.0, 0.0), device=device, dtype=dtype)
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):
eps = torch.finfo(dtype).eps
- quaternion_exp = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
- expected = torch.tensor((0., 0., kornia.pi / 2.), device=device, dtype=dtype)
+ quaternion_exp = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.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)
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_exp = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
+ expected = torch.tensor((0.0, 0.0, kornia.pi / 2.0), device=device, dtype=dtype)
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):
eps = torch.finfo(dtype).eps
- quaternion_exp = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ quaternion_exp = torch.tensor((1.0, 0.0, 0.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)
@@ -861,37 +806,39 @@ class TestQuaternionExpToLog:
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_exp = torch.tensor((0.0, 1.0, 0.0, 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)
assert_allclose(quaternion_exp, quaternion_exp_hat, atol=atol, rtol=rtol)
def test_gradcheck_xyzw(self, device, dtype):
eps = torch.finfo(dtype).eps
- quaternion = torch.tensor((1., 0., 0., 0.), device=device, dtype=dtype)
+ quaternion = torch.tensor((1.0, 0.0, 0.0, 0.0), device=device, dtype=dtype)
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
+ 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 = torch.tensor((0.0, 1.0, 0.0, 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
+ 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):
op = kornia.geometry.conversions.quaternion_exp_to_log
op_jit = torch.jit.script(op)
- quaternion = torch.tensor((0., 0., 1., 0.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 1.0, 0.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
assert_allclose(op(quaternion), op_jit(quaternion), atol=atol, rtol=rtol)
@@ -900,14 +847,13 @@ class TestQuaternionExpToLog:
op = kornia.quaternion_exp_to_log
op_script = torch.jit.script(op)
- quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
actual = op_script(quaternion, eps=torch.finfo(dtype).eps, order=QuaternionCoeffOrder.WXYZ)
expected = op(quaternion, eps=torch.finfo(dtype).eps, order=QuaternionCoeffOrder.WXYZ)
assert_allclose(actual, expected, atol=atol, rtol=rtol)
class TestAngleAxisToRotationMatrix:
-
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_rand_angle_axis_gradcheck(self, batch_size, device, dtype, atol, rtol):
# generate input data
@@ -922,26 +868,28 @@ 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)
+ (-0.30382753, -0.95095137, -0.05814062),
+ (-0.71581715, 0.26812278, -0.64476041),
+ (0.62872461, -0.15427791, -0.76217038),
),
device=device,
- dtype=dtype
+ 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)
+ (0.6027768, -0.79275544, -0.09054801),
+ (-0.67915707, -0.56931658, 0.46327563),
+ (-0.41881476, -0.21775548, -0.88157628),
),
device=device,
- dtype=dtype
+ 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)
@@ -951,7 +899,6 @@ class TestAngleAxisToRotationMatrix:
class TestRotationMatrixToAngleAxis:
-
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_rand_quaternion_gradcheck(self, batch_size, device, dtype, atol, rtol):
# generate input data
@@ -962,30 +909,32 @@ class TestRotationMatrixToAngleAxis:
eye_batch = create_eye_batch(batch_size, 3, device=device, dtype=dtype)
rotation_matrix_eye = torch.matmul(rotation_matrix, rotation_matrix.transpose(-2, -1))
# This didn't pass with atol=0.001, rtol=0.001 for float16 Cuda 11.2 GeForce 1080 Ti
- assert_allclose(rotation_matrix_eye, eye_batch, atol=atol * 10., rtol=rtol * 10.)
+ assert_allclose(rotation_matrix_eye, eye_batch, atol=atol * 10.0, rtol=rtol * 10.0)
# 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)
+ (-0.30382753, -0.95095137, -0.05814062),
+ (-0.71581715, 0.26812278, -0.64476041),
+ (0.62872461, -0.15427791, -0.76217038),
),
device=device,
- dtype=dtype
+ 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)
+ (0.6027768, -0.79275544, -0.09054801),
+ (-0.67915707, -0.56931658, 0.46327563),
+ (-0.41881476, -0.21775548, -0.88157628),
),
device=device,
- dtype=dtype
+ 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)
@@ -998,12 +947,7 @@ def test_pi():
assert_allclose(kornia.pi, 3.141592)
[email protected]("batch_shape", [
- (2, 3),
- (1, 2, 3),
- (2, 3, 3),
- (5, 5, 3),
-])
[email protected]("batch_shape", [(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)
@@ -1016,18 +960,13 @@ 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)
[email protected]("batch_shape", [
- (2, 3),
- (1, 2, 3),
- (2, 3, 3),
- (5, 5, 3),
-])
[email protected]("batch_shape", [(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)
+ x_deg = 180.0 * torch.rand(batch_shape, device=device, dtype=dtype)
# convert radians/degrees
x_rad = kornia.deg2rad(x_deg)
@@ -1036,22 +975,16 @@ 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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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)
@@ -1067,18 +1000,10 @@ class TestPolCartConversions:
assert_allclose(phi, phi_pol2cart)
assert gradcheck(
- kornia.pol2cart, (
- tensor_to_gradcheck_var(rho),
- tensor_to_gradcheck_var(phi),
- ), raise_exception=True
+ 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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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)
@@ -1094,37 +1019,29 @@ class TestPolCartConversions:
assert_allclose(y, y_cart2pol)
assert gradcheck(
- kornia.cart2pol, (
- tensor_to_gradcheck_var(x),
- tensor_to_gradcheck_var(y),
- ), raise_exception=True
+ 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
+ [[1.0, 2.0, 1.0], [0.0, 1.0, 2.0], [2.0, 1.0, 0.0], [-1.0, -2.0, -1.0], [0.0, 1.0, -2.0]],
+ 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.],
+ [1.0, 2.0, 1.0, 1.0],
+ [0.0, 1.0, 2.0, 1.0],
+ [2.0, 1.0, 0.0, 1.0],
+ [-1.0, -2.0, -1.0, 1.0],
+ [0.0, 1.0, -2.0, 1.0],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# to euclidean
@@ -1133,40 +1050,23 @@ class TestConvertPointsToHomogeneous:
def test_convert_points_batch(self, device, dtype):
# generate input data
- points_h = torch.tensor([[
- [2., 1., 0.],
- ], [
- [0., 1., 2.],
- ], [
- [0., 1., -2.],
- ]], device=device, dtype=dtype)
+ points_h = torch.tensor([[[2.0, 1.0, 0.0]], [[0.0, 1.0, 2.0]], [[0.0, 1.0, -2.0]]], device=device, dtype=dtype)
expected = torch.tensor(
- [[
- [2., 1., 0., 1.],
- ], [
- [0., 1., 2., 1.],
- ], [
- [0., 1., -2., 1.],
- ]], device=device, dtype=dtype
+ [[[2.0, 1.0, 0.0, 1.0]], [[0.0, 1.0, 2.0, 1.0]], [[0.0, 1.0, -2.0, 1.0]]], 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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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
@@ -1176,19 +1076,13 @@ class TestConvertPointsToHomogeneous:
class TestConvertAtoH:
-
def test_convert_points(self, device, dtype):
# generate input data
- A = torch.tensor([
- [1., 0., 0.],
- [0., 1., 0.],
- ], device=device, dtype=dtype).view(1, 2, 3)
+ A = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(1, 2, 3)
- expected = torch.tensor([
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ], device=device, dtype=dtype).view(1, 3, 3)
+ expected = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype).view(
+ 1, 3, 3
+ )
# to euclidean
H = kornia.geometry.conversions.convert_affinematrix_to_homography(A)
@@ -1200,7 +1094,7 @@ class TestConvertAtoH:
# 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
@@ -1210,37 +1104,23 @@ class TestConvertAtoH:
class TestConvertPointsFromHomogeneous:
-
- @pytest.mark.parametrize("batch_shape", [
- (2, 3),
- (1, 2, 3),
- (2, 3, 3),
- (5, 5, 3),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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
+ [[1.0, 2.0, 1.0], [0.0, 1.0, 2.0], [2.0, 1.0, 0.0], [-1.0, -2.0, -1.0], [0.0, 1.0, -2.0]],
+ device=device,
+ dtype=dtype,
)
- expected = torch.tensor([
- [1., 2.],
- [0., 0.5],
- [2., 1.],
- [1., 2.],
- [0., -0.5],
- ], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[1.0, 2.0], [0.0, 0.5], [2.0, 1.0], [1.0, 2.0], [0.0, -0.5]], device=device, dtype=dtype
+ )
# to euclidean
points = kornia.convert_points_from_homogeneous(points_h)
@@ -1248,21 +1128,9 @@ class TestConvertPointsFromHomogeneous:
def test_points_batch(self, device, dtype):
# generate input data
- points_h = torch.tensor([[
- [2., 1., 0.],
- ], [
- [0., 1., 2.],
- ], [
- [0., 1., -2.],
- ]], device=device, dtype=dtype)
-
- expected = torch.tensor([[
- [2., 1.],
- ], [
- [0., 0.5],
- ], [
- [0., -0.5],
- ]], device=device, dtype=dtype)
+ points_h = torch.tensor([[[2.0, 1.0, 0.0]], [[0.0, 1.0, 2.0]], [[0.0, 1.0, -2.0]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[2.0, 1.0]], [[0.0, 0.5]], [[0.0, -0.5]]], device=device, dtype=dtype)
# to euclidean
points = kornia.convert_points_from_homogeneous(points_h)
@@ -1273,20 +1141,16 @@ 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):
# generate input data
- points_h = torch.tensor([
- [1., 2., 0.],
- [0., 1., 0.1],
- [2., 1., 0.1],
- ], device=device, dtype=dtype)
+ points_h = torch.tensor([[1.0, 2.0, 0.0], [0.0, 1.0, 0.1], [2.0, 1.0, 0.1]], device=device, dtype=dtype)
# 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
@@ -1296,14 +1160,14 @@ 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)
- 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)
@@ -1315,8 +1179,9 @@ class TestNormalizePixelCoordinates:
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)
@@ -1336,13 +1201,13 @@ 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)
- 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)
@@ -1353,8 +1218,9 @@ class TestDenormalizePixelCoordinates:
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)
diff --git a/test/geometry/test_depth.py b/test/geometry/test_depth.py
index 11c865afe..253566c26 100644
--- a/test/geometry/test_depth.py
+++ b/test/geometry/test_depth.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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)
@@ -35,43 +34,21 @@ 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
+ [[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], device=device, dtype=dtype
)
- camera_matrix = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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.],
- ]
+ [[0.0, 2.0, 4.0], [0.0, 2.0, 4.0], [0.0, 2.0, 4.0], [0.0, 2.0, 4.0]],
+ [[0.0, 0.0, 0.0], [2.0, 2.0, 2.0], [4.0, 4.0, 4.0], [6.0, 6.0, 6.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]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
points3d = kornia.depth_to_3d(depth, camera_matrix) # default is normalize_points=False
@@ -80,19 +57,10 @@ class TestDepthTo3d:
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
+ [[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], device=device, dtype=dtype
)
- camera_matrix = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
points3d_expected = torch.tensor(
[
@@ -114,11 +82,11 @@ class TestDepthTo3d:
[1.4142, 1.1547, 0.8165],
[0.8944, 0.8165, 0.6667],
[0.6325, 0.6030, 0.5345],
- ]
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
points3d = kornia.depth_to_3d(depth, camera_matrix, normalize_points=True)
@@ -126,19 +94,10 @@ class TestDepthTo3d:
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
+ [[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], device=device, dtype=dtype
)
- camera_matrix = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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])
@@ -154,14 +113,10 @@ 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)
@@ -188,43 +143,21 @@ 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
+ [[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], device=device, dtype=dtype
)
- camera_matrix = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], 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.],
- ]
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[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]],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
normals = kornia.depth_to_normals(depth, camera_matrix) # default is normalize_points=False
@@ -233,19 +166,10 @@ class TestDepthToNormals:
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
+ [[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], device=device, dtype=dtype
)
- camera_matrix = torch.tensor([[
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
normals_expected = torch.tensor(
[
@@ -267,11 +191,11 @@ class TestDepthToNormals:
[0.8253, 0.7981, 0.6415],
[0.5432, 0.5807, 0.5105],
[0.4129, 0.4824, 0.4784],
- ]
+ ],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
normals = kornia.depth_to_normals(depth, camera_matrix, normalize_points=True)
@@ -286,14 +210,10 @@ 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)
@@ -317,46 +237,26 @@ 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
+ [[[[1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]]], device=device, dtype=dtype
)
depth_dst = torch.tensor(
- [[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype
+ [[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], 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
+ [[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
)
h, w = image_src.shape[-2:]
- camera_matrix = torch.tensor([[
- [1., 0., w / 2],
- [0., 1., h / 2],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor(
+ [[[1.0, 0.0, w / 2], [0.0, 1.0, h / 2], [0.0, 0.0, 1.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
+ [[[[2.0, 3.0, 0.0], [2.0, 3.0, 0.0], [2.0, 3.0, 0.0], [2.0, 3.0, 0.0]]]], device=device, dtype=dtype
)
image_dst = kornia.warp_frame_depth(
@@ -367,38 +267,23 @@ class TestWarpFrameDepth:
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
+ [[[[1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]]], device=device, dtype=dtype
)
depth_dst = torch.tensor(
- [[[
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- [1., 1., 1.],
- ]]], device=device, dtype=dtype
+ [[[[1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0], [1.0, 1.0, 1.0]]]], 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
+ [[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
)
h, w = image_src.shape[-2:]
- camera_matrix = torch.tensor([[
- [1., 0., w / 2],
- [0., 1., h / 2],
- [0., 0., 1.],
- ]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor(
+ [[[1.0, 0.0, w / 2], [0.0, 1.0, h / 2], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ )
image_dst_expected = torch.tensor(
[
@@ -412,7 +297,7 @@ class TestWarpFrameDepth:
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
image_dst = kornia.warp_frame_depth(image_src, depth_dst, src_trans_dst, camera_matrix, normalize_points=True)
@@ -433,10 +318,5 @@ class TestWarpFrameDepth:
# evaluate function gradient
assert gradcheck(
- kornia.warp_frame_depth, (
- image_src,
- depth_dst,
- src_trans_dst,
- camera_matrix,
- ), raise_exception=True
+ 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 b5391d65f..5946d8728 100644
--- a/test/geometry/test_depth_warper.py
+++ b/test/geometry/test_depth_warper.py
@@ -13,7 +13,7 @@ class TestDepthWarper:
def _create_pinhole_pair(self, batch_size, device, dtype):
# prepare data
- fx, fy = 1., 1.
+ fx, fy = 1.0, 1.0
height, width = 3, 5
cx, cy = width / 2, height / 2
tx, ty, tz = 0, 0, 0
@@ -27,14 +27,11 @@ class TestDepthWarper:
)
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)
- pinhole_dst.tx += 1. # apply offset to tx
+ pinhole_dst.tx += 1.0 # apply offset to tx
# create warper
warper = kornia.DepthWarper(pinhole_dst, height, width)
@@ -49,17 +46,14 @@ class TestDepthWarper:
dst_proj_src_expected = torch.eye(4, device=device, dtype=dtype)[None].repeat(batch_size, 1, 1) # Bx4x4
dst_proj_src_expected[..., 0, -2] += pinhole_src.cx
dst_proj_src_expected[..., 1, -2] += pinhole_src.cy
- dst_proj_src_expected[..., 0, -1] += 1. # offset to x-axis
+ dst_proj_src_expected[..., 0, -1] += 1.0 # 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)
- pinhole_dst.tx += 1. # apply offset to tx
+ pinhole_dst.tx += 1.0 # apply offset to tx
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)
@@ -80,15 +74,12 @@ class TestDepthWarper:
# 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)
- @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)
- pinhole_dst.tx += 1. # apply offset to tx
- pinhole_dst.ty += 1. # apply offset to ty
+ pinhole_dst.tx += 1.0 # apply offset to tx
+ pinhole_dst.ty += 1.0 # apply offset to ty
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)
@@ -111,15 +102,12 @@ class TestDepthWarper:
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)
- pinhole_dst.tx += 1. # apply offset to tx
- pinhole_dst.ty += 1. # apply offset to ty
+ pinhole_dst.tx += 1.0 # apply offset to tx
+ pinhole_dst.ty += 1.0 # apply offset to ty
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width, device=device, dtype=dtype)
@@ -129,8 +117,11 @@ 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)
@@ -138,10 +129,7 @@ class TestDepthWarper:
# compare patches
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)
@@ -154,10 +142,7 @@ 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)
@@ -186,14 +171,7 @@ class TestDepthWarper:
# evaluate function gradient
assert gradcheck(
- kornia.depth_warp, (
- pinhole_dst,
- pinhole_src,
- depth_src,
- img_dst,
- height,
- width,
- ), raise_exception=True
+ 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
diff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.py
index dcbafe625..7401604bc 100644
--- a/test/geometry/test_homography.py
+++ b/test/geometry/test_homography.py
@@ -10,7 +10,6 @@ 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)
@@ -18,10 +17,7 @@ class TestFindHomographyDLT:
H = find_homography_dlt(points1, points2, weights)
assert H.shape == (1, 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(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
@@ -30,10 +26,7 @@ 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)
@@ -41,10 +34,7 @@ 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)
@@ -96,14 +86,15 @@ class TestFindHomographyDLT:
# All iterations failed
if i == max_number_of_checks - 1:
assert gradcheck(
- find_homography_dlt, (points_src, points_dst, weights),
+ find_homography_dlt,
+ (points_src, points_dst, weights),
rtol=1e-6,
atol=1e-6,
- raise_exception=True
+ raise_exception=True,
)
# Next iteration
else:
- current_seed = random.randrange(0xffffffffffffffff)
+ current_seed = random.randrange(0xFFFFFFFFFFFFFFFF)
continue
# Gradcheck succeed
@@ -112,7 +103,6 @@ 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)
@@ -120,10 +110,7 @@ class TestFindHomographyDLTIter:
H = find_homography_dlt_iterated(points1, points2, weights, 5)
assert H.shape == (1, 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(self, batch_size, num_points, device, dtype):
B, N = batch_size, num_points
points1 = torch.rand(B, N, 2, device=device, dtype=dtype)
@@ -165,10 +152,11 @@ class TestFindHomographyDLTIter:
weights = torch.ones_like(points_src)[..., 0]
try:
gradcheck(
- find_homography_dlt_iterated, (points_src, points_dst, weights),
+ find_homography_dlt_iterated,
+ (points_src, points_dst, weights),
rtol=1e-6,
atol=1e-6,
- raise_exception=True
+ raise_exception=True,
)
# Gradcheck failed
@@ -177,14 +165,15 @@ class TestFindHomographyDLTIter:
# All iterations failed
if i == max_number_of_checks - 1:
assert gradcheck(
- find_homography_dlt_iterated, (points_src, points_dst, weights),
+ find_homography_dlt_iterated,
+ (points_src, points_dst, weights),
rtol=1e-6,
atol=1e-6,
- raise_exception=True
+ raise_exception=True,
)
# Next iteration
else:
- current_seed = random.randrange(0xffffffffffffffff)
+ current_seed = random.randrange(0xFFFFFFFFFFFFFFFF)
continue
# Gradcheck succeed
@@ -200,7 +189,7 @@ class TestFindHomographyDLTIter:
H = H * 0.3 * torch.rand_like(H)
H = H / H[:, 2:3, 2:3]
- points_src = 100. * torch.rand(batch_size, 20, 2, device=device, dtype=dtype)
+ points_src = 100.0 * torch.rand(batch_size, 20, 2, device=device, dtype=dtype)
points_dst = kornia.transform_points(H, points_src)
# making last point an outlier
diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.py
index 4472c8311..bd7acc4f0 100644
--- a/test/geometry/test_linalg.py
+++ b/test/geometry/test_linalg.py
@@ -19,31 +19,68 @@ 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,
+ ones,
+ zeros,
+ zeros,
+ zeros,
+ zeros,
+ torch.cos(x),
+ -torch.sin(x),
+ zeros,
+ zeros,
torch.sin(x),
- torch.cos(x), zeros, zeros, zeros, zeros, ones
+ 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.cos(z),
+ -torch.sin(z),
+ zeros,
+ zeros,
torch.sin(z),
- torch.cos(z), zeros, zeros, zeros, zeros, ones, zeros, zeros, zeros, zeros, ones
+ 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
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])
@@ -74,10 +111,7 @@ 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)
@@ -90,14 +124,13 @@ class TestTransformPoints:
class TestTransformBoxes:
-
def test_transform_boxes(self, device, dtype):
boxes = torch.tensor([[139.2640, 103.0150, 397.3120, 410.5225]], device=device, dtype=dtype)
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, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
out = kornia.transform_boxes(trans_mat, boxes)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -106,11 +139,13 @@ class TestTransformBoxes:
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]
+ [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
+ dtype=dtype,
)
boxes = boxes.repeat(2, 1, 1) # 2 x 4 x 4 two images 4 boxes each
@@ -118,22 +153,29 @@ class TestTransformBoxes:
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]
+ [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]
- ]
+ [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
+ dtype=dtype,
)
trans_mat = torch.tensor(
- [[[-1., 0., 512.], [0., 1., 0.], [0., 0., 1.]], [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]],
+ [
+ [[-1.0, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
+ [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
)
out = kornia.transform_boxes(trans_mat, boxes)
@@ -143,23 +185,27 @@ class TestTransformBoxes:
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]
+ [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
+ 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]
+ [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
+ 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, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
out = kornia.transform_boxes(trans_mat, boxes, mode='xywh')
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -168,14 +214,16 @@ class TestTransformBoxes:
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]
+ [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
+ 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, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
trans_mat = utils.tensor_to_gradcheck_var(trans_mat)
boxes = utils.tensor_to_gradcheck_var(boxes)
@@ -184,7 +232,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, 0.0, 512.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
args = (boxes, trans_mat)
op = kornia.geometry.transform_points
op_jit = torch.jit.script(op)
@@ -192,7 +240,6 @@ class TestTransformBoxes:
class TestComposeTransforms:
-
def test_translation_4x4(self, device, dtype):
offset = 10
trans_01 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]
@@ -219,14 +266,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:
-
def test_translation_4x4(self, device, dtype):
offset = 10
trans_01 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]
@@ -265,13 +308,12 @@ 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:
-
def test_translation_4x4(self, device, dtype):
- offset = 10.
+ offset = 10.0
trans_01 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]
trans_02 = identity_matrix(batch_size=1, device=device, dtype=dtype)[0]
trans_02[..., :3, -1] += offset # add offset to translation vector
@@ -282,8 +324,8 @@ class TestRelativeTransformation:
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_rotation_translation_Bx4x4(self, batch_size, device, dtype):
- offset = 10.
- x, y, z = 0., 0., kornia.pi
+ offset = 10.0
+ x, y, z = 0.0, 0.0, kornia.pi
ones = torch.ones(batch_size, device=device, dtype=dtype)
rmat_02 = euler_angles_to_rotation_matrix(x * ones, y * ones, z * ones)
@@ -303,14 +345,10 @@ 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):
@@ -339,7 +377,4 @@ 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 2aad93c10..0cd0049bb 100644
--- a/test/geometry/test_perspective.py
+++ b/test/geometry/test_perspective.py
@@ -7,7 +7,6 @@ from kornia.testing import tensor_to_gradcheck_var
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)
@@ -27,14 +26,10 @@ class TestProjectPoints:
assert point_2d.shape == (2, 4, 2)
def test_project_and_unproject(self, device, dtype):
- point_3d = torch.tensor([[10., 2., 30.]], device=device, dtype=dtype)
+ point_3d = torch.tensor([[10.0, 2.0, 30.0]], 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
+ [[[2746.0, 0.0, 991.0], [0.0, 2748.0, 619.0], [0.0, 0.0, 1.0]]], 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)
@@ -59,7 +54,6 @@ 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)
@@ -82,37 +76,25 @@ class TestUnprojectPoints:
assert point_3d.shape == (2, 3, 3)
def test_unproject_center(self, device, dtype):
- point_2d = torch.tensor([[0., 0.]], device=device, dtype=dtype)
- depth = torch.tensor([[2.]], device=device, dtype=dtype)
- camera_matrix = torch.tensor([
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ], device=device, dtype=dtype)
- expected = torch.tensor([[0., 0., 2.]], device=device, dtype=dtype)
+ point_2d = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
+ depth = torch.tensor([[2.0]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.0, 0.0, 2.0]], device=device, dtype=dtype)
actual = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix)
assert_allclose(actual, expected, atol=1e-4, rtol=1e-4)
def test_unproject_center_normalize(self, device, dtype):
- point_2d = torch.tensor([[0., 0.]], device=device, dtype=dtype)
- depth = torch.tensor([[2.]], device=device, dtype=dtype)
- camera_matrix = torch.tensor([
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ], device=device, dtype=dtype)
- expected = torch.tensor([[0., 0., 2.]], device=device, dtype=dtype)
+ point_2d = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
+ depth = torch.tensor([[2.0]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.0, 0.0, 2.0]], device=device, dtype=dtype)
actual = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix, True)
assert_allclose(actual, expected, atol=1e-4, rtol=1e-4)
def test_unproject_and_project(self, device, dtype):
- point_2d = torch.tensor([[0., 0.]], device=device, dtype=dtype)
- depth = torch.tensor([[2.]], device=device, dtype=dtype)
- camera_matrix = torch.tensor([
- [1., 0., 0.],
- [0., 1., 0.],
- [0., 0., 1.],
- ], device=device, dtype=dtype)
+ point_2d = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
+ depth = torch.tensor([[2.0]], device=device, dtype=dtype)
+ camera_matrix = torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
point_3d = kornia.geometry.camera.unproject_points(point_2d, depth, camera_matrix)
point_2d_hat = kornia.geometry.camera.project_points(point_3d, camera_matrix)
assert_allclose(point_2d, point_2d_hat, atol=1e-4, rtol=1e-4)
diff --git a/test/geometry/test_pinhole.py b/test/geometry/test_pinhole.py
index 7e167528a..4c6aeed2b 100644
--- a/test/geometry/test_pinhole.py
+++ b/test/geometry/test_pinhole.py
@@ -5,7 +5,6 @@ import kornia as kornia
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
@@ -75,22 +74,22 @@ class TestPinholeCamera:
assert pinhole.tz.item() == tz
# add offset
- pinhole.tx += 3.
- pinhole.ty += 2.
- pinhole.tz += 1.
+ pinhole.tx += 3.0
+ pinhole.ty += 2.0
+ pinhole.tz += 1.0
- assert pinhole.tx.item() == tx + 3.
- assert pinhole.ty.item() == ty + 2.
- assert pinhole.tz.item() == tz + 1.
+ assert pinhole.tx.item() == tx + 3.0
+ assert pinhole.ty.item() == ty + 2.0
+ assert pinhole.tz.item() == tz + 1.0
# set to zero
- pinhole.tx = 0.
- pinhole.ty = 0.
- pinhole.tz = 0.
+ pinhole.tx = 0.0
+ pinhole.ty = 0.0
+ pinhole.tz = 0.0
- assert pinhole.tx.item() == 0.
- assert pinhole.ty.item() == 0.
- assert pinhole.tz.item() == 0.
+ assert pinhole.tx.item() == 0.0
+ assert pinhole.ty.item() == 0.0
+ assert pinhole.tz.item() == 0.0
def test_pinhole_camera_attributes_batch2(self, device, dtype):
batch_size = 2
diff --git a/test/geometry/transform/crop/test_crop2d.py b/test/geometry/transform/crop/test_crop2d.py
index 0c975b263..039bcbd94 100644
--- a/test/geometry/transform/crop/test_crop2d.py
+++ b/test/geometry/transform/crop/test_crop2d.py
@@ -7,58 +7,32 @@ import kornia.testing as utils # test utils
class TestBoundingBoxInferring:
-
def test_bounding_boxes_dim_inferring(self, device, dtype):
- boxes = torch.tensor([[
- [1., 1.],
- [3., 1.],
- [3., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype)
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
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.],
- ]],
+ [[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]], [[2.0, 2.0], [4.0, 2.0], [4.0, 3.0], [2.0, 3.0]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
assert (h.unique().item(), w.unique().item()) == (2, 3)
def test_gradcheck(self, device, dtype):
- boxes = torch.tensor([[
- [1., 1.],
- [3., 1.],
- [3., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype)
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], 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
op = kornia.geometry.transform.crop.infer_box_shape
op_script = torch.jit.script(op)
# Define input
- boxes = torch.tensor([[
- [1., 1.],
- [3., 1.],
- [3., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype)
+ boxes = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype)
actual = op_script(boxes)
expected = op(boxes)
@@ -66,29 +40,18 @@ 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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ 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)
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype) # 1x4x2
+ boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
# default should use align_coners True
patches = kornia.crop_and_resize(inp, boxes, (height, width))
@@ -96,25 +59,15 @@ class TestCropAndResize:
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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ 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)
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype) # 1x4x2
+ boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
patches = kornia.crop_and_resize(inp, boxes, (height, width), align_corners=False)
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
@@ -122,44 +75,21 @@ class TestCropAndResize:
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.],
- ]]
+ [[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]],
+ [[[1.0, 5.0, 9.0, 13.0], [2.0, 6.0, 10.0, 14.0], [3.0, 7.0, 11.0, 15.0], [4.0, 8.0, 12.0, 16.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- expected = torch.tensor([[[
- [6., 7.],
- [10., 11.],
- ]], [[
- [7., 15.],
- [8., 16.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor(
+ [[[[6.0, 7.0], [10.0, 11.0]]], [[[7.0, 15.0], [8.0, 16.0]]]], device=device, dtype=dtype
+ )
boxes = torch.tensor(
- [[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ], [
- [1., 2.],
- [3., 2.],
- [3., 3.],
- [1., 3.],
- ]],
+ [[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]], [[1.0, 2.0], [3.0, 2.0], [3.0, 3.0], [1.0, 3.0]]],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 2x4x2
patches = kornia.crop_and_resize(inp, boxes, (2, 2))
@@ -168,36 +98,18 @@ class TestCropAndResize:
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.],
- ]]
+ [[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]],
+ [[[1.0, 5.0, 9.0, 13.0], [2.0, 6.0, 10.0, 14.0], [3.0, 7.0, 11.0, 15.0], [4.0, 8.0, 12.0, 16.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- expected = torch.tensor([[[
- [6., 7.],
- [10., 11.],
- ]], [[
- [6., 10.],
- [7., 11.],
- ]]], device=device, dtype=dtype)
-
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype) # 1x4x2
+ expected = torch.tensor(
+ [[[[6.0, 7.0], [10.0, 11.0]]], [[[6.0, 10.0], [7.0, 11.0]]]], device=device, dtype=dtype
+ )
+
+ boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
patches = kornia.crop_and_resize(inp, boxes, (2, 2))
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
@@ -206,19 +118,10 @@ class TestCropAndResize:
img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
img = utils.tensor_to_gradcheck_var(img) # to var
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype) # 1x4x2
+ boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], 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
@@ -226,21 +129,11 @@ class TestCropAndResize:
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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype) # 1x4x2
+ boxes = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
crop_height, crop_width = 4, 2
actual = op_script(img, boxes, (crop_height, crop_width))
@@ -249,46 +142,27 @@ 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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- expected = torch.tensor([[[
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0]]]], device=device, dtype=dtype)
out_crop = kornia.center_crop(inp, (2, 4))
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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
height, width = 4, 2
- expected = torch.tensor([[[
- [2., 3.],
- [6., 7.],
- [10., 11.],
- [14., 15.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[2.0, 3.0], [6.0, 7.0], [10.0, 11.0], [14.0, 15.0]]]], device=device, dtype=dtype)
out_crop = kornia.center_crop(inp, (height, width))
assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)
@@ -296,27 +170,20 @@ class TestCenterCrop:
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.]]]
+ [[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]],
+ [[[1.0, 5.0, 9.0, 13.0], [2.0, 6.0, 10.0, 14.0], [3.0, 7.0, 11.0, 15.0], [4.0, 8.0, 12.0, 16.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
expected = torch.tensor(
- [[[
- [2., 3.],
- [6., 7.],
- [10., 11.],
- [14., 15.],
- ]], [[
- [5., 9.],
- [6., 10.],
- [7., 11.],
- [8., 12.],
- ]]],
+ [
+ [[[2.0, 3.0], [6.0, 7.0], [10.0, 11.0], [14.0, 15.0]]],
+ [[[5.0, 9.0], [6.0, 10.0], [7.0, 11.0], [8.0, 12.0]]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
)
out_crop = kornia.center_crop(inp, (4, 2))
@@ -326,10 +193,7 @@ 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
@@ -357,157 +221,89 @@ 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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- src = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype) # 1x4x2
-
- dst = torch.tensor([[
- [0., 0.],
- [1., 0.],
- [1., 1.],
- [0., 1.],
- ]], device=device, dtype=dtype) # 1x4x2
-
- expected = torch.tensor([[[
- [6., 7.],
- [10., 11.],
- ]]], device=device, dtype=dtype)
+ src = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
+
+ dst = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype) # 1x4x2
+
+ expected = torch.tensor([[[[6.0, 7.0], [10.0, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst)
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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- src = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]], device=device, dtype=dtype) # 1x4x2
-
- dst = torch.tensor([[
- [0., 0.],
- [2., 0.],
- [2., 1.],
- [0., 1.],
- ]], device=device, dtype=dtype) # 1x4x2
-
- expected = torch.tensor([[[
- [6., 6.5, 7.],
- [10., 10.5, 11.],
- ]]], device=device, dtype=dtype)
+ src = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], device=device, dtype=dtype) # 1x4x2
+
+ dst = torch.tensor([[[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype) # 1x4x2
+
+ expected = torch.tensor([[[[6.0, 6.5, 7.0], [10.0, 10.5, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst)
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
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, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype)
+ dst = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], 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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- transform = torch.tensor([[
- [1., 0., -1.],
- [0., 1., -1.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype) # 1x3x3
+ transform = torch.tensor(
+ [[[1.0, 0.0, -1.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ ) # 1x3x3
- expected = torch.tensor([[[
- [6., 7.],
- [10., 11.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[6.0, 7.0], [10.0, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop.crop_by_transform_mat(inp, transform, (2, 2))
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.],
- ]]],
+ [[[[1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], [9.0, 10.0, 11.0, 12.0], [13.0, 14.0, 15.0, 16.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
- transform = torch.tensor([[
- [2., 0., -2.],
- [0., 1., -1.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype) # 1x3x3
+ transform = torch.tensor(
+ [[[2.0, 0.0, -2.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ ) # 1x3x3
- expected = torch.tensor([[[
- [6., 6.5, 7.],
- [10., 10.5, 11.],
- ]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[6.0, 6.5, 7.0], [10.0, 10.5, 11.0]]]], device=device, dtype=dtype)
patches = kornia.geometry.transform.crop.crop_by_transform_mat(inp, transform, (2, 3))
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device, dtype):
inp = torch.randn((1, 1, 3, 3), device=device, dtype=dtype)
- transform = torch.tensor([[
- [2., 0., -2.],
- [0., 1., -1.],
- [0., 0., 1.],
- ]], device=device, dtype=dtype) # 1x3x3
+ transform = torch.tensor(
+ [[[2.0, 0.0, -2.0], [0.0, 1.0, -1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ ) # 1x3x3
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
+ 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 31da31d62..e2c797fdd 100644
--- a/test/geometry/transform/crop/test_crop3d.py
+++ b/test/geometry/transform/crop/test_crop3d.py
@@ -8,30 +8,29 @@ import kornia.testing as utils # test utils
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]]
+ [[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
+ 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))
- assert_allclose(h, torch.tensor([21., 51.], device=device, dtype=dtype))
- assert_allclose(w, torch.tensor([11., 41.], device=device, dtype=dtype))
+ assert_allclose(d, torch.tensor([31.0, 61.0], device=device, dtype=dtype))
+ assert_allclose(h, torch.tensor([21.0, 51.0], device=device, dtype=dtype))
+ assert_allclose(w, torch.tensor([11.0, 41.0], 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
+ 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
@@ -39,18 +38,9 @@ class TestBoundingBoxInferring3D:
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],
- ]],
+ [[[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
+ dtype=dtype,
) # 1x8x3
actual = op_script(boxes)
@@ -59,30 +49,20 @@ 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)
+ inp = torch.arange(0.0, 64.0, 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
+ 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, 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
+ dtype=dtype,
) # 1x8x3
patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width))
@@ -91,97 +71,58 @@ class TestCropAndResize3D:
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)
+ torch.arange(0.0, 64.0, device=device, dtype=dtype).view(1, 1, 4, 4, 4),
+ torch.arange(0.0, 128.0, step=2, device=device, dtype=dtype).view(1, 1, 4, 4, 4),
],
- dim=0
+ 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]]]]
+ [[[[0.0000, 6.0000], [16.0000, 22.0000]], [[64.0000, 70.0000], [80.0000, 86.0000]]]],
],
device=device,
- dtype=dtype
+ 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],
- ]
+ [[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
+ dtype=dtype,
) # 2x8x3
patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width), align_corners=True)
assert_allclose(patches, expected)
def test_gradcheck(self, device, dtype):
- img = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ img = torch.arange(0.0, 64.0, 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],
- ]],
+ [[[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
+ 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
op = kornia.crop_and_resize3d
op_script = torch.jit.script(op)
- img = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ img = torch.arange(0.0, 64.0, 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],
- ]],
+ [[[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
+ dtype=dtype,
) # 1x8x3
actual = op_script(img, boxes, (4, 3, 2))
@@ -190,13 +131,16 @@ 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)]
+ inp = torch.arange(0.0, 343.0, 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)
@@ -204,24 +148,25 @@ class TestCenterCrop3D:
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)
+ torch.arange(0.0, 343.0, device=device, dtype=dtype).view(1, 1, 7, 7, 7),
+ torch.arange(343.0, 686.0, 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)
def test_gradcheck(self, device, dtype):
- img = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ img = torch.arange(0.0, 343.0, 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
@@ -235,40 +180,39 @@ 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)
+ inp = torch.arange(0.0, 343.0, 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.],
+ [1.0, 1.0, 1.0],
+ [3.0, 1.0, 1.0],
+ [3.0, 3.0, 1.0],
+ [1.0, 3.0, 1.0],
+ [1.0, 1.0, 2.0],
+ [3.0, 1.0, 2.0],
+ [3.0, 3.0, 2.0],
+ [1.0, 3.0, 2.0],
]
],
device=device,
- dtype=dtype
+ 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.],
+ [0.0, 0.0, 0.0],
+ [2.0, 0.0, 0.0],
+ [2.0, 2.0, 0.0],
+ [0.0, 2.0, 0.0],
+ [0.0, 0.0, 1.0],
+ [2.0, 0.0, 1.0],
+ [2.0, 2.0, 1.0],
+ [0.0, 2.0, 1.0],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1x8x3
expected = inp[:, :, 1:3, 1:4, 1:4]
@@ -277,44 +221,44 @@ class TestCropByBoxes3D:
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_by_boxes_resizing(self, device, dtype):
- inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ inp = torch.arange(0.0, 343.0, 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.],
+ [1.0, 1.0, 1.0],
+ [3.0, 1.0, 1.0],
+ [3.0, 3.0, 1.0],
+ [1.0, 3.0, 1.0],
+ [1.0, 1.0, 2.0],
+ [3.0, 1.0, 2.0],
+ [3.0, 3.0, 2.0],
+ [1.0, 3.0, 2.0],
]
],
device=device,
- dtype=dtype
+ 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.],
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0],
+ [1.0, 0.0, 1.0],
+ [1.0, 1.0, 1.0],
+ [0.0, 1.0, 1.0],
]
],
device=device,
- dtype=dtype
+ 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
+ dtype=dtype,
)
patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)
@@ -329,34 +273,34 @@ class TestCropByBoxes3D:
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.],
+ [1.0, 1.0, 1.0],
+ [3.0, 1.0, 1.0],
+ [3.0, 3.0, 1.0],
+ [1.0, 3.0, 1.0],
+ [1.0, 1.0, 2.0],
+ [3.0, 1.0, 2.0],
+ [3.0, 3.0, 2.0],
+ [1.0, 3.0, 2.0],
]
],
device=device,
- dtype=dtype
+ 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.],
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0],
+ [1.0, 0.0, 1.0],
+ [1.0, 1.0, 1.0],
+ [0.0, 1.0, 1.0],
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 1x8x3
actual = op_script(inp, src_box, dst_box, align_corners=True)
@@ -368,42 +312,36 @@ class TestCropByBoxes3D:
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.],
+ [1.0, 1.0, 1.0],
+ [3.0, 1.0, 1.0],
+ [3.0, 3.0, 1.0],
+ [1.0, 3.0, 1.0],
+ [1.0, 1.0, 2.0],
+ [3.0, 1.0, 2.0],
+ [3.0, 3.0, 2.0],
+ [1.0, 3.0, 2.0],
]
],
device=device,
- dtype=dtype
+ 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.],
+ [0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.0],
+ [1.0, 1.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0],
+ [1.0, 0.0, 1.0],
+ [1.0, 1.0, 1.0],
+ [0.0, 1.0, 1.0],
]
],
device=device,
- dtype=dtype
+ 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 6a5c738e5..c8d4d1ff4 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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))
@@ -59,11 +58,10 @@ class TestResize:
new_size = 4
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.Resize(new_size), (input, ), raise_exception=True)
+ assert gradcheck(kornia.Resize(new_size), (input,), raise_exception=True)
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))
@@ -80,7 +78,7 @@ class TestRescale:
assert output.shape == (1, 3, 3, 4)
def test_downscale_values(self, device, dtype):
- inp_x = torch.arange(20, device=device, dtype=dtype) / 20.
+ inp_x = torch.arange(20, device=device, dtype=dtype) / 20.0
inp = inp_x[None].T @ inp_x[None]
inp = inp[None, None]
out = kornia.rescale(inp, (0.25, 0.25), antialias=False)
@@ -88,19 +86,21 @@ class TestRescale:
[
[
[
- [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]
+ [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
+ dtype=dtype,
)
assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
def test_downscale_values_AA(self, device, dtype):
- inp_x = torch.arange(20, device=device, dtype=dtype) / 20.
+ inp_x = torch.arange(20, device=device, dtype=dtype) / 20.0
inp = inp_x[None].T @ inp_x[None]
inp = inp[None, None]
out = kornia.rescale(inp, (0.25, 0.25), antialias=True)
@@ -108,14 +108,16 @@ class TestRescale:
[
[
[
- [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]
+ [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
+ dtype=dtype,
)
assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
@@ -127,103 +129,63 @@ class TestRescale:
def test_gradcheck(self, device, dtype):
input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input)
- assert gradcheck(kornia.Rescale(2.0), (input, ), raise_exception=True)
+ assert gradcheck(kornia.Rescale(2.0), (input,), raise_exception=True)
class TestRotate:
-
def test_angle90(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 2.],
- [3., 4.],
- [5., 6.],
- [7., 8.],
- ]], device=device, dtype=dtype)
- expected = torch.tensor([[
- [0., 0.],
- [4., 6.],
- [3., 5.],
- [0., 0.],
- ]], device=device, dtype=dtype)
+ inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[0.0, 0.0], [4.0, 6.0], [3.0, 5.0], [0.0, 0.0]]], device=device, dtype=dtype)
# prepare transformation
- angle = torch.tensor([90.], device=device, dtype=dtype)
+ angle = torch.tensor([90.0], device=device, dtype=dtype)
transform = kornia.Rotate(angle, align_corners=True)
assert_allclose(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_angle90_batch2(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 2.],
- [3., 4.],
- [5., 6.],
- [7., 8.],
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], 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.],
- ]]],
+ [[[[0.0, 0.0], [4.0, 6.0], [3.0, 5.0], [0.0, 0.0]]], [[[0.0, 0.0], [5.0, 3.0], [6.0, 4.0], [0.0, 0.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# prepare transformation
- angle = torch.tensor([90., -90.], device=device, dtype=dtype)
+ angle = torch.tensor([90.0, -90.0], device=device, dtype=dtype)
transform = kornia.Rotate(angle, align_corners=True)
assert_allclose(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_angle90_batch2_broadcast(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 2.],
- [3., 4.],
- [5., 6.],
- [7., 8.],
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], 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.],
- ]]],
+ [[[[0.0, 0.0], [4.0, 6.0], [3.0, 5.0], [0.0, 0.0]]], [[[0.0, 0.0], [4.0, 6.0], [3.0, 5.0], [0.0, 0.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# prepare transformation
- angle = torch.tensor([90.], device=device, dtype=dtype)
+ angle = torch.tensor([90.0], device=device, dtype=dtype)
transform = kornia.Rotate(angle, align_corners=True)
assert_allclose(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device, dtype):
# test parameters
- angle = torch.tensor([90.], device=device, dtype=dtype)
+ angle = torch.tensor([90.0], device=device, dtype=dtype)
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")
def test_jit(self, device, dtype):
- angle = torch.tensor([90.], device=device, dtype=dtype)
+ angle = torch.tensor([90.0], device=device, dtype=dtype)
batch_size, channels, height, width = 2, 3, 64, 64
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
rot = kornia.Rotate(angle)
@@ -232,99 +194,59 @@ class TestRotate:
class TestTranslate:
-
def test_dxdy(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 2.],
- [3., 4.],
- [5., 6.],
- [7., 8.],
- ]], device=device, dtype=dtype)
- expected = torch.tensor([[
- [0., 1.],
- [0., 3.],
- [0., 5.],
- [0., 7.],
- ]], device=device, dtype=dtype)
+ inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0], [0.0, 7.0]]], device=device, dtype=dtype)
# prepare transformation
- translation = torch.tensor([[1., 0.]], device=device, dtype=dtype)
+ translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
transform = kornia.Translate(translation, align_corners=True)
assert_allclose(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_dxdy_batch(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 2.],
- [3., 4.],
- [5., 6.],
- [7., 8.],
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], 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.],
- ]]],
+ [[[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0], [0.0, 7.0]]], [[[0.0, 0.0], [0.0, 1.0], [0.0, 3.0], [0.0, 5.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# prepare transformation
- translation = torch.tensor([[1., 0.], [1., 1.]], device=device, dtype=dtype)
+ translation = torch.tensor([[1.0, 0.0], [1.0, 1.0]], device=device, dtype=dtype)
transform = kornia.Translate(translation, align_corners=True)
assert_allclose(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_dxdy_batch_broadcast(self, device, dtype):
# prepare input data
- inp = torch.tensor([[
- [1., 2.],
- [3., 4.],
- [5., 6.],
- [7., 8.],
- ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
+ inp = torch.tensor([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0], [7.0, 8.0]]], 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.],
- ]]],
+ [[[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0], [0.0, 7.0]]], [[[0.0, 1.0], [0.0, 3.0], [0.0, 5.0], [0.0, 7.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# prepare transformation
- translation = torch.tensor([[1., 0.]], device=device, dtype=dtype)
+ translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
transform = kornia.Translate(translation, align_corners=True)
assert_allclose(transform(inp), expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device, dtype):
# test parameters
- translation = torch.tensor([[1., 0.]], device=device, dtype=dtype)
+ translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
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")
def test_jit(self, device, dtype):
- translation = torch.tensor([[1., 0.]], device=device, dtype=dtype)
+ translation = torch.tensor([[1.0, 0.0]], device=device, dtype=dtype)
batch_size, channels, height, width = 2, 3, 64, 64
img = torch.ones(batch_size, channels, height, width, device=device, dtype=dtype)
trans = kornia.Translate(translation)
@@ -333,24 +255,29 @@ 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
+ [[[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]],
+ device=device,
+ dtype=dtype,
)
# prepare transformation
- scale_factor = torch.tensor([[2., 2.]], device=device, dtype=dtype)
+ scale_factor = torch.tensor([[2.0, 2.0]], device=device, dtype=dtype)
transform = kornia.Scale(scale_factor)
assert_allclose(transform(inp).sum().item(), 12.25, atol=1e-4, rtol=1e-4)
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
+ [[[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]]],
+ 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
+ [[[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.0, 0.0, 0.0]]],
+ device=device,
+ dtype=dtype,
)
# prepare transformation
scale_factor = torch.tensor([[0.5, 0.5]], device=device, dtype=dtype)
@@ -360,10 +287,14 @@ 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
+ [[[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]]],
+ 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
+ [[[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.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)
@@ -373,10 +304,14 @@ 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
+ [[[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]]],
+ 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
+ [[[0.0, 0.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 1.0, 1.0, 0.0], [0.0, 0.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)
@@ -391,10 +326,7 @@ class TestScale:
# 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")
@@ -408,16 +340,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
+ [[[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]]],
+ 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.]]],
+ [[[0.75, 1.0, 1.0, 1.0], [0.25, 1.0, 1.0, 1.0], [0.0, 0.75, 1.0, 1.0], [0.0, 0.25, 1.0, 1.0]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# prepare transformation
@@ -428,12 +361,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
+ [[[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]]],
+ 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.]]],
+ [[[0.75, 0.25, 0.0, 0.0], [1.0, 1.0, 0.75, 0.25], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# prepare transformation
@@ -444,16 +379,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
+ [[[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]]],
+ 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.]]]
+ [[[0.75, 1.0, 1.0, 1.0], [0.25, 1.0, 1.0, 1.0], [0.0, 0.75, 1.0, 1.0], [0.0, 0.25, 1.0, 1.0]]],
+ [[[0.75, 0.25, 0.0, 0.0], [1.0, 1.0, 0.75, 0.25], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# prepare transformation
@@ -464,13 +401,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
+ [[[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]]],
+ 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, 1.0, 1.0, 1.0], [0.25, 1.0, 1.0, 1.0], [0.0, 0.75, 1.0, 1.0], [0.0, 0.25, 1.0, 1.0]]]],
device=device,
- dtype=dtype
+ dtype=dtype,
).repeat(2, 1, 1, 1)
# prepare transformation
@@ -486,10 +425,7 @@ class TestShear:
# 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")
@@ -503,7 +439,6 @@ class TestShear:
class TestAffine2d:
-
def test_affine_no_args(self):
with pytest.raises(RuntimeError):
kornia.Affine()
@@ -577,7 +512,7 @@ class TestAffine2d:
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
+ dtype=dtype,
).repeat(batch_size, 1, 1, 1)
angle = torch.tensor(180.0, device=device, dtype=dtype).repeat(batch_size)
@@ -586,16 +521,17 @@ 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
+ 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)
def test_compose_affine_matrix_3x3(self, device, dtype):
- """ To get parameters:
+ """To get parameters:
import torchvision as tv
from PIL import Image
from torch import Tensor as T
@@ -625,18 +561,20 @@ class TestAffine2d:
"""
from torch import Tensor as T
import math
+
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]])
- center = T([float(width), float(height)]).view(1, 2) / 2. + 0.5
+ matrix_expected = T([[1.27536969, 4.26828945e-01, -3.2876e01], [2.18297196e-03, 1.29424165e00, -1.1717e01]])
+ center = T([float(width), float(height)]).view(1, 2) / 2.0 + 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 4949e4713..c84cec967 100644
--- a/test/geometry/transform/test_elastic_transform.py
+++ b/test/geometry/transform/test_elastic_transform.py
@@ -8,7 +8,6 @@ from kornia.geometry.transform import elastic_transform2d
class TestElasticTransform:
-
def test_smoke(self, device, dtype):
image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)
noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)
@@ -23,7 +22,7 @@ class TestElasticTransform:
def test_exception(self, device, dtype):
with pytest.raises(TypeError):
- assert elastic_transform2d([0.])
+ assert elastic_transform2d([0.0])
with pytest.raises(TypeError):
assert elastic_transform2d(torch.tensor(), 1)
@@ -39,11 +38,12 @@ class TestElasticTransform:
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.])],
- ]
+ "kernel_size, sigma, alpha",
+ [
+ [(3, 3), (4.0, 4.0), (32.0, 32.0)],
+ [(5, 3), (4.0, 8.0), (16.0, 32.0)],
+ [(5, 5), torch.tensor([2.0, 8.0]), torch.tensor([16.0, 64.0])],
+ ],
)
def test_valid_paramters(self, device, dtype, kernel_size, sigma, alpha):
image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)
@@ -58,7 +58,7 @@ class TestElasticTransform:
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
+ dtype=dtype,
)
noise = torch.ones(1, 2, 3, 3, device=device, dtype=dtype)
@@ -66,7 +66,7 @@ class TestElasticTransform:
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
+ dtype=dtype,
)
actual = elastic_transform2d(image, noise)
@@ -76,10 +76,7 @@ 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 ed17897d3..1f8d96d4d 100644
--- a/test/geometry/transform/test_flip.py
+++ b/test/geometry/transform/test_flip.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
class TestVflip:
-
def smoke_test(self, device, dtype):
f = kornia.Vflip()
repr = "Vflip()"
@@ -17,20 +16,24 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.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
+ expected = torch.tensor(
+ [[0.0, 1.0, 1.0], [0.0, 0.0, 0.0], [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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], 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.0, 1.0, 1.0], [0.0, 0.0, 0.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
@@ -38,23 +41,24 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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], [0.0, 0.0, 0.0], [5.0, 5.0, 0.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.0, 5.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], device=device, dtype=dtype
+ ) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -64,15 +68,14 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], 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:
-
def smoke_test(self, device, dtype):
f = kornia.Hflip()
repr = "Hflip()"
@@ -81,20 +84,26 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 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 = torch.tensor(
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 1.0, 0.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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], 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], [0.0, 0.0, 0.0], [1.0, 1.0, 0.0]]], device=device, dtype=dtype
+ ) # 3 x 3
expected = expected.repeat(2, 1, 1) # 2 x 3 x 3
@@ -102,23 +111,24 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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.0, 0.0], [5.0, 5.0, 0.0], [0.0, 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, 0.0], [0.0, 5.0, 5.0], [0.0, 0.0, 0.0]]], device=device, dtype=dtype
+ ) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -128,15 +138,14 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], 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:
-
def smoke_test(self, device, dtype):
f = kornia.Rot180()
repr = "Rot180()"
@@ -145,20 +154,24 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.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
+ expected = torch.tensor(
+ [[1.0, 1.0, 0.0], [0.0, 0.0, 0.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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], 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.0, 1.0, 0.0], [0.0, 0.0, 0.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
@@ -166,23 +179,24 @@ 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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], device=device, dtype=dtype) # 3 x 3
# Build jit trace
- op_trace = torch.jit.trace(op_script, (input, ))
+ 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], [0.0, 0.0, 0.0], [5.0, 5.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., 5., 5.], [0., 0., 0.], [0., 0., 0.]]], device=device, dtype=dtype) # 3 x 3
+ expected = torch.tensor(
+ [[[0.0, 5.0, 5.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]], device=device, dtype=dtype
+ ) # 3 x 3
expected = expected.repeat(2, 1, 1)
@@ -192,8 +206,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.0, 0.0, 0.0], [0.0, 1.0, 1.0]], 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 aaa6d095a..f98cbf6c0 100644
--- a/test/geometry/transform/test_homography_warper.py
+++ b/test/geometry/transform/test_homography_warper.py
@@ -42,8 +42,9 @@ class TestHomographyWarper:
# 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)
+ 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])
@@ -62,12 +63,7 @@ class TestHomographyWarper:
assert (norm_homo == res).all()
@pytest.mark.parametrize("offset", [1, 3, 7])
- @pytest.mark.parametrize("shape", [
- (4, 5),
- (2, 6),
- (4, 3),
- (5, 7),
- ])
+ @pytest.mark.parametrize("shape", [(4, 5), (2, 6), (4, 3), (5, 7)])
def test_warp_grid_translation(self, shape, offset, device, dtype):
# create input data
height, width = shape
@@ -81,11 +77,7 @@ class TestHomographyWarper:
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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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,15 +94,10 @@ class TestHomographyWarper:
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),
- ])
+ @pytest.mark.parametrize("shape", [(4, 5), (2, 6), (4, 3), (5, 7)])
def test_translation(self, shape, device, dtype):
# create input data
- offset = 2. # in pixel
+ offset = 2.0 # in pixel
height, width = shape
patch_src = torch.rand(1, 1, height, width, device=device, dtype=dtype)
dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3, device=device, dtype=dtype)
@@ -121,11 +108,7 @@ class TestHomographyWarper:
patch_dst = warper(patch_src, dst_homo_src)
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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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
@@ -156,9 +139,12 @@ 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)
@@ -193,11 +179,7 @@ class TestHomographyWarper:
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),
- ])
+ @pytest.mark.parametrize("batch_shape", [(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
@@ -215,10 +197,7 @@ class TestHomographyWarper:
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])
@@ -230,9 +209,12 @@ 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,41 +228,33 @@ class TestHomographyWarper:
# transform the points with and without jit
patch_dst = kornia.homography_warp(
patch_src,
- dst_homo_src_i, (height, width),
+ dst_homo_src_i,
+ (height, width),
align_corners=align_corners,
- normalized_coordinates=normalized_coordinates
+ normalized_coordinates=normalized_coordinates,
)
patch_dst_jit = torch.jit.script(kornia.homography_warp)(
patch_src,
- dst_homo_src_i, (height, width),
+ dst_homo_src_i,
+ (height, width),
align_corners=align_corners,
- normalized_coordinates=normalized_coordinates
+ 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_0 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0, -1.0], [0.0, 0.0, 1.0]]])
- expected_2d_1 = torch.tensor([[[0.5, 0.0, -1.], [0.0, 2e14, -1.], [0.0, 0.0, 1.]]])
+ expected_2d_1 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2e14, -1.0], [0.0, 0.0, 1.0]]])
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.],
- ]]
+ [[[0.4, 0.0, 0.0, -1.0], [0.0, 2.0, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]]
)
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.],
- ]]
+ [[[0.4, 0.0, 0.0, -1.0], [0.0, 2e14, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]]
)
@pytest.mark.parametrize("height,width,expected", [(2, 5, expected_2d_0), (1, 5, expected_2d_1)])
@@ -297,8 +271,8 @@ class TestHomographyNormalTransform:
def test_transform2d_apply(self, device, dtype):
height, width = 2, 5
- input = torch.tensor([[0., 0.], [width - 1, height - 1]], device=device, dtype=dtype)
- expected = torch.tensor([[-1., -1.], [1., 1.]], device=device, dtype=dtype)
+ input = torch.tensor([[0.0, 0.0], [width - 1, height - 1]], device=device, dtype=dtype)
+ expected = torch.tensor([[-1.0, -1.0], [1.0, 1.0]], device=device, dtype=dtype)
transform = kornia.normal_transform_pixel(height, width, device=device, dtype=dtype)
output = kornia.transform_points(transform, input)
assert_allclose(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
@@ -317,8 +291,8 @@ class TestHomographyNormalTransform:
def test_transform3d_apply(self, device, dtype):
depth, height, width = 3, 2, 5
- input = torch.tensor([[0., 0., 0.], [width - 1, height - 1, depth - 1]], device=device, dtype=dtype)
- expected = torch.tensor([[-1., -1., -1.], [1., 1., 1.]], device=device, dtype=dtype)
+ input = torch.tensor([[0.0, 0.0, 0.0], [width - 1, height - 1, depth - 1]], device=device, dtype=dtype)
+ expected = torch.tensor([[-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]], device=device, dtype=dtype)
transform = kornia.normal_transform_pixel3d(depth, height, width, device=device, dtype=dtype)
output = kornia.transform_points(transform, input)
assert_allclose(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
@@ -337,10 +311,11 @@ class TestHomographyWarper3D:
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
+ dtype=dtype,
+ )
+ norm = kornia.normal_transform_pixel3d(input_shape[0], input_shape[1], input_shape[2]).to(
+ 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)
@@ -356,7 +331,7 @@ class TestHomographyWarper3D:
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
+ dtype=dtype,
).repeat(batch_size, 1, 1)
assert_allclose(norm_homo, res, rtol=1e-4, atol=1e-4)
@@ -376,7 +351,7 @@ class TestHomographyWarper3D:
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
+ dtype=dtype,
)
assert (norm_homo == res).all()
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 895a067e0..2eae49ec0 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -30,10 +30,7 @@ def test_get_perspective_transform(batch_size, device, dtype):
# 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])
@@ -45,7 +42,7 @@ def test_rotation_matrix2d(batch_size, device, dtype):
# 90 deg rotation
center = center_base
- angle = 90. * angle_base
+ angle = 90.0 * angle_base
scale = scale_base
M = kornia.get_rotation_matrix2d(center, angle, scale)
@@ -57,8 +54,8 @@ def test_rotation_matrix2d(batch_size, device, dtype):
# 90 deg rotation + 2x scale
center = center_base
- angle = 90. * angle_base
- scale = 2. * scale_base
+ angle = 90.0 * angle_base
+ scale = 2.0 * scale_base
M = kornia.get_rotation_matrix2d(center, angle, scale)
for i in range(batch_size):
@@ -69,7 +66,7 @@ def test_rotation_matrix2d(batch_size, device, dtype):
# 45 deg rotation
center = center_base
- angle = 45. * angle_base
+ angle = 45.0 * angle_base
scale = scale_base
M = kornia.get_rotation_matrix2d(center, angle, scale)
@@ -87,7 +84,6 @@ def test_rotation_matrix2d(batch_size, device, dtype):
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
@@ -111,10 +107,10 @@ class TestWarpAffine:
size = (4, 5)
with pytest.raises(TypeError):
- assert kornia.warp_affine(0., aff, size)
+ assert kornia.warp_affine(0.0, aff, size)
with pytest.raises(TypeError):
- assert kornia.warp_affine(img, 0., size)
+ assert kornia.warp_affine(img, 0.0, size)
with pytest.raises(ValueError):
img = torch.rand(2, 3, 4, device=device, dtype=dtype)
@@ -125,7 +121,7 @@ class TestWarpAffine:
assert kornia.warp_affine(img, aff, size)
def test_translation(self, device, dtype):
- offset = 1.
+ offset = 1.0
h, w = 3, 4
aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
aff_ab[..., -1] += offset
@@ -146,7 +142,7 @@ class TestWarpAffine:
# create rotation matrix of 90deg (anti-clockwise)
center = torch.tensor([[w - 1, h - 1]], device=device, dtype=dtype) / 2
scale = torch.ones((1, 2), device=device, dtype=dtype)
- angle = 90. * torch.ones(1, device=device, dtype=dtype)
+ angle = 90.0 * torch.ones(1, device=device, dtype=dtype)
aff_ab = kornia.get_rotation_matrix2d(center, angle, scale)
# Same as opencv: cv2.getRotationMatrix2D(((w-1)/2,(h-1)/2), 90., 1.)
@@ -173,15 +169,10 @@ 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)
@@ -205,10 +196,10 @@ class TestWarpPerspective:
size = (4, 5)
with pytest.raises(TypeError):
- assert kornia.warp_perspective(0., homo, size)
+ assert kornia.warp_perspective(0.0, homo, size)
with pytest.raises(TypeError):
- assert kornia.warp_perspective(img, 0., size)
+ assert kornia.warp_perspective(img, 0.0, size)
with pytest.raises(ValueError):
img = torch.rand(2, 3, 4, device=device, dtype=dtype)
@@ -219,7 +210,7 @@ class TestWarpPerspective:
assert kornia.warp_perspective(img, homo, size)
def test_translation(self, device, dtype):
- offset = 1.
+ offset = 1.0
h, w = 3, 4
img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)
@@ -240,7 +231,7 @@ class TestWarpPerspective:
# create rotation matrix of 90deg (anti-clockwise)
center = torch.tensor([[w - 1, h - 1]], device=device, dtype=dtype) / 2
scale = torch.ones((1, 2), device=device, dtype=dtype)
- angle = 90. * torch.ones(1, device=device, dtype=dtype)
+ angle = 90.0 * torch.ones(1, device=device, dtype=dtype)
aff_ab = kornia.get_rotation_matrix2d(center, angle, scale)
# Same as opencv: cv2.getRotationMatrix2D(((w-1)/2,(h-1)/2), 90., 1.)
@@ -265,23 +256,13 @@ 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
+ [[[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
+ [[[0, 0], [0, dst_w - 1], [dst_h - 1, dst_w - 1], [dst_h - 1, 0]]], device=device, dtype=dtype
)
# compute transformation between points
@@ -289,12 +270,7 @@ class TestWarpPerspective:
# 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
+ [[[[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]
@@ -309,22 +285,12 @@ class TestWarpPerspective:
# [x, y] origin
# top-left, top-right, bottom-right, bottom-left
- points_src = torch.tensor([[
- [1, 1],
- [1, 2],
- [2, 2],
- [2, 1],
- ]], device=device, dtype=dtype)
+ points_src = torch.tensor([[[1, 1], [1, 2], [2, 2], [2, 1]]], 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
+ [[[0, 0], [0, dst_w - 1], [dst_h - 1, dst_w - 1], [dst_h - 1, 0]]], device=device, dtype=dtype
)
# compute transformation between points
@@ -332,25 +298,22 @@ class TestWarpPerspective:
# 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
+ [[[[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]
+ [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
+ dtype=dtype,
)
# warp and assert
@@ -372,15 +335,10 @@ 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)
@@ -390,75 +348,54 @@ class TestRemap:
def test_shift(self, device, dtype):
height, width = 3, 4
- inp = torch.tensor([[[
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- [1., 1., 1., 1.],
- ]]], device=device, dtype=dtype)
+ inp = torch.tensor(
+ [[[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]], device=device, dtype=dtype
+ )
expected = torch.tensor(
- [[[
- [1., 1., 1., 0.],
- [1., 1., 1., 0.],
- [0., 0., 0., 0.],
- ]]], device=device, dtype=dtype
+ [[[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.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
+ grid += 1.0 # apply shift in both x/y direction
input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input_warped, expected, rtol=1e-4, atol=1e-4)
def test_shift_batch(self, device, dtype):
height, width = 3, 4
- inp = torch.tensor([[[
- [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.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]], 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.],
- ]]
+ [[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0]]],
+ [[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 0.0]]],
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
# generate a batch of grids
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
+ grid[0, ..., 0] += 1.0 # apply shift in the x direction
+ grid[1, ..., 1] += 1.0 # apply shift in the y direction
input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input_warped, expected, rtol=1e-4, atol=1e-4)
def test_shift_batch_broadcast(self, device, dtype):
height, width = 3, 4
- inp = torch.tensor([[[
- [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.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]], 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
+ [[[[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 0.0], [0.0, 0.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
+ grid += 1.0 # apply shift in both x/y direction
input_warped = kornia.remap(inp, grid[..., 0], grid[..., 1], align_corners=True)
assert_allclose(input_warped, expected, rtol=1e-4, atol=1e-4)
@@ -466,17 +403,11 @@ class TestRemap:
def test_normalized_coordinates(self, device, dtype):
height, width = 3, 4
normalized_coordinates = True
- inp = torch.tensor([[[
- [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.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]], 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
+ [[[[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]]], device=device, dtype=dtype
).repeat(2, 1, 1, 1)
grid = kornia.utils.create_meshgrid(
@@ -497,15 +428,10 @@ class TestRemap:
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)
@@ -514,20 +440,15 @@ class TestRemap:
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 += 1. # apply some shift
+ grid += 1.0 # 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)
@@ -536,7 +457,7 @@ class TestRemap:
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 += 1. # apply some shift
+ grid += 1.0 # apply some shift
input_tuple = (img, grid[..., 0], grid[..., 1])
op_traced = torch.jit.trace(op_script, input_tuple)
@@ -544,7 +465,7 @@ class TestRemap:
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 += 2. # apply some shift
+ grid += 2.0 # apply some shift
# 3. Apply to different input
input_tuple = (img, grid[..., 0], grid[..., 1])
@@ -554,32 +475,25 @@ 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)
assert_allclose(matrix, matrix_inv, rtol=1e-4, atol=1e-4)
def test_rot90(self, device, dtype):
- angle = torch.tensor([90.], device=device, dtype=dtype)
- scale = torch.tensor([[1., 1.]], device=device, dtype=dtype)
- center = torch.tensor([[0., 0.]], device=device, dtype=dtype)
- expected = torch.tensor([[
- [0., -1., 0.],
- [1., 0., 0.],
- ]], device=device, dtype=dtype)
+ angle = torch.tensor([90.0], device=device, dtype=dtype)
+ scale = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)
+ center = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[[0.0, -1.0, 0.0], [1.0, 0.0, 0.0]]], device=device, dtype=dtype)
matrix = kornia.get_rotation_matrix2d(center, angle, scale)
matrix_inv = kornia.invert_affine_transform(matrix)
assert_allclose(matrix_inv, expected, rtol=1e-4, atol=1e-4)
def test_rot90_batch(self, device, dtype):
- angle = torch.tensor([90.], device=device, dtype=dtype)
- scale = torch.tensor([[1., 1.]], device=device, dtype=dtype)
- center = torch.tensor([[0., 0.]], device=device, dtype=dtype)
- expected = torch.tensor([[
- [0., -1., 0.],
- [1., 0., 0.],
- ]], device=device, dtype=dtype).repeat(2, 1, 1)
+ angle = torch.tensor([90.0], device=device, dtype=dtype)
+ scale = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)
+ center = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[[0.0, -1.0, 0.0], [1.0, 0.0, 0.0]]], device=device, dtype=dtype).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)
@@ -587,11 +501,10 @@ class TestInvertAffineTransform:
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)
@@ -604,7 +517,6 @@ 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)
diff --git a/test/geometry/transform/test_projwarp.py b/test/geometry/transform/test_projwarp.py
index d0fb4a454..5d609567d 100644
--- a/test/geometry/transform/test_projwarp.py
+++ b/test/geometry/transform/test_projwarp.py
@@ -9,7 +9,6 @@ import kornia.testing as utils # test utils
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)
@@ -46,54 +45,34 @@ class TestWarpAffine3d:
[
[
[
- [
- [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.],
- ]
+ [[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]],
]
]
],
device=device,
- dtype=dtype
+ 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.],
- ]
+ [[0.0, 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, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
_, _, D, H, W = input.shape
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)
+ angles = torch.tensor([[90.0, 0.0, 0.0]], device=device, dtype=dtype)
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
@@ -105,54 +84,34 @@ class TestWarpAffine3d:
[
[
[
- [
- [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.],
- ]
+ [[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]],
]
]
],
device=device,
- dtype=dtype
+ 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.],
- ]
+ [[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, 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]],
]
]
],
device=device,
- dtype=dtype
+ dtype=dtype,
)
_, _, D, H, W = input.shape
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)
+ angles = torch.tensor([[0.0, 90.0, 0.0]], device=device, dtype=dtype)
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
@@ -164,54 +123,34 @@ class TestWarpAffine3d:
[
[
[
- [
- [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.],
- ]
+ [[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, 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]],
]
]
],
device=device,
- dtype=dtype
+ 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.],
- ]
+ [[0.0, 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], [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
+ dtype=dtype,
)
_, _, D, H, W = input.shape
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)
+ angles = torch.tensor([[0.0, 0.0, 90.0]], device=device, dtype=dtype)
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
@@ -224,84 +163,44 @@ class TestWarpAffine3d:
[
[
[
- [
- [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, 4.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.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., 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.],
- ]
- ]
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 9.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 6.0, 7.0], [0.0, 0.0, 0.0]],
+ [[0.0, 0.0, 0.0], [0.0, 8.0, 0.0], [0.0, 0.0, 0.0]],
+ ],
]
],
device=device,
- dtype=dtype
+ 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, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[4.0, 2.0, 0.0], [3.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., 7., 0.],
- [0., 0., 0.],
- ], [
- [0., 0., 0.],
- [0., 6., 8.],
- [9., 0., 0.],
- ], [
- [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.0]],
+ [[0.0, 0.0, 0.0], [0.0, 6.0, 8.0], [9.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
+ dtype=dtype,
)
_, _, D, H, W = input.shape
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)
+ angles = torch.tensor([[0.0, 90.0, 0.0]], device=device, dtype=dtype)
scales: torch.Tensor = torch.ones_like(angles, device=device, dtype=dtype)
P = proj.get_projective_transform(center, angles, scales)
@@ -310,7 +209,6 @@ 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)
@@ -332,52 +230,38 @@ class TestGetRotationMatrix3d:
angle = torch.zeros(1, 3, 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., 1., 0., 0.],
- [0., 0., 1., 0.],
- ], device=device, dtype=dtype).unsqueeze(0)
+ P_expected = torch.tensor(
+ [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 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_rot90x(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
- angle = torch.tensor([[90., 0., 0.]], device=device, dtype=dtype)
+ angle = torch.tensor([[90.0, 0.0, 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
+ [[1.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
).unsqueeze(0)
assert_allclose(P, P_expected, atol=1e-4, rtol=1e-4)
def test_rot90y(self, device, dtype):
center = torch.zeros(1, 3, device=device, dtype=dtype)
- angle = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
+ angle = torch.tensor([[0.0, 90.0, 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(
- [
- [0., 0., 1., 0.],
- [0., 1., 0., 0.],
- [-1., 0., 0., 0.],
- ], device=device, dtype=dtype
+ [[0.0, 0.0, 1.0, 0.0], [0.0, 1.0, 0.0, 0.0], [-1.0, 0.0, 0.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):
center = torch.zeros(1, 3, device=device, dtype=dtype)
- angle = torch.tensor([[0., 0., 90.]], device=device, dtype=dtype)
+ angle = torch.tensor([[0.0, 0.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., -1., 0., 0.],
- [1., 0., 0., 0.],
- [0., 0., 1., 0.],
- ], device=device, dtype=dtype
+ [[0.0, -1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], device=device, dtype=dtype
).unsqueeze(0)
assert_allclose(P, P_expected, atol=1e-4, rtol=1e-4)
@@ -390,7 +274,6 @@ 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):
@@ -414,10 +297,7 @@ class TestPerspectiveTransform3D:
# 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):
@@ -426,44 +306,50 @@ 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]
+ [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
+ 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, -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]
+ [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
+ dtype=dtype,
)
assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
@@ -471,7 +357,4 @@ class TestPerspectiveTransform3D:
# 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 3c5921daa..89d6ad72b 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -8,7 +8,6 @@ import kornia.testing as utils # test utils
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 +21,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,7 +31,6 @@ 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()
@@ -53,7 +51,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)
@@ -63,7 +61,6 @@ 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)
@@ -106,7 +103,7 @@ class TestScalePyramid:
PS = 16
R = 2
inp = torch.zeros(1, 1, PS, PS, device=device, dtype=dtype)
- inp[..., PS // 2 - R:PS // 2 + R, PS // 2 - R:PS // 2 + R] = 1.0
+ inp[..., PS // 2 - R : PS // 2 + R, PS // 2 - R : PS // 2 + R] = 1.0
SP = kornia.geometry.ScalePyramid(n_levels=3)
sp, sigmas, pd = SP(inp)
for i, pyr_level in enumerate(sp):
@@ -125,11 +122,10 @@ class TestScalePyramid:
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)
@@ -146,7 +142,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
@@ -155,7 +151,4 @@ 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 a74e37774..7d9909b14 100644
--- a/test/geometry/transform/test_thin_plate_spline.py
+++ b/test/geometry/transform/test_thin_plate_spline.py
@@ -7,14 +7,13 @@ import kornia as kornia
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.0], [0.0, 10.0], [10.0, 0.0], [10.0, 10.0], [5.0, 5.0]]], 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)
@@ -27,20 +26,16 @@ class TestTransformParameters:
kernel, affine = kornia.get_tps_transform(src, src)
target_kernel = torch.zeros(batch_size, 5, 2, device=device)
target_affine = torch.zeros(batch_size, 3, 2, device=device)
- target_affine[:, [1, 2], [0, 1]] = 1.
+ target_affine[:, [1, 2], [0, 1]] = 1.0
assert_allclose(kernel, target_kernel, atol=1e-4, rtol=1e-4)
assert_allclose(affine, target_affine, atol=1e-4, rtol=1e-4)
@pytest.mark.parametrize('batch_size', [1, 3])
def test_affine_only(self, batch_size, device, dtype):
- src = torch.tensor([[
- [0., 0.],
- [0., 1.],
- [1., 0.],
- [1., 1.],
- [.5, .5],
- ]], device=device).repeat(batch_size, 1, 1)
- dst = src.clone() * 2.
+ src = torch.tensor([[[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0], [0.5, 0.5]]], device=device).repeat(
+ batch_size, 1, 1
+ )
+ dst = src.clone() * 2.0
kernel, affine = kornia.get_tps_transform(src, dst)
assert_allclose(kernel, torch.zeros_like(kernel), atol=1e-4, rtol=1e-4)
@@ -77,7 +72,6 @@ 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)
@@ -148,7 +142,6 @@ 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)
@@ -159,17 +152,13 @@ class TestWarpImage:
@pytest.mark.parametrize('batch_size', [1, 3])
def test_warp(self, batch_size, device, dtype):
- src = torch.tensor([[
- [-1., -1.],
- [-1., 1.],
- [1., -1.],
- [1., -1.],
- [0., 0.],
- ]], device=device).repeat(batch_size, 1, 1)
+ src = torch.tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, -1.0], [0.0, 0.0]]], device=device).repeat(
+ batch_size, 1, 1
+ )
# zoom in by a factor of 2
- dst = src.clone() * 2.
+ dst = src.clone() * 2.0
tensor = torch.zeros(batch_size, 3, 8, 8, device=device)
- tensor[:, :, 2:6, 2:6] = 1.
+ tensor[:, :, 2:6, 2:6] = 1.0
expected = torch.ones_like(tensor)
# nn.grid_sample interpolates the at the edges it seems, so the boundaries have values < 1
diff --git a/test/integration/test_conversions.py b/test/integration/test_conversions.py
index a4366385c..4e4cbc5c9 100644
--- a/test/integration/test_conversions.py
+++ b/test/integration/test_conversions.py
@@ -11,32 +11,31 @@ from kornia.geometry.conversions import QuaternionCoeffOrder
def atol(device, dtype):
"""Lower tolerance for cuda-float16 only"""
if 'cuda' in device.type and dtype == torch.float16:
- return 1.e-3
+ return 1.0e-3
else:
- return 1.e-4
+ return 1.0e-4
@pytest.fixture
def rtol(device, dtype):
"""Lower tolerance for cuda-float16 only"""
if 'cuda' in device.type and dtype == torch.float16:
- return 1.e-3
+ return 1.0e-3
else:
- return 1.e-4
+ return 1.0e-4
class TestAngleAxisToQuaternionToAngleAxis:
-
def test_zero_angle(self, device, dtype, atol, rtol):
- angle_axis = torch.tensor((0., 0., 0.), device=device, dtype=dtype)
+ angle_axis = torch.tensor((0.0, 0.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)
assert_allclose(angle_axis_hat, angle_axis, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_small_angle(self, axis, device, dtype, atol, rtol):
- theta = 1.e-2
- array = [0., 0., 0.]
+ theta = 1.0e-2
+ array = [0.0, 0.0, 0.0]
array[axis] = theta
angle_axis = torch.tensor(array, device=device, dtype=dtype)
quaternion = kornia.angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)
@@ -46,8 +45,8 @@ class TestAngleAxisToQuaternionToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_rotation(self, axis, device, dtype, atol, rtol):
# half_sqrt2 = 0.5 * np.sqrt(2)
- array = [0., 0., 0.]
- array[axis] = kornia.pi / 2.
+ array = [0.0, 0.0, 0.0]
+ array[axis] = kornia.pi / 2.0
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)
@@ -55,9 +54,8 @@ class TestAngleAxisToQuaternionToAngleAxis:
class TestQuaternionToAngleAxisToQuaternion:
-
def test_unit_quaternion_xyzw(self, device, dtype, atol, rtol):
- quaternion = torch.tensor((0., 0., 0., 1.), device=device, dtype=dtype)
+ quaternion = torch.tensor((0.0, 0.0, 0.0, 1.0), device=device, dtype=dtype)
with pytest.warns(UserWarning):
angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
with pytest.warns(UserWarning):
@@ -65,15 +63,15 @@ class TestQuaternionToAngleAxisToQuaternion:
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)
+ quaternion = torch.tensor((1.0, 0.0, 0.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)
assert_allclose(quaternion_hat, quaternion, atol=atol, rtol=rtol)
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_rotation_xyzw(self, axis, device, dtype, atol, rtol):
- array = [0., 0., 0., 0.]
- array[axis] = 1.
+ array = [0.0, 0.0, 0.0, 0.0]
+ array[axis] = 1.0
quaternion = torch.tensor(array, device=device, dtype=dtype)
with pytest.warns(UserWarning):
angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
@@ -83,8 +81,8 @@ class TestQuaternionToAngleAxisToQuaternion:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_rotation(self, axis, device, dtype, atol, rtol):
- array = [0., 0., 0., 0.]
- array[1 + axis] = 1.
+ array = [0.0, 0.0, 0.0, 0.0]
+ array[1 + axis] = 1.0
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)
@@ -97,9 +95,9 @@ class TestQuaternionToAngleAxisToQuaternion:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_small_angle_xyzw(self, axis, device, dtype, atol, rtol):
- theta = 1.e-2
- array = [0., 0., 0., np.cos(theta / 2)]
- array[axis] = np.sin(theta / 2.)
+ theta = 1.0e-2
+ array = [0.0, 0.0, 0.0, np.cos(theta / 2)]
+ array[axis] = np.sin(theta / 2.0)
quaternion = torch.tensor(array, device=device, dtype=dtype)
with pytest.warns(UserWarning):
angle_axis = kornia.quaternion_to_angle_axis(quaternion, order=QuaternionCoeffOrder.XYZW)
@@ -109,9 +107,9 @@ class TestQuaternionToAngleAxisToQuaternion:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_small_angle(self, axis, device, dtype, atol, rtol):
- theta = 1.e-2
- array = [np.cos(theta / 2), 0., 0., 0.]
- array[1 + axis] = np.sin(theta / 2.)
+ theta = 1.0e-2
+ array = [np.cos(theta / 2), 0.0, 0.0, 0.0]
+ array[1 + axis] = np.sin(theta / 2.0)
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)
@@ -124,11 +122,10 @@ class TestQuaternionToAngleAxisToQuaternion:
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.]]
- array[0][axis] = 1. # `0 + axis` should fail when WXYZ
+ array = [[0.0, 0.0, 0.0, 0.0]]
+ array[0][axis] = 1.0 # `0 + axis` should fail when WXYZ
quaternion = torch.tensor(array, device=device, dtype=dtype)
assert quaternion.shape[-1] == 4
@@ -139,7 +136,7 @@ class TestQuaternionToRotationMatrixToAngleAxis:
angle_axis = kornia.rotation_matrix_to_angle_axis(mm)
assert angle_axis.shape[-1] == 3
- angle_axis_expected = [[0., 0., 0.]]
+ angle_axis_expected = [[0.0, 0.0, 0.0]]
angle_axis_expected[0][axis] = kornia.pi
angle_axis_expected = torch.tensor(angle_axis_expected, device=device, dtype=dtype)
assert_allclose(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)
@@ -150,8 +147,8 @@ class TestQuaternionToRotationMatrixToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_qma(self, axis, device, dtype, atol, rtol):
- array = [[0., 0., 0., 0.]]
- array[0][1 + axis] = 1. # `1 + axis` this should fail when XYZW
+ array = [[0.0, 0.0, 0.0, 0.0]]
+ array[0][1 + axis] = 1.0 # `1 + axis` this should fail when XYZW
quaternion = torch.tensor(array, device=device, dtype=dtype)
assert quaternion.shape[-1] == 4
@@ -161,7 +158,7 @@ class TestQuaternionToRotationMatrixToAngleAxis:
angle_axis = kornia.rotation_matrix_to_angle_axis(mm)
assert angle_axis.shape[-1] == 3
- angle_axis_expected = [[0., 0., 0.]]
+ angle_axis_expected = [[0.0, 0.0, 0.0]]
angle_axis_expected[0][axis] = kornia.pi
angle_axis_expected = torch.tensor(angle_axis_expected, device=device, dtype=dtype)
assert_allclose(angle_axis, angle_axis_expected, atol=atol, rtol=rtol)
@@ -171,8 +168,8 @@ class TestQuaternionToRotationMatrixToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_qam_xyzw(self, axis, device, dtype, atol, rtol):
- array = [[0., 0., 0., 0.]]
- array[0][axis] = 1.
+ array = [[0.0, 0.0, 0.0, 0.0]]
+ array[0][axis] = 1.0
quaternion = torch.tensor(array, device=device, dtype=dtype)
assert quaternion.shape[-1] == 4
@@ -190,8 +187,8 @@ class TestQuaternionToRotationMatrixToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_qam(self, axis, device, dtype, atol, rtol):
- array = [[0., 0., 0., 0.]]
- array[0][1 + axis] = 1.
+ array = [[0.0, 0.0, 0.0, 0.0]]
+ array[0][1 + axis] = 1.0
quaternion = torch.tensor(array, device=device, dtype=dtype)
assert quaternion.shape[-1] == 4
@@ -207,8 +204,8 @@ class TestQuaternionToRotationMatrixToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_amq_xyzw(self, axis, device, dtype, atol, rtol):
- array = [[0., 0., 0.]]
- array[0][axis] = kornia.pi / 2.
+ array = [[0.0, 0.0, 0.0]]
+ array[0][axis] = kornia.pi / 2.0
angle_axis = torch.tensor(array, device=device, dtype=dtype)
assert angle_axis.shape[-1] == 3
@@ -226,8 +223,8 @@ class TestQuaternionToRotationMatrixToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_amq(self, axis, device, dtype, atol, rtol):
- array = [[0., 0., 0.]]
- array[0][axis] = kornia.pi / 2.
+ array = [[0.0, 0.0, 0.0]]
+ array[0][axis] = kornia.pi / 2.0
angle_axis = torch.tensor(array, device=device, dtype=dtype)
assert angle_axis.shape[-1] == 3
@@ -243,8 +240,8 @@ class TestQuaternionToRotationMatrixToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_aqm_xyzw(self, axis, device, dtype, atol, rtol):
- array = [[0., 0., 0.]]
- array[0][axis] = kornia.pi / 2.
+ array = [[0.0, 0.0, 0.0]]
+ array[0][axis] = kornia.pi / 2.0
angle_axis = torch.tensor(array, device=device, dtype=dtype)
assert angle_axis.shape[-1] == 3
@@ -262,8 +259,8 @@ class TestQuaternionToRotationMatrixToAngleAxis:
@pytest.mark.parametrize("axis", (0, 1, 2))
def test_triplet_aqm(self, axis, device, dtype, atol, rtol):
- array = [[0., 0., 0.]]
- array[0][axis] = kornia.pi / 2.
+ array = [[0.0, 0.0, 0.0]]
+ array[0][axis] = kornia.pi / 2.0
angle_axis = torch.tensor(array, device=device, dtype=dtype)
assert angle_axis.shape[-1] == 3
@@ -287,7 +284,7 @@ class TestAngleOfRotations:
def matrix_angle_abs(mx: torch.Tensor):
"""Unsigned rotation matrix angle"""
trace = torch.diagonal(mx[..., :3, :3], dim1=-1, dim2=-2).sum(-1, keepdim=True)
- return torch.acos((trace - 1.) / 2.)
+ return torch.acos((trace - 1.0) / 2.0)
@staticmethod
def axis_and_angle_to_rotation_matrix(axis_name: str, angle: torch.Tensor, device, dtype):
@@ -301,17 +298,14 @@ class TestAngleOfRotations:
ones = torch.ones_like(sn)
zeros = torch.zeros_like(sn)
if axis_name == 'x':
- axis = torch.tensor((1., 0., 0.), device=device, dtype=dtype).repeat(angle.size())
- rot_m = torch.stack((ones, zeros, zeros, zeros, cs, -sn, zeros, sn, cs), dim=2) \
- .view(-1, 3, 3)
+ axis = torch.tensor((1.0, 0.0, 0.0), device=device, dtype=dtype).repeat(angle.size())
+ rot_m = torch.stack((ones, zeros, zeros, zeros, cs, -sn, zeros, sn, cs), dim=2).view(-1, 3, 3)
elif axis_name == 'y':
- axis = torch.tensor((0., 1., 0.), device=device, dtype=dtype).repeat(angle.size())
- rot_m = torch.stack((cs, zeros, sn, zeros, ones, zeros, -sn, zeros, cs), dim=2) \
- .view(-1, 3, 3)
+ axis = torch.tensor((0.0, 1.0, 0.0), device=device, dtype=dtype).repeat(angle.size())
+ rot_m = torch.stack((cs, zeros, sn, zeros, ones, zeros, -sn, zeros, cs), dim=2).view(-1, 3, 3)
elif axis_name == 'z':
- axis = torch.tensor((0., 0., 1.), device=device, dtype=dtype).repeat(angle.size())
- rot_m = torch.stack((cs, -sn, zeros, sn, cs, zeros, zeros, zeros, ones), dim=2) \
- .view(-1, 3, 3)
+ axis = torch.tensor((0.0, 0.0, 1.0), device=device, dtype=dtype).repeat(angle.size())
+ rot_m = torch.stack((cs, -sn, zeros, sn, cs, zeros, zeros, zeros, ones), dim=2).view(-1, 3, 3)
else:
raise NotImplementedError(f'Not prepared for axis with name {axis_name}')
@@ -320,7 +314,7 @@ 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.0 * 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
)
@@ -333,13 +327,13 @@ 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.0, 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.0, 1.0, 0.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, 0.0, 1.0),) * angle.numel(), device=device, dtype=dtype))
assert_allclose(axis, rot_m[..., :3, 2])
else:
raise NotImplementedError(f'Not prepared for axis_name {axis_name}')
@@ -357,9 +351,9 @@ class TestAngleOfRotations:
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))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -135.0, -90.0, -45.0, 0.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)
+ angle = (angle_deg * kornia.pi / 180.0).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
)
@@ -367,11 +361,10 @@ class TestAngleOfRotations:
assert_allclose(torch.abs(angle), matrix_angle_abs)
@pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
- @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0., 45, 90, 179.9))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 0.0, 45, 90, 179.9))
def test_quaternion_xyzw(self, axis_name, angle_deg, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- angle = torch.tensor((angle_deg * kornia.pi / 180.,), device=device, dtype=dtype) \
- .repeat(2, 1)
+ angle = torch.tensor((angle_deg * kornia.pi / 180.0,), device=device, dtype=dtype).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(
@@ -381,15 +374,15 @@ class TestAngleOfRotations:
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.0 * 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):
- angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ angle_hat = torch.where(mask, angle_hat - 2.0 * kornia.pi, angle_hat)
mask = pi < angle_hat
# invert angle, if quaternion axis points in the opposite direction of the original axis
dots = (quaternion[..., :3] * axis).sum(dim=-1, keepdim=True)
- angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ angle_hat = torch.where(dots < 0.0, angle_hat * -1.0, angle_hat)
# quaternion angle should match input angle
assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
# magnitude of angle should match matrix rotation angle
@@ -397,11 +390,10 @@ class TestAngleOfRotations:
assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
@pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
- @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0., 45, 90, 179.9))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 0.0, 45, 90, 179.9))
def test_quaternion(self, axis_name, angle_deg, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- angle = torch.tensor((angle_deg * kornia.pi / 180.,), device=device, dtype=dtype) \
- .repeat(2, 1)
+ angle = torch.tensor((angle_deg * kornia.pi / 180.0,), device=device, dtype=dtype).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(
@@ -410,15 +402,15 @@ class TestAngleOfRotations:
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.0 * 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):
- angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ angle_hat = torch.where(mask, angle_hat - 2.0 * kornia.pi, angle_hat)
mask = pi < angle_hat
# invert angle, if quaternion axis points in the opposite direction of the original axis
dots = (quaternion[..., 1:4] * axis).sum(dim=-1, keepdim=True)
- angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ angle_hat = torch.where(dots < 0.0, angle_hat * -1.0, angle_hat)
# quaternion angle should match input angle
assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
# magnitude of angle should match matrix rotation angle
@@ -426,9 +418,9 @@ class TestAngleOfRotations:
assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
@pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
- @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0, 45, 90, 179.9))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 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)
+ angle = (angle_deg * kornia.pi / 180.0).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
)
@@ -437,7 +429,7 @@ class TestAngleOfRotations:
angle_hat = angle_axis.norm(p=2, dim=-1, keepdim=True)
# invert angle, if angle_axis axis points in the opposite direction of the original axis
dots = (angle_axis * axis).sum(dim=-1, keepdim=True)
- angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ angle_hat = torch.where(dots < 0.0, angle_hat * -1.0, angle_hat)
# angle_axis angle should match input angle
assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
# magnitude of angle should match matrix rotation angle
@@ -445,10 +437,10 @@ class TestAngleOfRotations:
assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
@pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
- @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0, 45, 90, 179.9))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 0, 45, 90, 179.9))
def test_log_quaternion_xyzw(self, axis_name, angle_deg, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
+ angle = (angle_deg * kornia.pi / 180.0).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
@@ -458,15 +450,15 @@ class TestAngleOfRotations:
with pytest.warns(UserWarning):
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)
+ angle_hat = 2.0 * log_q.norm(p=2, dim=-1, keepdim=True)
# make sure it lands between [-pi..pi)
mask = pi < angle_hat
while torch.any(mask):
- angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ angle_hat = torch.where(mask, angle_hat - 2.0 * kornia.pi, angle_hat)
mask = pi < angle_hat
# invert angle, if angle_axis axis points in the opposite direction of the original axis
dots = (log_q * axis).sum(dim=-1, keepdim=True)
- angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ angle_hat = torch.where(dots < 0.0, angle_hat * -1.0, angle_hat)
# angle_axis angle should match input angle
assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
# magnitude of angle should match matrix rotation angle
@@ -474,10 +466,10 @@ class TestAngleOfRotations:
assert_allclose(torch.abs(angle_hat), matrix_angle_abs, atol=atol, rtol=rtol)
@pytest.mark.parametrize('axis_name', ('x', 'y', 'z'))
- @pytest.mark.parametrize("angle_deg", (-179.9, -90., -45., 0, 45, 90, 179.9))
+ @pytest.mark.parametrize("angle_deg", (-179.9, -90.0, -45.0, 0, 45, 90, 179.9))
def test_log_quaternion(self, axis_name, angle_deg, device, dtype, atol, rtol):
eps = torch.finfo(dtype).eps
- angle = (angle_deg * kornia.pi / 180.).to(dtype).to(device).repeat(2, 1)
+ angle = (angle_deg * kornia.pi / 180.0).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
@@ -485,15 +477,15 @@ class TestAngleOfRotations:
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)
+ angle_hat = 2.0 * log_q.norm(p=2, dim=-1, keepdim=True)
# make sure it lands between [-pi..pi)
mask = pi < angle_hat
while torch.any(mask):
- angle_hat = torch.where(mask, angle_hat - 2. * kornia.pi, angle_hat)
+ angle_hat = torch.where(mask, angle_hat - 2.0 * kornia.pi, angle_hat)
mask = pi < angle_hat
# invert angle, if angle_axis axis points in the opposite direction of the original axis
dots = (log_q * axis).sum(dim=-1, keepdim=True)
- angle_hat = torch.where(dots < 0., angle_hat * -1., angle_hat)
+ angle_hat = torch.where(dots < 0.0, angle_hat * -1.0, angle_hat)
# angle_axis angle should match input angle
assert_allclose(angle_hat, angle, atol=atol, rtol=rtol)
# magnitude of angle should match matrix rotation angle
diff --git a/test/integration/test_focal.py b/test/integration/test_focal.py
index e1f279972..1bb08cddd 100644
--- a/test/integration/test_focal.py
+++ b/test/integration/test_focal.py
@@ -39,10 +39,7 @@ class TestIntegrationFocalLoss:
for i in range(1, self.num_classes):
target[..., i:-i, i:-i] = i
- m = nn.Sequential(
- nn.Conv2d(1, self.num_classes, kernel_size=3, padding=1),
- nn.ReLU(True),
- ).to(device)
+ m = nn.Sequential(nn.Conv2d(1, self.num_classes, kernel_size=3, padding=1), nn.ReLU(True)).to(device)
m.apply(self.init_weights)
optimizer = optim.Adam(m.parameters(), lr=self.lr)
diff --git a/test/integration/test_soft_argmax2d.py b/test/integration/test_soft_argmax2d.py
index c37654185..4a15db1dc 100644
--- a/test/integration/test_soft_argmax2d.py
+++ b/test/integration/test_soft_argmax2d.py
@@ -45,7 +45,7 @@ class TestIntegrationSoftArgmax2d:
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 3cd1b96dc..e66f92af8 100644
--- a/test/integration/test_warp.py
+++ b/test/integration/test_warp.py
@@ -8,7 +8,6 @@ import kornia
class MyHomography(nn.Module):
-
def __init__(self, init_homo: torch.Tensor) -> None:
super().__init__()
self.homo = nn.Parameter(init_homo.clone().detach())
diff --git a/test/morphology/test_bottom_hat.py b/test/morphology/test_bottom_hat.py
index b6f47d071..caaa307a4 100644
--- a/test/morphology/test_bottom_hat.py
+++ b/test/morphology/test_bottom_hat.py
@@ -7,7 +7,6 @@ from kornia.morphology.morphology import bottom_hat
class TestBlackHat:
-
def test_smoke(self, device, dtype):
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
@@ -20,11 +19,13 @@ class TestBlackHat:
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, :, :]
- 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, :, :]
+ input = torch.tensor([[0.5, 1.0, 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, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.2, 0.0, 0.5], [0.0, 0.4, 0.0], [0.3, 0.0, 0.6]], device=device, dtype=dtype)[
+ None, None, :, :
+ ]
assert_allclose(bottom_hat(input, kernel), expected)
def test_exception(self, device, dtype):
@@ -32,10 +33,10 @@ class TestBlackHat:
kernel = torch.ones(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert bottom_hat([0.], kernel)
+ assert bottom_hat([0.0], kernel)
with pytest.raises(TypeError):
- assert bottom_hat(input, [0.])
+ assert bottom_hat(input, [0.0])
with pytest.raises(ValueError):
test = torch.ones(2, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_closing.py b/test/morphology/test_closing.py
index ccb1c467e..45f3d8f32 100644
--- a/test/morphology/test_closing.py
+++ b/test/morphology/test_closing.py
@@ -7,7 +7,6 @@ from kornia.morphology.morphology import closing
class TestClosing:
-
def test_smoke(self, device, dtype):
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
@@ -20,11 +19,13 @@ class TestClosing:
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, :, :]
- 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, :, :]
+ tensor = torch.tensor([[0.5, 1.0, 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, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.7, 1.0, 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):
@@ -32,10 +33,10 @@ class TestClosing:
kernel = torch.ones(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert closing([0.], kernel)
+ assert closing([0.0], kernel)
with pytest.raises(TypeError):
- assert closing(tensor, [0.])
+ assert closing(tensor, [0.0])
with pytest.raises(ValueError):
test = torch.ones(2, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_dilation.py b/test/morphology/test_dilation.py
index b2f3b7c9c..90f778a54 100644
--- a/test/morphology/test_dilation.py
+++ b/test/morphology/test_dilation.py
@@ -7,7 +7,6 @@ from kornia.morphology.morphology import dilation
class TestDilate:
-
def test_smoke(self, device, dtype):
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
@@ -20,11 +19,13 @@ class TestDilate:
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, :, :]
- 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, :, :]
+ tensor = torch.tensor([[0.5, 1.0, 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, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[1.0, 1.0, 1.0], [0.7, 1.0, 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):
@@ -32,10 +33,10 @@ class TestDilate:
kernel = torch.ones(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert dilation([0.], kernel)
+ assert dilation([0.0], kernel)
with pytest.raises(TypeError):
- assert dilation(tensor, [0.])
+ assert dilation(tensor, [0.0])
with pytest.raises(ValueError):
test = torch.ones(2, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_erosion.py b/test/morphology/test_erosion.py
index 3a4da942b..333260c9c 100644
--- a/test/morphology/test_erosion.py
+++ b/test/morphology/test_erosion.py
@@ -7,7 +7,6 @@ from kornia.morphology.morphology import erosion
class TestErode:
-
def test_smoke(self, device, dtype):
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
@@ -20,11 +19,13 @@ class TestErode:
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, :, :]
- 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, :, :]
+ tensor = torch.tensor([[0.5, 1.0, 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, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], 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, :, :
+ ]
assert_allclose(erosion(tensor, kernel), expected)
def test_exception(self, device, dtype):
@@ -32,10 +33,10 @@ class TestErode:
kernel = torch.ones(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert erosion([0.], kernel)
+ assert erosion([0.0], kernel)
with pytest.raises(TypeError):
- assert erosion(tensor, [0.])
+ assert erosion(tensor, [0.0])
with pytest.raises(ValueError):
test = torch.ones(2, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_gradient.py b/test/morphology/test_gradient.py
index d44ed96ee..2e8985079 100644
--- a/test/morphology/test_gradient.py
+++ b/test/morphology/test_gradient.py
@@ -7,7 +7,6 @@ from kornia.morphology.morphology import gradient
class TestGradient:
-
def test_smoke(self, device, dtype):
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
@@ -20,11 +19,13 @@ class TestGradient:
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, :, :]
- 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, :, :]
+ tensor = torch.tensor([[0.5, 1.0, 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, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], 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, :, :
+ ]
assert_allclose(gradient(tensor, kernel), expected)
def test_exception(self, device, dtype):
@@ -32,10 +33,10 @@ class TestGradient:
kernel = torch.ones(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert gradient([0.], kernel)
+ assert gradient([0.0], kernel)
with pytest.raises(TypeError):
- assert gradient(tensor, [0.])
+ assert gradient(tensor, [0.0])
with pytest.raises(ValueError):
test = torch.ones(2, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_opening.py b/test/morphology/test_opening.py
index df314a9f0..6eed1974a 100644
--- a/test/morphology/test_opening.py
+++ b/test/morphology/test_opening.py
@@ -7,7 +7,6 @@ from kornia.morphology.morphology import opening
class TestOpening:
-
def test_smoke(self, device, dtype):
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
@@ -20,11 +19,13 @@ class TestOpening:
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, :, :]
- 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, :, :]
+ tensor = torch.tensor([[0.5, 1.0, 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, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], 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, :, :
+ ]
assert_allclose(opening(tensor, kernel), expected)
def test_exception(self, device, dtype):
@@ -32,10 +33,10 @@ class TestOpening:
kernel = torch.ones(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert opening([0.], kernel)
+ assert opening([0.0], kernel)
with pytest.raises(TypeError):
- assert opening(tensor, [0.])
+ assert opening(tensor, [0.0])
with pytest.raises(ValueError):
test = torch.ones(2, 3, 4, device=device, dtype=dtype)
diff --git a/test/morphology/test_top_hat.py b/test/morphology/test_top_hat.py
index f49cfe4a5..6780554fd 100644
--- a/test/morphology/test_top_hat.py
+++ b/test/morphology/test_top_hat.py
@@ -7,7 +7,6 @@ from kornia.morphology.morphology import top_hat
class TestTopHat:
-
def test_smoke(self, device, dtype):
kernel = torch.rand(3, 3, device=device, dtype=dtype)
assert kernel is not None
@@ -20,11 +19,13 @@ class TestTopHat:
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, :, :]
- 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, :, :]
+ input = torch.tensor([[0.5, 1.0, 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, 0.0, -1.0], [0.0, 0.0, 0.0], [-1.0, 0.0, -1.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.0, 0.5, 0.0], [0.2, 0.0, 0.5], [0.0, 0.5, 0.0]], device=device, dtype=dtype)[
+ None, None, :, :
+ ]
assert_allclose(top_hat(input, kernel), expected)
def test_exception(self, device, dtype):
@@ -32,10 +33,10 @@ class TestTopHat:
kernel = torch.ones(3, 3, device=device, dtype=dtype)
with pytest.raises(TypeError):
- assert top_hat([0.], kernel)
+ assert top_hat([0.0], kernel)
with pytest.raises(TypeError):
- assert top_hat(input, [0.])
+ assert top_hat(input, [0.0])
with pytest.raises(ValueError):
test = torch.ones(2, 3, 4, device=device, dtype=dtype)
diff --git a/test/performance/test_project_points_speed.py b/test/performance/test_project_points_speed.py
index 2e581fb97..d053d4efe 100644
--- a/test/performance/test_project_points_speed.py
+++ b/test/performance/test_project_points_speed.py
@@ -5,7 +5,7 @@ import torch
import kornia as kornia
-points_shapes = [(64, 1024**2, 3), (8192, 8192, 3), (1024**2, 64, 3)]
+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 6c97877af..db6d89efe 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -8,7 +8,6 @@ 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 +21,10 @@ 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)
@@ -41,14 +36,13 @@ class TestMaxBlurPool2d:
class TestExtractTensorPatches:
-
def test_smoke(self, device):
- input = torch.arange(16.).view(1, 1, 4, 4).to(device)
+ input = torch.arange(16.0).view(1, 1, 4, 4).to(device)
m = kornia.contrib.ExtractTensorPatches(3)
assert m(input).shape == (1, 4, 1, 3, 3)
def test_b1_ch1_h4w4_ws3(self, device):
- input = torch.arange(16.).view(1, 1, 4, 4).to(device)
+ input = torch.arange(16.0).view(1, 1, 4, 4).to(device)
m = kornia.contrib.ExtractTensorPatches(3)
patches = m(input)
assert patches.shape == (1, 4, 1, 3, 3)
@@ -58,7 +52,7 @@ class TestExtractTensorPatches:
assert_allclose(input[0, :, 1:, 1:], patches[0, 3])
def test_b1_ch2_h4w4_ws3(self, device):
- input = torch.arange(16.).view(1, 1, 4, 4).to(device)
+ input = torch.arange(16.0).view(1, 1, 4, 4).to(device)
input = input.expand(-1, 2, -1, -1) # copy all channels
m = kornia.contrib.ExtractTensorPatches(3)
patches = m(input)
@@ -69,7 +63,7 @@ class TestExtractTensorPatches:
assert_allclose(input[0, :, 1:, 1:], patches[0, 3])
def test_b1_ch1_h4w4_ws2(self, device):
- input = torch.arange(16.).view(1, 1, 4, 4).to(device)
+ input = torch.arange(16.0).view(1, 1, 4, 4).to(device)
m = kornia.contrib.ExtractTensorPatches(2)
patches = m(input)
assert patches.shape == (1, 9, 1, 2, 2)
@@ -79,7 +73,7 @@ class TestExtractTensorPatches:
assert_allclose(input[0, :, 2:4, 1:3], patches[0, 7])
def test_b1_ch1_h4w4_ws2_stride2(self, device):
- input = torch.arange(16.).view(1, 1, 4, 4).to(device)
+ input = torch.arange(16.0).view(1, 1, 4, 4).to(device)
m = kornia.contrib.ExtractTensorPatches(2, stride=2)
patches = m(input)
assert patches.shape == (1, 4, 1, 2, 2)
@@ -89,7 +83,7 @@ class TestExtractTensorPatches:
assert_allclose(input[0, :, 2:4, 2:4], patches[0, 3])
def test_b1_ch1_h4w4_ws2_stride21(self, device):
- input = torch.arange(16.).view(1, 1, 4, 4).to(device)
+ input = torch.arange(16.0).view(1, 1, 4, 4).to(device)
m = kornia.contrib.ExtractTensorPatches(2, stride=(2, 1))
patches = m(input)
assert patches.shape == (1, 6, 1, 2, 2)
@@ -99,7 +93,7 @@ class TestExtractTensorPatches:
assert_allclose(input[0, :, 2:4, 2:4], patches[0, 5])
def test_b1_ch1_h3w3_ws2_stride1_padding1(self, device):
- input = torch.arange(9.).view(1, 1, 3, 3).to(device)
+ input = torch.arange(9.0).view(1, 1, 3, 3).to(device)
m = kornia.contrib.ExtractTensorPatches(2, stride=1, padding=1)
patches = m(input)
assert patches.shape == (1, 16, 1, 2, 2)
@@ -110,7 +104,7 @@ class TestExtractTensorPatches:
def test_b2_ch1_h3w3_ws2_stride1_padding1(self, device):
batch_size = 2
- input = torch.arange(9.).view(1, 1, 3, 3).to(device)
+ input = torch.arange(9.0).view(1, 1, 3, 3).to(device)
input = input.expand(batch_size, -1, -1, -1)
m = kornia.contrib.ExtractTensorPatches(2, stride=1, padding=1)
patches = m(input)
@@ -122,7 +116,7 @@ class TestExtractTensorPatches:
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)
+ input = torch.arange(9.0).view(1, 1, 3, 3).to(device)
m = kornia.contrib.ExtractTensorPatches((2, 3))
patches = m(input)
assert patches.shape == (1, 2, 1, 2, 3)
@@ -130,7 +124,7 @@ class TestExtractTensorPatches:
assert_allclose(input[0, :, 1:3, 0:3], patches[0, 1])
def test_b1_ch1_h3w4_ws23(self, device):
- input = torch.arange(12.).view(1, 1, 3, 4).to(device)
+ input = torch.arange(12.0).view(1, 1, 3, 4).to(device)
m = kornia.contrib.ExtractTensorPatches((2, 3))
patches = m(input)
assert patches.shape == (1, 4, 1, 2, 3)
@@ -141,7 +135,6 @@ 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:
return kornia.denormalize_pixel_coordinates(input, height, width)
@@ -157,7 +150,4 @@ class TestExtractTensorPatches:
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 021ef9d30..17f6ac8e2 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -10,14 +10,14 @@ import kornia.testing as utils # test utils
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,8 +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):
@@ -35,8 +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):
@@ -45,8 +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):
@@ -69,9 +69,7 @@ class TestBinaryFocalLossWithLogits:
logits = utils.tensor_to_gradcheck_var(logits) # to var
assert gradcheck(
- kornia.losses.binary_focal_loss_with_logits,
- (logits, labels, alpha, gamma),
- raise_exception=True,
+ kornia.losses.binary_focal_loss_with_logits, (logits, labels, alpha, gamma), raise_exception=True
)
def test_same_output(self, device, dtype):
@@ -81,12 +79,12 @@ class TestBinaryFocalLossWithLogits:
kwargs = {"alpha": 0.25, "gamma": 2.0, "reduction": 'mean'}
- assert kornia.losses.binary_focal_loss_with_logits(logits, labels, **kwargs) == \
- kornia.losses.BinaryFocalLossWithLogits(**kwargs)(logits, labels)
+ assert kornia.losses.binary_focal_loss_with_logits(
+ logits, labels, **kwargs
+ ) == kornia.losses.BinaryFocalLossWithLogits(**kwargs)(logits, labels)
class TestFocalLoss:
-
def test_smoke_none(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -101,7 +99,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
@@ -109,14 +107,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
@@ -126,11 +124,7 @@ class TestFocalLoss:
labels = labels.to(device).long()
logits = utils.tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(
- kornia.losses.focal_loss,
- (logits, labels, alpha, gamma),
- raise_exception=True,
- )
+ assert gradcheck(kornia.losses.focal_loss, (logits, labels, alpha, gamma), raise_exception=True)
def test_jit(self, device, dtype):
num_classes = 3
@@ -162,7 +156,6 @@ 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)
@@ -192,11 +185,7 @@ class TestTverskyLoss:
labels = labels.to(device).long()
logits = utils.tensor_to_gradcheck_var(logits) # to var
- assert gradcheck(
- kornia.losses.tversky_loss,
- (logits, labels, alpha, beta),
- raise_exception=True,
- )
+ assert gradcheck(kornia.losses.tversky_loss, (logits, labels, alpha, beta), raise_exception=True)
def test_jit(self, device, dtype):
num_classes = 3
@@ -228,7 +217,6 @@ 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)
@@ -283,7 +271,6 @@ 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)
@@ -315,15 +302,10 @@ class TestDepthSmoothnessLoss:
depth = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
depth = utils.tensor_to_gradcheck_var(depth) # to var
image = utils.tensor_to_gradcheck_var(image) # to var
- assert gradcheck(
- kornia.losses.inverse_depth_smoothness_loss,
- (depth, image),
- raise_exception=True,
- )
+ assert gradcheck(kornia.losses.inverse_depth_smoothness_loss, (depth, image), raise_exception=True)
class TestSSIMLoss:
-
def test_ssim_equal_none(self, device, dtype):
# input data
img1 = torch.rand(1, 1, 10, 16, device=device, dtype=dtype)
@@ -388,50 +370,53 @@ class TestSSIMLoss:
class TestDivergenceLoss:
-
@pytest.mark.parametrize(
- 'input,target,expected', [
+ '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))
assert_allclose(actual.item(), expected)
@pytest.mark.parametrize(
- 'input,target,expected', [
+ '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))
assert_allclose(actual.item(), expected)
@pytest.mark.parametrize(
- 'input,target,expected', [
+ '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')
assert_allclose(actual, expected.to(device, dtype))
@pytest.mark.parametrize(
- 'input,target,expected', [
+ '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
@@ -440,12 +425,13 @@ class TestDivergenceLoss:
assert_allclose(actual, expected)
@pytest.mark.parametrize(
- 'input,target,expected', [
+ '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
@@ -491,10 +477,7 @@ 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)),
- ]
+ '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))
@@ -502,7 +485,8 @@ class TestTotalVariation:
# Total variation for 3D tensors
@pytest.mark.parametrize(
- 'input, expected', [
+ 'input, expected',
+ [
(
torch.tensor(
[
@@ -510,28 +494,29 @@ class TestTotalVariation:
[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.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.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]
- ]
+ [0.71935296, 0.9625162, 0.42287344, 0.07979459, 0.9149871],
+ ],
]
- ), torch.tensor(33.001236)
+ ),
+ torch.tensor(33.001236),
),
(
- torch.tensor([[[0.09094203, 0.32630223, 0.8066123], [0.10921168, 0.09534764, 0.48588026]]]
- ), torch.tensor(1.6900232)
+ 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))
@@ -539,50 +524,49 @@ class TestTotalVariation:
# Total variation for 4D tensors
@pytest.mark.parametrize(
- 'input, expected', [
+ '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.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]]
- ]
+ [[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([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]]]
+ [[[0.5078, 0.5703, 0.9110], [0.4765, 0.8401, 0.2754]]],
]
- ), torch.tensor([1.9565653, 2.5786452, 2.2681699])
+ ),
+ 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)
# Expect ValueError to be raised when tensors of ndim != 3 or 4 are passed
- @pytest.mark.parametrize('input', [
- torch.rand(2, 3, 4, 5, 3),
- torch.rand(3, 1),
- ])
+ @pytest.mark.parametrize('input', [torch.rand(2, 3, 4, 5, 3), torch.rand(3, 1)])
def test_tv_on_invalid_dims(self, device, dtype, input):
with pytest.raises(ValueError) as ex_info:
kornia.losses.total_variation(input.to(device, dtype))
# Expect TypeError to be raised when non-torch tensors are passed
- @pytest.mark.parametrize('input', [
- 1,
- [1, 2],
- ])
+ @pytest.mark.parametrize('input', [1, [1, 2]])
def test_tv_on_invalid_types(self, device, dtype, input):
with pytest.raises(TypeError) as ex_info:
kornia.losses.total_variation(input)
@@ -606,11 +590,10 @@ 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)
@@ -637,20 +620,20 @@ class TestPSNRLoss:
def test_metric(self, device, dtype):
input = torch.ones(1, device=device, dtype=dtype)
expected = torch.tensor(20.0, device=device, dtype=dtype)
- actual = kornia.losses.psnr(input, 1.2 * input, 2.)
+ actual = kornia.losses.psnr(input, 1.2 * input, 2.0)
assert_allclose(actual, expected)
def test_loss(self, device, dtype):
input = torch.ones(1, device=device, dtype=dtype)
expected = torch.tensor(-20.0, device=device, dtype=dtype)
- actual = kornia.losses.psnr_loss(input, 1.2 * input, 2.)
+ actual = kornia.losses.psnr_loss(input, 1.2 * input, 2.0)
assert_allclose(actual, expected)
def test_jit(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)
- args = (input, target, 1.)
+ args = (input, target, 1.0)
op = kornia.losses.psnr_loss
op_script = torch.jit.script(op)
@@ -661,10 +644,10 @@ class TestPSNRLoss:
input = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
target = torch.rand(2, 3, 3, 2, device=device, dtype=dtype)
- args = (input, target, 1.)
+ args = (input, target, 1.0)
op = kornia.losses.psnr_loss
- op_module = kornia.losses.PSNRLoss(1.)
+ op_module = kornia.losses.PSNRLoss(1.0)
assert_allclose(op(*args), op_module(input, target))
diff --git a/test/utils/test_draw.py b/test/utils/test_draw.py
index cd1f7d08d..3e352e2c6 100644
--- a/test/utils/test_draw.py
+++ b/test/utils/test_draw.py
@@ -5,12 +5,11 @@ 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):
black_image = torch.zeros(batch, 1, 3, 3, device=device) # 1 channel 3x3 black_image
- points = torch.tensor([1., 1., 1., 1.]).to(device).expand(batch, 1, 4) # single pixel rectangle
+ points = torch.tensor([1.0, 1.0, 1.0, 1.0]).to(device).expand(batch, 1, 4) # single pixel rectangle
draw_rectangle(black_image, points, color=color)
@@ -47,10 +46,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)
@@ -62,25 +61,44 @@ class TestDrawRectangle:
for b in range(batch):
for n in range(N):
if fill:
- assert random_w_rectangle[b, :, points_list[b][n][1]:points_list[b][n][3] + 1,
- points_list[b][n][0]:points_list[b][n][2] + 1].sum() \
- == (points_list[b][n][3] - points_list[b][n][1] + 1) * \
- (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
+ assert (
+ random_w_rectangle[
+ b,
+ :,
+ points_list[b][n][1] : points_list[b][n][3] + 1,
+ points_list[b][n][0] : points_list[b][n][2] + 1,
+ ].sum()
+ == (points_list[b][n][3] - points_list[b][n][1] + 1)
+ * (points_list[b][n][2] - points_list[b][n][0] + 1)
+ * 3
+ )
else:
- assert random_w_rectangle[b, :, points_list[b][n][1]:points_list[b][n][3] + 1,
- points_list[b][n][0]].sum() \
+ assert (
+ random_w_rectangle[
+ b, :, points_list[b][n][1] : points_list[b][n][3] + 1, points_list[b][n][0]
+ ].sum()
== (points_list[b][n][3] - points_list[b][n][1] + 1) * 3
- assert random_w_rectangle[b, :, points_list[b][n][1]:points_list[b][n][3] + 1,
- points_list[b][n][2]].sum() \
+ )
+ assert (
+ random_w_rectangle[
+ b, :, points_list[b][n][1] : points_list[b][n][3] + 1, points_list[b][n][2]
+ ].sum()
== (points_list[b][n][3] - points_list[b][n][1] + 1) * 3
- assert random_w_rectangle[b, :, points_list[b][n][1],
- points_list[b][n][0]:points_list[b][n][2] + 1].sum() \
+ )
+ assert (
+ random_w_rectangle[
+ b, :, points_list[b][n][1], points_list[b][n][0] : points_list[b][n][2] + 1
+ ].sum()
== (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
- assert random_w_rectangle[b, :, points_list[b][n][1],
- points_list[b][n][0]:points_list[b][n][2] + 1].sum() \
+ )
+ assert (
+ random_w_rectangle[
+ b, :, points_list[b][n][1], points_list[b][n][0] : points_list[b][n][2] + 1
+ ].sum()
== (points_list[b][n][2] - points_list[b][n][0] + 1) * 3
+ )
- @pytest.mark.parametrize('color', (torch.tensor([.5, .3, .15]), torch.tensor([.23, .33, .8])))
+ @pytest.mark.parametrize('color', (torch.tensor([0.5, 0.3, 0.15]), torch.tensor([0.23, 0.33, 0.8])))
def test_color_background(self, device, color):
image = torch.zeros(1, 3, 40, 40, device=device)
image[:, 0, :, :] = color[0]
@@ -92,13 +110,17 @@ class TestDrawRectangle:
points = torch.tensor([[[p1[1], p1[0], p2[1], p2[0]]]], device=device)
draw_rectangle(image_w_rectangle, points, color=torch.tensor([1.0]))
- assert torch.abs((image_w_rectangle - image).sum() -
- (1 - color[0]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4) -
- (1 - color[1]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4) -
- (1 - color[2]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4)) \
+ assert (
+ torch.abs(
+ (image_w_rectangle - image).sum()
+ - (1 - color[0]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4)
+ - (1 - color[1]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4)
+ - (1 - color[2]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1] + 1) - 4)
+ )
<= 0.0001
+ )
- @pytest.mark.parametrize('color', (torch.tensor([.34, .63, .16]), torch.tensor([.29, .13, .48])))
+ @pytest.mark.parametrize('color', (torch.tensor([0.34, 0.63, 0.16]), torch.tensor([0.29, 0.13, 0.48])))
def test_color_foreground(self, device, color):
image = torch.zeros(1, 3, 50, 40, device=device)
image_w_rectangle = image.clone()
@@ -109,8 +131,12 @@ class TestDrawRectangle:
draw_rectangle(image_w_rectangle, points, color=color)
# corners are double counted, no plus 1 for y since p2[1] of 40 already lies outside of the image
- assert torch.abs((image_w_rectangle - image).sum() -
- (color[0]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4) -
- (color[1]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4) -
- (color[2]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4)) \
+ assert (
+ torch.abs(
+ (image_w_rectangle - image).sum()
+ - (color[0]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4)
+ - (color[1]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4)
+ - (color[2]) * (2 * (p2[0] - p1[0] + 1) + 2 * (p2[1] - p1[1]) - 4)
+ )
<= 0.0001
+ )
diff --git a/test/utils/test_grid.py b/test/utils/test_grid.py
index e3cd272be..61c4b4e03 100644
--- a/test/utils/test_grid.py
+++ b/test/utils/test_grid.py
@@ -17,7 +17,7 @@ def test_create_meshgrid(device, dtype):
assert grid.shape == (1, height, width, 2)
# check grid corner values
- assert tuple(grid[0, 0, 0].cpu().numpy()) == (0., 0.)
+ assert tuple(grid[0, 0, 0].cpu().numpy()) == (0.0, 0.0)
assert tuple(grid[0, height - 1, width - 1].cpu().numpy()) == (width - 1, height - 1)
@@ -64,5 +64,5 @@ def test_create_meshgrid3d(device, dtype):
assert grid.shape == (1, depth, height, width, 3)
# check grid corner values
- assert tuple(grid[0, 0, 0, 0].cpu().numpy()) == (0., 0., 0.)
+ assert tuple(grid[0, 0, 0, 0].cpu().numpy()) == (0.0, 0.0, 0.0)
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 d859bdc6e..587b9d737 100644
--- a/test/utils/test_helpers.py
+++ b/test/utils/test_helpers.py
@@ -8,7 +8,8 @@ from kornia.utils.helpers import _torch_solve_cast, _torch_svd_cast
@pytest.mark.parametrize(
- "tensor_list,out_device,out_dtype,will_throw_error", [
+ "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),
@@ -18,23 +19,30 @@ from kornia.utils.helpers import _torch_solve_cast, _torch_svd_cast
([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.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.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
+ [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():
import warnings
+
warnings.warn("Add GPU tests.")
if will_throw_error:
@@ -47,7 +55,6 @@ 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)])
def test_smoke(self, device, dtype, input_shape):
x = torch.rand(input_shape, device=device, dtype=dtype)
@@ -55,15 +62,9 @@ class TestInverseCast(object):
assert y.shape == x.shape
def test_values(self, device, dtype):
- x = torch.tensor([
- [4., 7.],
- [2., 6.],
- ], device=device, dtype=dtype)
+ x = torch.tensor([[4.0, 7.0], [2.0, 6.0]], device=device, dtype=dtype)
- y_expected = torch.tensor([
- [0.6, -0.7],
- [-0.2, 0.4],
- ], device=device, dtype=dtype)
+ y_expected = torch.tensor([[0.6, -0.7], [-0.2, 0.4]], device=device, dtype=dtype)
y = _torch_inverse_cast(x)
@@ -77,10 +78,9 @@ 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)
+ x = torch.tensor([1.0, 2.0, 1.0], device=device, dtype=dtype)
+ y_expected = torch.tensor([0.0, 2.0, 1.0, 0.0], device=device, dtype=dtype)
y = _torch_histc_cast(x, bins=4, min=0, max=3)
@@ -88,7 +88,6 @@ 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)
@@ -98,7 +97,6 @@ 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 4fd54022a..ee731f641 100644
--- a/test/utils/test_image.py
+++ b/test/utils/test_image.py
@@ -7,11 +7,7 @@ import kornia as kornia
@pytest.mark.parametrize(
- "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)
@@ -20,14 +16,15 @@ def test_image_to_tensor_keep_dtype(input_dtype, expected_dtype):
@pytest.mark.parametrize(
- "input_shape, expected", [
+ "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)
@@ -37,14 +34,15 @@ def test_tensor_to_image(device, input_shape, expected):
@pytest.mark.parametrize(
- "input_shape, expected", [
+ "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)
@@ -57,14 +55,15 @@ def test_image_to_tensor(input_shape, expected):
@pytest.mark.parametrize(
- "input_shape, expected", [
+ "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)
diff --git a/test/utils/test_metrics.py b/test/utils/test_metrics.py
index 240505cd4..e57884e53 100644
--- a/test/utils/test_metrics.py
+++ b/test/utils/test_metrics.py
@@ -5,7 +5,6 @@ import kornia as kornia
class TestMeanIoU:
-
def test_two_classes_perfect(self):
batch_size = 1
num_classes = 2
@@ -64,7 +63,6 @@ class TestMeanIoU:
class TestConfusionMatrix:
-
def test_two_classes(self):
num_classes = 2
actual = torch.tensor([[1, 1, 1, 1, 0, 0, 0, 0]])
diff --git a/test/utils/test_one_hot.py b/test/utils/test_one_hot.py
index 3f4d85924..e00daf51a 100644
--- a/test/utils/test_one_hot.py
+++ b/test/utils/test_one_hot.py
@@ -5,7 +5,6 @@ import kornia as kornia
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 6f95f1d05..8ef7ce44f 100644
--- a/test/utils/test_pointcloud_io.py
+++ b/test/utils/test_pointcloud_io.py
@@ -7,7 +7,6 @@ import kornia
class TestSaveLoadPointCloud:
-
def test_save_pointcloud(self):
height, width = 10, 8
xyz_save = torch.rand(height, width, 3)
diff --git a/tutorials/color_adjust.py b/tutorials/color_adjust.py
index a12559d22..7e7902601 100644
--- a/tutorials/color_adjust.py
+++ b/tutorials/color_adjust.py
@@ -26,7 +26,7 @@ x_rgb: torch.Tensor = kornia.bgr_to_rgb(x_bgr)
#############################
# Create batch and normalize
x_rgb = x_rgb.expand(4, -1, -1, -1) # 4xCxHxW
-x_rgb = x_rgb.float() / 255.
+x_rgb = x_rgb.float() / 255.0
def imshow(input: torch.Tensor):
@@ -36,6 +36,7 @@ def imshow(input: torch.Tensor):
plt.axis('off')
plt.show()
+
#############################
# Show original
imshow(x_rgb)
@@ -52,7 +53,7 @@ imshow(x_contrast)
#############################
# Adjust Gamma
-x_gamma: torch.Tensor = kornia.adjust_gamma(x_rgb, gamma=3., gain=1.5)
+x_gamma: torch.Tensor = kornia.adjust_gamma(x_rgb, gamma=3.0, gain=1.5)
imshow(x_gamma)
#############################
diff --git a/tutorials/color_conversions.py b/tutorials/color_conversions.py
index c3470be7f..369d17654 100644
--- a/tutorials/color_conversions.py
+++ b/tutorials/color_conversions.py
@@ -45,6 +45,7 @@ def imshow(input: torch.Tensor):
plt.axis('off')
plt.show()
+
#############################
# Create a batch of images
xb_bgr = torch.cat([x_bgr, hflip(x_bgr), vflip(x_bgr), rot180(x_bgr)])
@@ -58,18 +59,18 @@ imshow(xb_rgb)
#############################
# Convert RGB to grayscale
# NOTE: image comes in torch.uint8, and kornia assumes floating point type
-xb_gray = kornia.rgb_to_grayscale(xb_rgb.float() / 255.)
+xb_gray = kornia.rgb_to_grayscale(xb_rgb.float() / 255.0)
imshow(xb_gray)
#############################
# Convert RGB to HSV
-xb_hsv = kornia.rgb_to_hsv(xb_rgb.float() / 255.)
+xb_hsv = kornia.rgb_to_hsv(xb_rgb.float() / 255.0)
imshow(xb_hsv[:, 2:3])
#############################
# Convert RGB to YUV
# NOTE: image comes in torch.uint8, and kornia assumes floating point type
-yuv = kornia.rgb_to_yuv(xb_rgb.float() / 255.)
+yuv = kornia.rgb_to_yuv(xb_rgb.float() / 255.0)
y_channel = torchvision.utils.make_grid(yuv, nrow=2)[0, :, :]
plt.imshow(y_channel, cmap='gray', vmin=0, vmax=1) # Displaying only y channel
plt.axis('off')
diff --git a/tutorials/data_augmentation.py b/tutorials/data_augmentation.py
index 26aeef48e..ed43701a5 100644
--- a/tutorials/data_augmentation.py
+++ b/tutorials/data_augmentation.py
@@ -35,6 +35,7 @@ class DummyDataset(Dataset):
label = torch.rand(1, 240, 320)
return dict(images=image, labels=label)
+
################################
# 2. Define the data augmentation operations
# Thanks to the `kornia` design all the operators can be placed inside inside a `nn.Sequential`.
@@ -42,9 +43,7 @@ class DummyDataset(Dataset):
import kornia
transform = nn.Sequential(
- kornia.enhance.AdjustBrightness(0.5),
- kornia.enhance.AdjustGamma(gamma=2.),
- kornia.enhance.AdjustContrast(0.7),
+ kornia.enhance.AdjustBrightness(0.5), kornia.enhance.AdjustGamma(gamma=2.0), kornia.enhance.AdjustContrast(0.7)
)
################################
diff --git a/tutorials/filter_blurring.py b/tutorials/filter_blurring.py
index 2545ea788..5d0e397f0 100644
--- a/tutorials/filter_blurring.py
+++ b/tutorials/filter_blurring.py
@@ -26,7 +26,7 @@ x_rgb: torch.Tensor = kornia.bgr_to_rgb(x_bgr)
#############################
# Create batch and normalize
x_rgb = x_rgb.expand(2, -1, -1, -1) # 4xCxHxW
-x_rgb = x_rgb.float() / 255.
+x_rgb = x_rgb.float() / 255.0
def imshow(input: torch.Tensor):
@@ -35,6 +35,7 @@ def imshow(input: torch.Tensor):
plt.imshow(out_np)
plt.axis('off')
+
#############################
# Show original
imshow(x_rgb)
@@ -51,5 +52,5 @@ imshow(x_blur)
#############################
# Gaussian Blur
-x_blur: torch.Tensor = kornia.gaussian_blur2d(x_rgb, (11, 11), (11., 11.))
+x_blur: torch.Tensor = kornia.gaussian_blur2d(x_rgb, (11, 11), (11.0, 11.0))
imshow(x_blur)
diff --git a/tutorials/filter_edges.py b/tutorials/filter_edges.py
index 4a06eb1d7..79ba3c693 100644
--- a/tutorials/filter_edges.py
+++ b/tutorials/filter_edges.py
@@ -26,7 +26,7 @@ x_rgb: torch.Tensor = kornia.bgr_to_rgb(x_bgr)
#############################
# Create batch and normalize
x_rgb = x_rgb.expand(2, -1, -1, -1) # 4xCxHxW
-x_gray = kornia.rgb_to_grayscale(x_rgb.float() / 255.)
+x_gray = kornia.rgb_to_grayscale(x_rgb.float() / 255.0)
def imshow(input: torch.Tensor):
@@ -35,6 +35,7 @@ def imshow(input: torch.Tensor):
plt.imshow(out_np)
plt.axis('off')
+
#############################
# Show original
imshow(x_rgb)
diff --git a/tutorials/total_variation_denoising.py b/tutorials/total_variation_denoising.py
index 6e5eb2774..24ea9f571 100644
--- a/tutorials/total_variation_denoising.py
+++ b/tutorials/total_variation_denoising.py
@@ -38,6 +38,7 @@ class TVDenoise(torch.nn.Module):
def get_clean_image(self):
return self.clean_image
+
tv_denoiser = TVDenoise(noisy_image)
# define the optimizer to optimize the 1 parameter of tv_denoiser
diff --git a/tutorials/warp_perspective.py b/tutorials/warp_perspective.py
index b979b0c8d..e6a9b4d53 100644
--- a/tutorials/warp_perspective.py
+++ b/tutorials/warp_perspective.py
@@ -20,15 +20,11 @@ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
data: torch.tensor = kornia.image_to_tensor(img, keepdim=False) # BxCxHxW
# the source points are the region to crop corners
-points_src = torch.tensor([[
- [125., 150.], [562., 40.], [562., 282.], [54., 328.],
-]])
+points_src = torch.tensor([[[125.0, 150.0], [562.0, 40.0], [562.0, 282.0], [54.0, 328.0]]])
# the destination points are the image vertexes
h, w = 64, 128 # destination size
-points_dst = torch.tensor([[
- [0., 0.], [w - 1., 0.], [w - 1., h - 1.], [0., h - 1.],
-]])
+points_dst = torch.tensor([[[0.0, 0.0], [w - 1.0, 0.0], [w - 1.0, h - 1.0], [0.0, h - 1.0]]])
# compute perspective transform
M: torch.tensor = kornia.get_perspective_transform(points_src, points_dst)