Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add `torch.jit.script` support for `warp_affine` (#2588)

Jakub Filipek292b5be79d44
diff --git a/.gitignore b/.gitignore
index 8498662d8..5c595b07d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,3 +20,6 @@ kornia.egg-info/
*ipynb_checkpoints*
docs/source/_static/*jpg
*DS_Store
+
+# onnx tests create temp.onnx file
+*.onnx
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 28263270d..75b6bf225 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -4,6 +4,7 @@ import importlib
import math
import os
from pathlib import Path
+from typing import Optional
import cv2
import matplotlib as mpl
@@ -31,7 +32,7 @@ def download_tutorials_examples(download_infos: dict[str, str], directory: Path)
fp.write(response)
-def read_img_from_url(url: str, resize_to: tuple[int, int] | None = None, **resize_kwargs) -> torch.Tensor:
+def read_img_from_url(url: str, resize_to: Optional[tuple[int, int]] = None, **resize_kwargs) -> torch.Tensor:
# perform request
response = requests.get(url, timeout=60).content
# convert to array of ints
@@ -99,8 +100,8 @@ def main():
BASE_IMAGE_URL6: str = "https://raw.githubusercontent.com/kornia/data/main/delorean.png" # geometry
hash1 = '8b98f44abbe92b7a84631ed06613b08fee7dae14'
BASE_IMAGEOUTDOOR_URL7: str = f"https://github.com/kornia/data_test/raw/{hash1}/knchurch_disk.pt" # image matching
- BASE_IMAGEOUTDOOR_URL8: str = (
- "https://github.com/kornia/data/raw/main/kornia_banner_pixie.png" # Response functions
+ BASE_IMAGEOUTDOOR_URL8: str = ( # Response functions
+ "https://github.com/kornia/data/raw/main/kornia_banner_pixie.png"
)
MASK_IMAGE_URL2: str = "https://raw.githubusercontent.com/kornia/data/main/simba_mask.png"
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 58d83f5f4..282639482 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -69,9 +69,9 @@ class Resize(GeometricAugmentationBase2D):
input[i : i + 1, :, y1:y2, x1:x2],
out_size,
interpolation=flags["resample"].name.lower(),
- align_corners=flags["align_corners"]
- if flags["resample"] in [Resample.BILINEAR, Resample.BICUBIC]
- else None,
+ align_corners=(
+ flags["align_corners"] if flags["resample"] in [Resample.BILINEAR, Resample.BICUBIC] else None
+ ),
antialias=flags["antialias"],
)
return out
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
index 577f118ce..ec5c4aaf7 100644
--- a/kornia/augmentation/_2d/intensity/normalize.py
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Optional
import torch
from torch import Tensor
@@ -62,6 +62,6 @@ class Normalize(IntensityAugmentationBase2D):
self.flags = {"mean": mean, "std": std}
def apply_transform(
- self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Tensor | None = None
+ self, input: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
return normalize(input, flags["mean"], flags["std"])
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index ea61e3de7..83a1791db 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Optional
import torch
@@ -47,7 +47,7 @@ class RandomRain(IntensityAugmentationBase2D):
self._param_generator = RainGenerator(number_of_drops, drop_height, drop_width)
def apply_transform(
- self, image: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Tensor | None = None
+ self, image: Tensor, params: dict[str, Tensor], flags: dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
# Check array and drops size
KORNIA_CHECK(image.shape[1] in {3, 1}, "Number of color channels should be 1 or 3.")
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index 798a85a2f..3c3c4fde6 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any, Sequence
+from typing import Any, Optional, Sequence, Union
import torch
@@ -148,10 +148,10 @@ class RandomTransplantation(MixAugmentationBaseV2):
def __init__(
self,
- excluded_labels: Sequence[int] | Tensor | None = None,
+ excluded_labels: Optional[Union[Sequence[int], Tensor]] = None,
p: float = 0.5,
p_batch: float = 1.0,
- data_keys: list[str | int | DataKey] | None = None,
+ data_keys: Optional[list[str | int | DataKey]] = None,
) -> None:
super().__init__(p=p, p_batch=p_batch)
@@ -188,7 +188,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
*input: Tensor,
data_keys: list[DataKey],
params: dict[str, Tensor],
- extra_args: dict[DataKey, dict[str, Any]] | None = None,
+ extra_args: Optional[dict[DataKey, dict[str, Any]]] = None,
) -> dict[str, Tensor]:
"""Compute parameters for the transformation which are based on one or more input tensors.
@@ -217,12 +217,12 @@ class RandomTransplantation(MixAugmentationBaseV2):
if key == DataKey.INPUT:
KORNIA_CHECK(
_input.ndim == mask.ndim + 1,
- f"Every image input must have one additional dimension (channel dimension) than the segmentation "
+ "Every image input must have one additional dimension (channel dimension) than the segmentation "
f"mask, but got {_input.ndim} for the input image and {mask.ndim} for the segmentation mask.",
)
KORNIA_CHECK(
mask.size() == torch.Size([s for i, s in enumerate(_input.size()) if i != self._channel_dim]),
- f"The dimensions of the input image and segmentation mask must match except for the channel "
+ "The dimensions of the input image and segmentation mask must match except for the channel "
f"dimension, but got {_input.size()} for the input image and {mask.size()} for the segmentation "
"mask.",
)
@@ -277,8 +277,8 @@ class RandomTransplantation(MixAugmentationBaseV2):
def forward( # type: ignore[override]
self,
*input: Tensor,
- params: dict[str, Tensor] | None = None,
- data_keys: list[str | int | DataKey] | None = None,
+ params: Optional[dict[str, Tensor]] = None,
+ data_keys: Optional[list[str | int | DataKey]] = None,
**kwargs: dict[str, Any],
) -> Tensor | list[Tensor]:
keys: list[DataKey]
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 11e044a6b..3c15ac612 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -62,12 +62,12 @@ class BasicSequentialBase(nn.Sequential):
for item in atoms:
if not hasattr(mod, item):
- raise AttributeError(mod._get_name() + " has no " "attribute `" + item + "`")
+ raise AttributeError(mod._get_name() + " has no attribute `" + item + "`")
mod = getattr(mod, item)
if not isinstance(mod, Module):
- raise AttributeError("`" + item + "` is not " "an Module")
+ raise AttributeError("`" + item + "` is not an Module")
return mod
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 3d8694f1c..4bc93fadb 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -185,8 +185,7 @@ class InputSequentialOps(SequentialOpsInterface[Tensor]):
input = module.inverse(input, params=cls.get_instance_module_param(param), **extra_args)
elif isinstance(module, (K.GeometricAugmentationBase3D,)):
raise NotImplementedError(
- "The support for 3d inverse operations are not yet supported. "
- "You are welcome to file a PR in our repo."
+ "The support for 3d inverse operations are not yet supported. You are welcome to file a PR in our repo."
)
elif isinstance(module, (K.auto.operations.OperationBase,)):
return InputSequentialOps.inverse(input, module=module.op, param=param, extra_args=extra_args)
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index 2d1a2fba2..abcf5e496 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -94,9 +94,11 @@ class AffineGenerator(RandomGeneratorBase):
_shear = stack(
[
_range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
- tensor([0, 0], device=device, dtype=dtype)
- if shear.dim() == 0 or len(shear) == 2
- else _range_bound(shear[2:], 'shear-y', 0, (-360, 360)),
+ (
+ tensor([0, 0], device=device, dtype=dtype)
+ if shear.dim() == 0 or len(shear) == 2
+ else _range_bound(shear[2:], 'shear-y', 0, (-360, 360))
+ ),
]
)
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index 2aec8e311..be2fe7b16 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -49,9 +49,11 @@ class ShearGenerator(RandomGeneratorBase):
_shear = stack(
[
_range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
- tensor([0, 0], device=device, dtype=dtype)
- if shear.dim() == 0 or len(shear) == 2
- else _range_bound(shear[2:], 'shear-y', 0, (-360, 360)),
+ (
+ tensor([0, 0], device=device, dtype=dtype)
+ if shear.dim() == 0 or len(shear) == 2
+ else _range_bound(shear[2:], 'shear-y', 0, (-360, 360))
+ ),
]
)
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 3e8f03c82..79fe6151d 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -153,7 +153,7 @@ def _transform_output_shape(output: Tensor, shape: Tuple[int, ...]) -> Tensor:
for dim in range(len(out_tensor.shape) - len(shape)):
if out_tensor.shape[0] != 1:
- raise AssertionError(f'Dimension {dim} of input is ' f'expected to be 1, got {out_tensor.shape[0]}')
+ raise AssertionError(f'Dimension {dim} of input is expected to be 1, got {out_tensor.shape[0]}')
out_tensor = out_tensor.squeeze(0)
return out_tensor
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index f37f4e38c..0fd25f3ba 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
from kornia.color.rgb import bgr_to_rgb
@@ -32,7 +34,7 @@ def grayscale_to_rgb(image: Tensor) -> Tensor:
return concatenate([image, image, image], -3)
-def rgb_to_grayscale(image: Tensor, rgb_weights: Tensor | None = None) -> Tensor:
+def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Tensor:
r"""Convert a RGB image to grayscale version of image.
.. image:: _static/img/rgb_to_grayscale.png
@@ -144,7 +146,7 @@ class RgbToGrayscale(Module):
>>> output = gray(input) # 2x1x4x5
"""
- def __init__(self, rgb_weights: Tensor | None = None) -> None:
+ def __init__(self, rgb_weights: Optional[Tensor] = None) -> None:
super().__init__()
if rgb_weights is None:
rgb_weights = Tensor([0.299, 0.587, 0.114])
diff --git a/kornia/contrib/image_prompter.py b/kornia/contrib/image_prompter.py
index 8513574b6..678fd8cd4 100644
--- a/kornia/contrib/image_prompter.py
+++ b/kornia/contrib/image_prompter.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import warnings
-from typing import Any
+from typing import Any, Optional, Union
import torch
@@ -56,8 +56,8 @@ class ImagePrompter:
config: SamConfig = SamConfig(
model_type='vit_h', checkpoint='https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth'
),
- device: torch.device | None = None,
- dtype: torch.dtype | None = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> None:
super().__init__()
warnings.warn(
@@ -67,8 +67,8 @@ class ImagePrompter:
if isinstance(config, SamConfig):
self.model = Sam.from_config(config)
transforms = (LongestMaxSize(self.model.image_encoder.img_size, p=1.0),)
- self.pixel_mean: Tensor | None = tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
- self.pixel_std: Tensor | None = tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255
+ self.pixel_mean: Optional[Tensor] = tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
+ self.pixel_std: Optional[Tensor] = tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255
else:
raise NotImplementedError
@@ -82,7 +82,7 @@ class ImagePrompter:
self._input_encoder_size: None | tuple[int, int] = None
self.reset_image()
- def preprocess_image(self, x: Tensor, mean: Tensor | None = None, std: Tensor | None = None) -> Tensor:
+ def preprocess_image(self, x: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> Tensor:
"""Normalize and pad a tensor.
For normalize the tensor: will prioritize the `mean` and `std` passed as argument, if None will use the default
@@ -113,7 +113,7 @@ class ImagePrompter:
return x
@torch.no_grad()
- def set_image(self, image: Tensor, mean: Tensor | None = None, std: Tensor | None = None) -> None:
+ def set_image(self, image: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> None:
"""Set the embeddings from the given image with `image_decoder` of the model.
Prepare the given image with the selected transforms and the preprocess method.
@@ -177,10 +177,10 @@ class ImagePrompter:
def preprocess_prompts(
self,
- keypoints: Keypoints | Tensor | None = None,
- keypoints_labels: Tensor | None = None,
- boxes: Boxes | Tensor | None = None,
- masks: Tensor | None = None,
+ keypoints: Optional[Union[Keypoints, Tensor]] = None,
+ keypoints_labels: Optional[Tensor] = None,
+ boxes: Optional[Union[Boxes, Tensor]] = None,
+ masks: Optional[Tensor] = None,
) -> Prompts:
"""Validate and preprocess the given prompts to be aligned with the input image."""
data_keys = []
@@ -220,10 +220,10 @@ class ImagePrompter:
@torch.no_grad()
def predict(
self,
- keypoints: Keypoints | Tensor | None = None,
- keypoints_labels: Tensor | None = None,
- boxes: Boxes | Tensor | None = None,
- masks: Tensor | None = None,
+ keypoints: Optional[Union[Keypoints, Tensor]] = None,
+ keypoints_labels: Optional[Tensor] = None,
+ boxes: Optional[Union[Boxes, Tensor]] = None,
+ masks: Optional[Tensor] = None,
multimask_output: bool = True,
output_original_size: bool = True,
) -> SegmentationResults:
@@ -297,7 +297,7 @@ class ImagePrompter:
fullgraph: bool = False,
dynamic: bool = False,
backend: str = 'inductor',
- mode: str | None = None,
+ mode: Optional[str] = None,
options: dict[Any, Any] = {},
disable: bool = False,
) -> None:
diff --git a/kornia/contrib/models/base.py b/kornia/contrib/models/base.py
index 60f28a770..9a62c3cff 100644
--- a/kornia/contrib/models/base.py
+++ b/kornia/contrib/models/base.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import os
from abc import ABC, abstractmethod
-from typing import Any, Generic, TypeVar, cast
+from typing import Any, Generic, Optional, TypeVar, cast
import torch
@@ -14,7 +14,7 @@ ModelConfig = TypeVar('ModelConfig')
class ModelBase(ABC, Module, Generic[ModelConfig]):
"""Abstract model class with some utilities function."""
- def load_checkpoint(self, checkpoint: str, device: torch.device | None = None) -> None:
+ def load_checkpoint(self, checkpoint: str, device: Optional[torch.device] = None) -> None:
"""Load checkpoint from a given url or file.
Args:
@@ -46,7 +46,7 @@ class ModelBase(ABC, Module, Generic[ModelConfig]):
fullgraph: bool = False,
dynamic: bool = False,
backend: str = 'inductor',
- mode: str | None = None,
+ mode: Optional[str] = None,
options: dict[Any, Any] = {},
disable: bool = False,
) -> ModelBase[ModelConfig]:
diff --git a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
index b88be95ee..3e61aad10 100644
--- a/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
+++ b/kornia/contrib/models/rt_detr/architecture/hybrid_encoder.py
@@ -4,6 +4,8 @@ ppdet/modeling/transformers/hybrid_encoder.py."""
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
from torch import nn
@@ -19,7 +21,7 @@ class RepVggBlock(Module):
self.conv1 = ConvNormAct(in_channels, out_channels, 3, act="none")
self.conv2 = ConvNormAct(in_channels, out_channels, 1, act="none")
self.act = nn.SiLU(inplace=True)
- self.conv: nn.Conv2d | None = None
+ self.conv: Optional[nn.Conv2d] = None
def forward(self, x: Tensor) -> Tensor:
if self.conv is not None:
@@ -112,8 +114,8 @@ class AIFI(Module):
h: int,
embed_dim: int,
temp: float = 10_000.0,
- device: torch.device | None = None,
- dtype: torch.dtype | None = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> Tensor:
"""Construct 2D sin-cos positional embeddings.
diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
index f2cda4cb0..1ff571eeb 100644
--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
@@ -3,6 +3,8 @@
from __future__ import annotations
+from typing import Optional
+
import torch
from torch import nn
@@ -168,10 +170,10 @@ class TransformerDecoderLayer(Module):
ref_points: Tensor,
memory: Tensor,
memory_spatial_shapes: list[tuple[int, int]],
- memory_level_start_index: list[int] | None = None,
- attn_mask: Tensor | None = None,
- memory_mask: Tensor | None = None,
- query_pos_embed: Tensor | None = None,
+ memory_level_start_index: Optional[list[int]] = None,
+ attn_mask: Optional[Tensor] = None,
+ memory_mask: Optional[Tensor] = None,
+ query_pos_embed: Optional[Tensor] = None,
) -> Tensor:
# TODO: rename variables because is confusing
# self attention
@@ -211,8 +213,8 @@ class TransformerDecoder:
bbox_head: nn.ModuleList,
score_head: nn.ModuleList,
query_pos_head: nn.Module,
- attn_mask: Tensor | None = None,
- memory_mask: Tensor | None = None,
+ attn_mask: Optional[Tensor] = None,
+ memory_mask: Optional[Tensor] = None,
) -> tuple[Tensor, Tensor]:
output: Tensor = tgt
dec_out_bboxes: list[Tensor] = []
@@ -381,8 +383,8 @@ class RTDETRHead(Module):
self,
memory: Tensor,
spatial_shapes: list[tuple[int, int]],
- denoising_class: Tensor | None = None,
- denoising_bbox_unact: Tensor | None = None,
+ denoising_class: Optional[Tensor] = None,
+ denoising_bbox_unact: Optional[Tensor] = None,
) -> tuple[Tensor, Tensor, Tensor, Tensor]:
# prepare input for decoder
# TODO: cache anchors and valid_mask as buffers
@@ -423,8 +425,8 @@ class RTDETRHead(Module):
spatial_shapes: list[tuple[int, int]],
grid_size: float = 0.05,
eps: float = 0.01,
- device: torch.device | None = None,
- dtype: torch.dtype | None = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> tuple[Tensor, Tensor]:
"""Generate anchors for RT-DETR.
diff --git a/kornia/contrib/models/rt_detr/model.py b/kornia/contrib/models/rt_detr/model.py
index c64154af9..1f250c77a 100644
--- a/kornia/contrib/models/rt_detr/model.py
+++ b/kornia/contrib/models/rt_detr/model.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
+from typing import Optional
from kornia.contrib.models.base import ModelBase
from kornia.contrib.models.rt_detr.architecture.hgnetv2 import PPHGNetV2
@@ -50,14 +51,14 @@ class RTDETRConfig:
model_type: RTDETRModelType | str | int
num_classes: int
- checkpoint: str | None = None
+ checkpoint: Optional[str] = None
- neck_hidden_dim: int | None = None
- neck_dim_feedforward: int | None = None
- neck_expansion: float | None = None
+ neck_hidden_dim: Optional[int] = None
+ neck_dim_feedforward: Optional[int] = None
+ neck_expansion: Optional[float] = None
head_hidden_dim: int = 256
head_num_queries: int = 300
- head_num_decoder_layers: int | None = None
+ head_num_decoder_layers: Optional[int] = None
confidence_threshold: float = 0.3
diff --git a/kornia/contrib/models/sam/architecture/image_encoder.py b/kornia/contrib/models/sam/architecture/image_encoder.py
index 714c8d869..8085a7484 100644
--- a/kornia/contrib/models/sam/architecture/image_encoder.py
+++ b/kornia/contrib/models/sam/architecture/image_encoder.py
@@ -5,6 +5,8 @@ anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling
"""
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
from torch import nn
@@ -64,7 +66,7 @@ class ImageEncoderViT(Module):
embed_dim=embed_dim,
)
- self.pos_embed: nn.Parameter | None = None
+ self.pos_embed: Optional[nn.Parameter] = None
if use_abs_pos:
# Initialize absolute positional embedding with pretrain image size.
self.pos_embed = nn.Parameter(zeros(1, img_size // patch_size, img_size // patch_size, embed_dim))
@@ -119,7 +121,7 @@ class Block(Module):
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
window_size: int = 0,
- input_size: tuple[int, int] | None = None,
+ input_size: Optional[tuple[int, int]] = None,
) -> None:
"""
Args:
@@ -179,7 +181,7 @@ class Attention(Module):
qkv_bias: bool = True,
use_rel_pos: bool = False,
rel_pos_zero_init: bool = True,
- input_size: tuple[int, int] | None = None,
+ input_size: Optional[tuple[int, int]] = None,
) -> None:
"""
Args:
diff --git a/kornia/contrib/models/sam/architecture/prompt_encoder.py b/kornia/contrib/models/sam/architecture/prompt_encoder.py
index 228ec2eef..5398ec169 100644
--- a/kornia/contrib/models/sam/architecture/prompt_encoder.py
+++ b/kornia/contrib/models/sam/architecture/prompt_encoder.py
@@ -6,6 +6,7 @@ anything/blob/3518c86b78b3bc9cf4fbe3d18e682fad1c79dc51/segment_anything/modeling
from __future__ import annotations
from math import pi
+from typing import Optional
import torch
from torch import nn
@@ -93,7 +94,9 @@ class PromptEncoder(Module):
mask_embedding = self.mask_downscaling(masks)
return mask_embedding
- def _get_batch_size(self, points: tuple[Tensor, Tensor] | None, boxes: Tensor | None, masks: Tensor | None) -> int:
+ def _get_batch_size(
+ self, points: Optional[tuple[Tensor, Tensor]], boxes: Optional[Tensor], masks: Optional[Tensor]
+ ) -> int:
"""Gets the batch size of the output given the batch size of the input prompts."""
if points is not None:
return points[0].shape[0]
@@ -108,7 +111,7 @@ class PromptEncoder(Module):
return self.point_embeddings[0].weight.device
def forward(
- self, points: tuple[Tensor, Tensor] | None, boxes: Tensor | None, masks: Tensor | None
+ self, points: Optional[tuple[Tensor, Tensor]], boxes: Optional[Tensor], masks: Optional[Tensor]
) -> tuple[Tensor, Tensor]:
"""Embeds different types of prompts, returning both sparse and dense embeddings.
@@ -145,7 +148,7 @@ class PromptEncoder(Module):
class PositionEmbeddingRandom(Module):
"""Positional encoding using random spatial frequencies."""
- def __init__(self, num_pos_feats: int = 64, scale: float | None = None) -> None:
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
super().__init__()
if scale is None or scale <= 0.0:
scale = 1.0
diff --git a/kornia/contrib/models/sam/model.py b/kornia/contrib/models/sam/model.py
index 8a072156c..acb670124 100644
--- a/kornia/contrib/models/sam/model.py
+++ b/kornia/contrib/models/sam/model.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import warnings
from dataclasses import dataclass
from enum import Enum
-from typing import Any
+from typing import Any, Optional
import torch
@@ -55,14 +55,14 @@ class SamConfig:
encoder_global_attn_indexes: Encoder indexes for blocks using global attention.
"""
- model_type: str | int | SamModelType | None = None
- checkpoint: str | None = None
+ model_type: Optional[str | int | SamModelType] = None
+ checkpoint: Optional[str] = None
pretrained: bool = False
- encoder_embed_dim: int | None = None
- encoder_depth: int | None = None
- encoder_num_heads: int | None = None
- encoder_global_attn_indexes: tuple[int, ...] | None = None
+ encoder_embed_dim: Optional[int] = None
+ encoder_depth: Optional[int] = None
+ encoder_num_heads: Optional[int] = None
+ encoder_global_attn_indexes: Optional[tuple[int, ...]] = None
class Sam(ModelBase[SamConfig]):
diff --git a/kornia/contrib/models/structures.py b/kornia/contrib/models/structures.py
index f5e2b313b..31825e1b1 100644
--- a/kornia/contrib/models/structures.py
+++ b/kornia/contrib/models/structures.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from dataclasses import dataclass
+from typing import Optional
from kornia.core import Tensor
from kornia.core.check import KORNIA_CHECK
@@ -39,7 +40,7 @@ class SegmentationResults:
return x > self.mask_threshold
def original_res_logits(
- self, input_size: tuple[int, int], original_size: tuple[int, int], image_size_encoder: tuple[int, int] | None
+ self, input_size: tuple[int, int], original_size: tuple[int, int], image_size_encoder: Optional[tuple[int, int]]
) -> Tensor:
"""Remove padding and upscale the logits to the original image size.
@@ -88,20 +89,20 @@ class Prompts:
masks: Batched mask prompts to the model with shape :math:`(K, 1, H, W)`
"""
- points: tuple[Tensor, Tensor] | None = None
- boxes: Tensor | None = None
- masks: Tensor | None = None
+ points: Optional[tuple[Tensor, Tensor]] = None
+ boxes: Optional[Tensor] = None
+ masks: Optional[Tensor] = None
def __post_init__(self) -> None:
if isinstance(self.keypoints, Tensor) and isinstance(self.boxes, Tensor):
KORNIA_CHECK(self.keypoints.shape[0] == self.boxes.shape[0], 'The prompts should have the same batch size!')
@property
- def keypoints(self) -> Tensor | None:
+ def keypoints(self) -> Optional[Tensor]:
"""The keypoints from the `points`"""
return self.points[0] if isinstance(self.points, tuple) else None
@property
- def keypoints_labels(self) -> Tensor | None:
+ def keypoints_labels(self) -> Optional[Tensor]:
"""The keypoints labels from the `points`"""
return self.points[1] if isinstance(self.points, tuple) else None
diff --git a/kornia/contrib/models/tiny_vit.py b/kornia/contrib/models/tiny_vit.py
index 0fbf50786..d2d51a078 100644
--- a/kornia/contrib/models/tiny_vit.py
+++ b/kornia/contrib/models/tiny_vit.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import itertools
import warnings
-from typing import Any
+from typing import Any, Optional
import torch
import torch.nn.functional as F
@@ -98,7 +98,7 @@ class ConvLayer(Module):
depth: int,
activation: type[Module] = nn.GELU,
drop_path: float | list[float] = 0.0,
- downsample: Module | None = None,
+ downsample: Optional[Module] = None,
use_checkpoint: bool = False,
conv_expand_ratio: float = 4.0,
) -> None:
@@ -171,7 +171,7 @@ class Attention(Module):
self.attention_biases = nn.Parameter(torch.zeros(num_heads, attn_offset_size))
self.register_buffer('attention_bias_idxs', indices, persistent=False)
self.attention_bias_idxs: Tensor
- self.ab: Tensor | None = None
+ self.ab: Optional[Tensor] = None
@staticmethod
def build_attention_bias(resolution: tuple[int, int]) -> tuple[Tensor, int]:
@@ -270,7 +270,7 @@ class BasicLayer(Module):
mlp_ratio: float = 4.0,
drop: float = 0.0,
drop_path: float | list[float] = 0.0,
- downsample: Module | None = None,
+ downsample: Optional[Module] = None,
use_checkpoint: bool = False,
local_conv_size: int = 3,
activation: type[Module] = nn.GELU,
@@ -349,7 +349,7 @@ class TinyViT(Module):
super().__init__()
self.img_size = img_size
self.mobile_sam = mobile_sam
- self.neck: Module | None
+ self.neck: Optional[Module]
if mobile_sam:
# MobileSAM adjusts the stride to match the total stride of other ViT backbones
# used in the original SAM (stride 16)
@@ -498,7 +498,9 @@ def _tiny_vit_5m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
pretrained = "in1k"
url = {
- "in22k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.pth",
+ "in22k": (
+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22k_distill.pth"
+ ),
"in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_5m_22kto1k_distill.pth",
}[pretrained]
model = _load_pretrained(model, url)
@@ -521,7 +523,9 @@ def _tiny_vit_11m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
pretrained = "in1k"
url = {
- "in22k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.pth",
+ "in22k": (
+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22k_distill.pth"
+ ),
"in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_11m_22kto1k_distill.pth",
}[pretrained]
model = _load_pretrained(model, url)
@@ -549,7 +553,9 @@ def _tiny_vit_21m(pretrained: bool | str = False, **kwargs: Any) -> TinyViT:
pretrained = "in1k_512"
url = {
- "in22k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.pth",
+ "in22k": (
+ "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22k_distill.pth"
+ ),
"in1k": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_distill.pth",
"in1k_384": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_384_distill.pth",
"in1k_512": "https://github.com/wkcn/TinyViT-model-zoo/releases/download/checkpoints/tiny_vit_21m_22kto1k_512_distill.pth",
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 55821b98a..70e6ddb2a 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -2,6 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
+from typing import Optional
import torch
@@ -165,8 +166,8 @@ class ObjectDetector(Module):
fullgraph: bool = False,
dynamic: bool = False,
backend: str = 'inductor',
- mode: str | None = None,
- options: dict[str, str | int | bool] | None = None,
+ mode: Optional[str] = None,
+ options: Optional[dict[str, str | int | bool]] = None,
disable: bool = False,
) -> None:
"""Compile the internal object detection model with :py:func:`torch.compile()`."""
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 7a1afe060..729642784 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Optional
import torch
@@ -53,15 +53,15 @@ class VisualPrompter:
def __init__(
self,
config: SamConfig = SamConfig(model_type='vit_h', pretrained=True),
- device: torch.device | None = None,
- dtype: torch.dtype | None = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> None:
super().__init__()
if isinstance(config, SamConfig):
self.model = Sam.from_config(config)
transforms = (LongestMaxSize(self.model.image_encoder.img_size, p=1.0),)
- self.pixel_mean: Tensor | None = tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
- self.pixel_std: Tensor | None = tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255
+ self.pixel_mean: Optional[Tensor] = tensor([123.675, 116.28, 103.53], device=device, dtype=dtype) / 255
+ self.pixel_std: Optional[Tensor] = tensor([58.395, 57.12, 57.375], device=device, dtype=dtype) / 255
else:
raise NotImplementedError
@@ -75,7 +75,7 @@ class VisualPrompter:
self._input_encoder_size: None | tuple[int, int] = None
self.reset_image()
- def preprocess_image(self, x: Tensor, mean: Tensor | None = None, std: Tensor | None = None) -> Tensor:
+ def preprocess_image(self, x: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> Tensor:
"""Normalize and pad a tensor.
For normalize the tensor: will prioritize the `mean` and `std` passed as argument, if None will use the default
@@ -106,7 +106,7 @@ class VisualPrompter:
return x
@torch.no_grad()
- def set_image(self, image: Tensor, mean: Tensor | None = None, std: Tensor | None = None) -> None:
+ def set_image(self, image: Tensor, mean: Optional[Tensor] = None, std: Optional[Tensor] = None) -> None:
"""Set the embeddings from the given image with `image_decoder` of the model.
Prepare the given image with the selected transforms and the preprocess method.
@@ -170,10 +170,10 @@ class VisualPrompter:
def preprocess_prompts(
self,
- keypoints: Keypoints | Tensor | None = None,
- keypoints_labels: Tensor | None = None,
- boxes: Boxes | Tensor | None = None,
- masks: Tensor | None = None,
+ keypoints: Optional[Keypoints | Tensor] = None,
+ keypoints_labels: Optional[Tensor] = None,
+ boxes: Optional[Boxes | Tensor] = None,
+ masks: Optional[Tensor] = None,
) -> Prompts:
"""Validate and preprocess the given prompts to be aligned with the input image."""
data_keys = []
@@ -213,10 +213,10 @@ class VisualPrompter:
@torch.no_grad()
def predict(
self,
- keypoints: Keypoints | Tensor | None = None,
- keypoints_labels: Tensor | None = None,
- boxes: Boxes | Tensor | None = None,
- masks: Tensor | None = None,
+ keypoints: Optional[Keypoints | Tensor] = None,
+ keypoints_labels: Optional[Tensor] = None,
+ boxes: Optional[Boxes | Tensor] = None,
+ masks: Optional[Tensor] = None,
multimask_output: bool = True,
output_original_size: bool = True,
) -> SegmentationResults:
@@ -290,7 +290,7 @@ class VisualPrompter:
fullgraph: bool = False,
dynamic: bool = False,
backend: str = 'inductor',
- mode: str | None = None,
+ mode: Optional[str] = None,
options: dict[Any, Any] = {},
disable: bool = False,
) -> None:
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index ee9cd89e6..614c30ac6 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -221,8 +221,7 @@ class VisionTransformer(Module):
if self.image_size not in (*x.shape[-2:],) and x.shape[-3] != self.in_channels:
raise ValueError(
- f"Input image shape must be Bx{self.in_channels}x{self.image_size}x{self.image_size}. "
- f"Got: {x.shape}"
+ f"Input image shape must be Bx{self.in_channels}x{self.image_size}x{self.image_size}. Got: {x.shape}"
)
out = self.patch_embedding(x)
diff --git a/kornia/core/check.py b/kornia/core/check.py
index c72a258f3..7ead855f5 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -1,7 +1,7 @@
"""The testing package contains testing-specific utilities."""
from __future__ import annotations
-from typing import Any, Sequence, TypeVar, cast
+from typing import Any, Optional, Sequence, TypeVar, cast
from torch import float16, float32, float64
from typing_extensions import TypeGuard
@@ -82,7 +82,7 @@ def KORNIA_CHECK_SHAPE(x: Tensor, shape: list[str], raises: bool = True) -> bool
return True
-def KORNIA_CHECK(condition: bool, msg: str | None = None, raises: bool = True) -> bool:
+def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check any arbitrary boolean condition.
Args:
@@ -120,7 +120,9 @@ T = TypeVar('T', bound=type)
# TODO: fix mypy typeguard issue
-def KORNIA_CHECK_TYPE(x: object, typ: T | tuple[T, ...], msg: str | None = None, raises: bool = True) -> TypeGuard[T]:
+def KORNIA_CHECK_TYPE(
+ x: object, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True
+) -> TypeGuard[T]:
"""Check the type of an aribratry variable.
Args:
@@ -144,7 +146,7 @@ def KORNIA_CHECK_TYPE(x: object, typ: T | tuple[T, ...], msg: str | None = None,
return True
-def KORNIA_CHECK_IS_TENSOR(x: object, msg: str | None = None, raises: bool = True) -> TypeGuard[Tensor]:
+def KORNIA_CHECK_IS_TENSOR(x: object, msg: Optional[str] = None, raises: bool = True) -> TypeGuard[Tensor]:
"""Check the input variable is a Tensor.
Args:
@@ -168,7 +170,7 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: str | None = None, raises: bool = Tru
return True
-def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Sequence[object] | None, raises: bool = True) -> TypeGuard[list[Tensor]]:
+def KORNIA_CHECK_IS_LIST_OF_TENSOR(x: Optional[Sequence[object]], raises: bool = True) -> TypeGuard[list[Tensor]]:
"""Check the input variable is a List of Tensors.
Args:
@@ -221,7 +223,7 @@ def KORNIA_CHECK_SAME_DEVICE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
return True
-def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: str | None = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_SAME_DEVICES(tensors: list[Tensor], msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether a list provided tensors live in the same device.
Args:
@@ -271,7 +273,7 @@ def KORNIA_CHECK_SAME_SHAPE(x: Tensor, y: Tensor, raises: bool = True) -> bool:
return True
-def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: str | None = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is a color images.
Args:
@@ -294,7 +296,7 @@ def KORNIA_CHECK_IS_COLOR(x: Tensor, msg: str | None = None, raises: bool = True
return True
-def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: str | None = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is grayscale.
Args:
@@ -317,7 +319,7 @@ def KORNIA_CHECK_IS_GRAY(x: Tensor, msg: str | None = None, raises: bool = True)
return True
-def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: str | None = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is grayscale or color.
Args:
@@ -340,7 +342,7 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: Tensor, msg: str | None = None, raises: boo
return True
-def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: str | None = None, raises: bool = True, bits: int = 8) -> bool:
+def KORNIA_CHECK_IS_IMAGE(x: Tensor, msg: Optional[str] = None, raises: bool = True, bits: int = 8) -> bool:
"""Check whether an image tensor is ranged properly [0, 1] for float or [0, 2 ** bits] for int.
Args:
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index b4df2cb45..bb52313ce 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -117,8 +117,7 @@ class ResNet(Module):
replace_stride_with_dilation = [False, False, False]
if len(replace_stride_with_dilation) != 3:
raise ValueError(
- "replace_stride_with_dilation should be None "
- f"or a 3-element tuple, got {replace_stride_with_dilation}"
+ f"replace_stride_with_dilation should be None or a 3-element tuple, got {replace_stride_with_dilation}"
)
self.groups = groups
self.base_width = width_per_group
diff --git a/kornia/feature/disk/detector.py b/kornia/feature/disk/detector.py
index 45bb5908e..1a9792cc8 100644
--- a/kornia/feature/disk/detector.py
+++ b/kornia/feature/disk/detector.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
@@ -25,7 +27,7 @@ def nms(signal: Tensor, window_size: int = 5, cutoff: float = 0.0) -> Tensor:
def heatmap_to_keypoints(
- heatmap: Tensor, n: int | None = None, window_size: int = 5, score_threshold: float = 0.0
+ heatmap: Tensor, n: Optional[int] = None, window_size: int = 5, score_threshold: float = 0.0
) -> list[Keypoints]:
"""Inference-time nms-based detection protocol."""
heatmap = heatmap.squeeze(1)
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index 0880f3712..607035233 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
from kornia.core import Module, Tensor
@@ -65,7 +67,7 @@ class DISK(Module):
def forward(
self,
images: Tensor,
- n: int | None = None,
+ n: Optional[int] = None,
window_size: int = 5,
score_threshold: float = 0.0,
pad_if_not_divisible: bool = False,
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 4fa03d9fa..68c5f499b 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -83,8 +83,7 @@ class Attention(Module):
super().__init__()
if allow_flash and not FLASH_AVAILABLE:
warnings.warn(
- 'FlashAttention is not available. For optimal speed, '
- 'consider installing torch >= 2.0 or flash-attn.',
+ 'FlashAttention is not available. For optimal speed, consider installing torch >= 2.0 or flash-attn.',
stacklevel=2,
)
self.enable_flash = allow_flash and FLASH_AVAILABLE
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 9f77c3159..65340ba2b 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Any
+from typing import Any, Optional
import torch
@@ -76,7 +76,7 @@ class LoFTR(Module):
>>> out = loftr(input)
"""
- def __init__(self, pretrained: str | None = 'outdoor', config: dict[str, Any] = default_cfg) -> None:
+ def __init__(self, pretrained: Optional[str] = 'outdoor', config: dict[str, Any] = default_cfg) -> None:
super().__init__()
# Misc
self.config = config
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index fe16b106c..2468634f8 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import copy
-from typing import Any, Literal
+from typing import Any, Literal, Optional
import torch
from torch import nn
@@ -12,7 +12,7 @@ from .linear_attention import FullAttention, LinearAttention
class LoFTREncoderLayer(Module):
- def __init__(self, d_model: int, nhead: int, attention: Literal['linear'] | None = 'linear') -> None:
+ def __init__(self, d_model: int, nhead: int, attention: Optional[Literal['linear']] = 'linear') -> None:
super().__init__()
self.dim = d_model // nhead
@@ -35,7 +35,7 @@ class LoFTREncoderLayer(Module):
self.norm2 = nn.LayerNorm(d_model)
def forward(
- self, x: Tensor, source: Tensor, x_mask: Tensor | None = None, source_mask: Tensor | None = None
+ self, x: Tensor, source: Tensor, x_mask: Optional[Tensor] = None, source_mask: Optional[Tensor] = None
) -> Tensor:
"""
Args:
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index ec794ab2d..383fff6de 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -155,13 +155,7 @@ class VonMisesKernel(nn.Module):
return embedding
def __repr__(self) -> str:
- return (
- f"{self.__class__.__name__}("
- f"patch_size={self.patch_size}, "
- f"n={self.n}, "
- f"d={self.d}, "
- f"coeffs={self.coeffs})"
- )
+ return f"{self.__class__.__name__}(patch_size={self.patch_size}, n={self.n}, d={self.d}, coeffs={self.coeffs})"
class EmbedGradients(nn.Module):
@@ -466,12 +460,7 @@ class Whitening(nn.Module):
return F.normalize(x, dim=1)
def __repr__(self) -> str:
- return (
- f'{self.__class__.__name__}('
- f'xform={self.xform}, '
- f'in_dims={self.in_dims}, '
- f'output_dims={self.output_dims})'
- )
+ return f'{self.__class__.__name__}(xform={self.xform}, in_dims={self.in_dims}, output_dims={self.output_dims})'
class MKDDescriptor(nn.Module):
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 6a02ec66b..7b237f99f 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -56,10 +56,7 @@ class PatchDominantGradientOrientation(nn.Module):
def __repr__(self) -> str:
return (
- f'{self.__class__.__name__}('
- f'patch_size={self.patch_size}, '
- f'num_ang_bins={self.num_ang_bins}, '
- f'eps={self.eps})'
+ f'{self.__class__.__name__}(patch_size={self.patch_size}, num_ang_bins={self.num_ang_bins}, eps={self.eps})'
)
def forward(self, patch: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 3c4ab2206..f3eb85d33 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -48,10 +48,9 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tup
out_size: int = (patch_size + 2 * pad - (ksize - 1) - 1) // stride + 1
if out_size != num_spatial_bins:
raise ValueError(
- f"Patch size {patch_size} is incompatible with \
- requested number of spatial bins {num_spatial_bins} \
- for SIFT descriptor. Usually it happens when patch size is too small\
- for num_spatial_bins specified"
+ f"Patch size {patch_size} is incompatible with requested number of spatial bins"
+ f" {num_spatial_bins} for SIFT descriptor. Usually it happens when patch size is too small "
+ " for num_spatial_bins specified"
)
return ksize, stride, pad
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index c75af80ad..ae1d5d3db 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
from kornia.core import Module, Tensor, pad
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
@@ -9,7 +11,7 @@ from .median import _compute_zero_padding
def _bilateral_blur(
input: Tensor,
- guidance: Tensor | None,
+ guidance: Optional[Tensor],
kernel_size: tuple[int, int] | int,
sigma_color: float | Tensor,
sigma_space: tuple[float, float] | Tensor,
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 0cc61b76b..63b3567a8 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections import OrderedDict
+from typing import Optional
import torch
import torch.nn.functional as F
@@ -148,7 +149,7 @@ class DoubleConvBlock(nn.Sequential):
self,
in_features: int,
mid_features: int,
- out_features: int | None = None,
+ out_features: Optional[int] = None,
stride: int = 1,
use_act: bool = True,
) -> None:
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 529e5cb41..2639c0e39 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import math
from math import sqrt
-from typing import Any
+from typing import Any, Optional
import torch
@@ -60,7 +60,7 @@ def normalize_kernel2d(input: Tensor) -> Tensor:
def gaussian(
- window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: Dtype | None = None
+ window_size: int, sigma: Tensor | float, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
"""Compute the gaussian values based on the window and sigma values.
@@ -91,7 +91,7 @@ def gaussian(
def gaussian_discrete_erf(
- window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: Dtype | None = None
+ window_size: int, sigma: Tensor | float, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
r"""Discrete Gaussian by interpolating the error function.
@@ -218,7 +218,7 @@ def _modified_bessel_i(n: int, x: Tensor) -> Tensor:
def gaussian_discrete(
- window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: Dtype | None = None
+ window_size: int, sigma: Tensor | float, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
r"""Discrete Gaussian kernel based on the modified Bessel functions.
@@ -251,7 +251,7 @@ def gaussian_discrete(
return out / out.sum(-1, keepdim=True)
-def laplacian_1d(window_size: int, *, device: Device | None = None, dtype: Dtype = torch.float32) -> Tensor:
+def laplacian_1d(window_size: int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32) -> Tensor:
"""One could also use the Laplacian of Gaussian formula to design the filter."""
# TODO: add default dtype as None when kornia relies on torch > 1.12
filter_1d = torch.ones(window_size, device=device, dtype=dtype)
@@ -260,7 +260,7 @@ def laplacian_1d(window_size: int, *, device: Device | None = None, dtype: Dtype
return filter_1d
-def get_box_kernel1d(kernel_size: int, *, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_box_kernel1d(kernel_size: int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
r"""Utility function that returns a 1-D box filter.
Args:
@@ -276,7 +276,7 @@ def get_box_kernel1d(kernel_size: int, *, device: Device | None = None, dtype: D
def get_box_kernel2d(
- kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: Dtype | None = None
+ kernel_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
r"""Utility function that returns a 2-D box filter.
@@ -294,7 +294,7 @@ def get_box_kernel2d(
def get_binary_kernel2d(
- window_size: tuple[int, int] | int, *, device: Device | None = None, dtype: Dtype = torch.float32
+ window_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
) -> Tensor:
"""Create a binary kernel to extract the patches.
@@ -312,12 +312,12 @@ def get_binary_kernel2d(
return kernel.view(window_range, 1, ky, kx)
-def get_sobel_kernel_3x3(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_sobel_kernel_3x3(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns a sobel kernel of 3x3."""
return tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype)
-def get_sobel_kernel_5x5_2nd_order(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_sobel_kernel_5x5_2nd_order(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5."""
return tensor(
[
@@ -332,7 +332,7 @@ def get_sobel_kernel_5x5_2nd_order(*, device: Device | None = None, dtype: Dtype
)
-def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5."""
return tensor(
[
@@ -347,12 +347,12 @@ def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Device | None = None, dtype: D
)
-def get_diff_kernel_3x3(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_diff_kernel_3x3(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3."""
return tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]], device=device, dtype=dtype)
-def get_diff_kernel3d(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_diff_kernel3d(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3."""
kernel = tensor(
[
@@ -378,7 +378,7 @@ def get_diff_kernel3d(device: Device | None = None, dtype: Dtype | None = None)
return kernel[:, None, ...]
-def get_diff_kernel3d_2nd_order(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_diff_kernel3d_2nd_order(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3."""
kernel = tensor(
[
@@ -419,26 +419,26 @@ def get_diff_kernel3d_2nd_order(device: Device | None = None, dtype: Dtype | Non
return kernel[:, None, ...]
-def get_sobel_kernel2d(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_sobel_kernel2d(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
kernel_x = get_sobel_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
return stack([kernel_x, kernel_y])
-def get_diff_kernel2d(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_diff_kernel2d(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
kernel_x = get_diff_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
return stack([kernel_x, kernel_y])
-def get_sobel_kernel2d_2nd_order(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_sobel_kernel2d_2nd_order(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
gxx = get_sobel_kernel_5x5_2nd_order(device=device, dtype=dtype)
gyy = gxx.transpose(0, 1)
gxy = _get_sobel_kernel_5x5_2nd_order_xy(device=device, dtype=dtype)
return stack([gxx, gxy, gyy])
-def get_diff_kernel2d_2nd_order(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_diff_kernel2d_2nd_order(*, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
gxx = tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype)
gyy = gxx.transpose(0, 1)
gxy = tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]], device=device, dtype=dtype)
@@ -446,7 +446,7 @@ def get_diff_kernel2d_2nd_order(*, device: Device | None = None, dtype: Dtype |
def get_spatial_gradient_kernel2d(
- mode: str, order: int, *, device: Device | None = None, dtype: Dtype | None = None
+ mode: str, order: int, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order image gradients, using one of the following operators:
@@ -470,7 +470,7 @@ def get_spatial_gradient_kernel2d(
def get_spatial_gradient_kernel3d(
- mode: str, order: int, device: Device | None = None, dtype: Dtype | None = None
+ mode: str, order: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the following
operators: sobel, diff."""
@@ -492,8 +492,8 @@ def get_gaussian_kernel1d(
sigma: float | Tensor,
force_even: bool = False,
*,
- device: Device | None = None,
- dtype: Dtype | None = None,
+ device: Optional[Device] = None,
+ dtype: Optional[Dtype] = None,
) -> Tensor:
r"""Function that returns Gaussian filter coefficients.
@@ -526,8 +526,8 @@ def get_gaussian_discrete_kernel1d(
sigma: float | Tensor,
force_even: bool = False,
*,
- device: Device | None = None,
- dtype: Dtype | None = None,
+ device: Optional[Device] = None,
+ dtype: Optional[Dtype] = None,
) -> Tensor:
"""Function that returns Gaussian filter coefficients based on the modified Bessel functions.
@@ -562,8 +562,8 @@ def get_gaussian_erf_kernel1d(
sigma: float | Tensor,
force_even: bool = False,
*,
- device: Device | None = None,
- dtype: Dtype | None = None,
+ device: Optional[Device] = None,
+ dtype: Optional[Dtype] = None,
) -> Tensor:
"""Function that returns Gaussian filter coefficients by interpolating the error function.
@@ -598,8 +598,8 @@ def get_gaussian_kernel2d(
sigma: tuple[float, float] | Tensor,
force_even: bool = False,
*,
- device: Device | None = None,
- dtype: Dtype | None = None,
+ device: Optional[Device] = None,
+ dtype: Optional[Dtype] = None,
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
@@ -654,8 +654,8 @@ def get_gaussian_kernel3d(
sigma: tuple[float, float, float] | Tensor,
force_even: bool = False,
*,
- device: Device | None = None,
- dtype: Dtype | None = None,
+ device: Optional[Device] = None,
+ dtype: Optional[Dtype] = None,
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
@@ -708,7 +708,9 @@ def get_gaussian_kernel3d(
return kernel_z.view(-1, ksize_z, 1, 1) * kernel_y.view(-1, 1, ksize_y, 1) * kernel_x.view(-1, 1, 1, ksize_x)
-def get_laplacian_kernel1d(kernel_size: int, *, device: Device | None = None, dtype: Dtype = torch.float32) -> Tensor:
+def get_laplacian_kernel1d(
+ kernel_size: int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
+) -> Tensor:
r"""Function that returns the coefficients of a 1D Laplacian filter.
Args:
@@ -736,7 +738,7 @@ def get_laplacian_kernel1d(kernel_size: int, *, device: Device | None = None, dt
def get_laplacian_kernel2d(
- kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: Dtype = torch.float32
+ kernel_size: tuple[int, int] | int, *, device: Optional[Device] = None, dtype: Dtype = torch.float32
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
@@ -777,7 +779,11 @@ def get_laplacian_kernel2d(
def get_pascal_kernel_2d(
- kernel_size: tuple[int, int] | int, norm: bool = True, *, device: Device | None = None, dtype: Dtype | None = None
+ kernel_size: tuple[int, int] | int,
+ norm: bool = True,
+ *,
+ device: Optional[Device] = None,
+ dtype: Optional[Dtype] = None,
) -> Tensor:
"""Generate pascal filter kernel by kernel size.
@@ -816,7 +822,7 @@ def get_pascal_kernel_2d(
def get_pascal_kernel_1d(
- kernel_size: int, norm: bool = False, *, device: Device | None = None, dtype: Dtype | None = None
+ kernel_size: int, norm: bool = False, *, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
"""Generate Yang Hui triangle (Pascal's triangle) by a given number.
@@ -863,7 +869,7 @@ def get_pascal_kernel_1d(
return out
-def get_canny_nms_kernel(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_canny_nms_kernel(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns 3x3 kernels for the Canny Non-maximal suppression."""
return tensor(
[
@@ -881,7 +887,7 @@ def get_canny_nms_kernel(device: Device | None = None, dtype: Dtype | None = Non
)
-def get_hysteresis_kernel(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_hysteresis_kernel(device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Utility function that returns the 3x3 kernels for the Canny hysteresis."""
return tensor(
[
@@ -899,7 +905,7 @@ def get_hysteresis_kernel(device: Device | None = None, dtype: Dtype | None = No
)
-def get_hanning_kernel1d(kernel_size: int, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
+def get_hanning_kernel1d(kernel_size: int, device: Optional[Device] = None, dtype: Optional[Dtype] = None) -> Tensor:
"""Returns Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
@@ -928,7 +934,7 @@ def get_hanning_kernel1d(kernel_size: int, device: Device | None = None, dtype:
def get_hanning_kernel2d(
- kernel_size: tuple[int, int] | int, device: Device | None = None, dtype: Dtype | None = None
+ kernel_size: tuple[int, int] | int, device: Optional[Device] = None, dtype: Optional[Dtype] = None
) -> Tensor:
"""Returns 2d Hanning kernel, used in signal processing and KCF tracker.
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 63572fd20..22d8b41b9 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import warnings
+from typing import Optional
import torch
@@ -439,7 +440,7 @@ def bbox_generator3d(
def transform_bbox(
- trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy", restore_coordinates: bool | None = None
+ trans_mat: torch.Tensor, boxes: torch.Tensor, mode: str = "xyxy", restore_coordinates: Optional[bool] = None
) -> torch.Tensor:
r"""Apply a transformation matrix to a box or batch of boxes.
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 126178833..e09b4b49c 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import cast
+from typing import Optional, cast
import torch
from torch import Size
@@ -192,7 +192,7 @@ class Boxes:
raise_if_not_floating_point: bool = True,
mode: str = "vertices_plus",
) -> None:
- self._N: list[int] | None = None
+ self._N: Optional[list[int]] = None
if isinstance(boxes, list):
boxes, self._N = _merge_box_list(boxes)
@@ -312,8 +312,8 @@ class Boxes:
def clamp(
self,
- topleft: Tensor | tuple[int, int] | None = None,
- botright: Tensor | tuple[int, int] | None = None,
+ topleft: Optional[Tensor | tuple[int, int]] = None,
+ botright: Optional[Tensor | tuple[int, int]] = None,
inplace: bool = False,
) -> Boxes:
""""""
@@ -372,7 +372,7 @@ class Boxes:
raise NotImplementedError
def filter_boxes_by_area(
- self, min_area: float | None = None, max_area: float | None = None, inplace: bool = False
+ self, min_area: Optional[float] = None, max_area: Optional[float] = None, inplace: bool = False
) -> Boxes:
area = self.compute_area()
if inplace:
@@ -449,7 +449,9 @@ class Boxes:
return cls(quadrilaterals, False, mode)
- def to_tensor(self, mode: str | None = None, as_padded_sequence: bool = False) -> torch.Tensor | list[torch.Tensor]:
+ def to_tensor(
+ self, mode: Optional[str] = None, as_padded_sequence: bool = False
+ ) -> torch.Tensor | list[torch.Tensor]:
r"""Cast :class:`Boxes` to a tensor. ``mode`` controls which 2D boxes format should be use to represent
boxes in the tensor.
@@ -636,7 +638,7 @@ class Boxes:
"""Returns boxes dtype."""
return self._data.dtype
- def to(self, device: torch.device | None = None, dtype: torch.dtype | None = None) -> Boxes:
+ def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> Boxes:
"""Like :func:`torch.nn.Module.to()` method."""
# In torchscript, dtype is a int and not a class. https://github.com/pytorch/pytorch/issues/51941
if dtype is not None and not _is_floating_point_dtype(dtype):
@@ -677,7 +679,7 @@ class VideoBoxes(Boxes):
out.temporal_channel_size = temporal_channel_size
return out
- def to_tensor(self, mode: str | None = None) -> torch.Tensor | list[torch.Tensor]: # type: ignore[override]
+ def to_tensor(self, mode: Optional[str] = None) -> torch.Tensor | list[torch.Tensor]: # type: ignore[override]
out = super().to_tensor(mode, as_padded_sequence=False)
if isinstance(out, Tensor):
return out.view(-1, self.temporal_channel_size, *out.shape[1:])
@@ -1044,7 +1046,7 @@ class Boxes3D:
"""Returns boxes dtype."""
return self._data.dtype
- def to(self, device: torch.device | None = None, dtype: torch.dtype | None = None) -> Boxes3D:
+ def to(self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None) -> Boxes3D:
"""Like :func:`torch.nn.Module.to()` method."""
# In torchscript, dtype is a int and not a class. https://github.com/pytorch/pytorch/issues/51941
if dtype is not None and not _is_floating_point_dtype(dtype):
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 2f45568a1..ba0fd3c92 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -140,7 +140,7 @@ def solve_pnp_dlt(
if (weights is not None) and (not isinstance(weights, torch.Tensor)):
raise AssertionError(
- f"If weights is not None, then weights should be an instance "
+ "If weights is not None, then weights should be an instance "
f"of torch.Tensor. Type of weights is {type(weights)}"
)
@@ -157,14 +157,12 @@ def solve_pnp_dlt(
if img_points.dtype not in accepted_dtypes:
raise AssertionError(
- f"img_points must have one of the following dtypes {accepted_dtypes}. "
- f"Currently it has {img_points.dtype}."
+ f"img_points must have one of the following dtypes {accepted_dtypes}. Currently it has {img_points.dtype}."
)
if intrinsics.dtype not in accepted_dtypes:
raise AssertionError(
- f"intrinsics must have one of the following dtypes {accepted_dtypes}. "
- f"Currently it has {intrinsics.dtype}."
+ f"intrinsics must have one of the following dtypes {accepted_dtypes}. Currently it has {intrinsics.dtype}."
)
if (len(world_points.shape) != 3) or (world_points.shape[2] != 3):
@@ -198,10 +196,10 @@ def solve_pnp_dlt(
s = _torch_linalg_svdvals(world_points_norm)
if torch.any(s[:, -1] < svd_eps):
raise AssertionError(
- f"The last singular value of one/more of the elements of the batch is smaller "
+ "The last singular value of one/more of the elements of the batch is smaller "
f"than {svd_eps}. This function cannot be used if all world_points (of any "
- f"element of the batch) lie on a line or if all world_points (of any "
- f"element of the batch) lie on a plane."
+ "element of the batch) lie on a line or if all world_points (of any "
+ "element of the batch) lie on a plane."
)
intrinsics_inv = torch.inverse(intrinsics)
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index 69e723d54..61372d096 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
from kornia.geometry.linalg import transform_points
@@ -11,7 +13,7 @@ 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: torch.Tensor | None = None, num_iters: int = 5
+ 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.
@@ -154,7 +156,7 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
# allowed to avoid a breaking change.
if not all((image.shape[:-3] == (1,), K.shape[:-2] == (), dist.shape[:-1] == ())):
raise ValueError(
- f'Input shape is invalid. Input batch dimensions should match. '
+ 'Input shape is invalid. Input batch dimensions should match. '
f'Got {image.shape[:-3]}, {K.shape[:-2]}, {dist.shape[:-1]}.'
)
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index cce37390b..912cc5d33 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -70,37 +70,35 @@ class StereoCamera:
if rectified_left_camera.shape[:1] == (3, 4):
raise StereoException(
- f"Expected each 'rectified_left_camera' to be of shape (3, 4)."
- f"Got {rectified_left_camera.shape[:1]}."
+ f"Expected each 'rectified_left_camera' to be of shape (3, 4).Got {rectified_left_camera.shape[:1]}."
)
if rectified_right_camera.shape[:1] == (3, 4):
raise StereoException(
- f"Expected each 'rectified_right_camera' to be of shape (3, 4)."
- f"Got {rectified_right_camera.shape[:1]}."
+ f"Expected each 'rectified_right_camera' to be of shape (3, 4).Got {rectified_right_camera.shape[:1]}."
)
# Ensure same devices for cameras.
if rectified_left_camera.device != rectified_right_camera.device:
raise StereoException(
- f"Expected 'rectified_left_camera' and 'rectified_right_camera' "
- f"to be on the same devices."
+ "Expected 'rectified_left_camera' and 'rectified_right_camera' "
+ "to be on the same devices."
f"Got {rectified_left_camera.device} and {rectified_right_camera.device}."
)
# Ensure same dtypes for cameras.
if rectified_left_camera.dtype != rectified_right_camera.dtype:
raise StereoException(
- f"Expected 'rectified_left_camera' and 'rectified_right_camera' to"
- f"have same dtype."
+ "Expected 'rectified_left_camera' and 'rectified_right_camera' to"
+ "have same dtype."
f"Got {rectified_left_camera.dtype} and {rectified_right_camera.dtype}."
)
# Ensure all intrinsics parameters (fx, fy, cx, cy) are the same in both cameras.
if not torch.all(torch.eq(rectified_left_camera[..., :, :3], rectified_right_camera[..., :, :3])):
raise StereoException(
- f"Expected 'left_rectified_camera' and 'rectified_right_camera' to have"
- f"same parameters except for the last column."
+ "Expected 'left_rectified_camera' and 'rectified_right_camera' to have"
+ "same parameters except for the last column."
f"Got {rectified_left_camera[..., :, :3]} and {rectified_right_camera[..., :, :3]}."
)
@@ -239,13 +237,13 @@ def _check_disparity_tensor(disparity_tensor: Tensor) -> None:
if disparity_tensor.shape[-1] != 1:
raise StereoException(
- f"Expected dimension 1 of 'disparity_tensor' to be 1 for as single channeled disparity map."
+ "Expected dimension 1 of 'disparity_tensor' to be 1 for as single channeled disparity map."
f"Got {disparity_tensor.shape}."
)
if disparity_tensor.dtype not in (torch.float16, torch.float32, torch.float64):
raise StereoException(
- f"Expected 'disparity_tensor' to have dtype torch.float16, torch.float32 or torch.float64."
+ "Expected 'disparity_tensor' to have dtype torch.float16, torch.float32 or torch.float64."
f"Got {disparity_tensor.dtype}"
)
@@ -298,9 +296,9 @@ def reproject_disparity_to_3D(disparity_tensor: Tensor, Q_matrix: Tensor) -> Ten
# Final check that everything went well.
if not points.shape == (batch_size, rows, cols, 3):
raise StereoException(
- f"Something went wrong in `reproject_disparity_to_3D`. Expected the final output"
+ "Something went wrong in `reproject_disparity_to_3D`. Expected the final output"
f"to be of shape {(batch_size, rows, cols, 3)}."
f"But the computed point cloud had shape {points.shape}. "
- f"Please ensure input are correct. If this is an error, please submit an issue."
+ "Please ensure input are correct. If this is an error, please submit an issue."
)
return points
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 9b077c1d2..2e80aa417 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
@@ -1013,7 +1015,11 @@ def normalize_homography(
def normal_transform_pixel(
- height: int, width: int, eps: float = 1e-14, device: torch.device | None = None, dtype: torch.dtype | None = None
+ height: int,
+ width: int,
+ eps: float = 1e-14,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
@@ -1042,8 +1048,8 @@ def normal_transform_pixel3d(
height: int,
width: int,
eps: float = 1e-14,
- device: torch.device | None = None,
- dtype: torch.dtype | None = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> Tensor:
r"""Compute the normalization matrix from image size in pixels to [-1, 1].
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 42298bc95..b8aa4ffa7 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -1,6 +1,8 @@
"""Module containing operators to work on RGB-Depth images."""
from __future__ import annotations
+from typing import Optional
+
import torch
import kornia.core as kornia_ops
@@ -30,8 +32,8 @@ def unproject_meshgrid(
width: int,
camera_matrix: Tensor,
normalize_points: bool = False,
- device: torch.device | None = None,
- dtype: torch.dtype | None = None,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> Tensor:
"""Compute a 3d point per pixel given its depth value and the camera intrinsics.
@@ -67,7 +69,7 @@ def unproject_meshgrid(
def depth_to_3d_v2(
- depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False, xyz_grid: Tensor | None = None
+ depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False, xyz_grid: Optional[Tensor] = None
) -> Tensor:
"""Compute a 3d point per pixel given its depth value and the camera intrinsics.
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 27636052f..523124858 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -2,7 +2,7 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se2.py
from __future__ import annotations
-from typing import overload
+from typing import Optional, overload
from kornia.core import (
Device,
@@ -240,7 +240,7 @@ class Se2(Module):
return concatenate((upsilon, theta[..., None]), -1)
@classmethod
- def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se2:
+ def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se2:
"""Create a Se2 group representing an identity rotation and zero translation.
Args:
@@ -319,7 +319,7 @@ class Se2(Module):
return Se2(r_inv, r_inv * _t)
@classmethod
- def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se2:
+ def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se2:
"""Create a Se2 group representing a random transformation.
Args:
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index f52ff6c77..32240417b 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -2,6 +2,8 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py
from __future__ import annotations
+from typing import Optional
+
from kornia.core import (
Device,
Dtype,
@@ -238,7 +240,7 @@ class Se3(Module):
return concatenate((head, tail), -1)
@classmethod
- def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se3:
+ def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se3:
"""Create a Se3 group representing an identity rotation and zero translation.
Args:
@@ -340,7 +342,7 @@ class Se3(Module):
return Se3(r_inv, r_inv * _t)
@classmethod
- def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se3:
+ def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> Se3:
"""Create a Se3 group representing a random transformation.
Args:
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 7fa9da2e7..d13e50688 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -2,7 +2,7 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so2.py
from __future__ import annotations
-from typing import overload
+from typing import Optional, overload
from kornia.core import Device, Dtype, Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
@@ -202,7 +202,9 @@ class So2(Module):
return cls(z)
@classmethod
- def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So2:
+ def identity(
+ cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ ) -> So2:
"""Create a So2 group representing an identity rotation.
Args:
@@ -234,7 +236,9 @@ class So2(Module):
return So2(1 / self.z)
@classmethod
- def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So2:
+ def random(
+ cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ ) -> So2:
"""Create a So2 group representing a random rotation.
Args:
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index e14954ea3..6c46b9327 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -2,6 +2,8 @@
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py
from __future__ import annotations
+from typing import Optional
+
from kornia.core import Device, Dtype, Module, Tensor, concatenate, eye, stack, tensor, where, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.conversions import vector_to_skew_symmetric_matrix
@@ -247,7 +249,9 @@ class So3(Module):
return cls(Quaternion(wxyz))
@classmethod
- def identity(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So3:
+ def identity(
+ cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ ) -> So3:
"""Create a So3 group representing an identity rotation.
Args:
@@ -279,7 +283,9 @@ class So3(Module):
return So3(self.q.conj())
@classmethod
- def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> So3:
+ def random(
+ cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Optional[Dtype] = None
+ ) -> So3:
"""Create a So3 group representing a random rotation.
Args:
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 6b146d106..556928a31 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -156,18 +156,17 @@ class RANSAC(Module):
KORNIA_CHECK_SHAPE(kp2, ["N", "2"])
if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):
raise ValueError(
- f"kp1 and kp2 should be \
- equal shape at at least [{self.minimal_sample_size}, 2], \
- got {kp1.shape}, {kp2.shape}"
+ "kp1 and kp2 should be equal shape at at least"
+ f" [{self.minimal_sample_size}, 2], got {kp1.shape}, {kp2.shape}"
)
if self.model_type == 'homography_from_linesegments':
KORNIA_CHECK_SHAPE(kp1, ["N", "2", "2"])
KORNIA_CHECK_SHAPE(kp2, ["N", "2", "2"])
if not (kp1.shape[0] == kp2.shape[0]) or (kp1.shape[0] < self.minimal_sample_size):
raise ValueError(
- f"kp1 and kp2 should be \
- equal shape at at least [{self.minimal_sample_size}, 2, 2], \
- got {kp1.shape}, {kp2.shape}"
+ "kp1 and kp2 should be equal shape at at least"
+ f" [{self.minimal_sample_size}, 2, 2], got {kp1.shape},"
+ f" {kp2.shape}"
)
def forward(self, kp1: Tensor, kp2: Tensor, weights: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 751351e7b..fb85edc10 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -232,8 +232,7 @@ def crop_by_boxes(
bbox: Tuple[Tensor, Tensor] = infer_bbox_shape(dst_box)
if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all()):
raise AssertionError(
- f"Cropping height, width and depth must be exact same in a batch. "
- f"Got height {bbox[0]} and width {bbox[1]}."
+ f"Cropping height, width and depth must be exact same in a batch. Got height {bbox[0]} and width {bbox[1]}."
)
h_out: int = int(bbox[0][0].item())
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 6f44153cc..51d5d3f54 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from abc import abstractmethod
-from typing import Any
+from typing import Any, Optional
import torch.nn.functional as F
@@ -20,7 +20,7 @@ class BaseWarper(Module):
self.width = width
@abstractmethod
- def forward(self, patch_src: Tensor, src_homo_dst: Tensor | None = None) -> Tensor:
+ def forward(self, patch_src: Tensor, src_homo_dst: Optional[Tensor] = None) -> Tensor:
...
@abstractmethod
@@ -44,7 +44,7 @@ class HomographyWarper(BaseWarper):
normalized_coordinates: whether to use a grid with normalized coordinates.
align_corners: interpolation flag.
"""
- _warped_grid: Tensor | None
+ _warped_grid: Optional[Tensor]
def __init__(
self,
@@ -80,7 +80,7 @@ class HomographyWarper(BaseWarper):
"""
self._warped_grid = warp_grid(self.grid, src_homo_dst)
- def forward(self, patch_src: Tensor, src_homo_dst: Tensor | None = None) -> Tensor:
+ def forward(self, patch_src: Tensor, src_homo_dst: Optional[Tensor] = None) -> Tensor:
r"""Warp a tensor from source into reference frame.
Args:
@@ -120,12 +120,10 @@ class HomographyWarper(BaseWarper):
elif _warped_grid is not None:
if not _warped_grid.device == patch_src.device:
raise TypeError(
- "Patch and warped grid must be on the same device. \
- Got patch.device: {} warped_grid.device: {}. Whether \
- recall precompute_warp_grid() with the correct device \
- for the homograhy or change the patch device.".format(
- patch_src.device, _warped_grid.device
- )
+ "Patch and warped grid must be on the same device. Got"
+ " patch.device: {} warped_grid.device: {}. Whether recall"
+ " precompute_warp_grid() with the correct device for the homograhy"
+ " or change the patch device.".format(patch_src.device, _warped_grid.device)
)
warped_patch = F.grid_sample(
patch_src,
@@ -136,9 +134,8 @@ class HomographyWarper(BaseWarper):
)
else:
raise RuntimeError(
- "Unknown warping. If homographies are not provided \
- they must be preset using the method: \
- precompute_warp_grid()."
+ "Unknown warping. If homographies are not provided they must be preset"
+ " using the method: precompute_warp_grid()."
)
return warped_patch
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index eb28bc599..36cc5d79d 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -88,8 +88,9 @@ class Similarity(BaseModel):
self.reset_model()
def __repr__(self) -> str:
- return f'{self.__class__.__name__}(angle = {self.rot},\
- \n shift={self.shift}, \n scale={self.scale})'
+ return (
+ f'{self.__class__.__name__}(angle = {self.rot}, \n shift={self.shift}, \n scale={self.scale})'
+ )
def reset_model(self) -> None:
"""Initialize the model with identity transform."""
@@ -187,8 +188,8 @@ class ImageRegistrator(Module):
# 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:} "
+ "Cannot register images of different shapes "
+ f" {img_src.shape} {img_dst.shape:} "
)
_height, _width = img_dst.shape[-2:]
warper = self.warper(_height, _width)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index e38d125e1..20fb76ec2 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
@@ -459,7 +461,7 @@ def remap(
map_y: Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: bool | None = None,
+ align_corners: Optional[bool] = None,
normalized_coordinates: bool = False,
) -> Tensor:
r"""Apply a generic geometrical transformation to an image tensor.
@@ -563,8 +565,8 @@ def get_affine_matrix2d(
center: Tensor,
scale: Tensor,
angle: Tensor,
- sx: Tensor | None = None,
- sy: Tensor | None = None,
+ sx: Optional[Tensor] = None,
+ sy: Optional[Tensor] = None,
) -> Tensor:
r"""Compose affine matrix from the components.
@@ -616,7 +618,7 @@ def get_translation_matrix2d(translations: Tensor) -> Tensor:
return transform_h
-def get_shear_matrix2d(center: Tensor, sx: Tensor | None = None, sy: Tensor | None = None) -> Tensor:
+def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional[Tensor] = None) -> Tensor:
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis.
@@ -671,12 +673,12 @@ def get_affine_matrix3d(
center: Tensor,
scale: Tensor,
angles: Tensor,
- sxy: Tensor | None = None,
- sxz: Tensor | None = None,
- syx: Tensor | None = None,
- syz: Tensor | None = None,
- szx: Tensor | None = None,
- szy: Tensor | None = None,
+ sxy: Optional[Tensor] = None,
+ sxz: Optional[Tensor] = None,
+ syx: Optional[Tensor] = None,
+ syz: Optional[Tensor] = None,
+ szx: Optional[Tensor] = None,
+ szy: Optional[Tensor] = None,
) -> Tensor:
r"""Compose 3d affine matrix from the components.
@@ -714,12 +716,12 @@ def get_affine_matrix3d(
def get_shear_matrix3d(
center: Tensor,
- sxy: Tensor | None = None,
- sxz: Tensor | None = None,
- syx: Tensor | None = None,
- syz: Tensor | None = None,
- szx: Tensor | None = None,
- szy: Tensor | None = None,
+ sxy: Optional[Tensor] = None,
+ sxz: Optional[Tensor] = None,
+ syx: Optional[Tensor] = None,
+ syz: Optional[Tensor] = None,
+ szx: Optional[Tensor] = None,
+ szy: Optional[Tensor] = None,
) -> Tensor:
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis then z-axis.
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index aae030718..e374a77ad 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
from torch import nn
@@ -14,10 +16,10 @@ from kornia.utils.one_hot import one_hot
def focal_loss(
input: Tensor,
target: Tensor,
- alpha: float | None,
+ alpha: Optional[float],
gamma: float = 2.0,
reduction: str = 'none',
- weight: Tensor | None = None,
+ weight: Optional[Tensor] = None,
) -> Tensor:
r"""Criterion that computes Focal loss.
@@ -145,13 +147,13 @@ class FocalLoss(nn.Module):
"""
def __init__(
- self, alpha: float | None, gamma: float = 2.0, reduction: str = 'none', weight: Tensor | None = None
+ self, alpha: Optional[float], gamma: float = 2.0, reduction: str = 'none', weight: Optional[Tensor] = None
) -> None:
super().__init__()
- self.alpha: float | None = alpha
+ self.alpha: Optional[float] = alpha
self.gamma: float = gamma
self.reduction: str = reduction
- self.weight: Tensor | None = weight
+ self.weight: Optional[Tensor] = weight
def forward(self, input: Tensor, target: Tensor) -> Tensor:
return focal_loss(input, target, self.alpha, self.gamma, self.reduction, self.weight)
@@ -160,11 +162,11 @@ class FocalLoss(nn.Module):
def binary_focal_loss_with_logits(
input: Tensor,
target: Tensor,
- alpha: float | None = 0.25,
+ alpha: Optional[float] = 0.25,
gamma: float = 2.0,
reduction: str = 'none',
- pos_weight: Tensor | None = None,
- weight: Tensor | None = None,
+ pos_weight: Optional[Tensor] = None,
+ weight: Optional[Tensor] = None,
) -> Tensor:
r"""Criterion that computes Binary Focal loss.
@@ -303,18 +305,18 @@ class BinaryFocalLossWithLogits(nn.Module):
def __init__(
self,
- alpha: float | None,
+ alpha: Optional[float],
gamma: float = 2.0,
reduction: str = 'none',
- pos_weight: Tensor | None = None,
- weight: Tensor | None = None,
+ pos_weight: Optional[Tensor] = None,
+ weight: Optional[Tensor] = None,
) -> None:
super().__init__()
- self.alpha: float | None = alpha
+ self.alpha: Optional[float] = alpha
self.gamma: float = gamma
self.reduction: str = reduction
- self.pos_weight: Tensor | None = pos_weight
- self.weight: Tensor | None = weight
+ self.pos_weight: Optional[Tensor] = pos_weight
+ self.weight: Optional[Tensor] = weight
def forward(self, input: Tensor, target: Tensor) -> Tensor:
return binary_focal_loss_with_logits(
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index 31970a57d..8d2378019 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
from torch import nn
@@ -83,7 +85,7 @@ class MS_SSIMLoss(nn.Module):
self.register_buffer('_g_masks', g_masks)
def _fspecial_gauss_1d(
- self, size: int, sigma: float, device: torch.device | None = None, dtype: torch.dtype | None = None
+ self, size: int, sigma: float, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
"""Create 1-D gauss kernel.
@@ -101,7 +103,7 @@ class MS_SSIMLoss(nn.Module):
return g.reshape(-1)
def _fspecial_gauss_2d(
- self, size: int, sigma: float, device: torch.device | None = None, dtype: torch.dtype | None = None
+ self, size: int, sigma: float, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
"""Create 2-D gauss kernel.
diff --git a/pyproject.toml b/pyproject.toml
index 0cc9e8e31..f5be57606 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -140,6 +140,7 @@ requires = [
ignore = [
"PLW2901", # Allow overwritten values on loops
"PLR0915", # Allow condition check in list comprehension
+ "UP007", # Prefer Optional[], Union[] over | due to torch jit scripting
]
[tool.ruff.isort]
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 36485ef6b..56228860d 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -11,6 +11,16 @@ from kornia.utils._compat import torch_version, torch_version_lt
from kornia.utils.helpers import _torch_inverse_cast
+class DummyNNModule(torch.nn.Module):
+ def __init__(self, h: int, w: int, align_corners: bool, padding_mode: str):
+ super().__init__()
+ self.h = h
+ self.w = w
+
+ def forward(self, x, y):
+ return kornia.geometry.transform.warp_affine(x, y, dsize=(self.h, self.w), align_corners=False)
+
+
class TestGetPerspectiveTransform:
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_smoke(self, device, dtype, batch_size):
@@ -268,6 +278,21 @@ class TestWarpAffine:
assert_close(img_a[:, :, :1, :1].squeeze(), fill_value.squeeze())
+ @pytest.mark.parametrize("align_corners", (True, False))
+ @pytest.mark.parametrize("padding_mode", ("zeros", "fill"))
+ def test_jit_script(self, device, dtype, align_corners, padding_mode):
+ offset = 1.0
+ h, w = 3, 4
+ aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
+ aff_ab[..., -1] += offset
+
+ img_b = torch.arange(float(3 * h * w), device=device, dtype=dtype).view(1, 3, h, w)
+ net = DummyNNModule(3, 4, align_corners, padding_mode)
+ script_net = torch.jit.script(net)
+
+ assert isinstance(script_net, torch.jit.ScriptModule)
+ assert_close(script_net(img_b, aff_ab), net(img_b, aff_ab))
+
class TestWarpPerspective:
def test_smoke(self, device, dtype):