Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Small refactor on `filters` module: Dropping JIT support (#2187)

João Gustavo A. Amorima5888b04a0fd
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.py
index c62212670..32449cded 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -1,12 +1,12 @@
import warnings
-from typing import Any, Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple, Union
from torch import Tensor
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
from kornia.constants import BorderType
-from kornia.filters import gaussian_blur2d_t
+from kornia.filters import gaussian_blur2d
class RandomGaussianBlur(IntensityAugmentationBase2D):
@@ -54,8 +54,8 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
def __init__(
self,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
+ kernel_size: Union[Tuple[int, int], int],
+ sigma: Union[Tuple[float, float], Tensor],
border_type: str = "reflect",
separable: bool = True,
same_on_batch: bool = False,
@@ -79,7 +79,7 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = None
) -> Tensor:
sigma = params["sigma"].to(device=input.device, dtype=input.dtype).unsqueeze(-1).expand(-1, 2)
- return gaussian_blur2d_t(
+ return gaussian_blur2d(
input,
self.flags["kernel_size"],
sigma,
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
index 30cc2ca37..1a20e5111 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_blur.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
@@ -1,4 +1,4 @@
-from typing import Dict, Tuple
+from typing import Dict, Tuple, Union
import torch
from torch import Tensor
@@ -25,7 +25,7 @@ class RandomGaussianBlurGenerator(RandomGeneratorBase):
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
"""
- def __init__(self, sigma: Tuple[float, float] = (0.1, 2.0)) -> None:
+ def __init__(self, sigma: Union[Tuple[float, float], Tensor] = (0.1, 2.0)) -> None:
super().__init__()
if sigma[1] < sigma[0]:
raise TypeError(f"sigma_max should be higher than sigma_min: {sigma} passed.")
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index 5d8d497e3..16cccc140 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -1,5 +1,14 @@
+from __future__ import annotations
+
from .blur import BoxBlur, box_blur
-from .blur_pool import BlurPool2D, MaxBlurPool2D, blur_pool2d, edge_aware_blur_pool2d, max_blur_pool2d
+from .blur_pool import (
+ BlurPool2D,
+ EdgeAwareBlurPool2D,
+ MaxBlurPool2D,
+ blur_pool2d,
+ edge_aware_blur_pool2d,
+ max_blur_pool2d,
+)
from .canny import Canny, canny
from .dexined import DexiNed
from .filter import filter2d, filter2d_separable, filter3d
@@ -38,13 +47,10 @@ __all__ = [
"get_binary_kernel2d",
"get_box_kernel2d",
"get_gaussian_kernel1d",
- "get_gaussian_kernel1d_t",
"get_gaussian_discrete_kernel1d",
"get_gaussian_erf_kernel1d",
"get_gaussian_kernel2d",
"get_gaussian_kernel3d",
- "get_gaussian_kernel2d_t",
- "get_gaussian_kernel3d_t",
"get_hanning_kernel1d",
"get_hanning_kernel2d",
"get_laplacian_kernel1d",
@@ -56,7 +62,6 @@ __all__ = [
"get_sobel_kernel2d",
"get_diff_kernel2d",
"gaussian_blur2d",
- "gaussian_blur2d_t",
"laplacian",
"laplacian_1d",
"unsharp_mask",
@@ -80,6 +85,7 @@ __all__ = [
"BoxBlur",
"BlurPool2D",
"MaxBlurPool2D",
+ "EdgeAwareBlurPool2D",
"MedianBlur",
"MotionBlur",
"MotionBlur3D",
@@ -87,4 +93,8 @@ __all__ = [
"spatial_gradient3d",
"UnsharpMask",
"DexiNed",
+ "gaussian_blur2d_t",
+ "get_gaussian_kernel1d_t",
+ "get_gaussian_kernel2d_t",
+ "get_gaussian_kernel3d_t",
]
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 1e397090e..35462b119 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -1,15 +1,14 @@
-from typing import Tuple
+from __future__ import annotations
-import torch
-import torch.nn as nn
+from kornia.core import Module, Tensor
from .filter import filter2d
from .kernels import get_box_kernel2d, normalize_kernel2d
def box_blur(
- input: torch.Tensor, kernel_size: Tuple[int, int], border_type: str = 'reflect', normalized: bool = True
-) -> torch.Tensor:
+ input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', normalized: bool = True
+) -> Tensor:
r"""Blur an image using the box filter.
.. image:: _static/img/box_blur.png
@@ -45,13 +44,13 @@ def box_blur(
>>> output.shape
torch.Size([2, 4, 5, 7])
"""
- kernel: torch.Tensor = get_box_kernel2d(kernel_size)
+ kernel = get_box_kernel2d(kernel_size, device=input.device, dtype=input.dtype)
if normalized:
kernel = normalize_kernel2d(kernel)
return filter2d(input, kernel, border_type)
-class BoxBlur(nn.Module):
+class BoxBlur(Module):
r"""Blur an image using the box filter.
The function smooths an image using the kernel:
@@ -87,11 +86,13 @@ class BoxBlur(nn.Module):
torch.Size([2, 4, 5, 7])
"""
- def __init__(self, kernel_size: Tuple[int, int], border_type: str = 'reflect', normalized: bool = True) -> None:
+ def __init__(
+ self, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', normalized: bool = True
+ ) -> None:
super().__init__()
- self.kernel_size: Tuple[int, int] = kernel_size
- self.border_type: str = border_type
- self.normalized: bool = normalized
+ self.kernel_size = kernel_size
+ self.border_type = border_type
+ self.normalized = normalized
def __repr__(self) -> str:
return (
@@ -107,5 +108,5 @@ class BoxBlur(nn.Module):
+ ')'
)
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return box_blur(input, self.kernel_size, self.border_type, self.normalized)
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index dea623083..8a0c3ca84 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -1,15 +1,21 @@
-from typing import Tuple
+from __future__ import annotations
-import torch
import torch.nn.functional as F
-from kornia.core import Module, Tensor
+from kornia.core import Module, Tensor, as_tensor, pad, tensor
from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from .kernels import get_pascal_kernel_2d
from .median import _compute_zero_padding # TODO: Move to proper place
-__all__ = ["BlurPool2D", "MaxBlurPool2D", "blur_pool2d", "max_blur_pool2d", 'edge_aware_blur_pool2d']
+__all__ = [
+ "BlurPool2D",
+ "MaxBlurPool2D",
+ "EdgeAwareBlurPool2D",
+ "blur_pool2d",
+ "max_blur_pool2d",
+ 'edge_aware_blur_pool2d',
+]
class BlurPool2D(Module):
@@ -43,16 +49,15 @@ class BlurPool2D(Module):
[0.0000, 0.0625, 0.3125]]]])
"""
- def __init__(self, kernel_size: int, stride: int = 2):
+ def __init__(self, kernel_size: tuple[int, int] | int, stride: int = 2):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
- self.register_buffer('kernel', get_pascal_kernel_2d(kernel_size, norm=True))
+ self.kernel = get_pascal_kernel_2d(kernel_size, norm=True)
def forward(self, input: Tensor) -> Tensor:
- # To align the logic with the whole lib
- kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
- return _blur_pool_by_kernel2d(input, kernel.repeat((input.shape[1], 1, 1, 1)), self.stride)
+ self.kernel = as_tensor(self.kernel, device=input.device, dtype=input.dtype)
+ return _blur_pool_by_kernel2d(input, self.kernel.repeat((input.shape[1], 1, 1, 1)), self.stride)
class MaxBlurPool2D(Module):
@@ -89,23 +94,39 @@ class MaxBlurPool2D(Module):
[0.3125, 0.8750]]]])
"""
- def __init__(self, kernel_size: int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False):
+ def __init__(
+ self, kernel_size: tuple[int, int] | int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False
+ ):
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
self.max_pool_size = max_pool_size
self.ceil_mode = ceil_mode
- self.register_buffer('kernel', get_pascal_kernel_2d(kernel_size, norm=True))
+ self.kernel = get_pascal_kernel_2d(kernel_size, norm=True)
def forward(self, input: Tensor) -> Tensor:
- # To align the logic with the whole lib
- kernel = torch.as_tensor(self.kernel, device=input.device, dtype=input.dtype)
+ self.kernel = as_tensor(self.kernel, device=input.device, dtype=input.dtype)
return _max_blur_pool_by_kernel2d(
- input, kernel.repeat((input.size(1), 1, 1, 1)), self.stride, self.max_pool_size, self.ceil_mode
+ input, self.kernel.repeat((input.size(1), 1, 1, 1)), self.stride, self.max_pool_size, self.ceil_mode
)
-def blur_pool2d(input: Tensor, kernel_size: int, stride: int = 2):
+class EdgeAwareBlurPool2D(Module):
+ def __init__(
+ self, kernel_size: tuple[int, int] | int, edge_threshold: float = 1.25, edge_dilation_kernel_size: int = 3
+ ):
+ super().__init__()
+ self.kernel_size = kernel_size
+ self.edge_threshold = edge_threshold
+ self.edge_dilation_kernel_size = edge_dilation_kernel_size
+
+ def forward(self, input: Tensor, epsilon: float = 1e-6) -> Tensor:
+ return edge_aware_blur_pool2d(
+ input, self.kernel_size, self.edge_threshold, self.edge_dilation_kernel_size, epsilon
+ )
+
+
+def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int = 2):
r"""Compute blurs and downsample a given feature map.
.. image:: _static/img/blur_pool2d.png
@@ -147,12 +168,14 @@ def blur_pool2d(input: Tensor, kernel_size: int, stride: int = 2):
[0.0625, 0.3750, 0.0625],
[0.0000, 0.0625, 0.3125]]]])
"""
- kernel = get_pascal_kernel_2d(kernel_size, norm=True).repeat((input.size(1), 1, 1, 1)).to(input)
+ kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat(
+ (input.size(1), 1, 1, 1)
+ )
return _blur_pool_by_kernel2d(input, kernel, stride)
def max_blur_pool2d(
- input: Tensor, kernel_size: int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False
+ input: Tensor, kernel_size: tuple[int, int] | int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False
) -> Tensor:
r"""Compute pools and blurs and downsample a given feature map.
@@ -179,34 +202,42 @@ def max_blur_pool2d(
tensor([[[[0.5625, 0.3125],
[0.3125, 0.8750]]]])
"""
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
- kernel = get_pascal_kernel_2d(kernel_size, norm=True).repeat((input.shape[1], 1, 1, 1)).to(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+
+ kernel = get_pascal_kernel_2d(kernel_size, norm=True, device=input.device, dtype=input.dtype).repeat(
+ (input.shape[1], 1, 1, 1)
+ )
return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size, ceil_mode)
def _blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int):
"""Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- if not (len(kernel.shape) == 4 and kernel.shape[-1] == kernel.shape[-2]):
- raise AssertionError(f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}")
- padding: Tuple[int, int] = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
+ KORNIA_CHECK(
+ len(kernel.shape) == 4 and kernel.shape[-2] == kernel.shape[-1],
+ f"Invalid kernel shape. Expect CxC_(out, None)xNxN, Got {kernel.shape}",
+ )
+
+ padding = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.shape[1])
def _max_blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int, max_pool_size: int, ceil_mode: bool):
- """Compute max_blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
- if not (len(kernel.shape) == 4 and kernel.shape[-1] == kernel.shape[-2]):
- raise AssertionError(f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}")
+ """Compute max_blur_pool by a given :math:`CxC_(out, None)xNxN` kernel."""
+ KORNIA_CHECK(
+ len(kernel.shape) == 4 and kernel.shape[-2] == kernel.shape[-1],
+ f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}",
+ )
+
# compute local maxima
input = F.max_pool2d(input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)
# blur and downsample
- padding: Tuple[int, int] = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
+ padding = _compute_zero_padding((kernel.shape[-2], kernel.shape[-1]))
return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.size(1))
def edge_aware_blur_pool2d(
input: Tensor,
- kernel_size: int,
+ kernel_size: tuple[int, int] | int,
edge_threshold: float = 1.25,
edge_dilation_kernel_size: int = 3,
epsilon: float = 1e-6,
@@ -226,14 +257,14 @@ def edge_aware_blur_pool2d(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(edge_threshold > 0.0, f"edge threshold should be positive, but got '{edge_threshold}'")
- input = F.pad(input, (2, 2, 2, 2), mode="reflect") # pad to avoid artifacts near physical edges
+ input = pad(input, (2, 2, 2, 2), mode="reflect") # pad to avoid artifacts near physical edges
blurred_input = blur_pool2d(input, kernel_size=kernel_size, stride=1) # blurry version of the input
# calculate the edges (add epsilon to avoid taking the log of 0)
- log_input, log_thresh = torch.log2(input + epsilon), torch.log2(torch.tensor(edge_threshold))
+ log_input, log_thresh = (input + epsilon).log2(), (tensor(edge_threshold)).log2()
edges_x = log_input[..., :, 4:] - log_input[..., :, :-4]
edges_y = log_input[..., 4:, :] - log_input[..., :-4, :]
- edges_x, edges_y = torch.mean(edges_x, dim=-3, keepdim=True), torch.mean(edges_y, dim=-3, keepdim=True)
+ edges_x, edges_y = edges_x.mean(dim=-3, keepdim=True), edges_y.mean(dim=-3, keepdim=True)
edges_x_mask, edges_y_mask = edges_x.abs() > log_thresh.to(edges_x), edges_y.abs() > log_thresh.to(edges_y)
edges_xy_mask = (edges_x_mask[..., 2:-2, :] + edges_y_mask[..., :, 2:-2]).type_as(input)
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index f5a2af3eb..d9756561b 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -1,11 +1,13 @@
+from __future__ import annotations
+
import math
-from typing import Tuple
import torch
-import torch.nn as nn
import torch.nn.functional as F
from kornia.color import rgb_to_grayscale
+from kornia.core import Module, Tensor
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .gaussian import gaussian_blur2d
from .kernels import get_canny_nms_kernel, get_hysteresis_kernel
@@ -13,14 +15,14 @@ from .sobel import spatial_gradient
def canny(
- input: torch.Tensor,
+ input: Tensor,
low_threshold: float = 0.1,
high_threshold: float = 0.2,
- kernel_size: Tuple[int, int] = (5, 5),
- sigma: Tuple[float, float] = (1, 1),
+ kernel_size: tuple[int, int] | int = (5, 5),
+ sigma: tuple[float, float] | Tensor = (1, 1),
hysteresis: bool = True,
eps: float = 1e-6,
-) -> Tuple[torch.Tensor, torch.Tensor]:
+) -> tuple[Tensor, Tensor]:
r"""Find edges of the input image and filters them using the Canny algorithm.
.. image:: _static/img/canny.png
@@ -51,45 +53,36 @@ def canny(
>>> edges.shape
torch.Size([5, 1, 4, 4])
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
-
- if low_threshold > high_threshold:
- raise ValueError(
- "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: {}>{}".format(
- low_threshold, high_threshold
- )
- )
-
- if low_threshold < 0 and low_threshold > 1:
- raise ValueError(f"Invalid input threshold. low_threshold should be in range (0,1). Got: {low_threshold}")
-
- if high_threshold < 0 and high_threshold > 1:
- raise ValueError(f"Invalid input threshold. high_threshold should be in range (0,1). Got: {high_threshold}")
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK(
+ low_threshold <= high_threshold,
+ "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: "
+ f"{low_threshold}>{high_threshold}",
+ )
+ KORNIA_CHECK(0 < low_threshold < 1, f'Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}')
+ KORNIA_CHECK(0 < high_threshold < 1, f'Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}')
- device: torch.device = input.device
- dtype: torch.dtype = input.dtype
+ device = input.device
+ dtype = input.dtype
# To Grayscale
if input.shape[1] == 3:
input = rgb_to_grayscale(input)
# Gaussian filter
- blurred: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma)
+ blurred: Tensor = gaussian_blur2d(input, kernel_size, sigma)
# Compute the gradients
- gradients: torch.Tensor = spatial_gradient(blurred, normalized=False)
+ gradients: Tensor = spatial_gradient(blurred, normalized=False)
# Unpack the edges
- gx: torch.Tensor = gradients[:, :, 0]
- gy: torch.Tensor = gradients[:, :, 1]
+ gx: Tensor = gradients[:, :, 0]
+ gy: Tensor = gradients[:, :, 1]
# Compute gradient magnitude and angle
- magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)
- angle: torch.Tensor = torch.atan2(gy, gx)
+ magnitude: Tensor = torch.sqrt(gx * gx + gy * gy + eps)
+ angle: Tensor = torch.atan2(gy, gx)
# Radians to Degrees
angle = 180.0 * angle / math.pi
@@ -98,47 +91,47 @@ def canny(
angle = torch.round(angle / 45) * 45
# Non-maximal suppression
- nms_kernels: torch.Tensor = get_canny_nms_kernel(device, dtype)
- nms_magnitude: torch.Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2)
+ nms_kernels: Tensor = get_canny_nms_kernel(device, dtype)
+ nms_magnitude: Tensor = F.conv2d(magnitude, nms_kernels, padding=nms_kernels.shape[-1] // 2)
# Get the indices for both directions
- positive_idx: torch.Tensor = (angle / 45) % 8
+ positive_idx: Tensor = (angle / 45) % 8
positive_idx = positive_idx.long()
- negative_idx: torch.Tensor = ((angle / 45) + 4) % 8
+ negative_idx: Tensor = ((angle / 45) + 4) % 8
negative_idx = negative_idx.long()
# Apply the non-maximum suppression to the different directions
- channel_select_filtered_positive: torch.Tensor = torch.gather(nms_magnitude, 1, positive_idx)
- channel_select_filtered_negative: torch.Tensor = torch.gather(nms_magnitude, 1, negative_idx)
+ channel_select_filtered_positive: Tensor = torch.gather(nms_magnitude, 1, positive_idx)
+ channel_select_filtered_negative: Tensor = torch.gather(nms_magnitude, 1, negative_idx)
- channel_select_filtered: torch.Tensor = torch.stack(
+ channel_select_filtered: Tensor = torch.stack(
[channel_select_filtered_positive, channel_select_filtered_negative], 1
)
- is_max: torch.Tensor = channel_select_filtered.min(dim=1)[0] > 0.0
+ is_max: Tensor = channel_select_filtered.min(dim=1)[0] > 0.0
magnitude = magnitude * is_max
# Threshold
- edges: torch.Tensor = F.threshold(magnitude, low_threshold, 0.0)
+ edges: Tensor = F.threshold(magnitude, low_threshold, 0.0)
- low: torch.Tensor = magnitude > low_threshold
- high: torch.Tensor = magnitude > high_threshold
+ low: Tensor = magnitude > low_threshold
+ high: Tensor = magnitude > high_threshold
edges = low * 0.5 + high * 0.5
edges = edges.to(dtype)
# Hysteresis
if hysteresis:
- edges_old: torch.Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)
- hysteresis_kernels: torch.Tensor = get_hysteresis_kernel(device, dtype)
+ edges_old: Tensor = -torch.ones(edges.shape, device=edges.device, dtype=dtype)
+ hysteresis_kernels: Tensor = get_hysteresis_kernel(device, dtype)
while ((edges_old - edges).abs() != 0).any():
- weak: torch.Tensor = (edges == 0.5).float()
- strong: torch.Tensor = (edges == 1).float()
+ weak: Tensor = (edges == 0.5).float()
+ strong: Tensor = (edges == 1).float()
- hysteresis_magnitude: torch.Tensor = F.conv2d(
+ hysteresis_magnitude: Tensor = F.conv2d(
edges, hysteresis_kernels, padding=hysteresis_kernels.shape[-1] // 2
)
hysteresis_magnitude = (hysteresis_magnitude == 1).any(1, keepdim=True).to(dtype)
@@ -152,7 +145,7 @@ def canny(
return magnitude, edges
-class Canny(nn.Module):
+class Canny(Module):
r"""Module that finds edges of the input image and filters them using the Canny algorithm.
Args:
@@ -182,26 +175,22 @@ class Canny(nn.Module):
self,
low_threshold: float = 0.1,
high_threshold: float = 0.2,
- kernel_size: Tuple[int, int] = (5, 5),
- sigma: Tuple[float, float] = (1, 1),
+ kernel_size: tuple[int, int] | int = (5, 5),
+ sigma: tuple[float, float] | Tensor = (1, 1),
hysteresis: bool = True,
eps: float = 1e-6,
) -> None:
super().__init__()
- if low_threshold > high_threshold:
- raise ValueError(
- "Invalid input thresholds. low_threshold should be\
- smaller than the high_threshold. Got: {}>{}".format(
- low_threshold, high_threshold
- )
- )
-
- if low_threshold < 0 or low_threshold > 1:
- raise ValueError(f"Invalid input threshold. low_threshold should be in range (0,1). Got: {low_threshold}")
-
- if high_threshold < 0 or high_threshold > 1:
- raise ValueError(f"Invalid input threshold. high_threshold should be in range (0,1). Got: {high_threshold}")
+ KORNIA_CHECK(
+ low_threshold <= high_threshold,
+ "Invalid input thresholds. low_threshold should be smaller than the high_threshold. Got: "
+ f"{low_threshold}>{high_threshold}",
+ )
+ KORNIA_CHECK(0 < low_threshold < 1, f'Invalid low threshold. Should be in range (0, 1). Got: {low_threshold}')
+ KORNIA_CHECK(
+ 0 < high_threshold < 1, f'Invalid high threshold. Should be in range (0, 1). Got: {high_threshold}'
+ )
# Gaussian blur parameters
self.kernel_size = kernel_size
@@ -227,7 +216,7 @@ class Canny(nn.Module):
)
)
- def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ def forward(self, input: Tensor) -> tuple[Tensor, Tensor]:
return canny(
input, self.low_threshold, self.high_threshold, self.kernel_size, self.sigma, self.hysteresis, self.eps
)
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index fbaa48164..72d42e2c4 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -1,12 +1,15 @@
# adapted from: https://github.com/xavysp/DexiNed/blob/d944b70eb6eaf40e22f8467c1e12919aa600d8e4/model.py
+
+from __future__ import annotations
+
from collections import OrderedDict
-from typing import List
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.core import Module, Tensor, concatenate
+from kornia.testing import KORNIA_CHECK
from kornia.utils import map_location_to_cpu
url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"
@@ -52,7 +55,7 @@ class CoFusion(Module):
attn = F.softmax(self.conv3(attn), dim=1)
# return ((fusecat * attn).sum(1)).unsqueeze(1)
- return ((x * attn).sum(1)).unsqueeze(1)
+ return ((x * attn).sum(1))[:, None, ...]
class _DenseLayer(nn.Sequential):
@@ -70,7 +73,7 @@ class _DenseLayer(nn.Sequential):
)
)
- def forward(self, x: List[Tensor]) -> List[Tensor]:
+ def forward(self, x: list[Tensor]) -> list[Tensor]:
x1, x2 = x[0], x[1]
x3: Tensor = x1
for mod in self:
@@ -86,7 +89,7 @@ class _DenseBlock(nn.Sequential):
self.add_module('denselayer%d' % (i + 1), layer)
input_features = out_features
- def forward(self, x: List[Tensor]) -> List[Tensor]:
+ def forward(self, x: list[Tensor]) -> list[Tensor]:
x_out = x
for mod in self:
x_out = mod(x_out)
@@ -100,12 +103,11 @@ class UpConvBlock(Module):
self.constant_features = 16
layers = self.make_deconv_layers(in_features, up_scale)
- if layers is None:
- raise Exception("layers cannot be none")
+ KORNIA_CHECK(layers is not None, "layers cannot be none")
self.features = nn.Sequential(*layers)
- def make_deconv_layers(self, in_features: int, up_scale: int) -> List[Module]:
- layers: List[Module] = []
+ def make_deconv_layers(self, in_features: int, up_scale: int) -> list[Module]:
+ layers: list[Module] = []
all_pads = [0, 0, 1, 3, 7]
for i in range(up_scale):
kernel_size = 2**up_scale
@@ -120,7 +122,7 @@ class UpConvBlock(Module):
def compute_out_features(self, idx: int, up_scale: int):
return 1 if idx == up_scale - 1 else self.constant_features
- def forward(self, x: Tensor, out_shape: List[int]) -> Tensor:
+ def forward(self, x: Tensor, out_shape: list[int]) -> Tensor:
out = self.features(x)
if out.shape[-2:] != out_shape:
out = F.interpolate(out, out_shape, mode='bilinear')
@@ -215,7 +217,7 @@ class DexiNed(Module):
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
- def forward(self, x: Tensor) -> List[Tensor]:
+ def forward(self, x: Tensor) -> list[Tensor]:
# Block 1
block_1 = self.block_1(x)
block_1_side = self.side_1(block_1)
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index ff5abaf53..15c8b44dc 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -1,12 +1,17 @@
-from typing import List
+from __future__ import annotations
-import torch
import torch.nn.functional as F
+from kornia.core import Tensor, pad
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+
from .kernels import normalize_kernel2d
+_VALID_BORDERS = {'constant', 'reflect', 'replicate', 'circular'}
+_VALID_PADDING = {'valid', 'same'}
+
-def _compute_padding(kernel_size: List[int]) -> List[int]:
+def _compute_padding(kernel_size: list[int]) -> list[int]:
"""Compute padding tuple."""
# 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)
# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad
@@ -30,12 +35,8 @@ def _compute_padding(kernel_size: List[int]) -> List[int]:
def filter2d(
- input: torch.Tensor,
- kernel: torch.Tensor,
- border_type: str = 'reflect',
- normalized: bool = False,
- padding: str = 'same',
-) -> torch.Tensor:
+ input: Tensor, kernel: Tensor, border_type: str = 'reflect', normalized: bool = False, padding: str = 'same'
+) -> Tensor:
r"""Convolve a tensor with a 2d kernel.
The function applies a given kernel to a tensor. The kernel is applied
@@ -56,7 +57,7 @@ def filter2d(
2 modes available ``'same'`` or ``'valid'``.
Return:
- torch.Tensor: the convolved tensor of same size and numbers of channels
+ Tensor: the convolved tensor of same size and numbers of channels
as the input with shape :math:`(B, C, H, W)`.
Example:
@@ -74,36 +75,23 @@ def filter2d(
[0., 5., 5., 5., 0.],
[0., 0., 0., 0., 0.]]]])
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input input is not torch.Tensor. Got {type(input)}")
-
- if not isinstance(kernel, torch.Tensor):
- raise TypeError(f"Input kernel is not torch.Tensor. Got {type(kernel)}")
-
- if not isinstance(border_type, str):
- raise TypeError(f"Input border_type is not string. Got {type(border_type)}")
-
- if border_type not in ['constant', 'reflect', 'replicate', 'circular']:
- raise ValueError(
- f"Invalid border type, we expect 'constant', \
- 'reflect', 'replicate', 'circular'. Got:{border_type}"
- )
-
- if not isinstance(padding, str):
- raise TypeError(f"Input padding is not string. Got {type(padding)}")
-
- if padding not in ['valid', 'same']:
- raise ValueError(f"Invalid padding mode, we expect 'valid' or 'same'. Got: {padding}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
-
- if (not len(kernel.shape) == 3) and not ((kernel.shape[0] == 0) or (kernel.shape[0] == input.shape[0])):
- raise ValueError(f"Invalid kernel shape, we expect 1xHxW or BxHxW. Got: {kernel.shape}")
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_IS_TENSOR(kernel)
+ KORNIA_CHECK_SHAPE(kernel, ['B', 'H', 'W'])
+
+ KORNIA_CHECK(
+ str(border_type).lower() in _VALID_BORDERS,
+ f'Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}',
+ )
+ KORNIA_CHECK(
+ str(padding).lower() in _VALID_PADDING,
+ f'Invalid padding mode, gotcha {padding}. Expected one of {_VALID_PADDING}',
+ )
# prepare kernel
b, c, h, w = input.shape
- tmp_kernel: torch.Tensor = kernel.unsqueeze(1).to(input)
+ tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
if normalized:
tmp_kernel = normalize_kernel2d(tmp_kernel)
@@ -114,17 +102,15 @@ def filter2d(
# pad the input tensor
if padding == 'same':
- padding_shape: List[int] = _compute_padding([height, width])
- input = F.pad(input, padding_shape, mode=border_type)
+ padding_shape: list[int] = _compute_padding([height, width])
+ input = pad(input, padding_shape, mode=border_type)
# kernel and input tensor reshape to align element-wise or batch-wise params
tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)
input = input.view(-1, tmp_kernel.size(0), input.size(-2), input.size(-1))
# convolve the tensor with the kernel.
- # NOTE: type(...) to fix getting `torch.bfloat16` type.
- # TODO: @johnnv1, fix it through the Augmentation Base.
- output = F.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1).type(input.dtype)
+ output = F.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
if padding == 'same':
out = output.view(b, c, h, w)
@@ -135,13 +121,13 @@ def filter2d(
def filter2d_separable(
- input: torch.Tensor,
- kernel_x: torch.Tensor,
- kernel_y: torch.Tensor,
+ input: Tensor,
+ kernel_x: Tensor,
+ kernel_y: Tensor,
border_type: str = 'reflect',
normalized: bool = False,
padding: str = 'same',
-) -> torch.Tensor:
+) -> Tensor:
r"""Convolve a tensor with two 1d kernels, in x and y directions.
The function applies a given kernel to a tensor. The kernel is applied
@@ -164,7 +150,7 @@ def filter2d_separable(
2 modes available ``'same'`` or ``'valid'``.
Return:
- torch.Tensor: the convolved tensor of same size and numbers of channels
+ Tensor: the convolved tensor of same size and numbers of channels
as the input with shape :math:`(B, C, H, W)`.
Example:
@@ -183,14 +169,12 @@ def filter2d_separable(
[0., 5., 5., 5., 0.],
[0., 0., 0., 0., 0.]]]])
"""
- out_x = filter2d(input, kernel_x.unsqueeze(-2), border_type, normalized, padding)
- out = filter2d(out_x, kernel_y.unsqueeze(-1), border_type, normalized, padding)
+ out_x = filter2d(input, kernel_x[..., None, :], border_type, normalized, padding)
+ out = filter2d(out_x, kernel_y[..., None], border_type, normalized, padding)
return out
-def filter3d(
- input: torch.Tensor, kernel: torch.Tensor, border_type: str = 'replicate', normalized: bool = False
-) -> torch.Tensor:
+def filter3d(input: Tensor, kernel: Tensor, border_type: str = 'replicate', normalized: bool = False) -> Tensor:
r"""Convolve a tensor with a 3d kernel.
The function applies a given kernel to a tensor. The kernel is applied
@@ -250,24 +234,19 @@ def filter3d(
[0., 5., 5., 5., 0.],
[0., 0., 0., 0., 0.]]]]])
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input border_type is not torch.Tensor. Got {type(input)}")
-
- if not isinstance(kernel, torch.Tensor):
- raise TypeError(f"Input border_type is not torch.Tensor. Got {type(kernel)}")
-
- if not isinstance(border_type, str):
- raise TypeError(f"Input border_type is not string. Got {type(kernel)}")
-
- if not len(input.shape) == 5:
- raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'D', 'H', 'W'])
+ KORNIA_CHECK_IS_TENSOR(kernel)
+ KORNIA_CHECK_SHAPE(kernel, ['B', 'D', 'H', 'W'])
- if not len(kernel.shape) == 4 and kernel.shape[0] != 1:
- raise ValueError(f"Invalid kernel shape, we expect 1xDxHxW. Got: {kernel.shape}")
+ KORNIA_CHECK(
+ str(border_type).lower() in _VALID_BORDERS,
+ f'Invalid border, gotcha {border_type}. Expected one of {_VALID_BORDERS}',
+ )
# prepare kernel
b, c, d, h, w = input.shape
- tmp_kernel: torch.Tensor = kernel.unsqueeze(1).to(input)
+ tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
if normalized:
bk, dk, hk, wk = kernel.shape
@@ -277,8 +256,8 @@ def filter3d(
# pad the input tensor
depth, height, width = tmp_kernel.shape[-3:]
- padding_shape: List[int] = _compute_padding([depth, height, width])
- input_pad: torch.Tensor = F.pad(input, padding_shape, mode=border_type)
+ padding_shape: list[int] = _compute_padding([depth, height, width])
+ input_pad = pad(input, padding_shape, mode=border_type)
# kernel and input tensor reshape to align element-wise or batch-wise params
tmp_kernel = tmp_kernel.reshape(-1, 1, depth, height, width)
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index c32bab9a6..1fe9fafa0 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -1,19 +1,22 @@
-from typing import Tuple
+from __future__ import annotations
-import torch
-import torch.nn as nn
+from typing import Any
+
+from kornia.core import Module, Tensor, tensor
+from kornia.testing import KORNIA_CHECK_IS_TENSOR
+from kornia.utils import deprecated
from .filter import filter2d, filter2d_separable
-from .kernels import get_gaussian_kernel1d_t, get_gaussian_kernel2d_t
+from .kernels import _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2d
def gaussian_blur2d(
- input: torch.Tensor,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
+ input: Tensor,
+ kernel_size: tuple[int, int] | int,
+ sigma: tuple[float, float] | Tensor,
border_type: str = 'reflect',
separable: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
r"""Create an operator that blurs a tensor using a Gaussian filter.
.. image:: _static/img/gaussian_blur2d.png
@@ -42,63 +45,33 @@ def gaussian_blur2d(
>>> output = gaussian_blur2d(input, (3, 3), (1.5, 1.5))
>>> output.shape
torch.Size([2, 4, 5, 5])
- """
- device, dtype = input.device, input.dtype
- sigma_t = torch.tensor(sigma, device=device, dtype=dtype).unsqueeze(0)
-
- return gaussian_blur2d_t(input, kernel_size, sigma_t, border_type, separable)
-
-
-def gaussian_blur2d_t(
- input: torch.Tensor,
- kernel_size: Tuple[int, int],
- sigma: torch.Tensor,
- 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
- The operator smooths the given tensor with a gaussian kernel by convolving
- it to each channel. It supports batched operation.
-
- Arguments:
- input: the input tensor with shape :math:`(B,C,H,W)`.
- kernel_size: the size of the kernel.
- sigma: the standard deviation of the kernel with shape :math:`(B,2)`.
- border_type: the padding mode to be applied before convolving.
- The expected modes are: ``'constant'``, ``'reflect'``,
- ``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
- separable: run as composition of two 1d-convolutions.
-
- Returns:
- the blurred tensor with shape :math:`(B, C, H, W)`.
-
- .. note::
- See a working example `here <https://kornia-tutorials.readthedocs.io/en/latest/
- gaussian_blur.html>`__.
-
- Examples:
- >>> input = torch.rand(2, 4, 5, 5)
- >>> output = gaussian_blur2d_t(input, (3, 3), torch.tensor([[1.5, 1.5]]))
+ >>> output = gaussian_blur2d(input, (3, 3), torch.tensor([[1.5, 1.5]]))
>>> output.shape
torch.Size([2, 4, 5, 5])
"""
- device, dtype = input.device, input.dtype
- sigma = sigma.to(device=device, dtype=dtype)
+ KORNIA_CHECK_IS_TENSOR(input)
+
+ if isinstance(sigma, tuple):
+ sigma = tensor([sigma], device=input.device, dtype=input.dtype)
+ else:
+ KORNIA_CHECK_IS_TENSOR(sigma)
+ sigma = sigma.to(device=input.device, dtype=input.dtype)
if separable:
- kernel_x: torch.Tensor = get_gaussian_kernel1d_t(kernel_size[1], sigma[:, 1])
- kernel_y: torch.Tensor = get_gaussian_kernel1d_t(kernel_size[0], sigma[:, 0])
+ ks = _unpack_2d_ks(kernel_size)
+ bs = sigma.shape[0]
+ kernel_x = get_gaussian_kernel1d(ks[1], sigma[:, 1].view(bs, 1))
+ kernel_y = get_gaussian_kernel1d(ks[0], sigma[:, 0].view(bs, 1))
out = filter2d_separable(input, kernel_x, kernel_y, border_type)
else:
- kernel: torch.Tensor = get_gaussian_kernel2d_t(kernel_size, sigma)
+ kernel = get_gaussian_kernel2d(kernel_size, sigma)
out = filter2d(input, kernel, border_type)
+
return out
-class GaussianBlur2d(nn.Module):
+class GaussianBlur2d(Module):
r"""Create an operator that blurs a tensor using a Gaussian filter.
The operator smooths the given tensor with a gaussian kernel by convolving
@@ -130,14 +103,14 @@ class GaussianBlur2d(nn.Module):
def __init__(
self,
- kernel_size: Tuple[int, int],
- sigma: Tuple[float, float],
+ kernel_size: tuple[int, int] | int,
+ sigma: tuple[float, float] | Tensor,
border_type: str = 'reflect',
separable: bool = True,
) -> None:
super().__init__()
- self.kernel_size: Tuple[int, int] = kernel_size
- self.sigma: Tuple[float, float] = sigma
+ self.kernel_size = kernel_size
+ self.sigma = sigma
self.border_type = border_type
self.separable = separable
@@ -157,5 +130,10 @@ class GaussianBlur2d(nn.Module):
+ ')'
)
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return gaussian_blur2d(input, self.kernel_size, self.sigma, self.border_type, self.separable)
+
+
+@deprecated(replace_with='gaussian_blur2d', version='6.9.10')
+def gaussian_blur2d_t(*args: Any, **kwargs: Any) -> Tensor:
+ return gaussian_blur2d(*args, **kwargs)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 034f1be8f..973aecca2 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -1,50 +1,129 @@
+from __future__ import annotations
+
import math
from math import sqrt
-from typing import List, Tuple
+from typing import Any
import torch
-from kornia.core import Tensor, as_tensor, stack, tensor, zeros
-from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core import Device, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
+from kornia.utils import deprecated
+
+
+def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, allow_even: bool = False):
+ if isinstance(kernel_size, int):
+ kernel_size = (kernel_size,)
+
+ fmt = 'even or odd' if allow_even else 'odd'
+ for size in kernel_size:
+ KORNIA_CHECK(
+ isinstance(size, int) and (((size % 2 == 1) or allow_even) and size > min_value),
+ f'Kernel size must be an {fmt} integer bigger than {min_value}. Gotcha {size} on {kernel_size}',
+ )
+
+
+def _unpack_2d_ks(kernel_size: tuple[int, int] | int) -> tuple[int, int]:
+ if isinstance(kernel_size, int):
+ kx = ky = kernel_size
+ else:
+ KORNIA_CHECK_TYPE(kernel_size, tuple, 'Kernel size should be an integer or a tuple of integer.')
+ KORNIA_CHECK(len(kernel_size) == 2, '2D Kernel size tuple should have a length of 2.')
+ kx, ky = kernel_size
+
+ kx = int(kx)
+ ky = int(ky)
+
+ return (kx, ky)
+
+
+def _unpack_3d_ks(kernel_size: tuple[int, int, int] | int) -> tuple[int, int, int]:
+ if isinstance(kernel_size, int):
+ kx = ky = kz = kernel_size
+ else:
+ KORNIA_CHECK(len(kernel_size) == 3, '3D Kernel size should have a length of 3.')
+ kx, ky, kz = kernel_size
+
+ kx = int(kx)
+ ky = int(ky)
+ kz = int(kz)
+
+ return (kx, ky, kz)
def normalize_kernel2d(input: Tensor) -> Tensor:
r"""Normalize both derivative and smoothing kernel."""
- if len(input.size()) < 2:
- raise TypeError(f"input should be at least 2D tensor. Got {input.size()}")
- norm: Tensor = input.abs().sum(dim=-1).sum(dim=-1)
- return input / (norm.unsqueeze(-1).unsqueeze(-1))
+ KORNIA_CHECK_SHAPE(input, ['*', 'H', 'W'])
+
+ norm = input.abs().sum(dim=-1).sum(dim=-1)
+ return input / (norm[..., None, None])
-def gaussian(window_size: int, sigma: float) -> torch.Tensor:
- sigma_t = torch.tensor(sigma)
- return gaussian_t(window_size, sigma_t)
+def gaussian(
+ window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
+ """Compute the gaussian values based on the window and sigma values.
+ Args:
+ window_size: the size which drives the filter amount.
+ sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
+
+ Returns:
+ A tensor withshape :math:`(B, \text{kernel_size})`, with Gaussian values.
+ """
-def gaussian_t(window_size: int, sigma: torch.Tensor) -> torch.Tensor:
- device, dtype = sigma.device, sigma.dtype
- sigma = sigma.unsqueeze(-1)
+ if isinstance(sigma, float):
+ sigma = tensor([[sigma]], device=device, dtype=dtype)
+
+ KORNIA_CHECK_IS_TENSOR(sigma)
+ KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
batch_size = sigma.shape[0]
- x = (torch.arange(window_size, device=device, dtype=dtype) - window_size // 2).expand(batch_size, -1)
+
+ x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)
+
if window_size % 2 == 0:
x = x + 0.5
+
gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0)))
+
return gauss / gauss.sum(-1, keepdim=True)
-def gaussian_discrete_erf(window_size: int, sigma) -> Tensor:
+def gaussian_discrete_erf(
+ window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
r"""Discrete Gaussian by interpolating the error function.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
+
+ Args:
+ window_size: the size which drives the filter amount.
+ sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
+
+ Returns:
+ A tensor withshape :math:`(B, \text{kernel_size})`, with discrete Gaussian values computed by approximation of
+ the error function.
"""
- device = sigma.device if isinstance(sigma, Tensor) else None
- sigma = as_tensor(sigma, dtype=torch.float, device=device)
- x = torch.arange(window_size).float() - window_size // 2
- t = 0.70710678 / torch.abs(sigma)
+ if isinstance(sigma, float):
+ sigma = tensor([[sigma]], device=device, dtype=dtype)
+
+ KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
+ batch_size = sigma.shape[0]
+
+ x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)
+
+ t = 0.70710678 / sigma.abs()
+ # t = tensor(2, device=sigma.device, dtype=sigma.dtype).sqrt() / (sigma.abs() * 2)
+
gauss = 0.5 * ((t * (x + 0.5)).erf() - (t * (x - 0.5)).erf())
gauss = gauss.clamp(min=0)
- return gauss / gauss.sum()
+
+ return gauss / gauss.sum(-1, keepdim=True)
def _modified_bessel_0(x: Tensor) -> Tensor:
@@ -52,16 +131,25 @@ def _modified_bessel_0(x: Tensor) -> Tensor:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
- if torch.abs(x) < 3.75:
- y = (x / 3.75) * (x / 3.75)
- return 1.0 + y * (
+ ax = torch.abs(x)
+
+ out = zeros_like(x)
+ idx_a = ax < 3.75
+
+ if idx_a.any():
+ y = (x[idx_a] / 3.75) * (x[idx_a] / 3.75)
+ out[idx_a] = 1.0 + y * (
3.5156229 + y * (3.0899424 + y * (1.2067492 + y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2))))
)
- ax = torch.abs(x)
- y = 3.75 / ax
- ans = 0.916281e-2 + y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1 + y * 0.392377e-2)))
- coef = 0.39894228 + y * (0.1328592e-1 + y * (0.225319e-2 + y * (-0.157565e-2 + y * ans)))
- return (torch.exp(ax) / torch.sqrt(ax)) * coef
+
+ idx_b = ~idx_a
+ if idx_b.any():
+ y = 3.75 / ax[idx_b]
+ ans = 0.916281e-2 + y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1 + y * 0.392377e-2)))
+ coef = 0.39894228 + y * (0.1328592e-1 + y * (0.225319e-2 + y * (-0.157565e-2 + y * ans)))
+ out[idx_b] = (ax[idx_b].exp() / ax[idx_b].sqrt()) * coef
+
+ return out
def _modified_bessel_1(x: Tensor) -> Tensor:
@@ -69,16 +157,25 @@ def _modified_bessel_1(x: Tensor) -> Tensor:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
- if torch.abs(x) < 3.75:
- y = (x / 3.75) * (x / 3.75)
- ans = 0.51498869 + y * (0.15084934 + y * (0.2658733e-1 + y * (0.301532e-2 + y * 0.32411e-3)))
- return torch.abs(x) * (0.5 + y * (0.87890594 + y * ans))
ax = torch.abs(x)
- y = 3.75 / ax
- ans = 0.2282967e-1 + y * (-0.2895312e-1 + y * (0.1787654e-1 - y * 0.420059e-2))
- ans = 0.39894228 + y * (-0.3988024e-1 + y * (-0.362018e-2 + y * (0.163801e-2 + y * (-0.1031555e-1 + y * ans))))
- ans = ans * torch.exp(ax) / torch.sqrt(ax)
- return -ans if x < 0.0 else ans
+
+ out = zeros_like(x)
+ idx_a = ax < 3.75
+
+ if idx_a.any():
+ y = (x[idx_a] / 3.75) * (x[idx_a] / 3.75)
+ ans = 0.51498869 + y * (0.15084934 + y * (0.2658733e-1 + y * (0.301532e-2 + y * 0.32411e-3)))
+ out[idx_a] = ax[idx_a] * (0.5 + y * (0.87890594 + y * ans))
+
+ idx_b = ~idx_a
+ if idx_b.any():
+ y = 3.75 / ax[idx_b]
+ ans = 0.2282967e-1 + y * (-0.2895312e-1 + y * (0.1787654e-1 - y * 0.420059e-2))
+ ans = 0.39894228 + y * (-0.3988024e-1 + y * (-0.362018e-2 + y * (0.163801e-2 + y * (-0.1031555e-1 + y * ans))))
+ ans = ans * ax[idx_b].exp() / ax[idx_b].sqrt()
+ out[idx_b] = where(x[idx_b] < 0, -ans, ans)
+
+ return out
def _modified_bessel_i(n: int, x: Tensor) -> Tensor:
@@ -86,37 +183,66 @@ def _modified_bessel_i(n: int, x: Tensor) -> Tensor:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
"""
- if n < 2:
- raise ValueError("n must be greater than 1.")
- if x == 0.0:
+ KORNIA_CHECK(n >= 2, "n must be greater than 1.99")
+
+ if (x == 0.0).all():
return x
- device = x.device
- tox = 2.0 / torch.abs(x)
- ans = tensor(0.0, device=device)
- bip = tensor(0.0, device=device)
- bi = tensor(1.0, device=device)
+
+ batch_size = x.shape[0]
+
+ tox = 2.0 / x.abs()
+ ans = zeros(batch_size, 1, device=x.device, dtype=x.dtype)
+ bip = zeros(batch_size, 1, device=x.device, dtype=x.dtype)
+ bi = torch.ones(batch_size, 1, device=x.device, dtype=x.dtype)
+
m = int(2 * (n + int(sqrt(40.0 * n))))
for j in range(m, 0, -1):
bim = bip + float(j) * tox * bi
bip = bi
bi = bim
- if abs(bi) > 1.0e10:
- ans = ans * 1.0e-10
- bi = bi * 1.0e-10
- bip = bip * 1.0e-10
+ idx = bi.abs() > 1.0e10
+
+ if idx.any():
+ ans[idx] = ans[idx] * 1.0e-10
+ bi[idx] = bi[idx] * 1.0e-10
+ bip[idx] = bip[idx] * 1.0e-10
+
if j == n:
ans = bip
- ans = ans * _modified_bessel_0(x) / bi
- return -ans if x < 0.0 and (n % 2) == 1 else ans
+
+ out = ans * _modified_bessel_0(x) / bi
+
+ if (n % 2) == 1:
+ out = where(x < 0.0, -out, out)
+
+ # TODO: skip the previous computation for x == 0, instead of forcing here
+ out = where(x == 0.0, x, out)
+
+ return out
-def gaussian_discrete(window_size, sigma) -> Tensor:
+def gaussian_discrete(
+ window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
r"""Discrete Gaussian kernel based on the modified Bessel functions.
Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py
+
+ Args:
+ window_size: the size which drives the filter amount.
+ sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
+
+ Returns:
+ A tensor withshape :math:`(B, \text{kernel_size})`, with discrete Gaussian values computed by modified Bessel
+ function.
"""
- device = sigma.device if isinstance(sigma, Tensor) else None
- sigma = as_tensor(sigma, dtype=torch.float, device=device)
+ if isinstance(sigma, float):
+ sigma = tensor([[sigma]], device=device, dtype=dtype)
+
+ KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
+
sigma2 = sigma * sigma
tail = int(window_size // 2) + 1
bessels = [
@@ -124,48 +250,56 @@ def gaussian_discrete(window_size, sigma) -> Tensor:
_modified_bessel_1(sigma2),
*(_modified_bessel_i(k, sigma2) for k in range(2, tail)),
]
+ # NOTE: on monain is exp(-sig)
+ # https://github.com/Project-MONAI/MONAI/blob/dev/monai/networks/layers/convutils.py#L128
+ out = concatenate(bessels[:0:-1] + bessels, -1) * sigma2.exp()
- out = stack(bessels[:0:-1] + bessels, 0) * torch.exp(sigma2)
-
- return out / out.sum()
-
+ return out / out.sum(-1, keepdim=True)
-def laplacian_1d(window_size) -> Tensor:
- r"""One could also use the Laplacian of Gaussian formula to design the filter."""
- filter_1d = torch.ones(window_size)
- filter_1d[window_size // 2] = 1 - window_size
- laplacian_1d: Tensor = filter_1d
- return laplacian_1d
+def laplacian_1d(window_size: int, *, device: Device | None = None, dtype: torch.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)
+ middle = window_size // 2
+ filter_1d[middle] = 1 - window_size
+ return filter_1d
-def get_box_kernel2d(kernel_size: Tuple[int, int]) -> Tensor:
+def get_box_kernel2d(
+ kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
r"""Utility function that returns a box filter."""
- kx: float = float(kernel_size[0])
- ky: float = float(kernel_size[1])
- scale: Tensor = tensor(1.0) / tensor([kx * ky])
- tmp_kernel: Tensor = torch.ones(1, kernel_size[0], kernel_size[1])
- return scale.to(tmp_kernel.dtype) * tmp_kernel
+ kx, ky = _unpack_2d_ks(kernel_size)
+ scale = tensor(1.0, device=device, dtype=dtype) / tensor([kx * ky], device=device, dtype=dtype)
+ return scale.expand(1, kx, ky)
-def get_binary_kernel2d(window_size: Tuple[int, int]) -> Tensor:
- r"""Create a binary kernel to extract the patches.
+def get_binary_kernel2d(
+ window_size: tuple[int, int] | int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
+) -> Tensor:
+ """Create a binary kernel to extract the patches.
- If the window size is HxW will create a (H*W)xHxW kernel.
+ If the window size is HxW will create a (H*W)x1xHxW kernel.
"""
- window_range: int = window_size[0] * window_size[1]
- kernel: Tensor = zeros(window_range, window_range)
- for i in range(window_range):
- kernel[i, i] += 1.0
- return kernel.view(window_range, 1, window_size[0], window_size[1])
+ # TODO: add default dtype as None when kornia relies on torch > 1.12
+
+ kx, ky = _unpack_2d_ks(window_size)
+ window_range = kx * ky
-def get_sobel_kernel_3x3() -> Tensor:
+ kernel = zeros((window_range, window_range), device=device, dtype=dtype)
+ idx = torch.arange(window_range, device=device)
+ kernel[idx, idx] += 1.0
+ return kernel.view(window_range, 1, kx, ky)
+
+
+def get_sobel_kernel_3x3(*, device: Device | None = None, dtype: torch.dtype | None = 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]])
+ 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() -> Tensor:
+def get_sobel_kernel_5x5_2nd_order(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5."""
return tensor(
[
@@ -174,11 +308,13 @@ def get_sobel_kernel_5x5_2nd_order() -> Tensor:
[-6.0, 0.0, 12.0, 0.0, -6.0],
[-4.0, 0.0, 8.0, 0.0, -4.0],
[-1.0, 0.0, 2.0, 0.0, -1.0],
- ]
+ ],
+ device=device,
+ dtype=dtype,
)
-def _get_sobel_kernel_5x5_2nd_order_xy() -> Tensor:
+def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5."""
return tensor(
[
@@ -187,18 +323,20 @@ def _get_sobel_kernel_5x5_2nd_order_xy() -> Tensor:
[0.0, 0.0, 0.0, 0.0, 0.0],
[2.0, 4.0, 0.0, -4.0, -2.0],
[1.0, 2.0, 0.0, -2.0, -1.0],
- ]
+ ],
+ device=device,
+ dtype=dtype,
)
-def get_diff_kernel_3x3() -> Tensor:
+def get_diff_kernel_3x3(*, device: Device | None = None, dtype: torch.dtype | None = 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]])
+ 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=torch.device('cpu'), dtype=torch.float) -> Tensor:
+def get_diff_kernel3d(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3."""
- kernel: Tensor = tensor(
+ kernel = tensor(
[
[
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
@@ -219,12 +357,12 @@ def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> Tensor:
device=device,
dtype=dtype,
)
- return kernel.unsqueeze(1)
+ return kernel[:, None, ...]
-def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -> Tensor:
+def get_diff_kernel3d_2nd_order(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3."""
- kernel: Tensor = tensor(
+ kernel = tensor(
[
[
[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
@@ -260,102 +398,93 @@ def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -
device=device,
dtype=dtype,
)
- return kernel.unsqueeze(1)
+ return kernel[:, None, ...]
-def get_sobel_kernel2d() -> Tensor:
- kernel_x: Tensor = get_sobel_kernel_3x3()
- kernel_y: Tensor = kernel_x.transpose(0, 1)
+def get_sobel_kernel2d(*, device: Device | None = None, dtype: torch.dtype | None = 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() -> Tensor:
- kernel_x: Tensor = get_diff_kernel_3x3()
- kernel_y: Tensor = kernel_x.transpose(0, 1)
+def get_diff_kernel2d(*, device: Device | None = None, dtype: torch.dtype | None = 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() -> Tensor:
- gxx: Tensor = get_sobel_kernel_5x5_2nd_order()
- gyy: Tensor = gxx.transpose(0, 1)
- gxy: Tensor = _get_sobel_kernel_5x5_2nd_order_xy()
+def get_sobel_kernel2d_2nd_order(*, device: Device | None = None, dtype: torch.dtype | None = 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() -> Tensor:
- gxx: Tensor = tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]])
- gyy: Tensor = gxx.transpose(0, 1)
- gxy: Tensor = tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]])
+def get_diff_kernel2d_2nd_order(*, device: Device | None = None, dtype: torch.dtype | None = 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)
return stack([gxx, gxy, gyy])
-def get_spatial_gradient_kernel2d(mode: str, order: int) -> Tensor:
+def get_spatial_gradient_kernel2d(
+ mode: str, order: int, *, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order image gradients, using one of the following operators:
sobel, diff.
"""
- if mode not in ['sobel', 'diff']:
- raise TypeError(
- "mode should be either sobel\
- or diff. Got {}".format(
- mode
- )
- )
- if order not in [1, 2]:
- raise TypeError(
- "order should be either 1 or 2\
- Got {}".format(
- order
- )
- )
+ KORNIA_CHECK(mode.lower() in {'sobel', 'diff'}, f'Mode should be `sobel` or `diff`. Got {mode}')
+ KORNIA_CHECK(order in {1, 2}, f'Order should be 1 or 2. Got {order}')
+
if mode == 'sobel' and order == 1:
- kernel: Tensor = get_sobel_kernel2d()
+ kernel: Tensor = get_sobel_kernel2d(device=device, dtype=dtype)
elif mode == 'sobel' and order == 2:
- kernel = get_sobel_kernel2d_2nd_order()
+ kernel = get_sobel_kernel2d_2nd_order(device=device, dtype=dtype)
elif mode == 'diff' and order == 1:
- kernel = get_diff_kernel2d()
+ kernel = get_diff_kernel2d(device=device, dtype=dtype)
elif mode == 'diff' and order == 2:
- kernel = get_diff_kernel2d_2nd_order()
+ kernel = get_diff_kernel2d_2nd_order(device=device, dtype=dtype)
else:
- raise NotImplementedError("")
+ raise NotImplementedError(f"Not implemented for order {order} on mode {mode}")
+
return kernel
-def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cpu'), dtype=torch.float) -> Tensor:
+def get_spatial_gradient_kernel3d(
+ mode: str, order: int, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the following
operators: sobel, diff."""
- if mode not in ['sobel', 'diff']:
- raise TypeError(
- "mode should be either sobel\
- or diff. Got {}".format(
- mode
- )
- )
- if order not in [1, 2]:
- raise TypeError(
- "order should be either 1 or 2\
- Got {}".format(
- order
- )
- )
- if mode == 'sobel':
- raise NotImplementedError("Sobel kernel for 3d gradient is not implemented yet")
+ KORNIA_CHECK(mode.lower() in {'sobel', 'diff'}, f'Mode should be `sobel` or `diff`. Got {mode}')
+ KORNIA_CHECK(order in {1, 2}, f'Order should be 1 or 2. Got {order}')
+
if mode == 'diff' and order == 1:
- kernel = get_diff_kernel3d(device, dtype)
+ kernel = get_diff_kernel3d(device=device, dtype=dtype)
elif mode == 'diff' and order == 2:
- kernel = get_diff_kernel3d_2nd_order(device, dtype)
+ kernel = get_diff_kernel3d_2nd_order(device=device, dtype=dtype)
else:
- raise NotImplementedError("")
+ raise NotImplementedError(f"Not implemented 3d gradient kernel for order {order} on mode {mode}")
+
return kernel
-def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> Tensor:
+def get_gaussian_kernel1d(
+ kernel_size: int,
+ sigma: float | Tensor,
+ force_even: bool = False,
+ *,
+ device: Device | None = None,
+ dtype: torch.dtype | None = None,
+) -> Tensor:
r"""Function that returns Gaussian filter coefficients.
Args:
kernel_size: filter size. It should be odd and positive.
sigma: gaussian standard deviation.
force_even: overrides requirement for odd kernel size.
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
Returns:
gaussian filter coefficients
@@ -370,114 +499,113 @@ def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = Fal
>>> get_gaussian_kernel1d(5, 1.5)
tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201]])
- """
- sigma_t = torch.tensor(sigma).unsqueeze(0)
-
- return get_gaussian_kernel1d_t(kernel_size, sigma_t, force_even)
-
-def get_gaussian_kernel1d_t(kernel_size: int, sigma: torch.Tensor, force_even: bool = False) -> torch.Tensor:
- r"""Function that returns Gaussian filter coefficients.
-
- Args:
- kernel_size: filter size. It should be odd and positive.
- sigma: gaussian standard deviation with shape of
- :math:`(B)`.
- force_even: overrides requirement for odd kernel size.
-
- Returns:
- gaussian filter coefficients
-
- Shape:
- - Output: :math:`(B, \text{kernel_size})`.
-
- Examples:
-
- >>> get_gaussian_kernel1d_t(3, torch.tensor([2.5]))
- tensor([[0.3243, 0.3513, 0.3243]])
-
- >>> get_gaussian_kernel1d_t(5, torch.tensor([1.5]))
- tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201]])
-
- >>> get_gaussian_kernel1d_t(5, torch.tensor([1.5, 0.7]))
+ >>> get_gaussian_kernel1d(5, torch.tensor([[1.5], [0.7]]))
tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201],
[0.0096, 0.2054, 0.5699, 0.2054, 0.0096]])
"""
- if not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0):
- raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))
+ _check_kernel_size(kernel_size, allow_even=force_even)
- window_1d: torch.Tensor = gaussian_t(kernel_size, sigma)
- return window_1d
+ return gaussian(kernel_size, sigma, device=device, dtype=dtype)
-def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> Tensor:
+def get_gaussian_discrete_kernel1d(
+ kernel_size: int,
+ sigma: float | Tensor,
+ force_even: bool = False,
+ *,
+ device: Device | None = None,
+ dtype: torch.dtype | None = None,
+) -> Tensor:
r"""Function that returns Gaussian filter coefficients based on the modified Bessel functions. Adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
Args:
kernel_size: filter size. It should be odd and positive.
- sigma: gaussian standard deviation.
+ sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
force_even: overrides requirement for odd kernel size.
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
Returns:
1D tensor with gaussian filter coefficients.
Shape:
- - Output: :math:`(\text{kernel_size})`
+ - Output: :math:`(B, \text{kernel_size})`
Examples:
>>> get_gaussian_discrete_kernel1d(3, 2.5)
- tensor([0.3235, 0.3531, 0.3235])
+ tensor([[0.3235, 0.3531, 0.3235]])
>>> get_gaussian_discrete_kernel1d(5, 1.5)
- tensor([0.1096, 0.2323, 0.3161, 0.2323, 0.1096])
+ tensor([[0.1096, 0.2323, 0.3161, 0.2323, 0.1096]])
+ >>> get_gaussian_discrete_kernel1d(5, torch.tensor([[1.5],[2.4]]))
+ tensor([[0.1096, 0.2323, 0.3161, 0.2323, 0.1096],
+ [0.1635, 0.2170, 0.2389, 0.2170, 0.1635]])
"""
- if not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0):
- raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))
- window_1d = gaussian_discrete(kernel_size, sigma)
- return window_1d
+ _check_kernel_size(kernel_size, allow_even=force_even)
+
+ return gaussian_discrete(kernel_size, sigma, device=device, dtype=dtype)
-def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> Tensor:
+def get_gaussian_erf_kernel1d(
+ kernel_size: int,
+ sigma: float | Tensor,
+ force_even: bool = False,
+ *,
+ device: Device | None = None,
+ dtype: torch.dtype | None = None,
+) -> Tensor:
r"""Function that returns Gaussian filter coefficients by interpolating the error function, adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
Args:
kernel_size: filter size. It should be odd and positive.
- sigma: gaussian standard deviation.
+ sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
force_even: overrides requirement for odd kernel size.
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
Returns:
1D tensor with gaussian filter coefficients.
Shape:
- - Output: :math:`(\text{kernel_size})`
+ - Output: :math:`(B, \text{kernel_size})`
Examples:
>>> get_gaussian_erf_kernel1d(3, 2.5)
- tensor([0.3245, 0.3511, 0.3245])
+ tensor([[0.3245, 0.3511, 0.3245]])
>>> get_gaussian_erf_kernel1d(5, 1.5)
- tensor([0.1226, 0.2331, 0.2887, 0.2331, 0.1226])
+ tensor([[0.1226, 0.2331, 0.2887, 0.2331, 0.1226]])
+
+ >>> get_gaussian_erf_kernel1d(5, torch.tensor([[1.5], [2.1]]))
+ tensor([[0.1226, 0.2331, 0.2887, 0.2331, 0.1226],
+ [0.1574, 0.2198, 0.2456, 0.2198, 0.1574]])
"""
- if not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0):
- raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))
- window_1d = gaussian_discrete_erf(kernel_size, sigma)
- return window_1d
+ _check_kernel_size(kernel_size, allow_even=force_even)
+
+ return gaussian_discrete_erf(kernel_size, sigma, device=device, dtype=dtype)
def get_gaussian_kernel2d(
- kernel_size: Tuple[int, int], sigma: Tuple[float, float], force_even: bool = False
-) -> torch.Tensor:
+ kernel_size: tuple[int, int] | int,
+ sigma: tuple[float, float] | Tensor,
+ force_even: bool = False,
+ *,
+ device: Device | None = None,
+ dtype: torch.dtype | None = None,
+) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
- kernel_size: filter sizes in the x and y direction.
- Sizes should be odd and positive.
+ kernel_size: filter sizes in the x and y direction. Sizes should be odd and positive.
sigma: gaussian standard deviation in the x and y.
force_even: overrides requirement for odd kernel size.
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
Returns:
2D tensor with gaussian filter matrix coefficients.
@@ -498,82 +626,45 @@ def get_gaussian_kernel2d(
tensor([[[0.0370, 0.0720, 0.0899, 0.0720, 0.0370],
[0.0462, 0.0899, 0.1123, 0.0899, 0.0462],
[0.0370, 0.0720, 0.0899, 0.0720, 0.0370]]])
- """
-
- sigma_t = torch.tensor(sigma).unsqueeze(0)
- return get_gaussian_kernel2d_t(kernel_size, sigma_t, force_even)
-
-
-def get_gaussian_kernel2d_t(
- kernel_size: Tuple[int, int], sigma: torch.Tensor, force_even: bool = False
-) -> torch.Tensor:
- r"""Function that returns Gaussian filter matrix coefficients.
-
- Args:
- kernel_size: filter sizes in the x and y direction.
- Sizes should be odd and positive.
- sigma: gaussian standard deviation in the x and y
- direction with shape of :math:`(B, 2)`.
- force_even: overrides requirement for odd kernel size.
-
- Returns:
- 2D tensor with gaussian filter matrix coefficients.
-
- Shape:
- - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y)`
-
- Examples:
-
- >>> get_gaussian_kernel2d_t((5, 5), torch.tensor([[1.5, 1.5]]))
+ >>> get_gaussian_kernel2d((5, 5), torch.tensor([[1.5, 1.5]]))
tensor([[[0.0144, 0.0281, 0.0351, 0.0281, 0.0144],
[0.0281, 0.0547, 0.0683, 0.0547, 0.0281],
[0.0351, 0.0683, 0.0853, 0.0683, 0.0351],
[0.0281, 0.0547, 0.0683, 0.0547, 0.0281],
[0.0144, 0.0281, 0.0351, 0.0281, 0.0144]]])
-
- >>> get_gaussian_kernel2d_t((3, 5), torch.tensor([[1.5, 1.5]]))
- tensor([[[0.0370, 0.0720, 0.0899, 0.0720, 0.0370],
- [0.0462, 0.0899, 0.1123, 0.0899, 0.0462],
- [0.0370, 0.0720, 0.0899, 0.0720, 0.0370]]])
-
- >>> get_gaussian_kernel2d_t((5, 5), torch.tensor([[1.5, 1.5], [0.5, 0.5]]))
- tensor([[[1.4419e-02, 2.8084e-02, 3.5073e-02, 2.8084e-02, 1.4419e-02],
- [2.8084e-02, 5.4700e-02, 6.8312e-02, 5.4700e-02, 2.8084e-02],
- [3.5073e-02, 6.8312e-02, 8.5312e-02, 6.8312e-02, 3.5073e-02],
- [2.8084e-02, 5.4700e-02, 6.8312e-02, 5.4700e-02, 2.8084e-02],
- [1.4419e-02, 2.8084e-02, 3.5073e-02, 2.8084e-02, 1.4419e-02]],
- <BLANKLINE>
- [[6.9625e-08, 2.8089e-05, 2.0755e-04, 2.8089e-05, 6.9625e-08],
- [2.8089e-05, 1.1332e-02, 8.3731e-02, 1.1332e-02, 2.8089e-05],
- [2.0755e-04, 8.3731e-02, 6.1869e-01, 8.3731e-02, 2.0755e-04],
- [2.8089e-05, 1.1332e-02, 8.3731e-02, 1.1332e-02, 2.8089e-05],
- [6.9625e-08, 2.8089e-05, 2.0755e-04, 2.8089e-05, 6.9625e-08]]])
"""
- if not isinstance(kernel_size, tuple) or len(kernel_size) != 2:
- raise TypeError(f"kernel_size must be a tuple of length two. Got {kernel_size}")
+ if isinstance(sigma, tuple):
+ sigma = tensor([sigma], device=device, dtype=dtype)
+ KORNIA_CHECK_IS_TENSOR(sigma)
KORNIA_CHECK_SHAPE(sigma, ["B", "2"])
- ksize_x, ksize_y = kernel_size
- sigma_x, sigma_y = sigma[:, 0], sigma[:, 1]
- kernel_x: torch.Tensor = get_gaussian_kernel1d_t(ksize_x, sigma_x, force_even)
- kernel_y: torch.Tensor = get_gaussian_kernel1d_t(ksize_y, sigma_y, force_even)
- kernel_2d: torch.Tensor = torch.matmul(kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).transpose(2, 1))
- return kernel_2d
+ ksize_x, ksize_y = _unpack_2d_ks(kernel_size)
+ sigma_x, sigma_y = sigma[:, 0, None], sigma[:, 1, None]
+
+ kernel_x = get_gaussian_kernel1d(ksize_x, sigma_x, force_even, device=device, dtype=dtype)[..., None]
+ kernel_y = get_gaussian_kernel1d(ksize_y, sigma_y, force_even, device=device, dtype=dtype)[..., None]
+
+ return torch.matmul(kernel_x, kernel_y.transpose(2, 1))
def get_gaussian_kernel3d(
- kernel_size: Tuple[int, int, int], sigma: Tuple[float, float, float], force_even: bool = False
+ kernel_size: tuple[int, int, int] | int,
+ sigma: tuple[float, float, float] | Tensor,
+ force_even: bool = False,
+ *,
+ device: Device | None = None,
+ dtype: torch.dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
- kernel_size: filter sizes in the x, y and z direction.
- Sizes should be odd and positive.
- sigma: gaussian standard deviation in the x, y and z
- direction.
+ kernel_size: filter sizes in the x, y and z direction. Sizes should be odd and positive.
+ sigma: gaussian standard deviation in the x, y and z direction.
force_even: overrides requirement for odd kernel size.
+ device: This value will be used if sigma is a float. Device desired to compute.
+ dtype: This value will be used if sigma is a float. Dtype desired for compute.
Returns:
3D tensor with gaussian filter matrix coefficients.
@@ -598,95 +689,37 @@ def get_gaussian_kernel3d(
tensor(1.)
>>> get_gaussian_kernel3d((3, 3, 3), (1.5, 1.5, 1.5)).shape
torch.Size([1, 3, 3, 3])
+ >>> get_gaussian_kernel3d((3, 7, 5), torch.tensor([[1.5, 1.5, 1.5]])).shape
+ torch.Size([1, 3, 7, 5])
"""
- sigma_t = torch.tensor(sigma).unsqueeze(0)
-
- return get_gaussian_kernel3d_t(kernel_size, sigma_t, force_even)
-
+ if isinstance(sigma, tuple):
+ sigma = tensor([sigma], device=device, dtype=dtype)
-def get_gaussian_kernel3d_t(
- kernel_size: Tuple[int, int, int], sigma: torch.Tensor, force_even: bool = False
-) -> torch.Tensor:
- r"""Function that returns Gaussian filter matrix coefficients.
-
- Args:
- kernel_size: filter sizes in the x, y and z direction.
- Sizes should be odd and positive.
- sigma: gaussian standard deviation in the x, y and z
- direction with shape of :math:`(B, 3)`.
- force_even: overrides requirement for odd kernel size.
-
- Returns:
- 3D tensor with gaussian filter matrix coefficients.
-
- Shape:
- - Output: :math:`(B, \text{kernel_size}_x, \text{kernel_size}_y, \text{kernel_size}_z)`
+ KORNIA_CHECK_IS_TENSOR(sigma)
+ KORNIA_CHECK_SHAPE(sigma, ["B", "3"])
- Examples:
+ ksize_x, ksize_y, ksize_z = _unpack_3d_ks(kernel_size)
+ sigma_x, sigma_y, sigma_z = sigma[:, 0, None], sigma[:, 1, None], sigma[:, 2, None]
- >>> get_gaussian_kernel3d_t((3, 3, 3), torch.tensor([[1.5, 1.5, 1.5]]))
- tensor([[[[0.0292, 0.0364, 0.0292],
- [0.0364, 0.0455, 0.0364],
- [0.0292, 0.0364, 0.0292]],
- <BLANKLINE>
- [[0.0364, 0.0455, 0.0364],
- [0.0455, 0.0568, 0.0455],
- [0.0364, 0.0455, 0.0364]],
- <BLANKLINE>
- [[0.0292, 0.0364, 0.0292],
- [0.0364, 0.0455, 0.0364],
- [0.0292, 0.0364, 0.0292]]]])
- >>> get_gaussian_kernel3d_t((3, 7, 5), torch.tensor([[1.5, 1.5, 1.5]])).shape
- torch.Size([1, 3, 7, 5])
+ kernel_x = get_gaussian_kernel1d(ksize_x, sigma_x, force_even, device=device, dtype=dtype)
+ kernel_y = get_gaussian_kernel1d(ksize_y, sigma_y, force_even, device=device, dtype=dtype)
+ kernel_z = get_gaussian_kernel1d(ksize_z, sigma_z, force_even, device=device, dtype=dtype)
- >>> get_gaussian_kernel3d_t((3, 3, 3), torch.tensor([[1.5, 1.5, 1.5], [0.5, 0.5, 0.5]]))
- tensor([[[[0.0292, 0.0364, 0.0292],
- [0.0364, 0.0455, 0.0364],
- [0.0292, 0.0364, 0.0292]],
- <BLANKLINE>
- [[0.0364, 0.0455, 0.0364],
- [0.0455, 0.0568, 0.0455],
- [0.0364, 0.0455, 0.0364]],
- <BLANKLINE>
- [[0.0292, 0.0364, 0.0292],
- [0.0364, 0.0455, 0.0364],
- [0.0292, 0.0364, 0.0292]]],
- <BLANKLINE>
- <BLANKLINE>
- [[[0.0012, 0.0089, 0.0012],
- [0.0089, 0.0660, 0.0089],
- [0.0012, 0.0089, 0.0012]],
- <BLANKLINE>
- [[0.0089, 0.0660, 0.0089],
- [0.0660, 0.4874, 0.0660],
- [0.0089, 0.0660, 0.0089]],
- <BLANKLINE>
- [[0.0012, 0.0089, 0.0012],
- [0.0089, 0.0660, 0.0089],
- [0.0012, 0.0089, 0.0012]]]])
- """
- KORNIA_CHECK(
- isinstance(kernel_size, tuple) or len(kernel_size) != 3,
- f"kernel_size must be a tuple of length three. Got {kernel_size}",
- )
- KORNIA_CHECK_IS_TENSOR(sigma, "signma must be a tensor")
- KORNIA_CHECK_SHAPE(sigma, ["B", "3"])
+ kernel_2d = kernel_x[..., None] @ kernel_y[..., None].transpose(2, 1)
+ kernel_3d = (kernel_z[:, None, :, None] @ (kernel_2d[..., None].transpose(3, 2))).transpose(3, 2)
- ksize_x, ksize_y, ksize_z = kernel_size
- sigma_x, sigma_y, sigma_z = sigma[:, 0], sigma[:, 1], sigma[:, 2]
- kernel_x: Tensor = get_gaussian_kernel1d_t(ksize_x, sigma_x, force_even)
- kernel_y: Tensor = get_gaussian_kernel1d_t(ksize_y, sigma_y, force_even)
- kernel_z: Tensor = get_gaussian_kernel1d_t(ksize_z, sigma_z, force_even)
- kernel_2d: torch.Tensor = kernel_x[..., None] @ kernel_y[..., None].transpose(2, 1)
- kernel_3d: Tensor = (kernel_z[:, None, :, None] @ (kernel_2d[..., None].transpose(3, 2))).transpose(3, 2)
return kernel_3d
-def get_laplacian_kernel1d(kernel_size: int) -> Tensor:
+def get_laplacian_kernel1d(
+ kernel_size: int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
+) -> Tensor:
r"""Function that returns the coefficients of a 1D Laplacian filter.
Args:
kernel_size: filter size. It should be odd and positive.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
Returns:
1D tensor with laplacian filter coefficients.
@@ -700,17 +733,22 @@ def get_laplacian_kernel1d(kernel_size: int) -> Tensor:
>>> get_laplacian_kernel1d(5)
tensor([ 1., 1., -4., 1., 1.])
"""
- if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size <= 0:
- raise TypeError(f"ksize must be an odd positive integer. Got {kernel_size}")
- window_1d: Tensor = laplacian_1d(kernel_size)
- return window_1d
+ # TODO: add default dtype as None when kornia relies on torch > 1.12
+
+ _check_kernel_size(kernel_size)
+
+ return laplacian_1d(kernel_size, device=device, dtype=dtype)
-def get_laplacian_kernel2d(kernel_size: int) -> Tensor:
+def get_laplacian_kernel2d(
+ kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
+) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
kernel_size: filter size should be odd.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
Returns:
2D tensor with laplacian filter matrix coefficients.
@@ -730,25 +768,37 @@ def get_laplacian_kernel2d(kernel_size: int) -> Tensor:
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
"""
- if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size <= 0:
- raise TypeError(f"ksize must be an odd positive integer. Got {kernel_size}")
+ # TODO: add default dtype as None when kornia relies on torch > 1.12
+
+ kx, ky = _unpack_2d_ks(kernel_size)
+ _check_kernel_size((kx, ky))
+
+ kernel = torch.ones((kx, ky), device=device, dtype=dtype)
+ mid_x = kx // 2
+ mid_y = ky // 2
- kernel = torch.ones((kernel_size, kernel_size))
- mid = kernel_size // 2
- kernel[mid, mid] = 1 - kernel_size**2
- kernel_2d: Tensor = kernel
- return kernel_2d
+ kernel[mid_x, mid_y] = 1 - kernel.sum()
+ return kernel
-def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> Tensor:
+def get_pascal_kernel_2d(
+ kernel_size: tuple[int, int] | int,
+ norm: bool = True,
+ *,
+ device: Device | None = None,
+ dtype: torch.dtype | None = None,
+) -> Tensor:
"""Generate pascal filter kernel by kernel size.
Args:
kernel_size: height and width of the kernel.
norm: if to normalize the kernel or not. Default: True.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
Returns:
- kernel shaped as :math:`(kernel_size, kernel_size)`
+ if kernel_size is an integer the kernel will be shaped as :math:`(kernel_size, kernel_size)`
+ otherwise the kernel will be shaped as :math: `kernel_size`
Examples:
>>> get_pascal_kernel_2d(1)
@@ -764,20 +814,26 @@ def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> Tensor:
[3., 9., 9., 3.],
[1., 3., 3., 1.]])
"""
- a = get_pascal_kernel_1d(kernel_size)
+ kx, ky = _unpack_2d_ks(kernel_size)
+ ax = get_pascal_kernel_1d(kx, device=device, dtype=dtype)
+ ay = get_pascal_kernel_1d(ky, device=device, dtype=dtype)
- filt = a[:, None] * a[None, :]
+ filt = ax[:, None] * ay[None, :]
if norm:
filt = filt / torch.sum(filt)
return filt
-def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> Tensor:
+def get_pascal_kernel_1d(
+ kernel_size: int, norm: bool = False, *, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
"""Generate Yang Hui triangle (Pascal's triangle) by a given number.
Args:
kernel_size: height and width of the kernel.
norm: if to normalize the kernel or not. Default: False.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
Returns:
kernel shaped as :math:`(kernel_size,)`
@@ -796,8 +852,8 @@ def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> Tensor:
>>> get_pascal_kernel_1d(6)
tensor([ 1., 5., 10., 10., 5., 1.])
"""
- pre: List[float] = []
- cur: List[float] = []
+ pre: list[float] = []
+ cur: list[float] = []
for i in range(kernel_size):
cur = [1.0] * (i + 1)
@@ -808,51 +864,51 @@ def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> Tensor:
cur[-j - 1] = value
pre = cur
- out = as_tensor(cur)
+ out = tensor(cur, device=device, dtype=dtype)
+
if norm:
- out = out / torch.sum(out)
+ out = out / out.sum()
+
return out
-def get_canny_nms_kernel(device=torch.device('cpu'), dtype=torch.float) -> Tensor:
+def get_canny_nms_kernel(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
"""Utility function that returns 3x3 kernels for the Canny Non-maximal suppression."""
- kernel: Tensor = tensor(
+ return tensor(
[
- [[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]],
- [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]],
- [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]],
- [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]],
- [[0.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]],
- [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]],
- [[0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]],
- [[0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]],
+ [[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [-1.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
+ [[[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, -1.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]],
],
device=device,
dtype=dtype,
)
- return kernel.unsqueeze(1)
-def get_hysteresis_kernel(device=torch.device('cpu'), dtype=torch.float) -> Tensor:
+def get_hysteresis_kernel(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
"""Utility function that returns the 3x3 kernels for the Canny hysteresis."""
- kernel: Tensor = tensor(
+ return tensor(
[
- [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]],
- [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]],
- [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
- [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]],
- [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
- [[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
- [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
- [[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
+ [[[1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
+ [[[0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]],
],
device=device,
dtype=dtype,
)
- return kernel.unsqueeze(1)
-def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=torch.float) -> Tensor:
+def get_hanning_kernel1d(kernel_size: int, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
r"""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)
@@ -862,6 +918,8 @@ def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=tor
Args:
kernel_size: The size the of the kernel. It should be positive.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
Returns:
1D tensor with Hanning filter coefficients.
@@ -874,19 +932,22 @@ def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=tor
>>> get_hanning_kernel1d(4)
tensor([0.0000, 0.7500, 0.7500, 0.0000])
"""
- if not isinstance(kernel_size, int) or kernel_size <= 2:
- raise TypeError(f"ksize must be an positive integer > 2. Got {kernel_size}")
+ _check_kernel_size(kernel_size, 2, allow_even=True)
- x: Tensor = torch.arange(kernel_size, device=device, dtype=dtype)
+ x = torch.arange(kernel_size, device=device, dtype=dtype)
x = 0.5 - 0.5 * torch.cos(2.0 * math.pi * x / float(kernel_size - 1))
return x
-def get_hanning_kernel2d(kernel_size: Tuple[int, int], device=torch.device('cpu'), dtype=torch.float) -> Tensor:
- r"""Returns 2d Hanning kernel, used in signal processing and KCF tracker.
+def get_hanning_kernel2d(
+ kernel_size: tuple[int, int] | int, device: Device | None = None, dtype: torch.dtype | None = None
+) -> Tensor:
+ """Returns 2d Hanning kernel, used in signal processing and KCF tracker.
Args:
kernel_size: The size of the kernel for the filter. It should be positive.
+ device: tensor device desired to create the kernel
+ dtype: tensor dtype desired to create the kernel
Returns:
2D tensor with Hanning filter coefficients.
@@ -895,9 +956,26 @@ def get_hanning_kernel2d(kernel_size: Tuple[int, int], device=torch.device('cpu'
Shape:
- Output: math:`(\text{kernel_size[0], kernel_size[1]})`
"""
- if kernel_size[0] <= 2 or kernel_size[1] <= 2:
- raise TypeError(f"ksize must be an tuple of positive integers > 2. Got {kernel_size}")
- ky: Tensor = get_hanning_kernel1d(kernel_size[0], device, dtype)[None].T
- kx: Tensor = get_hanning_kernel1d(kernel_size[1], device, dtype)[None]
+ kernel_size = _unpack_2d_ks(kernel_size)
+ _check_kernel_size(kernel_size, 2, allow_even=True)
+
+ ky = get_hanning_kernel1d(kernel_size[0], device, dtype)[None].T
+ kx = get_hanning_kernel1d(kernel_size[1], device, dtype)[None]
kernel2d = ky @ kx
+
return kernel2d
+
+
+@deprecated(replace_with='get_gaussian_kernel1d', version='6.9.10')
+def get_gaussian_kernel1d_t(*args: Any, **kwargs: Any) -> Tensor:
+ return get_gaussian_kernel1d(*args, **kwargs)
+
+
+@deprecated(replace_with='get_gaussian_kernel2d', version='6.9.10')
+def get_gaussian_kernel2d_t(*args: Any, **kwargs: Any) -> Tensor:
+ return get_gaussian_kernel2d(*args, **kwargs)
+
+
+@deprecated(replace_with='get_gaussian_kernel3d', version='6.9.10')
+def get_gaussian_kernel3d_t(*args: Any, **kwargs: Any) -> Tensor:
+ return get_gaussian_kernel3d(*args, **kwargs)
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index 62cbb5119..21c9c9ea4 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -1,14 +1,17 @@
-from typing import Tuple, Union
+from __future__ import annotations
import torch
from kornia.core import Tensor, pad, stack, tensor, zeros
from kornia.geometry.transform import rotate, rotate3d
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils import _extract_device_dtype
+from .kernels import _check_kernel_size, _unpack_2d_ks, _unpack_3d_ks
+
def get_motion_kernel2d(
- kernel_size: int, angle: Union[Tensor, float], direction: Union[Tensor, float] = 0.0, mode: str = 'nearest'
+ kernel_size: int, angle: Tensor | float, direction: Tensor | float = 0.0, mode: str = 'nearest'
) -> Tensor:
r"""Return 2D motion blur filter.
@@ -41,31 +44,29 @@ def get_motion_kernel2d(
[angle if isinstance(angle, Tensor) else None, direction if isinstance(direction, Tensor) else None]
)
- if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size < 3:
- raise TypeError("ksize must be an odd integer >= than 3")
+ # TODO: add support to kernel_size as tuple or integer
+ kernel_tuple = _unpack_2d_ks(kernel_size)
+ _check_kernel_size(kernel_size, 2)
if not isinstance(angle, Tensor):
angle = tensor([angle], device=device, dtype=dtype)
if angle.dim() == 0:
- angle = angle.unsqueeze(0)
+ angle = angle[None]
- if angle.dim() != 1:
- raise AssertionError(f"angle must be a 1-dim tensor. Got {angle}.")
+ KORNIA_CHECK_SHAPE(angle, ['B'])
if not isinstance(direction, Tensor):
direction = tensor([direction], device=device, dtype=dtype)
if direction.dim() == 0:
- direction = direction.unsqueeze(0)
-
- if direction.dim() != 1:
- raise AssertionError(f"direction must be a 1-dim tensor. Got {direction}.")
-
- if direction.size(0) != angle.size(0):
- raise AssertionError(f"direction and angle must have the same length. Got {direction} and {angle}.")
+ direction = direction[None]
- kernel_tuple: Tuple[int, int] = (kernel_size, kernel_size)
+ KORNIA_CHECK_SHAPE(direction, ['B'])
+ KORNIA_CHECK(
+ direction.size(0) == angle.size(0),
+ f'direction and angle must have the same length. Got {direction} and {angle}.',
+ )
# direction from [-1, 1] to [0, 1] range
direction = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0
@@ -80,9 +81,9 @@ def get_motion_kernel2d(
k = stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], -1)
kernel = pad(k[:, None], [0, 0, kernel_size // 2, kernel_size // 2, 0, 0])
- if kernel.shape != torch.Size([direction.size(0), *kernel_tuple]):
- raise AssertionError
- kernel = kernel.unsqueeze(1)
+ expected_shape = torch.Size([direction.size(0), *kernel_tuple])
+ KORNIA_CHECK(kernel.shape == expected_shape, f'Kernel shape should be {expected_shape}. Gotcha {kernel.shape}')
+ kernel = kernel[:, None, ...]
# rotate (counterclockwise) kernel by given angle
kernel = rotate(kernel, angle, mode=mode, align_corners=True)
@@ -92,10 +93,7 @@ def get_motion_kernel2d(
def get_motion_kernel3d(
- kernel_size: int,
- angle: Union[Tensor, Tuple[float, float, float]],
- direction: Union[Tensor, float] = 0.0,
- mode: str = 'nearest',
+ kernel_size: int, angle: Tensor | tuple[float, float, float], direction: Tensor | float = 0.0, mode: str = 'nearest'
) -> Tensor:
r"""Return 3D motion blur filter.
@@ -140,35 +138,33 @@ def get_motion_kernel3d(
[0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000]]]])
"""
- if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size < 3:
- raise TypeError(f"ksize must be an odd integer >= than 3. Got {kernel_size}.")
-
device, dtype = _extract_device_dtype(
[angle if isinstance(angle, Tensor) else None, direction if isinstance(direction, Tensor) else None]
)
+ # TODO: add support to kernel_size as tuple or integer
+ kernel_tuple = _unpack_3d_ks(kernel_size)
+ _check_kernel_size(kernel_size, 2)
+
if not isinstance(angle, Tensor):
angle = tensor([angle], device=device, dtype=dtype)
if angle.dim() == 1:
- angle = angle.unsqueeze(0)
+ angle = angle[None]
- if not (len(angle.shape) == 2 and angle.size(1) == 3):
- raise AssertionError(f"angle must be (B, 3). Got {angle}.")
+ KORNIA_CHECK_SHAPE(angle, ['B', '3'])
if not isinstance(direction, Tensor):
direction = tensor([direction], device=device, dtype=dtype)
if direction.dim() == 0:
- direction = direction.unsqueeze(0)
-
- if direction.dim() != 1:
- raise AssertionError(f"direction must be a 1-dim tensor. Got {direction}.")
+ direction = direction[None]
- if direction.size(0) != angle.size(0):
- raise AssertionError(f"direction and angle must have the same length. Got {direction} and {angle}.")
-
- kernel_tuple: Tuple[int, int, int] = (kernel_size, kernel_size, kernel_size)
+ KORNIA_CHECK_SHAPE(direction, ['B'])
+ KORNIA_CHECK(
+ direction.size(0) == angle.size(0),
+ f'direction and angle must have the same batch size. Got {direction.shape} and {angle.shape}.',
+ )
# direction from [-1, 1] to [0, 1] range
direction = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0
@@ -180,9 +176,9 @@ def get_motion_kernel3d(
k = stack([(direction + ((1 - 2 * direction) / (kernel_size - 1)) * i) for i in range(kernel_size)], -1)
kernel = pad(k[:, None, None], [0, 0, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, 0, 0])
- if kernel.shape != torch.Size([direction.size(0), *kernel_tuple]):
- raise AssertionError
- kernel = kernel.unsqueeze(1)
+ expected_shape = torch.Size([direction.size(0), *kernel_tuple])
+ KORNIA_CHECK(kernel.shape == expected_shape, f'Kernel shape should be {expected_shape}. Gotcha {kernel.shape}')
+ kernel = kernel[:, None, ...]
# rotate (counterclockwise) kernel by given angle
kernel = rotate3d(kernel, angle[:, 0], angle[:, 1], angle[:, 2], mode=mode, align_corners=True)
diff --git a/kornia/filters/laplacian.py b/kornia/filters/laplacian.py
index 6b62292a5..5196d06e4 100644
--- a/kornia/filters/laplacian.py
+++ b/kornia/filters/laplacian.py
@@ -1,13 +1,14 @@
-import torch
-import torch.nn as nn
+from __future__ import annotations
+
+from kornia.core import Module, Tensor
from .filter import filter2d
from .kernels import get_laplacian_kernel2d, normalize_kernel2d
def laplacian(
- input: torch.Tensor, kernel_size: int, border_type: str = 'reflect', normalized: bool = True
-) -> torch.Tensor:
+ input: Tensor, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', normalized: bool = True
+) -> Tensor:
r"""Create an operator that returns a tensor using a Laplacian filter.
.. image:: _static/img/laplacian.png
@@ -36,7 +37,7 @@ def laplacian(
>>> output.shape
torch.Size([2, 4, 5, 5])
"""
- kernel: torch.Tensor = torch.unsqueeze(get_laplacian_kernel2d(kernel_size), dim=0)
+ kernel = get_laplacian_kernel2d(kernel_size, device=input.device, dtype=input.dtype)[None, ...]
if normalized:
kernel = normalize_kernel2d(kernel)
@@ -44,7 +45,7 @@ def laplacian(
return filter2d(input, kernel, border_type)
-class Laplacian(nn.Module):
+class Laplacian(Module):
r"""Create an operator that returns a tensor using a Laplacian filter.
The operator smooths the given tensor with a laplacian kernel by convolving
@@ -69,9 +70,11 @@ class Laplacian(nn.Module):
torch.Size([2, 4, 5, 5])
"""
- def __init__(self, kernel_size: int, border_type: str = 'reflect', normalized: bool = True) -> None:
+ def __init__(
+ self, kernel_size: tuple[int, int] | int, border_type: str = 'reflect', normalized: bool = True
+ ) -> None:
super().__init__()
- self.kernel_size: int = kernel_size
+ self.kernel_size = kernel_size
self.border_type: str = border_type
self.normalized: bool = normalized
@@ -89,5 +92,5 @@ class Laplacian(nn.Module):
+ ')'
)
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return laplacian(input, self.kernel_size, self.border_type, self.normalized)
diff --git a/kornia/filters/median.py b/kornia/filters/median.py
index 3d9e26910..6782d8c41 100644
--- a/kornia/filters/median.py
+++ b/kornia/filters/median.py
@@ -1,19 +1,20 @@
-from typing import List, Tuple
+from __future__ import annotations
-import torch
-import torch.nn as nn
import torch.nn.functional as F
-from .kernels import get_binary_kernel2d
+from kornia.core import Module, Tensor
+from kornia.testing import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from .kernels import _unpack_2d_ks, get_binary_kernel2d
-def _compute_zero_padding(kernel_size: Tuple[int, int]) -> Tuple[int, int]:
+
+def _compute_zero_padding(kernel_size: tuple[int, int] | int) -> tuple[int, int]:
r"""Utility function that computes zero padding tuple."""
- computed: List[int] = [(k - 1) // 2 for k in kernel_size]
- return computed[0], computed[1]
+ kx, ky = _unpack_2d_ks(kernel_size)
+ return (kx - 1) // 2, (ky - 1) // 2
-def median_blur(input: torch.Tensor, kernel_size: Tuple[int, int]) -> torch.Tensor:
+def median_blur(input: Tensor, kernel_size: tuple[int, int] | int) -> Tensor:
r"""Blur an image using the median filter.
.. image:: _static/img/median_blur.png
@@ -35,29 +36,24 @@ def median_blur(input: torch.Tensor, kernel_size: Tuple[int, int]) -> torch.Tens
>>> output.shape
torch.Size([2, 4, 5, 7])
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
- padding: Tuple[int, int] = _compute_zero_padding(kernel_size)
+ padding = _compute_zero_padding(kernel_size)
# prepare kernel
- kernel: torch.Tensor = get_binary_kernel2d(kernel_size).to(input)
+ kernel: Tensor = get_binary_kernel2d(kernel_size, device=input.device, dtype=input.dtype)
b, c, h, w = input.shape
# map the local window to single vector
- features: torch.Tensor = F.conv2d(input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
+ features: Tensor = F.conv2d(input.reshape(b * c, 1, h, w), kernel, padding=padding, stride=1)
features = features.view(b, c, -1, h, w) # BxCx(K_h * K_w)xHxW
# compute the median along the feature axis
- median: torch.Tensor = torch.median(features, dim=2)[0]
-
- return median
+ return features.median(dim=2)[0]
-class MedianBlur(nn.Module):
+class MedianBlur(Module):
r"""Blur an image using the median filter.
Args:
@@ -78,9 +74,9 @@ class MedianBlur(nn.Module):
torch.Size([2, 4, 5, 7])
"""
- def __init__(self, kernel_size: Tuple[int, int]) -> None:
+ def __init__(self, kernel_size: tuple[int, int] | int) -> None:
super().__init__()
- self.kernel_size: Tuple[int, int] = kernel_size
+ self.kernel_size = kernel_size
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return median_blur(input, self.kernel_size)
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 3a0ac7414..96dafea0f 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -1,13 +1,15 @@
-from typing import Tuple, Union
+from __future__ import annotations
-import torch
-import torch.nn as nn
+from kornia.core import Module, Tensor
+from kornia.testing import KORNIA_CHECK
from .filter import filter2d, filter3d
from .kernels_geometry import get_motion_kernel2d, get_motion_kernel3d
+_VALID_BORDER = {"constant", "reflect", "replicate", "circular"}
-class MotionBlur(nn.Module):
+
+class MotionBlur(Module):
r"""Blur 2D images (4D tensor) using the motion filter.
Args:
@@ -18,7 +20,8 @@ class MotionBlur(nn.Module):
while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to a
uniformly (but still angled) motion blur.
border_type: the padding mode to be applied before convolving. The expected modes are:
- ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
+ ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
+ mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
Returns:
the blurred input tensor.
@@ -33,12 +36,15 @@ class MotionBlur(nn.Module):
>>> output = motion_blur(input) # 2x4x5x7
"""
- def __init__(self, kernel_size: int, angle: float, direction: float, border_type: str = 'constant') -> None:
+ def __init__(
+ self, kernel_size: int, angle: float, direction: float, border_type: str = 'constant', mode: str = 'nearest'
+ ) -> None:
super().__init__()
self.kernel_size = kernel_size
- self.angle: float = angle
- self.direction: float = direction
- self.border_type: str = border_type
+ self.angle = angle
+ self.direction = direction
+ self.border_type = border_type
+ self.mode = mode
def __repr__(self) -> str:
return (
@@ -46,11 +52,11 @@ class MotionBlur(nn.Module):
f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
)
- def forward(self, x: torch.Tensor):
+ def forward(self, x: Tensor):
return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)
-class MotionBlur3D(nn.Module):
+class MotionBlur3D(Module):
r"""Blur 3D volumes (5D tensor) using the motion filter.
Args:
@@ -62,6 +68,7 @@ class MotionBlur3D(nn.Module):
uniformly (but still angled) motion blur.
border_type: the padding mode to be applied before convolving. The expected modes are:
``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
+ mode: interpolation mode for rotating the kernel. ``'bilinear'`` or ``'nearest'``.
Returns:
the blurred input tensor.
@@ -79,21 +86,25 @@ class MotionBlur3D(nn.Module):
def __init__(
self,
kernel_size: int,
- angle: Union[float, Tuple[float, float, float]],
- direction: float,
+ angle: float | tuple[float, float, float] | Tensor,
+ direction: float | Tensor,
border_type: str = 'constant',
+ mode: str = 'nearest',
) -> None:
super().__init__()
self.kernel_size = kernel_size
- self.angle: Tuple[float, float, float]
+ KORNIA_CHECK(
+ isinstance(angle, (Tensor, float, list, tuple)),
+ f'Angle should be a Tensor, float or a sequence of floats. Got {angle}',
+ )
if isinstance(angle, float):
self.angle = (angle, angle, angle)
elif isinstance(angle, (tuple, list)) and len(angle) == 3:
- self.angle = angle
- else:
- raise ValueError(f"Expect angle to be either a float or a tuple of floats. Got {angle}.")
- self.direction: float = direction
- self.border_type: str = border_type
+ self.angle = (angle[0], angle[1], angle[2])
+
+ self.direction = direction
+ self.border_type = border_type
+ self.mode = mode
def __repr__(self) -> str:
return (
@@ -101,18 +112,18 @@ class MotionBlur3D(nn.Module):
f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
)
- def forward(self, x: torch.Tensor):
+ def forward(self, x: Tensor):
return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type)
def motion_blur(
- input: torch.Tensor,
+ input: Tensor,
kernel_size: int,
- angle: Union[float, torch.Tensor],
- direction: Union[float, torch.Tensor],
+ angle: float | Tensor,
+ direction: float | Tensor,
border_type: str = 'constant',
mode: str = 'nearest',
-) -> torch.Tensor:
+) -> Tensor:
r"""Perform motion blur on tensor images.
.. image:: _static/img/motion_blur.png
@@ -145,20 +156,18 @@ def motion_blur(
>>> torch.allclose(out_1[0], out_1[1])
False
"""
- if border_type not in ["constant", "reflect", "replicate", "circular"]:
- raise AssertionError
- kernel: torch.Tensor = get_motion_kernel2d(kernel_size, angle, direction, mode)
+ kernel = get_motion_kernel2d(kernel_size, angle, direction, mode)
return filter2d(input, kernel, border_type)
def motion_blur3d(
- input: torch.Tensor,
+ input: Tensor,
kernel_size: int,
- angle: Union[Tuple[float, float, float], torch.Tensor],
- direction: Union[float, torch.Tensor],
+ angle: tuple[float, float, float] | Tensor,
+ direction: float | Tensor,
border_type: str = 'constant',
mode: str = 'nearest',
-) -> torch.Tensor:
+) -> Tensor:
r"""Perform motion blur on 3D volumes (5D tensor).
Args:
@@ -189,7 +198,5 @@ def motion_blur3d(
>>> torch.allclose(out_1[0], out_1[1])
False
"""
- if border_type not in ["constant", "reflect", "replicate", "circular"]:
- raise AssertionError
- kernel: torch.Tensor = get_motion_kernel3d(kernel_size, angle, direction, mode)
+ kernel = get_motion_kernel3d(kernel_size, angle, direction, mode)
return filter3d(input, kernel, border_type)
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 08b59c83f..2f1ad69ad 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -1,7 +1,10 @@
+from __future__ import annotations
+
import torch
import torch.nn.functional as F
from kornia.core import Module, Tensor, pad
+from kornia.testing import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
@@ -30,20 +33,17 @@ def spatial_gradient(input: Tensor, mode: str = 'sobel', order: int = 1, normali
>>> output.shape
torch.Size([1, 3, 2, 4, 4])
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
# allocate kernel
- kernel: Tensor = get_spatial_gradient_kernel2d(mode, order)
+ kernel = get_spatial_gradient_kernel2d(mode, order, device=input.device, dtype=input.dtype)
if normalized:
kernel = normalize_kernel2d(kernel)
# prepare kernel
b, c, h, w = input.shape
- tmp_kernel: Tensor = kernel.to(input).detach()
- tmp_kernel = tmp_kernel.unsqueeze(1)
+ tmp_kernel = kernel[:, None, ...]
# Pad with "replicate for spatial dims, but with zeros for channel
spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2]
@@ -71,11 +71,9 @@ def spatial_gradient3d(input: Tensor, mode: str = 'diff', order: int = 1) -> Ten
>>> output.shape
torch.Size([1, 4, 3, 2, 4, 4])
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'D', 'H', 'W'])
- if not len(input.shape) == 5:
- raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
b, c, d, h, w = input.shape
dev = input.device
dtype = input.dtype
@@ -93,13 +91,12 @@ def spatial_gradient3d(input: Tensor, mode: str = 'diff', order: int = 1) -> Ten
else:
# prepare kernel
# allocate kernel
- kernel: Tensor = get_spatial_gradient_kernel3d(mode, order)
+ kernel = get_spatial_gradient_kernel3d(mode, order, device=dev, dtype=dtype)
- tmp_kernel: Tensor = kernel.to(input).detach()
- tmp_kernel = tmp_kernel.repeat(c, 1, 1, 1, 1)
+ tmp_kernel = kernel.repeat(c, 1, 1, 1, 1)
# convolve input tensor with grad kernel
- kernel_flip: Tensor = tmp_kernel.flip(-3)
+ kernel_flip = tmp_kernel.flip(-3)
# Pad with "replicate for spatial dims, but with zeros for channel
spatial_pad = [
@@ -140,11 +137,8 @@ def sobel(input: Tensor, normalized: bool = True, eps: float = 1e-6) -> Tensor:
>>> output.shape
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(input, Tensor):
- raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_SHAPE(input, ['B', 'C', 'H', 'W'])
# comput the x/y gradients
edges: Tensor = spatial_gradient(input, normalized=normalized)
diff --git a/kornia/filters/unsharp.py b/kornia/filters/unsharp.py
index 809101bce..1ff21e1bf 100644
--- a/kornia/filters/unsharp.py
+++ b/kornia/filters/unsharp.py
@@ -1,14 +1,13 @@
-from typing import Tuple
+from __future__ import annotations
-import torch
-import torch.nn as nn
+from kornia.core import Module, Tensor
from .gaussian import gaussian_blur2d
def unsharp_mask(
- input: torch.Tensor, kernel_size: Tuple[int, int], sigma: Tuple[float, float], border_type: str = 'reflect'
-) -> torch.Tensor:
+ input: Tensor, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = 'reflect'
+) -> Tensor:
r"""Create an operator that sharpens a tensor by applying operation out = 2 * image - gaussian_blur2d(image).
.. image:: _static/img/unsharp_mask.png
@@ -30,12 +29,12 @@ def unsharp_mask(
>>> output.shape
torch.Size([2, 4, 5, 5])
"""
- data_blur: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma, border_type)
- data_sharpened: torch.Tensor = input + (input - data_blur)
+ data_blur: Tensor = gaussian_blur2d(input, kernel_size, sigma, border_type)
+ data_sharpened: Tensor = input + (input - data_blur)
return data_sharpened
-class UnsharpMask(nn.Module):
+class UnsharpMask(Module):
r"""Create an operator that sharpens image with: out = 2 * image - gaussian_blur2d(image).
Args:
@@ -64,11 +63,13 @@ class UnsharpMask(nn.Module):
torch.Size([2, 4, 5, 5])
"""
- def __init__(self, kernel_size: Tuple[int, int], sigma: Tuple[float, float], border_type: str = 'reflect') -> None:
+ def __init__(
+ self, kernel_size: tuple[int, int] | int, sigma: tuple[float, float] | Tensor, border_type: str = 'reflect'
+ ) -> None:
super().__init__()
- self.kernel_size: Tuple[int, int] = kernel_size
- self.sigma: Tuple[float, float] = sigma
+ self.kernel_size = kernel_size
+ self.sigma = sigma
self.border_type = border_type
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return unsharp_mask(input, self.kernel_size, self.sigma, self.border_type)
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index aff69da8f..4d3c15538 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -4,7 +4,7 @@ import torch
import torch.nn.functional as F
from kornia.filters import filter2d
-from kornia.filters.kernels import get_gaussian_kernel2d_t
+from kornia.filters.kernels import get_gaussian_kernel2d
from kornia.utils import create_meshgrid
__all__ = ["elastic_transform2d"]
@@ -82,8 +82,8 @@ def elastic_transform2d(
sigma_t = sigma.to(device=device, dtype=dtype)
# Get Gaussian kernel for 'y' and 'x' displacement
- kernel_x: torch.Tensor = get_gaussian_kernel2d_t(kernel_size, sigma_t[0].expand(2).unsqueeze(0))
- kernel_y: torch.Tensor = get_gaussian_kernel2d_t(kernel_size, sigma_t[1].expand(2).unsqueeze(0))
+ kernel_x: torch.Tensor = get_gaussian_kernel2d(kernel_size, sigma_t[0].expand(2).unsqueeze(0))
+ kernel_y: torch.Tensor = get_gaussian_kernel2d(kernel_size, sigma_t[1].expand(2).unsqueeze(0))
# Convolve over a random displacement matrix and scale them with 'alpha'
disp_x: torch.Tensor = noise[:, :1]
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 9ff65c361..40679571d 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -104,9 +104,17 @@ def create_random_fundamental_matrix(batch_size, std_val=1e-3):
return H_left.permute(0, 2, 1) @ F_rect @ H_right
-class BaseTester(ABC):
- DTYPE_PRECISIONS = {torch.float16: (1e-3, 1e-3), torch.float32: (1.3e-6, 1e-5), torch.float64: (1.3e-6, 1e-5)}
+# {dtype: (rtol, atol)}
+_DTYPE_PRECISIONS = {
+ torch.bfloat16: (7.8e-3, 7.8e-3),
+ torch.float16: (9.7e-4, 9.7e-4),
+ torch.float32: (1e-4, 1e-5), # TODO: Update to ~1.2e-7
+ # TODO: Update to ~2.3e-16 for fp64
+ torch.float64: (1e-5, 1e-5), # TODO: BaseTester used (1.3e-6, 1e-5), but it fails for general cases
+}
+
+class BaseTester(ABC):
@abstractmethod
def test_smoke(self, device, dtype):
raise NotImplementedError("Implement a stupid routine.")
@@ -121,7 +129,7 @@ class BaseTester(ABC):
# TODO: add @abstractmethod
def test_dynamo(self, device, dtype, torch_optimizer):
- pass
+ pass # TODO: raise NotImplementedError -- now we see a bunch of dynamo tests running by inheritance
@abstractmethod
def test_gradcheck(self, device):
@@ -159,8 +167,8 @@ class BaseTester(ABC):
rtol, atol = 1e-2, 1e-2
if rtol is None and atol is None:
- actual_rtol, actual_atol = self.DTYPE_PRECISIONS.get(actual.dtype, (0.0, 0.0))
- expected_rtol, expected_atol = self.DTYPE_PRECISIONS.get(expected.dtype, (0.0, 0.0))
+ actual_rtol, actual_atol = _DTYPE_PRECISIONS.get(actual.dtype, (0.0, 0.0))
+ expected_rtol, expected_atol = _DTYPE_PRECISIONS.get(expected.dtype, (0.0, 0.0))
rtol, atol = max(actual_rtol, expected_rtol), max(actual_atol, expected_atol)
# halve the tolerance if `low_tolerance` is true
@@ -262,10 +270,6 @@ def _get_precision_by_name(
return tol_val_default
-# {dtype: (rtol, atol)}
-_DTYPE_PRECISIONS = {torch.float16: (1e-3, 1e-3), torch.float32: (1e-4, 1e-5), torch.float64: (1e-5, 1e-8)}
-
-
def _default_tolerances(*inputs: Any) -> Tuple[float, float]:
rtols, atols = zip(*[_DTYPE_PRECISIONS.get(torch.as_tensor(input).dtype, (0.0, 0.0)) for input in inputs])
return max(rtols), max(atols)
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index a9b4c902d..0bbea1a0c 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -3,6 +3,7 @@ from .draw import draw_convex_polygon, draw_line, draw_rectangle
from .grid import create_meshgrid, create_meshgrid3d
from .helpers import (
_extract_device_dtype,
+ deprecated,
get_cuda_device_if_available,
is_autocast_enabled,
map_location_to_cpu,
@@ -38,4 +39,5 @@ __all__ = [
"torch_meshgrid",
"map_location_to_cpu",
"is_autocast_enabled",
+ "deprecated",
]
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 78f1bb03d..a1c162cde 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -44,23 +44,36 @@ def map_location_to_cpu(storage: Union[str, Tensor], *args: Any, **kwargs: Any)
return storage
-def _deprecated(func: Callable[..., Any], replace_with: Optional[str] = None):
- @wraps(func)
- def wrapper(*args, **kwargs):
- name = ""
- if isclass(func):
- name = func.__class__.__name__
- if isfunction(func):
- name = func.__name__
- if replace_with is not 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
- )
- return func(*args, **kwargs)
+def deprecated(replace_with: Optional[str] = None, version: Optional[str] = None, extra_reason: Optional[str] = None):
+ def _deprecated(func: Callable[..., Any]):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ name = ""
+ beginning = f'Since kornia {version} the ' if version is not None else ''
+
+ if isclass(func):
+ name = func.__class__.__name__
+ if isfunction(func):
+ name = func.__name__
+ warnings.simplefilter('always', DeprecationWarning)
+ if replace_with is not None:
+ warnings.warn(
+ f"{beginning}`{name}` is deprecated in favor of `{replace_with}`.{extra_reason}",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+ else:
+ warnings.warn(
+ f"{beginning}`{name}` is deprecated and will be removed in the future versions.{extra_reason}",
+ category=DeprecationWarning,
+ stacklevel=2,
+ )
+ warnings.simplefilter('default', DeprecationWarning)
+ return func(*args, **kwargs)
+
+ return wrapper
- return wrapper
+ return _deprecated
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 913975248..77c18588a 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -3390,19 +3390,10 @@ class TestRandomGaussianBlur(BaseTester):
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(RandomGaussianBlur(kernel_size, sigma, "replicate", p=1.0), (input,), raise_exception=True)
- def test_jit(self, device, dtype):
- op = kornia.filters.gaussian_blur2d_t
- op_script = torch.jit.script(op)
- func_params = [(3, 3), torch.tensor([1.5, 1.5]).view(1, -1)]
- params = [(3, 3), torch.tensor([1.5, 1.5]).view(1, -1)]
-
- img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
- self.assert_close(op(img, *params), op_script(img, *func_params))
-
def test_module(self, device, dtype):
func_params = [(3, 3), torch.tensor([1.5, 1.5]).view(1, -1)]
params = [(3, 3), (1.5, 1.5)]
- op = kornia.filters.gaussian_blur2d_t
+ op = kornia.filters.gaussian_blur2d
op_module = RandomGaussianBlur(*params)
img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.py
index 65bf1a467..578ce7b25 100644
--- a/test/feature/test_affine_shape_estimator.py
+++ b/test/feature/test_affine_shape_estimator.py
@@ -1,4 +1,3 @@
-import pytest
import torch
from torch.autograd import gradcheck
@@ -40,13 +39,6 @@ class TestPatchAffineShapeEstimator:
patches = utils.tensor_to_gradcheck_var(patches) # to var
assert gradcheck(ori, (patches,), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
- def test_jit(self, device, dtype):
- B, C, H, W = 2, 1, 13, 13
- patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
- tfeat = PatchAffineShapeEstimator(W).to(patches.device, patches.dtype).eval()
- tfeat_jit = torch.jit.script(PatchAffineShapeEstimator(W).to(patches.device, patches.dtype).eval())
- assert_close(tfeat_jit(patches), tfeat(patches))
-
# TODO: add kornia.testing.BaseTester
class TestLAFAffineShapeEstimator:
@@ -111,17 +103,6 @@ class TestLAFAffineShapeEstimator:
fast_mode=True,
)
- @pytest.mark.jit
- @pytest.mark.skip("Failing because of extract patches")
- def test_jit(self, device, dtype):
- B, C, H, W = 1, 1, 13, 13
- inp = torch.zeros(B, C, H, W, device=device)
- inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device)
- tfeat = LAFAffineShapeEstimator(W).to(inp.device, inp.dtype).eval()
- tfeat_jit = torch.jit.script(LAFAffineShapeEstimator(W).to(inp.device, inp.dtype).eval())
- assert_close(tfeat_jit(laf, inp), tfeat(laf, inp))
-
# TODO: add kornia.testing.BaseTester
class TestLAFAffNetShapeEstimator:
@@ -174,13 +155,3 @@ class TestLAFAffNetShapeEstimator:
nondet_tol=1e-4,
fast_mode=True,
)
-
- @pytest.mark.jit
- @pytest.mark.skip("Laf type is not a torch.Tensor????")
- def test_jit(self, device, dtype):
- B, C, H, W = 1, 1, 32, 32
- patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
- laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device)
- laf_estimator = LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype).eval()
- laf_estimator_jit = torch.jit.script(LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype).eval())
- assert_close(laf_estimator(laf, patches), laf_estimator_jit(laf, patches))
diff --git a/test/feature/test_keynet.py b/test/feature/test_keynet.py
index 802bcb691..9d43ab389 100644
--- a/test/feature/test_keynet.py
+++ b/test/feature/test_keynet.py
@@ -1,10 +1,8 @@
-import pytest
import torch
from torch.autograd import gradcheck
import kornia.testing as utils # test utils
from kornia.feature import KeyNet
-from kornia.testing import assert_close
class TestKeyNet:
@@ -25,11 +23,3 @@ class TestKeyNet:
patches = utils.tensor_to_gradcheck_var(patches) # to var
keynet = KeyNet().to(patches.device, patches.dtype)
assert gradcheck(keynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8, raise_exception=True, fast_mode=True)
-
- @pytest.mark.jit
- def test_jit(self, device, dtype):
- B, C, H, W = 2, 1, 32, 32
- patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
- model = KeyNet(True).to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(KeyNet(True).to(patches.device, patches.dtype).eval())
- assert_close(model(patches), model_jit(patches))
diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.py
index bfe54500c..75fb7f6b2 100644
--- a/test/feature/test_mkd.py
+++ b/test/feature/test_mkd.py
@@ -79,14 +79,6 @@ class TestMKDGradients:
assert gradcheck(grad_describe, (patches), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
- @pytest.mark.jit
- def test_jit(self, device, dtype):
- B, C, H, W = 2, 1, 13, 13
- patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
- model = MKDGradients().to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(MKDGradients().to(patches.device, patches.dtype).eval())
- assert_close(model(patches), model_jit(patches))
-
class TestVonMisesKernel:
@pytest.mark.parametrize("ps", [5, 13, 25])
@@ -451,13 +443,3 @@ class TestSimpleKD:
return skd(patches.double())
assert gradcheck(skd_describe, (patches, ps), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
-
- @pytest.mark.jit
- def test_jit(self, device, dtype):
- batch_size, channels, ps = 1, 1, 19
- patches = torch.rand(batch_size, channels, ps, ps).to(device)
- model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(
- SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()
- )
- assert_close(model(patches), model_jit(patches))
diff --git a/test/feature/test_responces_local_features.py b/test/feature/test_responces_local_features.py
index 566617d8f..1f5166fbd 100644
--- a/test/feature/test_responces_local_features.py
+++ b/test/feature/test_responces_local_features.py
@@ -1,4 +1,3 @@
-import pytest
import torch
from torch.autograd import gradcheck
@@ -122,18 +121,6 @@ class TestCornerHarris:
kornia.feature.harris_response, (img, k), raise_exception=True, nondet_tol=1e-4, fast_mode=True
)
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- @torch.jit.script
- def op_script(input, k):
- return kornia.feature.harris_response(input, k)
-
- k = torch.tensor(0.04)
- img = torch.rand(2, 3, 4, 5, device=device)
- actual = op_script(img, k)
- expected = kornia.feature.harris_response(img, k)
- assert_close(actual, expected)
-
class TestCornerGFTT:
def test_shape(self, device):
@@ -245,17 +232,6 @@ class TestCornerGFTT:
img = utils.tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.feature.gftt_response, (img), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- @torch.jit.script
- def op_script(input):
- return kornia.feature.gftt_response(input)
-
- img = torch.rand(2, 3, 4, 5, device=device)
- actual = op_script(img)
- expected = kornia.feature.gftt_response(img)
- assert_close(actual, expected)
-
class TestBlobHessian:
def test_shape(self, device):
@@ -327,17 +303,6 @@ class TestBlobHessian:
img = utils.tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.feature.hessian_response, (img), raise_exception=True, nondet_tol=1e-4, fast_mode=True)
- @pytest.mark.jit
- def test_jit(self, device):
- @torch.jit.script
- def op_script(input):
- return kornia.feature.hessian_response(input)
-
- img = torch.rand(2, 3, 4, 5, device=device)
- actual = op_script(img)
- expected = kornia.feature.hessian_response(img)
- assert_close(actual, expected)
-
class TestBlobDoGSingle:
def test_shape(self, device):
@@ -412,14 +377,3 @@ class TestBlobDoGSingle:
assert gradcheck(
kornia.feature.dog_response_single, (img), raise_exception=True, nondet_tol=1e-4, fast_mode=True
)
-
- @pytest.mark.jit
- def test_jit(self, device):
- @torch.jit.script
- def op_script(input):
- return kornia.feature.dog_response_single(input)
-
- img = torch.rand(2, 3, 9, 9, device=device)
- actual = op_script(img)
- expected = kornia.feature.dog_response_single(img)
- assert_close(actual, expected)
diff --git a/test/filters/test_blur.py b/test/filters/test_blur.py
index e9c52c737..e64bd88b9 100644
--- a/test/filters/test_blur.py
+++ b/test/filters/test_blur.py
@@ -1,47 +1,43 @@
+import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import BoxBlur, box_blur
+from kornia.testing import BaseTester, tensor_to_gradcheck_var
-class TestBoxBlur:
- def test_shape(self, device, dtype):
- inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
- blur = kornia.filters.BoxBlur((3, 3))
- assert blur(inp).shape == (1, 3, 4, 4)
+class TestBoxBlur(BaseTester):
+ @pytest.mark.parametrize('kernel_size', [5, (3, 5)])
+ @pytest.mark.parametrize('normalized', [True, False])
+ def test_smoke(self, kernel_size, normalized, device, dtype):
+ inpt = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
- def test_shape_batch(self, device, dtype):
- inp = torch.zeros(2, 6, 4, 4, device=device, dtype=dtype)
- blur = kornia.filters.BoxBlur((3, 3))
- assert blur(inp).shape == (2, 6, 4, 4)
+ bb = BoxBlur(kernel_size, 'reflect', normalized)
+ actual = bb(inpt)
+ assert actual.shape == (1, 1, 10, 10)
- def test_kernel_3x3(self, device, dtype):
- inp = torch.tensor(
- [
- [
- [
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- ]
- ]
- ],
- device=device,
- dtype=dtype,
- )
+ def test_exception(self):
+ inpt = torch.rand(1, 1, 3, 3)
+ with pytest.raises(TypeError) as errinfo:
+ box_blur(inpt, '1')
+ assert 'Kernel size should be an integer or a tuple of integer.' in str(errinfo)
- kernel_size = (3, 3)
- actual = kornia.filters.box_blur(inp, kernel_size)
+ with pytest.raises(Exception) as errinfo:
+ box_blur(inpt, (1,))
+ assert '2D Kernel size tuple should have a length of 2.' in str(errinfo)
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(actual.sum(), torch.tensor(35.0).to(actual), rtol=tol_val, atol=tol_val)
+ @pytest.mark.parametrize('kernel_size', [(3, 3), 5, (5, 7)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_cardinality(self, batch_size, kernel_size, device, dtype):
+ inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
+ blur = BoxBlur(kernel_size)
+ actual = blur(inp)
+ expected = (batch_size, 3, 4, 4)
+ assert actual.shape == expected
# TODO(dmytro): normalized does not make any effect
- def test_kernel_3x3_nonormalize(self, device, dtype):
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('normalized', [True, False])
+ def test_kernel_3x3(self, batch_size, normalized, device, dtype):
inp = torch.tensor(
[
[
@@ -56,15 +52,16 @@ class TestBoxBlur:
],
device=device,
dtype=dtype,
- )
+ ).repeat(batch_size, 1, 1, 1)
kernel_size = (3, 3)
- actual = kornia.filters.box_blur(inp, kernel_size, normalized=False)
+ actual = box_blur(inp, kernel_size, normalized=normalized)
+ expected = torch.tensor(35.0 * batch_size, device=device, dtype=dtype)
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(actual.sum(), torch.tensor(35.0).to(actual), rtol=tol_val, atol=tol_val)
+ self.assert_close(actual.sum(), expected)
- def test_kernel_5x5(self, device, dtype):
+ @pytest.mark.parametrize('batch_size', [None, 1, 3])
+ def test_kernel_5x5(self, batch_size, device, dtype):
inp = torch.tensor(
[
[
@@ -81,70 +78,49 @@ class TestBoxBlur:
dtype=dtype,
)
- kernel_size = (5, 5)
- expected = inp.sum((1, 2, 3)) / torch.mul(*kernel_size)
-
- actual = kornia.filters.box_blur(inp, kernel_size)
-
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(actual[:, 0, 2, 2], expected, rtol=tol_val, atol=tol_val)
-
- def test_kernel_5x5_batch(self, device, dtype):
- batch_size = 3
- inp = torch.tensor(
- [
- [
- [
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [1.0, 1.0, 1.0, 1.0, 1.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- [2.0, 2.0, 2.0, 2.0, 2.0],
- ]
- ]
- ],
- device=device,
- dtype=dtype,
- ).repeat(batch_size, 1, 1, 1)
+ if batch_size:
+ inp = inp.repeat(batch_size, 1, 1, 1)
kernel_size = (5, 5)
- expected = inp.sum((1, 2, 3)) / torch.mul(*kernel_size)
- actual = kornia.filters.box_blur(inp, kernel_size)
+ actual = box_blur(inp, kernel_size)
+ expected = inp.sum((1, 2, 3)) / torch.mul(*kernel_size)
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(actual[:, 0, 2, 2], expected, rtol=tol_val, atol=tol_val)
+ self.assert_close(actual[:, 0, 2, 2], expected)
- def test_noncontiguous(self, device, dtype):
- batch_size = 3
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_noncontiguous(self, batch_size, device, dtype):
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
- kernel_size = (3, 3)
- actual = kornia.filters.box_blur(inp, kernel_size)
- assert_close(actual, actual)
+ actual = box_blur(inp, 3)
+
+ assert actual.is_contiguous()
- def test_gradcheck(self, device, dtype):
+ @pytest.mark.parametrize('kernel_size', [(3, 3), 5, (5, 7)])
+ def test_gradcheck(self, kernel_size, device, dtype):
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.box_blur, (img, (3, 3)), raise_exception=True)
+ img = tensor_to_gradcheck_var(img) # to var
+ fast_mode = 'cpu' in str(device) # Disable fast mode for GPU
+ self.gradcheck(box_blur, (img, kernel_size), fast_mode=fast_mode)
- def test_jit(self, device, dtype):
- op = kornia.filters.box_blur
- op_script = torch.jit.script(op)
+ @pytest.mark.parametrize('kernel_size', [(3, 3), 5, (5, 7)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_module(self, kernel_size, batch_size, device, dtype):
+ op = box_blur
+ op_module = BoxBlur
- kernel_size = (3, 3)
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- actual = op_script(img, kernel_size)
+ img = torch.rand(batch_size, 3, 4, 5, device=device, dtype=dtype)
+ actual = op_module(kernel_size)(img)
expected = op(img, kernel_size)
- assert_close(actual, expected)
- def test_module(self, device, dtype):
- op = kornia.filters.box_blur
- op_module = kornia.filters.BoxBlur
+ self.assert_close(actual, expected)
- kernel_size = (3, 3)
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- actual = op_module(kernel_size)(img)
- expected = op(img, kernel_size)
- assert_close(actual, expected)
+ @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = BoxBlur(kernel_size)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/filters/test_blur_pool.py b/test/filters/test_blur_pool.py
index cc4afaf0b..643cbc4e6 100644
--- a/test/filters/test_blur_pool.py
+++ b/test/filters/test_blur_pool.py
@@ -1,138 +1,198 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import (
+ BlurPool2D,
+ EdgeAwareBlurPool2D,
+ MaxBlurPool2D,
+ blur_pool2d,
+ edge_aware_blur_pool2d,
+ max_blur_pool2d,
+)
+from kornia.testing import BaseTester, tensor_to_gradcheck_var
-class TestMaxBlurPool:
- @pytest.mark.parametrize("ceil_mode", [True, False])
- def test_shape(self, ceil_mode, device, dtype):
- inp = torch.zeros(1, 4, 4, 8, device=device, dtype=dtype)
- blur = kornia.filters.MaxBlurPool2D(3, ceil_mode=ceil_mode)
- assert blur(inp).shape == (1, 4, 2, 4)
+class TestMaxBlurPool(BaseTester):
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('ceil_mode', [True, False])
+ def test_smoke(self, kernel_size, ceil_mode, device, dtype):
+ inpt = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
+ actual = MaxBlurPool2D(kernel_size, ceil_mode=ceil_mode)(inpt)
- @pytest.mark.parametrize("ceil_mode", [True, False])
- def test_shape_batch(self, ceil_mode, device, dtype):
- inp = torch.zeros(2, 4, 4, 8, device=device, dtype=dtype)
- blur = kornia.filters.MaxBlurPool2D(3, ceil_mode=ceil_mode)
- assert blur(inp).shape == (2, 4, 2, 4)
+ assert actual.shape == (1, 1, 5, 5)
- def test_noncontiguous(self, device, dtype):
- batch_size = 3
+ @pytest.mark.parametrize("ceil_mode", [True, False])
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_cardinality(self, batch_size, kernel_size, ceil_mode, device, dtype):
+ inpt = torch.zeros(batch_size, 4, 4, 8, device=device, dtype=dtype)
+ blur = MaxBlurPool2D(kernel_size, ceil_mode=ceil_mode)
+ assert blur(inpt).shape == (batch_size, 4, 2, 4)
+
+ def test_exception(self):
+ inpt = torch.rand(1, 1, 3, 3)
+ with pytest.raises(Exception) as errinfo:
+ MaxBlurPool2D((3, 5))(inpt)
+ assert 'Invalid kernel shape. Expect CxC_outxNxN' in str(errinfo)
+
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_noncontiguous(self, batch_size, device, dtype):
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
- kernel_size = 3
- actual = kornia.filters.max_blur_pool2d(inp, kernel_size)
- assert_close(actual, actual)
-
- def test_gradcheck(self, device, dtype):
- batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.max_blur_pool2d, (img, 3), raise_exception=True, fast_mode=True)
+ actual = max_blur_pool2d(inp, 3)
- def test_jit(self, device, dtype):
- op = kornia.filters.max_blur_pool2d
- op_script = torch.jit.script(op)
+ assert actual.is_contiguous()
- kernel_size = 3
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- actual = op_script(img, kernel_size)
- expected = op(img, kernel_size)
- assert_close(actual, expected)
+ def test_gradcheck(self, device):
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = tensor_to_gradcheck_var(img) # to var
+ self.gradcheck(max_blur_pool2d, (img, 3))
- def test_module(self, device, dtype):
- op = kornia.filters.max_blur_pool2d
- op_module = kornia.filters.MaxBlurPool2D
+ @pytest.mark.parametrize('kernel_size', [(3, 3), 5])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_module(self, kernel_size, batch_size, device, dtype):
+ op = max_blur_pool2d
+ op_module = MaxBlurPool2D
- kernel_size = 3
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ img = torch.rand(batch_size, 3, 4, 5, device=device, dtype=dtype)
actual = op_module(kernel_size)(img)
expected = op(img, kernel_size)
- assert_close(actual, expected)
-
-
-class TestBlurPool:
- def test_shape(self, device, dtype):
- inp = torch.zeros(1, 4, 4, 8, device=device, dtype=dtype)
- blur = kornia.filters.BlurPool2D(3, stride=1)
- assert blur(inp).shape == (1, 4, 4, 8)
- blur = kornia.filters.BlurPool2D(3)
- assert blur(inp).shape == (1, 4, 2, 4)
-
- def test_shape_batch(self, device, dtype):
- inp = torch.zeros(2, 4, 4, 8, device=device, dtype=dtype)
- blur = kornia.filters.BlurPool2D(3, stride=1)
- assert blur(inp).shape == (2, 4, 4, 8)
- blur = kornia.filters.BlurPool2D(3)
- assert blur(inp).shape == (2, 4, 2, 4)
-
- def test_noncontiguous(self, device, dtype):
- batch_size = 3
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('ceil_mode', [True, False])
+ def test_dynamo(self, batch_size, kernel_size, ceil_mode, device, dtype, torch_optimizer):
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = MaxBlurPool2D(kernel_size, ceil_mode=ceil_mode)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
+
+
+class TestBlurPool(BaseTester):
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('stride', [1, 2])
+ def test_smoke(self, kernel_size, stride, device, dtype):
+ inpt = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
+ actual = BlurPool2D(kernel_size, stride=stride)(inpt)
+ expected = (1, 1, int(10 / stride), int(10 / stride))
+ assert actual.shape == expected
+
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('stride', [1, 2])
+ def test_cardinality(self, batch_size, kernel_size, stride, device, dtype):
+ inpt = torch.zeros(batch_size, 4, 4, 8, device=device, dtype=dtype)
+ actual = BlurPool2D(kernel_size, stride=stride)(inpt)
+ expected = (batch_size, 4, int(4 / stride), int(8 / stride))
+ assert actual.shape == expected
+
+ def test_exception(self):
+ inpt = torch.rand(1, 1, 3, 3)
+ with pytest.raises(Exception) as errinfo:
+ BlurPool2D((3, 5))(inpt)
+ assert 'Invalid kernel shape. Expect CxC_(out, None)xNxN' in str(errinfo)
+
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_noncontiguous(self, batch_size, device, dtype):
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
- kernel_size = 3
- actual = kornia.filters.blur_pool2d(inp, kernel_size)
- assert_close(actual, actual)
+ actual = blur_pool2d(inp, 3)
+ assert actual.is_contiguous()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.blur_pool2d, (img, 3), raise_exception=True, fast_mode=True)
-
- def test_jit(self, device, dtype):
- op = kornia.filters.blur_pool2d
- op_script = torch.jit.script(op)
-
- kernel_size = 3
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- actual = op_script(img, kernel_size)
- expected = op(img, kernel_size)
- assert_close(actual, expected)
-
- def test_module(self, device, dtype):
- op = kornia.filters.blur_pool2d
- op_module = kornia.filters.BlurPool2D
-
- kernel_size = 3
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = tensor_to_gradcheck_var(img) # to var
+ self.gradcheck(blur_pool2d, (img, 3))
+
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('stride', [1, 2])
+ def test_module(self, batch_size, kernel_size, stride, device, dtype):
+ op = blur_pool2d
+ op_module = BlurPool2D
+
+ img = torch.rand(batch_size, 3, 4, 5, device=device, dtype=dtype)
actual = op_module(kernel_size)(img)
expected = op(img, kernel_size)
- assert_close(actual, expected)
-
-
-class TestEdgeAwareBlurPool:
- def test_shape(self, device, dtype):
- inp = torch.zeros(1, 3, 8, 8, device=device, dtype=dtype)
- blur = kornia.filters.edge_aware_blur_pool2d(inp, kernel_size=3)
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('stride', [1, 2])
+ def test_dynamo(self, batch_size, kernel_size, stride, device, dtype, torch_optimizer):
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = BlurPool2D(kernel_size, stride=stride)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
+
+
+class TestEdgeAwareBlurPool(BaseTester):
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('edge_threshold', [1.25, 2.5])
+ @pytest.mark.parametrize('edge_dilation_kernel_size', [3, 5])
+ def test_smoke(self, kernel_size, batch_size, edge_threshold, edge_dilation_kernel_size, device, dtype):
+ inpt = torch.zeros(batch_size, 3, 8, 8, device=device, dtype=dtype)
+ actual = edge_aware_blur_pool2d(inpt, kernel_size, edge_threshold, edge_dilation_kernel_size)
+ assert actual.shape == inpt.shape
+
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_cardinality(self, kernel_size, batch_size, device, dtype):
+ inp = torch.zeros(batch_size, 3, 8, 8, device=device, dtype=dtype)
+ blur = edge_aware_blur_pool2d(inp, kernel_size=kernel_size)
assert blur.shape == inp.shape
- def test_shape_batch(self, device, dtype):
- inp = torch.zeros(2, 3, 8, 8, device=device, dtype=dtype)
- blur = kornia.filters.edge_aware_blur_pool2d(inp, kernel_size=3)
- assert blur.shape == inp.shape
+ def test_exception(self):
+ with pytest.raises(Exception) as errinfo:
+ inpt = torch.rand(1, 3, 3)
+ edge_aware_blur_pool2d(inpt, 3)
+ assert "shape must be [[\'B\', \'C\', \'H\', \'W\']]" in str(errinfo)
+ with pytest.raises(Exception) as errinfo:
+ inpt = torch.rand(1, 1, 3, 3)
+ edge_aware_blur_pool2d(inpt, 3, edge_threshold=-1)
+ assert "edge threshold should be positive, but got" in str(errinfo)
+
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_noncontiguous(self, batch_size, device, dtype):
+ inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
- def test_gradcheck(self, device, dtype):
- img = torch.rand((1, 2, 5, 4), device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.edge_aware_blur_pool2d, (img, 3), raise_exception=True, fast_mode=True)
+ actual = edge_aware_blur_pool2d(inp, 3)
+ assert actual.is_contiguous()
- def test_jit(self, device, dtype):
- op = kornia.filters.edge_aware_blur_pool2d
- op_script = torch.jit.script(op)
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_module(self, kernel_size, batch_size, device, dtype):
+ op = edge_aware_blur_pool2d
+ op_module = EdgeAwareBlurPool2D
- kernel_size = 3
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- actual = op_script(img, kernel_size)
+ img = torch.rand(batch_size, 3, 4, 5, device=device, dtype=dtype)
+ actual = op_module(kernel_size)(img)
expected = op(img, kernel_size)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
+
+ def test_gradcheck(self, device):
+ img = torch.rand((1, 2, 5, 4), device=device)
+ img = tensor_to_gradcheck_var(img) # to var
+ self.gradcheck(edge_aware_blur_pool2d, (img, 3))
def test_smooth(self, device, dtype):
- img = torch.ones(1, 1, 5, 5).to(device, dtype)
+ img = torch.ones(1, 1, 5, 5, device=device, dtype=dtype)
img[0, 0, :, :2] = 0
- blur = kornia.filters.edge_aware_blur_pool2d(img, kernel_size=3, edge_threshold=32.0)
- assert_close(img, blur)
+ blur = edge_aware_blur_pool2d(img, kernel_size=3, edge_threshold=32.0)
+ self.assert_close(img, blur)
+
+ @pytest.mark.parametrize('kernel_size', [3, (5, 5)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
+ op = edge_aware_blur_pool2d
+ inpt = torch.rand(batch_size, 3, 4, 5, device=device, dtype=dtype)
+ op = EdgeAwareBlurPool2D(kernel_size)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/filters/test_canny.py b/test/filters/test_canny.py
index 6f9ef7b27..e0181787a 100644
--- a/test/filters/test_canny.py
+++ b/test/filters/test_canny.py
@@ -1,46 +1,66 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import Canny, canny
+from kornia.testing import BaseTester, tensor_to_gradcheck_var
-class TestCanny:
- def test_shape(self, device, dtype):
- inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
-
- canny = kornia.filters.Canny()
- magnitude, edges = canny(inp)
+class TestCanny(BaseTester):
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('kernel_size', [3, (5, 7)])
+ @pytest.mark.parametrize('sigma', [(1.5, 1.0), (2.5, 0.5)])
+ @pytest.mark.parametrize('hysteresis', [False, True])
+ @pytest.mark.parametrize('low_threshold,high_threshold', [(0.1, 0.2), (0.3, 0.5)])
+ def test_smoke(self, batch_size, kernel_size, sigma, hysteresis, low_threshold, high_threshold, device, dtype):
+ inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
- assert magnitude.shape == (1, 1, 4, 4)
- assert edges.shape == (1, 1, 4, 4)
+ op = Canny(low_threshold, high_threshold, kernel_size, sigma, hysteresis)
+ actual = op(inp)
+ assert len(actual) == 2
+ assert actual[0].shape == (batch_size, 1, 4, 4)
+ assert actual[1].shape == (batch_size, 1, 4, 4)
- def test_shape_batch(self, device, dtype):
- batch_size = 2
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_cardinality(self, batch_size, device, dtype):
inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
- canny = kornia.filters.Canny()
- magnitude, edges = canny(inp)
+ op = Canny()
+ magnitude, edges = op(inp)
assert magnitude.shape == (batch_size, 1, 4, 4)
assert edges.shape == (batch_size, 1, 4, 4)
- def test_noncontiguous(self, device, dtype):
- batch_size = 3
- inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
+ def test_exception(self, device, dtype):
+ with pytest.raises(Exception) as errinfo:
+ Canny(0.3, 0.2)
+ assert 'low_threshold should be smaller than the high_threshold' in str(errinfo)
+
+ with pytest.raises(Exception) as errinfo:
+ Canny(-2, 0.3)
+ assert 'Invalid low threshold.' in str(errinfo)
- magnitude, edges = kornia.filters.canny(inp)
+ with pytest.raises(Exception) as errinfo:
+ Canny(0.1, 3)
+ assert 'Invalid high threshold.' in str(errinfo)
- assert inp.is_contiguous() is False
+ with pytest.raises(Exception) as errinfo:
+ canny(1)
+ assert 'Not a Tensor type' in str(errinfo)
+
+ inp = torch.zeros(3, 4, 4, device=device, dtype=dtype)
+ with pytest.raises(Exception) as errinfo:
+ canny(inp)
+ assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
+
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_noncontiguous(self, batch_size, device, dtype):
+ inp = torch.rand(batch_size, 3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
+
+ magnitude, edges = canny(inp)
assert magnitude.is_contiguous()
assert edges.is_contiguous()
- assert magnitude.shape == (batch_size, 1, 5, 5)
- assert edges.shape == (batch_size, 1, 5, 5)
-
def test_magnitude(self, device, dtype):
inp = torch.tensor(
[
@@ -90,11 +110,10 @@ class TestCanny:
dtype=dtype,
)
- magnitude, edges = kornia.filters.canny(inp)
+ magnitude, edges = canny(inp)
- tol_val: float = utils._get_precision(device, dtype)
- assert_close(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)
- assert_close(edges, expected_edges, rtol=tol_val, atol=tol_val)
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
def test_magnitude_hyst(self, device, dtype):
inp = torch.tensor(
@@ -145,11 +164,10 @@ class TestCanny:
dtype=dtype,
)
- magnitude, edges = kornia.filters.canny(inp, hysteresis=True)
+ magnitude, edges = canny(inp, hysteresis=True)
- tol_val: float = utils._get_precision(device, dtype)
- assert_close(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)
- assert_close(edges, expected_edges, rtol=tol_val, atol=tol_val)
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
def test_magnitude_hyst_false(self, device, dtype):
inp = torch.tensor(
@@ -200,11 +218,10 @@ class TestCanny:
dtype=dtype,
)
- magnitude, edges = kornia.filters.canny(inp, hysteresis=False)
+ magnitude, edges = canny(inp, hysteresis=False)
- tol_val: float = utils._get_precision(device, dtype)
- assert_close(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)
- assert_close(edges, expected_edges, rtol=tol_val, atol=tol_val)
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
def test_magnitude_threshold(self, device, dtype):
inp = torch.tensor(
@@ -255,34 +272,37 @@ class TestCanny:
dtype=dtype,
)
- magnitude, edges = kornia.filters.canny(inp, low_threshold=0.3, high_threshold=0.9)
+ magnitude, edges = canny(inp, low_threshold=0.3, high_threshold=0.9)
- tol_val: float = utils._get_precision(device, dtype)
- assert_close(magnitude, expected_magnitude, rtol=tol_val, atol=tol_val)
- assert_close(edges, expected_edges, rtol=tol_val, atol=tol_val)
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
if "cuda" in str(device):
pytest.skip("RuntimeError: Backward is not reentrant, i.e., running backward,")
batch_size, channels, height, width = 1, 1, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.canny, img, raise_exception=True, fast_mode=True)
-
- def test_jit(self, device, dtype):
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.sobel
- op_script = torch.jit.script(op)
- expected_magnitude, expected_edges = op(img)
- actual_magnitude, actual_edges = op_script(img)
- assert_close(actual_magnitude, expected_magnitude)
- assert_close(actual_edges, expected_edges)
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = tensor_to_gradcheck_var(img)
+ self.gradcheck(canny, img)
def test_module(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.canny
- op_module = kornia.filters.Canny()
+ op = canny
+ op_module = Canny()
expected_magnitude, expected_edges = op(img)
actual_magnitude, actual_edges = op_module(img)
- assert_close(actual_magnitude, expected_magnitude)
- assert_close(actual_edges, expected_edges)
+ self.assert_close(actual_magnitude, expected_magnitude)
+ self.assert_close(actual_edges, expected_edges)
+
+ @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = Canny(kernel_size=kernel_size)
+ op_optimized = torch_optimizer(op)
+
+ expected_magnitude, expected_edges = op(inpt)
+ actual_magnitude, actual_edges = op_optimized(inpt)
+
+ self.assert_close(actual_magnitude, expected_magnitude)
+ self.assert_close(actual_edges, expected_edges)
diff --git a/test/filters/test_filters.py b/test/filters/test_filters.py
index a0bea0396..2c1f843ad 100644
--- a/test/filters/test_filters.py
+++ b/test/filters/test_filters.py
@@ -1,41 +1,66 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import DexiNed, filter2d, filter2d_separable, filter3d
+from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
+from kornia.utils._compat import torch_version_le
-class TestFilter2D:
+class TestFilter2D(BaseTester):
+ @pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])
+ @pytest.mark.parametrize("normalized", [True, False])
@pytest.mark.parametrize("padding", ["same", "valid"])
- def test_smoke(self, padding, device, dtype):
+ def test_smoke(self, border_type, normalized, padding, device, dtype):
kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
_, height, width = kernel.shape
input = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)
b, c, h, w = input.shape
- if padding == 'same':
- out = kornia.filters.filter2d(input, kernel, padding=padding)
- assert out.shape == (b, c, h, w)
- else:
- out = kornia.filters.filter2d(input, kernel, padding=padding)
- assert out.shape == (b, c, h - height + 1, w - width + 1)
+
+ actual = filter2d(input, kernel, border_type, normalized, padding)
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape in {(b, c, h, w), (b, c, h - height + 1, w - width + 1)}
@pytest.mark.parametrize("batch_size", [2, 3, 6, 8])
@pytest.mark.parametrize("padding", ["same", "valid"])
- def test_batch(self, batch_size, padding, device, dtype):
+ def test_cardinality(self, batch_size, padding, device, dtype):
B: int = batch_size
kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
_, height, width = kernel.shape
input = torch.ones(B, 3, 7, 8, device=device, dtype=dtype)
b, c, h, w = input.shape
+ out = filter2d(input, kernel, padding=padding)
if padding == 'same':
- out = kornia.filters.filter2d(input, kernel, padding=padding)
assert out.shape == (b, c, h, w)
else:
- out = kornia.filters.filter2d(input, kernel, padding=padding)
assert out.shape == (b, c, h - height + 1, w - width + 1)
+ def test_exception(self):
+ k = torch.ones(1, 1, 1)
+ inpt = torch.ones(1, 1, 1, 1)
+ with pytest.raises(TypeError) as errinfo:
+ filter2d(1, k)
+ assert 'Not a Tensor type.' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ filter2d(inpt, 1)
+ assert 'Not a Tensor type.' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ filter2d(torch.ones(1), k)
+ assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ filter2d(inpt, torch.ones(1))
+ assert 'shape must be [[\'B\', \'H\', \'W\']]' in str(errinfo)
+
+ with pytest.raises(Exception) as errinfo:
+ filter2d(inpt, k, border_type='a')
+ assert 'Invalid border, gotcha a. Ex' in str(errinfo)
+
+ with pytest.raises(Exception) as errinfo:
+ filter2d(inpt, k, padding='a')
+ assert 'Invalid padding mode, gotcha a. Ex' in str(errinfo)
+
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_mean_filter(self, padding, device, dtype):
kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)
@@ -54,31 +79,33 @@ class TestFilter2D:
device=device,
dtype=dtype,
)
- expected_same = torch.tensor(
- [
+
+ actual = filter2d(input, kernel, padding=padding)
+
+ if padding == 'same':
+ expected_same = torch.tensor(
[
[
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 5.0, 5.0, 5.0, 0.0],
- [0.0, 5.0, 5.0, 5.0, 0.0],
- [0.0, 5.0, 5.0, 5.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
]
- ]
- ],
- device=device,
- dtype=dtype,
- )
-
- expected_valid = torch.tensor(
- [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype
- )
+ ],
+ device=device,
+ dtype=dtype,
+ )
- actual = kornia.filters.filter2d(input, kernel, padding=padding)
- if padding == 'same':
- assert_close(actual, expected_same)
+ self.assert_close(actual, expected_same)
else:
- assert_close(actual, expected_valid)
+ expected_valid = torch.tensor(
+ [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype
+ )
+
+ self.assert_close(actual, expected_valid)
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_mean_filter_2batch_2ch(self, padding, device, dtype):
@@ -99,35 +126,35 @@ class TestFilter2D:
dtype=dtype,
).expand(2, 2, -1, -1)
- expected_same = torch.tensor(
- [
+ actual = filter2d(input, kernel, padding=padding)
+
+ if padding == 'same':
+ expected_same = torch.tensor(
[
[
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 5.0, 5.0, 5.0, 0.0],
- [0.0, 5.0, 5.0, 5.0, 0.0],
- [0.0, 5.0, 5.0, 5.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 5.0, 5.0, 5.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
]
- ]
- ],
- device=device,
- dtype=dtype,
- ).expand(2, 2, -1, -1)
-
- expected_valid = torch.tensor(
- [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype
- ).expand(2, 2, -1, -1)
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, -1, -1)
- actual = kornia.filters.filter2d(input, kernel, padding=padding)
- if padding == 'same':
- assert_close(actual, expected_same)
+ self.assert_close(actual, expected_same)
else:
- assert_close(actual, expected_valid)
+ expected_valid = torch.tensor(
+ [[[[5.0, 5.0, 5.0], [5.0, 5.0, 5.0], [5.0, 5.0, 5.0]]]], device=device, dtype=dtype
+ ).expand(2, 2, -1, -1)
+ self.assert_close(actual, expected_valid)
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_normalized_mean_filter(self, padding, device, dtype):
- kernel = torch.ones(1, 3, 3).to(device)
+ kernel = torch.ones(1, 3, 3, device=device, dtype=dtype)
input = torch.tensor(
[
[
@@ -145,33 +172,32 @@ class TestFilter2D:
).expand(2, 2, -1, -1)
nv: float = 5.0 / 9 # normalization value
- expected_same = torch.tensor(
- [
+ actual = filter2d(input, kernel, normalized=True, padding=padding)
+
+ if padding == 'same':
+ expected_same = torch.tensor(
[
[
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, nv, nv, nv, 0.0],
- [0.0, nv, nv, nv, 0.0],
- [0.0, nv, nv, nv, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, nv, nv, nv, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
]
- ]
- ],
- device=device,
- dtype=dtype,
- ).expand(2, 2, -1, -1)
-
- expected_valid = torch.tensor(
- [[[[nv, nv, nv], [nv, nv, nv], [nv, nv, nv]]]], device=device, dtype=dtype
- ).expand(2, 2, -1, -1)
-
- actual = kornia.filters.filter2d(input, kernel, normalized=True, padding=padding)
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, -1, -1)
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- if padding == 'same':
- assert_close(actual, expected_same, rtol=tol_val, atol=tol_val)
+ self.assert_close(actual, expected_same)
else:
- assert_close(actual, expected_valid, rtol=tol_val, atol=tol_val)
+ expected_valid = torch.tensor(
+ [[[[nv, nv, nv], [nv, nv, nv], [nv, nv, nv]]]], device=device, dtype=dtype
+ ).expand(2, 2, -1, -1)
+
+ self.assert_close(actual, expected_valid)
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_even_sized_filter(self, padding, device, dtype):
@@ -192,33 +218,34 @@ class TestFilter2D:
dtype=dtype,
)
- expected_same = torch.tensor(
- [
+ actual = filter2d(input, kernel, padding=padding)
+
+ if padding == 'same':
+ expected_same = torch.tensor(
[
[
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 5.0, 5.0, 0.0, 0.0],
- [0.0, 5.0, 5.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0, 0.0, 0.0, 0.0],
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 0.0, 0.0],
+ [0.0, 5.0, 5.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ ]
]
- ]
- ],
- device=device,
- dtype=dtype,
- )
-
- expected_valid = torch.tensor(
- [[[[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]],
- device=device,
- dtype=dtype,
- )
+ ],
+ device=device,
+ dtype=dtype,
+ )
- actual = kornia.filters.filter2d(input, kernel, padding=padding)
- if padding == 'same':
- assert_close(actual, expected_same)
+ self.assert_close(actual, expected_same)
else:
- assert_close(actual, expected_valid)
+ expected_valid = torch.tensor(
+ [[[[0.0, 0.0, 0.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 5.0, 5.0, 0.0], [0.0, 0.0, 0.0, 0.0]]]],
+ device=device,
+ dtype=dtype,
+ )
+
+ self.assert_close(actual, expected_valid)
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_mix_sized_filter_padding_same(self, padding, device, dtype):
@@ -255,8 +282,8 @@ class TestFilter2D:
dtype=dtype,
)
- actual = kornia.filters.filter2d(input_, kernel, padding='same', border_type='constant')
- assert_close(actual, expected_same)
+ actual = filter2d(input_, kernel, padding='same', border_type='constant')
+ self.assert_close(actual, expected_same)
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_noncontiguous(self, padding, device, dtype):
@@ -264,8 +291,8 @@ class TestFilter2D:
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
kernel = torch.ones(1, 2, 2, device=device, dtype=dtype)
- actual = kornia.filters.filter2d(inp, kernel, padding=padding)
- assert_close(actual, actual)
+ actual = filter2d(inp, kernel, padding=padding)
+ assert actual.is_contiguous()
@pytest.mark.parametrize("padding", ["same", "valid"])
def test_separable(self, padding, device, dtype):
@@ -274,45 +301,79 @@ class TestFilter2D:
kernel_x = torch.ones(1, 3, device=device, dtype=dtype)
kernel_y = torch.ones(1, 3, device=device, dtype=dtype)
kernel = kernel_y.t() @ kernel_x
- out = kornia.filters.filter2d(inp, kernel[None], padding=padding)
- out_sep = kornia.filters.filter2d_separable(inp, kernel_x, kernel_y, padding=padding)
- assert_close(out, out_sep)
+ out = filter2d(inp, kernel[None], padding=padding)
+ out_sep = filter2d_separable(inp, kernel_x, kernel_y, padding=padding)
+ self.assert_close(out, out_sep)
def test_gradcheck(self, device):
kernel = torch.rand(1, 3, 3, device=device)
input = torch.ones(1, 1, 7, 8, device=device)
# evaluate function gradient
- input = utils.tensor_to_gradcheck_var(input) # to var
- kernel = utils.tensor_to_gradcheck_var(kernel) # to var
- assert gradcheck(
- kornia.filters.filter2d, (input, kernel), nondet_tol=1e-8, raise_exception=True, fast_mode=True
- )
+ input = tensor_to_gradcheck_var(input) # to var
+ kernel = tensor_to_gradcheck_var(kernel) # to var
+ self.gradcheck(filter2d, (input, kernel), nondet_tol=1e-8)
- @pytest.mark.parametrize("padding", ["same", "valid"])
- def test_jit(self, padding, device, dtype):
- op = kornia.filters.filter2d
- op_script = torch.jit.script(op)
+ @pytest.mark.skip(reason='filter2d do not have a module')
+ def test_module(self):
+ ...
+ @pytest.mark.parametrize("normalized", [True, False])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_dynamo(self, normalized, padding, device, dtype, torch_optimizer):
kernel = torch.rand(1, 3, 3, device=device, dtype=dtype)
- input = torch.ones(1, 1, 7, 8, device=device, dtype=dtype)
- expected = op(input, kernel, padding=padding)
- actual = op_script(input, kernel, padding=padding)
- assert_close(actual, expected)
+ inpt = torch.ones(2, 3, 10, 10, device=device, dtype=dtype)
+ op = filter2d
+ op_optimized = torch_optimizer(op)
+ expected = op(inpt, kernel, padding=padding, normalized=normalized)
+ actual = op_optimized(inpt, kernel, padding=padding, normalized=normalized)
-class TestFilter3D:
- def test_smoke(self, device, dtype):
- kernel = torch.rand(1, 3, 3, 3).to(device)
- input = torch.ones(1, 1, 6, 7, 8).to(device)
- assert kornia.filters.filter3d(input, kernel).shape == input.shape
+ self.assert_close(actual, expected)
+
+
+class TestFilter3D(BaseTester):
+ @pytest.mark.parametrize("border_type", ['constant', 'reflect', 'replicate', 'circular'])
+ @pytest.mark.parametrize("normalized", [True, False])
+ def test_smoke(self, border_type, normalized, device, dtype):
+ if torch_version_le(1, 9, 1) and border_type == 'reflect':
+ pytest.skip(reason='Reflect border is not implemented for 3D on torch < 1.9.1')
+
+ kernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
+ inpt = torch.ones(1, 1, 6, 7, 8, device=device, dtype=dtype)
+ actual = filter3d(inpt, kernel, border_type, normalized)
+
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape == inpt.shape
@pytest.mark.parametrize("batch_size", [2, 3, 6, 8])
- def test_batch(self, batch_size, device, dtype):
- B: int = batch_size
+ def test_cardinality(self, batch_size, device, dtype):
kernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
- input = torch.ones(B, 3, 6, 7, 8, device=device, dtype=dtype)
- assert kornia.filters.filter3d(input, kernel).shape == input.shape
+ inpt = torch.ones(batch_size, 3, 6, 7, 8, device=device, dtype=dtype)
+ assert filter3d(inpt, kernel).shape == inpt.shape
+
+ def test_exception(self):
+ k = torch.ones(1, 1, 1, 1)
+ inpt = torch.ones(1, 1, 1, 1, 1)
+ with pytest.raises(TypeError) as errinfo:
+ filter3d(1, k)
+ assert 'Not a Tensor type.' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ filter3d(inpt, 1)
+ assert 'Not a Tensor type.' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ filter3d(torch.ones(1), k)
+ assert 'shape must be [[\'B\', \'C\', \'D\', \'H\', \'W\']]' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ filter3d(inpt, torch.ones(1))
+ assert 'shape must be [[\'B\', \'D\', \'H\', \'W\']]' in str(errinfo)
+
+ with pytest.raises(Exception) as errinfo:
+ filter3d(inpt, k, border_type='a')
+ assert 'Invalid border, gotcha a. Ex' in str(errinfo)
def test_mean_filter(self, device, dtype):
kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)
@@ -380,8 +441,8 @@ class TestFilter3D:
dtype=dtype,
)
- actual = kornia.filters.filter3d(input, kernel)
- assert_close(actual, expected)
+ actual = filter3d(input, kernel)
+ self.assert_close(actual, expected)
def test_mean_filter_2batch_2ch(self, device, dtype):
kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)
@@ -451,8 +512,8 @@ class TestFilter3D:
)
expected = expected.expand(2, 2, -1, -1, -1)
- actual = kornia.filters.filter3d(input, kernel)
- assert_close(actual, expected)
+ actual = filter3d(input, kernel)
+ self.assert_close(actual, expected)
def test_normalized_mean_filter(self, device, dtype):
kernel = torch.ones(1, 3, 3, 3, device=device, dtype=dtype)
@@ -523,10 +584,9 @@ class TestFilter3D:
)
expected = expected.expand(2, 2, -1, -1, -1)
- actual = kornia.filters.filter3d(input, kernel, normalized=True)
+ actual = filter3d(input, kernel, normalized=True)
- tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
- assert_close(actual, expected, rtol=tol_val, atol=tol_val)
+ self.assert_close(actual, expected)
def test_even_sized_filter(self, device, dtype):
kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)
@@ -594,51 +654,54 @@ class TestFilter3D:
dtype=dtype,
)
- actual = kornia.filters.filter3d(input, kernel)
- assert_close(actual, expected)
+ actual = filter3d(input, kernel)
+ self.assert_close(actual, expected)
def test_noncontiguous(self, device, dtype):
batch_size = 3
inp = torch.rand(3, 5, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1, -1)
kernel = torch.ones(1, 2, 2, 2, device=device, dtype=dtype)
- actual = kornia.filters.filter3d(inp, kernel)
- expected = actual
- assert_close(actual, expected)
+ actual = filter3d(inp, kernel)
+ assert actual.is_contiguous()
def test_gradcheck(self, device):
kernel = torch.rand(1, 3, 3, 3, device=device)
input = torch.ones(1, 1, 6, 7, 8, device=device)
# evaluate function gradient
- input = utils.tensor_to_gradcheck_var(input) # to var
- kernel = utils.tensor_to_gradcheck_var(kernel) # to var
- assert gradcheck(
- kornia.filters.filter3d, (input, kernel), nondet_tol=1e-8, raise_exception=True, fast_mode=True
- )
+ input = tensor_to_gradcheck_var(input) # to var
+ kernel = tensor_to_gradcheck_var(kernel) # to var
+ self.gradcheck(filter3d, (input, kernel), nondet_tol=1e-8)
- def test_jit(self, device, dtype):
- op = kornia.filters.filter3d
- op_script = torch.jit.script(op)
+ @pytest.mark.skip(reason='filter3d do not have a module')
+ def test_module(self):
+ ...
- kernel = torch.rand(1, 1, 3, 3, device=device, dtype=dtype)
- input = torch.ones(1, 1, 2, 7, 8, device=device, dtype=dtype)
- expected = op(input, kernel)
- actual = op_script(input, kernel)
- assert_close(actual, expected)
+ @pytest.mark.parametrize("normalized", [True, False])
+ def test_dynamo(self, normalized, device, dtype, torch_optimizer):
+ kernel = torch.rand(1, 3, 3, 3, device=device, dtype=dtype)
+ inpt = torch.ones(2, 3, 4, 10, 10, device=device, dtype=dtype)
+ op = filter3d
+ op_optimized = torch_optimizer(op)
+
+ expected = op(inpt, kernel, normalized=normalized)
+ actual = op_optimized(inpt, kernel, normalized=normalized)
+
+ self.assert_close(actual, expected)
class TestDexiNed:
def test_smoke(self, device, dtype):
- img = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)
- net = kornia.filters.DexiNed(pretrained=False).to(device, dtype)
+ img = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)
+ net = DexiNed(pretrained=False).to(device, dtype)
out = net(img)
assert len(out) == 7
- assert out[-1].shape == (2, 1, 64, 64)
+ assert out[-1].shape == (2, 1, 32, 32)
@pytest.mark.parametrize("data", ["dexined"], indirect=True)
def test_inference(self, device, dtype, data):
- model = kornia.filters.DexiNed(pretrained=False)
+ model = DexiNed(pretrained=False)
model.load_state_dict(data, strict=True)
model = model.to(device, dtype)
model.eval()
@@ -655,9 +718,14 @@ class TestDexiNed:
out = model(img)[-1]
assert_close(out, expect, atol=3e-4, rtol=3e-4)
- def test_jit(self, device, dtype):
- op = kornia.filters.DexiNed(pretrained=False).to(device, dtype)
- op_script = torch.jit.script(op)
+ @pytest.mark.skip(reason='DexiNed do not compile with dynamo.')
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ # TODO: update the dexined to be possible to use with dynamo
+ inpt = torch.rand(2, 3, 32, 32, device=device, dtype=dtype)
+ op = DexiNed(pretrained=True).to(device, dtype)
+ op_optimized = torch_optimizer(op)
- img = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)
- assert_close(op(img)[-1], op_script(img)[-1])
+ expected = op(inpt)
+ actual = op_optimized(inpt)
+
+ assert_close(actual, expected)
diff --git a/test/filters/test_gaussian.py b/test/filters/test_gaussian.py
index 17bae18c4..8b2d03e12 100644
--- a/test/filters/test_gaussian.py
+++ b/test/filters/test_gaussian.py
@@ -1,92 +1,205 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import (
+ GaussianBlur2d,
+ gaussian_blur2d,
+ get_gaussian_discrete_kernel1d,
+ get_gaussian_erf_kernel1d,
+ get_gaussian_kernel1d,
+ get_gaussian_kernel2d,
+ get_gaussian_kernel3d,
+)
+from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
@pytest.mark.parametrize("window_size", [5, 11])
@pytest.mark.parametrize("sigma", [1.5, 5.0])
-def test_get_gaussian_kernel(window_size, sigma):
- kernel = kornia.filters.get_gaussian_kernel1d(window_size, sigma)
- assert kernel.shape == (1, window_size)
- assert kernel.sum().item() == pytest.approx(1.0)
+def test_get_gaussian_kernel1d_float(window_size, sigma, device, dtype):
+ actual = get_gaussian_kernel1d(window_size, sigma, device=device, dtype=dtype)
+ expected = torch.ones(1, device=device, dtype=dtype)
+
+ assert actual.shape == (1, window_size)
+ assert_close(actual.sum(), expected.sum())
@pytest.mark.parametrize("window_size", [5, 11])
[email protected]("sigma", [1.5, 5.0])
-def test_get_gaussian_discrete_kernel(window_size, sigma):
- kernel = kornia.filters.get_gaussian_discrete_kernel1d(window_size, sigma)
- assert kernel.shape == (window_size,)
- assert kernel.sum().item() == pytest.approx(1.0)
[email protected]("sigma", [[[1.5]], [[1.5], [5.0]], [[1.5], [5.0]]])
+def test_get_gaussian_kernel1d_tensor(window_size, sigma, device, dtype):
+ sigma = torch.tensor(sigma, device=device, dtype=dtype)
+ bs = sigma.shape[0]
+ actual = get_gaussian_kernel1d(window_size, sigma)
+ expected = torch.ones(bs, device=device, dtype=dtype)
[email protected]("window_size", [5, 11])
[email protected]("sigma", [1.5, 5.0])
-def test_get_gaussian_erf_kernel(window_size, sigma):
- kernel = kornia.filters.get_gaussian_erf_kernel1d(window_size, sigma)
- assert kernel.shape == (window_size,)
- assert kernel.sum().item() == pytest.approx(1.0)
+ assert actual.shape == (bs, window_size)
+ assert_close(actual.sum(), expected.sum())
@pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
[email protected]("sigma", [1.5, 2.1])
-def test_get_gaussian_kernel2d(ksize_x, ksize_y, sigma):
- kernel = kornia.filters.get_gaussian_kernel2d((ksize_x, ksize_y), (sigma, sigma))
- assert kernel.shape == (1, ksize_x, ksize_y)
- assert kernel.sum().item() == pytest.approx(1.0)
[email protected]("sigma", [(1.5, 1.5), (2.1, 2.1)])
+def test_get_gaussian_kernel2d_float(ksize_x, ksize_y, sigma, device, dtype):
+ actual = get_gaussian_kernel2d((ksize_x, ksize_y), sigma, device=device, dtype=dtype)
+ expected = torch.ones(1, device=device, dtype=dtype)
+
+ assert actual.shape == (1, ksize_x, ksize_y)
+ assert_close(actual.sum(), expected.sum())
@pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
[email protected]("sigma", [1.5, 2.1])
-def test_separable(ksize_x, ksize_y, sigma, device, dtype):
- input = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
- out = kornia.filters.gaussian_blur2d(input, (ksize_x, ksize_y), (sigma, sigma), "replicate", separable=False)
- out_sep = kornia.filters.gaussian_blur2d(input, (ksize_x, ksize_y), (sigma, sigma), "replicate", separable=True)
[email protected]("sigma", ([[1.5, 2.1], [1.5, 2.1], [5.0, 2.7]], [[1.5, 2.1], [3.5, 2.1]]))
+def test_get_gaussian_kernel2d_tensor(ksize_x, ksize_y, sigma, device, dtype):
+ sigma = torch.tensor(sigma, device=device, dtype=dtype)
+ bs = sigma.shape[0]
- assert_close(out, out_sep)
+ actual = get_gaussian_kernel2d((ksize_x, ksize_y), sigma)
+ expected = torch.ones(bs, device=device, dtype=dtype)
+ assert actual.shape == (bs, ksize_x, ksize_y)
+ assert_close(actual.sum(), expected.sum())
[email protected]("window_size", [5, 11])
[email protected]("sigma", [torch.tensor([1.5, 5.0]), torch.tensor([1.5, 5.0])])
-def test_get_gaussian_kernel_t(window_size, sigma):
- kernel = kornia.filters.get_gaussian_kernel1d_t(window_size, sigma)
- assert kernel.shape == (2, window_size)
- assert_close(kernel.sum(1), torch.ones(2))
+
[email protected]("ksize_x", [5, 11])
[email protected]("ksize_y", [3, 7])
[email protected]("ksize_z", [9, 3])
[email protected]("sigma", [(1.5, 1.5, 3.5), (2.1, 1.5, 2.1)])
+def test_get_gaussian_kernel3d_float(ksize_x, ksize_y, ksize_z, sigma, device, dtype):
+ actual = get_gaussian_kernel3d((ksize_x, ksize_y, ksize_z), sigma, device=device, dtype=dtype)
+ expected = torch.ones(1, device=device, dtype=dtype)
+
+ assert actual.shape == (1, ksize_x, ksize_y, ksize_z)
+ assert_close(actual.sum(), expected.sum())
@pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
[email protected]("sigma", [torch.tensor([[1.5, 2.1], [1.5, 2.1]]), torch.tensor([[1.5, 2.1], [3.5, 2.1]])])
-def test_get_gaussian_kernel2d_t(ksize_x, ksize_y, sigma):
- kernel = kornia.filters.get_gaussian_kernel2d_t((ksize_x, ksize_y), sigma)
- assert kernel.shape == (2, ksize_x, ksize_y)
- assert_close(kernel.sum([1, 2]), torch.ones(2))
[email protected]("ksize_z", [9, 3])
+ "sigma", ([[1.5, 2.1, 3.5], [1.5, 2.1, 1.5], [5.0, 2.7, 2.1]], [[1.5, 3.5, 2.1], [1.2, 3.5, 2.1]])
+)
+def test_get_gaussian_kernel3d_tensor(ksize_x, ksize_y, ksize_z, sigma, device, dtype):
+ sigma = torch.tensor(sigma, device=device, dtype=dtype)
+ bs = sigma.shape[0]
+
+ actual = get_gaussian_kernel3d((ksize_x, ksize_y, ksize_z), sigma)
+ expected = torch.ones(bs, device=device, dtype=dtype)
+
+ assert actual.shape == (bs, ksize_x, ksize_y, ksize_z)
+ assert_close(actual.sum(), expected.sum())
+
+
[email protected]("window_size", [5, 11])
[email protected]("sigma", [1.5, 5.0])
+def test_get_discrete_gaussian_erf_kernel1d_float(window_size, sigma, device, dtype):
+ actual = get_gaussian_erf_kernel1d(window_size, sigma, device=device, dtype=dtype)
+ expected = torch.ones(1, device=device, dtype=dtype)
+
+ assert actual.shape == (1, window_size)
+ assert_close(actual.sum(), expected.sum())
+
+
[email protected]("window_size", [5, 11])
[email protected]("sigma", [[[1.5]], [[1.5], [5.0]], [[1.5], [5.0]]])
+def test_get_discrete_gaussian_erf_kernel1d_tensor(window_size, sigma, device, dtype):
+ sigma = torch.tensor(sigma, device=device, dtype=dtype)
+ bs = sigma.shape[0]
+
+ actual = get_gaussian_erf_kernel1d(window_size, sigma)
+ expected = torch.ones(bs, device=device, dtype=dtype)
+
+ assert actual.shape == (bs, window_size)
+ assert_close(actual.sum(), expected.sum())
+
+
[email protected]("window_size", [5, 11])
[email protected]("sigma", [1.5, 5.0])
+def test_get_gaussian_discrete_kernel1d_float(window_size, sigma, device, dtype):
+ actual = get_gaussian_discrete_kernel1d(window_size, sigma, device=device, dtype=dtype)
+ expected = torch.ones(1, device=device, dtype=dtype)
+
+ assert actual.shape == (1, window_size)
+ assert_close(actual.sum(), expected.sum())
+
+
[email protected]("window_size", [5, 11])
[email protected]("sigma", [[[1.5]], [[1.5], [5.0]], [[1.5], [5.0]]])
+def test_get_gaussian_discrete_kernel1d_tensor(window_size, sigma, device, dtype):
+ sigma = torch.tensor(sigma, device=device, dtype=dtype)
+ bs = sigma.shape[0]
+
+ actual = get_gaussian_discrete_kernel1d(window_size, sigma)
+ expected = torch.ones(bs, device=device, dtype=dtype)
+
+ assert actual.shape == (bs, window_size)
+ assert_close(actual.sum(), expected.sum())
@pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
[email protected]("sigma", [torch.tensor([[1.5, 2.1], [1.5, 2.1]]), torch.tensor([[1.5, 2.1], [2.5, 2.1]])])
-def test_separable_t(ksize_x, ksize_y, sigma, device, dtype):
- input = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
- out = kornia.filters.gaussian_blur2d_t(input, (ksize_x, ksize_y), sigma, "replicate", separable=False)
- out_sep = kornia.filters.gaussian_blur2d_t(input, (ksize_x, ksize_y), sigma, "replicate", separable=True)
[email protected]("sigma", [(1.5, 1.5), (2.1, 2.1)])
+def test_gaussian_blur2d_float(ksize_x, ksize_y, sigma, device, dtype):
+ input = torch.rand(1, 3, 16, 16, device=device, dtype=dtype)
+
+ actual = gaussian_blur2d(input, (ksize_x, ksize_y), sigma, "replicate", separable=False)
+ actual_sep = gaussian_blur2d(input, (ksize_x, ksize_y), sigma, "replicate", separable=True)
- assert_close(out, out_sep)
+ assert_close(actual, actual_sep)
-class TestGaussianBlur2d:
- @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
- def test_cardinality(self, batch_shape, device, dtype):
- kernel_size = (5, 7)
[email protected]("ksize_x", [5, 11])
[email protected]("ksize_y", [3, 7])
[email protected]("sigma", ([[1.5, 2.1], [1.5, 2.1], [5.0, 2.7]], [[1.5, 2.1], [3.5, 2.1]]))
+def test_gaussian_blur2d_tensor(ksize_x, ksize_y, sigma, device, dtype):
+ sigma = torch.tensor(sigma, device=device, dtype=dtype)
+ bs = sigma.shape[0]
+ input = torch.rand(bs, 3, 16, 16, device=device, dtype=dtype)
+ actual = gaussian_blur2d(input, (ksize_x, ksize_y), sigma, "replicate", separable=False)
+ actual_sep = gaussian_blur2d(input, (ksize_x, ksize_y), sigma, "replicate", separable=True)
+
+ assert_close(actual, actual_sep)
+
+
+class TestGaussianBlur2d(BaseTester):
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5), (5, 7)])
+ @pytest.mark.parametrize("separable", [False, True])
+ def test_smoke(self, shape, kernel_size, separable, device, dtype):
+ B, C, H, W = shape
+ inpt = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ sigma_tensor = torch.rand(B, 2, device=device, dtype=dtype)
+
+ actual_A = gaussian_blur2d(inpt, kernel_size, sigma_tensor, 'reflect', separable)
+ assert isinstance(actual_A, torch.Tensor)
+ assert actual_A.shape == shape
+
+ sigma = tuple(sigma_tensor[0, ...].cpu().numpy().tolist())
+ actual_B = gaussian_blur2d(inpt, kernel_size, sigma, 'reflect', separable)
+ assert isinstance(actual_B, torch.Tensor)
+ assert actual_B.shape == shape
+
+ # Just the first item of the batch use the same sigma
+ self.assert_close(actual_A[0, ...], actual_B[0, ...])
+
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5), (5, 7)])
+ def test_cardinality(self, shape, kernel_size, device, dtype):
sigma = (1.5, 2.1)
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- actual = kornia.filters.gaussian_blur2d(input, kernel_size, sigma, "replicate")
- assert actual.shape == batch_shape
+ input = torch.rand(shape, device=device, dtype=dtype)
+ actual = gaussian_blur2d(input, kernel_size, sigma, "replicate")
+ assert actual.shape == shape
+
+ def test_exception(self):
+ # input should be a tensor
+ with pytest.raises(Exception) as errinfo:
+ gaussian_blur2d(1, 3, (1.0, 1.0))
+ assert 'Not a Tensor type. Go' in str(errinfo)
+
+ # Sigma should be a tuple or a tensor
+ with pytest.raises(Exception) as errinfo:
+ gaussian_blur2d(torch.rand(1, 1, 1, 1), 3, 1.0)
+ assert 'Not a Tensor type. Go' in str(errinfo)
def test_noncontiguous(self, device, dtype):
batch_size = 3
@@ -94,37 +207,48 @@ class TestGaussianBlur2d:
kernel_size = (3, 3)
sigma = (1.5, 2.1)
- actual = kornia.filters.gaussian_blur2d(input, kernel_size, sigma, "replicate")
- assert_close(actual, actual)
+ actual = gaussian_blur2d(input, kernel_size, sigma, "replicate")
+ assert actual.is_contiguous()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
batch_shape = (1, 3, 5, 5)
kernel_size = (3, 3)
sigma = (1.5, 2.1)
# evaluate function gradient
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- kornia.filters.gaussian_blur2d,
- (input, kernel_size, sigma, "replicate"),
- raise_exception=True,
- fast_mode=True,
- )
-
- def test_jit(self, device, dtype):
- op = kornia.filters.gaussian_blur2d
- op_script = torch.jit.script(op)
- params = [(3, 3), (1.5, 1.5)]
+ input = torch.rand(batch_shape, device=device)
+ input = tensor_to_gradcheck_var(input) # to var
+ self.gradcheck(gaussian_blur2d, (input, kernel_size, sigma, "replicate"))
+
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5), (5, 7)])
+ @pytest.mark.parametrize("sigma", [(1.5, 2.1), (0.5, 0.5)])
+ def test_module(self, kernel_size, sigma, device, dtype):
+ params = [kernel_size, sigma]
+ op = gaussian_blur2d
+ op_module = GaussianBlur2d(*params)
img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
- assert_close(op(img, *params), op_script(img, *params))
- def test_module(self, device, dtype):
- params = [(3, 3), (1.5, 1.5)]
- op = kornia.filters.gaussian_blur2d
- op_module = kornia.filters.GaussianBlur2d(*params)
+ self.assert_close(op(img, *params), op_module(img))
+ sigma_tensor = torch.tensor([sigma], device=device, dtype=dtype)
+ params = [kernel_size, sigma_tensor]
+ op_module = GaussianBlur2d(*params)
- img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
- assert_close(op(img, *params), op_module(img))
+ self.assert_close(op(img, *params), op_module(img))
+
+ @pytest.mark.parametrize("kernel_size", [3, (5, 5), (5, 7)])
+ @pytest.mark.parametrize("sigma", [(1.5, 2.1), (0.5, 0.5)])
+ def test_dynamo(self, kernel_size, sigma, device, dtype, torch_optimizer):
+ inpt = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
+
+ op = GaussianBlur2d(kernel_size, sigma)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
+
+ sigma_tensor = torch.tensor([sigma], device=device, dtype=dtype)
+ op = GaussianBlur2d(kernel_size, sigma_tensor)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/filters/test_hanning.py b/test/filters/test_hanning.py
index b0f0ed11b..79a0eed16 100644
--- a/test/filters/test_hanning.py
+++ b/test/filters/test_hanning.py
@@ -1,13 +1,13 @@
import pytest
import torch
-import kornia
+from kornia.filters import get_hanning_kernel1d, get_hanning_kernel2d
from kornia.testing import assert_close
@pytest.mark.parametrize("window_size", [5, 11])
def test_get_hanning_kernel(window_size, device, dtype):
- kernel = kornia.filters.get_hanning_kernel1d(window_size, dtype=dtype, device=device)
+ kernel = get_hanning_kernel1d(window_size, dtype=dtype, device=device)
assert kernel.shape == (window_size,)
assert kernel.max().item() == pytest.approx(1.0)
@@ -15,20 +15,20 @@ def test_get_hanning_kernel(window_size, device, dtype):
@pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
def test_get_hanning_kernel2d(ksize_x, ksize_y, device, dtype):
- kernel = kornia.filters.get_hanning_kernel2d((ksize_x, ksize_y), dtype=dtype, device=device)
+ kernel = get_hanning_kernel2d((ksize_x, ksize_y), dtype=dtype, device=device)
assert kernel.shape == (ksize_x, ksize_y)
assert kernel.max().item() == pytest.approx(1.0)
def test_get_hanning_kernel1d_5(device, dtype):
- kernel = kornia.filters.get_hanning_kernel1d(5, dtype=dtype, device=device)
+ kernel = get_hanning_kernel1d(5, dtype=dtype, device=device)
expected = torch.tensor([0, 0.5, 1.0, 0.5, 0], dtype=dtype, device=device)
assert kernel.shape == (5,)
assert_close(kernel, expected)
def test_get_hanning_kernel2d_3x4(device, dtype):
- kernel = kornia.filters.get_hanning_kernel2d((3, 4), dtype=dtype, device=device)
+ kernel = get_hanning_kernel2d((3, 4), 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
)
diff --git a/test/filters/test_laplacian.py b/test/filters/test_laplacian.py
index aada2f6fc..bab358203 100644
--- a/test/filters/test_laplacian.py
+++ b/test/filters/test_laplacian.py
@@ -1,24 +1,37 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import Laplacian, get_laplacian_kernel1d, get_laplacian_kernel2d, laplacian
+from kornia.testing import BaseTester, assert_close, tensor_to_gradcheck_var
[email protected]("window_size", [5])
-def test_get_laplacian_kernel(window_size):
- kernel = kornia.filters.get_laplacian_kernel1d(window_size)
- assert kernel.shape == (window_size,)
- assert kernel.sum().item() == pytest.approx(0.0)
[email protected]("window_size", [5, 11])
+def test_get_laplacian_kernel1d(window_size, device, dtype):
+ actual = get_laplacian_kernel1d(window_size, device=device, dtype=dtype)
+ expected = torch.zeros(1, device=device, dtype=dtype)
+ assert actual.shape == (window_size,)
+ assert_close(actual.sum(), expected.sum())
[email protected]("window_size", [7])
-def test_get_laplacian_kernel2d(window_size):
- kernel = kornia.filters.get_laplacian_kernel2d(window_size)
- assert kernel.shape == (window_size, window_size)
- assert kernel.sum().item() == pytest.approx(0.0)
+
[email protected]("window_size", [5, 11, (3, 3)])
+def test_get_laplacian_kernel2d(window_size, device, dtype):
+ actual = get_laplacian_kernel2d(window_size, device=device, dtype=dtype)
+ expected = torch.zeros(1, device=device, dtype=dtype)
+ expected_shape = window_size if isinstance(window_size, tuple) else (window_size, window_size)
+
+ assert actual.shape == expected_shape
+ assert_close(actual.sum(), expected.sum())
+
+
+def test_get_laplacian_kernel1d_exact(device, dtype):
+ actual = get_laplacian_kernel1d(5, device=device, dtype=dtype)
+ expected = torch.tensor([1.0, 1.0, -4.0, 1.0, 1.0], device=device, dtype=dtype)
+ assert_close(expected, actual)
+
+
+def test_get_laplacian_kernel2d_exact(device, dtype):
+ actual = get_laplacian_kernel2d(7, device=device, dtype=dtype)
expected = torch.tensor(
[
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
@@ -28,50 +41,65 @@ def test_get_laplacian_kernel2d(window_size):
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
- ]
+ ],
+ device=device,
+ dtype=dtype,
)
- assert_close(expected, kernel)
-
-
-class TestLaplacian:
- @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
- def test_cardinality(self, batch_shape, device, dtype):
- kernel_size = 5
-
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- actual = kornia.filters.laplacian(input, kernel_size)
- assert actual.shape == batch_shape
+ assert_close(expected, actual)
+
+
+class TestLaplacian(BaseTester):
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ @pytest.mark.parametrize("kernel_size", [5, (11, 7), (3, 3)])
+ @pytest.mark.parametrize("normalized", [True, False])
+ def test_smoke(self, shape, kernel_size, normalized, device, dtype):
+ inpt = torch.rand(shape, device=device, dtype=dtype)
+ actual = laplacian(inpt, kernel_size, 'reflect', normalized)
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape == shape
+
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ @pytest.mark.parametrize("kernel_size", [5, (11, 7), 3])
+ def test_cardinality(self, shape, kernel_size, device, dtype):
+ input = torch.rand(shape, device=device, dtype=dtype)
+ actual = laplacian(input, kernel_size)
+ assert actual.shape == shape
+
+ @pytest.mark.skip(reason='Nothing to test.')
+ def test_exception(self):
+ ...
def test_noncontiguous(self, device, dtype):
batch_size = 3
input = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
kernel_size = 3
- actual = kornia.filters.laplacian(input, kernel_size)
- assert_close(actual, actual)
+ actual = laplacian(input, kernel_size)
+ assert actual.is_contiguous()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
batch_shape = (1, 2, 5, 7)
kernel_size = 3
# evaluate function gradient
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input)
- assert gradcheck(kornia.filters.laplacian, (input, kernel_size), raise_exception=True, fast_mode=True)
+ input = torch.rand(batch_shape, device=device)
+ input = tensor_to_gradcheck_var(input)
+ self.gradcheck(laplacian, (input, kernel_size))
- def test_jit(self, device, dtype):
- op = kornia.filters.laplacian
- op_script = torch.jit.script(op)
+ def test_module(self, device, dtype):
params = [3]
+ op = laplacian
+ op_module = Laplacian(*params)
img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
- assert_close(op(img, *params), op_script(img, *params))
+ self.assert_close(op(img, *params), op_module(img))
- def test_module(self, device, dtype):
- params = [3]
- op = kornia.filters.laplacian
- op_module = kornia.filters.Laplacian(*params)
+ @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = Laplacian(kernel_size)
+ op_optimized = torch_optimizer(op)
- img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
- assert_close(op(img, *params), op_module(img))
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/filters/test_median.py b/test/filters/test_median.py
index 54ba74126..1c5cd5d21 100644
--- a/test/filters/test_median.py
+++ b/test/filters/test_median.py
@@ -1,19 +1,31 @@
+import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import MedianBlur, median_blur
+from kornia.testing import BaseTester, tensor_to_gradcheck_var
-class TestMedianBlur:
- def test_shape(self, device, dtype):
+class TestMedianBlur(BaseTester):
+ def test_smoke(self, device, dtype):
inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
- assert kornia.filters.median_blur(inp, (3, 3)).shape == (1, 3, 4, 4)
+ actual = median_blur(inp, 3)
+ assert isinstance(actual, torch.Tensor)
- def test_shape_batch(self, device, dtype):
- inp = torch.zeros(2, 6, 4, 4, device=device, dtype=dtype)
- assert kornia.filters.median_blur(inp, (3, 3)).shape == (2, 6, 4, 4)
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('kernel_size', [3, (5, 7)])
+ def test_cardinality(self, batch_size, kernel_size, device, dtype):
+ inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
+ actual = median_blur(inp, kernel_size)
+ assert actual.shape == (batch_size, 3, 4, 4)
+
+ def test_exception(self, device, dtype):
+ with pytest.raises(TypeError) as errinfo:
+ median_blur(1, 1)
+ assert 'Not a Tensor type.' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ median_blur(torch.ones(1, 1, device=device, dtype=dtype), 1)
+ assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']].' in str(errinfo)
def test_kernel_3x3(self, device, dtype):
inp = torch.tensor(
@@ -38,38 +50,38 @@ class TestMedianBlur:
).repeat(2, 1, 1, 1)
kernel_size = (3, 3)
- actual = kornia.filters.median_blur(inp, kernel_size)
- assert_close(actual[0, 0, 2, 2], torch.tensor(3.0).to(actual))
- assert_close(actual[0, 1, 1, 1], torch.tensor(14.0).to(actual))
+ actual = median_blur(inp, kernel_size)
+ self.assert_close(actual[0, 0, 2, 2], torch.tensor(3.0, device=device, dtype=dtype))
+ self.assert_close(actual[0, 1, 1, 1], torch.tensor(14.0, device=device, dtype=dtype))
def test_noncontiguous(self, device, dtype):
batch_size = 3
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
kernel_size = (3, 3)
- actual = kornia.filters.median_blur(inp, kernel_size)
- assert_close(actual, actual)
+ actual = median_blur(inp, kernel_size)
+ assert actual.is_contiguous()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.median_blur, (img, (5, 3)), raise_exception=True, fast_mode=True)
-
- def test_jit(self, device, dtype):
- kernel_size = (3, 5)
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.median_blur
- op_script = torch.jit.script(op)
- actual = op_script(img, kernel_size)
- expected = op(img, kernel_size)
- assert_close(actual, expected)
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = tensor_to_gradcheck_var(img) # to var
+ self.gradcheck(median_blur, (img, (5, 3)))
def test_module(self, device, dtype):
kernel_size = (3, 5)
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.median_blur
- op_module = kornia.filters.MedianBlur((3, 5))
+ op = median_blur
+ op_module = MedianBlur((3, 5))
actual = op_module(img)
expected = op(img, kernel_size)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize('kernel_size', [5, (5, 7)])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, kernel_size, device, dtype, torch_optimizer):
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = MedianBlur(kernel_size)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/filters/test_motion.py b/test/filters/test_motion.py
index 490de93be..ccdf16474 100644
--- a/test/filters/test_motion.py
+++ b/test/filters/test_motion.py
@@ -1,37 +1,68 @@
import pytest
import torch
-from torch.autograd import gradcheck
-
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
-
-
[email protected]("batch_size", [0, 1, 5])
[email protected]("ksize", [3, 11])
[email protected]("angle", [0.0, 360.0])
[email protected]("direction", [-1.0, 1.0])
-def test_get_motion_kernel2d(batch_size, ksize, angle, direction):
- if batch_size != 0:
- angle = torch.tensor([angle] * batch_size)
- direction = torch.tensor([direction] * batch_size)
- else:
- batch_size = 1
- kernel = kornia.filters.kernels_geometry.get_motion_kernel2d(ksize, angle, direction)
- assert kernel.shape == (batch_size, ksize, ksize)
- assert kernel.sum().item() == pytest.approx(batch_size)
-
-
-class TestMotionBlur:
- @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
- def test_motion_blur(self, batch_shape, device, dtype):
+
+from kornia.filters import (
+ MotionBlur,
+ MotionBlur3D,
+ get_motion_kernel2d,
+ get_motion_kernel3d,
+ motion_blur,
+ motion_blur3d,
+)
+from kornia.testing import BaseTester, tensor_to_gradcheck_var
+
+
+class TestMotionBlur(BaseTester):
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ @pytest.mark.parametrize("kernel_size", [3, 5])
+ @pytest.mark.parametrize("angle", [36.0, 200.0])
+ @pytest.mark.parametrize("direction", [-0.9, 0.0, 0.9])
+ @pytest.mark.parametrize("mode", ['bilinear', 'nearest'])
+ @pytest.mark.parametrize("params_as_tensor", [True, False])
+ def test_smoke(self, shape, kernel_size, angle, direction, mode, params_as_tensor, device, dtype):
+ B, C, H, W = shape
+ inpt = torch.rand(shape, device=device, dtype=dtype)
+
+ if params_as_tensor is True:
+ angle = torch.tensor([angle], device=device, dtype=dtype).repeat(B)
+ direction = torch.tensor([direction], device=device, dtype=dtype).repeat(B)
+ actual = motion_blur(inpt, kernel_size, angle, direction, 'constant', mode)
+
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape == shape
+
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ def test_cardinality(self, shape, device, dtype):
ksize = 5
angle = 200.0
direction = 0.3
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- motion = kornia.filters.MotionBlur(ksize, angle, direction)
- assert motion(input).shape == batch_shape
+ input = torch.rand(shape, device=device, dtype=dtype)
+ motion = MotionBlur(ksize, angle, direction)
+ assert motion(input).shape == shape
+
+ @pytest.mark.skip(reason='nothing to test')
+ def test_exception(self):
+ ...
+
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ @pytest.mark.parametrize("ksize", [3, 11])
+ @pytest.mark.parametrize("angle", [0.0, 360.0])
+ @pytest.mark.parametrize("direction", [-1.0, 1.0])
+ @pytest.mark.parametrize("params_as_tensor", [True, False])
+ def test_get_motion_kernel2d(self, batch_size, ksize, angle, direction, params_as_tensor, device, dtype):
+ if params_as_tensor is True:
+ angle = torch.tensor([angle], device=device, dtype=dtype).repeat(batch_size)
+ direction = torch.tensor([direction], device=device, dtype=dtype).repeat(batch_size)
+ else:
+ batch_size = 1
+ device = None
+ dtype = None
+
+ actual = get_motion_kernel2d(ksize, angle, direction)
+ expected = torch.ones(1, device=device, dtype=dtype) * batch_size
+ assert actual.shape == (batch_size, ksize, ksize)
+ self.assert_close(actual.sum(), expected.sum())
def test_noncontiguous(self, device, dtype):
batch_size = 3
@@ -40,33 +71,124 @@ class TestMotionBlur:
kernel_size = 3
angle = 200.0
direction = 0.3
- actual = kornia.filters.motion_blur(inp, kernel_size, angle, direction)
- assert_close(actual, actual)
+ actual = motion_blur(inp, kernel_size, angle, direction)
+ assert actual.is_contiguous()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_shape = (1, 3, 4, 5)
ksize = 9
angle = 34.0
direction = -0.2
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input)
- assert gradcheck(
- kornia.filters.motion_blur,
- (input, ksize, angle, direction, "replicate"),
- nondet_tol=1e-8,
- raise_exception=True,
- fast_mode=True,
- )
-
- @pytest.mark.skip("angle can be Union")
- def test_jit(self, device, dtype):
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
+ input = torch.rand(batch_shape, device=device)
+ input = tensor_to_gradcheck_var(input)
+ self.gradcheck(motion_blur, (input, ksize, angle, direction, "replicate"), nondet_tol=1e-8)
+
+ def test_module(self, device, dtype):
+ params = [3, 20.0, 0.5]
+ op = motion_blur
+ op_module = MotionBlur(*params)
+ img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
+
+ self.assert_close(op(img, *params), op_module(img))
+
+ @pytest.mark.skip(reason='After the op be optimized the results are not the same')
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, device, dtype, torch_optimizer):
+ # TODO: FIX op
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = MotionBlur(3, 36.0, 0.5)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
+
+
+class TestMotionBlur3D(BaseTester):
+ @pytest.mark.parametrize("shape", [(1, 4, 3, 8, 15), (2, 2, 3, 11, 7)])
+ @pytest.mark.parametrize("kernel_size", [3, 5])
+ @pytest.mark.parametrize("angle", [(36.0, 15.0, 200.0), (200.0, 10.0, 150.0)])
+ @pytest.mark.parametrize("direction", [-0.9, 0.0, 0.9])
+ @pytest.mark.parametrize("mode", ['bilinear', 'nearest'])
+ @pytest.mark.parametrize("params_as_tensor", [True, False])
+ def test_smoke(self, shape, kernel_size, angle, direction, mode, params_as_tensor, device, dtype):
+ B, C, D, H, W = shape
+ inpt = torch.rand(shape, device=device, dtype=dtype)
+
+ if params_as_tensor is True:
+ angle = torch.tensor([angle], device=device, dtype=dtype).expand(B, 3)
+ direction = torch.tensor([direction], device=device, dtype=dtype).repeat(B)
+ actual = motion_blur3d(inpt, kernel_size, angle, direction, 'constant', mode)
+
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape == shape
+
+ @pytest.mark.parametrize("shape", [(1, 4, 1, 8, 15), (2, 3, 1, 11, 7)])
+ def test_cardinality(self, shape, device, dtype):
ksize = 5
- angle = 65.0
- direction = 0.1
- op = kornia.filters.motion_blur
- op_script = torch.jit.script(op)
- actual = op_script(img, ksize, angle, direction)
- expected = op(img, ksize, angle, direction)
- assert_close(actual, expected)
+ angle = (200.0, 15.0, 120.0)
+ direction = 0.3
+
+ input = torch.rand(shape, device=device, dtype=dtype)
+ motion = MotionBlur3D(ksize, angle, direction)
+ assert motion(input).shape == shape
+
+ @pytest.mark.skip(reason='nothing to test')
+ def test_exception(self):
+ ...
+
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ @pytest.mark.parametrize("ksize", [3, 11])
+ @pytest.mark.parametrize("angle", [(0.0, 360.0, 150.0)])
+ @pytest.mark.parametrize("direction", [-1.0, 1.0])
+ @pytest.mark.parametrize("params_as_tensor", [True, False])
+ def test_get_motion_kernel3d(self, batch_size, ksize, angle, direction, params_as_tensor, device, dtype):
+ if params_as_tensor is True:
+ angle = torch.tensor([angle], device=device, dtype=dtype).repeat(batch_size, 1)
+ direction = torch.tensor([direction], device=device, dtype=dtype).repeat(batch_size)
+ else:
+ batch_size = 1
+ device = None
+ dtype = None
+
+ actual = get_motion_kernel3d(ksize, angle, direction)
+ expected = torch.ones(1, device=device, dtype=dtype) * batch_size
+ assert actual.shape == (batch_size, ksize, ksize, ksize)
+ self.assert_close(actual.sum(), expected.sum())
+
+ def test_noncontiguous(self, device, dtype):
+ batch_size = 3
+ inp = torch.rand(3, 1, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1, -1)
+
+ kernel_size = 3
+ angle = (0.0, 360.0, 150.0)
+ direction = 0.3
+ actual = motion_blur3d(inp, kernel_size, angle, direction)
+ assert actual.is_contiguous()
+
+ def test_gradcheck(self, device):
+ batch_shape = (1, 3, 1, 4, 5)
+ ksize = 9
+ angle = (0.0, 360.0, 150.0)
+ direction = -0.2
+
+ input = torch.rand(batch_shape, device=device)
+ input = tensor_to_gradcheck_var(input)
+ self.gradcheck(motion_blur3d, (input, ksize, angle, direction, "replicate"), nondet_tol=1e-8)
+
+ def test_module(self, device, dtype):
+ params = [3, (0.0, 360.0, 150.0), 0.5]
+ op = motion_blur3d
+ op_module = MotionBlur3D(*params)
+ img = torch.ones(1, 3, 1, 5, 5, device=device, dtype=dtype)
+
+ self.assert_close(op(img, *params), op_module(img))
+
+ @pytest.mark.skip(reason='After the op be optimized the results are not the same')
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, device, dtype, torch_optimizer):
+ # TODO: Fix the operation to works after dynamo optimize
+ inpt = torch.ones(batch_size, 3, 1, 10, 10, device=device, dtype=dtype)
+ op = MotionBlur3D(3, (0.0, 360.0, 150.0), 0.5)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.py
index 3003c2429..90087b01c 100644
--- a/test/filters/test_sobel.py
+++ b/test/filters/test_sobel.py
@@ -1,22 +1,33 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import Sobel, SpatialGradient, SpatialGradient3d, sobel, spatial_gradient, spatial_gradient3d
+from kornia.testing import BaseTester, tensor_to_gradcheck_var
-class TestSpatialGradient:
- def test_shape(self, device, dtype):
- inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
- sobel = kornia.filters.SpatialGradient()
- assert sobel(inp).shape == (1, 3, 2, 4, 4)
+class TestSpatialGradient(BaseTester):
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('mode', ['sobel', 'diff'])
+ @pytest.mark.parametrize('order', [1, 2])
+ @pytest.mark.parametrize('normalized', [True, False])
+ def test_smoke(self, batch_size, mode, order, normalized, device, dtype):
+ inpt = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
+ actual = SpatialGradient(mode, order, normalized)(inpt)
+ assert isinstance(actual, torch.Tensor)
- def test_shape_batch(self, device, dtype):
- inp = torch.zeros(2, 6, 4, 4, device=device, dtype=dtype)
- sobel = kornia.filters.SpatialGradient()
- assert sobel(inp).shape == (2, 6, 2, 4, 4)
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_cardinality(self, batch_size, device, dtype):
+ inp = torch.zeros(batch_size, 3, 4, 4, device=device, dtype=dtype)
+ assert SpatialGradient()(inp).shape == (batch_size, 3, 2, 4, 4)
+
+ def test_exception(self):
+ with pytest.raises(TypeError) as errinfo:
+ spatial_gradient(1)
+ assert 'Not a Tensor type' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ spatial_gradient(torch.zeros(1))
+ assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
def test_edges(self, device, dtype):
inp = torch.tensor(
@@ -60,8 +71,8 @@ class TestSpatialGradient:
dtype=dtype,
)
- edges = kornia.filters.spatial_gradient(inp, normalized=False)
- assert_close(edges, expected)
+ edges = spatial_gradient(inp, normalized=False)
+ self.assert_close(edges, expected)
def test_edges_norm(self, device, dtype):
inp = torch.tensor(
@@ -108,8 +119,8 @@ class TestSpatialGradient:
/ 8.0
)
- edges = kornia.filters.spatial_gradient(inp, normalized=True)
- assert_close(edges, expected)
+ edges = spatial_gradient(inp, normalized=True)
+ self.assert_close(edges, expected)
def test_edges_sep(self, device, dtype):
inp = torch.tensor(
@@ -153,8 +164,8 @@ class TestSpatialGradient:
dtype=dtype,
)
- edges = kornia.filters.spatial_gradient(inp, 'diff', normalized=False)
- assert_close(edges, expected)
+ edges = spatial_gradient(inp, 'diff', normalized=False)
+ self.assert_close(edges, expected)
def test_edges_sep_norm(self, device, dtype):
inp = torch.tensor(
@@ -201,54 +212,71 @@ class TestSpatialGradient:
/ 2.0
)
- edges = kornia.filters.spatial_gradient(inp, 'diff', normalized=True)
- assert_close(edges, expected)
+ edges = spatial_gradient(inp, 'diff', normalized=True)
+ self.assert_close(edges, expected)
def test_noncontiguous(self, device, dtype):
batch_size = 3
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
- actual = kornia.filters.spatial_gradient(inp)
+ actual = spatial_gradient(inp)
assert inp.is_contiguous() is False
assert actual.is_contiguous()
assert actual.shape == (3, 3, 2, 5, 5)
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.spatial_gradient, (img,), raise_exception=True, fast_mode=True)
-
- def test_jit(self, device, dtype):
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.spatial_gradient
- op_script = torch.jit.script(op)
- actual = op_script(img)
- expected = op(img)
- assert_close(actual, expected)
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = tensor_to_gradcheck_var(img) # to var
+ self.gradcheck(spatial_gradient, (img,))
def test_module(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.spatial_gradient
- op_module = kornia.filters.SpatialGradient()
+ op = spatial_gradient
+ op_module = SpatialGradient()
expected = op(img)
actual = op_module(img)
- assert_close(actual, expected)
-
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize('mode', ['sobel', 'diff'])
+ @pytest.mark.parametrize('order', [1, 2])
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, order, mode, device, dtype, torch_optimizer):
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ if order == 1 and dtype == torch.float64:
+ # TODO: FIX order 1 spatial gradient with fp64 on dynamo
+ pytest.xfail(reason='Order 1 on spatial gradient may be wrong computed for float64 on dynamo')
+ op = SpatialGradient(mode, order)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
+
+
+class TestSpatialGradient3d(BaseTester):
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('mode', ['diff']) # TODO: add support to 'sobel'
+ @pytest.mark.parametrize('order', [1, 2])
+ def test_smoke(self, batch_size, mode, order, device, dtype):
+ inpt = torch.ones(batch_size, 3, 2, 7, 4, device=device, dtype=dtype)
+ actual = SpatialGradient3d(mode, order)(inpt)
+ assert isinstance(actual, torch.Tensor)
+
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_cardinality(self, batch_size, device, dtype):
+ inp = torch.zeros(batch_size, 2, 4, 5, 6, device=device, dtype=dtype)
+ sobel = SpatialGradient3d()
+ assert sobel(inp).shape == (batch_size, 2, 3, 4, 5, 6)
+
+ def test_exception(self):
+ with pytest.raises(TypeError) as errinfo:
+ spatial_gradient3d(1)
+ assert 'Not a Tensor type' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ spatial_gradient3d(torch.zeros(1))
+ assert 'shape must be [[\'B\', \'C\', \'D\', \'H\', \'W\']]' in str(errinfo)
-class TestSpatialGradient3d:
- def test_shape(self, device, dtype):
- inp = torch.zeros(1, 2, 4, 5, 6, device=device, dtype=dtype)
- sobel = kornia.filters.SpatialGradient3d()
- assert sobel(inp).shape == (1, 2, 3, 4, 5, 6)
-
- def test_shape_batch(self, device, dtype):
- inp = torch.zeros(7, 2, 4, 5, 6, device=device, dtype=dtype)
- sobel = kornia.filters.SpatialGradient3d()
- assert sobel(inp).shape == (7, 2, 3, 4, 5, 6)
-
- @pytest.mark.skip("fix due to bug in kernel_flip")
def test_edges(self, device, dtype):
inp = torch.tensor(
[
@@ -362,42 +390,56 @@ class TestSpatialGradient3d:
dtype=dtype,
)
- edges = kornia.filters.spatial_gradient3d(inp)
- assert_close(edges, expected)
-
- def test_gradcheck(self, device, dtype):
- img = torch.rand(1, 1, 1, 3, 4, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.spatial_gradient3d, (img,), raise_exception=True)
+ edges = spatial_gradient3d(inp)
+ self.assert_close(edges, expected)
- @pytest.mark.skip("issue with device in kernel generation")
- def test_jit(self, device, dtype):
- img = torch.rand(2, 3, 1, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.spatial_gradient3d
- op_script = torch.jit.script(op)
- expected = op(img)
- actual = op_script(img)
- assert_close(actual, expected)
+ def test_gradcheck(self, device):
+ img = torch.rand(1, 1, 1, 3, 4, device=device)
+ img = tensor_to_gradcheck_var(img) # to var
+ fast_mode = 'cpu' in str(device) # disable fast mode on gpu
+ self.gradcheck(spatial_gradient3d, (img,), fast_mode=fast_mode)
def test_module(self, device, dtype):
img = torch.rand(2, 3, 1, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.spatial_gradient3d
- op_module = kornia.filters.SpatialGradient3d()
+ op = spatial_gradient3d
+ op_module = SpatialGradient3d()
expected = op(img)
actual = op_module(img)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
+ @pytest.mark.parametrize('mode', ['diff'])
+ @pytest.mark.parametrize('order', [1, 2])
+ def test_dynamo(self, mode, order, device, dtype, torch_optimizer):
+ inpt = torch.ones(1, 3, 1, 10, 10, device=device, dtype=dtype)
+ op = SpatialGradient3d(mode, order)
+ op_optimized = torch_optimizer(op)
-class TestSobel:
- def test_shape(self, device, dtype):
- inp = torch.zeros(1, 3, 4, 4, device=device, dtype=dtype)
- sobel = kornia.filters.Sobel()
- assert sobel(inp).shape == (1, 3, 4, 4)
+ self.assert_close(op(inpt), op_optimized(inpt))
- def test_shape_batch(self, device, dtype):
- inp = torch.zeros(3, 2, 4, 4, device=device, dtype=dtype)
- sobel = kornia.filters.Sobel()
- assert sobel(inp).shape == (3, 2, 4, 4)
+
+class TestSobel(BaseTester):
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ @pytest.mark.parametrize('normalized', [True, False])
+ def test_smoke(self, batch_size, normalized, device, dtype):
+ inp = torch.zeros(batch_size, 3, 4, 7, device=device, dtype=dtype)
+ actual = Sobel()(inp)
+
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape == (batch_size, 3, 4, 7)
+
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_cardinality(self, batch_size, device, dtype):
+ inp = torch.zeros(batch_size, 3, 4, 7, device=device, dtype=dtype)
+ assert Sobel()(inp).shape == (batch_size, 3, 4, 7)
+
+ def test_exception(self):
+ with pytest.raises(TypeError) as errinfo:
+ sobel(1)
+ assert 'Not a Tensor type' in str(errinfo)
+
+ with pytest.raises(TypeError) as errinfo:
+ sobel(torch.zeros(1))
+ assert 'shape must be [[\'B\', \'C\', \'H\', \'W\']]' in str(errinfo)
def test_magnitude(self, device, dtype):
inp = torch.tensor(
@@ -432,48 +474,42 @@ class TestSobel:
dtype=dtype,
)
- edges = kornia.filters.sobel(inp, normalized=False, eps=0.0)
- assert_close(edges, expected)
+ edges = sobel(inp, normalized=False, eps=0.0)
+ self.assert_close(edges, expected)
def test_noncontiguous(self, device, dtype):
batch_size = 3
inp = torch.rand(3, 5, 5, device=device, dtype=dtype).expand(batch_size, -1, -1, -1)
- sobel = kornia.filters.Sobel()
- actual = sobel(inp)
+ op = Sobel()
+ actual = op(inp)
assert inp.is_contiguous() is False
assert actual.is_contiguous()
assert actual.shape == (3, 3, 5, 5)
- def test_gradcheck_unnorm(self, device, dtype):
- if "cuda" in str(device):
- pytest.skip("RuntimeError: Backward is not reentrant, i.e., running backward,")
+ @pytest.mark.parametrize('normalized', [True, False])
+ def test_gradcheck(self, normalized, device):
batch_size, channels, height, width = 1, 1, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.sobel, (img, False), raise_exception=True, fast_mode=True)
-
- def test_gradcheck(self, device, dtype):
- if "cuda" in str(device):
- pytest.skip("RuntimeError: Backward is not reentrant, i.e., running backward,")
- batch_size, channels, height, width = 1, 1, 3, 4
- img = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.filters.sobel, (img, True), raise_exception=True, fast_mode=True)
-
- def test_jit(self, device, dtype):
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.sobel
- op_script = torch.jit.script(op)
- expected = op(img)
- actual = op_script(img)
- assert_close(actual, expected)
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = tensor_to_gradcheck_var(img) # to var
+ self.gradcheck(sobel, (img, normalized))
def test_module(self, device, dtype):
img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.filters.sobel
- op_module = kornia.filters.Sobel()
+ op = sobel
+ op_module = Sobel()
expected = op(img)
actual = op_module(img)
- assert_close(actual, expected)
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize('batch_size', [1, 2])
+ def test_dynamo(self, batch_size, device, dtype, torch_optimizer):
+ if dtype == torch.float64:
+ # TODO: investigate sobel for float64 with dynamo
+ pytest.xfail(reason='The sobel results can be different after dynamo on fp64')
+ inpt = torch.ones(batch_size, 3, 10, 10, device=device, dtype=dtype)
+ op = Sobel()
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/filters/test_unsharp_mask.py b/test/filters/test_unsharp_mask.py
index 6f562dad4..37ba0a09a 100644
--- a/test/filters/test_unsharp_mask.py
+++ b/test/filters/test_unsharp_mask.py
@@ -1,21 +1,36 @@
import pytest
import torch
-from torch.autograd import gradcheck
-import kornia
-import kornia.testing as utils # test utils
-from kornia.testing import assert_close
+from kornia.filters import UnsharpMask, unsharp_mask
+from kornia.testing import BaseTester, tensor_to_gradcheck_var
-class Testunsharp:
- @pytest.mark.parametrize("batch_shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
- def test_cardinality(self, batch_shape, device, dtype):
+class Testunsharp(BaseTester):
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ @pytest.mark.parametrize("kernel_size", [3, (5, 3)])
+ @pytest.mark.parametrize("sigma", [(3.0, 1.0), (0.5, -0.1)])
+ @pytest.mark.parametrize("params_as_tensor", [True, False])
+ def test_smoke(self, shape, kernel_size, sigma, params_as_tensor, device, dtype):
+ if params_as_tensor is True:
+ sigma = torch.tensor([sigma], device=device, dtype=dtype).repeat(shape[0], 1)
+
+ inpt = torch.ones(shape, device=device, dtype=dtype)
+ actual = unsharp_mask(inpt, kernel_size, sigma, 'replicate')
+ assert isinstance(actual, torch.Tensor)
+ assert actual.shape == shape
+
+ @pytest.mark.parametrize("shape", [(1, 4, 8, 15), (2, 3, 11, 7)])
+ def test_cardinality(self, shape, device, dtype):
kernel_size = (5, 7)
sigma = (1.5, 2.1)
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- actual = kornia.filters.unsharp_mask(input, kernel_size, sigma, "replicate")
- assert actual.shape == batch_shape
+ inpt = torch.ones(shape, device=device, dtype=dtype)
+ actual = unsharp_mask(inpt, kernel_size, sigma, "replicate")
+ assert actual.shape == shape
+
+ @pytest.mark.skip(reason='nothing to test')
+ def test_exception(self):
+ ...
def test_noncontiguous(self, device, dtype):
batch_size = 3
@@ -23,34 +38,36 @@ class Testunsharp:
kernel_size = (3, 3)
sigma = (1.5, 2.1)
- actual = kornia.filters.unsharp_mask(input, kernel_size, sigma, "replicate")
- assert_close(actual, actual)
+ actual = unsharp_mask(input, kernel_size, sigma, "replicate")
+ assert actual.is_contiguous()
- def test_gradcheck(self, device, dtype):
+ def test_gradcheck(self, device):
# test parameters
- batch_shape = (1, 3, 5, 5)
+ shape = (1, 3, 5, 5)
kernel_size = (3, 3)
sigma = (1.5, 2.1)
# evaluate function gradient
- input = torch.rand(batch_shape, device=device, dtype=dtype)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(
- kornia.filters.unsharp_mask, (input, kernel_size, sigma, "replicate"), raise_exception=True, fast_mode=True
- )
-
- def test_jit(self, device, dtype):
- op = kornia.filters.unsharp_mask
- op_script = torch.jit.script(op)
- params = [(3, 3), (1.5, 1.5)]
-
- img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
- assert_close(op(img, *params), op_script(img, *params))
+ inpt = torch.rand(shape, device=device)
+ inpt = tensor_to_gradcheck_var(inpt) # to var
+ self.gradcheck(unsharp_mask, (inpt, kernel_size, sigma, "replicate"))
def test_module(self, device, dtype):
params = [(3, 3), (1.5, 1.5)]
- op = kornia.filters.unsharp_mask
- op_module = kornia.filters.UnsharpMask(*params)
+ op = unsharp_mask
+ op_module = UnsharpMask(*params)
img = torch.ones(1, 3, 5, 5, device=device, dtype=dtype)
- assert_close(op(img, *params), op_module(img))
+ self.assert_close(op(img, *params), op_module(img))
+
+ @pytest.mark.parametrize("sigma", [(3.0, 1.0), (0.5, -0.1)])
+ @pytest.mark.parametrize("params_as_tensor", [True, False])
+ def test_dynamo(self, sigma, params_as_tensor, device, dtype, torch_optimizer):
+ if params_as_tensor is True:
+ sigma = torch.tensor([sigma], device=device, dtype=dtype)
+
+ inpt = torch.ones(1, 3, 10, 10, device=device, dtype=dtype)
+ op = UnsharpMask(3, sigma)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(inpt), op_optimized(inpt))
diff --git a/test/geometry/transform/test_elastic_transform.py b/test/geometry/transform/test_elastic_transform.py
index a2c86e26f..2d57f7a47 100644
--- a/test/geometry/transform/test_elastic_transform.py
+++ b/test/geometry/transform/test_elastic_transform.py
@@ -2,7 +2,6 @@ import pytest
import torch
from torch.autograd import gradcheck
-import kornia
from kornia.geometry.transform import elastic_transform2d
from kornia.testing import assert_close
@@ -77,12 +76,3 @@ class TestElasticTransform:
image = torch.rand(1, 1, 3, 3, device=device, dtype=torch.float64, requires_grad=requires_grad)
noise = torch.rand(1, 2, 3, 3, device=device, dtype=torch.float64, requires_grad=not requires_grad)
assert gradcheck(elastic_transform2d, (image, noise), raise_exception=True, fast_mode=True)
-
- def test_jit(self, device, dtype):
- image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)
- noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)
-
- op = kornia.geometry.transform.elastic_transform2d
- op_jit = torch.jit.script(op)
-
- assert_close(op(image, noise), op_jit(image, noise))
diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.py
index 40b8fd8e7..4eacfa97e 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -23,12 +23,6 @@ class TestPyrUp:
img = utils.tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.geometry.pyrup, (img,), nondet_tol=1e-8, raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.geometry.pyrup
- op_jit = torch.jit.script(op)
- assert_close(op(img), op_jit(img))
-
class TestPyrDown:
def test_shape(self, device, dtype):
@@ -58,12 +52,6 @@ class TestPyrDown:
img = utils.tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.geometry.pyrdown, (img,), nondet_tol=1e-8, raise_exception=True, fast_mode=True)
- def test_jit(self, device, dtype):
- img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)
- op = kornia.geometry.pyrdown
- op_jit = torch.jit.script(op)
- assert_close(op(img), op_jit(img))
-
class TestScalePyramid:
def test_shape_tuple(self, device, dtype):
diff --git a/test/losses/test_ssim.py b/test/losses/test_ssim.py
index 4cb4ad219..657dd174e 100644
--- a/test/losses/test_ssim.py
+++ b/test/losses/test_ssim.py
@@ -35,17 +35,6 @@ class TestSSIMLoss:
tol_val: float = utils._get_precision_by_name(device, 'xla', 1e-1, 1e-4)
assert_close(loss.item(), 0.0, rtol=tol_val, atol=tol_val)
- def test_jit(self, device, dtype):
- img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
- img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
-
- args = (img1, img2, 5, 1.0, 1e-6, 'mean')
-
- op = kornia.losses.ssim_loss
- op_script = torch.jit.script(op)
-
- assert_close(op(*args), op_script(*args))
-
def test_module(self, device, dtype):
img1 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
img2 = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
@@ -161,17 +150,6 @@ class TestSSIM3DLoss(BaseTester):
self.assert_close(actual, expected)
- def test_jit(self, device, dtype):
- img1 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
- img2 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
-
- args = (img1, img2, 5, 1.0, 1e-6, 'mean')
-
- op = kornia.losses.ssim3d_loss
- op_script = torch.jit.script(op)
-
- self.assert_close(op(*args), op_script(*args))
-
def test_module(self, device, dtype):
img1 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
img2 = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
diff --git a/test/test_metrics.py b/test/test_metrics.py
index 8cc24056d..7a9742e69 100644
--- a/test/test_metrics.py
+++ b/test/test_metrics.py
@@ -352,12 +352,3 @@ class TestSSIM3d(BaseTester):
img = tensor_to_gradcheck_var(img)
assert self.gradcheck(op, (img, img, 3), nondet_tol=1e-8)
-
- @pytest.mark.jit
- def test_jit(self, device, dtype):
- img = torch.rand(1, 1, 3, 3, 3, device=device, dtype=dtype)
-
- op = kornia.metrics.ssim3d
- op_jit = torch.jit.script(op)
-
- assert_close(op(img, img, 3), op_jit(img, img, 3))