Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

enable black in the precommit (#1777)

Edgar Riba08de6723e143
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 490517a48..dc298b031 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -20,7 +20,6 @@ repos:
rev: 22.6.0
hooks:
- id: black
- args: [--diff]
- repo: https://github.com/codespell-project/codespell
rev: v2.1.0
diff --git a/docs/source/_static/image_registration.py b/docs/source/_static/image_registration.py
index 0345f6ffc..02e826c61 100644
--- a/docs/source/_static/image_registration.py
+++ b/docs/source/_static/image_registration.py
@@ -14,7 +14,7 @@ def load_timg(file_name):
# load image with OpenCV
img = cv2.imread(file_name, cv2.IMREAD_COLOR)
# convert image to torch tensor
- tensor = K.image_to_tensor(img, None).float() / 255.
+ tensor = K.image_to_tensor(img, None).float() / 255.0
return K.color.bgr_to_rgb(tensor)
@@ -28,11 +28,11 @@ video_writer = imageio.get_writer('medical_registration.gif', fps=2)
timg_dst_first = img1.clone()
timg_dst_first[0, 0, :, :] = img2[0, 0, :, :]
-video_writer.append_data(K.tensor_to_image((timg_dst_first * 255.).byte()))
+video_writer.append_data(K.tensor_to_image((timg_dst_first * 255.0).byte()))
with torch.no_grad():
for m in intermediate:
timg_dst = KG.homography_warp(img1, m, img2.shape[-2:])
timg_dst[0, 0, :, :] = img2[0, 0, :, :]
- video_writer.append_data(K.tensor_to_image((timg_dst_first * 255.).byte()))
+ video_writer.append_data(K.tensor_to_image((timg_dst_first * 255.0).byte()))
video_writer.close()
diff --git a/docs/source/conf.py b/docs/source/conf.py
index cc2518aad..f95ddc4c0 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -134,7 +134,6 @@ html_theme_options = {
"color-sidebar-caption-text": "white",
"color-sidebar-link-text--top-level": "white",
},
-
# "announcement": """
# <a style=\"text-decoration: none; color: white;\"
# href=\"https://github.com/kornia/kornia\">
diff --git a/kornia/__init__.py b/kornia/__init__.py
index aaf5fec5b..d21a2087b 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -8,28 +8,9 @@ from . import geometry
from . import grad_estimator
# import the other modules for convenience
-from . import (
- augmentation,
- color,
- contrib,
- core,
- enhance,
- feature,
- io,
- losses,
- metrics,
- morphology,
- tracking,
- utils,
- x,
-)
+from . import augmentation, color, contrib, core, enhance, feature, io, losses, metrics, morphology, tracking, utils, x
+
# NOTE: we are going to expose to top level very few things
from kornia.constants import pi
from kornia.testing import xla_is_available
-from kornia.utils import (
- eye_like,
- vec_like,
- create_meshgrid,
- image_to_tensor,
- tensor_to_image,
-)
+from kornia.utils import eye_like, vec_like, create_meshgrid, image_to_tensor, tensor_to_image
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 7297b0612..8ff9d1b8f 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -129,6 +129,8 @@ class RandomAffine(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
- flags=flags
+ input,
+ params=self._params,
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index baf86be66..c2b35af13 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -40,14 +40,14 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
) -> Tensor:
flags = self.flags if flags is None else flags
if params is not None:
- transform = self.compute_transformation(
- input[params['batch_prob']], params=params, flags=flags)
+ transform = self.compute_transformation(input[params['batch_prob']], params=params, flags=flags)
elif self.transform_matrix is None:
params = self.forward_parameters(input.shape)
transform = self.identity_matrix(input)
transform[params['batch_prob']] = self.compute_transformation(
- input[params['batch_prob']], params=params, flags=flags)
+ input[params['batch_prob']], params=params, flags=flags
+ )
else:
transform = self.transform_matrix
return as_tensor(transform, device=input.device, dtype=input.dtype)
@@ -82,7 +82,8 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
if params is not None:
transform = self.identity_matrix(in_tensor)
transform[params['batch_prob']] = self.compute_transformation(
- in_tensor[params['batch_prob']], params=params, flags=flags)
+ in_tensor[params['batch_prob']], params=params, flags=flags
+ )
else:
# Avoid recompute.
transform = self.get_transformation_matrix(in_tensor, params=params, flags=flags)
@@ -107,5 +108,6 @@ class GeometricAugmentationBase2D(AugmentationBase2D):
else:
transform[to_apply] = self.compute_inverse_transformation(transform[to_apply])
output[to_apply] = self.inverse_transform(
- in_tensor[to_apply], transform=transform[to_apply], size=size, flags=flags)
+ in_tensor[to_apply], transform=transform[to_apply], size=size, flags=flags
+ )
return cast(Tensor, self.transform_output_tensor(output, input_shape)) if self.keepdim else output
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 6a615951f..df8848bf1 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -83,8 +83,11 @@ class CenterCrop(GeometricAugmentationBase2D):
raise Exception(f"Invalid size type. Expected (int, tuple(int, int). " f"Got: {type(size)}.")
self.flags = dict(
- resample=Resample.get(resample), cropping_mode=cropping_mode, align_corners=align_corners, size=self.size,
- padding_mode="zeros"
+ resample=Resample.get(resample),
+ cropping_mode=cropping_mode,
+ align_corners=align_corners,
+ size=self.size,
+ padding_mode="zeros",
)
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, Tensor]:
@@ -104,12 +107,7 @@ class CenterCrop(GeometricAugmentationBase2D):
transform = cast(Tensor, transform)
return crop_by_transform_mat(
- input,
- transform[:, :2, :],
- self.size,
- flags["resample"].name.lower(),
- "zeros",
- flags["align_corners"],
+ input, transform[:, :2, :], self.size, flags["resample"].name.lower(), "zeros", flags["align_corners"]
)
if flags["cropping_mode"] == "slice": # uses advanced slicing to crop
return crop_by_indices(input, params["src"], flags["size"])
@@ -130,6 +128,10 @@ class CenterCrop(GeometricAugmentationBase2D):
size = self.size
transform = cast(Tensor, transform)
return crop_by_transform_mat(
- input, transform[:, :2, :], size, flags["resample"].name.lower(),
- flags["padding_mode"], flags["align_corners"]
+ input,
+ transform[:, :2, :],
+ size,
+ flags["resample"].name.lower(),
+ flags["padding_mode"],
+ flags["align_corners"],
)
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 6914ec2d8..239aba6ae 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -112,19 +112,9 @@ class RandomCrop(GeometricAugmentationBase2D):
if isinstance(flags["padding"], int):
padding = [flags["padding"]] * 4
elif isinstance(flags["padding"], tuple) and len(flags["padding"]) == 2:
- padding = [
- flags["padding"][1],
- flags["padding"][1],
- flags["padding"][0],
- flags["padding"][0],
- ]
+ padding = [flags["padding"][1], flags["padding"][1], flags["padding"][0], flags["padding"][0]]
elif isinstance(flags["padding"], tuple) and len(flags["padding"]) == 4:
- padding = [
- flags["padding"][3],
- flags["padding"][2],
- flags["padding"][1],
- flags["padding"][0],
- ]
+ padding = [flags["padding"][3], flags["padding"][2], flags["padding"][1], flags["padding"][0]]
else:
raise RuntimeError(f"Expect `padding` to be a scalar, or length 2/4 list. Got {flags['padding']}.")
@@ -204,8 +194,12 @@ class RandomCrop(GeometricAugmentationBase2D):
else:
padding_mode = flags['padding_mode']
return crop_by_transform_mat(
- input, transform[:, :2, :], size, flags["resample"].name.lower(),
- padding_mode=padding_mode, align_corners=flags["align_corners"]
+ input,
+ transform[:, :2, :],
+ size,
+ flags["resample"].name.lower(),
+ padding_mode=padding_mode,
+ align_corners=flags["align_corners"],
)
def inverse(
@@ -237,12 +231,7 @@ class RandomCrop(GeometricAugmentationBase2D):
_params.update({"padding_size": padding_size})
return _params
- def forward(
- self,
- input: Tensor,
- params: Optional[Dict[str, Tensor]] = None,
- **kwargs
- ) -> Tensor:
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
padding_size = params.get("padding_size") if params else None
if padding_size is not None:
input_pad = padding_size.unique(dim=0).cpu().squeeze().numpy().tolist()
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index 4c68c1235..d546cbeda 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -55,9 +55,7 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
w: int = int(params["forward_input_shape"][-1])
- flip_mat: Tensor = torch.tensor(
- [[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype
- )
+ flip_mat: Tensor = torch.tensor([[-1, 0, w - 1], [0, 1, 0], [0, 0, 1]], device=input.device, dtype=input.dtype)
return flip_mat.repeat(input.size(0), 1, 1)
@@ -74,6 +72,8 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
- flags=flags
+ input,
+ params=self._params,
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index f38c66442..e610e020f 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -70,8 +70,7 @@ class RandomPerspective(GeometricAugmentationBase2D):
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = cast(
- rg.PerspectiveGenerator,
- rg.PerspectiveGenerator(distortion_scale, sampling_method=sampling_method)
+ rg.PerspectiveGenerator, rg.PerspectiveGenerator(distortion_scale, sampling_method=sampling_method)
)
self.flags: Dict[str, Any] = dict(align_corners=align_corners, resample=Resample.get(resample))
@@ -85,11 +84,7 @@ class RandomPerspective(GeometricAugmentationBase2D):
transform = cast(Tensor, transform)
return warp_perspective(
- input,
- transform,
- (height, width),
- mode=flags["resample"].name.lower(),
- align_corners=flags["align_corners"],
+ input, transform, (height, width), mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
)
def inverse_transform(
@@ -100,6 +95,8 @@ class RandomPerspective(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
- flags=flags
+ input,
+ params=self._params,
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index be5211316..852de78dc 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -34,14 +34,10 @@ class Resize(GeometricAugmentationBase2D):
return_transform: Optional[bool] = None,
keepdim: bool = False,
) -> None:
- super().__init__(p=1., return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
+ super().__init__(p=1.0, return_transform=return_transform, same_on_batch=True, p_batch=p, keepdim=keepdim)
self._param_generator = cast(rg.ResizeGenerator, rg.ResizeGenerator(resize_to=size, side=side))
self.flags = dict(
- size=size,
- side=side,
- resample=Resample.get(resample),
- align_corners=align_corners,
- antialias=antialias
+ size=size, side=side, resample=Resample.get(resample), align_corners=align_corners, antialias=antialias
)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
@@ -69,7 +65,7 @@ class Resize(GeometricAugmentationBase2D):
out_size,
interpolation=flags["resample"].name.lower(),
align_corners=flags["align_corners"],
- antialias=flags["antialias"]
+ antialias=flags["antialias"],
)
return out
@@ -83,7 +79,8 @@ class Resize(GeometricAugmentationBase2D):
size = cast(Tuple[int, int], size)
transform = cast(Tensor, transform)
return crop_by_transform_mat(
- input, transform[:, :2, :], size, flags["resample"], flags["padding_mode"], flags["align_corners"])
+ input, transform[:, :2, :], size, flags["resample"], flags["padding_mode"], flags["align_corners"]
+ )
class LongestMaxSize(Resize):
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index c9ac735f9..4a9af6583 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -82,8 +82,11 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
)
self._param_generator = cast(rg.ResizedCropGenerator, rg.ResizedCropGenerator(size, scale, ratio))
self.flags = dict(
- size=size, resample=Resample.get(resample), align_corners=align_corners, cropping_mode=cropping_mode,
- padding_mode="zeros"
+ size=size,
+ resample=Resample.get(resample),
+ align_corners=align_corners,
+ cropping_mode=cropping_mode,
+ padding_mode="zeros",
)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
@@ -112,7 +115,7 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
params["src"],
flags["size"],
interpolation=flags["resample"].name.lower(),
- align_corners=flags["align_corners"]
+ align_corners=flags["align_corners"],
)
raise NotImplementedError(f"Not supported type: {flags['cropping_mode']}.")
@@ -130,6 +133,10 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
size = cast(Tuple[int, int], size)
transform = cast(Tensor, transform)
return crop_by_transform_mat(
- input, transform[:, :2, :], size, flags["resample"].name.lower(),
- flags["padding_mode"], flags["align_corners"]
+ input,
+ transform[:, :2, :],
+ size,
+ flags["resample"].name.lower(),
+ flags["padding_mode"],
+ flags["align_corners"],
)
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 6872ea22a..de0df969f 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -99,9 +99,7 @@ class RandomRotation(GeometricAugmentationBase2D):
) -> Tensor:
transform = cast(Tensor, transform)
- return affine(
- input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"]
- )
+ return affine(input, transform[..., :2, :3], flags["resample"].name.lower(), "zeros", flags["align_corners"])
def inverse_transform(
self,
@@ -111,6 +109,8 @@ class RandomRotation(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
- flags=flags
+ input,
+ params=self._params,
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ flags=flags,
)
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index 66ffec339..d51077a1c 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -48,9 +48,7 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
h: int = int(params["forward_input_shape"][-2])
- flip_mat: Tensor = torch.tensor(
- [[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype
- )
+ flip_mat: Tensor = torch.tensor([[1, 0, 0], [0, -1, h - 1], [0, 0, 1]], device=input.device, dtype=input.dtype)
return flip_mat.repeat(input.size(0), 1, 1)
@@ -67,6 +65,8 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
size: Optional[Tuple[int, int]] = None,
) -> Tensor:
return self.apply_transform(
- input, params=self._params, transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
- flags=flags
+ input,
+ params=self._params,
+ transform=torch.as_tensor(transform, device=input.device, dtype=input.dtype),
+ flags=flags,
)
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 7b7ec1cab..3842163c0 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -64,7 +64,7 @@ class ColorJiggle(IntensityAugmentationBase2D):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- return_transform: Optional[bool] = None
+ return_transform: Optional[bool] = None,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self.brightness = brightness
@@ -72,8 +72,7 @@ class ColorJiggle(IntensityAugmentationBase2D):
self.saturation = saturation
self.hue = hue
self._param_generator = cast(
- rg.ColorJiggleGenerator,
- rg.ColorJiggleGenerator(brightness, contrast, saturation, hue)
+ rg.ColorJiggleGenerator, rg.ColorJiggleGenerator(brightness, contrast, saturation, hue)
)
def apply_transform(
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index 6923bb92f..ddda9667e 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -75,7 +75,7 @@ class ColorJitter(IntensityAugmentationBase2D):
p: float = 1.0,
keepdim: bool = False,
return_transform: Optional[bool] = None,
- silence_instantiation_warning: bool = False
+ silence_instantiation_warning: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
@@ -83,7 +83,7 @@ class ColorJitter(IntensityAugmentationBase2D):
warnings.warn(
"`ColorJitter` is now following Torchvision implementation. Old "
"behavior can be retrieved by instantiating `ColorJiggle`.",
- category=DeprecationWarning
+ category=DeprecationWarning,
)
self.brightness = brightness
@@ -91,8 +91,7 @@ class ColorJitter(IntensityAugmentationBase2D):
self.saturation = saturation
self.hue = hue
self._param_generator = cast(
- rg.ColorJitterGenerator,
- rg.ColorJitterGenerator(brightness, contrast, saturation, hue)
+ rg.ColorJitterGenerator, rg.ColorJitterGenerator(brightness, contrast, saturation, hue)
)
def apply_transform(
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.py
index c04215215..be8213f47 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -65,6 +65,4 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
- return gaussian_blur2d(
- input, flags["kernel_size"], flags["sigma"], flags["border_type"].name.lower()
- )
+ return gaussian_blur2d(input, flags["kernel_size"], flags["sigma"], flags["border_type"].name.lower())
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index 91f98e6dd..96a199b55 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -87,9 +87,11 @@ class RandomRGBShift(IntensityAugmentationBase2D):
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = cast(
rg.PlainUniformGenerator,
- rg.PlainUniformGenerator((r_shift_limit, "r_shift", 0, (-r_shift_limit, r_shift_limit)),
- (g_shift_limit, "g_shift", 0, (-g_shift_limit, g_shift_limit)),
- (b_shift_limit, "b_shift", 0, (-b_shift_limit, b_shift_limit)))
+ rg.PlainUniformGenerator(
+ (r_shift_limit, "r_shift", 0, (-r_shift_limit, r_shift_limit)),
+ (g_shift_limit, "g_shift", 0, (-g_shift_limit, g_shift_limit)),
+ (b_shift_limit, "b_shift", 0, (-b_shift_limit, b_shift_limit)),
+ ),
)
def apply_transform(
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index 3d104f89e..7988895f0 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -95,9 +95,7 @@ class RandomAffine3D(AugmentationBase3D):
],
translate: Optional[Union[Tensor, Tuple[float, float, float]]] = None,
scale: Optional[
- Union[
- Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]
- ]
+ Union[Tensor, Tuple[float, float], Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]
] = None,
shears: Union[
Tensor,
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index fe0080af0..29305257c 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -96,9 +96,5 @@ class CenterCrop3D(AugmentationBase3D):
) -> Tensor:
transform = cast(Tensor, transform)
return crop_by_transform_mat3d(
- input,
- transform,
- self.size,
- mode=flags["resample"].name.lower(),
- align_corners=flags["align_corners"],
+ input, transform, self.size, mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
)
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 0e3fc76b0..e0f40b93b 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -133,19 +133,10 @@ class RandomCrop3D(AugmentationBase3D):
) -> Tensor:
transform = cast(Tensor, transform)
return crop_by_transform_mat3d(
- input,
- transform,
- flags["size"],
- mode=flags["resample"].name.lower(),
- align_corners=flags["align_corners"],
+ input, transform, flags["size"], mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
)
- def forward( # type: ignore
- self,
- input: Tensor,
- params: Optional[Dict[str, Tensor]] = None,
- **kwargs
- ) -> Tensor:
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor: # type: ignore
# TODO: need to align 2D implementations
input = self.precrop_padding(input)
return super().forward(input, params) # type:ignore
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index b07962037..553e221d4 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -59,8 +59,11 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
"""
def __init__(
- self, return_transform: Optional[bool] = None,
- same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False
+ self,
+ return_transform: Optional[bool] = None,
+ same_on_batch: bool = False,
+ p: float = 0.5,
+ keepdim: bool = False,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 7a752a853..f5eaa60ed 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -110,6 +110,4 @@ class RandomRotation3D(AugmentationBase3D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
transform = cast(Tensor, transform)
- return affine3d(
- input, transform[..., :3, :4], flags["resample"].name.lower(), "zeros", flags["align_corners"]
- )
+ return affine3d(input, transform[..., :3, :4], flags["resample"].name.lower(), "zeros", flags["align_corners"])
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 0a570e8ba..2cff5e256 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -151,9 +151,7 @@ class _BasicAugmentationBase(nn.Module):
def apply_func(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
return self.apply_transform(input, params, flags)
- def forward( # type: ignore
- self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs
- ) -> Tensor:
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor: # type: ignore
"""Perform forward operations.
Args:
@@ -215,11 +213,11 @@ class _AugmentationBase(_BasicAugmentationBase):
if return_transform is not None:
raise ValueError(
"`return_transform` is deprecated. Please access the transformation matrix with "
- "`.transform_matrix`. For chained matrices, please use `AugmentationSequential`.",
+ "`.transform_matrix`. For chained matrices, please use `AugmentationSequential`."
)
@property
- def transform_matrix(self,) -> Tensor:
+ def transform_matrix(self) -> Tensor:
return self._transform_matrix
def __repr__(self) -> str:
@@ -237,10 +235,7 @@ class _AugmentationBase(_BasicAugmentationBase):
raise NotImplementedError
def apply_func( # type: ignore
- self,
- in_tensor: Tensor,
- params: Dict[str, Tensor],
- flags: Optional[Dict[str, Any]] = None
+ self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
) -> Tensor:
if flags is None:
flags = self.flags
@@ -257,10 +252,10 @@ class _AugmentationBase(_BasicAugmentationBase):
else:
output = in_tensor.clone()
trans_matrix = self.identity_matrix(in_tensor)
- trans_matrix[to_apply] = self.compute_transformation(
- in_tensor[to_apply], params=params, flags=flags)
+ trans_matrix[to_apply] = self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)
output[to_apply] = self.apply_transform(
- in_tensor[to_apply], params=params, flags=flags, transform=trans_matrix[to_apply])
+ in_tensor[to_apply], params=params, flags=flags, transform=trans_matrix[to_apply]
+ )
self._transform_matrix = trans_matrix
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
index 469f40a81..6642af1b6 100644
--- a/kornia/augmentation/container/utils.py
+++ b/kornia/augmentation/container/utils.py
@@ -15,12 +15,11 @@ from kornia.augmentation.utils import override_parameters
from kornia.constants import DataKey
from kornia.geometry.bbox import transform_bbox
from kornia.geometry.linalg import transform_points
+from kornia.testing import KORNIA_UNWRAP
from kornia.utils.helpers import _torch_inverse_cast
-def _get_geometric_only_param(
- module: "kornia.augmentation.ImageSequential", param: List[ParamItem]
-) -> List[ParamItem]:
+def _get_geometric_only_param(module: "kornia.augmentation.ImageSequential", param: List[ParamItem]) -> List[ParamItem]:
named_modules: Iterator[Tuple[str, nn.Module]] = module.get_forward_sequence(param)
res: List[ParamItem] = []
@@ -36,8 +35,12 @@ class ApplyInverseInterface(metaclass=ABCMeta):
@classmethod
@abstractmethod
def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: nn.Module, param: ParamItem,
- extra_args: Dict[str, Any] = {}
+ cls,
+ input: Tensor,
+ label: Optional[Tensor],
+ module: nn.Module,
+ param: ParamItem,
+ extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -53,8 +56,7 @@ class ApplyInverseInterface(metaclass=ABCMeta):
@classmethod
@abstractmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -74,8 +76,12 @@ class ApplyInverseImpl(ApplyInverseInterface):
@classmethod
def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: nn.Module, param: ParamItem,
- extra_args: Dict[str, Any] = {}
+ cls,
+ input: Tensor,
+ label: Optional[Tensor],
+ module: nn.Module,
+ param: ParamItem,
+ extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -106,8 +112,7 @@ class ApplyInverseImpl(ApplyInverseInterface):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -131,28 +136,27 @@ class ApplyInverseImpl(ApplyInverseInterface):
@classmethod
def _get_transformation(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: nn.Module, maybe_param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Optional[Tensor]:
if (
isinstance(module, (GeometricAugmentationBase2D, kornia.augmentation.ImageSequential))
- and param is None
+ and maybe_param is None
):
raise ValueError(f"Parameters of transformation matrix for {module} has not been computed.")
- mat: Optional[Tensor] = None
+ maybe_mat: Optional[Tensor] = None
+ param = KORNIA_UNWRAP(maybe_param, ParamItem)
if isinstance(module, GeometricAugmentationBase2D):
- _param = cast(Dict[str, Tensor], param.data) # type: ignore
+ param_data = KORNIA_UNWRAP(param.data, Dict[str, Tensor])
flags = override_parameters(module.flags, extra_args)
- mat = module.get_transformation_matrix(input, _param, flags=flags)
+ maybe_mat = module.get_transformation_matrix(input, param_data, flags=flags)
elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
- _param = cast(List[ParamItem], param.data) # type: ignore
- mat = module.get_transformation_matrix(
- input, _param, recompute=False, extra_args=extra_args) # type: ignore
+ param_data = KORNIA_UNWRAP(param.data, List[ParamItem])
+ maybe_mat = module.get_transformation_matrix(input, param_data, recompute=False, extra_args=extra_args)
else:
- return None # No need to update anything
- return mat
+ pass # No need to update anything
+ return maybe_mat
@classmethod
def _get_inverse_transformation(cls, transform: Tensor) -> Tensor:
@@ -161,12 +165,17 @@ class ApplyInverseImpl(ApplyInverseInterface):
class InputApplyInverse(ApplyInverseImpl):
"""Apply and inverse transformations for (image) input tensors."""
+
data_key = DataKey.INPUT
@classmethod
def apply_trans( # type: ignore
- cls, input: Tensor, label: Optional[Tensor], module: nn.Module, param: ParamItem,
- extra_args: Dict[str, Any] = {}
+ cls,
+ input: Tensor,
+ label: Optional[Tensor],
+ module: nn.Module,
+ param: ParamItem,
+ extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -204,8 +213,7 @@ class InputApplyInverse(ApplyInverseImpl):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -217,22 +225,24 @@ class InputApplyInverse(ApplyInverseImpl):
"""
if isinstance(module, GeometricAugmentationBase2D):
input = module.inverse(
- input, params=None if param is None else cast(Dict, param.data), extra_args=extra_args)
+ input, params=None if param is None else cast(Dict, param.data), extra_args=extra_args
+ )
elif isinstance(module, kornia.augmentation.ImageSequential):
temp = module.apply_inverse_func
module.apply_inverse_func = InputApplyInverse
if isinstance(module, kornia.augmentation.AugmentationSequential):
- input = cast(Tensor, module.inverse(
- input, params=None if param is None else cast(List, param.data)))
+ input = cast(Tensor, module.inverse(input, params=None if param is None else cast(List, param.data)))
else:
input = module.inverse(
- input, params=None if param is None else cast(List, param.data), extra_args=extra_args)
+ input, params=None if param is None else cast(List, param.data), extra_args=extra_args
+ )
module.apply_inverse_func = temp
return input
class MaskApplyInverse(ApplyInverseImpl):
"""Apply and inverse transformations for mask tensors."""
+
data_key = DataKey.MASK
@classmethod
@@ -250,8 +260,12 @@ class MaskApplyInverse(ApplyInverseImpl):
@classmethod
def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls,
+ input: Tensor,
+ label: Optional[Tensor],
+ module: nn.Module,
+ param: Optional[ParamItem] = None,
+ extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -287,8 +301,7 @@ class MaskApplyInverse(ApplyInverseImpl):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -300,13 +313,11 @@ class MaskApplyInverse(ApplyInverseImpl):
"""
if isinstance(module, GeometricAugmentationBase2D):
- input = module.inverse(
- input, params=None if param is None else cast(Dict, param.data), **extra_args)
+ input = module.inverse(input, params=None if param is None else cast(Dict, param.data), **extra_args)
elif isinstance(module, kornia.augmentation.ImageSequential):
temp = module.apply_inverse_func
module.apply_inverse_func = MaskApplyInverse
- input = module.inverse(
- input, params=None if param is None else cast(List, param.data))
+ input = module.inverse(input, params=None if param is None else cast(List, param.data))
module.apply_inverse_func = temp
return input
@@ -331,7 +342,7 @@ class BBoxApplyInverse(ApplyInverseImpl):
input: (B, N, 4, 2)
padding_size: (B, 4)
"""
- if len(input.shape) not in (3, 4,):
+ if len(input.shape) not in (3, 4):
raise AssertionError(input.shape)
if len(padding_size.shape) != 2:
@@ -358,7 +369,7 @@ class BBoxApplyInverse(ApplyInverseImpl):
input: (B, N, 4, 2)
padding_size: (B, 4)
"""
- if len(input.shape) not in (3, 4,):
+ if len(input.shape) not in (3, 4):
raise AssertionError(input.shape)
if len(padding_size.shape) != 2:
@@ -382,8 +393,12 @@ class BBoxApplyInverse(ApplyInverseImpl):
@classmethod
def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: nn.Module, param: ParamItem,
- extra_args: Dict[str, Any] = {}
+ cls,
+ input: Tensor,
+ label: Optional[Tensor],
+ module: nn.Module,
+ param: ParamItem,
+ extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -408,8 +423,7 @@ class BBoxApplyInverse(ApplyInverseImpl):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -456,16 +470,19 @@ class BBoxXYXYApplyInverse(BBoxApplyInverse):
@classmethod
def apply_trans(
- cls, input: Tensor, label: Optional[Tensor], module: nn.Module, param: ParamItem,
- extra_args: Dict[str, Any] = {}
+ cls,
+ input: Tensor,
+ label: Optional[Tensor],
+ module: nn.Module,
+ param: ParamItem,
+ extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
warnings.warn("BBoxXYXYApplyInverse is no longer maintained. Please use BBoxApplyInverse instead.")
return super().apply_trans(input, label=label, module=module, param=param, extra_args=extra_args)
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None,
- extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
warnings.warn("BBoxXYXYApplyInverse is no longer maintained. Please use BBoxApplyInverse instead.")
return super().inverse(input, module=module, param=param, extra_args=extra_args)
@@ -510,7 +527,7 @@ class KeypointsApplyInverse(BBoxApplyInverse):
@classmethod
def pad(cls, input: Tensor, padding_size: Tensor) -> Tensor:
- if len(input.shape) not in (2, 3,):
+ if len(input.shape) not in (2, 3):
raise AssertionError(input.shape)
if len(padding_size.shape) != 2:
@@ -533,7 +550,7 @@ class KeypointsApplyInverse(BBoxApplyInverse):
@classmethod
def unpad(cls, input: Tensor, padding_size: Tensor) -> Tensor:
- if len(input.shape) not in (2, 3,):
+ if len(input.shape) not in (2, 3):
raise AssertionError(input.shape)
if len(padding_size.shape) != 2:
raise AssertionError(padding_size.shape)
@@ -578,7 +595,7 @@ class ApplyInverse:
module: nn.Module,
param: ParamItem,
dcate: Union[str, int, DataKey] = DataKey.INPUT,
- extra_args: Dict[str, Any] = {}
+ extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -605,7 +622,7 @@ class ApplyInverse:
module: nn.Module,
param: Optional[ParamItem] = None,
dcate: Union[str, int, DataKey] = DataKey.INPUT,
- extra_args: Dict[str, Any] = {}
+ extra_args: Dict[str, Any] = {},
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index fc97131b6..81771a238 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -200,8 +200,13 @@ class VideoSequential(ImageSequential):
if self.same_on_frame:
for k, v in mod_param.items():
# TODO: revise ColorJiggle and ColorJitter order param in the future to align the standard.
- if not (k == "order" and (isinstance(module, kornia.augmentation.ColorJiggle)
- or isinstance(module, kornia.augmentation.ColorJitter))):
+ if not (
+ k == "order"
+ and (
+ isinstance(module, kornia.augmentation.ColorJiggle)
+ or isinstance(module, kornia.augmentation.ColorJitter)
+ )
+ ):
mod_param.update({k: self.__repeat_param_across_channels__(v, frame_num)})
param = ParamItem(name, mod_param)
else:
@@ -211,8 +216,7 @@ class VideoSequential(ImageSequential):
return params
def inverse(
- self, input: torch.Tensor, params: Optional[List[ParamItem]] = None,
- extra_args: Dict[str, Any] = {}
+ self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
) -> torch.Tensor:
"""Inverse transformation.
@@ -235,8 +239,11 @@ class VideoSequential(ImageSequential):
return input
def forward( # type: ignore
- self, input: torch.Tensor, label: Optional[torch.Tensor] = None, params: Optional[List[ParamItem]] = None,
- extra_args: Dict[str, Any] = {}
+ self,
+ input: torch.Tensor,
+ label: Optional[torch.Tensor] = None,
+ params: Optional[List[ParamItem]] = None,
+ extra_args: Dict[str, Any] = {},
) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
"""Define the video computation performed."""
if len(input.shape) != 5:
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index bb494db19..a3e6ebdda 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -50,14 +50,12 @@ class ColorJiggleGenerator(RandomGeneratorBase):
def __repr__(self) -> str:
repr = (
- f"brightness={self.brightness}, contrast={self.contrast}, saturation="
- f"{self.saturation}, hue={self.hue}"
+ f"brightness={self.brightness}, contrast={self.contrast}, saturation=" f"{self.saturation}, hue={self.hue}"
)
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- brightness = _range_bound(self.brightness, 'brightness', center=1.0,
- bounds=(0, 2), device=device, dtype=dtype)
+ brightness = _range_bound(self.brightness, 'brightness', center=1.0, bounds=(0, 2), device=device, dtype=dtype)
contrast: Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)
saturation: Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)
hue: Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)
diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.py
index bf3146a10..87b3bdcf2 100644
--- a/kornia/augmentation/random_generator/_2d/color_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -50,15 +50,12 @@ class ColorJitterGenerator(RandomGeneratorBase):
def __repr__(self) -> str:
repr = (
- f"brightness={self.brightness}, contrast={self.contrast}, saturation="
- f"{self.saturation}, hue={self.hue}"
+ f"brightness={self.brightness}, contrast={self.contrast}, saturation=" f"{self.saturation}, hue={self.hue}"
)
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- brightness: Tensor = _range_bound(
- self.brightness, 'brightness', center=1.0, device=device, dtype=dtype
- )
+ brightness: Tensor = _range_bound(self.brightness, 'brightness', center=1.0, device=device, dtype=dtype)
contrast: Tensor = _range_bound(self.contrast, 'contrast', center=1.0, device=device, dtype=dtype)
saturation: Tensor = _range_bound(self.saturation, 'saturation', center=1.0, device=device, dtype=dtype)
hue: Tensor = _range_bound(self.hue, 'hue', bounds=(-0.5, 0.5), device=device, dtype=dtype)
diff --git a/kornia/augmentation/random_generator/_2d/planckian_jitter.py b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
index d6378c4e5..9a81c8065 100644
--- a/kornia/augmentation/random_generator/_2d/planckian_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
@@ -8,8 +8,7 @@ from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _
class PlanckianJitterGenerator(RandomGeneratorBase):
- r"""Generate random planckian jitter parameters for a batch of images
- """
+ r"""Generate random planckian jitter parameters for a batch of images"""
def __init__(self, domain: List[float]) -> None:
super().__init__()
@@ -17,19 +16,14 @@ class PlanckianJitterGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- idx_range = _range_bound(self.domain,
- 'idx_range',
- device=device, dtype=dtype)
+ idx_range = _range_bound(self.domain, 'idx_range', device=device, dtype=dtype)
_joint_range_check(idx_range, 'idx_range', (0, self.domain[1]))
self.pl_idx_dist = Uniform(idx_range[0], idx_range[1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool =
- False) -> Dict[str, torch.Tensor]:
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
- pl_idx = _adapted_rsampling((batch_size,),
- self.pl_idx_dist,
- same_on_batch)
+ pl_idx = _adapted_rsampling((batch_size,), self.pl_idx_dist, same_on_batch)
return dict(idx=pl_idx.long())
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index f1b19f744..6f323528e 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -132,9 +132,7 @@ def _validate_input_dtype(input: Tensor, accepted_dtypes: List) -> None:
raise TypeError(f"Expected input of {accepted_dtypes}. Got {input.dtype}")
-def _transform_output_shape(
- output: Tensor, shape: Tuple
-) -> Tensor:
+def _transform_output_shape(output: Tensor, shape: Tuple) -> Tensor:
r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
Args:
input: Tensor
@@ -248,9 +246,7 @@ def _adapted_beta(
By default, sampling happens on the default device and dtype. If a/b is a tensor, sampling will happen
in the same device/dtype as a/b tensor.
"""
- device, dtype = _extract_device_dtype(
- [a if isinstance(a, Tensor) else None, b if isinstance(b, Tensor) else None]
- )
+ device, dtype = _extract_device_dtype([a if isinstance(a, Tensor) else None, b if isinstance(b, Tensor) else None])
a = torch.as_tensor(a, device=device, dtype=dtype)
b = torch.as_tensor(b, device=device, dtype=dtype)
dist = Beta(a, b, validate_args=False)
@@ -278,8 +274,10 @@ def deepcopy_dict(params: Dict[str, Any]) -> Dict[str, Any]:
def override_parameters(
- params: Dict[str, Any], params_override: Optional[Dict[str, Any]] = None,
- if_none_exist: str = 'ignore', in_place: bool = False
+ params: Dict[str, Any],
+ params_override: Optional[Dict[str, Any]] = None,
+ if_none_exist: str = 'ignore',
+ in_place: bool = False,
) -> Dict[str, Any]:
"""Override params dict w.r.t params_override.
diff --git a/kornia/color/hsv.py b/kornia/color/hsv.py
index 7d6bd0677..95d618e8c 100644
--- a/kornia/color/hsv.py
+++ b/kornia/color/hsv.py
@@ -43,14 +43,14 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
deltac = torch.where(deltac == 0, torch.ones_like(deltac), deltac)
rc, gc, bc = torch.unbind((max_rgb.unsqueeze(-3) - image), dim=-3)
- h1 = (bc - gc)
+ h1 = bc - gc
h2 = (rc - bc) + 2.0 * deltac
h3 = (gc - rc) + 4.0 * deltac
h = torch.stack((h1, h2, h3), dim=-3) / deltac.unsqueeze(-3)
h = torch.gather(h, dim=-3, index=argmax_rgb.unsqueeze(-3)).squeeze(-3)
h = (h / 6.0) % 1.0
- h = 2. * math.pi * h # we return 0/2pi output
+ h = 2.0 * math.pi * h # we return 0/2pi output
return torch.stack((h, s, v), dim=-3)
diff --git a/kornia/color/raw.py b/kornia/color/raw.py
index a273ab5c5..977eb93c7 100644
--- a/kornia/color/raw.py
+++ b/kornia/color/raw.py
@@ -123,18 +123,21 @@ def raw_to_rgb(image: torch.Tensor, cfa: CFA) -> torch.Tensor:
# for a 2x2 bayer filter
gpadded = torch.nn.functional.pad(image, [1, 1, 1, 1], 'reflect')
- ru = torch.nn.functional.interpolate(rpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1),
- mode='bilinear', align_corners=True)
- bu = torch.nn.functional.interpolate(bpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1),
- mode='bilinear', align_corners=True)
+ ru = torch.nn.functional.interpolate(
+ rpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode='bilinear', align_corners=True
+ )
+ bu = torch.nn.functional.interpolate(
+ bpadded, size=(image.shape[-2] + 1, image.shape[-1] + 1), mode='bilinear', align_corners=True
+ )
# remove the extra padding
ru = torch.nn.functional.pad(ru, [-x for x in rpad])
bu = torch.nn.functional.pad(bu, [-x for x in bpad])
# all unknown pixels are the average of the nearby green samples
- kernel = torch.tensor([[[[0.0, 0.25, 0.0], [0.25, 0.0, 0.25], [0.0, 0.25, 0.0]]]],
- dtype=image.dtype, device=image.device)
+ kernel = torch.tensor(
+ [[[[0.0, 0.25, 0.0], [0.25, 0.0, 0.25], [0.0, 0.25, 0.0]]]], dtype=image.dtype, device=image.device
+ )
# This is done on all samples but result for the known green samples is then overwritten by the input
gu = torch.nn.functional.conv2d(gpadded, kernel)
diff --git a/kornia/color/yuv.py b/kornia/color/yuv.py
index 905a2057d..aafeb4af7 100644
--- a/kornia/color/yuv.py
+++ b/kornia/color/yuv.py
@@ -171,10 +171,15 @@ def yuv420_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
if len(imagey.shape) < 2 or imagey.shape[-2] % 2 == 1 or imagey.shape[-1] % 2 == 1:
raise ValueError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")
- if (len(imageuv.shape) < 2 or len(imagey.shape) < 2 or imagey.shape[-2] / imageuv.shape[-2] != 2
- or imagey.shape[-1] / imageuv.shape[-1] != 2):
- raise ValueError(f"Input imageuv H&W must be half the size of the luma plane. "
- f"Got {imagey.shape} and {imageuv.shape}")
+ if (
+ len(imageuv.shape) < 2
+ or len(imagey.shape) < 2
+ or imagey.shape[-2] / imageuv.shape[-2] != 2
+ or imagey.shape[-1] / imageuv.shape[-1] != 2
+ ):
+ raise ValueError(
+ f"Input imageuv H&W must be half the size of the luma plane. " f"Got {imagey.shape} and {imageuv.shape}"
+ )
# first upsample
yuv444image = torch.cat([imagey, imageuv.repeat_interleave(2, dim=-1).repeat_interleave(2, dim=-2)], dim=-3)
@@ -218,8 +223,9 @@ def yuv422_to_rgb(imagey: torch.Tensor, imageuv: torch.Tensor) -> torch.Tensor:
raise ValueError(f"Input H&W must be evenly disible by 2. Got {imagey.shape}")
if len(imageuv.shape) < 2 or len(imagey.shape) < 2 or imagey.shape[-1] / imageuv.shape[-1] != 2:
- raise ValueError(f"Input imageuv W must be half the size of the luma plane. "
- f"Got {imagey.shape} and {imageuv.shape}")
+ raise ValueError(
+ f"Input imageuv W must be half the size of the luma plane. " f"Got {imagey.shape} and {imageuv.shape}"
+ )
# first upsample
yuv444image = torch.cat([imagey, imageuv.repeat_interleave(2, dim=-1)], dim=-3)
diff --git a/kornia/contrib/classification.py b/kornia/contrib/classification.py
index 81270299f..8bda9d01a 100644
--- a/kornia/contrib/classification.py
+++ b/kornia/contrib/classification.py
@@ -16,6 +16,7 @@ class ClassificationHead(nn.Module):
>>> head(feat).shape
torch.Size([1, 10])
"""
+
def __init__(self, embed_size: int = 768, num_classes: int = 10) -> None:
super().__init__()
self.norm = nn.LayerNorm(embed_size)
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 254039b91..56eb2c017 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -7,11 +7,7 @@ from kornia.filters import filter2d
from kornia.utils import create_meshgrid
-def distance_transform(
- image: torch.Tensor,
- kernel_size: int = 3,
- h: float = 0.35
-) -> torch.Tensor:
+def distance_transform(image: torch.Tensor, kernel_size: int = 3, h: float = 0.35) -> torch.Tensor:
r"""Approximates the Manhattan distance transform of images using cascaded convolution operations.
The value at each pixel in the output represents the distance to the nearest non-zero pixel in the image image.
@@ -43,8 +39,9 @@ def distance_transform(
# n_iters is set such that the DT will be able to propagate from any corner of the image to its far,
# diagonally opposite corner
n_iters: int = math.ceil(max(image.shape[2], image.shape[3]) / math.floor(kernel_size / 2))
- grid = create_meshgrid(kernel_size, kernel_size, normalized_coordinates=False,
- device=image.device, dtype=image.dtype)
+ grid = create_meshgrid(
+ kernel_size, kernel_size, normalized_coordinates=False, device=image.device, dtype=image.dtype
+ )
grid -= math.floor(kernel_size / 2)
kernel = torch.hypot(grid[0, :, :, 0], grid[0, :, :, 1])
@@ -82,11 +79,8 @@ class DistanceTransform(nn.Module):
h: value that influence the approximation of the min function.
"""
- def __init__(
- self,
- kernel_size: int = 3,
- h: float = 0.35
- ):
+
+ def __init__(self, kernel_size: int = 3, h: float = 0.35):
super().__init__()
self.kernel_size = kernel_size
self.h = h
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index 59facc4e8..60efb91d6 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -9,11 +9,7 @@ import torch.nn.functional as F
from kornia.geometry.bbox import nms as nms_kornia
-__all__ = [
- "FaceDetector",
- "FaceDetectorResult",
- "FaceKeypoint",
-]
+__all__ = ["FaceDetector", "FaceDetectorResult", "FaceKeypoint"]
url: str = "https://github.com/kornia/data/raw/main/yunet_final.pth"
@@ -38,6 +34,7 @@ class FaceDetectorResult:
data: the encoded results coming from the feature detector with shape :math:`(14,)`.
"""
+
def __init__(self, data: torch.Tensor) -> None:
if len(data) < 15:
raise ValueError(f"Result must comes as vector of size(14). Got: {data.shape}.")
@@ -147,11 +144,10 @@ class FaceDetector(nn.Module):
>>> detect = FaceDetector()
>>> res = detect(img)
"""
- def __init__(self,
- top_k: int = 5000,
- confidence_threshold: float = 0.3,
- nms_threshold: float = 0.3,
- keep_top_k: int = 750) -> None:
+
+ def __init__(
+ self, top_k: int = 5000, confidence_threshold: float = 0.3, nms_threshold: float = 0.3, keep_top_k: int = 750
+ ) -> None:
super().__init__()
self.top_k = top_k
self.confidence_threshold = confidence_threshold
@@ -177,12 +173,11 @@ class FaceDetector(nn.Module):
def postprocess(self, data: Dict[str, torch.Tensor], height: int, width: int) -> torch.Tensor:
loc, conf, iou = data['loc'], data['conf'], data['iou']
- scale = torch.tensor([
- width, height, width, height,
- width, height, width, height,
- width, height, width, height,
- width, height,
- ], device=loc.device, dtype=loc.dtype) # 14
+ scale = torch.tensor(
+ [width, height, width, height, width, height, width, height, width, height, width, height, width, height],
+ device=loc.device,
+ dtype=loc.dtype,
+ ) # 14
priors = _PriorBox(self.min_sizes, self.steps, self.clip, image_size=(height, width))
priors = priors.to(loc.device, loc.dtype)
@@ -192,14 +187,14 @@ class FaceDetector(nn.Module):
# clamp here for the compatibility for ONNX
cls_scores, iou_scores = conf[:, 1], iou[:, 0]
- scores = (cls_scores * iou_scores.clamp(0., 1.)).sqrt()
+ scores = (cls_scores * iou_scores.clamp(0.0, 1.0)).sqrt()
# ignore low scores
- inds = (scores > self.confidence_threshold)
+ inds = scores > self.confidence_threshold
boxes, scores = boxes[inds], scores[inds]
# keep top-K before NMS
- order = scores.sort(descending=True)[1][:self.top_k]
+ order = scores.sort(descending=True)[1][: self.top_k]
boxes, scores = boxes[order], scores[order]
# performd NMS
@@ -210,7 +205,7 @@ class FaceDetector(nn.Module):
dets = dets[keep, :]
# keep top-K faster NMS
- return dets[:self.keep_top_k]
+ return dets[: self.keep_top_k]
def forward(self, image: torch.Tensor) -> torch.Tensor:
img = self.preprocess(image)
@@ -220,6 +215,7 @@ class FaceDetector(nn.Module):
# utils for the network
+
class ConvDPUnit(nn.Sequential):
def __init__(self, in_channels, out_channels, withBNRelu=True):
super().__init__()
@@ -282,9 +278,7 @@ class YuFaceDetectNet(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- url, map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(url, map_location=storage_fcn)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
@@ -348,14 +342,18 @@ def _decode(loc: torch.Tensor, priors: torch.Tensor, variances: List[float]) ->
Return:
Tensor containing decoded bounding box predictions.
"""
- boxes = torch.cat((
- priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4],
- priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]),
- priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4],
- priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4],
- priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4],
- priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4],
- priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4]), 1)
+ boxes = torch.cat(
+ (
+ priors[:, 0:2] + loc[:, 0:2] * variances[0] * priors[:, 2:4],
+ priors[:, 2:4] * torch.exp(loc[:, 2:4] * variances[1]),
+ priors[:, 0:2] + loc[:, 4:6] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 6:8] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 8:10] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 10:12] * variances[0] * priors[:, 2:4],
+ priors[:, 0:2] + loc[:, 12:14] * variances[0] * priors[:, 2:4],
+ ),
+ 1,
+ )
# prepare final output
tmp = boxes[:, 0:2] - boxes[:, 2:4] / 2
return torch.cat((tmp, boxes[:, 2:4] + tmp, boxes[:, 4:]), dim=-1)
@@ -372,22 +370,16 @@ class _PriorBox:
self.dtype: torch.dtype = torch.float32
for i in range(4):
- if(self.steps[i] != math.pow(2, (i + 3))):
+ if self.steps[i] != math.pow(2, (i + 3)):
raise ValueError("steps must be [8,16,32,64]")
- self.feature_map_2th = [int(int((self.image_size[0] + 1) / 2) / 2),
- int(int((self.image_size[1] + 1) / 2) / 2)]
- self.feature_map_3th = [int(self.feature_map_2th[0] / 2),
- int(self.feature_map_2th[1] / 2)]
- self.feature_map_4th = [int(self.feature_map_3th[0] / 2),
- int(self.feature_map_3th[1] / 2)]
- self.feature_map_5th = [int(self.feature_map_4th[0] / 2),
- int(self.feature_map_4th[1] / 2)]
- self.feature_map_6th = [int(self.feature_map_5th[0] / 2),
- int(self.feature_map_5th[1] / 2)]
-
- self.feature_maps = [self.feature_map_3th, self.feature_map_4th,
- self.feature_map_5th, self.feature_map_6th]
+ self.feature_map_2th = [int(int((self.image_size[0] + 1) / 2) / 2), int(int((self.image_size[1] + 1) / 2) / 2)]
+ self.feature_map_3th = [int(self.feature_map_2th[0] / 2), int(self.feature_map_2th[1] / 2)]
+ self.feature_map_4th = [int(self.feature_map_3th[0] / 2), int(self.feature_map_3th[1] / 2)]
+ self.feature_map_5th = [int(self.feature_map_4th[0] / 2), int(self.feature_map_4th[1] / 2)]
+ self.feature_map_6th = [int(self.feature_map_5th[0] / 2), int(self.feature_map_5th[1] / 2)]
+
+ self.feature_maps = [self.feature_map_3th, self.feature_map_4th, self.feature_map_5th, self.feature_map_6th]
def to(self, device: torch.device, dtype: torch.dtype) -> '_PriorBox':
self.device = device
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index f6862285c..3d8548f6f 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -33,9 +33,7 @@ class ImageStitcher(nn.Module):
plt.imshow(K.tensor_to_image(out))
"""
- def __init__(
- self, matcher: nn.Module, estimator: str = 'ransac', blending_method: str = "naive",
- ) -> None:
+ def __init__(self, matcher: nn.Module, estimator: str = 'ransac', blending_method: str = "naive") -> None:
super().__init__()
self.matcher = matcher
self.estimator = estimator
@@ -55,9 +53,7 @@ class ImageStitcher(nn.Module):
homo: torch.Tensor
if self.estimator == "vanilla":
homo = find_homography_dlt_iterated(
- keypoints2[None],
- keypoints1[None],
- torch.ones_like(keypoints1[None, :, 0])
+ keypoints2[None], keypoints1[None], torch.ones_like(keypoints1[None, :, 0])
)
elif self.estimator == "ransac":
homo, _ = self.ransac(keypoints2, keypoints1)
@@ -91,7 +87,7 @@ class ImageStitcher(nn.Module):
if isinstance(self.matcher, LoFTR) or isinstance(self.matcher, LocalFeatureMatcher):
input_dict: Dict[str, torch.Tensor] = { # LofTR works on grayscale images only
"image0": rgb_to_grayscale(image_1),
- "image1": rgb_to_grayscale(image_2)
+ "image1": rgb_to_grayscale(image_2),
}
else:
raise NotImplementedError(f"The preprocessor for {self.matcher} has not been implemented.")
@@ -109,8 +105,11 @@ class ImageStitcher(nn.Module):
return self.matcher(data)
def stitch_pair(
- self, images_left: torch.Tensor, images_right: torch.Tensor,
- mask_left: Optional[torch.Tensor] = None, mask_right: Optional[torch.Tensor] = None
+ self,
+ images_left: torch.Tensor,
+ images_right: torch.Tensor,
+ mask_left: Optional[torch.Tensor] = None,
+ mask_right: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
# Compute the transformed images
input_dict: Dict[str, torch.Tensor] = self.preprocess(images_left, images_right)
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index b8d46a2d9..c39602c32 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -10,9 +10,7 @@ from typing import List, Optional, Tuple
import torch
from torch import nn
-__all__ = [
- "VisionTransformer"
-]
+__all__ = ["VisionTransformer"]
class ResidualAdd(nn.Module):
@@ -28,17 +26,13 @@ class ResidualAdd(nn.Module):
class FeedForward(nn.Sequential):
- def __init__(self,
- in_features: int,
- hidden_features: int,
- out_features: int,
- dropout_rate: float = 0.) -> None:
+ def __init__(self, in_features: int, hidden_features: int, out_features: int, dropout_rate: float = 0.0) -> None:
super().__init__(
nn.Linear(in_features, hidden_features),
nn.GELU(),
nn.Dropout(dropout_rate),
nn.Linear(hidden_features, out_features),
- nn.Dropout(dropout_rate) # added one extra as in timm
+ nn.Dropout(dropout_rate), # added one extra as in timm
)
@@ -48,7 +42,7 @@ class MultiHeadAttention(nn.Module):
self.emb_size = emb_size
self.num_heads = num_heads
head_size = emb_size // num_heads # fom timm
- self.scale = head_size ** -0.5 # from timm
+ self.scale = head_size**-0.5 # from timm
# fuse the queries, keys and values in one matrix
self.qkv = nn.Linear(emb_size, emb_size * 3, bias=False)
@@ -78,22 +72,23 @@ class MultiHeadAttention(nn.Module):
class TransformerEncoderBlock(nn.Sequential):
- def __init__(self,
- embed_dim: int,
- num_heads: int,
- dropout_rate: float,
- dropout_attn: float) -> None:
+ def __init__(self, embed_dim: int, num_heads: int, dropout_rate: float, dropout_attn: float) -> None:
super().__init__(
- ResidualAdd(nn.Sequential(
- nn.LayerNorm(embed_dim),
- MultiHeadAttention(embed_dim, num_heads, dropout_attn, dropout_rate),
- nn.Dropout(dropout_rate)
- )),
- ResidualAdd(nn.Sequential(
- nn.LayerNorm(embed_dim),
- FeedForward(embed_dim, embed_dim, embed_dim, dropout_rate=dropout_rate),
- nn.Dropout(dropout_rate)
- )))
+ ResidualAdd(
+ nn.Sequential(
+ nn.LayerNorm(embed_dim),
+ MultiHeadAttention(embed_dim, num_heads, dropout_attn, dropout_rate),
+ nn.Dropout(dropout_rate),
+ )
+ ),
+ ResidualAdd(
+ nn.Sequential(
+ nn.LayerNorm(embed_dim),
+ FeedForward(embed_dim, embed_dim, embed_dim, dropout_rate=dropout_rate),
+ nn.Dropout(dropout_rate),
+ )
+ ),
+ )
class TransformerEncoder(nn.Module):
@@ -102,14 +97,13 @@ class TransformerEncoder(nn.Module):
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
- dropout_rate: float = 0.,
- dropout_attn: float = 0.,
+ dropout_rate: float = 0.0,
+ dropout_attn: float = 0.0,
) -> None:
super().__init__()
- self.blocks = nn.Sequential(*(
- TransformerEncoderBlock(embed_dim, num_heads, dropout_rate, dropout_attn)
- for _ in range(depth)
- ))
+ self.blocks = nn.Sequential(
+ *(TransformerEncoderBlock(embed_dim, num_heads, dropout_rate, dropout_attn) for _ in range(depth))
+ )
self.results: List[torch.Tensor] = []
def forward(self, x: torch.Tensor) -> torch.Tensor:
@@ -123,6 +117,7 @@ class TransformerEncoder(nn.Module):
class PatchEmbedding(nn.Module):
"""Compute the 2d image patch embedding ready to pass to transformer encoder."""
+
def __init__(
self,
in_channels: int = 3,
@@ -190,6 +185,7 @@ class VisionTransformer(nn.Module):
>>> vit(img).shape
torch.Size([1, 197, 768])
"""
+
def __init__(
self,
image_size: int = 224,
@@ -198,8 +194,8 @@ class VisionTransformer(nn.Module):
embed_dim: int = 768,
depth: int = 12,
num_heads: int = 12,
- dropout_rate: float = 0.,
- dropout_attn: float = 0.,
+ dropout_rate: float = 0.0,
+ dropout_attn: float = 0.0,
backbone: Optional[nn.Module] = None,
) -> None:
super().__init__()
diff --git a/kornia/contrib/vit_mobile.py b/kornia/contrib/vit_mobile.py
index 7092ed444..0977f59cb 100644
--- a/kornia/contrib/vit_mobile.py
+++ b/kornia/contrib/vit_mobile.py
@@ -11,24 +11,17 @@ class SiLU(nn.Module):
Paper: https://arxiv.org/abs/1702.03118
"""
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x * torch.sigmoid(x)
def conv_1x1_bn(inp: int, oup: int) -> nn.Module:
- return nn.Sequential(
- nn.Conv2d(inp, oup, 1, 1, 0, bias=False),
- nn.BatchNorm2d(oup),
- SiLU()
- )
+ return nn.Sequential(nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), SiLU())
def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> nn.Module:
- return nn.Sequential(
- nn.Conv2d(inp, oup, kernal_size, stride, 1, bias=False),
- nn.BatchNorm2d(oup),
- SiLU()
- )
+ return nn.Sequential(nn.Conv2d(inp, oup, kernal_size, stride, 1, bias=False), nn.BatchNorm2d(oup), SiLU())
class PreNorm(nn.Module):
@@ -42,14 +35,10 @@ class PreNorm(nn.Module):
class FeedForward(nn.Module):
- def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.) -> None:
+ def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0) -> None:
super().__init__()
self.net = nn.Sequential(
- nn.Linear(dim, hidden_dim),
- SiLU(),
- nn.Dropout(dropout),
- nn.Linear(hidden_dim, dim),
- nn.Dropout(dropout)
+ nn.Linear(dim, hidden_dim), SiLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout)
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
@@ -57,21 +46,18 @@ class FeedForward(nn.Module):
class Attention(nn.Module):
- def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.) -> None:
+ def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0) -> None:
super().__init__()
inner_dim = dim_head * heads
project_out = not (heads == 1 and dim_head == dim)
self.heads = heads
- self.scale = dim_head ** -0.5
+ self.scale = dim_head**-0.5
self.attend = nn.Softmax(dim=-1)
self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
- self.to_out = nn.Sequential(
- nn.Linear(inner_dim, dim),
- nn.Dropout(dropout)
- ) if project_out else nn.Identity()
+ self.to_out = nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout)) if project_out else nn.Identity()
def forward(self, x: torch.Tensor) -> torch.Tensor:
qkv = self.to_qkv(x).chunk(3, dim=-1)
@@ -102,14 +88,18 @@ class Transformer(nn.Module):
dropout: dropout ratio, defaults to 0.
"""
- def __init__(self, dim: int, depth: int, heads: int, dim_head: int, mlp_dim: int, dropout: float = 0.) -> None:
+ def __init__(self, dim: int, depth: int, heads: int, dim_head: int, mlp_dim: int, dropout: float = 0.0) -> None:
super().__init__()
self.layers = nn.ModuleList([])
for _ in range(depth):
- self.layers.append(nn.ModuleList([
- PreNorm(dim, Attention(dim, heads, dim_head, dropout)),
- PreNorm(dim, FeedForward(dim, mlp_dim, dropout))
- ]))
+ self.layers.append(
+ nn.ModuleList(
+ [
+ PreNorm(dim, Attention(dim, heads, dim_head, dropout)),
+ PreNorm(dim, FeedForward(dim, mlp_dim, dropout)),
+ ]
+ )
+ )
def forward(self, x: torch.Tensor) -> torch.Tensor:
for attn, ff in self.layers:
@@ -191,7 +181,7 @@ class MobileViTBlock(nn.Module):
kernel_size: int,
patch_size: Tuple[int, int],
mlp_dim: int,
- dropout: float = 0.
+ dropout: float = 0.0,
) -> None:
super().__init__()
self.ph, self.pw = patch_size
@@ -244,11 +234,7 @@ class MobileViT(nn.Module):
"""
def __init__(
- self,
- mode: str = 'xxs',
- in_channels: int = 3,
- patch_size: Tuple[int, int] = (2, 2),
- dropout: float = 0.
+ self, mode: str = 'xxs', in_channels: int = 3, patch_size: Tuple[int, int] = (2, 2), dropout: float = 0.0
) -> None:
super().__init__()
if mode == 'xxs':
@@ -273,18 +259,21 @@ class MobileViT(nn.Module):
self.mv2.append(MV2Block(channels[0], channels[1], 1, expansion))
self.mv2.append(MV2Block(channels[1], channels[2], 2, expansion))
self.mv2.append(MV2Block(channels[2], channels[3], 1, expansion))
- self.mv2.append(MV2Block(channels[2], channels[3], 1, expansion)) # Repeat
+ self.mv2.append(MV2Block(channels[2], channels[3], 1, expansion)) # Repeat
self.mv2.append(MV2Block(channels[3], channels[4], 2, expansion))
self.mv2.append(MV2Block(channels[5], channels[6], 2, expansion))
self.mv2.append(MV2Block(channels[7], channels[8], 2, expansion))
self.mvit = nn.ModuleList([])
- self.mvit.append(MobileViTBlock(dims[0], depth[0], channels[5],
- kernel_size, patch_size, int(dims[0] * 2), dropout=dropout))
- self.mvit.append(MobileViTBlock(dims[1], depth[1], channels[7],
- kernel_size, patch_size, int(dims[1] * 4), dropout=dropout))
- self.mvit.append(MobileViTBlock(dims[2], depth[2], channels[9],
- kernel_size, patch_size, int(dims[2] * 4), dropout=dropout))
+ self.mvit.append(
+ MobileViTBlock(dims[0], depth[0], channels[5], kernel_size, patch_size, int(dims[0] * 2), dropout=dropout)
+ )
+ self.mvit.append(
+ MobileViTBlock(dims[1], depth[1], channels[7], kernel_size, patch_size, int(dims[1] * 4), dropout=dropout)
+ )
+ self.mvit.append(
+ MobileViTBlock(dims[2], depth[2], channels[9], kernel_size, patch_size, int(dims[2] * 4), dropout=dropout)
+ )
self.conv2 = conv_1x1_bn(channels[-2], channels[-1])
@@ -294,7 +283,7 @@ class MobileViT(nn.Module):
x = self.mv2[1](x)
x = self.mv2[2](x)
- x = self.mv2[3](x) # Repeat
+ x = self.mv2[3](x) # Repeat
x = self.mv2[4](x)
x = self.mvit[0](x)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 72d35b99e..26ef2522a 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -143,9 +143,10 @@ def adjust_hue_raw(image: Tensor, factor: Union[float, Tensor]) -> Tensor:
r"""Adjust hue of an image. Expecting image to be in hsv format already."""
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
- KORNIA_CHECK(isinstance(factor, (float, Tensor)),
- f"The factor should be a float number or Tensor in the range between"
- f" [-PI, PI]. Got {type(factor)}")
+ KORNIA_CHECK(
+ isinstance(factor, (float, Tensor)),
+ f"The factor should be a float number or Tensor in the range between" f" [-PI, PI]. Got {type(factor)}",
+ )
if isinstance(factor, float):
factor = torch.as_tensor(factor)
@@ -556,9 +557,9 @@ def adjust_sigmoid(image: Tensor, cutoff: float = 0.5, gain: float = 10, inv: bo
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
if inv:
- img_adjust = (1 - 1 / (1 + (gain * (cutoff - image)).exp()))
+ img_adjust = 1 - 1 / (1 + (gain * (cutoff - image)).exp())
else:
- img_adjust = (1 / (1 + (gain * (cutoff - image)).exp()))
+ img_adjust = 1 / (1 + (gain * (cutoff - image)).exp())
return img_adjust
@@ -588,7 +589,7 @@ def adjust_log(image: Tensor, gain: float = 1, inv: bool = False, clip_output: b
KORNIA_CHECK_IS_TENSOR(image, "Expected shape (*, H, W)")
if inv:
- img_adjust = (2 ** image - 1) * gain
+ img_adjust = (2**image - 1) * gain
else:
img_adjust = (1 + image).log2() * gain
@@ -1209,10 +1210,7 @@ class AdjustContrast(Module):
torch.Size([2, 5, 3, 3])
"""
- def __init__(
- self,
- contrast_factor: Union[float, Tensor],
- ) -> None:
+ def __init__(self, contrast_factor: Union[float, Tensor]) -> None:
super().__init__()
self.contrast_factor: Union[float, Tensor] = contrast_factor
@@ -1250,10 +1248,7 @@ class AdjustContrastWithMeanSubtraction(Module):
torch.Size([2, 5, 3, 3])
"""
- def __init__(
- self,
- contrast_factor: Union[float, Tensor],
- ) -> None:
+ def __init__(self, contrast_factor: Union[float, Tensor]) -> None:
super().__init__()
self.contrast_factor: Union[float, Tensor] = contrast_factor
@@ -1289,10 +1284,7 @@ class AdjustBrightness(Module):
torch.Size([2, 5, 3, 3])
"""
- def __init__(
- self,
- brightness_factor: Union[float, Tensor],
- ) -> None:
+ def __init__(self, brightness_factor: Union[float, Tensor]) -> None:
super().__init__()
self.brightness_factor: Union[float, Tensor] = brightness_factor
@@ -1322,12 +1314,7 @@ class AdjustSigmoid(Module):
[0.5000, 0.5000]]]])
"""
- def __init__(
- self,
- cutoff: float = 0.5,
- gain: float = 10,
- inv: bool = False,
- ) -> None:
+ def __init__(self, cutoff: float = 0.5, gain: float = 10, inv: bool = False) -> None:
super().__init__()
self.cutoff: float = cutoff
self.gain: float = gain
@@ -1358,12 +1345,7 @@ class AdjustLog(Module):
[0., 0.]]]])
"""
- def __init__(
- self,
- gain: float = 1,
- inv: bool = False,
- clip_output: bool = True,
- ) -> None:
+ def __init__(self, gain: float = 1, inv: bool = False, clip_output: bool = True) -> None:
super().__init__()
self.gain: float = gain
self.inv: bool = inv
@@ -1401,10 +1383,7 @@ class AdjustBrightnessAccumulative(Module):
torch.Size([2, 5, 3, 3])
"""
- def __init__(
- self,
- brightness_factor: Union[float, Tensor],
- ) -> None:
+ def __init__(self, brightness_factor: Union[float, Tensor]) -> None:
super().__init__()
self.brightness_factor: Union[float, Tensor] = brightness_factor
diff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.py
index 9e433e411..d3f939148 100644
--- a/kornia/enhance/equalization.py
+++ b/kornia/enhance/equalization.py
@@ -216,13 +216,13 @@ def _map_luts(interp_tiles: torch.Tensor, luts: torch.Tensor) -> torch.Tensor:
(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)
@@ -293,7 +293,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)
@@ -312,10 +312,12 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->
@perform_keep_shape_image
-def equalize_clahe(input: torch.Tensor,
- clip_limit: float = 40.0,
- grid_size: Tuple[int, int] = (8, 8),
- slow_and_differentiable: bool = False) -> torch.Tensor:
+def equalize_clahe(
+ input: torch.Tensor,
+ clip_limit: float = 40.0,
+ grid_size: Tuple[int, int] = (8, 8),
+ slow_and_differentiable: bool = False,
+) -> torch.Tensor:
r"""Apply clahe equalization on the input tensor.
.. image:: _static/img/equalize_clahe.png
diff --git a/kornia/enhance/histogram.py b/kornia/enhance/histogram.py
index f71ef9c89..f663c0c97 100644
--- a/kornia/enhance/histogram.py
+++ b/kornia/enhance/histogram.py
@@ -222,16 +222,16 @@ def image_histogram2d(
u = torch.abs(image.unsqueeze(0) - centers) / bandwidth
if kernel == "gaussian":
- kernel_values = torch.exp(-0.5 * u ** 2)
- elif kernel in ("triangular", "uniform", "epanechnikov",):
+ kernel_values = torch.exp(-0.5 * u**2)
+ elif kernel in ("triangular", "uniform", "epanechnikov"):
# compute the mask and cast to floating point
mask = (u <= 1).to(u.dtype)
if kernel == "triangular":
- kernel_values = (1. - u) * mask
+ kernel_values = (1.0 - u) * mask
elif kernel == "uniform":
kernel_values = torch.ones_like(u) * mask
else: # kernel == "epanechnikov"
- kernel_values = (1. - u ** 2) * mask
+ kernel_values = (1.0 - u**2) * mask
else:
raise ValueError(f"Kernel must be 'triangular', 'gaussian', " f"'uniform' or 'epanechnikov'. Got {kernel}.")
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index d50ca4722..eb69b1ff7 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -232,7 +232,7 @@ def zca_mean(
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)
@@ -372,7 +372,7 @@ def linear_transform(
new_order: List[int] = perm.tolist()
inv_order: List[int] = perm_inv.tolist()
- 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)
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 75036d089..14d631e19 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -91,20 +91,21 @@ class LAFAffineShapeEstimator(nn.Module):
preserve_orientation: if True, the original orientation is preserved.
""" # pylint: disable
- def __init__(self,
- patch_size: int = 32,
- affine_shape_detector: Optional[nn.Module] = None,
- preserve_orientation: bool = True) -> None:
+ def __init__(
+ self, patch_size: int = 32, affine_shape_detector: Optional[nn.Module] = None, preserve_orientation: bool = True
+ ) -> None:
super().__init__()
self.patch_size = patch_size
self.affine_shape_detector = affine_shape_detector or PatchAffineShapeEstimator(self.patch_size)
self.preserve_orientation = preserve_orientation
if preserve_orientation:
- warnings.warn("`LAFAffineShapeEstimator` default behaviour is changed "
- "and now it does preserve original LAF orientation. "
- "Make sure your code accounts for this.",
- DeprecationWarning,
- stacklevel=2)
+ warnings.warn(
+ "`LAFAffineShapeEstimator` default behaviour is changed "
+ "and now it does preserve original LAF orientation. "
+ "Make sure your code accounts for this.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
def __repr__(self):
return (
@@ -190,17 +191,17 @@ class LAFAffNetShapeEstimator(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['affnet'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['affnet'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict['state_dict'], strict=False)
self.preserve_orientation = preserve_orientation
if preserve_orientation:
- warnings.warn("`LAFAffNetShapeEstimator` default behaviour is changed "
- "and now it does preserve original LAF orientation. "
- "Make sure your code accounts for this.",
- DeprecationWarning,
- stacklevel=2)
+ warnings.warn(
+ "`LAFAffNetShapeEstimator` default behaviour is changed "
+ "and now it does preserve original LAF orientation. "
+ "Make sure your code accounts for this.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
self.eval()
@staticmethod
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index 9cbbb6a7c..5a715dcbe 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -288,13 +288,9 @@ class DeFMO(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['defmo_encoder'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['defmo_encoder'], map_location=storage_fcn)
self.encoder.load_state_dict(pretrained_dict, strict=True)
- pretrained_dict_ren = torch.hub.load_state_dict_from_url(
- urls['defmo_rendering'], map_location=storage_fcn
- )
+ pretrained_dict_ren = torch.hub.load_state_dict_from_url(urls['defmo_rendering'], map_location=storage_fcn)
self.rendering.load_state_dict(pretrained_dict_ren, strict=True)
self.eval()
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index ef767d7e9..5163ccd73 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -66,9 +66,7 @@ class HardNet(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['liberty_aug'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty_aug'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict['state_dict'], strict=True)
self.eval()
@@ -147,9 +145,7 @@ class HardNet8(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['hardnet8v2'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['hardnet8v2'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index 4a0b2cea9..ca87baf5b 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -38,12 +38,15 @@ class FilterResponseNorm2d(nn.Module):
- Input: :math:`(B, \text{num_features}, H, W)`
- Output: :math:`(B, \text{num_features}, H, W)`
"""
- def __init__(self,
- num_features: int,
- eps: float = 1e-6,
- is_bias: bool = True,
- is_scale: bool = True,
- is_eps_leanable: bool = False):
+
+ def __init__(
+ self,
+ num_features: int,
+ eps: float = 1e-6,
+ is_bias: bool = True,
+ is_scale: bool = True,
+ is_eps_leanable: bool = False,
+ ):
super().__init__()
@@ -102,6 +105,7 @@ class TLU(nn.Module):
- Input: :math:`(B, \text{num_features}, H, W)`
- Output: :math:`(B, \text{num_features}, H, W)`
"""
+
def __init__(self, num_features: int):
"""max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau"""
super().__init__()
@@ -149,12 +153,15 @@ class HyNet(nn.Module):
"""
patch_size = 32
- def __init__(self, pretrained: bool = False,
- is_bias: bool = True,
- is_bias_FRN: bool = True,
- dim_desc: int = 128,
- drop_rate: float = 0.3,
- eps_l2_norm: float = 1e-10):
+ def __init__(
+ self,
+ pretrained: bool = False,
+ is_bias: bool = True,
+ is_bias_FRN: bool = True,
+ dim_desc: int = 128,
+ drop_rate: float = 0.3,
+ eps_l2_norm: float = 1e-10,
+ ):
super().__init__()
self.eps_l2_norm = eps_l2_norm
self.dim_desc = dim_desc
@@ -199,16 +206,14 @@ class HyNet(nn.Module):
self.layer7 = nn.Sequential(
nn.Dropout(self.drop_rate),
nn.Conv2d(128, self.dim_desc, kernel_size=8, bias=False),
- nn.BatchNorm2d(self.dim_desc, affine=False)
+ nn.BatchNorm2d(self.dim_desc, affine=False),
)
self.desc_norm = nn.LocalResponseNorm(2 * self.dim_desc, 2.0 * self.dim_desc, 0.5, 0.0)
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['liberty'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
return
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index e5872987f..4ea2cc675 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -17,11 +17,13 @@ from .scale_space_detector import ScaleSpaceDetector
from .siftdesc import SIFTDescriptor
-def get_laf_descriptors(img: torch.Tensor,
- lafs: torch.Tensor,
- patch_descriptor: nn.Module,
- patch_size: int = 32,
- grayscale_descriptor: bool = True) -> torch.Tensor:
+def get_laf_descriptors(
+ img: torch.Tensor,
+ lafs: torch.Tensor,
+ patch_descriptor: nn.Module,
+ patch_size: int = 32,
+ grayscale_descriptor: bool = True,
+) -> torch.Tensor:
r"""Function to get local descriptors, corresponding to LAFs (keypoints).
Args:
@@ -62,10 +64,12 @@ class LAFDescriptor(nn.Module):
grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image.
"""
- def __init__(self,
- patch_descriptor_module: Optional[nn.Module] = None,
- patch_size: int = 32,
- grayscale_descriptor: bool = True) -> None:
+ def __init__(
+ self,
+ patch_descriptor_module: Optional[nn.Module] = None,
+ patch_size: int = 32,
+ grayscale_descriptor: bool = True,
+ ) -> None:
super().__init__()
if patch_descriptor_module is None:
patch_descriptor_module = HardNet(True)
@@ -74,10 +78,19 @@ class LAFDescriptor(nn.Module):
self.grayscale_descriptor = grayscale_descriptor
def __repr__(self) -> str:
- return self.__class__.__name__ + '(' + \
- 'descriptor=' + self.descriptor.__repr__() + ', ' + \
- 'patch_size=' + str(self.patch_size) + ', ' + \
- 'grayscale_descriptor=' + str(self.grayscale_descriptor) + ')'
+ return (
+ self.__class__.__name__
+ + '('
+ + 'descriptor='
+ + self.descriptor.__repr__()
+ + ', '
+ + 'patch_size='
+ + str(self.patch_size)
+ + ', '
+ + 'grayscale_descriptor='
+ + str(self.grayscale_descriptor)
+ + ')'
+ )
def forward(self, img: torch.Tensor, lafs: torch.Tensor) -> torch.Tensor:
r"""Three stage local feature detection.
@@ -102,18 +115,15 @@ class LocalFeature(nn.Module):
detector: the detection module.
descriptor: the descriptor module.
"""
- def __init__(self,
- detector: nn.Module,
- descriptor: LAFDescriptor) -> None:
+
+ def __init__(self, detector: nn.Module, descriptor: LAFDescriptor) -> None:
super().__init__()
self.detector = detector
self.descriptor = descriptor
- def forward(self,
- img: torch.Tensor,
- mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor,
- torch.Tensor,
- torch.Tensor]: # type: ignore
+ def forward(
+ self, img: torch.Tensor, mask: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: # type: ignore
"""
Args:
img: image to extract features with shape :math:`(B,C,H,W)`.
@@ -135,75 +145,67 @@ class SIFTFeature(LocalFeature):
Still not as good as OpenCV/VLFeat because of https://github.com/kornia/kornia/pull/884, but we are working on it
"""
- def __init__(self,
- num_features: int = 8000,
- upright: bool = False,
- rootsift: bool = True,
- device: torch.device = torch.device('cpu')):
+
+ def __init__(
+ self,
+ num_features: int = 8000,
+ upright: bool = False,
+ rootsift: bool = True,
+ device: torch.device = torch.device('cpu'),
+ ):
patch_size: int = 41
- detector = ScaleSpaceDetector(num_features,
- resp_module=BlobDoG(),
- nms_module=ConvQuadInterp3d(10),
- scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),
- ori_module=PassLAF() if upright else LAFOrienter(19),
- scale_space_response=True,
- minima_are_also_good=True,
- mr_size=6.0).to(device)
- descriptor = LAFDescriptor(SIFTDescriptor(patch_size=patch_size, rootsift=rootsift),
- patch_size=patch_size,
- grayscale_descriptor=True).to(device)
+ detector = ScaleSpaceDetector(
+ num_features,
+ resp_module=BlobDoG(),
+ nms_module=ConvQuadInterp3d(10),
+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),
+ ori_module=PassLAF() if upright else LAFOrienter(19),
+ scale_space_response=True,
+ minima_are_also_good=True,
+ mr_size=6.0,
+ ).to(device)
+ descriptor = LAFDescriptor(
+ SIFTDescriptor(patch_size=patch_size, rootsift=rootsift), patch_size=patch_size, grayscale_descriptor=True
+ ).to(device)
super().__init__(detector, descriptor)
class GFTTAffNetHardNet(LocalFeature):
"""Convenience module, which implements GFTT detector + AffNet-HardNet descriptor."""
- def __init__(self,
- num_features: int = 8000,
- upright: bool = False,
- device: torch.device = torch.device('cpu')):
- detector = ScaleSpaceDetector(num_features,
- resp_module=CornerGFTT(),
- nms_module=ConvQuadInterp3d(10, 1e-5),
- scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=False),
- ori_module=PassLAF() if upright else LAFOrienter(19),
- aff_module=LAFAffNetShapeEstimator(True).eval(),
- mr_size=6.0).to(device)
- descriptor = LAFDescriptor(None,
- patch_size=32,
- grayscale_descriptor=True).to(device)
+
+ def __init__(self, num_features: int = 8000, upright: bool = False, device: torch.device = torch.device('cpu')):
+ detector = ScaleSpaceDetector(
+ num_features,
+ resp_module=CornerGFTT(),
+ nms_module=ConvQuadInterp3d(10, 1e-5),
+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=False),
+ ori_module=PassLAF() if upright else LAFOrienter(19),
+ aff_module=LAFAffNetShapeEstimator(True).eval(),
+ mr_size=6.0,
+ ).to(device)
+ descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)
super().__init__(detector, descriptor)
class KeyNetHardNet(LocalFeature):
"""Convenience module, which implements KeyNet detector + HardNet descriptor."""
- def __init__(self,
- num_features: int = 8000,
- upright: bool = False,
- device: torch.device = torch.device('cpu')):
+
+ def __init__(self, num_features: int = 8000, upright: bool = False, device: torch.device = torch.device('cpu')):
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
- detector = KeyNetDetector(True,
- num_features=num_features,
- ori_module=ori_module).to(device)
- descriptor = LAFDescriptor(None,
- patch_size=32,
- grayscale_descriptor=True).to(device)
+ detector = KeyNetDetector(True, num_features=num_features, ori_module=ori_module).to(device)
+ descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)
super().__init__(detector, descriptor)
class KeyNetAffNetHardNet(LocalFeature):
"""Convenience module, which implements KeyNet detector + AffNet + HardNet descriptor."""
- def __init__(self,
- num_features: int = 8000,
- upright: bool = False,
- device: torch.device = torch.device('cpu')):
+
+ def __init__(self, num_features: int = 8000, upright: bool = False, device: torch.device = torch.device('cpu')):
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
- detector = KeyNetDetector(True,
- num_features=num_features,
- ori_module=ori_module,
- aff_module=LAFAffNetShapeEstimator(True).eval()).to(device)
- descriptor = LAFDescriptor(None,
- patch_size=32,
- grayscale_descriptor=True).to(device)
+ detector = KeyNetDetector(
+ True, num_features=num_features, ori_module=ori_module, aff_module=LAFAffNetShapeEstimator(True).eval()
+ ).to(device)
+ descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)
super().__init__(detector, descriptor)
@@ -233,9 +235,7 @@ class LocalFeatureMatcher(nn.Module):
self.matcher = matcher
self.eval()
- def extract_features(self,
- image: torch.Tensor,
- mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
+ def extract_features(self, image: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
"""Function for feature extraction from simple image."""
lafs0, resps0, descs0 = self.local_feature(image, mask)
return {"lafs": lafs0, "responses": resps0, "descriptors": descs0}
@@ -247,7 +247,7 @@ class LocalFeatureMatcher(nn.Module):
'lafs0': torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
'lafs1': torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
'confidence': torch.empty(0, device=device, dtype=dtype),
- 'batch_indexes': torch.empty(0, device=device, dtype=torch.long)
+ 'batch_indexes': torch.empty(0, device=device, dtype=torch.long),
}
def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
@@ -305,9 +305,7 @@ class LocalFeatureMatcher(nn.Module):
current_lafs_1 = lafs1[batch_idx, idxs[:, 1]]
out_confidence.append(1.0 - dists)
- batch_idxs = batch_idx * torch.ones(len(dists),
- device=keypoints0.device,
- dtype=torch.long)
+ batch_idxs = batch_idx * torch.ones(len(dists), device=keypoints0.device, dtype=torch.long)
out_keypoints0.append(current_keypoints_0)
out_keypoints1.append(current_keypoints_1)
out_lafs0.append(current_lafs_0)
@@ -315,8 +313,7 @@ class LocalFeatureMatcher(nn.Module):
out_batch_indexes.append(batch_idxs)
if len(out_batch_indexes) == 0:
- return self.no_match_output(data['image0'].device,
- data['image0'].dtype)
+ return self.no_match_output(data['image0'].device, data['image0'].dtype)
return {
'keypoints0': torch.cat(out_keypoints0, dim=0).view(-1, 2),
@@ -324,5 +321,5 @@ class LocalFeatureMatcher(nn.Module):
'lafs0': torch.cat(out_lafs0, dim=0).view(1, -1, 2, 3),
'lafs1': torch.cat(out_lafs1, dim=0).view(1, -1, 2, 3),
'confidence': torch.cat(out_confidence, dim=0).view(-1),
- 'batch_indexes': torch.cat(out_batch_indexes, dim=0).view(-1)
+ 'batch_indexes': torch.cat(out_batch_indexes, dim=0).view(-1),
}
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index cdc82dc30..e32aa079a 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -14,20 +14,18 @@ from .laf import laf_from_center_scale_ori
from .orientation import PassLAF
keynet_config = {
-
- 'KeyNet_default_config':
- {
- # Key.Net Model
- 'num_filters': 8,
- 'num_levels': 3,
- 'kernel_size': 5,
- # Extraction Parameters
- 'nms_size': 15,
- 'pyramid_levels': 4,
- 'up_levels': 1,
- 'scale_factor_levels': math.sqrt(2),
- 's_mult': 22,
- },
+ 'KeyNet_default_config': {
+ # Key.Net Model
+ 'num_filters': 8,
+ 'num_levels': 3,
+ 'kernel_size': 5,
+ # Extraction Parameters
+ 'nms_size': 15,
+ 'pyramid_levels': 4,
+ 'up_levels': 1,
+ 'scale_factor_levels': math.sqrt(2),
+ 's_mult': 22,
+ }
}
urls: Dict[str, str] = {}
@@ -39,6 +37,7 @@ class _FeatureExtractor(nn.Module):
It loads both, the handcrafted and learnable blocks
"""
+
def __init__(self):
super().__init__()
@@ -53,6 +52,7 @@ class _FeatureExtractor(nn.Module):
class _HandcraftedBlock(nn.Module):
"""Helper class for KeyNet, it defines the handcrafted filters within the Key.Net handcrafted block."""
+
def __init__(self):
super().__init__()
self.spatial_gradient = SpatialGradient('sobel', 1)
@@ -68,16 +68,7 @@ class _HandcraftedBlock(nn.Module):
sobel_dy = self.spatial_gradient(dy)
dyy = sobel_dy[:, :, 1, :, :]
- hc_feats = torch.cat([dx,
- dy,
- dx ** 2.,
- dy ** 2.,
- dx * dy,
- dxy,
- dxy ** 2.,
- dxx,
- dyy,
- dxx * dyy], dim=1)
+ hc_feats = torch.cat([dx, dy, dx**2.0, dy**2.0, dx * dy, dxy, dxy**2.0, dxx, dyy, dxx * dyy], dim=1)
return hc_feats
@@ -100,20 +91,23 @@ class _LearnableBlock(nn.Sequential):
return x
-def _KeyNetConvBlock(in_channels: int = 8,
- out_channels: int = 8,
- kernel_size: int = 5,
- stride: int = 1,
- padding: int = 2,
- dilation: int = 1):
+def _KeyNetConvBlock(
+ in_channels: int = 8,
+ out_channels: int = 8,
+ kernel_size: int = 5,
+ stride: int = 1,
+ padding: int = 2,
+ dilation: int = 1,
+):
"""Helper function for KeyNet.
Default learnable convolutional block for KeyNet.
"""
- return nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size,
- stride, padding, dilation),
- nn.BatchNorm2d(out_channels),
- nn.ReLU(inplace=True))
+ return nn.Sequential(
+ nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation),
+ nn.BatchNorm2d(out_channels),
+ nn.ReLU(inplace=True),
+ )
class KeyNet(nn.Module):
@@ -132,9 +126,8 @@ class KeyNet(nn.Module):
- Input: :math:`(B, 1, H, W)`
- Output: :math:`(B, 1, H, W)`
"""
- def __init__(self,
- pretrained: bool = False,
- keynet_conf: Dict = keynet_config['KeyNet_default_config']):
+
+ def __init__(self, pretrained: bool = False, keynet_conf: Dict = keynet_config['KeyNet_default_config']):
super().__init__()
num_filters = keynet_conf['num_filters']
@@ -143,15 +136,16 @@ class KeyNet(nn.Module):
padding: int = kernel_size // 2
self.feature_extractor = _FeatureExtractor()
- self.last_conv = nn.Sequential(nn.Conv2d(in_channels=num_filters * self.num_levels,
- out_channels=1, kernel_size=kernel_size, padding=padding),
- nn.ReLU(inplace=True))
+ self.last_conv = nn.Sequential(
+ nn.Conv2d(
+ in_channels=num_filters * self.num_levels, out_channels=1, kernel_size=kernel_size, padding=padding
+ ),
+ nn.ReLU(inplace=True),
+ )
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['keynet'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['keynet'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict['state_dict'], strict=True)
self.eval()
@@ -186,12 +180,15 @@ class KeyNetDetector(nn.Module):
aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
"""
- def __init__(self,
- pretrained: bool = False,
- num_features: int = 2048,
- keynet_conf: Dict = keynet_config['KeyNet_default_config'],
- ori_module: nn.Module = PassLAF(),
- aff_module: nn.Module = PassLAF()):
+
+ def __init__(
+ self,
+ pretrained: bool = False,
+ num_features: int = 2048,
+ keynet_conf: Dict = keynet_config['KeyNet_default_config'],
+ ori_module: nn.Module = PassLAF(),
+ aff_module: nn.Module = PassLAF(),
+ ):
super().__init__()
self.model = KeyNet(pretrained, keynet_conf)
# Load extraction configuration
@@ -211,10 +208,9 @@ class KeyNetDetector(nn.Module):
mask[:, :, borders:-borders, borders:-borders] = 1
return mask * score_map
- def detect_features_on_single_level(self,
- level_img: Tensor,
- num_kp: int,
- factor: Tuple[float, float]) -> Tuple[Tensor, Tensor]:
+ def detect_features_on_single_level(
+ self, level_img: Tensor, num_kp: int, factor: Tuple[float, float]
+ ) -> Tuple[Tensor, Tensor]:
det_map = self.nms(self.remove_borders(self.model(level_img)))
device = level_img.device
dtype = level_img.dtype
@@ -223,15 +219,15 @@ class KeyNetDetector(nn.Module):
scores_sorted, indices = torch.sort(scores, descending=True)
- indices = indices[torch.where(scores_sorted > 0.)]
+ indices = indices[torch.where(scores_sorted > 0.0)]
yx = yx[:, indices[:num_kp]].t()
current_kp_num = len(yx)
xy_projected = yx.view(1, current_kp_num, 2).flip(2) * torch.tensor(factor, device=device, dtype=dtype)
scale_factor = 0.5 * (factor[0] + factor[1])
scale = scale_factor * self.mr_size * torch.ones(1, current_kp_num, 1, 1, device=device, dtype=dtype)
- lafs = laf_from_center_scale_ori(xy_projected,
- scale,
- torch.zeros(1, current_kp_num, 1, device=device, dtype=dtype))
+ lafs = laf_from_center_scale_ori(
+ xy_projected, scale, torch.zeros(1, current_kp_num, 1, device=device, dtype=dtype)
+ )
return scores_sorted[:num_kp], lafs
def detect( # type: ignore
@@ -240,7 +236,7 @@ class KeyNetDetector(nn.Module):
# Compute points per level
num_features_per_level: List[float] = []
tmp = 0.0
- factor_points = (self.scale_factor_levels ** 2)
+ factor_points = self.scale_factor_levels**2
levels = self.num_pyramid_levels + self.num_upscale_levels + 1
for idx_level in range(levels):
tmp += factor_points ** (-1 * (idx_level - self.num_upscale_levels))
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index e89099f03..f498c8f79 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -109,9 +109,9 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc
return laf_out
-def laf_from_center_scale_ori(xy: torch.Tensor,
- scale: Optional[torch.Tensor] = None,
- ori: Optional[torch.Tensor] = None) -> torch.Tensor:
+def laf_from_center_scale_ori(
+ xy: torch.Tensor, scale: Optional[torch.Tensor] = None, ori: Optional[torch.Tensor] = None
+) -> torch.Tensor:
"""Return orientation of the LAFs, in radians. Useful to create kornia LAFs from OpenCV keypoints.
Args:
@@ -309,7 +309,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])
@@ -430,10 +430,10 @@ 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,
@@ -478,9 +478,9 @@ 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,
diff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.py
index 4ecded3d8..0cdd076a9 100644
--- a/kornia/feature/loftr/backbone/resnet_fpn.py
+++ b/kornia/feature/loftr/backbone/resnet_fpn.py
@@ -24,10 +24,7 @@ class BasicBlock(nn.Module):
if stride == 1:
self.downsample = None
else:
- self.downsample = nn.Sequential(
- conv1x1(in_planes, planes, stride=stride),
- nn.BatchNorm2d(planes)
- )
+ self.downsample = nn.Sequential(conv1x1(in_planes, planes, stride=stride), nn.BatchNorm2d(planes))
def forward(self, x):
y = x
@@ -188,11 +185,11 @@ class ResNetFPN_16_4(nn.Module):
# FPN
x4_out = self.layer4_outconv(x4)
- x4_out_2x = F.interpolate(x4_out, scale_factor=2., mode='bilinear', align_corners=True)
+ x4_out_2x = F.interpolate(x4_out, scale_factor=2.0, mode='bilinear', align_corners=True)
x3_out = self.layer3_outconv(x3)
x3_out = self.layer3_outconv2(x3_out + x4_out_2x)
- x3_out_2x = F.interpolate(x3_out, scale_factor=2., mode='bilinear', align_corners=True)
+ x3_out_2x = F.interpolate(x3_out, scale_factor=2.0, mode='bilinear', align_corners=True)
x2_out = self.layer2_outconv(x2)
x2_out = self.layer2_outconv2(x2_out + x3_out_2x)
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 4f4200cbe..a038b726b 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -18,38 +18,33 @@ urls["indoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt"
# Comments: the config below is the one corresponding to the pretrained models
# Some do not change there anything, unless you want to retrain it.
-default_cfg = {'backbone_type': 'ResNetFPN',
- 'resolution': (8, 2),
- 'fine_window_size': 5,
- 'fine_concat_coarse_feat': True,
- 'resnetfpn': {'initial_dim': 128, 'block_dims': [128, 196, 256]},
- 'coarse': {'d_model': 256,
- 'd_ffn': 256,
- 'nhead': 8,
- 'layer_names': ['self',
- 'cross',
- 'self',
- 'cross',
- 'self',
- 'cross',
- 'self',
- 'cross'],
- 'attention': 'linear',
- 'temp_bug_fix': False},
- 'match_coarse': {'thr': 0.2,
- 'border_rm': 2,
- 'match_type': 'dual_softmax',
- 'dsmax_temperature': 0.1,
- 'skh_iters': 3,
- 'skh_init_bin_score': 1.0,
- 'skh_prefilter': True,
- 'train_coarse_percent': 0.4,
- 'train_pad_num_gt_min': 200},
- 'fine': {'d_model': 128,
- 'd_ffn': 128,
- 'nhead': 8,
- 'layer_names': ['self', 'cross'],
- 'attention': 'linear'}}
+default_cfg = {
+ 'backbone_type': 'ResNetFPN',
+ 'resolution': (8, 2),
+ 'fine_window_size': 5,
+ 'fine_concat_coarse_feat': True,
+ 'resnetfpn': {'initial_dim': 128, 'block_dims': [128, 196, 256]},
+ 'coarse': {
+ 'd_model': 256,
+ 'd_ffn': 256,
+ 'nhead': 8,
+ 'layer_names': ['self', 'cross', 'self', 'cross', 'self', 'cross', 'self', 'cross'],
+ 'attention': 'linear',
+ 'temp_bug_fix': False,
+ },
+ 'match_coarse': {
+ 'thr': 0.2,
+ 'border_rm': 2,
+ 'match_type': 'dual_softmax',
+ 'dsmax_temperature': 0.1,
+ 'skh_iters': 3,
+ 'skh_init_bin_score': 1.0,
+ 'skh_prefilter': True,
+ 'train_coarse_percent': 0.4,
+ 'train_pad_num_gt_min': 200,
+ },
+ 'fine': {'d_model': 128, 'd_ffn': 128, 'nhead': 8, 'layer_names': ['self', 'cross'], 'attention': 'linear'},
+}
class LoFTR(nn.Module):
@@ -84,8 +79,8 @@ class LoFTR(nn.Module):
# Modules
self.backbone = build_backbone(config)
self.pos_encoding = PositionEncodingSine(
- config['coarse']['d_model'],
- temp_bug_fix=config['coarse']['temp_bug_fix'])
+ config['coarse']['d_model'], temp_bug_fix=config['coarse']['temp_bug_fix']
+ )
self.loftr_coarse = LocalFeatureTransformer(config['coarse'])
self.coarse_matching = CoarseMatching(config['match_coarse'])
self.fine_preprocess = FinePreprocess(config)
@@ -96,9 +91,7 @@ class LoFTR(nn.Module):
if pretrained not in urls.keys():
raise ValueError(f"pretrained should be None or one of {urls.keys()}")
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls[pretrained], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls[pretrained], map_location=storage_fcn)
self.load_state_dict(pretrained_dict['state_dict'])
self.eval()
@@ -121,10 +114,9 @@ class LoFTR(nn.Module):
"""
# 1. Local Feature CNN
- data.update({
- 'bs': data['image0'].size(0),
- 'hw0_i': data['image0'].shape[2:], 'hw1_i': data['image1'].shape[2:]
- })
+ data.update(
+ {'bs': data['image0'].size(0), 'hw0_i': data['image0'].shape[2:], 'hw1_i': data['image1'].shape[2:]}
+ )
if data['hw0_i'] == data['hw1_i']: # faster & better BN convergence
feats_c, feats_f = self.backbone(torch.cat([data['image0'], data['image1']], dim=0))
@@ -132,10 +124,14 @@ class LoFTR(nn.Module):
else: # handle different input shapes
(feat_c0, feat_f0), (feat_c1, feat_f1) = self.backbone(data['image0']), self.backbone(data['image1'])
- data.update({
- 'hw0_c': feat_c0.shape[2:], 'hw1_c': feat_c1.shape[2:],
- 'hw0_f': feat_f0.shape[2:], 'hw1_f': feat_f1.shape[2:]
- })
+ data.update(
+ {
+ 'hw0_c': feat_c0.shape[2:],
+ 'hw1_c': feat_c1.shape[2:],
+ 'hw0_f': feat_f0.shape[2:],
+ 'hw1_f': feat_f1.shape[2:],
+ }
+ )
# 2. coarse-level loftr module
# add featmap with positional encoding, then flatten it to sequence [N, HW, C]
@@ -168,10 +164,12 @@ class LoFTR(nn.Module):
# 5. match fine-level
self.fine_matching(feat_f0_unfold, feat_f1_unfold, data)
- rename_keys: Dict[str, str] = {"mkpts0_f": 'keypoints0',
- "mkpts1_f": 'keypoints1',
- "mconf": 'confidence',
- "b_ids": 'batch_indexes'}
+ rename_keys: Dict[str, str] = {
+ "mkpts0_f": 'keypoints0',
+ "mkpts1_f": 'keypoints1',
+ "mconf": 'confidence',
+ "b_ids": 'batch_indexes',
+ }
out = {}
for k, v in rename_keys.items():
out[v] = data[k]
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index 9e57a4cb8..5ea07c5b8 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -55,12 +55,18 @@ class FinePreprocess(nn.Module):
# option: use coarse-level loftr feature as context: concat and linear
if self.cat_c_feat:
- feat_c_win = self.down_proj(torch.cat([feat_c0[data['b_ids'], data['i_ids']],
- feat_c1[data['b_ids'], data['j_ids']]], 0)) # [2n, c]
- feat_cf_win = self.merge_feat(torch.cat([
- torch.cat([feat_f0_unfold, feat_f1_unfold], 0), # [2n, ww, cf]
- feat_c_win.unsqueeze(1).repeat(1, W**2, 1), # [2n, ww, cf]
- ], -1))
+ feat_c_win = self.down_proj(
+ torch.cat([feat_c0[data['b_ids'], data['i_ids']], feat_c1[data['b_ids'], data['j_ids']]], 0)
+ ) # [2n, c]
+ feat_cf_win = self.merge_feat(
+ torch.cat(
+ [
+ torch.cat([feat_f0_unfold, feat_f1_unfold], 0), # [2n, ww, cf]
+ feat_c_win.unsqueeze(1).repeat(1, W**2, 1), # [2n, ww, cf]
+ ],
+ -1,
+ )
+ )
feat_f0_unfold, feat_f1_unfold = torch.chunk(feat_cf_win, 2, dim=0)
return feat_f0_unfold, feat_f1_unfold
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index aa6064d27..dcba7319f 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -18,13 +18,15 @@ class LinearAttention(Module):
self.feature_map = elu_feature_map
self.eps = eps
- def forward(self,
- queries: torch.Tensor,
- keys: torch.Tensor,
- values: torch.Tensor,
- q_mask: Optional[torch.Tensor] = None,
- kv_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
- """ Multi-Head linear attention proposed in "Transformers are RNNs"
+ def forward(
+ self,
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ q_mask: Optional[torch.Tensor] = None,
+ kv_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ """Multi-Head linear attention proposed in "Transformers are RNNs"
Args:
queries: [N, L, H, D]
keys: [N, S, H, D]
@@ -78,7 +80,7 @@ class FullAttention(Module):
QK.masked_fill_(~(q_mask[:, :, None, None] * kv_mask[:, None, :, None]), float('-inf'))
# Compute the attention and the weighted average
- softmax_temp = 1. / queries.size(3)**.5 # sqrt(D)
+ softmax_temp = 1.0 / queries.size(3) ** 0.5 # sqrt(D)
A = torch.softmax(softmax_temp * QK, dim=2)
if self.use_dropout:
A = self.dropout(A)
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index bc39ff09c..ff4211fc8 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -8,10 +8,7 @@ from .linear_attention import FullAttention, LinearAttention
class LoFTREncoderLayer(nn.Module):
- def __init__(self,
- d_model,
- nhead,
- attention='linear'):
+ def __init__(self, d_model, nhead, attention='linear'):
super().__init__()
self.dim = d_model // nhead
@@ -26,20 +23,20 @@ class LoFTREncoderLayer(nn.Module):
# feed-forward network
self.mlp = nn.Sequential(
- nn.Linear(d_model * 2, d_model * 2, bias=False),
- nn.ReLU(True),
- nn.Linear(d_model * 2, d_model, bias=False),
+ nn.Linear(d_model * 2, d_model * 2, bias=False), nn.ReLU(True), nn.Linear(d_model * 2, d_model, bias=False)
)
# norm and dropout
self.norm1 = nn.LayerNorm(d_model)
self.norm2 = nn.LayerNorm(d_model)
- def forward(self,
- x: torch.Tensor,
- source: torch.Tensor,
- x_mask: Optional[torch.Tensor] = None,
- source_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
+ def forward(
+ self,
+ x: torch.Tensor,
+ source: torch.Tensor,
+ x_mask: Optional[torch.Tensor] = None,
+ source_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
"""
Args:
x (torch.Tensor): [N, L, C]
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 622cebcd1..147186558 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -6,7 +6,7 @@ INF = 1e9
def mask_border(m, b: int, v):
- """ Mask borders with value
+ """Mask borders with value
Args:
m (torch.Tensor): [N, H0, W0, H1, W1]
b (int)
@@ -37,10 +37,10 @@ def mask_border_with_padding(m, bd, v, p_m0, p_m1):
h0s, w0s = p_m0.sum(1).max(-1)[0].int(), p_m0.sum(-1).max(-1)[0].int()
h1s, w1s = p_m1.sum(1).max(-1)[0].int(), p_m1.sum(-1).max(-1)[0].int()
for b_idx, (h0, w0, h1, w1) in enumerate(zip(h0s, w0s, h1s, w1s)):
- m[b_idx, h0 - bd:] = v
- m[b_idx, :, w0 - bd:] = v
- m[b_idx, :, :, h1 - bd:] = v
- m[b_idx, :, :, :, w1 - bd:] = v
+ m[b_idx, h0 - bd :] = v
+ m[b_idx, :, w0 - bd :] = v
+ m[b_idx, :, :, h1 - bd :] = v
+ m[b_idx, :, :, :, w1 - bd :] = v
def compute_max_candidates(p_m0, p_m1):
@@ -51,8 +51,7 @@ def compute_max_candidates(p_m0, p_m1):
"""
h0s, w0s = p_m0.sum(1).max(-1)[0], p_m0.sum(-1).max(-1)[0]
h1s, w1s = p_m1.sum(1).max(-1)[0], p_m1.sum(-1).max(-1)[0]
- max_cand = torch.sum(
- torch.min(torch.stack([h0s * w0s, h1s * w1s], -1), -1)[0])
+ max_cand = torch.sum(torch.min(torch.stack([h0s * w0s, h1s * w1s], -1), -1)[0])
return max_cand
@@ -77,8 +76,7 @@ class CoarseMatching(nn.Module):
except ImportError:
raise ImportError("download superglue.py first!")
self.log_optimal_transport = log_optimal_transport
- self.bin_score = nn.Parameter(
- torch.tensor(config['skh_init_bin_score'], requires_grad=True))
+ self.bin_score = nn.Parameter(torch.tensor(config['skh_init_bin_score'], requires_grad=True))
self.skh_iters = config['skh_iters']
self.skh_prefilter = config['skh_prefilter']
else:
@@ -106,29 +104,22 @@ class CoarseMatching(nn.Module):
_, L, S, _ = feat_c0.size(0), feat_c0.size(1), feat_c1.size(1), feat_c0.size(2)
# normalize
- feat_c0, feat_c1 = map(lambda feat: feat / feat.shape[-1]**.5,
- [feat_c0, feat_c1])
+ feat_c0, feat_c1 = map(lambda feat: feat / feat.shape[-1] ** 0.5, [feat_c0, feat_c1])
if self.match_type == 'dual_softmax':
- sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0,
- feat_c1) / self.temperature
+ sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature
if mask_c0 is not None:
- sim_matrix.masked_fill_(
- ~(mask_c0[..., None] * mask_c1[:, None]).bool(),
- -INF)
+ sim_matrix.masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF)
conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)
elif self.match_type == 'sinkhorn':
# sinkhorn, dustbin included
sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1)
if mask_c0 is not None:
- sim_matrix[:, :L, :S].masked_fill_(
- ~(mask_c0[..., None] * mask_c1[:, None]).bool(),
- -INF)
+ sim_matrix[:, :L, :S].masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF)
# build uniform prior & use sinkhorn
- log_assign_matrix = self.log_optimal_transport(
- sim_matrix, self.bin_score, self.skh_iters)
+ log_assign_matrix = self.log_optimal_transport(sim_matrix, self.bin_score, self.skh_iters)
assign_matrix = log_assign_matrix.exp()
conf_matrix = assign_matrix[:, :-1, :-1]
@@ -168,32 +159,29 @@ class CoarseMatching(nn.Module):
'h0c': data['hw0_c'][0],
'w0c': data['hw0_c'][1],
'h1c': data['hw1_c'][0],
- 'w1c': data['hw1_c'][1]
+ 'w1c': data['hw1_c'][1],
}
_device = conf_matrix.device
# 1. confidence thresholding
mask = conf_matrix > self.thr
N = conf_matrix.shape[0]
- mask = mask.reshape(N,
- axes_lengths['h0c'], axes_lengths['w0c'],
- axes_lengths['h1c'], axes_lengths['w1c'])
+ mask = mask.reshape(N, axes_lengths['h0c'], axes_lengths['w0c'], axes_lengths['h1c'], axes_lengths['w1c'])
# mask = rearrange(mask, 'b (h0c w0c) (h1c w1c) -> b h0c w0c h1c w1c',
# **axes_lengths)
if 'mask0' not in data:
mask_border(mask, self.border_rm, False)
else:
- mask_border_with_padding(mask, self.border_rm, False,
- data['mask0'], data['mask1'])
- mask = mask.reshape(N,
- axes_lengths['h0c'] * axes_lengths['w0c'],
- axes_lengths['h1c'] * axes_lengths['w1c'])
+ mask_border_with_padding(mask, self.border_rm, False, data['mask0'], data['mask1'])
+ mask = mask.reshape(N, axes_lengths['h0c'] * axes_lengths['w0c'], axes_lengths['h1c'] * axes_lengths['w1c'])
# rearrange(mask, 'b h0c w0c h1c w1c -> b (h0c w0c) (h1c w1c)',
# **axes_lengths)
# 2. mutual nearest
- mask = mask \
- * (conf_matrix == conf_matrix.max(dim=2, keepdim=True)[0]) \
+ mask = (
+ mask
+ * (conf_matrix == conf_matrix.max(dim=2, keepdim=True)[0])
* (conf_matrix == conf_matrix.max(dim=1, keepdim=True)[0])
+ )
# 3. find all valid coarse matches
# this only works when at most one `True` in each row
@@ -209,11 +197,9 @@ class CoarseMatching(nn.Module):
# The sampling is performed across all pairs in a batch without manually balancing
# #samples for fine-level increases w.r.t. batch_size
if 'mask0' not in data:
- num_candidates_max = mask.size(0) * max(
- mask.size(1), mask.size(2))
+ num_candidates_max = mask.size(0) * max(mask.size(1), mask.size(2))
else:
- num_candidates_max = compute_max_candidates(
- data['mask0'], data['mask1'])
+ num_candidates_max = compute_max_candidates(data['mask0'], data['mask1'])
num_matches_train = num_candidates_max * self.train_coarse_percent
num_matches_train = int(num_matches_train)
num_matches_pred = len(b_ids)
@@ -226,23 +212,26 @@ class CoarseMatching(nn.Module):
pred_indices = torch.arange(num_matches_pred, device=_device)
else:
pred_indices = torch.randint(
- num_matches_pred,
- (num_matches_train - self.train_pad_num_gt_min, ),
- device=_device)
+ num_matches_pred, (num_matches_train - self.train_pad_num_gt_min,), device=_device
+ )
# gt_pad_indices is to select from gt padding. e.g. max(3787-4800, 200)
gt_pad_indices = torch.randint(
len(data['spv_b_ids']),
- (max(num_matches_train - num_matches_pred,
- self.train_pad_num_gt_min), ),
- device=_device)
+ (max(num_matches_train - num_matches_pred, self.train_pad_num_gt_min),),
+ device=_device,
+ )
mconf_gt = torch.zeros(len(data['spv_b_ids']), device=_device) # set conf of gt paddings to all zero
b_ids, i_ids, j_ids, mconf = map(
- lambda x, y: torch.cat([x[pred_indices], y[gt_pad_indices]],
- dim=0),
- *zip([b_ids, data['spv_b_ids']], [i_ids, data['spv_i_ids']],
- [j_ids, data['spv_j_ids']], [mconf, mconf_gt]))
+ lambda x, y: torch.cat([x[pred_indices], y[gt_pad_indices]], dim=0),
+ *zip(
+ [b_ids, data['spv_b_ids']],
+ [i_ids, data['spv_i_ids']],
+ [j_ids, data['spv_j_ids']],
+ [mconf, mconf_gt],
+ )
+ )
# These matches select patches that feed into fine-level network
coarse_matches = {'b_ids': b_ids, 'i_ids': i_ids, 'j_ids': j_ids}
@@ -251,20 +240,18 @@ class CoarseMatching(nn.Module):
scale = data['hw0_i'][0] / data['hw0_c'][0]
scale0 = scale * data['scale0'][b_ids] if 'scale0' in data else scale
scale1 = scale * data['scale1'][b_ids] if 'scale1' in data else scale
- mkpts0_c = torch.stack(
- [i_ids % data['hw0_c'][1], i_ids // data['hw0_c'][1]],
- dim=1) * scale0
- mkpts1_c = torch.stack(
- [j_ids % data['hw1_c'][1], j_ids // data['hw1_c'][1]],
- dim=1) * scale1
+ mkpts0_c = torch.stack([i_ids % data['hw0_c'][1], i_ids // data['hw0_c'][1]], dim=1) * scale0
+ mkpts1_c = torch.stack([j_ids % data['hw1_c'][1], j_ids // data['hw1_c'][1]], dim=1) * scale1
# These matches is the current prediction (for visualization)
- coarse_matches.update({
- 'gt_mask': mconf == 0,
- 'm_bids': b_ids[mconf != 0], # mconf == 0 => gt matches
- 'mkpts0_c': mkpts0_c[mconf != 0].to(dtype=conf_matrix.dtype),
- 'mkpts1_c': mkpts1_c[mconf != 0].to(dtype=conf_matrix.dtype),
- 'mconf': mconf[mconf != 0]
- })
+ coarse_matches.update(
+ {
+ 'gt_mask': mconf == 0,
+ 'm_bids': b_ids[mconf != 0], # mconf == 0 => gt matches
+ 'mkpts0_c': mkpts0_c[mconf != 0].to(dtype=conf_matrix.dtype),
+ 'mkpts1_c': mkpts1_c[mconf != 0].to(dtype=conf_matrix.dtype),
+ 'mconf': mconf[mconf != 0],
+ }
+ )
return coarse_matches
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index 9b97bd6b7..09f6db016 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -35,23 +35,27 @@ class FineMatching(nn.Module):
if self.training:
raise ValueError("M >0, when training, see coarse_matching.py")
# logger.warning('No matches found in coarse-level.')
- data.update({
- 'expec_f': torch.empty(0, 3, device=feat_f0.device, dtype=feat_f0.dtype),
- 'mkpts0_f': data['mkpts0_c'],
- 'mkpts1_f': data['mkpts1_c'],
- })
+ data.update(
+ {
+ 'expec_f': torch.empty(0, 3, device=feat_f0.device, dtype=feat_f0.dtype),
+ 'mkpts0_f': data['mkpts0_c'],
+ 'mkpts1_f': data['mkpts1_c'],
+ }
+ )
return
feat_f0_picked = feat_f0_picked = feat_f0[:, WW // 2, :]
sim_matrix = torch.einsum('mc,mrc->mr', feat_f0_picked, feat_f1)
- softmax_temp = 1. / C**.5
+ softmax_temp = 1.0 / C**0.5
heatmap = torch.softmax(softmax_temp * sim_matrix, dim=1).view(-1, W, W)
# compute coordinates from heatmap
coords_normalized = dsnt.spatial_expectation2d(heatmap[None], True)[0] # [M, 2]
grid_normalized = create_meshgrid(
W, W, normalized_coordinates=True, device=heatmap.device, dtype=heatmap.dtype
- ).reshape(1, -1, 2) # [1, WW, 2]
+ ).reshape(
+ 1, -1, 2
+ ) # [1, WW, 2]
# compute std over <x, y>
var = torch.sum(grid_normalized**2 * heatmap.view(-1, WW, 1), dim=1) - coords_normalized**2 # [M, 2]
@@ -70,9 +74,6 @@ class FineMatching(nn.Module):
# mkpts0_f and mkpts1_f
mkpts0_f = data['mkpts0_c']
scale1 = scale * data['scale1'][data['b_ids']] if 'scale0' in data else scale
- mkpts1_f = data['mkpts1_c'] + (coords_normed * (W // 2) * scale1)[:len(data['mconf'])]
+ mkpts1_f = data['mkpts1_c'] + (coords_normed * (W // 2) * scale1)[: len(data['mconf'])]
- data.update({
- "mkpts0_f": mkpts0_f,
- "mkpts1_f": mkpts1_f
- })
+ data.update({"mkpts0_f": mkpts0_f, "mkpts1_f": mkpts1_f})
diff --git a/kornia/feature/loftr/utils/geometry.py b/kornia/feature/loftr/utils/geometry.py
index e53a9f38d..cd73bc983 100644
--- a/kornia/feature/loftr/utils/geometry.py
+++ b/kornia/feature/loftr/utils/geometry.py
@@ -30,7 +30,7 @@ def warp_kpts(kpts0, depth0, depth1, T_0to1, K0, K1):
kpts0_cam = K0.inverse() @ kpts0_h.transpose(2, 1) # (N, 3, L)
# Rigid Transform
- w_kpts0_cam = T_0to1[:, :3, :3] @ kpts0_cam + T_0to1[:, :3, [3]] # (N, 3, L)
+ w_kpts0_cam = T_0to1[:, :3, :3] @ kpts0_cam + T_0to1[:, :3, [3]] # (N, 3, L)
w_kpts0_depth_computed = w_kpts0_cam[:, 2, :]
# Project
@@ -39,8 +39,9 @@ def warp_kpts(kpts0, depth0, depth1, T_0to1, K0, K1):
# Covisible Check
h, w = depth1.shape[1:3]
- covisible_mask = (w_kpts0[:, :, 0] > 0) * (w_kpts0[:, :, 0] < w - 1) * \
- (w_kpts0[:, :, 1] > 0) * (w_kpts0[:, :, 1] < h - 1)
+ covisible_mask = (
+ (w_kpts0[:, :, 0] > 0) * (w_kpts0[:, :, 0] < w - 1) * (w_kpts0[:, :, 1] > 0) * (w_kpts0[:, :, 1] < h - 1)
+ )
w_kpts0_long = w_kpts0.long()
w_kpts0_long[~covisible_mask, :] = 0
diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
index f260edde1..503ed41d5 100644
--- a/kornia/feature/loftr/utils/position_encoding.py
+++ b/kornia/feature/loftr/utils/position_encoding.py
@@ -38,4 +38,4 @@ class PositionEncodingSine(nn.Module):
Args:
x: [N, C, H, W]
"""
- return x + self.pe[:, :, :x.size(2), :x.size(3)]
+ return x + self.pe[:, :, : x.size(2), : x.size(3)]
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index 30242a252..4f6207a5d 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -46,7 +46,7 @@ def spvs_coarse(data, config):
# 2. warp grids
# create kpts in meshgrid and resize them to image resolution
- grid_pt0_c = create_meshgrid(h0, w0, False, device).reshape(1, h0 * w0, 2).repeat(N, 1, 1) # [N, hw, 2]
+ grid_pt0_c = create_meshgrid(h0, w0, False, device).reshape(1, h0 * w0, 2).repeat(N, 1, 1) # [N, hw, 2]
grid_pt0_i = scale0 * grid_pt0_c
grid_pt1_c = create_meshgrid(h1, w1, False, device).reshape(1, h1 * w1, 2).repeat(N, 1, 1)
grid_pt1_i = scale1 * grid_pt1_c
@@ -73,6 +73,7 @@ def spvs_coarse(data, config):
# corner case: out of boundary
def out_bound_mask(pt, w, h):
return (pt[..., 0] < 0) + (pt[..., 0] >= w) + (pt[..., 1] < 0) + (pt[..., 1] >= h)
+
nearest_index1[out_bound_mask(w_pt0_c_round, w1, h1)] = 0
nearest_index0[out_bound_mask(w_pt1_c_round, w0, h0)] = 0
@@ -95,17 +96,10 @@ def spvs_coarse(data, config):
i_ids = torch.tensor([0], device=device)
j_ids = torch.tensor([0], device=device)
- data.update({
- 'spv_b_ids': b_ids,
- 'spv_i_ids': i_ids,
- 'spv_j_ids': j_ids
- })
+ data.update({'spv_b_ids': b_ids, 'spv_i_ids': i_ids, 'spv_j_ids': j_ids})
# 6. save intermediate results (for fast fine-level computation)
- data.update({
- 'spv_w_pt0_i': w_pt0_i,
- 'spv_pt1_i': grid_pt1_i
- })
+ data.update({'spv_w_pt0_i': w_pt0_i, 'spv_pt1_i': grid_pt1_i})
def compute_supervision_coarse(data, config):
@@ -120,6 +114,7 @@ def compute_supervision_coarse(data, config):
# Fine-Level supervision
+
@torch.no_grad()
def spvs_fine(data, config):
"""
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 6a85c6b83..455a94223 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -191,6 +191,7 @@ class DescriptorMatcher(nn.Module):
match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`.
th: threshold on distance ratio, or other quality measure.
"""
+
known_modes = ['nn', 'mnn', 'snn', 'smnn']
def __init__(self, match_mode: str = 'snn', th: float = 0.8) -> None:
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index dad1ad605..159ba8b94 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -128,7 +128,7 @@ class VonMisesKernel(nn.Module):
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[1:])
weights = weights.reshape(-1, 1, 1)
self.register_buffer('emb0', emb0)
self.register_buffer('frange', frange)
@@ -336,7 +336,7 @@ class ExplicitSpacialEncoding(nn.Module):
def get_gmask(self, sigma: float) -> torch.Tensor:
"""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]:
@@ -580,9 +580,7 @@ class MKDDescriptor(nn.Module):
# Load supervised(lw)/unsupervised(pca) model trained on training_set.
if self.whitening is not None:
storage_fcn: Callable = lambda storage, loc: storage
- whitening_models = torch.hub.load_state_dict_from_url(
- urls[self.kernel_type], map_location=storage_fcn
- )
+ whitening_models = torch.hub.load_state_dict_from_url(urls[self.kernel_type], map_location=storage_fcn)
whitening_model = whitening_models[training_set]
self.whitening_layer = Whitening(
whitening, whitening_model, in_dims=self.odims, output_dims=self.output_dims
@@ -641,9 +639,7 @@ class MKDDescriptor(nn.Module):
def load_whitening_model(kernel_type: str, training_set: str) -> Dict:
storage_fcn: Callable = lambda storage, loc: storage
- whitening_models = torch.hub.load_state_dict_from_url(
- urls[kernel_type], map_location=storage_fcn
- )
+ whitening_models = torch.hub.load_state_dict_from_url(urls[kernel_type], map_location=storage_fcn)
whitening_model = whitening_models[training_set]
return whitening_model
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index b694aceb5..b651043be 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -166,9 +166,7 @@ class OriNet(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['orinet'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['orinet'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict['state_dict'], strict=False)
self.eval()
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 3c5cacd21..29a037b98 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -78,15 +78,15 @@ def harris_response(
# compute the structure tensor M elements
- 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))
+ 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)
@@ -150,15 +150,15 @@ def gftt_response(
dx: torch.Tensor = gradients[:, :, 0]
dy: torch.Tensor = gradients[:, :, 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))
+ 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)
@@ -236,7 +236,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)
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 0871cdb7f..a1b542ed0 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -28,7 +28,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
- kernel: torch.Tensor = torch.ger(xc2, xc2) / (ks_2 ** 2)
+ kernel: torch.Tensor = torch.ger(xc2, xc2) / (ks_2**2)
return kernel
@@ -176,13 +176,14 @@ class SIFTDescriptor(nn.Module):
return ang_bins
-def sift_describe(input: torch.Tensor,
- patch_size: int = 41,
- num_ang_bins: int = 8,
- num_spatial_bins: int = 4,
- rootsift: bool = True,
- clipval: float = 0.2,
- ) -> torch.Tensor:
+def sift_describe(
+ input: torch.Tensor,
+ patch_size: int = 41,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+ rootsift: bool = True,
+ clipval: float = 0.2,
+) -> torch.Tensor:
r"""Computes the sift descriptor.
See :class:`~kornia.feature.SIFTDescriptor` for details.
"""
@@ -216,23 +217,39 @@ class DenseSIFTDescriptor(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) +\
- ', ' + 'spatial_bin_size=' + str(self.spatial_bin_size) +\
- ', ' + 'rootsift=' + str(self.rootsift) +\
- ', ' + 'stride=' + str(self.stride) +\
- ', ' + 'clipval=' + str(self.clipval) + ')'
-
- def __init__(self,
- num_ang_bins: int = 8,
- num_spatial_bins: int = 4,
- spatial_bin_size: int = 4,
- rootsift: bool = True,
- clipval: float = 0.2,
- stride: int = 1,
- padding: int = 1,
- ) -> None:
+ return (
+ self.__class__.__name__
+ + '('
+ + 'num_ang_bins='
+ + str(self.num_ang_bins)
+ + ', '
+ + 'num_spatial_bins='
+ + str(self.num_spatial_bins)
+ + ', '
+ + 'spatial_bin_size='
+ + str(self.spatial_bin_size)
+ + ', '
+ + 'rootsift='
+ + str(self.rootsift)
+ + ', '
+ + 'stride='
+ + str(self.stride)
+ + ', '
+ + 'clipval='
+ + str(self.clipval)
+ + ')'
+ )
+
+ def __init__(
+ self,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+ spatial_bin_size: int = 4,
+ rootsift: bool = True,
+ clipval: float = 0.2,
+ stride: int = 1,
+ padding: int = 1,
+ ) -> None:
super().__init__()
self.eps = 1e-10
self.num_ang_bins = num_ang_bins
@@ -243,18 +260,26 @@ class DenseSIFTDescriptor(nn.Module):
self.stride = stride
self.pad = padding
nw = get_sift_pooling_kernel(ksize=self.spatial_bin_size).float()
- self.bin_pooling_kernel = nn.Conv2d(1, 1, kernel_size=(nw.size(0), nw.size(1)),
- stride=(1, 1),
- bias=False,
- padding=(nw.size(0) // 2, nw.size(1) // 2))
+ self.bin_pooling_kernel = nn.Conv2d(
+ 1,
+ 1,
+ kernel_size=(nw.size(0), nw.size(1)),
+ stride=(1, 1),
+ bias=False,
+ padding=(nw.size(0) // 2, nw.size(1) // 2),
+ )
self.bin_pooling_kernel.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1)))
- self.PoolingConv = nn.Conv2d(num_ang_bins,
- num_ang_bins * num_spatial_bins**2,
- kernel_size=(num_spatial_bins, num_spatial_bins),
- stride=(self.stride, self.stride), bias=False, padding=(self.pad, self.pad))
- self.PoolingConv.weight.data.copy_(_get_reshape_kernel(num_ang_bins,
- num_spatial_bins,
- num_spatial_bins).float())
+ self.PoolingConv = nn.Conv2d(
+ num_ang_bins,
+ num_ang_bins * num_spatial_bins**2,
+ kernel_size=(num_spatial_bins, num_spatial_bins),
+ stride=(self.stride, self.stride),
+ bias=False,
+ padding=(self.pad, self.pad),
+ )
+ self.PoolingConv.weight.data.copy_(
+ _get_reshape_kernel(num_ang_bins, num_spatial_bins, num_spatial_bins).float()
+ )
return
def get_pooling_kernel(self) -> torch.Tensor:
@@ -275,15 +300,16 @@ class DenseSIFTDescriptor(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
wo1_big: torch.Tensor = wo1_big_ * mag
ang_bins = []
for i in range(0, self.num_ang_bins):
- out = self.bin_pooling_kernel((bo0_big == i).to(input.dtype) * wo0_big + # noqa
- (bo1_big == i).to(input.dtype) * wo1_big)
+ out = self.bin_pooling_kernel(
+ (bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big
+ )
ang_bins.append(out)
ang_bins = torch.cat(ang_bins, dim=1)
out_no_norm = self.PoolingConv(ang_bins)
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 6fa490310..5fe8d86ca 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -60,9 +60,7 @@ class SOSNet(nn.Module):
# load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['lib'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['lib'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
return
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index 8b5d70a7e..d6aed9bad 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -6,9 +6,7 @@ import torch.nn as nn
from kornia.testing import KORNIA_CHECK_SHAPE
urls: Dict[str, str] = {}
-urls[
- "liberty"
-] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # pylint: disable
+urls["liberty"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # pylint: disable
urls[
"notredame"
] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params" # pylint: disable
@@ -55,9 +53,7 @@ class TFeat(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(
- urls['liberty'], map_location=storage_fcn
- )
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=storage_fcn)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index 2f11f4b73..dacaf7b2c 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -92,7 +92,7 @@ def canny(
angle: torch.Tensor = torch.atan2(gy, gx)
# Radians to Degrees
- angle = 180. * angle / math.pi
+ angle = 180.0 * angle / math.pi
# Round angle to the nearest 45 degree
angle = torch.round(angle / 45) * 45
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 6fe2b1d6a..66c824de4 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -7,11 +7,13 @@ from .filter import filter2d, filter2d_separable
from .kernels import get_gaussian_kernel1d, get_gaussian_kernel2d
-def gaussian_blur2d(input: torch.Tensor,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect',
- separable: bool = True) -> torch.Tensor:
+def gaussian_blur2d(
+ input: torch.Tensor,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = 'reflect',
+ separable: bool = True,
+) -> torch.Tensor:
r"""Create an operator that blurs a tensor using a Gaussian filter.
.. image:: _static/img/gaussian_blur2d.png
@@ -81,11 +83,13 @@ class GaussianBlur2d(nn.Module):
torch.Size([2, 4, 5, 5])
"""
- def __init__(self,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
- border_type: str = 'reflect',
- separable: bool = True) -> None:
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int],
+ sigma: Tuple[float, float],
+ border_type: str = 'reflect',
+ separable: bool = True,
+ ) -> None:
super().__init__()
self.kernel_size: Tuple[int, int] = kernel_size
self.sigma: Tuple[float, float] = sigma
@@ -109,8 +113,4 @@ class GaussianBlur2d(nn.Module):
)
def forward(self, input: torch.Tensor) -> torch.Tensor:
- return gaussian_blur2d(input,
- self.kernel_size,
- self.sigma,
- self.border_type,
- self.separable)
+ return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type, self.separable)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 12f316772..cc32fcfb0 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -20,7 +20,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()
@@ -516,7 +516,7 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:
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
@@ -663,9 +663,7 @@ def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=tor
return x
-def get_hanning_kernel2d(kernel_size: Tuple[int, int],
- device=torch.device('cpu'),
- dtype=torch.float) -> torch.Tensor:
+def get_hanning_kernel2d(kernel_size: Tuple[int, int], device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
r"""Returns 2d Hanning kernel, used in signal processing and KCF tracker.
Args:
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index ab77e56b8..e3955a5c7 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -90,9 +90,9 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1)
left = slice(0, -2)
right = slice(2, None)
out = torch.empty(b, c, 3, d, h, w, device=dev, dtype=dtype)
- out[..., 0, :, :, :] = (x[..., center, center, right] - x[..., center, center, left])
- out[..., 1, :, :, :] = (x[..., center, right, center] - x[..., center, left, center])
- out[..., 2, :, :, :] = (x[..., right, center, center] - x[..., left, center, center])
+ out[..., 0, :, :, :] = x[..., center, center, right] - x[..., center, center, left]
+ out[..., 1, :, :, :] = x[..., center, right, center] - x[..., center, left, center]
+ out[..., 2, :, :, :] = x[..., right, center, center] - x[..., left, center, center]
out = 0.5 * out
else:
# prepare kernel
@@ -106,17 +106,18 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1)
kernel_flip: torch.Tensor = tmp_kernel.flip(-3)
# Pad with "replicate for spatial dims, but with zeros for channel
- spatial_pad = [kernel.size(2) // 2,
- kernel.size(2) // 2,
- kernel.size(3) // 2,
- kernel.size(3) // 2,
- kernel.size(4) // 2,
- kernel.size(4) // 2]
+ spatial_pad = [
+ kernel.size(2) // 2,
+ kernel.size(2) // 2,
+ kernel.size(3) // 2,
+ kernel.size(3) // 2,
+ kernel.size(4) // 2,
+ kernel.size(4) // 2,
+ ]
out_ch: int = 6 if order == 2 else 3
- out = F.conv3d(F.pad(input, spatial_pad, 'replicate'),
- kernel_flip,
- padding=0,
- groups=c).view(b, c, out_ch, d, h, w)
+ out = F.conv3d(F.pad(input, spatial_pad, 'replicate'), kernel_flip, padding=0, groups=c).view(
+ b, c, out_ch, d, h, w
+ )
return out
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 12abbfddd..6b2569f69 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -197,7 +197,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
box_i = (boxes + 1).long()
# set all pixels within box to 1
for msk, bx in zip(mask, box_i):
- msk[bx[0, 1]:bx[2, 1] + 1, bx[0, 0]:bx[1, 0] + 1] = 1.0
+ msk[bx[0, 1] : bx[2, 1] + 1, bx[0, 0] : bx[1, 0] + 1] = 1.0
return mask[:, 1:-1, 1:-1]
@@ -537,8 +537,8 @@ def nms(boxes: torch.Tensor, scores: torch.Tensor, iou_threshold: float) -> torc
xx2 = torch.min(x2[i], x2[order[1:]])
yy2 = torch.min(y2[i], y2[order[1:]])
- w = torch.clamp(xx2 - xx1, min=0.)
- h = torch.clamp(yy2 - yy1, min=0.)
+ w = torch.clamp(xx2 - xx1, min=0.0)
+ h = torch.clamp(yy2 - yy1, min=0.0)
inter = w * h
ovr = inter / (areas[i] + areas[order[1:]] - inter)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 79d14342b..c368f57a0 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -12,14 +12,10 @@ def _is_floating_point_dtype(dtype: torch.dtype) -> bool:
return dtype in (torch.float16, torch.float32, torch.float64, torch.bfloat16, torch.half)
-def _merge_box_list(
- boxes: List[torch.Tensor], method: str = "pad"
-) -> Tuple[torch.Tensor, List[int]]:
- r"""Merge a list of boxes into one tensor.
- """
+def _merge_box_list(boxes: List[torch.Tensor], method: str = "pad") -> Tuple[torch.Tensor, List[int]]:
+ r"""Merge a list of boxes into one tensor."""
if not all(box.shape[-2:] == torch.Size([4, 2]) and box.dim() == 3 for box in boxes):
- raise TypeError(
- f"Input boxes must be a list of (N, 4, 2) shaped. Got: {[box.shape for box in boxes]}.")
+ raise TypeError(f"Input boxes must be a list of (N, 4, 2) shaped. Got: {[box.shape for box in boxes]}.")
if method == "pad":
max_N = max(box.shape[0] for box in boxes)
@@ -75,9 +71,7 @@ def _boxes_to_polygons(
return polygons
-def _boxes_to_quadrilaterals(
- boxes: torch.Tensor, mode: str = "xyxy", validate_boxes: bool = True
-) -> torch.Tensor:
+def _boxes_to_quadrilaterals(boxes: torch.Tensor, mode: str = "xyxy", validate_boxes: bool = True) -> torch.Tensor:
"""Convert from boxes to quadrilaterals."""
mode = mode.lower()
@@ -185,9 +179,12 @@ class Boxes:
``width = xmax - xmin + 1`` and ``height = ymax - ymin + 1``. Examples of
`quadrilaterals <https://en.wikipedia.org/wiki/Quadrilateral>`_ are rectangles, rhombus and trapezoids.
"""
+
def __init__(
- self, boxes: Union[torch.Tensor, List[torch.Tensor]], raise_if_not_floating_point: bool = True,
- mode: str = "vertices_plus"
+ self,
+ boxes: Union[torch.Tensor, List[torch.Tensor]],
+ raise_if_not_floating_point: bool = True,
+ mode: str = "vertices_plus",
) -> None:
self._N: Optional[List[int]] = None
@@ -354,8 +351,9 @@ class Boxes:
boxes = _boxes_to_polygons(boxes[..., 0], boxes[..., 1], boxes[..., 2], boxes[..., 3])
if self._N is not None and not as_padded_sequence:
- boxes = list(torch.nn.functional.pad(
- o, (len(o.shape) - 1) * [0, 0] + [0, - n]) for o, n in zip(boxes, self._N))
+ boxes = list(
+ torch.nn.functional.pad(o, (len(o.shape) - 1) * [0, 0] + [0, -n]) for o, n in zip(boxes, self._N)
+ )
else:
boxes = boxes if self._is_batched else boxes.squeeze(0)
return boxes
@@ -482,9 +480,9 @@ class Boxes3D:
``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and ``depth = zmax - zmin + 1``. Examples of
`hexahedrons <https://en.wikipedia.org/wiki/Hexahedron>`_ are cubes and rhombohedrons.
"""
+
def __init__(
- self, boxes: torch.Tensor, raise_if_not_floating_point: bool = True,
- mode: str = "xyzxyz_plus"
+ self, boxes: torch.Tensor, raise_if_not_floating_point: bool = True, mode: str = "xyzxyz_plus"
) -> None:
if not isinstance(boxes, torch.Tensor):
raise TypeError(f"Input boxes is not a Tensor. Got: {type(boxes)}.")
@@ -642,10 +640,12 @@ class Boxes3D:
>>> assert (boxes.to_tensor(mode='xyzxyz') == boxes_xyzxyz).all()
"""
if self._data.requires_grad:
- raise RuntimeError("Boxes3D.to_tensor doesn't support computing gradients since they aren't accurate. "
- "Please, create boxes from tensors with `requires_grad=False`. "
- "This is a known bug. Help is needed to fix it. For more information, "
- "see https://github.com/kornia/kornia/issues/1396.")
+ raise RuntimeError(
+ "Boxes3D.to_tensor doesn't support computing gradients since they aren't accurate. "
+ "Please, create boxes from tensors with `requires_grad=False`. "
+ "This is a known bug. Help is needed to fix it. For more information, "
+ "see https://github.com/kornia/kornia/issues/1396."
+ )
batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)
diff --git a/kornia/geometry/calibration/__init__.py b/kornia/geometry/calibration/__init__.py
index d62ef7e52..76487461e 100644
--- a/kornia/geometry/calibration/__init__.py
+++ b/kornia/geometry/calibration/__init__.py
@@ -2,10 +2,4 @@ from .distort import distort_points, tilt_projection
from .pnp import solve_pnp_dlt
from .undistort import undistort_image, undistort_points
-__all__ = [
- "undistort_points",
- "undistort_image",
- "tilt_projection",
- "distort_points",
- "solve_pnp_dlt",
-]
+__all__ = ["undistort_points", "undistort_image", "tilt_projection", "distort_points", "solve_pnp_dlt"]
diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.py
index facaece76..18c0e5f8c 100644
--- a/kornia/geometry/calibration/distort.py
+++ b/kornia/geometry/calibration/distort.py
@@ -56,8 +56,9 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool
return tilt
-def distort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor, new_K: Optional[torch.Tensor] = None
- ) -> torch.Tensor:
+def distort_points(
+ points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor, new_K: Optional[torch.Tensor] = None
+) -> torch.Tensor:
r"""Distortion of a set of 2D points based on the lens distortion model.
Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`,
@@ -114,8 +115,8 @@ def distort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor, ne
# Distort points
r2 = x * x + y * y
- rad_poly = (1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2 ** 3) / (
- 1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2 ** 3
+ rad_poly = (1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2**3) / (
+ 1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2**3
)
xd = (
x * rad_poly
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 3ff27ea68..471cfaa9b 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -8,9 +8,7 @@ from kornia.utils import eye_like
from kornia.utils._compat import linalg_qr
-def _mean_isotropic_scale_normalize(
- points: torch.Tensor, eps: float = 1e-8
-) -> Tuple[torch.Tensor, torch.Tensor]:
+def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Normalizes points.
Args:
@@ -46,8 +44,10 @@ def _mean_isotropic_scale_normalize(
def solve_pnp_dlt(
- world_points: torch.Tensor, img_points: torch.Tensor,
- intrinsics: torch.Tensor, weights: Optional[torch.Tensor] = None,
+ world_points: torch.Tensor,
+ img_points: torch.Tensor,
+ intrinsics: torch.Tensor,
+ weights: Optional[torch.Tensor] = None,
svd_eps: float = 1e-4,
) -> torch.Tensor:
r"""This function attempts to solve the Perspective-n-Point (PnP)
@@ -134,14 +134,10 @@ def solve_pnp_dlt(
)
if not isinstance(img_points, torch.Tensor):
- raise AssertionError(
- f"img_points is not an instance of torch.Tensor. Type of img_points is {type(img_points)}"
- )
+ raise AssertionError(f"img_points is not an instance of torch.Tensor. Type of img_points is {type(img_points)}")
if not isinstance(intrinsics, torch.Tensor):
- raise AssertionError(
- f"intrinsics is not an instance of torch.Tensor. Type of intrinsics is {type(intrinsics)}"
- )
+ raise AssertionError(f"intrinsics is not an instance of torch.Tensor. Type of intrinsics is {type(intrinsics)}")
if (weights is not None) and (not isinstance(weights, torch.Tensor)):
raise AssertionError(
@@ -173,19 +169,13 @@ def solve_pnp_dlt(
)
if (len(world_points.shape) != 3) or (world_points.shape[2] != 3):
- raise AssertionError(
- f"world_points must be of shape (B, N, 3). Got shape {world_points.shape}."
- )
+ raise AssertionError(f"world_points must be of shape (B, N, 3). Got shape {world_points.shape}.")
if (len(img_points.shape) != 3) or (img_points.shape[2] != 2):
- raise AssertionError(
- f"img_points must be of shape (B, N, 2). Got shape {img_points.shape}."
- )
+ raise AssertionError(f"img_points must be of shape (B, N, 2). Got shape {img_points.shape}.")
if (len(intrinsics.shape) != 3) or (intrinsics.shape[1:] != (3, 3)):
- raise AssertionError(
- f"intrinsics must be of shape (B, 3, 3). Got shape {intrinsics.shape}."
- )
+ raise AssertionError(f"intrinsics must be of shape (B, 3, 3). Got shape {intrinsics.shape}.")
if world_points.shape[1] != img_points.shape[1]:
raise AssertionError("world_points and img_points must have equal number of points.")
@@ -195,8 +185,7 @@ def solve_pnp_dlt(
if world_points.shape[1] < 6:
raise AssertionError(
- f"At least 6 points are required to use this function. "
- f"Got {world_points.shape[1]} points."
+ f"At least 6 points are required to use this function. " f"Got {world_points.shape[1]} points."
)
B, N = world_points.shape[:2]
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 58bfabf1f..bac76289b 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -10,8 +10,9 @@ from .distort import distort_points, tilt_projection
# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384
-def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor,
- new_K: Optional[torch.Tensor] = None, num_iters: int = 5) -> torch.Tensor:
+def undistort_points(
+ points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor, new_K: Optional[torch.Tensor] = None, num_iters: int = 5
+) -> torch.Tensor:
r"""Compensate for lens distortion a set of 2D image points.
Radial :math:`(k_1, k_2, k_3, k_4, k_5, k_6)`,
@@ -82,8 +83,8 @@ def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor,
for _ in range(num_iters):
r2 = x * x + y * y
- inv_rad_poly = (1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2 ** 3) / (
- 1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2 ** 3
+ inv_rad_poly = (1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2**3) / (
+ 1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2**3
)
deltaX = (
2 * dist[..., 2:3] * x * y
diff --git a/kornia/geometry/camera/__init__.py b/kornia/geometry/camera/__init__.py
index 54c33d0d5..343ac3348 100644
--- a/kornia/geometry/camera/__init__.py
+++ b/kornia/geometry/camera/__init__.py
@@ -2,11 +2,4 @@ from .perspective import project_points, unproject_points
from .pinhole import PinholeCamera, cam2pixel, pixel2cam
from .stereo import StereoCamera
-__all__ = [
- "PinholeCamera",
- "StereoCamera",
- "pixel2cam",
- "cam2pixel",
- "unproject_points",
- "project_points"
-]
+__all__ = ["PinholeCamera", "StereoCamera", "pixel2cam", "cam2pixel", "unproject_points", "project_points"]
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index bbc738964..89e0dd2a1 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -128,7 +128,7 @@ def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1.0e-8) -> Tuple[tor
if not (isinstance(x, torch.Tensor) & isinstance(y, torch.Tensor)):
raise TypeError(f"Input type is not a torch.Tensor. Got {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
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index c7a03cb1d..7fadd2921 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -12,13 +12,7 @@ from .camera import PinholeCamera, cam2pixel, pixel2cam, project_points, unproje
from .conversions import normalize_pixel_coordinates
from .linalg import compose_transformations, convert_points_to_homogeneous, inverse_transformation, transform_points
-__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:
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index bf272055f..41df71c80 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -112,9 +112,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.0, 1.0, 0.0],
- device=F_mat.device,
- dtype=F_mat.dtype)
+ rank_mask = torch.tensor([1.0, 1.0, 0.0], device=F_mat.device, dtype=F_mat.dtype)
F_projected = U @ (torch.diag_embed(S * rank_mask) @ V.transpose(-2, -1))
F_est = transform2.transpose(-2, -1) @ (F_projected @ transform1)
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index c64de1d66..6d53b88b1 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -177,7 +177,7 @@ def find_homography_dlt_iterated(
H: torch.Tensor = find_homography_dlt(points1, points2, weights)
for _ in range(n_iter - 1):
errors: torch.Tensor = symmetric_transfer_error(points1, points2, H, False)
- weights_new: torch.Tensor = torch.exp(-errors / (2.0 * (soft_inl_th ** 2)))
+ weights_new: torch.Tensor = torch.exp(-errors / (2.0 * (soft_inl_th**2)))
H = find_homography_dlt(points1, points2, weights_new)
return H
@@ -201,18 +201,17 @@ def sample_is_valid_for_homography(points1: torch.Tensor, points2: torch.Tensor)
if points1.shape[1] != 4:
raise AssertionError(points1.shape)
device = points1.device
- idx_perm = torch.tensor([[0, 1, 2],
- [0, 1, 3],
- [0, 2, 3],
- [1, 2, 3]], dtype=torch.long, device=device)
+ idx_perm = torch.tensor([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]], dtype=torch.long, device=device)
points_src_h = convert_points_to_homogeneous(points1)
points_dst_h = convert_points_to_homogeneous(points2)
src_perm = points_src_h[:, idx_perm]
dst_perm = points_dst_h[:, idx_perm]
- left_sign = (torch.cross(src_perm[..., 1:2, :],
- src_perm[..., 2:3, :]) @ src_perm[..., 0:1, :].permute(0, 1, 3, 2)).sign()
- right_sign = (torch.cross(dst_perm[..., 1:2, :],
- dst_perm[..., 2:3, :]) @ dst_perm[..., 0:1, :].permute(0, 1, 3, 2)).sign()
+ left_sign = (
+ torch.cross(src_perm[..., 1:2, :], src_perm[..., 2:3, :]) @ src_perm[..., 0:1, :].permute(0, 1, 3, 2)
+ ).sign()
+ right_sign = (
+ torch.cross(dst_perm[..., 1:2, :], dst_perm[..., 2:3, :]) @ dst_perm[..., 0:1, :].permute(0, 1, 3, 2)
+ ).sign()
sample_is_valid = (left_sign == right_sign).view(-1, 4).min(dim=1)[0]
return sample_is_valid
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index f5f650518..b7d2ad269 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -29,15 +29,18 @@ class RANSAC(nn.Module):
confidence: desired confidence of the result, used for the early stopping.
max_local_iterations: number of local optimization (polishing) iterations.
"""
+
supported_models = ['homography', 'fundamental']
- def __init__(self,
- model_type: str = 'homography',
- inl_th: float = 2.0,
- batch_size: int = 2048,
- max_iter: int = 10,
- confidence: float = 0.99,
- max_lo_iters: int = 5):
+ def __init__(
+ self,
+ model_type: str = 'homography',
+ inl_th: float = 2.0,
+ batch_size: int = 2048,
+ max_iter: int = 10,
+ confidence: float = 0.99,
+ max_lo_iters: int = 5,
+ ):
super().__init__()
self.inl_th = inl_th
self.max_iter = max_iter
@@ -61,11 +64,9 @@ class RANSAC(nn.Module):
else:
raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
- def sample(self,
- sample_size: int,
- pop_size: int,
- batch_size: int,
- device: torch.device = torch.device('cpu')) -> torch.Tensor:
+ def sample(
+ self, sample_size: int, pop_size: int, batch_size: int, device: torch.device = torch.device('cpu')
+ ) -> torch.Tensor:
"""Minimal sampler, but unlike traditional RANSAC we sample in batches to get benefit of the parallel
processing, esp.
@@ -81,33 +82,23 @@ class RANSAC(nn.Module):
https://en.wikipedia.org/wiki/Random_sample_consensus."""
if n_inl == num_tc:
return 1.0
- return math.log(1.0 - conf) / math.log(1. - math.pow(n_inl / num_tc, sample_size))
+ return math.log(1.0 - conf) / math.log(1.0 - math.pow(n_inl / num_tc, sample_size))
- def estimate_model_from_minsample(self,
- kp1: torch.Tensor,
- kp2: torch.Tensor) -> torch.Tensor:
+ def estimate_model_from_minsample(self, kp1: torch.Tensor, kp2: torch.Tensor) -> torch.Tensor:
batch_size, sample_size = kp1.shape[:2]
- H = self.minimal_solver(kp1,
- kp2,
- torch.ones(batch_size,
- sample_size,
- dtype=kp1.dtype,
- device=kp1.device))
+ H = self.minimal_solver(kp1, kp2, torch.ones(batch_size, sample_size, dtype=kp1.dtype, device=kp1.device))
return H
- def verify(self,
- kp1: torch.Tensor,
- kp2: torch.Tensor,
- models: torch.Tensor, inl_th: float) -> Tuple[torch.Tensor, torch.Tensor, float]:
+ def verify(
+ self, kp1: torch.Tensor, kp2: torch.Tensor, models: torch.Tensor, inl_th: float
+ ) -> Tuple[torch.Tensor, torch.Tensor, float]:
if len(kp1.shape) == 2:
kp1 = kp1[None]
if len(kp2.shape) == 2:
kp2 = kp2[None]
batch_size = models.shape[0]
- errors = self.error_fn(kp1.expand(batch_size, -1, 2),
- kp2.expand(batch_size, -1, 2),
- models)
- inl = (errors <= inl_th)
+ errors = self.error_fn(kp1.expand(batch_size, -1, 2), kp2.expand(batch_size, -1, 2), models)
+ inl = errors <= inl_th
models_score = inl.to(kp1).sum(dim=1)
best_model_idx = models_score.argmax()
best_model_score = models_score[best_model_idx].item()
@@ -127,32 +118,23 @@ class RANSAC(nn.Module):
def remove_bad_models(self, models: torch.Tensor) -> torch.Tensor:
# ToDo: add more and better degenerate model rejection
# For now it is simple and hardcoded
- main_diagonal = torch.diagonal(models,
- dim1=1,
- dim2=2)
+ main_diagonal = torch.diagonal(models, dim1=1, dim2=2)
mask = main_diagonal.abs().min(dim=1)[0] > 1e-4
return models[mask]
- def polish_model(self,
- kp1: torch.Tensor,
- kp2: torch.Tensor,
- inliers: torch.Tensor) -> torch.Tensor:
+ def polish_model(self, kp1: torch.Tensor, kp2: torch.Tensor, inliers: torch.Tensor) -> torch.Tensor:
# TODO: Replace this with MAGSAC++ polisher
kp1_inl = kp1[inliers][None]
kp2_inl = kp2[inliers][None]
num_inl = kp1_inl.size(1)
- model = self.polisher_solver(kp1_inl,
- kp2_inl,
- torch.ones(1,
- num_inl,
- dtype=kp1_inl.dtype,
- device=kp1_inl.device))
+ model = self.polisher_solver(
+ kp1_inl, kp2_inl, torch.ones(1, num_inl, dtype=kp1_inl.dtype, device=kp1_inl.device)
+ )
return model
- def forward(self,
- kp1: torch.Tensor,
- kp2: torch.Tensor,
- weights: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
+ def forward(
+ self, kp1: torch.Tensor, kp2: torch.Tensor, weights: Optional[torch.Tensor] = None
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
r"""Main forward method to execute the RANSAC algorithm.
Args:
@@ -163,7 +145,7 @@ class RANSAC(nn.Module):
Returns:
- Estimated model, shape of :math:`(1, 3, 3)`.
- The inlier/outlier mask, shape of :math:`(1, N)`, where N is number of input correspondences.
- """
+ """
if not isinstance(kp1, torch.Tensor):
raise TypeError(f"Input kp1 is not torch.Tensor. Got {type(kp1)}")
if not isinstance(kp2, torch.Tensor):
@@ -173,9 +155,11 @@ class RANSAC(nn.Module):
if not len(kp2.shape) == 2:
raise ValueError(f"Invalid kp2 shape, we expect Nx2 Got: {kp2.shape}")
if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):
- raise ValueError(f"kp1 and kp2 should be \
+ raise ValueError(
+ f"kp1 and kp2 should be \
equal shape at at least [{self.minimal_sample_size}, 2], \
- got {kp1.shape}, {kp2.shape}")
+ got {kp1.shape}, {kp2.shape}"
+ )
best_score_total: float = float(self.minimal_sample_size)
num_tc: int = len(kp1)
@@ -218,10 +202,9 @@ class RANSAC(nn.Module):
best_score_total = model_score
# Should we already stop?
- new_max_iter = int(self.max_samples_by_conf(int(best_score_total),
- num_tc,
- self.minimal_sample_size,
- self.confidence))
+ new_max_iter = int(
+ self.max_samples_by_conf(int(best_score_total), num_tc, self.minimal_sample_size, self.confidence)
+ )
# print (f"New max_iter = {new_max_iter}")
# Stop estimation, if the model is very good
if (i + 1) * self.batch_size >= new_max_iter:
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 7d853b58d..5c64a5caa 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -54,11 +54,7 @@ class NonMaximaSuppression2d(nn.Module):
B, CH, HP, WP = x_padded.size()
max_non_center = (
- F.conv2d(
- x_padded.view(B * CH, 1, HP, WP),
- self.kernel.to(x.device, x.dtype), # type: ignore
- stride=1
- )
+ F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1) # type: ignore
.view(B, CH, -1, H, W)
.max(dim=2)[0]
)
@@ -101,32 +97,34 @@ class NonMaximaSuppression3d(nn.Module):
left = slice(0, -2)
right = slice(2, None)
center_tensor = x[..., center, center, center]
- mask[..., 1: -1, 1: -1, 1: -1] = ((center_tensor > x[..., center, center, left]) & # noqa: W504
- (center_tensor > x[..., center, center, right]) & # noqa: W504
- (center_tensor > x[..., center, left, center]) & # noqa: W504
- (center_tensor > x[..., center, left, left]) & # noqa: W504
- (center_tensor > x[..., center, left, right]) & # noqa: W504
- (center_tensor > x[..., center, right, center]) & # noqa: W504
- (center_tensor > x[..., center, right, left]) & # noqa: W504
- (center_tensor > x[..., center, right, right]) & # noqa: W504
- (center_tensor > x[..., left, center, center]) & # noqa: W504
- (center_tensor > x[..., left, center, left]) & # noqa: W504
- (center_tensor > x[..., left, center, right]) & # noqa: W504
- (center_tensor > x[..., left, left, center]) & # noqa: W504
- (center_tensor > x[..., left, left, left]) & # noqa: W504
- (center_tensor > x[..., left, left, right]) & # noqa: W504
- (center_tensor > x[..., left, right, center]) & # noqa: W504
- (center_tensor > x[..., left, right, left]) & # noqa: W504
- (center_tensor > x[..., left, right, right]) & # noqa: W504
- (center_tensor > x[..., right, center, center]) & # noqa: W504
- (center_tensor > x[..., right, center, left]) & # noqa: W504
- (center_tensor > x[..., right, center, right]) & # noqa: W504
- (center_tensor > x[..., right, left, center]) & # noqa: W504
- (center_tensor > x[..., right, left, left]) & # noqa: W504
- (center_tensor > x[..., right, left, right]) & # noqa: W504
- (center_tensor > x[..., right, right, center]) & # noqa: W504
- (center_tensor > x[..., right, right, left]) & # noqa: W504
- (center_tensor > x[..., right, right, right]))
+ mask[..., 1:-1, 1:-1, 1:-1] = (
+ (center_tensor > x[..., center, center, left])
+ & (center_tensor > x[..., center, center, right])
+ & (center_tensor > x[..., center, left, center])
+ & (center_tensor > x[..., center, left, left])
+ & (center_tensor > x[..., center, left, right])
+ & (center_tensor > x[..., center, right, center])
+ & (center_tensor > x[..., center, right, left])
+ & (center_tensor > x[..., center, right, right])
+ & (center_tensor > x[..., left, center, center])
+ & (center_tensor > x[..., left, center, left])
+ & (center_tensor > x[..., left, center, right])
+ & (center_tensor > x[..., left, left, center])
+ & (center_tensor > x[..., left, left, left])
+ & (center_tensor > x[..., left, left, right])
+ & (center_tensor > x[..., left, right, center])
+ & (center_tensor > x[..., left, right, left])
+ & (center_tensor > x[..., left, right, right])
+ & (center_tensor > x[..., right, center, center])
+ & (center_tensor > x[..., right, center, left])
+ & (center_tensor > x[..., right, center, right])
+ & (center_tensor > x[..., right, left, center])
+ & (center_tensor > x[..., right, left, left])
+ & (center_tensor > x[..., right, left, right])
+ & (center_tensor > x[..., right, right, center])
+ & (center_tensor > x[..., right, right, left])
+ & (center_tensor > x[..., right, right, right])
+ )
else:
max_non_center = (
F.conv3d(
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 13efd60e8..00872f558 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -496,16 +496,14 @@ def conv_soft_argmax3d(
out_levels: int = x_softmaxpool.size(2)
skip_levels: int = (in_levels - out_levels) // 2
strict_maxima: torch.Tensor = F.avg_pool3d(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
def spatial_soft_argmax2d(
- input: torch.Tensor,
- temperature: torch.Tensor = torch.tensor(1.0),
- normalized_coordinates: bool = True,
+ input: torch.Tensor, temperature: torch.Tensor = torch.tensor(1.0), normalized_coordinates: bool = True
) -> torch.Tensor:
r"""Compute the Spatial Soft-Argmax 2D of a given input heatmap.
@@ -538,9 +536,7 @@ class SpatialSoftArgmax2d(nn.Module):
See :func:`~kornia.geometry.subpix.spatial_soft_argmax2d` for details.
"""
- def __init__(
- self, temperature: torch.Tensor = torch.tensor(1.0), normalized_coordinates: bool = True
- ) -> None:
+ def __init__(self, temperature: torch.Tensor = torch.tensor(1.0), normalized_coordinates: bool = True) -> None:
super().__init__()
self.temperature: torch.Tensor = temperature
self.normalized_coordinates: bool = normalized_coordinates
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 52b034158..982e59137 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -582,8 +582,7 @@ def resize(
if antialias:
# First, we have to determine sigma
# Taken from skimage: https://github.com/scikit-image/scikit-image/blob/v0.19.2/skimage/transform/_warps.py#L171
- sigmas = (max((factors[0] - 1.0) / 2.0, 0.001),
- max((factors[1] - 1.0) / 2.0, 0.001))
+ sigmas = (max((factors[0] - 1.0) / 2.0, 0.001), max((factors[1] - 1.0) / 2.0, 0.001))
# Now kernel size. Good results are for 3 sigma, but that is kind of slow. Pillow uses 1 sigma
# https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206
@@ -906,11 +905,7 @@ class Translate(nn.Module):
"""
def __init__(
- self,
- translation: torch.Tensor,
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = True,
+ self, translation: torch.Tensor, mode: str = 'bilinear', padding_mode: str = 'zeros', align_corners: bool = True
) -> None:
super().__init__()
self.translation: torch.Tensor = translation
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 226095b09..9620de55a 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -7,13 +7,7 @@ from kornia.geometry.bbox import infer_bbox_shape, validate_bbox
from .affwarp import resize
from .imgwarp import get_perspective_transform, warp_affine
-__all__ = [
- "crop_and_resize",
- "crop_by_boxes",
- "crop_by_transform_mat",
- "crop_by_indices",
- "center_crop",
-]
+__all__ = ["crop_and_resize", "crop_by_boxes", "crop_by_transform_mat", "crop_by_indices", "center_crop"]
def crop_and_resize(
@@ -170,7 +164,7 @@ def crop_by_boxes(
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
- validate_boxes: bool = True
+ validate_boxes: bool = True,
) -> torch.Tensor:
"""Perform crop transform on 2D images (4D tensor) given two bounding boxes.
@@ -309,18 +303,16 @@ def crop_by_indices(
y2 = src[:, 3, 1] + 1
if (
- len(x1.unique(sorted=False)) == len(x2.unique(sorted=False)) == len(
- y1.unique(sorted=False)) == len(y2.unique(sorted=False)) == 1
+ len(x1.unique(sorted=False))
+ == len(x2.unique(sorted=False))
+ == len(y1.unique(sorted=False))
+ == len(y2.unique(sorted=False))
+ == 1
):
- out = input[..., y1[0]:y2[0], x1[0]:x2[0]] # type:ignore
+ out = input[..., y1[0] : y2[0], x1[0] : x2[0]] # type:ignore
if size is not None and out.shape[-2:] != size:
return resize(
- out,
- size,
- interpolation=interpolation,
- align_corners=align_corners,
- side="short",
- antialias=antialias
+ out, size, interpolation=interpolation, align_corners=align_corners, side="short", antialias=antialias
)
if size is None:
@@ -334,13 +326,13 @@ def crop_by_indices(
for i, same in enumerate(same_sized):
if not same:
out[i] = resize(
- input[i:i + 1, :, y1[i]:y2[i], x1[i]:x2[i]], # type:ignore
+ input[i : i + 1, :, y1[i] : y2[i], x1[i] : x2[i]], # type:ignore
size,
interpolation=interpolation,
align_corners=align_corners,
side="short",
- antialias=antialias
+ antialias=antialias,
)
else:
- out[i] = input[i:i + 1, :, y1[i]:y2[i], x1[i]:x2[i]] # type:ignore
+ out[i] = input[i : i + 1, :, y1[i] : y2[i], x1[i] : x2[i]] # type:ignore
return out
diff --git a/kornia/geometry/transform/crop3d.py b/kornia/geometry/transform/crop3d.py
index 3f499768e..32e1b02c2 100644
--- a/kornia/geometry/transform/crop3d.py
+++ b/kornia/geometry/transform/crop3d.py
@@ -6,12 +6,7 @@ from kornia.geometry.bbox import infer_bbox_shape3d, validate_bbox3d
from .imgwarp import get_perspective_transform3d, warp_affine3d
-__all__ = [
- "crop_and_resize3d",
- "crop_by_boxes3d",
- "crop_by_transform_mat3d",
- "center_crop3d",
-]
+__all__ = ["crop_and_resize3d", "crop_by_boxes3d", "crop_by_transform_mat3d", "center_crop3d"]
def crop_and_resize3d(
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index e1ca69278..f9de71a4d 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -17,7 +17,7 @@ def elastic_transform2d(
alpha: Tuple[float, float] = (1.0, 1.0),
align_corners: bool = False,
mode: str = 'bilinear',
- padding_mode: str = 'zeros'
+ padding_mode: str = 'zeros',
) -> torch.Tensor:
r"""Apply elastic transform of images as described in :cite:`Simard2003BestPF`.
@@ -91,7 +91,8 @@ def elastic_transform2d(
# Warp image based on displacement matrix
_, _, h, w = image.shape
grid = create_meshgrid(h, w, device=image.device).to(image.dtype)
- warped = F.grid_sample(image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode,
- padding_mode=padding_mode)
+ warped = F.grid_sample(
+ image, (grid + disp).clamp(-1, 1), align_corners=align_corners, mode=mode, padding_mode=padding_mode
+ )
return warped
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index 2804644bb..69657ea19 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -1,14 +1,7 @@
import torch
import torch.nn as nn
-__all__ = [
- "Vflip",
- "Hflip",
- "Rot180",
- "rot180",
- "hflip",
- "vflip",
-]
+__all__ = ["Vflip", "Hflip", "Rot180", "rot180", "hflip", "vflip"]
class Vflip(nn.Module):
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 50e070140..02864102f 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -8,9 +8,7 @@ from kornia.utils import create_meshgrid
from .imgwarp import homography_warp, warp_grid
-__all__ = [
- "HomographyWarper",
-]
+__all__ = ["HomographyWarper"]
class HomographyWarper(nn.Module):
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index c1628ea45..311e4aeec 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -10,11 +10,7 @@ from kornia.geometry.conversions import angle_to_rotation_matrix, convert_affine
from .homography_warper import HomographyWarper
from .pyramid import build_pyramid
-__all__ = [
- "ImageRegistrator",
- "Homography",
- "Similarity"
-]
+__all__ = ["ImageRegistrator", "Homography", "Similarity"]
class Homography(nn.Module):
@@ -61,10 +57,7 @@ class Similarity(nn.Module):
shift: if True, the shift is optimizable, else constant one.
"""
- def __init__(self,
- rotation: bool = True,
- scale: bool = True,
- shift: bool = True) -> None:
+ def __init__(self, rotation: bool = True, scale: bool = True, shift: bool = True) -> None:
super().__init__()
if rotation:
self.rot = nn.Parameter(torch.zeros(1))
@@ -96,8 +89,7 @@ class Similarity(nn.Module):
Returns:
Similarity with shape :math:`(1, 3, 3)`"""
rot = self.scale * angle_to_rotation_matrix(self.rot)
- out = convert_affinematrix_to_homography(torch.cat([rot, self.shift],
- dim=2))
+ out = convert_affinematrix_to_homography(torch.cat([rot, self.shift], dim=2))
return out
def forward_inverse(self) -> torch.Tensor:
@@ -128,22 +120,20 @@ class ImageRegistrator(nn.Module):
>>> registrator = ImageRegistrator('similarity')
>>> homo = registrator.register(img_src, img_dst)
"""
- known_models = ['homography',
- 'similarity',
- 'translation',
- 'scale',
- 'rotation']
+ known_models = ['homography', 'similarity', 'translation', 'scale', 'rotation']
# TODO: resolve better type, potentially using factory.
- def __init__(self,
- model_type='homography',
- optimizer=optim.Adam,
- loss_fn: Callable = F.l1_loss,
- pyramid_levels: int = 5,
- lr: float = 1e-3,
- num_iterations: int = 100,
- tolerance: float = 1e-4,
- warper=None) -> None:
+ def __init__(
+ self,
+ model_type='homography',
+ optimizer=optim.Adam,
+ loss_fn: Callable = F.l1_loss,
+ pyramid_levels: int = 5,
+ lr: float = 1e-3,
+ num_iterations: int = 100,
+ tolerance: float = 1e-4,
+ warper=None,
+ ) -> None:
super().__init__()
# We provide pre-defined combinations or allow user to supply model
# together with warper
@@ -177,15 +167,16 @@ class ImageRegistrator(nn.Module):
self.num_iterations = num_iterations
self.tolerance = tolerance
- def get_single_level_loss(self,
- img_src: torch.Tensor,
- img_dst: torch.Tensor,
- transform_model: torch.Tensor) -> torch.Tensor:
+ def get_single_level_loss(
+ self, img_src: torch.Tensor, img_dst: torch.Tensor, transform_model: torch.Tensor
+ ) -> torch.Tensor:
"""Warp img_src into img_dst with transform_model and returns loss."""
# ToDo: Make possible registration of images of different shape
if img_src.shape != img_dst.shape:
- raise ValueError(f"Cannot register images of different shapes\
- {img_src.shape} {img_dst.shape:} ")
+ raise ValueError(
+ f"Cannot register images of different shapes\
+ {img_src.shape} {img_dst.shape:} "
+ )
_height, _width = img_dst.shape[-2:]
warper = self.warper(_height, _width)
img_src_to_dst = warper(img_src, transform_model)
@@ -199,12 +190,13 @@ class ImageRegistrator(nn.Module):
"""Calls model reset function."""
self.model.reset_model()
- def register(self,
- src_img: torch.Tensor,
- dst_img: torch.Tensor,
- verbose: bool = False,
- output_intermediate_models: bool = False) -> \
- Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
+ def register(
+ self,
+ src_img: torch.Tensor,
+ dst_img: torch.Tensor,
+ verbose: bool = False,
+ output_intermediate_models: bool = False,
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
r"""Estimate the tranformation' which warps src_img into dst_img by gradient descent.
The shape of the tensors is not checked, because it may depend on the model, e.g. volume registration
@@ -235,12 +227,8 @@ class ImageRegistrator(nn.Module):
for i in range(self.num_iterations):
# compute gradient and update optimizer parameters
opt.zero_grad()
- loss = self.get_single_level_loss(img_src_level,
- img_dst_level,
- self.model())
- loss += self.get_single_level_loss(img_dst_level,
- img_src_level,
- self.model.forward_inverse())
+ loss = self.get_single_level_loss(img_src_level, img_dst_level, self.model())
+ loss += self.get_single_level_loss(img_dst_level, img_src_level, self.model.forward_inverse())
current_loss = loss.item()
if abs(current_loss - prev_loss) < self.tolerance:
break
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index f2d8ce578..39b135409 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -283,6 +283,7 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
# def __init__(self) -> None:
# super().__init__()
+
def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
r"""Calculate a perspective transform from four pairs of the corresponding points.
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 3d250b686..7adcc611b 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -7,14 +7,7 @@ import torch.nn.functional as F
from kornia.filters import filter2d, gaussian_blur2d
-__all__ = [
- "PyrDown",
- "PyrUp",
- "ScalePyramid",
- "pyrdown",
- "pyrup",
- "build_pyramid"
-]
+__all__ = ["PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyramid"]
def _get_pyramid_gaussian_kernel() -> torch.Tensor:
@@ -183,7 +176,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
@@ -202,7 +195,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.
@@ -234,8 +227,9 @@ class ScalePyramid(nn.Module):
return pyr, sigmas, pixel_dists
-def pyrdown(input: torch.Tensor, border_type: str = 'reflect',
- align_corners: bool = False, factor: float = 2.0) -> torch.Tensor:
+def pyrdown(
+ input: torch.Tensor, border_type: str = 'reflect', align_corners: bool = False, factor: float = 2.0
+) -> torch.Tensor:
r"""Blur a tensor and downsamples it.
.. image:: _static/img/pyrdown.png
@@ -270,7 +264,7 @@ def pyrdown(input: torch.Tensor, border_type: str = 'reflect',
x_blur,
size=(int(float(height) / factor), int(float(width) // factor)),
mode='bilinear',
- align_corners=align_corners
+ align_corners=align_corners,
)
return out
diff --git a/kornia/grad_estimator/ste.py b/kornia/grad_estimator/ste.py
index baaa5a1d1..29c50fe8f 100644
--- a/kornia/grad_estimator/ste.py
+++ b/kornia/grad_estimator/ste.py
@@ -4,10 +4,7 @@ import torch.nn as nn
from torch import Tensor
from torch.autograd import Function
-__all__ = [
- "STEFunction",
- "StraightThroughEstimator"
-]
+__all__ = ["STEFunction", "StraightThroughEstimator"]
class STEFunction(Function):
@@ -40,8 +37,7 @@ class STEFunction(Function):
@staticmethod
def forward( # type:ignore
- ctx, input: Tensor, output: Tensor,
- grad_fn: Optional[Callable] = None
+ ctx, input: Tensor, output: Tensor, grad_fn: Optional[Callable] = None
) -> Tensor:
ctx.in_shape = input.shape
ctx.out_shape = output.shape
@@ -55,7 +51,7 @@ class STEFunction(Function):
return (
ctx.grad_fn(grad_output.sum_to_size(ctx.in_shape)),
ctx.grad_fn(grad_output.sum_to_size(ctx.out_shape)),
- None
+ None,
)
# https://pytorch.org/docs/1.10.0/onnx.html#torch-autograd-functions
@@ -121,6 +117,7 @@ class StraightThroughEstimator(nn.Module):
out = self.target_fn(input)
if not isinstance(out, Tensor):
raise NotImplementedError(
- "Only Tensor is supported at the moment. Feel free to contribute to https://github.com/kornia/kornia.")
+ "Only Tensor is supported at the moment. Feel free to contribute to https://github.com/kornia/kornia."
+ )
output = STEFunction.apply(input, out, self.grad_fn)
return output
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index a4dd344d6..1faac575f 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -209,9 +209,9 @@ def binary_focal_loss_with_logits(
probs_pos = torch.sigmoid(input)
probs_neg = torch.sigmoid(-input)
- loss_tmp = -alpha * torch.pow(probs_neg, gamma) * target * F.logsigmoid(input) - (
- 1 - alpha
- ) * torch.pow(probs_pos, gamma) * (1.0 - target) * F.logsigmoid(-input)
+ loss_tmp = -alpha * torch.pow(probs_neg, gamma) * target * F.logsigmoid(input) - (1 - alpha) * torch.pow(
+ probs_pos, gamma
+ ) * (1.0 - target) * F.logsigmoid(-input)
if reduction == 'none':
loss = loss_tmp
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index b0c844fd3..03756f803 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -37,9 +37,7 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):
"""Get kernel for image morphology convolution."""
raise NotImplementedError
- def perform_erosion(
- self, pred: torch.Tensor, target: torch.Tensor
- ) -> torch.Tensor:
+ def perform_erosion(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
bound = (pred - target) ** 2
kernel = torch.as_tensor(self.kernel, device=pred.device, dtype=pred.dtype)
@@ -58,7 +56,7 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):
# image-wise differences for 2D images
erosion_max = self.max_pool(erosion)
- erosion_min = - self.max_pool(- erosion)
+ erosion_min = -self.max_pool(-erosion)
# No normalization needed if `max - min = 0`
_to_norm = (erosion_max - erosion_min) != 0
to_norm = _to_norm.squeeze()
@@ -96,17 +94,19 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):
if pred.size(1) < target.max().item():
raise ValueError("Invalid target value.")
- out = torch.stack([
- self.perform_erosion(
- pred[:, i:i + 1],
- torch.where(
- target == i,
- torch.tensor(1, device=target.device, dtype=target.dtype),
- torch.tensor(0, device=target.device, dtype=target.dtype)
+ out = torch.stack(
+ [
+ self.perform_erosion(
+ pred[:, i : i + 1],
+ torch.where(
+ target == i,
+ torch.tensor(1, device=target.device, dtype=target.dtype),
+ torch.tensor(0, device=target.device, dtype=target.dtype),
+ ),
)
- )
- for i in range(pred.size(1))
- ])
+ for i in range(pred.size(1))
+ ]
+ )
if self.reduction == 'mean':
out = out.mean()
@@ -182,8 +182,7 @@ class HausdorffERLoss(_HausdorffERLossBase):
if not (target.max() < pred.size(1) and target.min() >= 0 and target.dtype == torch.long):
raise ValueError(
- f"Expect long type target value in range (0, {pred.size(1)})."
- f"({target.min()}, {target.max()})"
+ f"Expect long type target value in range (0, {pred.size(1)})." f"({target.min()}, {target.max()})"
)
return super().forward(pred, target)
diff --git a/kornia/losses/lovasz_hinge.py b/kornia/losses/lovasz_hinge.py
index dc5f76878..52598dd9b 100644
--- a/kornia/losses/lovasz_hinge.py
+++ b/kornia/losses/lovasz_hinge.py
@@ -72,16 +72,16 @@ def lovasz_hinge_loss(pred: Tensor, target: Tensor) -> Tensor:
B, N = pred_flatten.shape
# compute actual loss
- signs = 2. * target_flatten - 1.
- errors = 1. - pred_flatten * signs
+ signs = 2.0 * target_flatten - 1.0
+ errors = 1.0 - pred_flatten * signs
errors_sorted, permutation = errors.sort(dim=1, descending=True)
batch_index: Tensor = torch.arange(B, device=pred.device).reshape(-1, 1).repeat(1, N).reshape(-1)
target_sorted: Tensor = target_flatten[batch_index, permutation.view(-1)]
target_sorted = target_sorted.view(B, N)
target_sorted_sum: Tensor = target_sorted.sum(1, keepdim=True)
intersection: Tensor = target_sorted_sum - target_sorted.cumsum(1)
- union: Tensor = target_sorted_sum + (1. - target_sorted).cumsum(1)
- gradient: Tensor = 1. - intersection / union
+ union: Tensor = target_sorted_sum + (1.0 - target_sorted).cumsum(1)
+ gradient: Tensor = 1.0 - intersection / union
if N > 1:
gradient[..., 1:] = gradient[..., 1:] - gradient[..., :-1]
loss: Tensor = (errors_sorted.relu() * gradient).sum(1).mean()
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index 5a1b5ed85..88ef91c07 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -80,7 +80,7 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor) -> Tensor:
losses: List[Tensor] = []
batch_index: Tensor = torch.arange(B, device=pred.device).reshape(-1, 1).repeat(1, N).reshape(-1)
for c in range(C):
- foreground: Tensor = 1. * (target_flatten == c)
+ foreground: Tensor = 1.0 * (target_flatten == c)
class_pred: Tensor = pred_soft[:, c]
errors = (class_pred - foreground).abs()
errors_sorted, permutation = torch.sort(errors, dim=1, descending=True)
@@ -88,8 +88,8 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor) -> Tensor:
target_sorted = target_sorted.view(B, N)
target_sorted_sum: Tensor = target_sorted.sum(1, keepdim=True)
intersection: Tensor = target_sorted_sum - target_sorted.cumsum(1)
- union: Tensor = target_sorted_sum + (1. - target_sorted).cumsum(1)
- gradient: Tensor = 1. - intersection / union
+ union: Tensor = target_sorted_sum + (1.0 - target_sorted).cumsum(1)
+ gradient: Tensor = 1.0 - intersection / union
if N > 1:
gradient[..., 1:] = gradient[..., 1:] - gradient[..., :-1]
loss: Tensor = (errors_sorted.relu() * gradient).sum(1).mean()
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index f44e8963b..b43e9e47a 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -96,7 +96,7 @@ class MS_SSIMLoss(nn.Module):
"""
coords = torch.arange(size, device=device, dtype=dtype)
coords -= size // 2
- g = torch.exp(-(coords ** 2) / (2 * sigma ** 2))
+ g = torch.exp(-(coords**2) / (2 * sigma**2))
g /= g.sum()
return g.reshape(-1)
@@ -160,9 +160,7 @@ class MS_SSIMLoss(nn.Module):
loss_l1 = F.l1_loss(img1, img2, reduction='none')
# Compute average l1 loss in 3 channels
- gaussian_l1 = F.conv2d(loss_l1, g_masks[-CH:], groups=CH, padding=self.pad).mean(
- 1
- )
+ gaussian_l1 = F.conv2d(loss_l1, g_masks[-CH:], groups=CH, padding=self.pad).mean(1)
# Compute MS-SSIM + L1 loss
loss = self.alpha * loss_ms_ssim + (1 - self.alpha) * gaussian_l1 / self.DR
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index b06a88ed2..62c346aee 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -22,4 +22,4 @@ def accuracy(input: torch.Tensor, target: torch.Tensor, topk=(1,)) -> List[torch
_, pred = input.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.reshape(1, -1).expand_as(pred))
- return [correct[:min(k, maxk)].reshape(-1).float().sum(0) * 100. / batch_size for k in topk]
+ return [correct[: min(k, maxk)].reshape(-1).float().sum(0) * 100.0 / batch_size for k in topk]
diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.py
index 54fb98858..b0d11d422 100644
--- a/kornia/metrics/average_meter.py
+++ b/kornia/metrics/average_meter.py
@@ -13,6 +13,7 @@ class AverageMeter:
>>> stats.avg
tensor(0.9900)
"""
+
def __init__(self) -> None:
self.reset()
diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.py
index 0e3aa01ac..9f7ac29eb 100644
--- a/kornia/metrics/confusion_matrix.py
+++ b/kornia/metrics/confusion_matrix.py
@@ -59,7 +59,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/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index 70f6f8256..7f31144a1 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -6,8 +6,13 @@ from .mean_iou import mean_iou_bbox
def mean_average_precision(
- pred_boxes: List[torch.Tensor], pred_labels: List[torch.Tensor], pred_scores: List[torch.Tensor],
- gt_boxes: List[torch.Tensor], gt_labels: List[torch.Tensor], n_classes: int, threshold: float = 0.5
+ pred_boxes: List[torch.Tensor],
+ pred_labels: List[torch.Tensor],
+ pred_scores: List[torch.Tensor],
+ gt_boxes: List[torch.Tensor],
+ gt_labels: List[torch.Tensor],
+ n_classes: int,
+ threshold: float = 0.5,
) -> Tuple[torch.Tensor, dict]:
"""Calculate the Mean Average Precision (mAP) of detected objects.
@@ -62,7 +67,8 @@ def mean_average_precision(
# Calculate APs for each class (except background)
average_precisions = torch.zeros(
- (n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype) # (n_classes - 1)
+ (n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype
+ ) # (n_classes - 1)
for c in range(1, n_classes):
# Extract only objects with this class
gt_class_images = _gt_images[_gt_labels == c] # (n_class_objects)
@@ -71,7 +77,8 @@ def mean_average_precision(
# Keep track of which true objects with this class have already been 'detected'
# (n_class_objects)
gt_class_boxes_detected = torch.zeros(
- (gt_class_images.size(0)), dtype=torch.uint8, device=gt_class_images.device)
+ (gt_class_images.size(0)), dtype=torch.uint8, device=gt_class_images.device
+ )
# Extract only detections with this class
pred_class_images = _pred_images[_pred_labels == c] # (n_class_detections)
@@ -88,9 +95,11 @@ def mean_average_precision(
# In the order of decreasing scores, check if true or false positive
gt_positives = torch.zeros(
- (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device) # (n_class_detections)
+ (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
+ ) # (n_class_detections)
false_positives = torch.zeros(
- (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device) # (n_class_detections)
+ (n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
+ ) # (n_class_detections)
for d in range(n_class_detections):
this_detection_box = pred_class_boxes[d].unsqueeze(0) # (1, 4)
this_image = pred_class_images[d] # (), scalar
@@ -130,19 +139,19 @@ def mean_average_precision(
cumul_gt_positives = torch.cumsum(gt_positives, dim=0) # (n_class_detections)
cumul_false_positives = torch.cumsum(false_positives, dim=0) # (n_class_detections)
cumul_precision = cumul_gt_positives / (
- cumul_gt_positives + cumul_false_positives + 1e-10) # (n_class_detections)
+ cumul_gt_positives + cumul_false_positives + 1e-10
+ ) # (n_class_detections)
cumul_recall = cumul_gt_positives / _gt_boxes.size(0) # (n_class_detections)
# Find the mean of the maximum of the precisions corresponding to recalls above the threshold 't'
- recall_thresholds = torch.arange(start=0, end=1.1, step=.1).tolist() # (11)
- precisions = torch.zeros(
- (len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
+ recall_thresholds = torch.arange(start=0, end=1.1, step=0.1).tolist() # (11)
+ precisions = torch.zeros((len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
for i, t in enumerate(recall_thresholds):
recalls_above_t = cumul_recall >= t
if recalls_above_t.any():
precisions[i] = cumul_precision[recalls_above_t].max()
else:
- precisions[i] = 0.
+ precisions[i] = 0.0
average_precisions[c - 1] = precisions.mean() # c is in [1, n_classes - 1]
# Calculate Mean Average Precision (mAP)
diff --git a/kornia/metrics/psnr.py b/kornia/metrics/psnr.py
index 86f319dc4..19b0d3382 100644
--- a/kornia/metrics/psnr.py
+++ b/kornia/metrics/psnr.py
@@ -46,4 +46,4 @@ 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.0 * torch.log10(max_val ** 2 / mse(input, target, reduction='mean'))
+ return 10.0 * torch.log10(max_val**2 / mse(input, target, reduction='mean'))
diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.py
index 82187a640..9db60bea1 100644
--- a/kornia/metrics/ssim.py
+++ b/kornia/metrics/ssim.py
@@ -94,12 +94,12 @@ def ssim(
elif padding == 'same':
pass
- mu1_sq = mu1 ** 2
- mu2_sq = mu2 ** 2
+ mu1_sq = mu1**2
+ mu2_sq = mu2**2
mu1_mu2 = mu1 * mu2
- mu_img1_sq = filter2d(img1 ** 2, kernel)
- mu_img2_sq = filter2d(img2 ** 2, kernel)
+ mu_img1_sq = filter2d(img1**2, kernel)
+ mu_img2_sq = filter2d(img2**2, kernel)
mu_img1_img2 = filter2d(img1 * img2, kernel)
if padding == 'valid':
diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.py
index 2db61c93c..601127972 100644
--- a/kornia/morphology/morphology.py
+++ b/kornia/morphology/morphology.py
@@ -3,15 +3,7 @@ from typing import List, Optional
import torch
import torch.nn.functional as F
-__all__ = [
- "dilation",
- "erosion",
- "opening",
- "closing",
- "gradient",
- "top_hat",
- "bottom_hat"
-]
+__all__ = ["dilation", "erosion", "opening", "closing", "gradient", "top_hat", "bottom_hat"]
def _neight2channels_like_kernel(kernel: torch.Tensor) -> torch.Tensor:
@@ -199,10 +191,9 @@ def erosion(
B, C, H, W = tensor.size()
Hpad, Wpad = output.shape[-2:]
reshape_kernel = _neight2channels_like_kernel(kernel)
- output, _ = F.conv2d(output.view(B * C, 1, Hpad, Wpad),
- reshape_kernel,
- padding=0,
- bias=-neighborhood.view(-1)).min(dim=1)
+ output, _ = F.conv2d(
+ output.view(B * C, 1, Hpad, Wpad), reshape_kernel, padding=0, bias=-neighborhood.view(-1)
+ ).min(dim=1)
output = output.view(B, C, H, W)
else:
raise NotImplementedError(f"engine {engine} is unknown, use 'convolution' or 'unfold'")
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 97950d18a..c99967cbd 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -210,6 +210,10 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None):
raise Exception(f"{condition} not true.\n{msg}")
+def KORNIA_UNWRAP(maybe_obj, typ):
+ return cast(typ, maybe_obj)
+
+
def KORNIA_CHECK_IS_TENSOR(x, msg: Optional[str] = None):
if not isinstance(x, Tensor):
raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}")
diff --git a/kornia/tracking/__init__.py b/kornia/tracking/__init__.py
index 3d2a98bba..144f0335b 100644
--- a/kornia/tracking/__init__.py
+++ b/kornia/tracking/__init__.py
@@ -1,5 +1,3 @@
from .planar_tracker import HomographyTracker
-__all__ = [
- "HomographyTracker",
-]
+__all__ = ["HomographyTracker"]
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
index 33e82ff66..610865d25 100644
--- a/kornia/tracking/planar_tracker.py
+++ b/kornia/tracking/planar_tracker.py
@@ -22,17 +22,20 @@ class HomographyTracker(nn.Module):
ransac: homography estimation module. Default: :class:`~kornia.geometry.RANSAC`.
minimum_inliers_num: threshold for number inliers for matching to be successful.
"""
- def __init__(self,
- initial_matcher: Optional[LocalFeature] = None,
- fast_matcher: Optional[nn.Module] = None,
- ransac: Optional[nn.Module] = None,
- minimum_inliers_num: int = 30) -> None:
+
+ def __init__(
+ self,
+ initial_matcher: Optional[LocalFeature] = None,
+ fast_matcher: Optional[nn.Module] = None,
+ ransac: Optional[nn.Module] = None,
+ minimum_inliers_num: int = 30,
+ ) -> None:
super().__init__()
self.initial_matcher = initial_matcher or (
- LocalFeatureMatcher(GFTTAffNetHardNet(3000), DescriptorMatcher('smnn', 0.95)))
+ LocalFeatureMatcher(GFTTAffNetHardNet(3000), DescriptorMatcher('smnn', 0.95))
+ )
self.fast_matcher = fast_matcher or LoFTR('outdoor')
- self.ransac = ransac or RANSAC(
- 'homography', inl_th=5.0, batch_size=4096, max_iter=10, max_lo_iters=10)
+ self.ransac = ransac or RANSAC('homography', inl_th=5.0, batch_size=4096, max_iter=10, max_lo_iters=10)
self.minimum_inliers_num = minimum_inliers_num
# placeholders
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 87985f60d..203a95433 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -43,7 +43,8 @@ def _deprecated(func: Callable = None, replace_with: Optional[str] = None):
warnings.warn(f"`{name}` is deprecated in favor of `{replace_with}`.", category=DeprecationWarning)
else:
warnings.warn(
- f"`{name}` is deprecated and will be removed in the future versions.", category=DeprecationWarning)
+ f"`{name}` is deprecated and will be removed in the future versions.", category=DeprecationWarning
+ )
return func(*args, **kwargs)
return wrapper
@@ -179,6 +180,7 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
else:
dtype = dtype_original
from torch.linalg import inv_ex # type: ignore # (not available in 1.8.1)
+
inverse, info = inv_ex(A.to(dtype))
mask = info == 0
return inverse.to(dtype_original), mask
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index 3bbef51fc..070d76415 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -58,6 +58,7 @@ class Trainer:
Learn how to use the API in our documentation
`here <https://kornia.readthedocs.io/en/latest/get-started/training.html>`_.
"""
+
def __init__(
self,
model: nn.Module,
@@ -71,8 +72,7 @@ class Trainer:
) -> None:
# setup the accelerator
if Accelerator is None:
- raise ModuleNotFoundError(
- "accelerate library is not installed: pip install kornia[x]")
+ raise ModuleNotFoundError("accelerate library is not installed: pip install kornia[x]")
self.accelerator = Accelerator()
# setup the data related objects
@@ -131,7 +131,7 @@ class Trainer:
f"Loss: {losses.val:.3f} {losses.avg:.3f}"
)
- def fit(self,) -> None:
+ def fit(self) -> None:
# execute the main loop
# NOTE: Do not change and keep this structure clear for readability.
for epoch in range(self.num_epochs):
@@ -180,9 +180,7 @@ class Trainer:
stats.update_from_dict(self.compute_metrics(out, sample['target']), batch_size)
if sample_id % 10 == 0:
- self._logger.info(
- f"Test: {sample_id}/{len(self.valid_dataloader)} {stats}"
- )
+ self._logger.info(f"Test: {sample_id}/{len(self.valid_dataloader)} {stats}")
return stats.as_dict()
diff --git a/kornia/x/trainers.py b/kornia/x/trainers.py
index 88986e8d3..8d576e303 100644
--- a/kornia/x/trainers.py
+++ b/kornia/x/trainers.py
@@ -59,6 +59,7 @@ class ObjectDetectionTrainer(Trainer):
Learn how to use this class in the following
`example <https://github.com/kornia/kornia/blob/master/examples/train/object_detection/>`__.
"""
+
def __init__(
self,
model: nn.Module,
@@ -74,9 +75,7 @@ class ObjectDetectionTrainer(Trainer):
) -> None:
if callbacks is None:
callbacks = {}
- super().__init__(
- model, train_dataloader, valid_dataloader, criterion, optimizer, scheduler, config, callbacks
- )
+ super().__init__(model, train_dataloader, valid_dataloader, criterion, optimizer, scheduler, config, callbacks)
# TODO: auto-detect if the model is from TorchVision
self.loss_computed_by_model = loss_computed_by_model
self.num_classes = num_classes
@@ -98,8 +97,13 @@ class ObjectDetectionTrainer(Trainer):
def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
if (
- isinstance(args[0], dict) and "boxes" in args[0] and "labels" in args[0] and "scores" in args[0]
- and isinstance(args[1], dict) and "boxes" in args[1] and "labels" in args[1]
+ isinstance(args[0], dict)
+ and "boxes" in args[0]
+ and "labels" in args[0]
+ and "scores" in args[0]
+ and isinstance(args[1], dict)
+ and "boxes" in args[1]
+ and "labels" in args[1]
):
mAP, _ = mean_average_precision(
[a['boxes'] for a in args[0]],
@@ -108,7 +112,7 @@ class ObjectDetectionTrainer(Trainer):
[a['boxes'] for a in args[1]],
[a['labels'] for a in args[1]],
n_classes=self.num_classes,
- threshold=0.000001
+ threshold=0.000001,
)
return {'mAP': mAP.item()}
return super().compute_metrics(*args)
diff --git a/kornia/x/utils.py b/kornia/x/utils.py
index e54003eb6..0b9d77d7b 100644
--- a/kornia/x/utils.py
+++ b/kornia/x/utils.py
@@ -53,6 +53,7 @@ class Lambda(nn.Module):
>>> fcn(torch.rand(1, 4, 64, 32)).shape
torch.Size([1, 4, 32, 16])
"""
+
def __init__(self, fcn):
super().__init__()
self.fcn = fcn
@@ -63,11 +64,12 @@ class Lambda(nn.Module):
class StatsTracker:
"""Stats tracker for computing metrics on the fly."""
+
def __init__(self) -> None:
self._stats: Dict[str, AverageMeter] = {}
@property
- def stats(self,):
+ def stats(self):
return self._stats
def update(self, key: str, val: float, batch_size: int) -> None:
diff --git a/setup.py b/setup.py
index 074f51b7c..9776a261f 100644
--- a/setup.py
+++ b/setup.py
@@ -25,9 +25,7 @@ VERSION = find_version("kornia/_version.py")
# NOTE: kornia MUST only require PyTorch
-requirements = [
- 'torch>=1.8.1', 'packaging',
-]
+requirements = ['torch>=1.8.1', 'packaging']
# open readme file and set long description
with open("README.md", encoding="utf-8") as fh:
@@ -39,10 +37,7 @@ def load_requirements(filename: str):
return [x.strip() for x in f.readlines() if "-r" != x[0:2]]
-requirements_extras = {
- "x": load_requirements("requirements/x.txt"),
- "dev": load_requirements("requirements/dev.txt")
-}
+requirements_extras = {"x": load_requirements("requirements/x.txt"), "dev": load_requirements("requirements/dev.txt")}
requirements_extras["all"] = requirements_extras["x"] + requirements_extras["dev"]
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 6a17292fb..c82112b16 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -3057,7 +3057,6 @@ class TestPlanckianJitter:
class TestRandomRGBShift:
-
def test_smoke(self, device, dtype):
img = torch.rand(1, 3, 4, 5, device=device, dtype=dtype)
aug = RandomRGBShift(p=1.0).to(device)
diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.py
index fb61c8c58..920b66a60 100644
--- a/test/augmentation/test_augmentation_3d.py
+++ b/test/augmentation/test_augmentation_3d.py
@@ -104,9 +104,7 @@ class TestRandomHorizontalFlip3D:
def test_sequential(self, device):
- f = AugmentationSequential(
- RandomHorizontalFlip3D(p=1.0), RandomHorizontalFlip3D(p=1.0)
- )
+ f = AugmentationSequential(RandomHorizontalFlip3D(p=1.0), RandomHorizontalFlip3D(p=1.0))
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)
@@ -225,9 +223,7 @@ class TestRandomVerticalFlip3D:
def test_sequential(self, device):
- f = AugmentationSequential(
- RandomVerticalFlip3D(p=1.0), RandomVerticalFlip3D(p=1.0)
- )
+ f = AugmentationSequential(RandomVerticalFlip3D(p=1.0), RandomVerticalFlip3D(p=1.0))
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)
@@ -356,9 +352,7 @@ class TestRandomDepthicalFlip3D:
def test_sequential(self, device):
- f = AugmentationSequential(
- RandomDepthicalFlip3D(p=1.0), RandomDepthicalFlip3D(p=1.0)
- )
+ f = AugmentationSequential(RandomDepthicalFlip3D(p=1.0), RandomDepthicalFlip3D(p=1.0))
input = torch.tensor(
[
@@ -571,10 +565,7 @@ class TestRandomRotation3D:
torch.manual_seed(24) # for random reproductibility
- f = AugmentationSequential(
- RandomRotation3D(torch.tensor([-45.0, 90])),
- RandomRotation3D(10.4),
- )
+ f = AugmentationSequential(RandomRotation3D(torch.tensor([-45.0, 90])), RandomRotation3D(10.4))
input = torch.tensor(
[
[[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]],
@@ -719,8 +710,13 @@ class TestRandomCrop3D:
def test_same_on_batch(self, device, dtype):
f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.0, same_on_batch=True)
- input = torch.eye(
- 6, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 5, 1, 1)
+ input = (
+ torch.eye(6, device=device, dtype=dtype)
+ .unsqueeze(dim=0)
+ .unsqueeze(dim=0)
+ .unsqueeze(dim=0)
+ .repeat(2, 3, 5, 1, 1)
+ )
res = f(input)
assert (res[0] == res[1]).all()
@@ -818,7 +814,7 @@ class TestCenterCrop3D:
def test_transform(self, device, dtype):
inp = torch.rand(1, 2, 5, 4, 8, device=device, dtype=dtype)
- aug = CenterCrop3D(2,)
+ aug = CenterCrop3D(2)
out = aug(inp)
assert out.shape == (1, 2, 2, 2, 2)
assert aug.transform_matrix.shape == (1, 4, 4)
diff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.py
index 4d96881b1..2fc832e00 100644
--- a/test/augmentation/test_augmentation_mix.py
+++ b/test/augmentation/test_augmentation_mix.py
@@ -98,9 +98,7 @@ class TestRandomMixUp:
class TestRandomCutMix:
def test_smoke(self):
f = RandomCutMix()
- repr = (
- "RandomCutMix(cut_size=None, beta=None, num_mix=1, p=1.0, p_batch=1.0, same_on_batch=False)"
- )
+ repr = "RandomCutMix(cut_size=None, beta=None, num_mix=1, p=1.0, p_batch=1.0, same_on_batch=False)"
assert str(f) == repr
def test_random_mixup_p1(self, device, dtype):
diff --git a/test/augmentation/test_backward.py b/test/augmentation/test_backward.py
index a70dd0ea4..243c20108 100644
--- a/test/augmentation/test_backward.py
+++ b/test/augmentation/test_backward.py
@@ -21,8 +21,7 @@ class TestColorJiggleBackward:
@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("same_on_batch", [True, False])
- def test_param(self, brightness, contrast, saturation, hue,
- same_on_batch, device, dtype):
+ def test_param(self, brightness, contrast, saturation, hue, same_on_batch, device, dtype):
_brightness = (
brightness
@@ -78,8 +77,7 @@ class TestColorJitterBackward:
@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("same_on_batch", [True, False])
- def test_param(self, brightness, contrast, saturation, hue,
- same_on_batch, device, dtype):
+ def test_param(self, brightness, contrast, saturation, hue, same_on_batch, device, dtype):
_brightness = (
brightness
@@ -141,9 +139,7 @@ class TestRandomAffineBackward:
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
- def test_param(
- self, degrees, translate, scale, shear, resample, align_corners, same_on_batch, device, dtype
- ):
+ def test_param(self, degrees, translate, scale, shear, resample, align_corners, same_on_batch, device, dtype):
_degrees = (
degrees
@@ -256,12 +252,7 @@ class TestRandomRotationBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
- aug = RandomRotation(
- _degrees,
- resample,
- align_corners=align_corners,
- same_on_batch=same_on_batch,
- )
+ aug = RandomRotation(_degrees, resample, align_corners=align_corners, same_on_batch=same_on_batch)
output = aug(input)
@@ -302,11 +293,7 @@ class TestRandomPerspectiveBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomPerspective(
- _distortion_scale,
- resample=resample,
- same_on_batch=same_on_batch,
- align_corners=align_corners,
- p=1.0,
+ _distortion_scale, resample=resample, same_on_batch=same_on_batch, align_corners=align_corners, p=1.0
)
output = aug(input)
@@ -357,9 +344,7 @@ class TestRandomMotionBlurBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
- aug = RandomMotionBlur(
- (3, 3), _angle, _direction, border_type, resample, same_on_batch, p=1.0
- )
+ aug = RandomMotionBlur((3, 3), _angle, _direction, border_type, resample, same_on_batch, p=1.0)
output = aug(input)
@@ -442,12 +427,7 @@ class TestRandomResizedCropBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomResizedCrop(
- (8, 8),
- _scale,
- _ratio,
- resample=resample,
- same_on_batch=same_on_batch,
- align_corners=align_corners,
+ (8, 8), _scale, _ratio, resample=resample, same_on_batch=same_on_batch, align_corners=align_corners
)
output = aug(input)
diff --git a/test/augmentation/test_backward_3d.py b/test/augmentation/test_backward_3d.py
index 3d832bd18..5233dabe2 100644
--- a/test/augmentation/test_backward_3d.py
+++ b/test/augmentation/test_backward_3d.py
@@ -45,9 +45,7 @@ class TestRandomAffine3DBackward:
@pytest.mark.parametrize("resample", ['bilinear']) # TODO: Ignore nearest for now.
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False])
- def test_param(
- self, degrees, translate, scale, shear, resample, align_corners, same_on_batch, device, dtype
- ):
+ def test_param(self, degrees, translate, scale, shear, resample, align_corners, same_on_batch, device, dtype):
_degrees = (
degrees
@@ -169,13 +167,7 @@ class TestRandomRotation3DBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.0
- aug = RandomRotation3D(
- _degrees,
- resample,
- align_corners=align_corners,
- same_on_batch=same_on_batch,
- p=1.0,
- )
+ aug = RandomRotation3D(_degrees, resample, align_corners=align_corners, same_on_batch=same_on_batch, p=1.0)
output = aug(input)
@@ -216,11 +208,7 @@ class TestRandomPerspective3DBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.0
aug = RandomPerspective3D(
- _distortion_scale,
- resample=resample,
- same_on_batch=same_on_batch,
- align_corners=align_corners,
- p=1.0,
+ _distortion_scale, resample=resample, same_on_batch=same_on_batch, align_corners=align_corners, p=1.0
)
output = aug(input)
@@ -272,9 +260,7 @@ class TestRandomMotionBlur3DBackward:
torch.manual_seed(0)
input = torch.randint(255, (2, 3, 10, 10, 10), device=device, dtype=dtype) / 255.0
- aug = RandomMotionBlur3D(
- (3, 3), _angle, _direction, border_type, resample, same_on_batch, p=1.0
- )
+ aug = RandomMotionBlur3D((3, 3), _angle, _direction, border_type, resample, same_on_batch, p=1.0)
output = aug(input)
diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.py
index c49c765ec..0eadf0105 100644
--- a/test/augmentation/test_container.py
+++ b/test/augmentation/test_container.py
@@ -222,9 +222,7 @@ class TestAugmentationSequential:
def test_mixup(self, inp, random_apply, same_on_batch, device, dtype):
inp = torch.as_tensor(inp, device=device, dtype=dtype)
aug = K.AugmentationSequential(
- K.ImageSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
K.RandomMixUp(p=1.0),
@@ -265,9 +263,7 @@ class TestAugmentationSequential:
def test_3d_augmentations(self, device, dtype):
input = torch.randn(2, 2, 3, 5, 6, device=device, dtype=dtype)
aug_list = K.AugmentationSequential(
- K.RandomAffine3D(360., p=1.),
- K.RandomHorizontalFlip3D(p=1.),
- data_keys=["input"],
+ K.RandomAffine3D(360.0, p=1.0), K.RandomHorizontalFlip3D(p=1.0), data_keys=["input"]
)
out = aug_list(input)
assert out.shape == input.shape
@@ -316,7 +312,8 @@ class TestAugmentationSequential:
# specifying the crop locations allows us to compute by hand the expected outputs
crop_locations = torch.tensor(
[[1.0, 2.0], [1.0, 1.0], [2.0, 0.0]],
- device=_params[0].data['src'].device, dtype=_params[0].data['src'].dtype,
+ device=_params[0].data['src'].device,
+ dtype=_params[0].data['src'].dtype,
)
crops = crop_locations.expand(4, -1, -1).permute(1, 0, 2).clone()
crops[:, 1:3, 0] += crop_width - 1
@@ -350,14 +347,12 @@ class TestAugmentationSequential:
def test_random_erasing(self, device, dtype):
fill_value = 0.5
input = torch.randn(3, 3, 100, 100, device=device, dtype=dtype)
- aug = K.AugmentationSequential(
- K.RandomErasing(p=1., value=fill_value), data_keys=["input", "mask"],
- )
+ aug = K.AugmentationSequential(K.RandomErasing(p=1.0, value=fill_value), data_keys=["input", "mask"])
reproducibility_test((input, input), aug)
out = aug(input, input)
- assert torch.all(out[1][out[0] == fill_value] == 0.)
+ assert torch.all(out[1][out[0] == fill_value] == 0.0)
def test_random_crops(self, device, dtype):
torch.manual_seed(233)
@@ -368,9 +363,9 @@ class TestAugmentationSequential:
points = torch.tensor([[[0.0, 0.0], [1.0, 1.0]]], device=device, dtype=dtype).expand(3, -1, -1)
aug = K.AugmentationSequential(
K.RandomCrop((3, 3), padding=1, cropping_mode='resample', fill=0),
- K.RandomAffine((360., 360.), p=1.),
+ K.RandomAffine((360.0, 360.0), p=1.0),
data_keys=["input", "mask", "bbox_xyxy", "keypoints"],
- extra_args={}
+ extra_args={},
)
reproducibility_test((input, input, bbox, points), aug)
@@ -425,13 +420,12 @@ class TestAugmentationSequential:
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
)[:, None].float()
aug = K.AugmentationSequential(
- K.ImageSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.AugmentationSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0),
+ K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
- data_keys=["input", "mask", "bbox", "keypoints"]
+ K.RandomAffine(360, p=1.0),
+ data_keys=["input", "mask", "bbox", "keypoints"],
),
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
@@ -463,16 +457,12 @@ class TestAugmentationSequential:
crop_size = (200, 200)
aug = K.AugmentationSequential(
- K.ImageSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
- K.AugmentationSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
+ K.AugmentationSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.RandomAffine(360, p=1.0),
K.RandomCrop(crop_size, padding=1, cropping_mode='resample', fill=0),
data_keys=['input', 'mask', 'bbox', 'keypoints'],
- extra_args={}
+ extra_args={},
)
# NOTE: Mask data with nearest not passing reproducibility check under float64.
reproducibility_test((inp, mask, bbox, keypoints), aug)
@@ -509,17 +499,13 @@ class TestAugmentationSequential:
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
)[:, None].float()
aug = K.AugmentationSequential(
- K.ImageSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
- K.AugmentationSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
+ K.AugmentationSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
data_keys=["input", "mask", "bbox", "keypoints"],
random_apply=random_apply,
- extra_args={}
+ extra_args={},
)
out = aug(inp, mask, bbox, keypoints)
assert out[0].shape == inp.shape
@@ -557,12 +543,8 @@ class TestAugmentationSequential:
torch.tensor([[[155, 0], [900, 0], [900, 400], [155, 400]]], device=device, dtype=dtype), 1000, 500
)[:, None].float()
aug = K.AugmentationSequential(
- K.ImageSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
- K.AugmentationSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)
- ),
+ K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
+ K.AugmentationSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0), K.RandomAffine(360, p=1.0)),
K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
K.RandomAffine(360, p=1.0),
data_keys=["input", "mask", "bbox", "keypoints", "bbox", "BBOX_XYWH", "BBOX_XYWH"],
diff --git a/test/augmentation/test_dist_mapper.py b/test/augmentation/test_dist_mapper.py
index 050878bac..2cc972858 100644
--- a/test/augmentation/test_dist_mapper.py
+++ b/test/augmentation/test_dist_mapper.py
@@ -7,12 +7,9 @@ from kornia.augmentation.random_generator import DistributionWithMapper
class TestDistMapper:
-
- def test_mapper(self,):
+ def test_mapper(self):
_ = torch.manual_seed(0)
- dist = DistributionWithMapper(Normal(0., 1.,), map_fn=nn.Sigmoid())
+ dist = DistributionWithMapper(Normal(0.0, 1.0), map_fn=nn.Sigmoid())
out = dist.rsample((8,))
- exp = torch.tensor([
- 0.8236, 0.4272, 0.1017, 0.6384, 0.2527, 0.1980, 0.5995, 0.6980
- ])
+ exp = torch.tensor([0.8236, 0.4272, 0.1017, 0.6384, 0.2527, 0.1980, 0.5995, 0.6980])
assert_allclose(out, exp, rtol=1e-4, atol=1e-4)
diff --git a/test/augmentation/test_motionblur.py b/test/augmentation/test_motionblur.py
index 852c60022..20f32a4bc 100644
--- a/test/augmentation/test_motionblur.py
+++ b/test/augmentation/test_motionblur.py
@@ -24,13 +24,7 @@ class TestRandomMotionBlur:
@pytest.mark.parametrize("same_on_batch", [True, False])
@pytest.mark.parametrize("p", [0.0, 1.0])
def test_random_motion_blur(self, kernel_size, same_on_batch, p, device, dtype):
- f = RandomMotionBlur(
- kernel_size=kernel_size,
- angle=(10, 30),
- direction=0.5,
- same_on_batch=same_on_batch,
- p=p,
- )
+ f = RandomMotionBlur(kernel_size=kernel_size, angle=(10, 30), direction=0.5, same_on_batch=same_on_batch, p=p)
torch.manual_seed(0)
batch_size = 2
input = torch.randn(1, 3, 5, 6, device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
@@ -99,13 +93,7 @@ class TestRandomMotionBlur3D:
@pytest.mark.parametrize("same_on_batch", [True, False])
@pytest.mark.parametrize("p", [0.0, 1.0])
def test_random_motion_blur(self, same_on_batch, p, device, dtype):
- f = RandomMotionBlur3D(
- kernel_size=(3, 5),
- angle=(10, 30),
- direction=0.5,
- same_on_batch=same_on_batch,
- p=p,
- )
+ f = RandomMotionBlur3D(kernel_size=(3, 5), angle=(10, 30), direction=0.5, same_on_batch=same_on_batch, p=p)
batch_size = 2
input = torch.randn(1, 3, 5, 6, 7, device=device, dtype=dtype).repeat(batch_size, 1, 1, 1, 1)
diff --git a/test/augmentation/test_perspective_rand.py b/test/augmentation/test_perspective_rand.py
index 20076bbce..42a796efd 100644
--- a/test/augmentation/test_perspective_rand.py
+++ b/test/augmentation/test_perspective_rand.py
@@ -56,9 +56,7 @@ class TestRandomPerspective:
x_data = torch.rand(1, 2, 4, 5, dtype=dtype).to(device)
aug = kornia.augmentation.RandomPerspective(
- torch.tensor(0.5, device=device, dtype=dtype),
- p=0.5,
- sampling_method="area_preserving",
+ torch.tensor(0.5, device=device, dtype=dtype), p=0.5, sampling_method="area_preserving"
)
out_perspective = aug(x_data)
@@ -69,7 +67,7 @@ class TestRandomPerspective:
def test_no_transform_module(self, device, dtype):
x_data = torch.rand(1, 2, 8, 9, dtype=dtype).to(device)
- aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype),)
+ aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype))
out_perspective = aug(x_data)
assert out_perspective.shape == x_data.shape
assert aug.inverse(out_perspective).shape == x_data.shape
@@ -119,8 +117,7 @@ class TestRandomPerspective:
)
aug = kornia.augmentation.RandomPerspective(
- torch.tensor(0.5, device=device, dtype=dtype),
- p=0.99999999
+ torch.tensor(0.5, device=device, dtype=dtype), p=0.99999999
) # step one the random state
out_perspective = aug(x_data)
@@ -135,11 +132,11 @@ class TestRandomPerspective:
input = torch.rand(1, 2, 5, 7, dtype=dtype).to(device)
input = utils.tensor_to_gradcheck_var(input) # to var
# TODO: turned off with p=0
- assert gradcheck(kornia.augmentation.RandomPerspective(
- torch.tensor(0.5, device=device, dtype=dtype),
- p=0.0),
+ assert gradcheck(
+ kornia.augmentation.RandomPerspective(torch.tensor(0.5, device=device, dtype=dtype), p=0.0),
(input,),
- raise_exception=True)
+ raise_exception=True,
+ )
class TestRandomAffine:
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index 76ee3a82a..72f9e2213 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -81,18 +81,17 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
- self, brightness, contrast, saturation, hue,
- batch_size, same_on_batch, device, dtype
+ self, brightness, contrast, saturation, hue, batch_size, same_on_batch, device, dtype
):
ColorJiggleGenerator(
torch.as_tensor(
- brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
- torch.as_tensor(
- contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
- torch.as_tensor(
- saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ brightness if brightness is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
+ torch.as_tensor(contrast if contrast is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype),
torch.as_tensor(
- hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ saturation if saturation is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
+ torch.as_tensor(hue if hue is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype),
)(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
@@ -115,24 +114,19 @@ class TestColorJiggleGen(RandomGeneratorBaseTests):
(None, None, None, torch.tensor([0.0, 1.0, 2.0])),
],
)
- def test_invalid_param_combinations(
- self,
- brightness,
- contrast,
- saturation,
- hue,
- device,
- dtype
- ):
+ def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):
with pytest.raises(Exception):
ColorJiggleGenerator(
torch.as_tensor(
- brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ brightness if brightness is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
torch.as_tensor(
- contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ contrast if contrast is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
torch.as_tensor(
- saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
- torch.as_tensor(hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ saturation if saturation is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
+ torch.as_tensor(hue if hue is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype),
)(torch.Size([8]))
def test_random_gen(self, device, dtype):
@@ -264,18 +258,17 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
- self, brightness, contrast, saturation, hue,
- batch_size, same_on_batch, device, dtype
+ self, brightness, contrast, saturation, hue, batch_size, same_on_batch, device, dtype
):
ColorJitterGenerator(
torch.as_tensor(
- brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
- torch.as_tensor(
- contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
- torch.as_tensor(
- saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ brightness if brightness is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
+ torch.as_tensor(contrast if contrast is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype),
torch.as_tensor(
- hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ saturation if saturation is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
+ torch.as_tensor(hue if hue is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype),
)(torch.Size([batch_size]), same_on_batch)
@pytest.mark.parametrize(
@@ -297,24 +290,19 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
(None, None, None, torch.tensor([0.0, 1.0, 2.0])),
],
)
- def test_invalid_param_combinations(
- self,
- brightness,
- contrast,
- saturation,
- hue,
- device,
- dtype
- ):
+ def test_invalid_param_combinations(self, brightness, contrast, saturation, hue, device, dtype):
with pytest.raises(Exception):
ColorJitterGenerator(
torch.as_tensor(
- brightness if brightness is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ brightness if brightness is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
torch.as_tensor(
- contrast if contrast is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ contrast if contrast is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
torch.as_tensor(
- saturation if saturation is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
- torch.as_tensor(hue if hue is not None else torch.tensor([0., 0.]), device=device, dtype=dtype),
+ saturation if saturation is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype
+ ),
+ torch.as_tensor(hue if hue is not None else torch.tensor([0.0, 0.0]), device=device, dtype=dtype),
)(torch.Size([8]))
def test_random_gen(self, device, dtype):
@@ -397,7 +385,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
@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):
PerspectiveGenerator(distortion_scale.to(device=device, dtype=dtype))(
- torch.Size([batch_size, 1, height, width]), same_on_batch)
+ torch.Size([batch_size, 1, height, width]), same_on_batch
+ )
@pytest.mark.parametrize(
'height,width,distortion_scale',
@@ -412,14 +401,12 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, height, width, distortion_scale, device, dtype):
with pytest.raises(Exception):
- PerspectiveGenerator(distortion_scale.to(device=device, dtype=dtype))(
- torch.Size([8, 1, height, width]))
+ PerspectiveGenerator(distortion_scale.to(device=device, dtype=dtype))(torch.Size([8, 1, height, width]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(
- torch.Size([batch_size, 1, 200, 200]))
+ res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(torch.Size([batch_size, 1, 200, 200]))
expected = dict(
start_points=torch.tensor(
@@ -447,7 +434,8 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 2
res = PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype))(
- torch.Size([batch_size, 1, 200, 200]), same_on_batch=True)
+ torch.Size([batch_size, 1, 200, 200]), same_on_batch=True
+ )
expected = dict(
start_points=torch.tensor(
[[[0.0, 0.0], [199.0, 0.0], [199.0, 199.0], [0.0, 199.0]]], device=device, dtype=dtype
@@ -494,9 +482,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
def test_not_implemented_sampling_method(self, device, dtype):
batch_size = 2
with pytest.raises(NotImplementedError):
- PerspectiveGenerator(
- torch.tensor(0.5, device=device, dtype=dtype),
- sampling_method="non_existing_method")(
+ PerspectiveGenerator(torch.tensor(0.5, device=device, dtype=dtype), sampling_method="non_existing_method")(
torch.Size([batch_size, 1, 200, 200])
)
@@ -517,7 +503,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,
)(torch.Size([batch_size, 1, height, width]), same_on_batch)
@pytest.mark.parametrize(
@@ -542,7 +528,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,
)(torch.Size([8, 1, height, width]))
def test_random_gen(self, device, dtype):
@@ -555,7 +541,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,
)(torch.Size([2, 1, 200, 200]))
expected = dict(
translations=torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),
@@ -583,7 +569,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,
)(torch.Size([2, 1, 200, 200]), True)
expected = dict(
translations=torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),
@@ -620,15 +606,15 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
batch_size = 2
with pytest.raises(Exception):
- CropGenerator(
- size.to(device=device, dtype=dtype) if isinstance(size, Tensor) else size, resize_to
- )(torch.Size([batch_size, 1, *input_size]))
+ CropGenerator(size.to(device=device, dtype=dtype) if isinstance(size, Tensor) else size, resize_to)(
+ torch.Size([batch_size, 1, *input_size])
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- res = CropGenerator(
- torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200)
- )(torch.Size([2, 1, 100, 100]))
+ res = CropGenerator(torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200))(
+ torch.Size([2, 1, 100, 100])
+ )
expected = dict(
src=torch.tensor(
[[[36, 19], [95, 19], [95, 68], [36, 68]], [[19, 29], [98, 29], [98, 98], [19, 98]]],
@@ -641,7 +627,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
dtype=dtype,
),
input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
- output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long)
+ output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -649,9 +635,9 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- res = CropGenerator(
- torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200)
- )(torch.Size([2, 1, 100, 100]), True)
+ res = CropGenerator(torch.tensor([[50, 60], [70, 80]], device=device, dtype=dtype), (200, 200))(
+ torch.Size([2, 1, 100, 100]), True
+ )
expected = dict(
src=torch.tensor(
[[[36, 46], [95, 46], [95, 95], [36, 95]], [[36, 46], [115, 46], [115, 115], [36, 115]]],
@@ -664,7 +650,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
dtype=dtype,
),
input_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
- output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long)
+ output_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -679,9 +665,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, size, scale, ratio, same_on_batch, device, dtype):
ResizedCropGenerator(
- size,
- torch.as_tensor(scale, device=device, dtype=dtype),
- torch.as_tensor(ratio, device=device, dtype=dtype)
+ size, torch.as_tensor(scale, device=device, dtype=dtype), torch.as_tensor(ratio, device=device, dtype=dtype)
)(torch.Size([batch_size, 1, 300, 300]), same_on_batch)
@pytest.mark.parametrize(
@@ -701,7 +685,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
ResizedCropGenerator(
size,
torch.as_tensor(scale, device=device, dtype=dtype),
- torch.as_tensor(ratio, device=device, dtype=dtype)
+ torch.as_tensor(ratio, device=device, dtype=dtype),
)(torch.Size([batch_size, 1, 300, 300]))
def test_random_gen(self, device, dtype):
@@ -709,31 +693,27 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
res = ResizedCropGenerator(
(100, 100),
torch.tensor([0.7, 1.3], device=device, dtype=dtype),
- torch.tensor([0.9, 1.1], device=device, dtype=dtype)
+ torch.tensor([0.9, 1.1], device=device, dtype=dtype),
)(torch.Size([2, 1, 300, 300]))
expected = dict(
src=torch.tensor(
[
- [[3., 12.], [298., 12.], [298., 294.], [3., 294.]],
- [[8., 20.], [284., 20.], [284., 298.], [8., 298.]]
+ [[3.0, 12.0], [298.0, 12.0], [298.0, 294.0], [3.0, 294.0]],
+ [[8.0, 20.0], [284.0, 20.0], [284.0, 298.0], [8.0, 298.0]],
],
device=device,
dtype=dtype,
),
dst=torch.tensor(
[
- [[0., 0.], [99., 0.], [99., 99.], [0., 99.]],
- [[0., 0.], [99., 0.], [99., 99.], [0., 99.]]
+ [[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
+ [[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
],
device=device,
dtype=dtype,
),
- input_size=torch.tensor(
- [[300, 300], [300, 300]],
- device=device,
- dtype=torch.int64,
- ),
- output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
+ input_size=torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),
+ output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -745,31 +725,27 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
res = ResizedCropGenerator(
(100, 100),
torch.tensor([0.7, 1.3], device=device, dtype=dtype),
- torch.tensor([0.9, 1.1], device=device, dtype=dtype)
+ torch.tensor([0.9, 1.1], device=device, dtype=dtype),
)(torch.Size([2, 1, 300, 300]), same_on_batch=True)
expected = dict(
src=torch.tensor(
[
- [[5., 0.], [283., 0.], [283., 298.], [5., 298.]],
- [[5., 0.], [283., 0.], [283., 298.], [5., 298.]]
+ [[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],
+ [[5.0, 0.0], [283.0, 0.0], [283.0, 298.0], [5.0, 298.0]],
],
device=device,
dtype=dtype,
),
dst=torch.tensor(
[
- [[0., 0.], [99., 0.], [99., 99.], [0., 99.]],
- [[0., 0.], [99., 0.], [99., 99.], [0., 99.]]
+ [[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
+ [[0.0, 0.0], [99.0, 0.0], [99.0, 99.0], [0.0, 99.0]],
],
device=device,
dtype=dtype,
),
- input_size=torch.tensor(
- [[300, 300], [300, 300]],
- device=device,
- dtype=torch.int64,
- ),
- output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long)
+ input_size=torch.tensor([[300, 300], [300, 300]], device=device, dtype=torch.int64),
+ output_size=torch.tensor([[100, 100], [100, 100]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_close(res['src'], expected['src'])
@@ -789,9 +765,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
self, batch_size, height, width, scale, ratio, value, same_on_batch, device, dtype
):
RectangleEraseGenerator(
- scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype),
- value=value,
+ scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value
)(torch.Size([batch_size, 1, height, width]), same_on_batch)
@pytest.mark.parametrize(
@@ -812,9 +786,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
batch_size = 8
with pytest.raises(Exception):
RectangleEraseGenerator(
- scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype),
- value=value,
+ scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value
)(torch.Size([batch_size, 1, height, width]))
def test_random_gen(self, device, dtype):
@@ -824,9 +796,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
ratio = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
value = 0.5
res = RectangleEraseGenerator(
- scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype),
- value=value,
+ scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value
)(torch.Size([2, 1, height, width]))
expected = dict(
widths=torch.tensor([100, 100], device=device, dtype=dtype),
@@ -849,9 +819,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
ratio = torch.tensor([0.7, 1.3], device=device, dtype=dtype)
value = 0.5
res = RectangleEraseGenerator(
- scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype),
- value=value,
+ scale=scale.to(device=device, dtype=dtype), ratio=ratio.to(device=device, dtype=dtype), value=value
)(torch.Size([2, 1, height, width]), True)
expected = dict(
widths=torch.tensor([100, 100], device=device, dtype=dtype),
@@ -906,7 +874,7 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
dtype=torch.long,
),
input_size=torch.tensor([[200, 200], [200, 200]], device=device, dtype=torch.long),
- output_size=torch.tensor([[120, 150], [120, 150]], device=device, dtype=torch.long)
+ output_size=torch.tensor([[120, 150], [120, 150]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_close(res['src'].to(device=device), expected['src'])
@@ -1012,8 +980,9 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(9)
batch_size = 8
- res = PosterizeGenerator(
- bits=torch.tensor([0, 8], device=device, dtype=dtype))(torch.Size([batch_size]), same_on_batch=True)
+ res = PosterizeGenerator(bits=torch.tensor([0, 8], device=device, dtype=dtype))(
+ torch.Size([batch_size]), same_on_batch=True
+ )
expected = dict(bits_factor=torch.tensor([5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32))
assert res.keys() == expected.keys()
assert_close(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
@@ -1026,7 +995,7 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):
def test_valid_param_combinations(self, batch_size, sharpness, same_on_batch, device, dtype):
PlainUniformGenerator(
(sharpness.to(device=device, dtype=dtype), "sharpness", None, None),
- (sharpness.to(device=device, dtype=dtype), "sharpness_xx", 0., (0., 1.)),
+ (sharpness.to(device=device, dtype=dtype), "sharpness_xx", 0.0, (0.0, 1.0)),
)(torch.Size([batch_size, 1]), same_on_batch)
@pytest.mark.parametrize('sharpness', [(torch.tensor([-1, 5])), (torch.tensor([3])), ([0, 1.0])])
@@ -1034,14 +1003,14 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):
with pytest.raises(Exception):
PlainUniformGenerator(
(sharpness.to(device=device, dtype=dtype), "sharpness", None, None),
- (sharpness.to(device=device, dtype=dtype), "sharpness", 0., (0., 1.)),
+ (sharpness.to(device=device, dtype=dtype), "sharpness", 0.0, (0.0, 1.0)),
)(torch.Size([8, 1]))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 8
res = PlainUniformGenerator(
- (torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None),
+ (torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None)
)(torch.Size([batch_size, 1]))
expected = dict(
sharpness_factor=torch.tensor(
@@ -1055,7 +1024,7 @@ class TestPlainUniformGenerator(RandomGeneratorBaseTests):
torch.manual_seed(42)
batch_size = 8
res = PlainUniformGenerator(
- (torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None),
+ (torch.tensor([0.0, 1.0], device=device, dtype=dtype), "sharpness_factor", None, None)
)(torch.Size([batch_size, 1]), True)
expected = dict(
sharpness_factor=torch.tensor(
@@ -1075,9 +1044,7 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
random_mixup_generator(
batch_size=batch_size,
p=p,
- lambda_val=lambda_val.to(device=device, dtype=dtype)
- if isinstance(lambda_val, (Tensor))
- else lambda_val,
+ lambda_val=lambda_val.to(device=device, dtype=dtype) if isinstance(lambda_val, (Tensor)) else lambda_val,
same_on_batch=same_on_batch,
)
diff --git a/test/benchmark.py b/test/benchmark.py
index 97c1f8db8..989e09a39 100644
--- a/test/benchmark.py
+++ b/test/benchmark.py
@@ -14,15 +14,17 @@ for b, n in product(sizes, sizes):
sub_label = f'[{b}, {4}, {2}]'
x = torch.rand((b, 4, 2))
for num_threads in [1, 4, 16, 32]:
- results.append(benchmark.Timer(
- stmt='get_perspective_transform(x, x)',
- setup='from kornia.geometry import get_perspective_transform',
- globals={'x': x},
- num_threads=num_threads,
- label=label,
- sub_label=sub_label,
- description='get_perspective_transform',
- ).blocked_autorange(min_run_time=1))
+ results.append(
+ benchmark.Timer(
+ stmt='get_perspective_transform(x, x)',
+ setup='from kornia.geometry import get_perspective_transform',
+ globals={'x': x},
+ num_threads=num_threads,
+ label=label,
+ sub_label=sub_label,
+ description='get_perspective_transform',
+ ).blocked_autorange(min_run_time=1)
+ )
compare = benchmark.Compare(results)
compare.print()
diff --git a/test/enhance/test_adjust.py b/test/enhance/test_adjust.py
index 115dbd7bb..34de7f87f 100644
--- a/test/enhance/test_adjust.py
+++ b/test/enhance/test_adjust.py
@@ -129,9 +129,7 @@ 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.enhance.adjust_saturation_with_gray_subtraction,
- (img, 2.0),
- raise_exception=True)
+ assert gradcheck(kornia.enhance.adjust_saturation_with_gray_subtraction, (img, 2.0), raise_exception=True)
class TestAdjustHue:
@@ -318,8 +316,11 @@ class TestAdjustContrast:
) # 3x2x2
expected = torch.tensor(
- [[[0.6210, 0.6210], [0.6210, 0.6210]], [[0.6210, 0.6210], [0.6210, 0.6210]],
- [[0.6210, 0.6210], [0.6210, 0.6210]]],
+ [
+ [[0.6210, 0.6210], [0.6210, 0.6210]],
+ [[0.6210, 0.6210], [0.6210, 0.6210]],
+ [[0.6210, 0.6210], [0.6210, 0.6210]],
+ ],
device=device,
dtype=dtype,
) # 3x2x2
@@ -377,10 +378,13 @@ class TestAdjustContrast:
) # 3x2x2
expected = torch.tensor(
- [[[1.0000, 1.0000], [1.0000, 1.0000]], [[0.3790, 0.3790], [0.3790, 0.3790]],
- [[0.0000, 0.0000], [0.0000, 0.0000]]],
+ [
+ [[1.0000, 1.0000], [1.0000, 1.0000]],
+ [[0.3790, 0.3790], [0.3790, 0.3790]],
+ [[0.0000, 0.0000], [0.0000, 0.0000]],
+ ],
device=device,
- dtype=dtype
+ dtype=dtype,
) # 3x2x2
f = kornia.enhance.AdjustContrastWithMeanSubtraction(2.0)
@@ -530,12 +534,12 @@ class TestAdjustContrast:
[
[[1.0000, 1.0000, 0.4818], [1.0000, 1.0000, 0.4818]],
[[0.4818, 0.4818, 0.1068], [0.4818, 0.4818, 0.1068]],
- [[0.1068, 0.1068, 0.1068], [0.6318, 0.6318, 0.1818]]
+ [[0.1068, 0.1068, 0.1068], [0.6318, 0.6318, 0.1818]],
],
[
[[0.0000, 0.0000, 1.0000], [0.0000, 0.0000, 0.2079]],
[[0.3079, 0.3079, 0.5079], [0.3079, 0.3079, 0.5079]],
- [[0.9079, 0.9079, 0.0000], [0.3079, 0.1079, 0.0000]]
+ [[0.9079, 0.9079, 0.0000], [0.3079, 0.1079, 0.0000]],
],
],
device=device,
@@ -608,10 +612,16 @@ class TestAdjustBrightness:
expected = torch.tensor(
[
- [[[0.2500, 0.2500], [0.2500, 0.2500]], [[0.1250, 0.1250], [0.1250, 0.1250]],
- [[0.0625, 0.0625], [0.0625, 0.0625]]],
- [[[0.0000, 0.0000], [0.0000, 0.0000]], [[0.0300, 0.0300], [0.0300, 0.0300]],
- [[0.0600, 0.0600], [0.0600, 0.0600]]]
+ [
+ [[0.2500, 0.2500], [0.2500, 0.2500]],
+ [[0.1250, 0.1250], [0.1250, 0.1250]],
+ [[0.0625, 0.0625], [0.0625, 0.0625]],
+ ],
+ [
+ [[0.0000, 0.0000], [0.0000, 0.0000]],
+ [[0.0300, 0.0300], [0.0300, 0.0300]],
+ [[0.0600, 0.0600], [0.0600, 0.0600]],
+ ],
],
device=device,
dtype=dtype,
@@ -632,9 +642,7 @@ class TestAdjustBrightness:
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.enhance.adjust_brightness_accumulative,
- (img, 2.0),
- raise_exception=True)
+ assert gradcheck(kornia.enhance.adjust_brightness_accumulative, (img, 2.0), raise_exception=True)
class TestAdjustSigmoid:
@@ -656,11 +664,16 @@ class TestAdjustSigmoid:
expected = torch.tensor(
[
- [[[0.99330715, 0.99330715], [0.99330715, 0.99330715]], [[0.5, 0.5], [0.5, 0.5]],
- [[0.07585818, 0.07585818], [0.07585818, 0.07585818]]],
- [[[0.00669285, 0.00669285], [0.00669285, 0.00669285]],
- [[0.11920292, 0.11920292], [0.11920292, 0.11920292]],
- [[0.73105858, 0.73105858], [0.73105858, 0.73105858]]],
+ [
+ [[0.99330715, 0.99330715], [0.99330715, 0.99330715]],
+ [[0.5, 0.5], [0.5, 0.5]],
+ [[0.07585818, 0.07585818], [0.07585818, 0.07585818]],
+ ],
+ [
+ [[0.00669285, 0.00669285], [0.00669285, 0.00669285]],
+ [[0.11920292, 0.11920292], [0.11920292, 0.11920292]],
+ [[0.73105858, 0.73105858], [0.73105858, 0.73105858]],
+ ],
],
device=device,
dtype=dtype,
@@ -705,10 +718,16 @@ class TestAdjustLog:
expected = torch.tensor(
[
- [[[1, 1], [1, 1]], [[0.5849625, 0.5849625], [0.5849625, 0.5849625]],
- [[0.32192809, 0.32192809], [0.32192809, 0.32192809]]],
- [[[0, 0], [0, 0]], [[0.37851162, 0.37851162], [0.37851162, 0.37851162]],
- [[0.67807191, 0.67807191], [0.67807191, 0.67807191]]],
+ [
+ [[1, 1], [1, 1]],
+ [[0.5849625, 0.5849625], [0.5849625, 0.5849625]],
+ [[0.32192809, 0.32192809], [0.32192809, 0.32192809]],
+ ],
+ [
+ [[0, 0], [0, 0]],
+ [[0.37851162, 0.37851162], [0.37851162, 0.37851162]],
+ [[0.67807191, 0.67807191], [0.67807191, 0.67807191]],
+ ],
],
device=device,
dtype=dtype,
diff --git a/test/enhance/test_histogram.py b/test/enhance/test_histogram.py
index a1ddd6848..98806359f 100644
--- a/test/enhance/test_histogram.py
+++ b/test/enhance/test_histogram.py
@@ -62,7 +62,7 @@ class TestImageHistogram2d:
input_x, _ = torch.meshgrid(input, input)
input_x = input_x.repeat(*size)
if kernel == "gaussian":
- bandwidth = 2 * 0.4 ** 2
+ bandwidth = 2 * 0.4**2
else:
bandwidth = None
hist, _ = TestImageHistogram2d.fcn(input_x, 0.0, 255.0, 10, bandwidth=bandwidth, centers=input, kernel=kernel)
@@ -76,7 +76,7 @@ class TestImageHistogram2d:
input_x, _ = torch.meshgrid(input, input)
input_x = input_x.repeat(*size)
if kernel == "gaussian":
- bandwidth = 2 * 0.4 ** 2
+ bandwidth = 2 * 0.4**2
else:
bandwidth = None
hist, pdf = TestImageHistogram2d.fcn(
@@ -121,7 +121,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
@@ -133,7 +133,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)
@@ -170,7 +170,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
@@ -181,7 +181,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)
diff --git a/test/enhance/test_shift_rgb.py b/test/enhance/test_shift_rgb.py
index a83cdc61a..7a8dcc0d5 100644
--- a/test/enhance/test_shift_rgb.py
+++ b/test/enhance/test_shift_rgb.py
@@ -7,7 +7,6 @@ import kornia.testing as utils # test utils
class TestRGBShift:
-
def test_rgb_shift_no_shift(self, device, dtype):
r_shift, g_shift, b_shift = 0, 0, 0
image = torch.rand(2, 3, 5, 5, device=device, dtype=dtype)
@@ -46,7 +45,7 @@ class TestRGBShift:
def test_rgb_shift(self, device, dtype):
r_shift, g_shift, b_shift = 0.1, 0.2, -0.3
- image = torch.tensor([[[[0.2, 0.]], [[0.3, 0.5]], [[0.4, 0.7]]]], device=device, dtype=dtype)
+ image = torch.tensor([[[[0.2, 0.0]], [[0.3, 0.5]], [[0.4, 0.7]]]], device=device, dtype=dtype)
shifted = kornia.enhance.shift_rgb(image, r_shift, g_shift, b_shift)
expected = torch.tensor([[[[0.3, 0.1]], [[0.5, 0.7]], [[0.1, 0.4]]]], device=device, dtype=dtype)
diff --git a/test/feature/test_integrated.py b/test/feature/test_integrated.py
index 26a9b82fd..c573538dd 100644
--- a/test/feature/test_integrated.py
+++ b/test/feature/test_integrated.py
@@ -50,9 +50,7 @@ class TestGetLAFDescriptors:
B, C, H, W = 1, 1, 32, 32
PS = 16
img = torch.rand(B, C, H, W, device=device)
- centers = torch.tensor([[H / 2.0, W / 2.0], [2.0 * H / 3.0, W / 2.0]], device=device, dtype=dtype).view(
- 1, 2, 2
- )
+ centers = torch.tensor([[H / 2.0, W / 2.0], [2.0 * H / 3.0, W / 2.0]], device=device, dtype=dtype).view(1, 2, 2)
scales = torch.tensor([(H + W) / 5.0, (H + W) / 6.0], device=device, dtype=dtype).view(1, 2, 1, 1)
ori = torch.tensor([0.0, 30.0], device=device, dtype=dtype).view(1, 2, 1)
lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
@@ -64,8 +62,9 @@ class TestGetLAFDescriptors:
return inputs.mean(dim=(2, 3))
desc = _MeanPatch()
- assert gradcheck(get_laf_descriptors, (img, lafs, desc, PS, True),
- eps=1e-3, atol=1e-3, raise_exception=True, nondet_tol=1e-3)
+ assert gradcheck(
+ get_laf_descriptors, (img, lafs, desc, PS, True), eps=1e-3, atol=1e-3, raise_exception=True, nondet_tol=1e-3
+ )
class TestLAFDescriptor:
@@ -92,9 +91,7 @@ class TestLAFDescriptor:
B, C, H, W = 1, 1, 32, 32
PS = 16
img = torch.rand(B, C, H, W, device=device)
- centers = torch.tensor([[H / 2.0, W / 2.0], [2.0 * H / 3.0, W / 2.0]], device=device).view(
- 1, 2, 2
- )
+ centers = torch.tensor([[H / 2.0, W / 2.0], [2.0 * H / 3.0, W / 2.0]], device=device).view(1, 2, 2)
scales = torch.tensor([(H + W) / 5.0, (H + W) / 6.0], device=device).view(1, 2, 1, 1)
ori = torch.tensor([0.0, 30.0], device=device).view(1, 2, 1)
lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
@@ -104,6 +101,7 @@ class TestLAFDescriptor:
class _MeanPatch(nn.Module):
def forward(self, inputs):
return inputs.mean(dim=(2, 3))
+
lafdesc = LAFDescriptor(_MeanPatch(), PS)
assert gradcheck(lafdesc, (img, lafs), eps=1e-3, atol=1e-3, raise_exception=True, nondet_tol=1e-3)
@@ -259,8 +257,7 @@ class TestLocalFeatureMatcher:
# Reprojection error of 5px is OK
assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
- @pytest.mark.skipif(sys.platform == "win32",
- reason="this test takes so much memory in the CI with Windows")
+ @pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_real_gftt(self, device, dtype, data):
torch.random.manual_seed(0)
@@ -277,8 +274,7 @@ class TestLocalFeatureMatcher:
# Reprojection error of 5px is OK
assert_close(transform_points(homography[None], pts_src[None]), pts_dst[None], rtol=5e-2, atol=5)
- @pytest.mark.skipif(sys.platform == "win32",
- reason="this test takes so much memory in the CI with Windows")
+ @pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_real_keynet(self, device, dtype, data):
torch.random.manual_seed(0)
diff --git a/test/feature/test_loftr.py b/test/feature/test_loftr.py
index 2f58b8f16..73a121fe2 100644
--- a/test/feature/test_loftr.py
+++ b/test/feature/test_loftr.py
@@ -21,8 +21,7 @@ class TestLoFTR:
assert loftr is not None
@pytest.mark.skipif(torch_version_geq(1, 10), reason="RuntimeError: CUDA out of memory with pytorch>=1.10")
- @pytest.mark.skipif(sys.platform == "win32",
- reason="this test takes so much memory in the CI with Windows")
+ @pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)
def test_pretrained_indoor(self, device, dtype, data):
loftr = LoFTR('indoor').to(device, dtype)
@@ -33,8 +32,7 @@ class TestLoFTR:
assert_close(out['keypoints1'], data_dev["loftr_indoor_tentatives1"])
@pytest.mark.skipif(torch_version_geq(1, 10), reason="RuntimeError: CUDA out of memory with pytorch>=1.10")
- @pytest.mark.skipif(sys.platform == "win32",
- reason="this test takes so much memory in the CI with Windows")
+ @pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_pretrained_outdoor(self, device, dtype, data):
loftr = LoFTR('outdoor').to(device, dtype)
diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.py
index b3926cd3f..da6d4379a 100644
--- a/test/feature/test_siftdesc.py
+++ b/test/feature/test_siftdesc.py
@@ -41,7 +41,7 @@ class TestSIFTDescriptor:
inp = torch.ones(3, 1, 19, 19, device=device, dtype=dtype)
sift = SIFTDescriptor(19, 5, 3).to(device, dtype)
out = sift(inp)
- assert out.shape == (3, (3 ** 2) * 5)
+ assert out.shape == (3, (3**2) * 5)
def test_toy(self, device, dtype):
patch = torch.ones(1, 1, 6, 6, device=device, dtype=dtype)
@@ -99,5 +99,4 @@ class TestDenseSIFTDescriptor:
batch_size, channels, height, width = 1, 1, 32, 32
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(DenseSIFTDescriptor(4, 2, 2), (patches),
- raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(DenseSIFTDescriptor(4, 2, 2), (patches), raise_exception=True, nondet_tol=1e-4)
diff --git a/test/filters/test_filters.py b/test/filters/test_filters.py
index 603bb1d37..3a242dce1 100644
--- a/test/filters/test_filters.py
+++ b/test/filters/test_filters.py
@@ -247,7 +247,7 @@ class TestFilter2D:
[3.0, 3.0, 3.0, 3.0, 3.0, 0.0],
[3.0, 3.0, 3.0, 3.0, 3.0, 0.0],
[3.0, 3.0, 3.0, 3.0, 3.0, 0.0],
- [2.0, 2.0, 2.0, 2.0, 2.0, 0.0]
+ [2.0, 2.0, 2.0, 2.0, 2.0, 0.0],
]
]
],
diff --git a/test/filters/test_hanning.py b/test/filters/test_hanning.py
index 80b4cebf4..b0f0ed11b 100644
--- a/test/filters/test_hanning.py
+++ b/test/filters/test_hanning.py
@@ -29,8 +29,8 @@ def test_get_hanning_kernel1d_5(device, dtype):
def test_get_hanning_kernel2d_3x4(device, dtype):
kernel = kornia.filters.get_hanning_kernel2d((3, 4), dtype=dtype, device=device)
- expected = torch.tensor([[0., 0.00, 0.00, 0.],
- [0., 0.75, 0.75, 0.],
- [0., 0.00, 0.00, 0.]], dtype=dtype, device=device)
+ expected = torch.tensor(
+ [[0.0, 0.00, 0.00, 0.0], [0.0, 0.75, 0.75, 0.0], [0.0, 0.00, 0.00, 0.0]], dtype=dtype, device=device
+ )
assert kernel.shape == (3, 4)
assert_close(kernel, expected)
diff --git a/test/geometry/calibration/test_pnp.py b/test/geometry/calibration/test_pnp.py
index df5815011..de61f1b27 100644
--- a/test/geometry/calibration/test_pnp.py
+++ b/test/geometry/calibration/test_pnp.py
@@ -88,7 +88,7 @@ class TestSolvePnpDlt:
return intrinsics, world_to_cam_3x4, world_points, img_points
- @pytest.mark.parametrize("num_points", (6, 20,))
+ @pytest.mark.parametrize("num_points", (6, 20))
def test_smoke(self, num_points, device, dtype):
intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)
@@ -108,7 +108,7 @@ class TestSolvePnpDlt:
assert gradcheck(kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics), raise_exception=True)
- @pytest.mark.parametrize("num_points", (6, 20,))
+ @pytest.mark.parametrize("num_points", (6, 20))
def test_pred_world_to_cam(self, num_points, device, dtype):
intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)
@@ -116,7 +116,7 @@ class TestSolvePnpDlt:
pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)
assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-4)
- @pytest.mark.parametrize("num_points", (6, 20,))
+ @pytest.mark.parametrize("num_points", (6, 20))
def test_project(self, num_points, device, dtype):
intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)
diff --git a/test/geometry/epipolar/test_numeric.py b/test/geometry/epipolar/test_numeric.py
index 61d55f5be..8bd977e5f 100644
--- a/test/geometry/epipolar/test_numeric.py
+++ b/test/geometry/epipolar/test_numeric.py
@@ -22,7 +22,7 @@ class TestSkewSymmetric:
@pytest.mark.parametrize("shapes", [(1, 1), (1, 5), (2, 1), (2, 5), (4, 1), (4, 5)])
def test_shapes(self, device, dtype, shapes):
- input_shape = shapes + (3, )
+ input_shape = shapes + (3,)
output_shape = shapes + (3, 3)
t = torch.rand(*input_shape, device=device, dtype=dtype)
cross_product_matrix = epi.cross_product_matrix(t)
@@ -30,7 +30,7 @@ class TestSkewSymmetric:
@pytest.mark.parametrize("shapes", [(1, 1), (1, 5), (2, 1), (2, 5), (4, 1), (4, 5)])
def test_funcional_shapes(self, device, dtype, shapes):
- input_shape = shapes + (3, )
+ input_shape = shapes + (3,)
t = torch.rand(*input_shape, device=device, dtype=dtype)
# Feed batches
diff --git a/test/geometry/test_bbox.py b/test/geometry/test_bbox.py
index d311ff344..64469def9 100644
--- a/test/geometry/test_bbox.py
+++ b/test/geometry/test_bbox.py
@@ -140,7 +140,7 @@ class TestTransformBoxes2D:
[114.6880, 103.0150, 258.0480, 307.5075],
[0.0000, 80.5547, 510.9760, 431.4453],
[1.3654, 262.1440, 345.4293, 246.7840],
- [254.9760, 144.2067, 137.2160, 265.9225]
+ [254.9760, 144.2067, 137.2160, 265.9225],
],
device=device,
dtype=dtype,
@@ -253,12 +253,16 @@ class TestBbox3D:
class TestNMS:
def test_smoke(self, device, dtype):
- boxes = torch.tensor([
- [10., 10., 20., 20.],
- [15., 5., 15., 25.],
- [100., 100., 200., 200.],
- [100., 100., 200., 200.],
- ], device=device, dtype=dtype)
+ boxes = torch.tensor(
+ [
+ [10.0, 10.0, 20.0, 20.0],
+ [15.0, 5.0, 15.0, 25.0],
+ [100.0, 100.0, 200.0, 200.0],
+ [100.0, 100.0, 200.0, 200.0],
+ ],
+ device=device,
+ dtype=dtype,
+ )
scores = torch.tensor([0.9, 0.8, 0.7, 0.9], device=device, dtype=dtype)
expected = torch.tensor([0, 3, 1], device=device, dtype=torch.long)
actual = nms(boxes, scores, iou_threshold=0.8)
diff --git a/test/geometry/test_boxes.py b/test/geometry/test_boxes.py
index b9053de70..208457d2a 100644
--- a/test/geometry/test_boxes.py
+++ b/test/geometry/test_boxes.py
@@ -169,13 +169,13 @@ class TestBoxes2D:
def test_boxes_list_to_tensor_list(self, mode, device, dtype):
src_1 = [
torch.as_tensor([[[2, 2], [2, 3], [1, 3], [1, 2]]], device=device, dtype=dtype),
- torch.as_tensor([
- [[2, 2], [2, 3], [1, 3], [1, 2]], [[2, 2], [2, 3], [1, 3], [1, 2]]
- ], device=device, dtype=dtype)
+ torch.as_tensor(
+ [[[2, 2], [2, 3], [1, 3], [1, 2]], [[2, 2], [2, 3], [1, 3], [1, 2]]], device=device, dtype=dtype
+ ),
]
src_2 = [
torch.as_tensor([[1, 1, 5, 5]], device=device, dtype=dtype),
- torch.as_tensor([[1, 1, 5, 5], [1, 1, 5, 5]], device=device, dtype=dtype)
+ torch.as_tensor([[1, 1, 5, 5], [1, 1, 5, 5]], device=device, dtype=dtype),
]
src = src_1 if mode in ['vertices', 'vertices_plus'] else src_2
box = Boxes.from_tensor(src, mode=mode)
@@ -279,12 +279,8 @@ class TestBoxes2D:
partial(apply_boxes_method, method='to_tensor', mode='vertices_plus'), (t_boxes4,), raise_exception=True
)
assert gradcheck(partial(apply_boxes_method, method='get_boxes_shape'), (t_boxes1,), raise_exception=True)
- assert gradcheck(
- lambda x: Boxes.from_tensor(x, mode='xyxy_plus').data, (t_boxes_xyxy,), raise_exception=True
- )
- assert gradcheck(
- lambda x: Boxes.from_tensor(x, mode='xywh').data, (t_boxes_xyxy1,), raise_exception=True
- )
+ assert gradcheck(lambda x: Boxes.from_tensor(x, mode='xyxy_plus').data, (t_boxes_xyxy,), raise_exception=True)
+ assert gradcheck(lambda x: Boxes.from_tensor(x, mode='xywh').data, (t_boxes_xyxy1,), raise_exception=True)
class TestTransformBoxes2D:
@@ -482,12 +478,12 @@ class TestBbox3D:
t_box1 = torch.tensor(
[[[0, 1, 2], [0, 1, 32], [10, 21, 2], [0, 21, 2], [10, 1, 32], [10, 21, 32], [10, 1, 2], [0, 21, 32]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
t_box2 = torch.tensor(
[[[3, 4, 5], [3, 4, 65], [43, 54, 5], [3, 54, 5], [43, 4, 5], [43, 4, 65], [43, 54, 65], [3, 54, 65]]],
device=device,
- dtype=dtype
+ dtype=dtype,
)
batched_boxes = Boxes3D(torch.stack([t_box1, t_box2]))
@@ -762,9 +758,7 @@ class TestBbox3D:
assert gradcheck(
lambda x: Boxes3D.from_tensor(x, mode='xyzxyz_plus').data, (t_boxes_xyzxyz,), raise_exception=True
)
- assert gradcheck(
- lambda x: Boxes3D.from_tensor(x, mode='xyzwhd').data, (t_boxes_xyzxyz1,), raise_exception=True
- )
+ assert gradcheck(lambda x: Boxes3D.from_tensor(x, mode='xyzwhd').data, (t_boxes_xyzxyz1,), raise_exception=True)
class TestTransformBoxes3D:
diff --git a/test/geometry/test_homography.py b/test/geometry/test_homography.py
index e6c171a6d..1ca570fa7 100644
--- a/test/geometry/test_homography.py
+++ b/test/geometry/test_homography.py
@@ -18,24 +18,15 @@ from kornia.testing import assert_close
class TestSampleValidation:
def test_good(self, device, dtype):
- pts1 = torch.tensor([[0.0, 0.0],
- [0.0, 1.0],
- [1.0, 1.0],
- [1.0, 0.0]], device=device, dtype=dtype)[None]
+ pts1 = torch.tensor([[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]], device=device, dtype=dtype)[None]
mask = sample_is_valid_for_homography(pts1, pts1)
expected = torch.tensor([True], device=device, dtype=torch.bool)
assert torch.equal(mask, expected)
def test_bad(self, device, dtype):
- pts1 = torch.tensor([[0.0, 0.0],
- [1.0, 0.0],
- [0.0, 1.0],
- [1.0, 1.0]], device=device, dtype=dtype)[None]
-
- pts2 = torch.tensor([[0.0, 0.0],
- [0.0, 1.0],
- [1.0, 0.0],
- [1.0, 1.0]], device=device, dtype=dtype)[None]
+ pts1 = torch.tensor([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], device=device, dtype=dtype)[None]
+
+ pts2 = torch.tensor([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]], device=device, dtype=dtype)[None]
mask = sample_is_valid_for_homography(pts1, pts2)
expected = torch.tensor([False], device=device, dtype=torch.bool)
assert torch.equal(mask, expected)
@@ -45,7 +36,7 @@ class TestSampleValidation:
pts1 = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
pts2 = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
mask = sample_is_valid_for_homography(pts1, pts2)
- assert (mask.shape == torch.Size([batch_size]))
+ assert mask.shape == torch.Size([batch_size])
class TestOneWayError:
diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.py
index 852ec28ec..94ba76681 100644
--- a/test/geometry/test_linalg.py
+++ b/test/geometry/test_linalg.py
@@ -368,7 +368,7 @@ class TestPointsLinesDistances:
def test_functional(self, device):
pts = torch.tensor([1.0, 0], device=device, dtype=torch.float64).view(1, 1, 2).tile(1, 6, 1)
lines = torch.tensor(
- [[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0], ],
+ [[0.0, 1.0, 0.0], [0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 0.0, 1.0], [1.0, 1.0, 0.0], [1.0, 1.0, 1.0]],
device=device,
dtype=torch.float64,
).view(1, 6, 3)
diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.py
index 9c5b0e0e0..441136db6 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -233,7 +233,7 @@ class TestRescale:
[0.0237, 0.0756, 0.1306, 0.1856, 0.2376],
[0.0409, 0.1306, 0.2256, 0.3206, 0.4104],
[0.0581, 0.1856, 0.3206, 0.4556, 0.5832],
- [0.0743, 0.2376, 0.4104, 0.5832, 0.7464]
+ [0.0743, 0.2376, 0.4104, 0.5832, 0.7464],
]
]
],
diff --git a/test/geometry/transform/test_homography_warper.py b/test/geometry/transform/test_homography_warper.py
index e0cdf6f1b..d20d42deb 100644
--- a/test/geometry/transform/test_homography_warper.py
+++ b/test/geometry/transform/test_homography_warper.py
@@ -112,15 +112,15 @@ class TestHomographyWarper:
dst_homo_src[..., 1, 2] = 2.0
dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)
- denorm_homo = kornia.geometry.conversions.denormalize_homography(
- dst_homo_src, (height, width), (height, width))
+ denorm_homo = kornia.geometry.conversions.denormalize_homography(dst_homo_src, (height, width), (height, width))
norm_denorm_homo = kornia.geometry.conversions.normalize_homography(
- denorm_homo, (height, width), (height, width))
+ denorm_homo, (height, width), (height, width)
+ )
assert (dst_homo_src == norm_denorm_homo).all()
- norm_homo = kornia.geometry.conversions.normalize_homography(
- dst_homo_src, (height, width), (height, width))
+ norm_homo = kornia.geometry.conversions.normalize_homography(dst_homo_src, (height, width), (height, width))
denorm_norm_homo = kornia.geometry.conversions.denormalize_homography(
- norm_homo, (height, width), (height, width))
+ norm_homo, (height, width), (height, width)
+ )
assert (dst_homo_src == denorm_norm_homo).all()
@pytest.mark.parametrize("offset", [1, 3, 7])
@@ -341,7 +341,8 @@ class TestHomographyNormalTransform:
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.geometry.conversions.normal_transform_pixel3d(
- depth, height, width, device=device, dtype=dtype)
+ depth, height, width, device=device, dtype=dtype
+ )
output = kornia.geometry.linalg.transform_points(transform, input)
assert_close(output, expected.to(device=device, dtype=dtype), atol=1e-4, rtol=1e-4)
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 208be9606..3a213e1a0 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -15,8 +15,7 @@ class TestGetPerspectiveTransform:
points_src = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
points_dst = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
- dst_trans_src = kornia.geometry.get_perspective_transform(
- points_src, points_dst)
+ dst_trans_src = kornia.geometry.get_perspective_transform(points_src, points_dst)
assert dst_trans_src.shape == (batch_size, 3, 3)
@@ -62,21 +61,16 @@ class TestGetPerspectiveTransform:
assert_close(points_dst, points_dst_hat)
def test_hflip(self, device, dtype):
- points_src = torch.tensor(
- [[[0., 0.], [1., 0.], [1., 1.], [0., 1.]]], device=device, dtype=dtype)
+ points_src = torch.tensor([[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]], device=device, dtype=dtype)
- points_dst = torch.tensor(
- [[[1., 0.], [0., 0.], [0., 1.], [1., 1.]]], device=device, dtype=dtype)
+ points_dst = torch.tensor([[[1.0, 0.0], [0.0, 0.0], [0.0, 1.0], [1.0, 1.0]]], device=device, dtype=dtype)
- dst_trans_src = kornia.geometry.get_perspective_transform(
- points_src, points_dst)
+ dst_trans_src = kornia.geometry.get_perspective_transform(points_src, points_dst)
- point_left = torch.tensor([[[0., 0.]]], device=device, dtype=dtype)
- point_right = torch.tensor([[[1., 0.]]], device=device, dtype=dtype)
+ point_left = torch.tensor([[[0.0, 0.0]]], device=device, dtype=dtype)
+ point_right = torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype)
- assert_close(
- kornia.geometry.transform_points(dst_trans_src, point_left),
- point_right)
+ assert_close(kornia.geometry.transform_points(dst_trans_src, point_left), point_right)
def test_jit(self, device, dtype):
points_src = torch.rand(1, 4, 2, device=device, dtype=dtype)
@@ -87,9 +81,7 @@ class TestGetPerspectiveTransform:
assert_close(op(points_src, points_dst), op_jit(points_src, points_dst))
- @pytest.mark.skipif(
- torch_version_lt(1, 11, 0),
- reason="backward for LSTSQ not supported in pytorch < 1.11.0")
+ @pytest.mark.skipif(torch_version_lt(1, 11, 0), reason="backward for LSTSQ not supported in pytorch < 1.11.0")
def test_gradcheck(self, device):
# compute gradient check
points_src = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.py
index 67b442ba2..d2bd973d5 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -145,7 +145,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
diff --git a/test/geometry/transform/test_thin_plate_spline.py b/test/geometry/transform/test_thin_plate_spline.py
index 3030da72b..ced320254 100644
--- a/test/geometry/transform/test_thin_plate_spline.py
+++ b/test/geometry/transform/test_thin_plate_spline.py
@@ -152,8 +152,8 @@ class TestWarpImage:
assert warp.shape == tensor.shape
@pytest.mark.skipif(
- torch_version_geq(1, 10),
- reason="for some reason the solver detects singular matrices in pytorch >=1.10.")
+ torch_version_geq(1, 10), reason="for some reason the solver detects singular matrices in pytorch >=1.10."
+ )
@pytest.mark.parametrize('batch_size', [1, 3])
def test_warp(self, batch_size, device, dtype):
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(
diff --git a/test/grad_estimator/test_ste.py b/test/grad_estimator/test_ste.py
index 57c832efe..c6150bde7 100644
--- a/test/grad_estimator/test_ste.py
+++ b/test/grad_estimator/test_ste.py
@@ -8,8 +8,7 @@ from kornia.grad_estimator import STEFunction, StraightThroughEstimator
class TestSTE:
-
- def test_smoke(self,):
+ def test_smoke(self):
StraightThroughEstimator(K.Normalize(0.5, 0.5))
def test_function(self, device, dtype):
@@ -17,7 +16,7 @@ class TestSTE:
output = torch.sign(input)
loss = output.mean()
loss.backward()
- assert_allclose(input.grad, torch.tensor([0., 0., 0., 0.], device=device, dtype=dtype))
+ assert_allclose(input.grad, torch.tensor([0.0, 0.0, 0.0, 0.0], device=device, dtype=dtype))
out_est = STEFunction.apply(input, output, F.hardtanh)
loss = out_est.mean()
@@ -31,15 +30,24 @@ class TestSTE:
def test_module(self, device, dtype):
input = torch.randn(1, 1, 4, 4, requires_grad=True, device=device, dtype=dtype)
- estimator = StraightThroughEstimator(K.RandomPosterize(3, p=1.), grad_fn=F.hardtanh)
+ estimator = StraightThroughEstimator(K.RandomPosterize(3, p=1.0), grad_fn=F.hardtanh)
out = estimator(input)
loss = out.mean()
loss.backward()
o = torch.tensor(
- [[[[0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625],
- [0.0625, 0.0625, 0.0625, 0.0625]]]], device=device, dtype=dtype)
+ [
+ [
+ [
+ [0.0625, 0.0625, 0.0625, 0.0625],
+ [0.0625, 0.0625, 0.0625, 0.0625],
+ [0.0625, 0.0625, 0.0625, 0.0625],
+ [0.0625, 0.0625, 0.0625, 0.0625],
+ ]
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
assert_allclose(input.grad, o)
@pytest.mark.skip("Function.apply is not supported in Torchscript rightnow.")
diff --git a/test/losses/test_losses.py b/test/losses/test_losses.py
index ed8879364..5621f97f0 100644
--- a/test/losses/test_losses.py
+++ b/test/losses/test_losses.py
@@ -22,22 +22,28 @@ class TestBinaryFocalLossWithLogits:
logits = torch.rand(2, 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="sum").shape == ())
+ assert (
+ 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):
logits = torch.rand(2, 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="mean").shape == ())
+ assert (
+ 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):
logits = torch.rand(2, 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="mean").shape == ())
+ assert (
+ kornia.losses.binary_focal_loss_with_logits(logits, labels, alpha=0.5, gamma=2.0, reduction="mean").shape
+ == ()
+ )
def test_jit(self, device, dtype):
logits = torch.rand(2, 3, 2, dtype=dtype, device=device)
@@ -577,7 +583,6 @@ class TestPSNRLoss:
class TestLovaszHingeLoss:
-
def test_smoke(self, device, dtype):
num_classes = 1
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
@@ -663,7 +668,7 @@ class TestLovaszSoftmaxLoss:
# make perfect prediction
# note that softmax(prediction[:, 1]) == 1. softmax(prediction[:, 0]) == 0.
prediction = torch.zeros(2, num_classes, 1, 2, device=device, dtype=dtype)
- prediction[:, 1] = 100.
+ prediction[:, 1] = 100.0
labels = torch.ones(2, 1, 2, device=device, dtype=torch.int64)
criterion = kornia.losses.LovaszSoftmaxLoss()
diff --git a/test/performance/test_project_points_speed.py b/test/performance/test_project_points_speed.py
index 87a9fab93..95893ae9e 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
-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 bandwidth in the CI
diff --git a/test/test_metrics.py b/test/test_metrics.py
index ed265bece..58f3501d2 100644
--- a/test/test_metrics.py
+++ b/test/test_metrics.py
@@ -198,27 +198,25 @@ class TestPsnr:
class TestMeanAveragePrecision:
def test_smoke(self, device, dtype):
- boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
labels = torch.tensor([1], device=device, dtype=torch.long)
- scores = torch.tensor([.7], device=device, dtype=dtype)
+ scores = torch.tensor([0.7], device=device, dtype=dtype)
- gt_boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ gt_boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
gt_labels = torch.tensor([1], device=device, dtype=torch.long)
- mean_ap = kornia.metrics.mean_average_precision(
- [boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
+ mean_ap = kornia.metrics.mean_average_precision([boxes], [labels], [scores], [gt_boxes], [gt_labels], 2)
- assert_close(mean_ap[0], torch.tensor(1., device=device, dtype=dtype))
+ assert_close(mean_ap[0], torch.tensor(1.0, device=device, dtype=dtype))
assert_close(mean_ap[1][1], 1.0)
def test_raise(self, device, dtype):
- boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
labels = torch.tensor([1], device=device, dtype=torch.long)
- scores = torch.tensor([.7], device=device, dtype=dtype)
+ scores = torch.tensor([0.7], device=device, dtype=dtype)
- gt_boxes = torch.tensor([[100, 50, 150, 100.]], device=device, dtype=dtype)
+ gt_boxes = torch.tensor([[100, 50, 150, 100.0]], device=device, dtype=dtype)
gt_labels = torch.tensor([1], device=device, dtype=torch.long)
with pytest.raises(AssertionError):
- _ = kornia.metrics.mean_average_precision(
- boxes[0], [labels], [scores], [gt_boxes], [gt_labels], 2)
+ _ = kornia.metrics.mean_average_precision(boxes[0], [labels], [scores], [gt_boxes], [gt_labels], 2)
diff --git a/test/x/test_detection.py b/test/x/test_detection.py
index a250b8d8d..7ffbe97de 100644
--- a/test/x/test_detection.py
+++ b/test/x/test_detection.py
@@ -11,16 +11,13 @@ class DummyDatasetDetection(Dataset):
return 10
def __getitem__(self, index):
- return torch.ones(3, 32, 32), torch.tensor([10., 10., 15., 15.])
+ return torch.ones(3, 32, 32), torch.tensor([10.0, 10.0, 15.0, 15.0])
class DummyModel(nn.Module):
def __init__(self):
super().__init__()
- self.model = nn.Sequential(
- nn.Conv2d(3, 1, kernel_size=16, stride=16),
- nn.Flatten()
- )
+ self.model = nn.Sequential(nn.Conv2d(3, 1, kernel_size=16, stride=16), nn.Flatten())
def forward(self, x, y=None):
return self.model(x)
@@ -63,14 +60,28 @@ class TestObjectDetectionTrainer:
@pytest.mark.parametrize("loss_computed_by_model", [True, False])
def test_fit(self, model, dataloader, criterion, optimizer, scheduler, configuration, loss_computed_by_model):
trainer = ObjectDetectionTrainer(
- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, num_classes=3,
- loss_computed_by_model=loss_computed_by_model
+ model,
+ dataloader,
+ dataloader,
+ criterion,
+ optimizer,
+ scheduler,
+ configuration,
+ num_classes=3,
+ loss_computed_by_model=loss_computed_by_model,
)
trainer.fit()
def test_exception(self, model, dataloader, criterion, optimizer, scheduler, configuration):
with pytest.raises(ValueError):
ObjectDetectionTrainer(
- model, dataloader, dataloader, criterion, optimizer, scheduler, configuration, num_classes=3,
- callbacks={'frodo': None}
+ model,
+ dataloader,
+ dataloader,
+ criterion,
+ optimizer,
+ scheduler,
+ configuration,
+ num_classes=3,
+ callbacks={'frodo': None},
)