Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Dog and fix features (#591)

Dmytro Mishkin768acfd40021
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index a10bf8bfa..31cab0846 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -17,6 +17,8 @@ Detectors
.. autofunction:: gftt_response
.. autofunction:: harris_response
.. autofunction:: hessian_response
+.. autofunction:: dog_response
+
Descriptors
-----------
@@ -54,6 +56,8 @@ Module
.. autoclass:: BlobHessian
.. autoclass:: CornerGFTT
.. autoclass:: CornerHarris
+.. autoclass:: BlobDoG
+
.. autoclass:: ScaleSpaceDetector
:members: forward
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 1547f6cfc..797a7c7a1 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -1,9 +1,11 @@
from .responses import (CornerHarris,
CornerGFTT,
BlobHessian,
+ BlobDoG,
harris_response,
gftt_response,
- hessian_response)
+ hessian_response,
+ dog_response)
from .nms import (NonMaximaSuppression2d,
nms2d,
NonMaximaSuppression3d,
@@ -44,11 +46,13 @@ __all__ = [
"harris_response",
"gftt_response",
"hessian_response",
+ "dog_response",
"NonMaximaSuppression2d",
"NonMaximaSuppression3d",
"CornerHarris",
"CornerGFTT",
"BlobHessian",
+ "BlobDoG",
"extract_patches_from_pyramid",
"extract_patches_simple",
"normalize_laf",
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 557e314bd..bb7396141 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -477,13 +477,15 @@ def extract_patches_from_pyramid(img: torch.Tensor,
return out
-def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
+def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor,
+ border: int = 0) -> torch.Tensor:
"""Checks if the LAF is touching or partly outside the image boundary. Returns the mask
of LAFs, which are fully inside the image, i.e. valid.
Args:
laf (torch.Tensor): :math:`(B, N, 2, 3)`
images (torch.Tensor): images, lafs are detected in :math:`(B, CH, H, W)`
+ border (int): additional border
Returns:
mask (torch.Tensor): :math:`(B, N)`
@@ -491,7 +493,10 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor) -> torch.Tensor
raise_error_if_laf_is_not_valid(laf)
n, ch, h, w = images.size()
pts: torch.Tensor = laf_to_boundary_points(laf, 12)
- good_lafs_mask: torch.Tensor = (pts[..., 0] >= 0) * (pts[..., 0] <= w) * (pts[..., 1] >= 0) * (pts[..., 1] <= h)
+ good_lafs_mask: torch.Tensor = (pts[..., 0] >= border) *\
+ (pts[..., 0] <= w - border) *\
+ (pts[..., 1] >= border) *\
+ (pts[..., 1] <= h - border)
good_lafs_mask = good_lafs_mask.min(dim=2)[0]
return good_lafs_mask
diff --git a/kornia/feature/nms.py b/kornia/feature/nms.py
index 77f6aa05b..e4db350bc 100644
--- a/kornia/feature/nms.py
+++ b/kornia/feature/nms.py
@@ -30,13 +30,13 @@ class NonMaximaSuppression2d(nn.Module):
def __init__(self, kernel_size: Tuple[int, int]):
super(NonMaximaSuppression2d, self).__init__()
self.kernel_size: Tuple[int, int] = kernel_size
- self.padding: Tuple[int,
- int] = self._compute_zero_padding2d(kernel_size)
+ self.padding: Tuple[int, int,
+ int, int] = self._compute_zero_padding2d(kernel_size)
self.kernel = _get_nms_kernel2d(*kernel_size)
@staticmethod
def _compute_zero_padding2d(
- kernel_size: Tuple[int, int]) -> Tuple[int, int]:
+ kernel_size: Tuple[int, int]) -> Tuple[int, int, int, int]:
assert isinstance(kernel_size, tuple), type(kernel_size)
assert len(kernel_size) == 2, kernel_size
@@ -44,15 +44,15 @@ class NonMaximaSuppression2d(nn.Module):
return (x - 1) // 2 # zero padding function
ky, kx = kernel_size # we assume a cubic kernel
- return (pad(ky), pad(kx))
+ return (pad(ky), pad(ky), pad(kx), pad(kx))
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
assert len(x.shape) == 4, x.shape
B, CH, H, W = x.size()
# find local maximum values
- max_non_center = F.conv2d(x, self.kernel.repeat(CH, 1, 1, 1).to(x.device, x.dtype),
+ max_non_center = F.conv2d(F.pad(x, list(self.padding)[::-1], mode='replicate'),
+ self.kernel.repeat(CH, 1, 1, 1).to(x.device, x.dtype),
stride=1,
- padding=self.padding,
groups=CH).view(B, CH, -1, H, W).max(dim=2)[0]
mask = x > max_non_center
if mask_only:
@@ -67,14 +67,13 @@ class NonMaximaSuppression3d(nn.Module):
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.padding: Tuple[int, int, int,
+ int, int, int] = self._compute_zero_padding3d(kernel_size)
self.kernel = _get_nms_kernel3d(*kernel_size)
@staticmethod
def _compute_zero_padding3d(
- kernel_size: Tuple[int, int, int]) -> Tuple[int, int, int]:
+ kernel_size: Tuple[int, int, int]) -> Tuple[int, int, int, int, int, int]:
assert isinstance(kernel_size, tuple), type(kernel_size)
assert len(kernel_size) == 3, kernel_size
@@ -82,15 +81,15 @@ class NonMaximaSuppression3d(nn.Module):
return (x - 1) // 2 # zero padding function
kd, ky, kx = kernel_size # we assume a cubic kernel
- return pad(kd), pad(ky), pad(kx)
+ return pad(kd), pad(kd), pad(ky), pad(ky), pad(kx), 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
B, CH, D, H, W = x.size()
- max_non_center = F.conv3d(x, self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
+ max_non_center = F.conv3d(F.pad(x, list(self.padding)[::-1], mode='replicate'),
+ self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
stride=1,
- padding=self.padding,
groups=CH).view(B, CH, -1, D, H, W).max(dim=2, keepdim=False)[0]
mask = x > max_non_center
if mask_only:
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 4ddbb4fe8..665818011 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -259,6 +259,47 @@ def hessian_response(input: torch.Tensor,
return scores
+def dog_response(input: torch.Tensor) -> torch.Tensor:
+ r"""Computes the Difference-of-Gaussian responce given the Gaussian 5d input:
+
+
+ Args:
+ input: torch.Tensor: 5d tensor
+
+ Return:
+ torch.Tensor: the response map per channel.
+
+ Shape:
+ - Input: :math:`(B, C, D, H, W)`
+ - Output: :math:`(B, C, D-1, H, W)`
+
+ """
+ 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))
+ return input[:, :, 1:] - input[:, :, :-1]
+
+
+class BlobDoG(nn.Module):
+ r"""nn.Module that calculates Difference-of-Gaussians blobs
+ See :func:`~kornia.feature.dog_response` for details.
+ """
+
+ def __init__(self) -> None:
+ super(BlobDoG, self).__init__()
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__
+
+ def forward(self, input: torch.Tensor, # type: ignore
+ sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ return dog_response(input) # type: ignore
+
+
class CornerHarris(nn.Module):
r"""nn.Module that calculates Harris corners
See :func:`~kornia.feature.harris_response` for details.
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 8d7a476f7..767f22646 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -9,12 +9,12 @@ from kornia.feature.responses import BlobHessian
from kornia.geometry import ConvSoftArgmax3d
from kornia.feature.orientation import PassLAF
from kornia.feature.laf import (
- denormalize_laf,
+ denormalize_laf, scale_laf,
normalize_laf, laf_is_inside_image)
from kornia.geometry.transform import ScalePyramid
-def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:
"""Auxilary function for ScaleSpaceDetector. Converts scale level index from ConvSoftArgmax3d
to the actual scale, using the sigmas from the ScalePyramid output
Args:
@@ -33,23 +33,9 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> tor
B, N, _ = max_coords.shape
L: int = sigmas.size(1)
scale_coords = max_coords[:, :, 0].contiguous().view(-1, 1, 1, 1)
-
- # Normalize coordinate
- scale_coords_index = (2.0 * scale_coords / sigmas.size(1)) - 1.0
-
- # Dummy dimension
- dummy_x = torch.zeros_like(scale_coords_index)
-
- # Create grid
- scale_grid = torch.cat([scale_coords_index, dummy_x], dim=3)
-
- # Finally, interpolate the scale value
- scale_val = F.grid_sample( # type: ignore
- sigmas[0].log2().view(1, 1, 1, -1).expand(scale_grid.size(0), 1, 1, L),
- scale_grid, align_corners=False)
-
# Replace the scale_x_y
- out = torch.cat([torch.pow(2.0, scale_val).view(B, N, 1), max_coords[:, :, 1:]], dim=2)
+ out = torch.cat([sigmas[0, 0] * torch.pow(2.0, scale_coords / float(num_levels)).view(B, N, 1),
+ max_coords[:, :, 1:]], dim=2)
return out
@@ -76,20 +62,20 @@ class ScaleSpaceDetector(nn.Module):
scale_pyr_module: (nn.Module), which generates scale pyramid.
See :class:`~kornia.geometry.ScalePyramid` for details. Default is ScalePyramid(3, 1.6, 10)
resp_module: (nn.Module), which calculates 'cornerness' of the pixel. Default is BlobHessian().
- nms_module: (nn.Module), which outputs per-patch coordinates of the responce maxima.
+ nms_module: (nn.Module), which outputs per-patch coordinates of the response maxima.
See :class:`~kornia.geometry.ConvSoftArgmax3d` for details.
ori_module: (nn.Module) for local feature orientation estimation. Default is :class:`~kornia.feature.PassLAF`,
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
+ Useful for symmetric response functions like DoG or Hessian. Default is False
"""
def __init__(self,
num_features: int = 500,
mr_size: float = 6.0,
- scale_pyr_module: nn.Module = ScalePyramid(3, 1.6, 10),
+ scale_pyr_module: nn.Module = ScalePyramid(3, 1.6, 15),
resp_module: nn.Module = BlobHessian(),
nms_module: nn.Module = ConvSoftArgmax3d((3, 3, 3),
(1, 1, 1),
@@ -98,7 +84,8 @@ class ScaleSpaceDetector(nn.Module):
output_value=True),
ori_module: nn.Module = PassLAF(),
aff_module: nn.Module = PassLAF(),
- minima_are_also_good: bool = False):
+ minima_are_also_good: bool = False,
+ scale_space_response=False):
super(ScaleSpaceDetector, self).__init__()
self.mr_size = mr_size
self.num_features = num_features
@@ -108,6 +95,9 @@ class ScaleSpaceDetector(nn.Module):
self.ori = ori_module
self.aff = aff_module
self.minima_are_also_good = minima_are_also_good
+ # scale_space_response should be True if the response function works on scale space
+ # like Difference-of-Gaussians
+ self.scale_space_response = scale_space_response
return
def __repr__(self):
@@ -131,12 +121,18 @@ class ScaleSpaceDetector(nn.Module):
sigmas_oct = sigmas[oct_idx]
pix_dists_oct = pix_dists[oct_idx]
- B, L, CH, H, W = octave.size()
+ B, CH, L, H, W = octave.size()
# Run response function
- oct_resp = self.resp(octave.view(B * L, CH, H, W), sigmas_oct.view(-1))
-
- # We want nms for scale responses, so reorder to (B, CH, L, H, W)
- oct_resp = oct_resp.view_as(octave).permute(0, 2, 1, 3, 4)
+ if self.scale_space_response:
+ oct_resp = self.resp(octave, sigmas_oct.view(-1))
+ else:
+ oct_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W),
+ sigmas_oct.view(-1)).view(B, L, CH, H, W)
+ # We want nms for scale responses, so reorder to (B, CH, L, H, W)
+ oct_resp = oct_resp.permute(0, 2, 1, 3, 4)
+ # 3rd extra level is required for DoG only
+ if self.scale_pyr.extra_levels % 2 != 0: # type: ignore
+ oct_resp = oct_resp[:, :, :-1]
if mask is not None:
oct_mask: torch.Tensor = _create_octave_mask(mask, oct_resp.shape)
@@ -148,7 +144,7 @@ class ScaleSpaceDetector(nn.Module):
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
+ coord_max = coord_min * take_min_mask.unsqueeze(2) + (1 - take_min_mask.unsqueeze(2)) * coord_max
# Now, lets crop out some small responses
responses_flatten = response_max.view(response_max.size(0), -1) # [B, N]
@@ -163,7 +159,9 @@ class ScaleSpaceDetector(nn.Module):
B, N = resp_flat_best.size()
# Converts scale level index from ConvSoftArgmax3d to the actual scale, using the sigmas
- max_coords_best = _scale_index_to_scale(max_coords_best, sigmas_oct)
+ max_coords_best = _scale_index_to_scale(max_coords_best,
+ sigmas_oct,
+ self.scale_pyr.n_levels) # type: ignore
# Create local affine frames (LAFs)
rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index f9661a934..25c8457a8 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -491,5 +491,5 @@ def get_motion_kernel2d(kernel_size: int, angle: float, direction: float = 0.) -
# rotate (counterclockwise) kernel by given angle
kernel = rotate(kernel, torch.tensor(angle))
kernel = kernel[0][0]
- kernel /= kernel.sum()
+ kernel = kernel / kernel.sum()
return kernel
diff --git a/kornia/geometry/spatial_soft_argmax.py b/kornia/geometry/spatial_soft_argmax.py
index 21cc3a1fd..21e8826ec 100644
--- a/kornia/geometry/spatial_soft_argmax.py
+++ b/kornia/geometry/spatial_soft_argmax.py
@@ -542,7 +542,7 @@ class SpatialSoftArgmax2d(nn.Module):
self.normalized_coordinates, self.eps)
-def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 1.0, eps: float = 1e-6):
+def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7):
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
@@ -591,12 +591,16 @@ def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 1.0, ep
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)
- Hes += torch.eye(3, device=Hes.device)[None] * eps
+ dxy = 0.25 * A[..., 3] # normalization to match OpenCV implementation
+ dys = 0.25 * A[..., 4] # normalization to match OpenCV implementation
+ dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementation
+
+ Hes = torch.stack([dxx, dxy, dxs,
+ dxy, dyy, dys,
+ dxs, dys, dss], dim=-1).view(-1, 3, 3)
+
+ # The following is needed to avoid singular cases
+ Hes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
nms_mask: torch.Tensor = kornia.feature.nms3d(input, (3, 3, 3), True)
x_solved: torch.Tensor = torch.zeros_like(b)
@@ -604,17 +608,18 @@ def conv_quad_interp3d(input: torch.Tensor, strict_maxima_bonus: float = 1.0, ep
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
-
+ # Ignore ones, which are far from window center
+ mask1 = (dx.abs().max(dim=1, keepdim=True)[0] > 0.7)
+ dx.masked_fill_(mask1.expand_as(dx), 0)
dy: torch.Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
y_max = input + dy.view(B, CH, D, H, W)
if strict_maxima_bonus > 0:
- y_max *= (1.0 + strict_maxima_bonus * nms_mask.to(input.dtype))
+ y_max += 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
@@ -624,7 +629,7 @@ class ConvQuadInterp3d(nn.Module):
"""
def __init__(self,
- strict_maxima_bonus: float = 1.0, eps: float = 1e-6) -> None:
+ strict_maxima_bonus: float = 10.0, eps: float = 1e-7) -> None:
super(ConvQuadInterp3d, self).__init__()
self.strict_maxima_bonus = strict_maxima_bonus
self.eps = eps
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 863693eef..3429df9c7 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -135,7 +135,7 @@ class ScalePyramid(nn.Module):
Shape:
- Input: :math:`(B, C, H, W)`
- - Output 1st: :math:`[(B, NL, C, H, W), (B, NL, C, H/2, W/2), ...]`
+ - Output 1st: :math:`[(B, C, NL, H, W), (B, C, NL, H/2, W/2), ...]`
- Output 2nd: :math:`[(B, NL), (B, NL), (B, NL), ...]`
- Output 3rd: :math:`[(B, NL), (B, NL), (B, NL), ...]`
@@ -147,10 +147,12 @@ class ScalePyramid(nn.Module):
def __init__(self,
n_levels: int = 3,
init_sigma: float = 1.6,
- min_size: int = 5,
+ min_size: int = 15,
double_image: bool = False):
super(ScalePyramid, self).__init__()
+ # 3 extra levels are needed for DoG nms.
self.n_levels = n_levels
+ self.extra_levels: int = 3
self.init_sigma = init_sigma
self.min_size = min_size
self.border = min_size // 2 - 1
@@ -163,76 +165,96 @@ class ScalePyramid(nn.Module):
'(n_levels=' + str(self.n_levels) + ', ' +\
'init_sigma=' + str(self.init_sigma) + ', ' + \
'min_size=' + str(self.min_size) + ', ' + \
+ 'extra_levels=' + str(self.extra_levels) + ', ' + \
'border=' + str(self.border) + ', ' + \
- 'sigma_step=' + str(self.sigma_step) + \
+ 'sigma_step=' + str(self.sigma_step) + ', ' + \
'double_image=' + str(self.double_image) + ')'
def get_kernel_size(self, sigma: float):
ksize = int(2.0 * 4.0 * sigma + 1.0)
+
+ # matches OpenCV, but may cause padding problem for small images
+ # PyTorch does not allow to pad more than original size.
+ # Therefore there is a hack in forward function
+
if ksize % 2 == 0:
ksize += 1
return ksize
- def forward(self, x: torch.Tensor) -> Tuple[ # type: ignore
- List, List, List]:
- bs, ch, h, w = x.size()
+ def get_first_level(self, input):
pixel_distance = 1.0
cur_sigma = 0.5
+ # Same as in OpenCV up to interpolation difference
if self.double_image:
- x = F.interpolate(x, scale_factor=2.0, mode='bilinear', align_corners=False)
+ x = F.interpolate(input, scale_factor=2.0, mode='bilinear', align_corners=False)
pixel_distance = 0.5
cur_sigma *= 2.0
+ else:
+ x = input
if self.init_sigma > cur_sigma:
- sigma = math.sqrt(self.init_sigma**2 - cur_sigma**2)
- cur_sigma = self.init_sigma
+ sigma = max(math.sqrt(self.init_sigma**2 - cur_sigma**2), 0.01)
ksize = self.get_kernel_size(sigma)
cur_level = gaussian_blur2d(x, (ksize, ksize), (sigma, sigma))
+ cur_sigma = self.init_sigma
else:
cur_level = x
- sigmas = [cur_sigma * torch.ones(bs, self.n_levels).to(x.device).to(x.dtype)]
+ return cur_level, cur_sigma, pixel_distance
+
+ def forward(self, x: torch.Tensor) -> Tuple[ # type: ignore
+ List, List, List]:
+ bs, ch, h, w = x.size()
+ cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
+
+ sigmas = [cur_sigma * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device).to(x.dtype)]
pixel_dists = [pixel_distance * torch.ones(
bs,
- self.n_levels).to(
+ self.n_levels + self.extra_levels).to(
x.device).to(x.dtype)]
- pyr = [[cur_level.unsqueeze(1)]]
+ pyr = [[cur_level]]
oct_idx = 0
while True:
- cur_level = pyr[-1][0].squeeze(1)
- for level_idx in range(1, self.n_levels):
+ cur_level = pyr[-1][0]
+ for level_idx in range(1, self.n_levels + self.extra_levels):
sigma = cur_sigma * math.sqrt(self.sigma_step**2 - 1.0)
+ ksize = self.get_kernel_size(sigma)
+
+ # Hack, because PyTorch does not allow to pad more than original size.
+ # But for the huge sigmas, one needs huge kernel and padding...
+
+ ksize = min(ksize, min(cur_level.size(2), cur_level.size(3)))
+ if ksize % 2 == 0:
+ ksize += 1
+
cur_level = gaussian_blur2d(
cur_level, (ksize, ksize), (sigma, sigma))
cur_sigma *= self.sigma_step
- pyr[-1].append(cur_level.unsqueeze(1))
+ pyr[-1].append(cur_level)
sigmas[-1][:, level_idx] = cur_sigma
pixel_dists[-1][:, level_idx] = pixel_distance
- nextOctaveFirstLevel = F.interpolate(pyr[-1][-1].squeeze(1), scale_factor=0.5,
- mode='bilinear',
- align_corners=False)
+ nextOctaveFirstLevel = F.interpolate(pyr[-1][-self.extra_levels], scale_factor=0.5,
+ mode='nearest') # Nearest matches OpenCV SIFT
pixel_distance *= 2.0
cur_sigma = self.init_sigma
if (min(nextOctaveFirstLevel.size(2),
nextOctaveFirstLevel.size(3)) <= self.min_size):
break
- pyr.append([nextOctaveFirstLevel.unsqueeze(1)])
+ pyr.append([nextOctaveFirstLevel])
sigmas.append(cur_sigma * torch.ones(
bs,
- self.n_levels).to(
+ self.n_levels + self.extra_levels).to(
x.device))
pixel_dists.append(
pixel_distance * torch.ones(
bs,
- self.n_levels).to(
+ self.n_levels + self.extra_levels).to(
x.device))
oct_idx += 1
for i in range(len(pyr)):
- pyr[i] = torch.cat(pyr[i], dim=1) # type: ignore
+ pyr[i] = torch.stack(pyr[i], dim=2) # type: ignore
return pyr, sigmas, pixel_dists
# functional api
-
-
def pyrdown(
input: torch.Tensor,
border_type: str = 'reflect', align_corners: bool = False) -> torch.Tensor:
diff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.py
index 870f19cee..06cb88ada 100644
--- a/test/feature/test_scale_space_detector.py
+++ b/test/feature/test_scale_space_detector.py
@@ -37,19 +37,19 @@ class TestScaleSpaceDetector:
resp_module=kornia.feature.BlobHessian(),
mr_size=3.0).to(device)
lafs, resps = det(inp)
- 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.001, atol=1e-03)
- assert_allclose(expected_resp, resps, rtol=0.001, atol=1e-03)
+ expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device)
+ expected_resp = torch.tensor([[0.0857]], device=device)
+ assert_allclose(lafs, expected_laf, rtol=0.001, atol=1e-03)
+ assert_allclose(resps, expected_resp, rtol=0.001, atol=1e-03)
def test_toy_mask(self, device):
if "cuda" in str(device):
pytest.skip("this cuda test is broken")
- inp = torch.zeros(1, 1, 15, 10, device=device)
- inp[:, :, 2:-2, 1:-1] = 1.0
+ inp = torch.zeros(1, 1, 33, 33, device=device)
+ inp[:, :, 13:-13, 13:-13] = 1.0
- mask = torch.zeros(1, 1, 15, 10, device=device)
+ mask = torch.zeros(1, 1, 33, 33, device=device)
mask[:, :, 1:-1, 3:-3] = 1.0
n_feats = 1
@@ -57,11 +57,10 @@ class TestScaleSpaceDetector:
resp_module=kornia.feature.BlobHessian(),
mr_size=3.0).to(device)
lafs, resps = det(inp, mask)
- expected_laf = torch.tensor([[[[6.0478, 0.0000, 4.9978],
- [0.0000, 6.0478, 4.9993]]]], device=device)
- expected_resp = torch.tensor([[0.0]], device=device)
- assert_allclose(expected_laf, lafs, rtol=0.001, atol=1e-03)
- assert_allclose(expected_resp, resps, rtol=0.001, atol=1e-03)
+ expected_laf = torch.tensor([[[[9.5823, 0.0000, 16.0], [0.0, 9.5823, 16.0]]]], device=device)
+ expected_resp = torch.tensor([[0.0857]], device=device)
+ assert_allclose(lafs, expected_laf, rtol=0.001, atol=1e-03)
+ assert_allclose(resps, expected_resp, rtol=0.001, atol=1e-03)
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 31, 21
diff --git a/test/geometry/test_spatial_softargmax.py b/test/geometry/test_spatial_softargmax.py
index 9bc20d13a..e95771989 100644
--- a/test/geometry/test_spatial_softargmax.py
+++ b/test/geometry/test_spatial_softargmax.py
@@ -416,10 +416,11 @@ class TestConvQuadInterp3d:
assert val.shape == (2, 3, 3, 4, 4)
def test_gradcheck(self, device):
- input = torch.rand(1, 2, 3, 5, 5).to(device)
+ input = torch.rand(1, 1, 3, 5, 5).to(device)
+ input[0, 0, 1, 2, 2] += 20.
input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.geometry.ConvQuadInterp3d(),
- (input), raise_exception=True)
+ assert gradcheck(kornia.geometry.ConvQuadInterp3d(strict_maxima_bonus=0),
+ (input), raise_exception=True, atol=1e-3, rtol=1e-3)
def test_diag(self, device):
input = torch.tensor([[
@@ -442,7 +443,7 @@ class TestConvQuadInterp3d:
[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)
+ softargmax = kornia.geometry.ConvQuadInterp3d(10)
expected_val = torch.tensor([[[
[[0., 0., 0., 0, 0],
[0., 0., 0.0, 0, 0.],
@@ -451,7 +452,7 @@ class TestConvQuadInterp3d:
[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],
+ [1.6807e-01, 7.4227e-01, 1.1086e+01, 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],
@@ -459,61 +460,61 @@ class TestConvQuadInterp3d:
[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)
+ expected_coord = torch.tensor([[[[[[0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0]],
+
+ [[1.0, 1.0, 1.0, 1.0, 1.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0]],
+
+ [[2.0, 2.0, 2.0, 2.0, 2.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0]]],
+
+
+ [[[0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0]],
+
+ [[0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0]],
+
+ [[0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0],
+ [0.0, 1.0, 2.0, 3.0, 4.0]]],
+
+
+ [[[0.0, 0.0, 0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0],
+ [4.0, 4.0, 4.0, 4.0, 4.0]],
+
+ [[0.0, 0.0, 0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0],
+ [2.0, 2.0, 2.0495, 2.0, 2.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0],
+ [4.0, 4.0, 4.0, 4.0, 4.0]],
+
+ [[0.0, 0.0, 0.0, 0.0, 0.0],
+ [1.0, 1.0, 1.0, 1.0, 1.0],
+ [2.0, 2.0, 2.0, 2.0, 2.0],
+ [3.0, 3.0, 3.0, 3.0, 3.0],
+ [4.0, 4.0, 4.0, 4.0, 4.0]]]]]]).to(device)
coords, val = softargmax(input)
assert_allclose(val, expected_val)
assert_allclose(coords, expected_coord)
diff --git a/test/geometry/transform/test_crop.py b/test/geometry/transform/test_crop.py
index 37db96693..de982b425 100644
--- a/test/geometry/transform/test_crop.py
+++ b/test/geometry/transform/test_crop.py
@@ -40,6 +40,10 @@ class TestBoundingBoxInferring:
h, w = kornia.geometry.transform.crop._infer_bounding_box(boxes)
assert (h, w) == (expected_height, expected_width)
+ @pytest.mark.skip(reason="Crashes with pytorch internal error")
+ # RuntimeError: isDifferentiableType(variable.scalar_type()) INTERNAL ASSERT FAILED at
+ # "/opt/conda/conda-bld/pytorch_1595629417679/work/torch/csrc/autograd/functions/utils.h":59,
+ # please report a bug to PyTorch.
def test_gradcheck(self, device):
boxes = torch.tensor([[
[1., 1.],
diff --git a/test/geometry/transform/test_pyramid.py b/test/geometry/transform/test_pyramid.py
index c35c475d0..df3764d38 100644
--- a/test/geometry/transform/test_pyramid.py
+++ b/test/geometry/transform/test_pyramid.py
@@ -76,8 +76,8 @@ class TestPyrDown:
class TestScalePyramid:
def test_shape_tuple(self, device):
- inp = torch.zeros(3, 2, 12, 12).to(device)
- SP = kornia.geometry.ScalePyramid(n_levels=1, min_size=10)
+ inp = torch.zeros(3, 2, 41, 41).to(device)
+ SP = kornia.geometry.ScalePyramid(n_levels=1, min_size=30)
out = SP(inp)
assert len(out) == 3
assert len(out[0]) == 1
@@ -85,25 +85,25 @@ class TestScalePyramid:
assert len(out[2]) == 1
def test_shape_batch(self, device):
- inp = torch.zeros(3, 2, 21, 21).to(device)
+ inp = torch.zeros(3, 2, 31, 31).to(device)
SP = kornia.geometry.ScalePyramid(n_levels=1)
sp, sigmas, pd = SP(inp)
- assert sp[0].shape == (3, 1, 2, 21, 21)
+ assert sp[0].shape == (3, 2, 3 + 1, 31, 31)
def test_shape_batch_double(self, device):
- inp = torch.zeros(3, 2, 12, 12).to(device)
+ inp = torch.zeros(3, 2, 31, 31).to(device)
SP = kornia.geometry.ScalePyramid(n_levels=1, double_image=True)
sp, sigmas, pd = SP(inp)
- assert sp[0].shape == (3, 1, 2, 24, 24)
+ assert sp[0].shape == (3, 2, 1 + 3, 62, 62)
def test_n_levels_shape(self, device):
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, 3, 1, 32, 32)
+ assert sp[0].shape == (1, 1, 3 + 3, 32, 32)
def test_blur_order(self, device):
- inp = torch.rand(1, 1, 21, 21).to(device)
+ inp = torch.rand(1, 1, 31, 31).to(device)
SP = kornia.geometry.ScalePyramid(n_levels=3)
sp, sigmas, pd = SP(inp)
for i, pyr_level in enumerate(sp):
@@ -114,15 +114,17 @@ class TestScalePyramid:
return
def test_symmetry_preserving(self, device):
- inp = torch.zeros(1, 1, 22, 22).to(device)
- inp[0, 0, 8:14, 8:14] = 1.0
+ PS = 16
+ R = 2
+ inp = torch.zeros(1, 1, PS, PS).to(device)
+ inp[..., PS // 2 - R:PS // 2 + R, PS // 2 - R:PS // 2 + R] = 1.0
SP = kornia.geometry.ScalePyramid(n_levels=3)
sp, sigmas, pd = SP(inp)
for i, pyr_level in enumerate(sp):
for ii, img in enumerate(pyr_level):
img = img.squeeze()
- assert torch.allclose(img, img.flip(1))
- assert torch.allclose(img, img.flip(2))
+ assert torch.allclose(img, img.flip(1), atol=1e-5, rtol=1e-3)
+ assert torch.allclose(img, img.flip(2), atol=1e-5, rtol=1e-3)
return
def test_gradcheck(self, device):