Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[ready to review] Better nms (#371)

Dmytro Mishkin83e646e5fa79
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index e0d210e9a..f270b332e 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -4,6 +4,9 @@ kornia.feature
.. currentmodule:: kornia.feature
.. autofunction:: non_maxima_suppression2d
+.. autofunction:: non_maxima_suppression3d
+.. autofunction:: nms2d
+.. autofunction:: nms3d
.. autofunction:: gftt_response
.. autofunction:: harris_response
.. autofunction:: hessian_response
@@ -19,6 +22,7 @@ kornia.feature
.. autofunction:: raise_error_if_laf_is_not_valid
.. autoclass:: NonMaximaSuppression2d
+.. autoclass:: NonMaximaSuppression3d
.. autoclass:: BlobHessian
.. autoclass:: CornerGFTT
.. autoclass:: CornerHarris
diff --git a/docs/source/filters.rst b/docs/source/filters.rst
index 142888461..0cc8f91df 100644
--- a/docs/source/filters.rst
+++ b/docs/source/filters.rst
@@ -12,6 +12,7 @@ The functions in this sections perform various image filtering operations.
.. autofunction:: laplacian
.. autofunction:: sobel
.. autofunction:: spatial_gradient
+.. autofunction:: spatial_gradient3d
.. autofunction:: motion_blur
.. autofunction:: get_gaussian_kernel1d
@@ -26,4 +27,5 @@ The functions in this sections perform various image filtering operations.
.. autoclass:: Laplacian
.. autoclass:: Sobel
.. autoclass:: SpatialGradient
+.. autoclass:: SpatialGradient3d
.. autoclass:: MotionBlur
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index 6406f923a..a70bfbb4f 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -8,12 +8,14 @@ kornia.geometry
.. autofunction:: render_gaussian_2d
.. autofunction:: conv_soft_argmax2d
.. autofunction:: conv_soft_argmax3d
+.. autofunction:: conv_quad_interp3d
.. autofunction:: spatial_softmax_2d
-.. autofunction:: spatial_softmax_2d
+
.. autoclass:: SpatialSoftArgmax2d
.. autoclass:: ConvSoftArgmax2d
.. autoclass:: ConvSoftArgmax3d
+.. autoclass:: ConvQuadInterp3d
.. toctree::
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 845dc798d..38b5945bb 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -43,8 +43,10 @@ from kornia.contrib import (
max_blur_pool2d,
)
from kornia.feature import (
- non_maxima_suppression2d,
+ nms2d,
harris_response,
+ hessian_response,
+ gftt_response,
SIFTDescriptor
)
from kornia.filters import (
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 10c52537e..984d07bf4 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -4,7 +4,15 @@ from .responses import (CornerHarris,
harris_response,
gftt_response,
hessian_response)
-from .nms import NonMaximaSuppression2d, non_maxima_suppression2d
+from .nms import (NonMaximaSuppression2d,
+ nms2d,
+ NonMaximaSuppression3d,
+ nms3d)
+
+# Backward compatibility
+from .nms import nms2d as non_maxima_suppression2d
+from .nms import nms3d as non_maxima_suppression3d
+
from .laf import (extract_patches_from_pyramid,
extract_patches_simple,
normalize_laf,
@@ -27,11 +35,15 @@ from .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator
from .orientation import LAFOrienter, PatchDominantGradientOrientation
__all__ = [
+ "nms2d",
+ "nms3d",
"non_maxima_suppression2d",
+ "non_maxima_suppression3d",
"harris_response",
"gftt_response",
"hessian_response",
"NonMaximaSuppression2d",
+ "NonMaximaSuppression3d",
"CornerHarris",
"CornerGFTT",
"BlobHessian",
diff --git a/kornia/feature/nms.py b/kornia/feature/nms.py
index cbabfe7dc..4043bede4 100644
--- a/kornia/feature/nms.py
+++ b/kornia/feature/nms.py
@@ -7,7 +7,6 @@ import torch.nn as nn
class NonMaximaSuppression2d(nn.Module):
r"""Applies non maxima suppression to filter.
"""
-
def __init__(self, kernel_size: Tuple[int, int]):
super(NonMaximaSuppression2d, self).__init__()
self.kernel_size: Tuple[int, int] = kernel_size
@@ -28,26 +27,61 @@ class NonMaximaSuppression2d(nn.Module):
ky, kx = kernel_size # we assume a cubic kernel
return (pad(ky), pad(kx))
- def forward(self, x: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
assert len(x.shape) == 4, x.shape
# find local maximum values
- x_max: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]] = \
- self.max_pool2d(x)
+ if mask_only:
+ return x == self.max_pool2d(x)
+ return x * (x == self.max_pool2d(x)).to(x.dtype)
+
+
+class NonMaximaSuppression3d(nn.Module):
+ r"""Applies non maxima suppression to filter.
+ """
+ def __init__(self, kernel_size: Tuple[int, int, int]):
+ super(NonMaximaSuppression3d, self).__init__()
+ self.kernel_size: Tuple[int, int, int] = kernel_size
+ self.padding: Tuple[int,
+ int,
+ int] = self._compute_zero_padding3d(kernel_size)
+ self.max_pool3d = nn.MaxPool3d(kernel_size, stride=1,
+ padding=self.padding)
+
+ @staticmethod
+ def _compute_zero_padding3d(
+ kernel_size: Tuple[int, int, int]) -> Tuple[int, int, int]:
+ assert isinstance(kernel_size, tuple), type(kernel_size)
+ assert len(kernel_size) == 3, kernel_size
- # create mask for maximums in the original map
- x_mask: torch.Tensor = torch.where(
- x == x_max, torch.ones_like(x), torch.zeros_like(x))
+ def pad(x):
+ return (x - 1) // 2 # zero padding function
- return x * x_mask # return original masked by local max
+ kd, ky, kx = kernel_size # we assume a cubic kernel
+ return pad(kd), pad(ky), pad(kx)
+ def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
+ assert len(x.shape) == 5, x.shape
+ # find local maximum values
+ if mask_only:
+ return x == self.max_pool3d(x)
+ return x * (x == self.max_pool3d(x)).to(x.dtype)
# functiona api
-def non_maxima_suppression2d(
- input: torch.Tensor, kernel_size: Tuple[int, int]) -> torch.Tensor:
+def nms2d(
+ input: torch.Tensor, kernel_size: Tuple[int, int], mask_only: bool = False) -> torch.Tensor:
r"""Applies non maxima suppression to filter.
See :class:`~kornia.feature.NonMaximaSuppression2d` for details.
"""
- return NonMaximaSuppression2d(kernel_size)(input)
+ return NonMaximaSuppression2d(kernel_size)(input, mask_only)
+
+
+def nms3d(
+ input: torch.Tensor, kernel_size: Tuple[int, int, int], mask_only: bool = False) -> torch.Tensor:
+ r"""Applies non maxima suppression to filter.
+
+ See :class:`~kornia.feature.NonMaximaSuppression3d` for details.
+ """
+ return NonMaximaSuppression3d(kernel_size)(input, mask_only)
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index e28577c63..4ddbb4fe8 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -83,7 +83,7 @@ def harris_response(input: torch.Tensor,
# compute the structure tensor M elements
def g(x):
- return gaussian_blur2d(x, (3, 3), (1., 1.))
+ return gaussian_blur2d(x, (7, 7), (1., 1.))
dx2: torch.Tensor = g(dx ** 2)
dy2: torch.Tensor = g(dy ** 2)
@@ -91,7 +91,7 @@ def harris_response(input: torch.Tensor,
det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
trace_m: torch.Tensor = dx2 + dy2
# compute the response map
- scores: torch.Tensor = torch.relu(det_m - k * (trace_m ** 2))
+ scores: torch.Tensor = det_m - k * (trace_m ** 2)
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
return scores
@@ -163,7 +163,7 @@ def gftt_response(input: torch.Tensor,
# compute the structure tensor M elements
def g(x):
- return gaussian_blur2d(x, (3, 3), (1., 1.))
+ return gaussian_blur2d(x, (7, 7), (1., 1.))
dx2: torch.Tensor = g(dx ** 2)
dy2: torch.Tensor = g(dy ** 2)
@@ -177,7 +177,7 @@ def gftt_response(input: torch.Tensor,
scores: torch.Tensor = torch.min(e1, e2)
if sigmas is not None:
- scores = scores * sigmas.pow(2).view(-1, 1, 1, 1)
+ scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
return scores
@@ -253,7 +253,7 @@ def hessian_response(input: torch.Tensor,
dxy: torch.Tensor = gradients[:, :, 1]
dyy: torch.Tensor = gradients[:, :, 2]
- scores: torch.Tensor = torch.abs(dxx * dyy - dxy ** 2)
+ scores: torch.Tensor = dxx * dyy - dxy ** 2
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
return scores
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 6473f7aab..8717ae494 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -44,10 +44,10 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> tor
scale_grid = torch.cat([scale_coords_index, dummy_x], dim=3)
# Finally, interpolate the scale value
- scale_val = F.grid_sample(sigmas[0].view(1, 1, 1, -1).expand(scale_grid.size(0), 1, 1, L), scale_grid)
+ scale_val = F.grid_sample(sigmas[0].log2().view(1, 1, 1, -1).expand(scale_grid.size(0), 1, 1, L), scale_grid)
# Replace the scale_x_y
- out = torch.cat([scale_val.view(B, N, 1), max_coords[:, :, 1:]], dim=2)
+ out = torch.cat([torch.pow(2.0, scale_val).view(B, N, 1), max_coords[:, :, 1:]], dim=2)
return out
@@ -73,6 +73,8 @@ class ScaleSpaceDetector(nn.Module):
which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
aff_module: (nn.Module) for local feature affine shape estimation. Default is :class:`~kornia.feature.PassLAF`,
which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
+ minima_are_also_good: (bool) if True, then both response function minima and maxima are detected
+ Useful for symmetric responce functions like DoG or Hessian. Default is False
"""
def __init__(self,
@@ -86,7 +88,8 @@ class ScaleSpaceDetector(nn.Module):
normalized_coordinates=False,
output_value=True),
ori_module: nn.Module = PassLAF(),
- aff_module: nn.Module = PassLAF()):
+ aff_module: nn.Module = PassLAF(),
+ minima_are_also_good: bool = False):
super(ScaleSpaceDetector, self).__init__()
self.mr_size = mr_size
self.num_features = num_features
@@ -95,6 +98,7 @@ class ScaleSpaceDetector(nn.Module):
self.nms = nms_module
self.ori = ori_module
self.aff = aff_module
+ self.minima_are_also_good = minima_are_also_good
return
def __repr__(self):
@@ -108,6 +112,8 @@ class ScaleSpaceDetector(nn.Module):
'aff=' + self.aff.__repr__() + ')'
def detect(self, img: torch.Tensor, num_feats: int) -> Tuple[torch.Tensor, torch.Tensor]:
+ dev: torch.device = img.device
+ dtype: torch.dtype = img.dtype
sp, sigmas, pix_dists = self.scale_pyr(img)
all_responses = []
all_lafs = []
@@ -123,9 +129,14 @@ class ScaleSpaceDetector(nn.Module):
# Differentiable nms
coord_max, response_max = self.nms(oct_resp)
+ if self.minima_are_also_good:
+ coord_min, response_min = self.nms(-oct_resp)
+ take_min_mask = (response_min > response_max).to(response_max.dtype)
+ response_max = response_min * take_min_mask + (1 - take_min_mask) * response_max
+ coord_max = coord_min * take_min_mask.unsqueeze(1) + (1 - take_min_mask.unsqueeze(1)) * coord_max
# Now, lets crop out some small responses
- responses_flatten = response_max.view(response_max.size(0), -1) # [B * N, 3]
+ responses_flatten = response_max.view(response_max.size(0), -1) # [B, N]
max_coords_flatten = coord_max.view(response_max.size(0), 3, -1).permute(0, 2, 1) # [B, N, 3]
if responses_flatten.size(1) > num_feats:
@@ -140,13 +151,13 @@ class ScaleSpaceDetector(nn.Module):
max_coords_best = _scale_index_to_scale(max_coords_best, sigmas_oct)
# Create local affine frames (LAFs)
- rotmat = angle_to_rotation_matrix(torch.zeros(B, N).to(max_coords_best.device).to(max_coords_best.dtype))
+ rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
current_lafs = torch.cat([self.mr_size * max_coords_best[:, :, 0].view(B, N, 1, 1) * rotmat,
max_coords_best[:, :, 1:3].view(B, N, 2, 1)], dim=3)
# Zero response lafs, which touch the boundary
good_mask = laf_is_inside_image(current_lafs, octave[:, 0])
- resp_flat_best = resp_flat_best * good_mask.to(resp_flat_best.device).to(resp_flat_best.dtype)
+ resp_flat_best = resp_flat_best * good_mask.to(dev, dtype)
# Normalize LAFs
current_lafs = normalize_laf(current_lafs, octave[:, 0]) # We don`t need # of scale levels, only shape
diff --git a/kornia/filters/__init__.py b/kornia/filters/__init__.py
index e56e5a812..84168504b 100644
--- a/kornia/filters/__init__.py
+++ b/kornia/filters/__init__.py
@@ -1,6 +1,6 @@
from .gaussian import GaussianBlur2d, gaussian_blur2d
from .laplacian import Laplacian, laplacian
-from .sobel import SpatialGradient, spatial_gradient
+from .sobel import SpatialGradient, spatial_gradient, SpatialGradient3d, spatial_gradient3d
from .sobel import Sobel, sobel
from .blur import BoxBlur, box_blur
from .median import MedianBlur, median_blur
@@ -18,7 +18,8 @@ from .kernels import (
get_gaussian_kernel2d,
get_laplacian_kernel1d,
get_laplacian_kernel2d,
- get_motion_kernel2d
+ get_motion_kernel2d,
+ get_spatial_gradient_kernel3d,
)
__all__ = [
@@ -27,6 +28,7 @@ __all__ = [
"get_laplacian_kernel1d",
"get_laplacian_kernel2d",
"get_spatial_gradient_kernel2d",
+ "get_spatial_gradient_kernel3d",
"get_sobel_kernel2d",
"get_diff_kernel2d",
"gaussian_blur2d",
@@ -44,5 +46,7 @@ __all__ = [
"Sobel",
"BoxBlur",
"MedianBlur",
- "MotionBlur"
+ "MotionBlur",
+ "SpatialGradient3d",
+ "spatial_gradient3d",
]
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index d37d93cde..56dd828d8 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -95,6 +95,126 @@ def get_diff_kernel_3x3() -> torch.Tensor:
])
+def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
+ """Utility function that returns a first order derivative kernel of 3x3x3"""
+ kernel: torch.Tensor = torch.tensor([[[[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [-0.5, 0.0, 0.5],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ [[[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, -0.5, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.5, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ [[[0.0, 0.0, 0.0],
+ [0.0, -0.5, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.5, 0.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ ], device=device, dtype=dtype)
+ return kernel.unsqueeze(1)
+
+
+def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:
+ """Utility function that returns a first order derivative kernel of 3x3x3"""
+ kernel: torch.Tensor = torch.tensor([[[[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [1.0, -2.0, 1.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ [[[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 1.0, 0.0],
+ [0.0, -2.0, 0.0],
+ [0.0, 1.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ [[[0.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, -2.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ [[[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[1.0, 0.0, -1.0],
+ [0.0, 0.0, 0.0],
+ [-1.0, 0.0, 1.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ [[[0.0, 1.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, -1.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, -1.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 1.0, 0.0]],
+ ],
+ [[[0.0, 0.0, 0.0],
+ [1.0, 0.0, -1.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]],
+
+ [[0.0, 0.0, 0.0],
+ [-1.0, 0.0, 1.0],
+ [0.0, 0.0, 0.0]],
+ ],
+ ], device=device, dtype=dtype)
+ return kernel.unsqueeze(1)
+
+
def get_sobel_kernel2d() -> torch.Tensor:
kernel_x: torch.Tensor = get_sobel_kernel_3x3()
kernel_y: torch.Tensor = kernel_x.transpose(0, 1)
@@ -151,6 +271,26 @@ def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:
return kernel
+def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cpu'), dtype=torch.float) -> torch.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")
+ elif mode == 'diff' and order == 1:
+ kernel = get_diff_kernel3d(device, dtype)
+ elif mode == 'diff' and order == 2:
+ kernel = get_diff_kernel3d_2nd_order(device, dtype)
+ else:
+ raise NotImplementedError("")
+ return kernel
+
+
def get_gaussian_kernel1d(kernel_size: int,
sigma: float,
force_even: bool = False) -> torch.Tensor:
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index f5ab2991a..71b64eb56 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -2,7 +2,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.filters.kernels import get_spatial_gradient_kernel2d
+from kornia.filters.kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d
from kornia.filters.kernels import normalize_kernel2d
@@ -50,7 +50,7 @@ class SpatialGradient(nn.Module):
.format(input.shape))
# prepare kernel
b, c, h, w = input.shape
- tmp_kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype)
+ tmp_kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype).detach()
kernel: torch.Tensor = tmp_kernel.unsqueeze(1).unsqueeze(1)
# convolve input tensor with sobel kernel
@@ -65,6 +65,61 @@ class SpatialGradient(nn.Module):
return F.conv3d(padded_inp, kernel_flip, padding=0).view(b, c, out_channels, h, w)
+class SpatialGradient3d(nn.Module):
+ r"""Computes the first and second order volume derivative in x, y and d using a diff
+ operator.
+
+ Return:
+ torch.Tensor: the spatial gradients of the input feature map.
+
+ Shape:
+ - Input: :math:`(B, C, D, H, W)`. D, H, W are spatial dimensions, gradient is calculated w.r.t to them.
+ - Output: :math:`(B, C, 3, D, H, W)` or :math:`(B, C, 6, D, H, W)`
+
+ Examples:
+ >>> input = torch.rand(1, 3, 4, 4)
+ >>> output = kornia.filters.SpatialGradient()(input) # 1x3x2x4x4
+ """
+
+ def __init__(self,
+ mode: str = 'diff',
+ order: int = 1) -> None:
+ super(SpatialGradient3d, self).__init__()
+ self.order: int = order
+ self.mode: str = mode
+ self.kernel = get_spatial_gradient_kernel3d(mode, order)
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ + '('\
+ 'order=' + str(self.order) + ', ' + \
+ 'mode=' + self.mode + ')'
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 5:
+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
+ .format(input.shape))
+ # prepare kernel
+ b, c, d, h, w = input.shape
+ tmp_kernel: torch.Tensor = self.kernel.to(input.device).to(input.dtype).detach()
+ kernel: torch.Tensor = tmp_kernel.repeat(c, 1, 1, 1, 1)
+
+ # convolve input tensor with grad kernel
+ kernel_flip: torch.Tensor = kernel.flip(-3)
+ # Pad with "replicate for spatial dims, but with zeros for channel
+ spatial_pad = [self.kernel.size(2) // 2,
+ self.kernel.size(2) // 2,
+ self.kernel.size(3) // 2,
+ self.kernel.size(3) // 2,
+ self.kernel.size(4) // 2,
+ self.kernel.size(4) // 2]
+ out_ch: int = 6 if self.order == 2 else 3
+ return F.conv3d(F.pad(input, spatial_pad, 'replicate'), kernel, padding=0, groups=c).view(b, c, out_ch, d, h, w)
+
+
class Sobel(nn.Module):
r"""Computes the Sobel operator and returns the magnitude per channel.
@@ -127,6 +182,17 @@ def spatial_gradient(input: torch.Tensor,
return SpatialGradient(mode, order, normalized)(input)
+def spatial_gradient3d(input: torch.Tensor,
+ mode: str = 'diff',
+ order: int = 1) -> torch.Tensor:
+ r"""Computes the first or second order image derivative in both x and y and y using a diff
+ operator.
+
+ See :class:`~kornia.filters.SpatialGradient3d` for details.
+ """
+ return SpatialGradient3d(mode, order)(input)
+
+
def sobel(input: torch.Tensor, normalized: bool = True) -> torch.Tensor:
r"""Computes the Sobel operator and returns the magnitude per channel.
diff --git a/kornia/geometry/spatial_soft_argmax.py b/kornia/geometry/spatial_soft_argmax.py
index 571a835a4..c2e9de9bb 100644
--- a/kornia/geometry/spatial_soft_argmax.py
+++ b/kornia/geometry/spatial_soft_argmax.py
@@ -2,6 +2,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
+import kornia
from kornia.geometry import dsnt
from kornia.utils import create_meshgrid, create_meshgrid3d
from kornia.geometry import normalize_pixel_coordinates, normalize_pixel_coordinates3d
@@ -179,7 +180,8 @@ class ConvSoftArgmax3d(nn.Module):
temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
normalized_coordinates: bool = False,
eps: float = 1e-8,
- output_value: bool = True) -> None:
+ output_value: bool = True,
+ strict_maxima_bonus: float = 0.0) -> None:
super(ConvSoftArgmax3d, self).__init__()
self.kernel_size = kernel_size
self.stride = stride
@@ -188,6 +190,8 @@ class ConvSoftArgmax3d(nn.Module):
self.normalized_coordinates = normalized_coordinates
self.eps = eps
self.output_value = output_value
+ self.strict_maxima_bonus = strict_maxima_bonus
+ return
def __repr__(self) -> str:
return self.__class__.__name__ +\
@@ -197,6 +201,7 @@ class ConvSoftArgmax3d(nn.Module):
', ' + 'temperature=' + str(self.temperature) +\
', ' + 'normalized_coordinates=' + str(self.normalized_coordinates) +\
', ' + 'eps=' + str(self.eps) +\
+ ', ' + 'strict_maxima_bonus=' + str(self.strict_maxima_bonus) +\
', ' + 'output_value=' + str(self.output_value) + ')'
def forward(self, x: torch.Tensor): # type: ignore
@@ -207,7 +212,8 @@ class ConvSoftArgmax3d(nn.Module):
self.temperature,
self.normalized_coordinates,
self.eps,
- self.output_value)
+ self.output_value,
+ self.strict_maxima_bonus)
def conv_soft_argmax2d(input: torch.Tensor,
@@ -340,8 +346,8 @@ def conv_soft_argmax3d(input: torch.Tensor,
temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
normalized_coordinates: bool = False,
eps: float = 1e-8,
- output_value: bool = True) -> Union[torch.Tensor,
- Tuple[torch.Tensor, torch.Tensor]]:
+ output_value: bool = True,
+ strict_maxima_bonus: float = 0.0) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
r"""Function that computes the convolutional spatial Soft-Argmax 3D over the windows
of a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap values
themselves.
@@ -364,7 +370,8 @@ def conv_soft_argmax3d(input: torch.Tensor,
it will return the coordinates in the range of the input shape. Default is False.
eps (float): small value to avoid zero division. Default is 1e-8.
output_value (bool): if True, val is outputed, if False, only ij
-
+ strict_maxima_bonus (float): pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.
+ This is needed for mimic behavior of strict NMS in classic local features
Shape:
- Input: :math:`(N, C, D_{in}, H_{in}, W_{in})`
- Output: :math:`(N, C, 3, D_{out}, H_{out}, W_{out})`, :math:`(N, C, D_{out}, H_{out}, W_{out})`, where
@@ -422,16 +429,6 @@ def conv_soft_argmax3d(input: torch.Tensor,
stride=stride,
padding=padding) + eps
- x_softmaxpool = pool_coef * F.avg_pool3d(x_exp.view_as(input) * input,
- kernel_size,
- stride=stride,
- padding=padding) / den
- x_softmaxpool = x_softmaxpool.view(b,
- c,
- x_softmaxpool.size(2),
- x_softmaxpool.size(3),
- x_softmaxpool.size(4))
-
# We need to output also coordinates
# Pooled window center coordinates
grid_global: torch.Tensor = create_meshgrid3d(
@@ -462,9 +459,25 @@ def conv_soft_argmax3d(input: torch.Tensor,
# Back B*C -> (b, c)
coords_max = coords_max.view(b, c, 3, coords_max.size(2), coords_max.size(3), coords_max.size(4))
- if output_value:
- return coords_max, x_softmaxpool
- return coords_max
+ if not output_value:
+ return coords_max
+ x_softmaxpool = pool_coef * F.avg_pool3d(x_exp.view(input.size()) * input,
+ kernel_size,
+ stride=stride,
+ padding=padding) / den
+ if strict_maxima_bonus > 0:
+ in_levels: int = input.size(2)
+ out_levels: int = x_softmaxpool.size(2)
+ skip_levels: int = (in_levels - out_levels) // 2
+ strict_maxima: torch.Tensor = F.avg_pool3d(kornia.feature.nms3d(input, kernel_size), 1, stride, 0)
+ strict_maxima = strict_maxima[:, :, skip_levels:out_levels - skip_levels]
+ x_softmaxpool *= 1.0 + strict_maxima_bonus * strict_maxima
+ x_softmaxpool = x_softmaxpool.view(b,
+ c,
+ x_softmaxpool.size(2),
+ x_softmaxpool.size(3),
+ x_softmaxpool.size(4))
+ return coords_max, x_softmaxpool
def spatial_soft_argmax2d(
@@ -528,3 +541,95 @@ class SpatialSoftArgmax2d(nn.Module):
def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
return spatial_soft_argmax2d(input, self.temperature,
self.normalized_coordinates, self.eps)
+
+
+def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 1.0):
+ r"""Function that computes the single iteration of quadratic interpolation of of the extremum (max or min) location
+ and value per each 3x3x3 window which contains strict extremum, similar to one done is SIFT
+
+ Args:
+ strict_maxima_bonus (float): pixels, which are strict maxima will score (1 + strict_maxima_bonus) * value.
+ This is needed for mimic behavior of strict NMS in classic local features
+ Shape:
+ - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})`
+ - Output: :math:`(N, C, 3, D_{out}, H_{out}, W_{out})`, :math:`(N, C, D_{out}, H_{out}, W_{out})`, where
+
+ .. math::
+ D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -
+ (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
+
+ .. math::
+ H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] -
+ (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
+
+ .. math::
+ W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] -
+ (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor
+
+ Examples:
+ >>> input = torch.randn(20, 16, 3, 50, 32)
+ >>> nms_coords, nms_val = conv_quad_interp3d(input, 1.0)
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 5:
+ raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
+ .format(input.shape))
+ B, CH, D, H, W = input.shape
+ dev: torch.device = input.device
+ grid_global: torch.Tensor = create_meshgrid3d(D, H, W, False,
+ device=input.device).permute(0, 4, 1, 2, 3)
+ grid_global = grid_global.to(input.dtype)
+
+ # to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient
+ # and A is Hessian matrix
+ b: torch.Tensor = kornia.filters.spatial_gradient3d(input, order=1, mode='diff') #
+ b = b.permute(0, 1, 3, 4, 5, 2).reshape(-1, 3, 1)
+ A: torch.Tensor = kornia.filters.spatial_gradient3d(input, order=2, mode='diff')
+ A = A.permute(0, 1, 3, 4, 5, 2).reshape(-1, 6)
+ dxx = A[..., 0]
+ dyy = A[..., 1]
+ dss = A[..., 2]
+ dxy = A[..., 3]
+ dys = A[..., 4]
+ dxs = A[..., 5]
+ # for the Hessian
+ Hes = torch.stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss]).view(-1, 3, 3)
+
+ nms_mask: torch.Tensor = kornia.feature.nms3d(input, (3, 3, 3), True)
+ x_solved: torch.Tensor = torch.zeros_like(b)
+ x_solved_masked, _ = torch.solve(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])
+ x_solved.masked_scatter_(nms_mask.view(-1, 1, 1), x_solved_masked)
+ dx: torch.Tensor = -x_solved
+
+ # Ignore ones, which are far from window,
+ dx[(dx.abs().max(dim=1, keepdim=True)[0] > 0.7).view(-1), :, :] = 0
+
+ dy: torch.Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
+ y_max = input + dy.view(B, CH, D, H, W)
+ if strict_maxima_bonus > 0:
+ y_max *= (1.0 + strict_maxima_bonus * nms_mask.to(input.dtype))
+
+ dx_res: torch.Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)
+ coords_max: torch.Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)
+ coords_max = coords_max + dx_res
+ return coords_max, y_max
+
+
+class ConvQuadInterp3d(nn.Module):
+ r"""Module that calculates soft argmax 3d per window
+ See :func:`~kornia.geometry.conv_quad_interp3d` for details.
+ """
+
+ def __init__(self,
+ strict_maxima_bonus: float = 1.0) -> None:
+ super(ConvQuadInterp3d, self).__init__()
+ self.strict_maxima_bonus = strict_maxima_bonus
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ + '(' + 'strict_maxima_bonus=' + str(self.strict_maxima_bonus) + ')'
+
+ def forward(self, x: torch.Tensor): # type: ignore
+ return conv_quad_interp3d(x, self.strict_maxima_bonus)
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index be838c914..7f4641088 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -64,8 +64,8 @@ class PyrDown(nn.Module):
# blur image
x_blur: torch.Tensor = filter2D(input, self.kernel, self.border_type)
- # reject even rows and columns.
- out: torch.Tensor = F.avg_pool2d(x_blur, 2, 2)
+ # downsample.
+ out: torch.Tensor = F.interpolate(x_blur, scale_factor=0.5, mode='bilinear', align_corners=False)
return out
@@ -161,7 +161,7 @@ class ScalePyramid(nn.Module):
'double_image=' + str(self.double_image) + ')'
def get_kernel_size(self, sigma: float):
- ksize = int(2.0 * 3.0 * sigma + 1.0)
+ ksize = int(2.0 * 4.0 * sigma + 1.0)
if ksize % 2 == 0:
ksize += 1
return ksize
@@ -174,6 +174,7 @@ class ScalePyramid(nn.Module):
if self.double_image:
x = F.interpolate(x, scale_factor=2.0, mode='bilinear', align_corners=False)
pixel_distance = 0.5
+ cur_sigma *= 2.0
if self.init_sigma > cur_sigma:
sigma = math.sqrt(self.init_sigma**2 - cur_sigma**2)
cur_sigma = self.init_sigma
@@ -198,8 +199,9 @@ class ScalePyramid(nn.Module):
pyr[-1].append(cur_level.unsqueeze(1))
sigmas[-1][:, level_idx] = cur_sigma
pixel_dists[-1][:, level_idx] = pixel_distance
- nextOctaveFirstLevel = F.avg_pool2d(
- cur_level, kernel_size=2, stride=2, padding=0)
+ nextOctaveFirstLevel = F.interpolate(pyr[-1][-1].squeeze(1), scale_factor=0.5,
+ mode='bilinear',
+ align_corners=False)
pixel_distance *= 2.0
cur_sigma = self.init_sigma
if (min(nextOctaveFirstLevel.size(2),
diff --git a/test/feature/test_nms.py b/test/feature/test_nms.py
new file mode 100644
index 000000000..9c1093ff7
--- /dev/null
+++ b/test/feature/test_nms.py
@@ -0,0 +1,104 @@
+import pytest
+
+import kornia as kornia
+import kornia.testing as utils # test utils
+from test.common import device
+
+import torch
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+
+class TestNMS2d:
+ def test_shape(self, device):
+ inp = torch.ones(1, 3, 4, 4, device=device)
+ nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)
+ assert nms(inp).shape == inp.shape
+
+ def test_shape_batch(self, device):
+ inp = torch.ones(4, 3, 4, 4, device=device)
+ nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)
+ assert nms(inp).shape == inp.shape
+
+ def test_nms(self, device):
+ inp = torch.tensor([[[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0.1, 1., 0., 1., 1., 0.],
+ [0., 0.7, 1.1, 0., 1., 1., 0.],
+ [0., 0.8, 1., 0., 1., 1., 0.],
+ ]]], device=device).float()
+
+ expected = torch.tensor([[[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0, 0, 0., 1, 1., 0.],
+ [0., 0, 1.1, 0., 1., 1., 0.],
+ [0., 0, 0, 0., 1., 1., 0.],
+ ]]], device=device).float()
+ nms = kornia.feature.NonMaximaSuppression2d((3, 3)).to(device)
+ scores = nms(inp)
+ assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
+
+ def test_gradcheck(self, device):
+ k = 0.04
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.feature.nms2d, (img, (3, 3)),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestNMS3d:
+ def test_shape(self, device):
+ inp = torch.ones(1, 1, 3, 4, 4, device=device)
+ nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).to(device)
+ assert nms(inp).shape == inp.shape
+
+ def test_shape_batch(self, device):
+ inp = torch.ones(4, 1, 3, 4, 4, device=device)
+ nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).to(device)
+ assert nms(inp).shape == inp.shape
+
+ def test_nms(self, device):
+ inp = torch.tensor([[[
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 2., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ ]]]).to(device)
+
+ expected = torch.tensor([[[[[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 2., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]]]]])
+ nms = kornia.feature.NonMaximaSuppression3d((3, 3, 3)).to(device)
+ scores = nms(inp)
+ assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
+
+ def test_gradcheck(self, device):
+ batch_size, channels, depth, height, width = 1, 1, 4, 5, 4
+ img = torch.rand(batch_size, channels, depth, height, width, device=device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.feature.nms3d, (img, (3, 3, 3)),
+ raise_exception=True, nondet_tol=1e-4)
diff --git a/test/feature/test_responces_local_features.py b/test/feature/test_responces_local_features.py
index 537aacf80..ea6825097 100644
--- a/test/feature/test_responces_local_features.py
+++ b/test/feature/test_responces_local_features.py
@@ -32,13 +32,13 @@ class TestCornerHarris:
]]], device=device).float()
expected = torch.tensor([[[
- [0.001233, 0.003920, 0.001985, 0.000000, 0.001985, 0.003920, 0.001233],
- [0.003920, 0.006507, 0.003976, 0.000000, 0.003976, 0.006507, 0.003920],
- [0.001985, 0.003976, 0.002943, 0.000000, 0.002943, 0.003976, 0.001985],
- [0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],
- [0.001985, 0.003976, 0.002943, 0.000000, 0.002943, 0.003976, 0.001985],
- [0.003920, 0.006507, 0.003976, 0.000000, 0.003976, 0.006507, 0.003920],
- [0.001233, 0.003920, 0.001985, 0.000000, 0.001985, 0.003920, 0.001233]]]],
+ [0.0042, 0.0054, 0.0035, 0.0006, 0.0035, 0.0054, 0.0042],
+ [0.0054, 0.0068, 0.0046, 0.0014, 0.0046, 0.0068, 0.0054],
+ [0.0035, 0.0046, 0.0034, 0.0014, 0.0034, 0.0046, 0.0035],
+ [0.0006, 0.0014, 0.0014, 0.0006, 0.0014, 0.0014, 0.0006],
+ [0.0035, 0.0046, 0.0034, 0.0014, 0.0034, 0.0046, 0.0035],
+ [0.0054, 0.0068, 0.0046, 0.0014, 0.0046, 0.0068, 0.0054],
+ [0.0042, 0.0054, 0.0035, 0.0006, 0.0035, 0.0054, 0.0042]]]],
device=device).float()
harris = kornia.feature.CornerHarris(k=0.04).to(device)
scores = harris(inp)
@@ -63,22 +63,22 @@ class TestCornerHarris:
[0., 0., 0., 0., 0., 0., 0.],
]], device=device).repeat(2, 1, 1, 1)
expected = torch.tensor([[
- [0.001233, 0.003920, 0.001985, 0.000000, 0.001985, 0.003920, 0.001233],
- [0.003920, 0.006507, 0.003976, 0.000000, 0.003976, 0.006507, 0.003920],
- [0.001985, 0.003976, 0.002943, 0.000000, 0.002943, 0.003976, 0.001985],
- [0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],
- [0.001985, 0.003976, 0.002943, 0.000000, 0.002943, 0.003976, 0.001985],
- [0.003920, 0.006507, 0.003976, 0.000000, 0.003976, 0.006507, 0.003920],
- [0.001233, 0.003920, 0.001985, 0.000000, 0.001985, 0.003920, 0.001233]
+ [0.0415, 0.0541, 0.0346, 0.0058, 0.0346, 0.0541, 0.0415],
+ [0.0541, 0.0678, 0.0457, 0.0145, 0.0457, 0.0678, 0.0541],
+ [0.0346, 0.0457, 0.0335, 0.0139, 0.0335, 0.0457, 0.0346],
+ [0.0058, 0.0145, 0.0139, 0.0064, 0.0139, 0.0145, 0.0058],
+ [0.0346, 0.0457, 0.0335, 0.0139, 0.0335, 0.0457, 0.0346],
+ [0.0541, 0.0678, 0.0457, 0.0145, 0.0457, 0.0678, 0.0541],
+ [0.0415, 0.0541, 0.0346, 0.0058, 0.0346, 0.0541, 0.0415]
], [
- [0.001233, 0.003920, 0.001985, 0.001985, 0.003920, 0.000589, 0.000000],
- [0.003920, 0.006507, 0.003976, 0.003976, 0.006507, 0.001526, 0.000008],
- [0.001985, 0.003976, 0.002943, 0.002943, 0.003976, 0.000542, 0.000000],
- [0.001985, 0.003976, 0.002943, 0.002943, 0.003976, 0.000542, 0.000000],
- [0.003920, 0.006507, 0.003976, 0.003976, 0.006507, 0.001526, 0.000008],
- [0.000589, 0.001526, 0.000542, 0.000542, 0.001526, 0.000277, 0.000000],
- [0.000000, 0.000008, 0.000000, 0.000000, 0.000008, 0.000000, 0.000000]
- ]], device=device).repeat(2, 1, 1, 1)
+ [0.0415, 0.0547, 0.0447, 0.0440, 0.0490, 0.0182, 0.0053],
+ [0.0547, 0.0688, 0.0557, 0.0549, 0.0610, 0.0229, 0.0066],
+ [0.0447, 0.0557, 0.0444, 0.0437, 0.0489, 0.0168, 0.0035],
+ [0.0440, 0.0549, 0.0437, 0.0431, 0.0481, 0.0166, 0.0034],
+ [0.0490, 0.0610, 0.0489, 0.0481, 0.0541, 0.0205, 0.0060],
+ [0.0182, 0.0229, 0.0168, 0.0166, 0.0205, 0.0081, 0.0025],
+ [0.0053, 0.0066, 0.0035, 0.0034, 0.0060, 0.0025, 0.0008]
+ ]], device=device).repeat(2, 1, 1, 1) / 10.
scores = kornia.feature.harris_response(inp, k=0.04)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
@@ -125,13 +125,13 @@ class TestCornerGFTT:
]]], device=device).float()
expected = torch.tensor([[[
- [0.01548, 0.03340, 0.01944, 0.00000, 0.01944, 0.03340, 0.01548],
- [0.03340, 0.05748, 0.03388, 0.00000, 0.03388, 0.05748, 0.03340],
- [0.01944, 0.03388, 0.04974, 0.00000, 0.04974, 0.03388, 0.01944],
- [0.00000, 0.00000, 0.00000, 0.00000, 0.00000, 0.00000, 0.00000],
- [0.01944, 0.03388, 0.04974, 0.00000, 0.04974, 0.03388, 0.01944],
- [0.03340, 0.05748, 0.03388, 0.00000, 0.03388, 0.05748, 0.03340],
- [0.01548, 0.03340, 0.01944, 0.00000, 0.01944, 0.03340, 0.01548]]]], device=device).float()
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0121, 0.0168, 0.0245, 0.0276, 0.0245, 0.0168, 0.0121],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379]]]], device=device).float()
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
@@ -155,21 +155,21 @@ class TestCornerGFTT:
[0., 0., 0., 0., 0., 0., 0.],
]], device=device).repeat(2, 1, 1, 1)
expected = torch.tensor([[
- [0.01548, 0.03340, 0.01944, 0.00000, 0.01944, 0.03340, 0.01548],
- [0.03340, 0.05748, 0.03388, 0.00000, 0.03388, 0.05748, 0.03340],
- [0.01944, 0.03388, 0.04974, 0.00000, 0.04974, 0.03388, 0.01944],
- [0.00000, 0.00000, 0.00000, 0.00000, 0.00000, 0.00000, 0.00000],
- [0.01944, 0.03388, 0.04974, 0.00000, 0.04974, 0.03388, 0.01944],
- [0.03340, 0.05748, 0.03388, 0.00000, 0.03388, 0.05748, 0.03340],
- [0.01548, 0.03340, 0.01944, 0.00000, 0.01944, 0.03340, 0.01548]
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0121, 0.0168, 0.0245, 0.0276, 0.0245, 0.0168, 0.0121],
+ [0.0283, 0.0402, 0.0545, 0.0245, 0.0545, 0.0402, 0.0283],
+ [0.0456, 0.0598, 0.0402, 0.0168, 0.0402, 0.0598, 0.0456],
+ [0.0379, 0.0456, 0.0283, 0.0121, 0.0283, 0.0456, 0.0379]
], [
- [0.01548, 0.03340, 0.01944, 0.01944, 0.03340, 0.01090, 0.00136],
- [0.03340, 0.05748, 0.03388, 0.03388, 0.05748, 0.01981, 0.00348],
- [0.01944, 0.03388, 0.04974, 0.04974, 0.03388, 0.01070, 0.00193],
- [0.01944, 0.03388, 0.04974, 0.04974, 0.03388, 0.01070, 0.00193],
- [0.03340, 0.05748, 0.03388, 0.03388, 0.05748, 0.01981, 0.00348],
- [0.01090, 0.01981, 0.01070, 0.01070, 0.01981, 0.00774, 0.00121],
- [0.00136, 0.00348, 0.00193, 0.00193, 0.00348, 0.00121, 0.00000]
+ [0.0379, 0.0462, 0.0349, 0.0345, 0.0443, 0.0248, 0.0112],
+ [0.0462, 0.0608, 0.0488, 0.0483, 0.0581, 0.0274, 0.0119],
+ [0.0349, 0.0488, 0.0669, 0.0664, 0.0460, 0.0191, 0.0084],
+ [0.0345, 0.0483, 0.0664, 0.0660, 0.0455, 0.0189, 0.0083],
+ [0.0443, 0.0581, 0.0460, 0.0455, 0.0555, 0.0262, 0.0114],
+ [0.0248, 0.0274, 0.0191, 0.0189, 0.0262, 0.0172, 0.0084],
+ [0.0112, 0.0119, 0.0084, 0.0083, 0.0114, 0.0084, 0.0046]
]], device=device).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
@@ -223,21 +223,21 @@ class TestBlobHessian:
[0., 0., 0., 0., 0., 0., 0.],
]], device=device).repeat(2, 1, 1, 1)
expected = torch.tensor([[
- [0.0564, 0.0759, 0.0342, 0.0759, 0.0564, 0.0057, 0.0000],
- [0.0759, 0.0330, 0.0752, 0.0330, 0.0759, 0.0096, 0.0000],
- [0.0342, 0.0752, 0.1914, 0.0752, 0.0342, 0.0068, 0.0000],
- [0.0759, 0.0330, 0.0752, 0.0330, 0.0759, 0.0096, 0.0000],
- [0.0564, 0.0759, 0.0342, 0.0759, 0.0564, 0.0057, 0.0000],
- [0.0057, 0.0096, 0.0068, 0.0096, 0.0057, 0.0005, 0.0000],
+ [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],
+ [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],
+ [-0.0342, 0.0752, 0.1914, 0.0752, -0.0342, -0.0068, 0.0000],
+ [-0.0759, -0.0330, 0.0752, -0.0330, -0.0759, -0.0096, 0.0000],
+ [-0.0564, -0.0759, -0.0342, -0.0759, -0.0564, -0.0057, 0.0000],
+ [-0.0057, -0.0096, -0.0068, -0.0096, -0.0057, -0.0005, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]
], [
- [0.0564, 0.0522, 0.0522, 0.0564, 0.0057, 0.0000, 0.0000],
- [0.0522, 0.0688, 0.0688, 0.0123, 0.0033, 0.0057, 0.0005],
- [0.0522, 0.0688, 0.0755, 0.1111, 0.0123, 0.0564, 0.0057],
- [0.0564, 0.0123, 0.1111, 0.0755, 0.0688, 0.0522, 0.0080],
- [0.0057, 0.0033, 0.0123, 0.0688, 0.0688, 0.0522, 0.0080],
- [0.0000, 0.0057, 0.0564, 0.0522, 0.0522, 0.0564, 0.0057],
- [0.0000, 0.0005, 0.0057, 0.0080, 0.0080, 0.0057, 0.0005]
+ [-0.0564, -0.0522, -0.0522, -0.0564, -0.0057, 0.0000, 0.0000],
+ [-0.0522, 0.0688, 0.0688, -0.0123, 0.0033, -0.0057, -0.0005],
+ [-0.0522, 0.0688, -0.0755, -0.1111, -0.0123, -0.0564, -0.0057],
+ [-0.0564, -0.0123, -0.1111, -0.0755, 0.0688, -0.0522, -0.0080],
+ [-0.0057, 0.0033, -0.0123, 0.0688, 0.0688, -0.0522, -0.0080],
+ [0.0000, -0.0057, -0.0564, -0.0522, -0.0522, -0.0564, -0.0057],
+ [0.0000, -0.0005, -0.0057, -0.0080, -0.0080, -0.0057, -0.0005]
]], device=device).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.BlobHessian().to(device)
scores = shi_tomasi(inp)
diff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.py
index dce5573ae..e7d33cfa4 100644
--- a/test/feature/test_scale_space_detector.py
+++ b/test/feature/test_scale_space_detector.py
@@ -1,4 +1,5 @@
import pytest
+import torch
import kornia.testing as utils # test utils
import kornia
from test.common import device
@@ -37,14 +38,14 @@ class TestScaleSpaceDetector:
resp_module=kornia.feature.BlobHessian(),
mr_size=3.0).to(device)
lafs, resps = det(inp)
- expected_laf = torch.tensor([[[[6.0548, 0.0000, 16.0], [0.0, 6.0548, 16.0]]]], device=device)
- expected_resp = torch.tensor([[0.0806]], device=device)
- assert_allclose(expected_laf, lafs)
- assert_allclose(expected_resp, resps)
+ expected_laf = torch.tensor([[[[6.0543, 0.0000, 16.0], [0.0, 6.0543, 16.0]]]], device=device)
+ expected_resp = torch.tensor([[0.0804]], device=device)
+ assert_allclose(expected_laf, lafs, rtol=0.0001, atol=1e-04)
+ assert_allclose(expected_resp, resps, rtol=0.0001, atol=1e-04)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 31, 21
patches = torch.rand(batch_size, channels, height, width, device=device)
patches = utils.tensor_to_gradcheck_var(patches) # to var
- assert gradcheck(ScaleSpaceDetector(2).to(device), (patches),
+ assert gradcheck(ScaleSpaceDetector(2).to(device), patches,
raise_exception=True, nondet_tol=1e-4)
diff --git a/test/filters/test_sobel.py b/test/filters/test_sobel.py
index a9170a374..a768e2e25 100644
--- a/test/filters/test_sobel.py
+++ b/test/filters/test_sobel.py
@@ -150,6 +150,103 @@ class TestSpatialGradient:
assert_allclose(actual, expected)
+class TestSpatialGradient3d:
+ def test_shape(self, device):
+ inp = torch.zeros(1, 2, 4, 5, 6).to(device)
+ sobel = kornia.filters.SpatialGradient3d()
+ assert sobel(inp).shape == (1, 2, 3, 4, 5, 6)
+
+ def test_shape_batch(self, device):
+ inp = torch.zeros(7, 2, 4, 5, 6).to(device)
+ sobel = kornia.filters.SpatialGradient3d()
+ assert sobel(inp).shape == (7, 2, 3, 4, 5, 6)
+
+ def test_edges(self, device):
+ inp = torch.tensor([[[
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 1., 1., 1., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ ]]]).to(device)
+
+ expected = torch.tensor([[[[[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
+ [0.5000, 0.5000, 0.0000, -0.5000, -0.5000],
+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.0000, -0.5000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],
+ [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
+ [[0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.5000, 0.5000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, -0.5000, -0.5000, -0.5000, 0.0000],
+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000]],
+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]],
+ [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.5000, 0.0000, 0.5000, 0.0000],
+ [0.0000, 0.0000, 0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, -0.5000, 0.0000, -0.5000, 0.0000],
+ [0.0000, 0.0000, -0.5000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]]]])
+
+ edges = kornia.filters.spatial_gradient3d(inp)
+ assert_allclose(edges, expected)
+
+ def test_gradcheck(self, device):
+ batch_size, channels, depth, height, width = 1, 2, 3, 5, 4
+ img = torch.rand(batch_size, channels, depth, height, width).to(device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.filters.spatial_gradient3d, (img,),
+ raise_exception=True)
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self, device):
+ @torch.jit.script
+ def op_script(input):
+ return kornia.filters.spatial_gradient(input)
+ img = torch.rand(2, 3, 4, 5).to(device)
+ actual = op_script(img)
+ expected = kornia.filters.spatial_gradient(img)
+ assert_allclose(actual, expected)
+
+
class TestSobel:
def test_shape(self, device):
inp = torch.zeros(1, 3, 4, 4).to(device)
diff --git a/test/geometry/test_spatial_softargmax.py b/test/geometry/test_spatial_softargmax.py
index 0f40145e2..555d66986 100644
--- a/test/geometry/test_spatial_softargmax.py
+++ b/test/geometry/test_spatial_softargmax.py
@@ -489,3 +489,115 @@ class TestConvSoftArgmax3d:
coords, val = softargmax(input)
assert_allclose(val, expected_val)
assert_allclose(coords, expected_coord)
+
+
+class TestConvQuadInterp3d:
+ def test_smoke(self, device):
+ input = torch.randn(2, 3, 3, 4, 4).to(device)
+ nms = kornia.geometry.ConvQuadInterp3d(1)
+ coord, val = nms(input)
+ assert coord.shape == (2, 3, 3, 3, 4, 4)
+ assert val.shape == (2, 3, 3, 4, 4)
+
+ def test_gradcheck(self, device):
+ input = torch.rand(1, 2, 3, 5, 5).to(device)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(kornia.geometry.ConvQuadInterp3d(),
+ (input), raise_exception=True)
+
+ def test_diag(self, device):
+ input = torch.tensor([[
+ [[0., 0., 0., 0, 0],
+ [0., 0., 0.0, 0, 0.],
+ [0., 0, 0., 0, 0.],
+ [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.]],
+
+ [[0., 0., 0., 0, 0],
+ [0., 0., 1, 0, 0.],
+ [0., 1, 1.2, 1.1, 0.],
+ [0., 0., 1., 0, 0.],
+ [0., 0., 0., 0, 0.]],
+
+ [[0., 0., 0., 0, 0],
+ [0., 0., 0.0, 0, 0.],
+ [0., 0, 0., 0, 0.],
+ [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.],
+ ]]]).to(device)
+ input = kornia.gaussian_blur2d(input, (5, 5), (0.5, 0.5)).unsqueeze(0)
+ softargmax = kornia.geometry.ConvQuadInterp3d(1)
+ expected_val = torch.tensor([[[
+ [[0., 0., 0., 0, 0],
+ [0., 0., 0.0, 0, 0.],
+ [0., 0, 0., 0, 0.],
+ [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.]],
+ [[2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04],
+ [2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
+ [1.6807e-01, 7.4227e-01, 2.1722e+00, 8.0414e-01, 1.8482e-01],
+ [2.3146e-02, 1.8118e-01, 7.4338e-01, 1.8955e-01, 2.5413e-02],
+ [2.2504e-04, 2.3146e-02, 1.6808e-01, 2.3188e-02, 2.3628e-04]],
+ [[0., 0., 0., 0, 0],
+ [0., 0., 0.0, 0, 0.],
+ [0., 0, 0., 0, 0.],
+ [0., 0., 0, 0, 0.],
+ [0., 0., 0., 0, 0.]]]]]).to(device)
+ expected_coord = torch.tensor([[[[[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
+
+ [[1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
+ [1.0000, 1.0000, 1.0688, 1.0000, 1.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000]],
+
+ [[2.0000, 2.0000, 2.0000, 2.0000, 2.0000],
+ [2.0000, 2.0000, 2.0000, 2.0000, 2.0000],
+ [2.0000, 2.0000, 2.0000, 2.0000, 2.0000],
+ [2.0000, 2.0000, 2.0000, 2.0000, 2.0000],
+ [2.0000, 2.0000, 2.0000, 2.0000, 2.0000]]],
+
+
+ [[[0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000]],
+
+ [[0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 1.8366, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000]],
+
+ [[0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000],
+ [0.0000, 1.0000, 2.0000, 3.0000, 4.0000]]],
+
+
+ [[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
+ [2.0000, 2.0000, 2.0000, 2.0000, 2.0000],
+ [3.0000, 3.0000, 3.0000, 3.0000, 3.0000],
+ [4.0000, 4.0000, 4.0000, 4.0000, 4.0000]],
+
+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
+ [2.0000, 2.0000, 2.0244, 2.0000, 2.0000],
+ [3.0000, 3.0000, 3.0000, 3.0000, 3.0000],
+ [4.0000, 4.0000, 4.0000, 4.0000, 4.0000]],
+
+ [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [1.0000, 1.0000, 1.0000, 1.0000, 1.0000],
+ [2.0000, 2.0000, 2.0000, 2.0000, 2.0000],
+ [3.0000, 3.0000, 3.0000, 3.0000, 3.0000],
+ [4.0000, 4.0000, 4.0000, 4.0000, 4.0000]]]]]]).to(device)
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.py
index 8737dd6b7..1ae41f840 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -77,8 +77,8 @@ class TestPyrDown:
class TestScalePyramid:
def test_shape_tuple(self, device):
- inp = torch.zeros(3, 2, 6, 6).to(device)
- SP = kornia.geometry.ScalePyramid(n_levels=1)
+ inp = torch.zeros(3, 2, 12, 12).to(device)
+ SP = kornia.geometry.ScalePyramid(n_levels=1, min_size=10)
out = SP(inp)
assert len(out) == 3
assert len(out[0]) == 1
@@ -86,38 +86,38 @@ class TestScalePyramid:
assert len(out[2]) == 1
def test_shape_batch(self, device):
- inp = torch.zeros(3, 2, 6, 6).to(device)
+ inp = torch.zeros(3, 2, 21, 21).to(device)
SP = kornia.geometry.ScalePyramid(n_levels=1)
sp, sigmas, pd = SP(inp)
- assert sp[0].shape == (3, 1, 2, 6, 6)
+ assert sp[0].shape == (3, 1, 2, 21, 21)
def test_shape_batch_double(self, device):
- inp = torch.zeros(3, 2, 6, 6).to(device)
+ inp = torch.zeros(3, 2, 12, 12).to(device)
SP = kornia.geometry.ScalePyramid(n_levels=1, double_image=True)
sp, sigmas, pd = SP(inp)
- assert sp[0].shape == (3, 1, 2, 12, 12)
+ assert sp[0].shape == (3, 1, 2, 24, 24)
def test_n_levels_shape(self, device):
- inp = torch.zeros(1, 1, 6, 6).to(device)
- SP = kornia.geometry.ScalePyramid(n_levels=5)
+ inp = torch.zeros(1, 1, 32, 32).to(device)
+ SP = kornia.geometry.ScalePyramid(n_levels=3)
sp, sigmas, pd = SP(inp)
- assert sp[0].shape == (1, 5, 1, 6, 6)
+ assert sp[0].shape == (1, 3, 1, 32, 32)
def test_blur_order(self, device):
- inp = torch.rand(1, 1, 12, 12).to(device)
- SP = kornia.geometry.ScalePyramid(n_levels=5)
+ inp = torch.rand(1, 1, 21, 21).to(device)
+ SP = kornia.geometry.ScalePyramid(n_levels=3)
sp, sigmas, pd = SP(inp)
for i, pyr_level in enumerate(sp):
for ii, img in enumerate(pyr_level):
- img = img.squeeze().view(5, -1)
+ img = img.squeeze().view(3, -1)
max_per_blur_level_val, _ = img.max(dim=1)
assert torch.argmax(max_per_blur_level_val).item() == 0
return
def test_symmetry_preserving(self, device):
- inp = torch.zeros(1, 1, 12, 12).to(device)
- inp[0, 0, 4:8, 4:8] = 1.0
- SP = kornia.geometry.ScalePyramid(n_levels=5)
+ inp = torch.zeros(1, 1, 22, 22).to(device)
+ inp[0, 0, 8:14, 8:14] = 1.0
+ SP = kornia.geometry.ScalePyramid(n_levels=3)
sp, sigmas, pd = SP(inp)
for i, pyr_level in enumerate(sp):
for ii, img in enumerate(pyr_level):