Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

resolve

Dmytro Mishkin58deb5d44039
diff --git a/kornia/__init__.py b/kornia/__init__.py
index ea7ce84ca..5c790a4fd 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -26,13 +26,12 @@ from kornia.color import (
adjust_brightness,
)
from kornia.contrib import (
- spatial_soft_argmax2d,
extract_tensor_patches,
max_blur_pool2d,
)
from kornia.feature import (
non_maxima_suppression2d,
- corner_harris,
+ harris_response,
SIFTDescriptor
)
from kornia.filters import (
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index a29119741..0aa6a1e5b 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -1,4 +1,4 @@
-from .spatial_soft_argmax2d import SpatialSoftArgmax2d, spatial_soft_argmax2d
+from kornia.geometry.spatial_soft_argmax import SpatialSoftArgmax2d, spatial_soft_argmax2d
from .extract_patches import ExtractTensorPatches, extract_tensor_patches
from .max_blur_pool import MaxBlurPool2d, max_blur_pool2d
diff --git a/kornia/contrib/spatial_soft_argmax2d.py b/kornia/contrib/spatial_soft_argmax2d.py
deleted file mode 100644
index 2f5d1585e..000000000
--- a/kornia/contrib/spatial_soft_argmax2d.py
+++ /dev/null
@@ -1,62 +0,0 @@
-import torch
-import torch.nn as nn
-
-from kornia.contrib.dsnt import (spatial_softmax_2d,
- spatial_softargmax_2d)
-
-
-def spatial_soft_argmax2d(
- input: torch.Tensor,
- temperature: torch.Tensor = torch.tensor(1.0),
- normalized_coordinates: bool = True,
- eps: float = 1e-8) -> torch.Tensor:
- r"""Function that computes the Spatial Soft-Argmax 2D
- of a given input heatmap.
-
- Returns the index of the maximum 2d coordinates of the give map.
- The output order is x-coord and y-coord.
-
- Arguments:
- temperature (torch.Tensor): factor to apply to input. Default is 1.
- normalized_coordinates (bool): whether to return the
- coordinates normalized in the range of [-1, 1]. Otherwise,
- it will return the coordinates in the range of the input shape.
- Default is True.
- eps (float): small value to avoid zero division. Default is 1e-8.
-
- Shape:
- - Input: :math:`(B, N, H, W)`
- - Output: :math:`(B, N, 2)`
-
- Examples:
- >>> input = torch.tensor([[[
- [0., 0., 0.],
- [0., 10., 0.],
- [0., 0., 0.]]]])
- >>> coords = kornia.spatial_soft_argmax2d(input, False)
- tensor([[[1.0000, 1.0000]]])
- """
- input_soft: torch.Tensor = spatial_softmax_2d(input, temperature)
- output: torch.Tensor = spatial_softargmax_2d(input_soft,
- normalized_coordinates)
- return output
-
-
-class SpatialSoftArgmax2d(nn.Module):
- r"""Function that computes the Spatial Soft-Argmax 2D of a given heatmap.
-
- See :class:`~kornia.contrib.spatial_soft_argmax2d` for details.
- """
-
- def __init__(self,
- temperature: torch.Tensor = torch.tensor(1.0),
- normalized_coordinates: bool = True,
- eps: float = 1e-8) -> None:
- super(SpatialSoftArgmax2d, self).__init__()
- self.temperature: torch.Tensor = temperature
- self.normalized_coordinates: bool = normalized_coordinates
- self.eps: float = eps
-
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
- return spatial_soft_argmax2d(input, self.temperature,
- self.normalized_coordinates, self.eps)
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index ec4dba8ab..232eb7a71 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -1,5 +1,10 @@
from kornia.geometry import angle_to_rotation_matrix
-from .harris import CornerHarris, corner_harris
+from .responses import (CornerHarris,
+ CornerGFTT,
+ BlobHessian,
+ harris_response,
+ gftt_response,
+ hessian_response)
from .nms import NonMaximaSuppression2d, non_maxima_suppression2d
from .laf import (extract_patches_from_pyramid,
extract_patches_simple,
@@ -8,13 +13,24 @@ from .laf import (extract_patches_from_pyramid,
laf_to_boundary_points,
ellipse_to_laf,
make_upright,
- get_laf_scale)
+ scale_laf,
+ get_laf_scale,
+ raise_error_if_laf_is_not_valid)
from .siftdesc import SIFTDescriptor
+from .scale_space_detector import ScaleSpaceDetector, PassLAF
+from .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator
+from .orientation import LAFOrienter, PatchDominantGradientOrientation
+
+
__all__ = [
"non_maxima_suppression2d",
- "corner_harris",
+ "harris_response",
+ "gftt_response",
+ "hessian_response",
"NonMaximaSuppression2d",
"CornerHarris",
+ "CornerGFTT",
+ "BlobHessian",
"extract_patches_from_pyramid",
"extract_patches_simple",
"normalize_laf",
@@ -23,5 +39,13 @@ __all__ = [
"ellipse_to_laf",
"make_upright",
"get_laf_scale",
- "SIFTDescriptor"
+ "scale_laf",
+ "SIFTDescriptor",
+ "PassLAF",
+ "ScaleSpaceDetector",
+ "LAFAffineShapeEstimator",
+ "PatchAffineShapeEstimator",
+ "LAFOrienter",
+ "PatchDominantGradientOrientation",
+ "raise_error_if_laf_is_not_valid"
]
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
new file mode 100644
index 000000000..940df14a4
--- /dev/null
+++ b/kornia/feature/affine_shape.py
@@ -0,0 +1,78 @@
+from typing import Tuple
+
+import torch
+import torch.nn as nn
+import math
+from kornia.filters import get_gaussian_kernel2d
+from kornia.filters import SpatialGradient
+from kornia.feature.laf import (ellipse_to_laf,
+ make_upright,
+ get_laf_scale,
+ raise_error_if_laf_is_not_valid,
+ scale_laf)
+from kornia.feature import extract_patches_from_pyramid
+
+
+class PatchAffineShapeEstimator(nn.Module):
+ def __init__(self, patch_size: int = 19):
+ super(PatchAffineShapeEstimator, self).__init__()
+ self.patch_size: int = patch_size
+ self.gradient: nn.Module = SpatialGradient('sobel', 1)
+ sigma: float = float(self.patch_size) / math.sqrt(2.0)
+ self.weighting: torch.Tensor = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)
+ return
+
+ def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore
+ if not torch.is_tensor(patch):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(patch)))
+ if not len(patch.shape) == 4:
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
+ .format(patch.shape))
+ B, CH, W, H = patch.size()
+ if (W != self.patch_size) or (H != self.patch_size) or (CH != 1):
+ raise TypeError(
+ "input shape should be must be [Bx1x{}x{}]. "
+ "Got {}".format(self.patch_size, self.patch_size, patch.size()))
+ self.weighting = self.weighting.to(patch.dtype).to(patch.device)
+ grads: torch.Tensor = self.gradient(patch)
+ # unpack the edges
+ gx: torch.Tensor = grads[:, :, 0]
+ gy: torch.Tensor = grads[:, :, 1]
+ ellipse_shape = torch.cat([gx.pow(2).mean(dim=2).mean(dim=2, keepdim=True),
+ (gx * gy).mean(dim=2).mean(dim=2, keepdim=True),
+ gy.pow(2).mean(dim=2).mean(dim=2, keepdim=True)], dim=2)
+ return ellipse_shape
+
+
+class LAFAffineShapeEstimator(nn.Module):
+ def __init__(self,
+ patch_size: int = 32):
+ super(LAFAffineShapeEstimator, self).__init__()
+ self.patch_size = patch_size
+ self.affine_shape_detector = PatchAffineShapeEstimator(self.patch_size)
+ return
+
+ def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore
+ raise_error_if_laf_is_not_valid(laf)
+ img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
+ if not torch.is_tensor(img):
+ raise TypeError("img type is not a torch.Tensor. Got {}"
+ .format(type(img)))
+ if len(img.shape) != 4:
+ raise ValueError(img_message)
+ if laf.size(0) != img.size(0):
+ raise ValueError("Batch size of laf and img should be the same. Got {}, {}"
+ .format(img.size(0), laf.size(0)))
+ B, N = laf.shape[:2]
+ patches: torch.Tensor = extract_patches_from_pyramid(img, laf, PS=self.patch_size).view(-1,
+ 1,
+ self.patch_size,
+ self.patch_size)
+ ellipse_shape: torch.Tensor = self.affine_shape_detector(patches)
+ ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), ellipse_shape], dim=2).view(B, N, 5)
+ scale_orig = get_laf_scale(laf)
+ laf_out = ellipse_to_laf(ellipses)
+ ellipse_scale = get_laf_scale(laf_out)
+ laf_out = scale_laf(laf_out, scale_orig / ellipse_scale)
+ return laf_out
diff --git a/kornia/feature/harris.py b/kornia/feature/harris.py
deleted file mode 100644
index b6fcbbd83..000000000
--- a/kornia/feature/harris.py
+++ /dev/null
@@ -1,115 +0,0 @@
-from typing import Tuple
-
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-
-from kornia.feature.nms import non_maxima_suppression2d
-from kornia.filters import spatial_gradient, gaussian_blur2d
-
-
-class CornerHarris(nn.Module):
- r"""Computes the Harris corner detection.
-
- The response map is computed according the following formulation:
-
- .. math::
- R = det(M) - k \cdot trace(M)^2
-
- where:
-
- .. math::
- M = \sum_{(x,y) \in W}
- \begin{bmatrix}
- I^{2}_x & I_x I_y \\
- I_x I_y & I^{2}_y \\
- \end{bmatrix}
-
- and :math:`k` is an empirically determined constant
- :math:`k ∈ [ 0.04 , 0.06 ]`
-
- Args:
- k (torch.Tensor): the Harris detector free parameter.
-
- Return:
- torch.Tensor: the response map per channel.
-
- Shape:
- - Input: :math:`(B, C, H, W)`
- - Output: :math:`(B, C, H, W)`
-
- Examples:
- >>> input = torch.tensor([[[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]]]) # 1x1x7x7
- >>> # compute the response map
- >>> output = kornia.feature.CornerHarris()(input)
- tensor([[[[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., 1., 0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.]]]])
- """
-
- def __init__(self, k: torch.Tensor) -> None:
- super(CornerHarris, self).__init__()
- self.k: torch.Tensor = k
- # TODO: add as signature parameter
- self.kernel_size: Tuple[int, int] = (3, 3)
-
- 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) == 4:
- raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
- .format(input.shape))
- # compute the first order gradients with sobel operator
- # TODO: implement support for kernel different than three
- gradients: torch.Tensor = spatial_gradient(input)
- dx: torch.Tensor = gradients[:, :, 0]
- dy: torch.Tensor = gradients[:, :, 1]
-
- # compute the structure tensor M elements
- def g(x):
- return gaussian_blur2d(x, (3, 3), (1., 1.))
-
- dx2: torch.Tensor = g(dx * dx)
- dy2: torch.Tensor = g(dy * dy)
- dxy: torch.Tensor = g(dx * dy)
-
- det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
- trace_m: torch.Tensor = dx2 + dy2
-
- # compute the response map
- scores: torch.Tensor = det_m - self.k * trace_m ** 2
-
- # threshold
- # TODO: add as signature parameter ?
- scores = torch.clamp(scores, min=1e-6)
-
- # apply non maxima suppresion
- scores = non_maxima_suppression2d(scores, kernel_size=(3, 3))
-
- # normalize and return
- scores_max: torch.Tensor = F.adaptive_max_pool2d(scores, output_size=1)
- return scores / scores_max
-
-
-# functiona api
-
-
-def corner_harris(input: torch.Tensor, k: torch.Tensor) -> torch.Tensor:
- r"""Computes the Harris corner detection.
-
- See :class:`~kornia.feature.CornerHarris` for details.
- """
- return CornerHarris(k)(input)
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index a581fde2a..7b4cf3f89 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -1,12 +1,27 @@
-# flake8: noqa E127
-# flake8: noqa E128
-
+from typing import Union
import kornia
import math
import torch
import torch.nn.functional as F
+def raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:
+ """
+ Auxilary function, which verifies that input is a torch.tensor of [BxNx2x3] shape
+ Args:
+ laf
+ """
+ laf_message: str = "Invalid laf shape, we expect BxNx2x3. Got: {}".format(laf.shape)
+ if not torch.is_tensor(laf):
+ raise TypeError("Laf type is not a torch.Tensor. Got {}"
+ .format(type(laf)))
+ if len(laf.shape) != 4:
+ raise ValueError(laf_message)
+ if laf.size(2) != 2 or laf.size(3) != 3:
+ raise ValueError(laf_message)
+ return
+
+
def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
"""
Returns a scale of the LAFs
@@ -24,23 +39,49 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = kornia.get_laf_scale(input) # BxNx1x1
"""
- n_dims = len(LAF.size())
+ raise_error_if_laf_is_not_valid(LAF)
eps = 1e-10
- if (n_dims != 4):
- raise TypeError(
- "LAF shape should be must be [BxNx2x3]. "
- "Got {}".format(LAF.size())
- )
- out = LAF[..., 0:1, 0:1] * LAF[..., 1:2, 1:2] -\
- LAF[..., 1:2, 0:1] * LAF[..., 0:1, 1:2] + eps
+ out = LAF[..., 0:1, 0:1] * LAF[..., 1:2, 1:2] - LAF[..., 1:2, 0:1] * LAF[..., 0:1, 1:2] + eps
return out.abs().sqrt()
-def make_upright(LAF: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
+def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torch.Tensor:
+ """
+ Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient.
+ So the center, shape and orientation of the local feature stays the same, but the region area changes.
+
+ Args:
+ laf: (torch.Tensor): tensor [BxNx2x3] or [BxNx2x2].
+ scale_coef: (torch.Tensor): broadcastable tensor or float.
+
+
+ Returns:
+ torch.Tensor: tensor BxNx2x3 .
+
+ Shape:
+ - Input: :math: `(B, N, 2, 3)`
+ - Input: :math: `(B, N,)` or ()
+ - Output: :math: `(B, N, 1, 1)`
+
+ Example:
+ >>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
+ >>> scale = 0.5
+ >>> output = kornia.scale_laf(input, scale) # BxNx2x3
+ """
+ if (type(scale_coef) is not float) and (type(scale_coef) is not torch.Tensor):
+ raise TypeError(
+ "scale_coef should be float or torch.Tensor "
+ "Got {}".format(type(scale_coef)))
+ raise_error_if_laf_is_not_valid(laf)
+ centerless_laf: torch.Tensor = laf[:, :, :2, :2]
+ return torch.cat([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3)
+
+
+def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
"""
Rectifies the affine matrix, so that it becomes upright
Args:
- LAF: (torch.Tensor): tensor of LAFs.
+ laf: (torch.Tensor): tensor of LAFs.
eps (float): for safe division, (default 1e-9)
Returns:
@@ -53,23 +94,19 @@ def make_upright(LAF: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3
>>> output = kornia.make_upright(input) # BxNx2x3
"""
- n_dims = len(LAF.size())
- if (n_dims != 4):
- raise TypeError(
- "LAF shape should be must be [BxNx2x3]. "
- "Got {}".format(LAF.size())
- )
- det = get_laf_scale(LAF)
+ raise_error_if_laf_is_not_valid(laf)
+ det = get_laf_scale(laf)
+ scale = det
# The function is equivalent to doing 2x2 SVD and reseting rotation
# matrix to an identity: U, S, V = svd(LAF); LAF_upright = U * S.
- b2a2 = torch.sqrt(LAF[..., 0:1, 1:2]**2 + LAF[..., 0:1, 0:1]**2) + eps
- LAF1_ell = torch.cat([(b2a2 / det).contiguous(), # type: ignore
- torch.zeros_like(det)], dim=3) # type: ignore
- LAF2_ell = torch.cat([((LAF[..., 1:2, 1:2] * LAF[..., 0:1, 1:2] +
- LAF[..., 1:2, 0:1] * LAF[..., 0:1, 0:1]) / (b2a2 * det)),
+ b2a2 = torch.sqrt(laf[..., 0:1, 1:2] ** 2 + laf[..., 0:1, 0:1] ** 2) + eps
+ laf1_ell = torch.cat([(b2a2 / det).contiguous(),
+ torch.zeros_like(det)], dim=3)
+ laf2_ell = torch.cat([((laf[..., 1:2, 1:2] * laf[..., 0:1, 1:2] +
+ laf[..., 1:2, 0:1] * laf[..., 0:1, 0:1]) / (b2a2 * det)),
(det / b2a2).contiguous()], dim=3) # type: ignore
- return torch.cat([torch.cat([LAF1_ell, LAF2_ell], dim=2),
- LAF[..., :, 2:3]], dim=3)
+ laf_unit_scale = torch.cat([torch.cat([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
+ return scale_laf(laf_unit_scale, scale)
def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
@@ -94,7 +131,7 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
>>> output = kornia.ellipse_to_laf(input) # BxNx2x3
"""
n_dims = len(ells.size())
- if (n_dims != 3):
+ if n_dims != 3:
raise TypeError(
"ellipse shape should be must be [BxNx5]. "
"Got {}".format(ells.size()))
@@ -105,8 +142,7 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
"Got {}".format(ells.size()))
ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),
- torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)],
- dim=2).view(-1, 2, 2)
+ torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)
out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)
out = torch.cat([out, ells[..., :2].view(B, N, 2, 1)], dim=3)
return out
@@ -127,26 +163,18 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
- Input: :math:`(B, N, 2, 3)`
- Output: :math:`(B, N, n_pts, 2)`
"""
- n_dims = len(LAF.size())
- if (n_dims != 4):
- raise TypeError(
- "LAF shape should be must be [Nx2x3] or [BxNx2x3]. "
- "Got {}".format(LAF.size())
- )
+ raise_error_if_laf_is_not_valid(LAF)
B, N, _, _ = LAF.size()
pts = torch.cat([torch.sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
torch.ones(n_pts - 1, 1)], dim=1)
# Add origin to draw also the orientation
- pts = torch.cat([torch.tensor([0, 0, 1.]).view(1, 3),
- pts],
- dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
+ pts = torch.cat([torch.tensor([0, 0, 1.]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
pts = pts.to(LAF.device).to(LAF.dtype)
aux = torch.tensor([0, 0, 1.]).view(1, 1, 3).expand(B * N, 1, 3)
HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)
pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)
- return kornia.convert_points_from_homogeneous(
- pts_h.view(B, N, n_pts, 3))
+ return kornia.convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))
def get_laf_pts_to_draw(LAF: torch.Tensor,
@@ -171,6 +199,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor,
- Input: :math:`(B, N, 2, 3)`
- Output: :math:`(B, N, n_pts, 2)`
"""
+ raise_error_if_laf_is_not_valid(LAF)
pts = laf_to_boundary_points(LAF[img_idx:img_idx + 1])[0]
pts_np = pts.detach().permute(1, 0, 2).cpu().numpy()
return (pts_np[..., 0], pts_np[..., 1])
@@ -198,12 +227,7 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
- Input: :math:`(B, N, 2, 3)`
- Output: :math:`(B, N, 2, 3)`
"""
- n_dims = len(LAF.size())
- if (n_dims != 4):
- raise TypeError(
- "LAF shape should be must be [Nx2x3] or [BxNx2x3]. "
- "Got {}".format(LAF.size())
- )
+ raise_error_if_laf_is_not_valid(LAF)
n, ch, h, w = images.size()
w = float(w)
h = float(h)
@@ -237,11 +261,7 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
- Input: :math:`(B, N, 2, 3)`
- Output: :math:`(B, N, 2, 3)`
"""
- n_dims = len(LAF.size())
- if (n_dims != 4):
- raise TypeError(
- "LAF shape should be must be [BxNx2x3]. "
- "Got {}".format(LAF.size()))
+ raise_error_if_laf_is_not_valid(LAF)
n, ch, h, w = images.size()
w = float(w)
h = float(h)
@@ -271,11 +291,7 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor,
- Input: :math:`(B, CH, H, W)`, :math:`(B, N, 2, 3)`
- Output: :math:`(B, N, PS, PS)`
"""
- n_dims = len(LAF.size())
- if (n_dims != 4):
- raise TypeError(
- "LAF shape should be must be [BxNx2x3]. "
- "Got {}".format(LAF.size()))
+ raise_error_if_laf_is_not_valid(LAF)
B, N, _, _ = LAF.size()
num, ch, h, w = img.size()
@@ -291,71 +307,76 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor,
def extract_patches_simple(img: torch.Tensor,
- LAF: torch.Tensor,
- PS: int = 32) -> torch.Tensor:
+ laf: torch.Tensor,
+ PS: int = 32,
+ normalize_lafs_before_extraction: bool = True) -> torch.Tensor:
"""
Extract patches defined by LAFs from image tensor.
No smoothing applied, huge aliasing (better use extract_patches_from_pyramid)
Args:
- LAF: (torch.Tensor).
- images: (torch.Tensor) images, LAFs are detected in
+ img: (torch.Tensor) images, LAFs are detected in
+ laf: (torch.Tensor).
PS: (int) patch size, default = 32
-
+ normalize_lafs_before_extraction (bool) - if True, lafs are normalized to image size, default = True
Returns:
patches: (torch.Tensor), :math:`(B, N, CH, PS,PS)`
"""
+ raise_error_if_laf_is_not_valid(laf)
+ if normalize_lafs_before_extraction:
+ nlaf: torch.Tensor = normalize_laf(laf, img)
+ else:
+ nlaf = laf
num, ch, h, w = img.size()
- B, N, _, _ = LAF.size()
+ B, N, _, _ = laf.size()
out = []
# for loop temporarily, to be refactored
for i in range(B):
- grid = generate_patch_grid_from_normalized_LAF(
- img[i:i + 1], LAF[i:i + 1], PS)
- out.append(F.grid_sample(
- img[i:i + 1].expand(grid.size(0), ch, h, w),
- grid,
- padding_mode="border")
- )
+ grid = generate_patch_grid_from_normalized_LAF(img[i:i + 1], nlaf[i:i + 1], PS)
+ out.append(F.grid_sample(img[i:i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border"))
return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
def extract_patches_from_pyramid(img: torch.Tensor,
- LAF: torch.Tensor,
- PS: int = 32) -> torch.Tensor:
+ laf: torch.Tensor,
+ PS: int = 32,
+ normalize_lafs_before_extraction: bool = True) -> torch.Tensor:
"""
Extract patches defined by LAFs from image tensor.
Patches are extracted from appropriate pyramid level
Args:
- LAF: (torch.Tensor).
+ laf: (torch.Tensor).
images: (torch.Tensor) images, LAFs are detected in
PS: (int) patch size, default = 32
-
+ normalize_lafs_before_extraction (bool) - if True, lafs are normalized to image size, default = True
Returns:
patches: (torch.Tensor), :math:`(B, N, CH, PS,PS)`
"""
- B, N, _, _ = LAF.size()
+ raise_error_if_laf_is_not_valid(laf)
+ if normalize_lafs_before_extraction:
+ nlaf: torch.Tensor = normalize_laf(laf, img)
+ else:
+ nlaf = laf
+ B, N, _, _ = laf.size()
num, ch, h, w = img.size()
- scale = 2.0 * get_laf_scale(denormalize_laf(LAF, img)) / float(PS)
+ scale = 2.0 * get_laf_scale(denormalize_laf(nlaf, img)) / float(PS)
pyr_idx = (scale.log2() + 0.5).relu().long()
cur_img = img
cur_pyr_level = int(0)
- out = torch.zeros(B, N, ch, PS, PS).to(LAF.dtype)
- while min(cur_img.size(2), cur_img.size(3)) > PS:
+ out = torch.zeros(B, N, ch, PS, PS).to(nlaf.dtype)
+ while min(cur_img.size(2), cur_img.size(3)) >= PS:
num, ch, h, w = cur_img.size()
# for loop temporarily, to be refactored
for i in range(B):
- scale_mask = (pyr_idx[i] == cur_pyr_level).squeeze()
+ scale_mask = (pyr_idx[i] == cur_pyr_level).bool().squeeze()
if (scale_mask.float().sum()) == 0:
continue
- scale_mask = scale_mask.byte().view(-1)
+ scale_mask = scale_mask.bool().view(-1)
grid = generate_patch_grid_from_normalized_LAF(
cur_img[i:i + 1],
- LAF[i:i + 1, scale_mask, :, :],
+ nlaf[i:i + 1, scale_mask, :, :],
PS)
out[i, scale_mask, ..., :] = out[i, scale_mask, ..., :].clone() * 0\
- + F.grid_sample(cur_img[i:i + 1].expand(grid.size(0), ch, h, w),
- grid,
- padding_mode="border")
+ + F.grid_sample(cur_img[i:i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border")
cur_img = kornia.pyrdown(cur_img)
cur_pyr_level += 1
return out
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
new file mode 100644
index 000000000..9af6dedc4
--- /dev/null
+++ b/kornia/feature/orientation.py
@@ -0,0 +1,118 @@
+from typing import Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import math
+from kornia.filters import get_gaussian_kernel2d
+from kornia.filters import SpatialGradient
+from kornia.geometry import pi, angle_to_rotation_matrix
+from kornia.feature import (extract_patches_from_pyramid, make_upright,
+ normalize_laf, raise_error_if_laf_is_not_valid)
+from kornia.geometry import rad2deg
+
+
+class PassLAF(nn.Module):
+ """Dummy module to use instead of local feature orientation or affine shape estimator
+ """
+ def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore
+ """
+ Args:
+ laf: torch.Tensor: 4d tensor
+ img (torch.Tensor): the input image tensor
+
+ Return:
+ torch.Tensor: unchanged laf from the input."""
+ return laf
+
+
+class PatchDominantGradientOrientation(nn.Module):
+ def __init__(self,
+ patch_size: int = 32,
+ num_angular_bins: int = 36, eps: float = 1e-8):
+ super(PatchDominantGradientOrientation, self).__init__()
+ self.patch_size = patch_size
+ self.num_ang_bins = num_angular_bins
+ self.gradient = SpatialGradient('sobel', 1)
+ self.eps = eps
+ self.angular_smooth = nn.Conv1d(1, 1, kernel_size=3, padding=1, bias=False)
+ with torch.no_grad():
+ self.angular_smooth.weight[:] = torch.tensor([[[0.33, 0.34, 0.33]]])
+ sigma: float = float(self.patch_size) / math.sqrt(2.0)
+ self.weighting = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)
+ return
+
+ def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore
+ if not torch.is_tensor(patch):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(patch)))
+ if not len(patch.shape) == 4:
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
+ .format(patch.shape))
+ B, CH, W, H = patch.size()
+ if (W != self.patch_size) or (H != self.patch_size) or (CH != 1):
+ raise TypeError(
+ "input shape should be must be [Bx1x{}x{}]. "
+ "Got {}".format(self.patch_size, self.patch_size, patch.size()))
+ self.weighting = self.weighting.to(patch.dtype).to(patch.device)
+ self.angular_smooth = self.angular_smooth.to(patch.dtype).to(patch.device)
+ grads: torch.Tensor = self.gradient(patch)
+ # unpack the edges
+ gx: torch.Tensor = grads[:, :, 0]
+ gy: torch.Tensor = grads[:, :, 1]
+
+ mag: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps)
+ ori: torch.Tensor = torch.atan2(gy, gx + self.eps) + 2.0 * pi
+
+ o_big = float(self.num_ang_bins) * (ori + 1.0 * pi) / (2.0 * pi)
+ bo0_big = torch.floor(o_big)
+ wo1_big = o_big - bo0_big
+ bo0_big = bo0_big % self.num_ang_bins
+ bo1_big = (bo0_big + 1) % self.num_ang_bins
+ wo0_big = (1.0 - wo1_big) * mag # type: ignore
+ wo1_big = wo1_big * mag
+ ang_bins = []
+ for i in range(0, self.num_ang_bins):
+ ang_bins.append(F.adaptive_avg_pool2d((bo0_big == i).to(patch.dtype) * wo0_big +
+ (bo1_big == i).to(patch.dtype) * wo1_big, (1, 1)))
+ ang_bins = torch.cat(ang_bins, 1).view(-1, 1, self.num_ang_bins) # type: ignore
+ ang_bins = self.angular_smooth(ang_bins) # type: ignore
+ values, indices = ang_bins.view(-1, self.num_ang_bins).max(1) # type: ignore
+ angle = -((2. * pi * indices.to(patch.dtype) / float(self.num_ang_bins)) - pi) # type: ignore
+ return angle
+
+
+class LAFOrienter(nn.Module):
+ def __init__(self,
+ num_angular_bins: int = 36,
+ patch_size: int = 32):
+ super(LAFOrienter, self).__init__()
+ self.patch_size = patch_size
+ self.num_ang_bins = num_angular_bins
+ self.angle_detector = PatchDominantGradientOrientation(self.patch_size, self.num_ang_bins)
+ return
+
+ def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore
+ raise_error_if_laf_is_not_valid(laf)
+ img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
+ if not torch.is_tensor(img):
+ raise TypeError("img type is not a torch.Tensor. Got {}"
+ .format(type(img)))
+ if len(img.shape) != 4:
+ raise ValueError(img_message)
+ if laf.size(0) != img.size(0):
+ raise ValueError("Batch size of laf and img should be the same. Got {}, {}"
+ .format(img.size(0), laf.size(0)))
+ B, N = laf.shape[:2]
+ patches: torch.Tensor = extract_patches_from_pyramid(img,
+ laf,
+ self.patch_size).view(-1,
+ 1,
+ self.patch_size,
+ self.patch_size)
+ angles_radians: torch.Tensor = self.angle_detector(patches).view(B, N)
+ rotmat: torch.Tensor = angle_to_rotation_matrix(rad2deg(angles_radians)).view(B * N, 2, 2)
+
+ laf_out: torch.Tensor = torch.cat([torch.bmm(make_upright(laf).view(B * N, 2, 3)[:, :2, :2], rotmat),
+ laf.view(B * N, 2, 3)[:, :2, 2:]], dim=2).view(B, N, 2, 3)
+ return laf_out
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
new file mode 100644
index 000000000..029479087
--- /dev/null
+++ b/kornia/feature/responses.py
@@ -0,0 +1,313 @@
+from typing import Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from kornia.filters import spatial_gradient, gaussian_blur2d
+
+
+def harris_response(input: torch.Tensor,
+ k: Union[torch.Tensor, float] = 0.04,
+ grads_mode: str = 'sobel',
+ sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:
+ r"""Computes the Harris cornerness function. Function does not do
+ any normalization or nms.
+
+ The response map is computed according the following formulation:
+
+ .. math::
+ R = max(0, det(M) - k \cdot trace(M)^2)
+
+ where:
+
+ .. math::
+ M = \sum_{(x,y) \in W}
+ \begin{bmatrix}
+ I^{2}_x & I_x I_y \\
+ I_x I_y & I^{2}_y \\
+ \end{bmatrix}
+
+ and :math:`k` is an empirically determined constant
+ :math:`k ∈ [ 0.04 , 0.06 ]`
+
+ Args:
+ input: torch.Tensor: 4d tensor
+ k (torch.Tensor): the Harris detector free parameter.
+ grads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid
+ sigmas (torch.Tensor or None): coefficients to be multiplied by multichannel response.
+ Should be shape of (B)
+ It is necessary for performing non-maxima-suppression across different scale pyramid levels.
+ See also https://github.com/vlfeat/vlfeat/blob/1b9075fc42fe54b42f0e937f8b9a230d8e2c7701/vl/covdet.c#L874
+
+ Return:
+ torch.Tensor: the response map per channel.
+
+ Shape:
+ - Input: :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ Examples:
+ >>> input = torch.tensor([[[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]]) # 1x1x7x7
+ >>> # compute the response map
+ >>> output = harris_response(input, 0.04)
+ tensor([[[[0.0012, 0.0039, 0.0020, 0.0000, 0.0020, 0.0039, 0.0012],
+ [0.0039, 0.0065, 0.0040, 0.0000, 0.0040, 0.0065, 0.0039],
+ [0.0020, 0.0040, 0.0029, 0.0000, 0.0029, 0.0040, 0.0020],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0020, 0.0040, 0.0029, 0.0000, 0.0029, 0.0040, 0.0020],
+ [0.0039, 0.0065, 0.0040, 0.0000, 0.0040, 0.0065, 0.0039],
+ [0.0012, 0.0039, 0.0020, 0.0000, 0.0020, 0.0039, 0.0012]]]])
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ if sigmas is not None:
+ if not torch.is_tensor(sigmas):
+ raise TypeError("sigmas type is not a torch.Tensor. Got {}"
+ .format(type(sigmas)))
+ if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
+ raise ValueError("Invalid sigmas shape, we expect B == input.size(0). Got: {}".format(sigmas.shape))
+ gradients: torch.Tensor = spatial_gradient(input, grads_mode)
+ dx: torch.Tensor = gradients[:, :, 0]
+ dy: torch.Tensor = gradients[:, :, 1]
+
+ # compute the structure tensor M elements
+ def g(x):
+ return gaussian_blur2d(x, (3, 3), (1., 1.))
+
+ dx2: torch.Tensor = g(dx ** 2)
+ dy2: torch.Tensor = g(dy ** 2)
+ dxy: torch.Tensor = g(dx * dy)
+ 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))
+ if sigmas is not None:
+ scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
+ return scores
+
+
+def gftt_response(input: torch.Tensor,
+ grads_mode: str = 'sobel',
+ sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:
+ r"""Computes the Shi-Tomasi cornerness function. Function does not do
+ any normalization or nms.
+
+ The response map is computed according the following formulation:
+
+ .. math::
+ R = min(eig(M))
+
+ where:
+
+ .. math::
+ M = \sum_{(x,y) \in W}
+ \begin{bmatrix}
+ I^{2}_x & I_x I_y \\
+ I_x I_y & I^{2}_y \\
+ \end{bmatrix}
+
+ Args:
+ input (torch.Tensor): 4d tensor
+ grads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid
+ sigmas (torch.Tensor or None): coefficients to be multiplied by multichannel response.
+ Should be shape of (B)
+ It is necessary for performing non-maxima-suppression across different scale pyramid levels.
+ See also https://github.com/vlfeat/vlfeat/blob/1b9075fc42fe54b42f0e937f8b9a230d8e2c7701/vl/covdet.c#L874
+
+ Return:
+ torch.Tensor: the response map per channel.
+
+ Shape:
+ - Input: :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ Examples:
+ >>> input = torch.tensor([[[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]]) # 1x1x7x7
+ >>> # compute the response map
+ >>> output = gftt_response(input)
+ tensor([[[[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155],
+ [0.0334, 0.0575, 0.0339, 0.0000, 0.0339, 0.0575, 0.0334],
+ [0.0194, 0.0339, 0.0497, 0.0000, 0.0497, 0.0339, 0.0194],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0194, 0.0339, 0.0497, 0.0000, 0.0497, 0.0339, 0.0194],
+ [0.0334, 0.0575, 0.0339, 0.0000, 0.0339, 0.0575, 0.0334],
+ [0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ gradients: torch.Tensor = spatial_gradient(input, grads_mode)
+ dx: torch.Tensor = gradients[:, :, 0]
+ dy: torch.Tensor = gradients[:, :, 1]
+
+ # compute the structure tensor M elements
+ def g(x):
+ return gaussian_blur2d(x, (3, 3), (1., 1.))
+
+ dx2: torch.Tensor = g(dx ** 2)
+ dy2: torch.Tensor = g(dy ** 2)
+ dxy: torch.Tensor = g(dx * dy)
+
+ det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
+ trace_m: torch.Tensor = dx2 + dy2
+
+ e1: torch.Tensor = 0.5 * (trace_m + torch.sqrt((trace_m ** 2 - 4 * det_m).abs()))
+ e2: torch.Tensor = 0.5 * (trace_m - torch.sqrt((trace_m ** 2 - 4 * det_m).abs()))
+
+ scores: torch.Tensor = torch.min(e1, e2)
+ if sigmas is not None:
+ scores = scores * sigmas.pow(2).view(-1, 1, 1, 1)
+ return scores
+
+
+def hessian_response(input: torch.Tensor,
+ grads_mode: str = 'sobel',
+ sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:
+ r"""Computes the absolute of determinant of the Hessian matrix. Function does not do
+ any normalization or nms.
+
+ The response map is computed according the following formulation:
+
+ .. math::
+ R = det(H)
+ where:
+
+ .. math::
+ M = \sum_{(x,y) \in W}
+ \begin{bmatrix}
+ I_{xx} & I_{xy} \\
+ I_{xy} & I_yy \\
+ \end{bmatrix}
+
+
+ Args:
+ input: torch.Tensor: 4d tensor
+ grads_mode (string): can be 'sobel' for standalone use or 'diff' for use on Gaussian pyramid
+ sigmas (torch.Tensor or None): coefficients to be multiplied by multichannel response.
+ Should be shape of (B)
+ It is necessary for performing non-maxima-suppression across different scale pyramid levels.
+ See also https://github.com/vlfeat/vlfeat/blob/1b9075fc42fe54b42f0e937f8b9a230d8e2c7701/vl/covdet.c#L874
+
+ Return:
+ torch.Tensor: the response map per channel.
+
+ Shape:
+ - Input: :math:`(B, C, H, W)`
+ - Output: :math:`(B, C, H, W)`
+
+ Examples:
+ >>> input = torch.tensor([[[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]]) # 1x1x7x7
+ >>> # compute the response map
+ >>> output = hessian_response(input)
+ tensor([[[[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155],
+ [0.0334, 0.0575, 0.0339, 0.0000, 0.0339, 0.0575, 0.0334],
+ [0.0194, 0.0339, 0.0497, 0.0000, 0.0497, 0.0339, 0.0194],
+ [0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
+ [0.0194, 0.0339, 0.0497, 0.0000, 0.0497, 0.0339, 0.0194],
+ [0.0334, 0.0575, 0.0339, 0.0000, 0.0339, 0.0575, 0.0334],
+ [0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ if sigmas is not None:
+ if not torch.is_tensor(sigmas):
+ raise TypeError("sigmas type is not a torch.Tensor. Got {}"
+ .format(type(sigmas)))
+ if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
+ raise ValueError("Invalid sigmas shape, we expect B == input.size(0). Got: {}"
+ .format(sigmas.shape))
+ gradients: torch.Tensor = spatial_gradient(input, grads_mode, 2)
+ dxx: torch.Tensor = gradients[:, :, 0]
+ dxy: torch.Tensor = gradients[:, :, 1]
+ dyy: torch.Tensor = gradients[:, :, 2]
+
+ scores: torch.Tensor = torch.abs(dxx * dyy - dxy ** 2)
+ if sigmas is not None:
+ scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
+ return scores
+
+
+class CornerHarris(nn.Module):
+ def __init__(self, k: Union[float, torch.Tensor],
+ grads_mode='sobel') -> None:
+ super(CornerHarris, self).__init__()
+ if type(k) is float:
+ self.register_buffer('k', torch.tensor(k))
+ else:
+ self.register_buffer('k', k) # type: ignore
+ self.grads_mode: str = grads_mode
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(k=' + str(self.k) + ', ' +\
+ 'grads_mode=' + self.grads_mode + ')'
+
+ def forward(self, input: torch.Tensor, # type: ignore
+ sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:
+ return harris_response(input, self.k, self.grads_mode, sigmas) # type: ignore
+
+
+class CornerGFTT(nn.Module):
+ def __init__(self, grads_mode='sobel') -> None:
+ super(CornerGFTT, self).__init__()
+ self.grads_mode: str = grads_mode
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ 'grads_mode=' + self.grads_mode + ')'
+
+ def forward(self, input: torch.Tensor, # type: ignore
+ sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:
+ return gftt_response(input, self.grads_mode, sigmas)
+
+
+class BlobHessian(nn.Module):
+ def __init__(self, grads_mode='sobel') -> None:
+ super(BlobHessian, self).__init__()
+ self.grads_mode: str = grads_mode
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ 'grads_mode=' + self.grads_mode + ')'
+
+ def forward(self, input: torch.Tensor, # type: ignore
+ sigmas: Union[torch.Tensor, None] = None) -> torch.Tensor:
+ return hessian_response(input, self.grads_mode, sigmas)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
new file mode 100644
index 000000000..c04b9a362
--- /dev/null
+++ b/kornia/feature/scale_space_detector.py
@@ -0,0 +1,141 @@
+from typing import Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from kornia.geometry import angle_to_rotation_matrix
+from kornia.feature.responses import BlobHessian
+from kornia.geometry import ConvSoftArgmax3d
+from kornia.feature.orientation import PassLAF
+from kornia.feature.laf import (
+ denormalize_laf,
+ normalize_laf)
+from kornia.geometry.transform import ScalePyramid
+
+
+def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:
+ """Auxilary function for ScaleSpaceDetector. Converts scale level index from ConvSoftArgmax3d
+ to the actual scale, using the sigmas from the ScalePyramid output
+ Args:
+ max_coords: (torch.Tensor): tensor [BxNx3].
+ sigmas: (torch.Tensor): tensor [BxNxD], D >= 1
+
+ Returns:
+ torch.Tensor: tensor [BxNx3].
+
+ """
+ # depth (scale) in coord_max is represented as (float) index, not the scale yet.
+ # we will interpolate the scale using pytorch.grid_sample function
+ # Because grid_sample is for 4d input only, we will create fake 2nd dimension
+ # ToDo: replace with 3d input, when grid_sample will start to support it
+
+ # Reshape for grid shape
+ B, N, _ = max_coords.shape
+ L: int = sigmas.size(1)
+ scale_coords = max_coords[:, :, 0].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(sigmas[0].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)
+ return out
+
+
+class ScaleSpaceDetector(nn.Module):
+ def __init__(self,
+ num_features: int = 500,
+ mr_size: float = 5.192,
+ scale_pyr_module: nn.Module = ScalePyramid(3, 1.6, 10),
+ resp_module: nn.Module = BlobHessian(),
+ nms_module: nn.Module = ConvSoftArgmax3d((3, 3, 3),
+ (2, 2, 2),
+ (1, 1, 1),
+ normalized_coordinates=False,
+ output_value=True),
+ ori_module: nn.Module = PassLAF(),
+ aff_module: nn.Module = PassLAF()):
+ super(ScaleSpaceDetector, self).__init__()
+ self.mr_size = mr_size
+ self.num_features = num_features
+ self.scale_pyr = scale_pyr_module
+ self.resp = resp_module
+ self.nms = nms_module
+ self.ori = ori_module
+ self.aff = aff_module
+ return
+
+ def __repr__(self):
+ return self.__class__.__name__ + '('\
+ 'num_features=' + str(self.num_features) + ', ' + \
+ 'mr_size=' + str(self.mr_size) + ', ' + \
+ 'scale_pyr=' + self.scale_pyr.__repr__() + ', ' + \
+ 'resp=' + self.resp.__repr__() + ', ' + \
+ 'nms=' + self.nms.__repr__() + ', ' + \
+ 'ori=' + self.ori.__repr__() + ', ' + \
+ 'aff=' + self.aff.__repr__() + ')'
+
+ def detect(self, img: torch.Tensor, num_feats: int) -> Tuple[torch.Tensor, torch.Tensor]:
+ sp, sigmas, pix_dists = self.scale_pyr(img)
+ all_responses = []
+ all_lafs = []
+ for oct_idx, octave in enumerate(sp):
+ sigmas_oct = sigmas[oct_idx]
+ pix_dists_oct = pix_dists[oct_idx]
+ B, L, CH, H, W = octave.size()
+ # Run response function
+ oct_resp = self.resp(octave.view(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)
+
+ # Differentiable nms
+ coord_max, response_max = self.nms(oct_resp)
+
+ # Now, lets crop out some small responses
+ responses_flatten = response_max.view(response_max.size(0), -1) # [B * N, 3]
+ 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:
+ resp_flat_best, idxs = torch.topk(responses_flatten, k=num_feats, dim=1)
+ max_coords_best = max_coords_flatten[:, idxs.view(-1)]
+ else:
+ resp_flat_best = responses_flatten
+ max_coords_best = max_coords_flatten
+ 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)
+
+ # Create local affine frames (LAFs)
+ rotmat = angle_to_rotation_matrix(torch.zeros(B, N))
+ 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)
+ # Normalize LAFs
+ current_lafs = normalize_laf(current_lafs, octave[:, 0]) # We don`t need # of scale levels, only shape
+
+ all_responses.append(resp_flat_best)
+ all_lafs.append(current_lafs)
+
+ # Sort and keep best n
+ responses: torch.Tensor = torch.cat(all_responses, dim=1)
+ lafs: torch.Tensor = torch.cat(all_lafs, dim=1)
+ responses, idxs = torch.topk(responses, k=num_feats, dim=1)
+ lafs = lafs[:, idxs.view(-1), :, :]
+ return responses, denormalize_laf(lafs, img)
+
+ def forward(self, img: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
+ responses, lafs = self.detect(img, self.num_features)
+ lafs = self.aff(lafs, img)
+ lafs = self.ori(lafs, img)
+ return lafs, responses
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index 8680aa0b7..902ce60f6 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -55,9 +55,14 @@ class SpatialGradient(nn.Module):
# convolve input tensor with sobel kernel
kernel_flip: torch.Tensor = kernel.flip(-3)
- # Pad with "replicate for spatial dims, but with zeros for channel dim
- padded_inp: torch.Tensor = F.pad(F.pad(input, [1, 1, 1, 1], 'replicate')[:, :, None], # noqa
- [0, 0, 0, 0, 1, 1], 'constant', 0)
+ # Pad with "replicate for spatial dims, but with zeros for channel
+ spatial_pad = [self.kernel.size(1) // 2,
+ self.kernel.size(1) // 2,
+ self.kernel.size(2) // 2,
+ self.kernel.size(2) // 2]
+ channel_pad = [0, 0, 0, 0, self.order, self.order]
+ padded_inp: torch.Tensor = F.pad(F.pad(input, spatial_pad, 'replicate')[:, :, None],
+ channel_pad, 'constant', 0)
return F.conv3d(padded_inp, kernel_flip, padding=0, groups=c)
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index 55ab8fb4b..2bff65407 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -4,3 +4,5 @@ from kornia.geometry.linalg import *
from kornia.geometry.transform import *
from kornia.geometry.warp import *
from kornia.geometry.depth import *
+from kornia.geometry.dsnt import *
+from kornia.geometry.spatial_soft_argmax import *
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 562fc5c68..fe80d5770 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -21,6 +21,8 @@ __all__ = [
"denormalize_pixel_coordinates",
"normalize_pixel_coordinates",
"normalize_quaternion",
+ "denormalize_pixel_coordinates3d",
+ "normalize_pixel_coordinates3d",
]
@@ -620,7 +622,7 @@ def normalize_pixel_coordinates(
torch.tensor(width), torch.tensor(height)
]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
- factor: torch.Tensor = torch.tensor(2.) / (hw - 1)
+ factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(1e-8)
return factor * pixel_coordinates - 1
@@ -651,6 +653,71 @@ def denormalize_pixel_coordinates(
torch.tensor(width), torch.tensor(height)
]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
- factor: torch.Tensor = torch.tensor(2.) / (hw - 1)
+ factor: torch.Tensor = torch.tensor(2.) / (hw - 1).clamp(1e-8)
+
+ return torch.tensor(1.) / factor * (pixel_coordinates + 1)
+
+
+def normalize_pixel_coordinates3d(
+ pixel_coordinates: torch.Tensor,
+ depth: int,
+ height: int,
+ width: int) -> torch.Tensor:
+ r"""Normalize pixel coordinates between -1 and 1.
+
+ Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
+
+ Args:
+ pixel_coordinate (torch.Tensor): the grid with pixel coordinates.
+ Shape can be :math:`(*, 3)`.
+ depth (int): the maximum depth in the z-axis.
+ height (int): the maximum height in the y-axis.
+ width (int): the maximum width in the x-axis.
+
+ Return:
+ torch.Tensor: the normalized pixel coordinates.
+ """
+ if pixel_coordinates.shape[-1] != 3:
+ raise ValueError("Input pixel_coordinates must be of shape (*, 3). "
+ "Got {}".format(pixel_coordinates.shape))
+ # compute normalization factor
+ dhw: torch.Tensor = torch.stack([
+ torch.tensor(depth), torch.tensor(width), torch.tensor(height)
+ ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+
+ factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(1e-8)
+
+ return factor * pixel_coordinates - 1
+
+
+def denormalize_pixel_coordinates3d(
+ pixel_coordinates: torch.Tensor,
+ depth: int,
+ height: int,
+ width: int) -> torch.Tensor:
+ r"""Denormalize pixel coordinates.
+
+ The input is assumed to be -1 if on extreme left, 1 if on
+ extreme right (x = w-1).
+
+ Args:
+ pixel_coordinate (torch.Tensor): the normalized grid coordinates.
+ Shape can be :math:`(*, 3)`.
+ depth (int): the maximum depth in the x-axis.
+ height (int): the maximum height in the y-axis.
+ width (int): the maximum width in the x-axis.
+
+ Return:
+ torch.Tensor: the denormalized pixel coordinates.
+ """
+ if pixel_coordinates.shape[-1] != 3:
+ raise ValueError("Input pixel_coordinates must be of shape (*, 3). "
+ "Got {}".format(pixel_coordinates.shape))
+ # compute normalization factor
+ dhw: torch.Tensor = torch.stack([
+ torch.tensor(depth), torch.tensor(width), torch.tensor(height)
+ ]).to(pixel_coordinates.device).to(pixel_coordinates.dtype)
+
+ factor: torch.Tensor = torch.tensor(2.) / (dhw - 1).clamp(1e-8)
return torch.tensor(1.) / factor * (pixel_coordinates + 1)
diff --git a/kornia/contrib/dsnt.py b/kornia/geometry/dsnt.py
similarity index 100%
rename from kornia/contrib/dsnt.py
rename to kornia/geometry/dsnt.py
diff --git a/kornia/geometry/spatial_soft_argmax.py b/kornia/geometry/spatial_soft_argmax.py
new file mode 100644
index 000000000..fa975e9c8
--- /dev/null
+++ b/kornia/geometry/spatial_soft_argmax.py
@@ -0,0 +1,469 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from kornia.geometry import dsnt
+from kornia.utils import create_meshgrid, create_meshgrid3d
+from kornia.geometry import normalize_pixel_coordinates, normalize_pixel_coordinates3d
+from typing import Tuple, Union
+
+
+def _get_window_grid_kernel2d(h: int, w: int) -> torch.Tensor:
+ '''Helper function, which generates a kernel to
+ with window coordinates, residual to window center
+ Args:
+ h (int): kernel height
+ w (int): kernel width
+ Returns:
+ conv_kernel (torch.Tensor) [2x1xhxw]
+ '''
+ window_grid2d = create_meshgrid(h, w, False)
+ window_grid2d = normalize_pixel_coordinates(window_grid2d, h, w)
+ conv_kernel = window_grid2d.permute(3, 0, 1, 2)
+ return conv_kernel
+
+
+def _get_center_kernel2d(h: int, w: int) -> torch.Tensor:
+ '''Helper function, which generates a kernel to
+ return center coordinates, when applied with F.conv2d to 2d coordinates grid
+ Args:
+ h (int): kernel height
+ w (int): kernel width
+ Returns:
+ conv_kernel (torch.Tensor) [2x2xhxw]
+ '''
+ center_kernel = torch.zeros(2, 2, h, w)
+ center_kernel[0, 0, h // 2, w // 2] = 1.0
+ center_kernel[1, 1, h // 2, w // 2] = 1.0
+ return center_kernel
+
+
+def _get_center_kernel3d(d: int, h: int, w: int) -> torch.Tensor:
+ '''Helper function, which generates a kernel to
+ return center coordinates, when applied with F.conv2d to 3d coordinates grid
+ Args:
+ d (int): kernel depth
+ h (int): kernel height
+ w (int): kernel width
+ Returns:
+ conv_kernel (torch.Tensor) [3x3xdxhxw]
+ '''
+ center_kernel = torch.zeros(3, 3, d, h, w)
+ center_kernel[0, 0, d // 2, h // 2, w // 2] = 1.0
+ center_kernel[1, 1, d // 2, h // 2, w // 2] = 1.0
+ center_kernel[2, 2, d // 2, h // 2, w // 2] = 1.0
+ return center_kernel
+
+
+def _get_window_grid_kernel3d(d: int, h: int, w: int) -> torch.Tensor:
+ '''Helper function, which generates a kernel to return coordinates,
+ residual to window center
+ Args:
+ d (int): kernel depth
+ h (int): kernel height
+ w (int): kernel width
+ Returns:
+ conv_kernel (torch.Tensor) [3x1xdxhxw]
+ '''
+ grid2d = create_meshgrid(h, w, True)
+ if d > 1:
+ z = torch.linspace(-1, 1, d).view(d, 1, 1, 1)
+ else: # only onr channel with index == 0
+ z = torch.zeros(1, 1, 1, 1)
+ grid3d = torch.cat([z.repeat(1, h, w, 1).contiguous(), grid2d.repeat(d, 1, 1, 1)], dim=3)
+ conv_kernel = grid3d.permute(3, 0, 1, 2).unsqueeze(1)
+ return conv_kernel
+
+
+class ConvSoftArgmax2d(nn.Module):
+ def __init__(self,
+ kernel_size: Tuple[int, int] = (3, 3),
+ stride: Tuple[int, int] = (1, 1),
+ padding: Tuple[int, int] = (1, 1),
+ temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8,
+ output_value: bool = False) -> None:
+ super(ConvSoftArgmax2d, self).__init__()
+ self.kernel_size = kernel_size
+ self.stride = stride
+ self.padding = padding
+ self.temperature = temperature
+ self.normalized_coordinates = normalized_coordinates
+ self.eps = eps
+ self.output_value = output_value
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'kernel_size=' + str(self.kernel_size) +\
+ ', ' + 'stride=' + str(self.stride) +\
+ ', ' + 'padding=' + str(self.padding) +\
+ ', ' + 'temperature=' + str(self.temperature) +\
+ ', ' + 'normalized_coordinates=' + str(self.normalized_coordinates) +\
+ ', ' + 'eps=' + str(self.eps) +\
+ ', ' + 'output_value=' + str(self.output_value) + ')'
+
+ def forward(self, x: torch.Tensor): # type: ignore
+ return conv_soft_argmax2d(x,
+ self.kernel_size,
+ self.stride,
+ self.padding,
+ self.temperature,
+ self.normalized_coordinates,
+ self.eps,
+ self.output_value)
+
+
+class ConvSoftArgmax3d(nn.Module):
+ def __init__(self,
+ kernel_size: Tuple[int, int, int] = (3, 3, 3),
+ stride: Tuple[int, int, int] = (1, 1, 1),
+ padding: Tuple[int, int, int] = (1, 1, 1),
+ temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ normalized_coordinates: bool = False,
+ eps: float = 1e-8,
+ output_value: bool = True) -> None:
+ super(ConvSoftArgmax3d, self).__init__()
+ self.kernel_size = kernel_size
+ self.stride = stride
+ self.padding = padding
+ self.temperature = temperature
+ self.normalized_coordinates = normalized_coordinates
+ self.eps = eps
+ self.output_value = output_value
+ return
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'kernel_size=' + str(self.kernel_size) +\
+ ', ' + 'stride=' + str(self.stride) +\
+ ', ' + 'padding=' + str(self.padding) +\
+ ', ' + 'temperature=' + str(self.temperature) +\
+ ', ' + 'normalized_coordinates=' + str(self.normalized_coordinates) +\
+ ', ' + 'eps=' + str(self.eps) +\
+ ', ' + 'output_value=' + str(self.output_value) + ')'
+
+ def forward(self, x: torch.Tensor): # type: ignore
+ return conv_soft_argmax3d(x,
+ self.kernel_size,
+ self.stride,
+ self.padding,
+ self.temperature,
+ self.normalized_coordinates,
+ self.eps,
+ self.output_value)
+
+
+def conv_soft_argmax2d(input: torch.Tensor,
+ kernel_size: Tuple[int, int] = (3, 3),
+ stride: Tuple[int, int] = (1, 1),
+ padding: Tuple[int, int] = (1, 1),
+ temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8,
+ output_value: bool = False) -> Union[torch.Tensor,
+ Tuple[torch.Tensor, torch.Tensor]]:
+ """
+ Function that computes the convolutional spatial Soft-Argmax 2D over the windows
+ of a given input heatmap. Function has two outputs: argmax coordinates and the softmaxpooled heatmap values
+ themselves.
+
+ On each window, the function computed is:
+
+ .. math::
+ ij(X) = \frac{\sum_{(i,j) * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}
+ val(X) = \frac{\sum_{x * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}
+
+ - where T is temperature.
+
+ Args:
+ kernel_size (Tuple([int,int])): the size of the window
+ stride (Tuple([int,int])): the stride of the window.
+ padding (Tuple([int,int])): input zero padding
+ temperature (torch.Tensor): factor to apply to input. Default is 1.
+ normalized_coordinates (bool): whether to return the
+ coordinates normalized in the range of [-1, 1]. Otherwise,
+ it will return the coordinates in the range of the input shape.
+ Default is True.
+ eps (float): small value to avoid zero division. Default is 1e-8.
+ output_value(bool): if True, val is outputed, if False, only ij
+
+
+ Shape:
+ - Input: :math:`(N, C, H_{in}, W_{in})`
+ - Output: math:`(N, C, 2, H_{out}, W_{out})`, :math:`(N, C, H_{out}, W_{out})`, where
+
+ .. math::
+ H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] -
+ (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
+
+ .. math::
+ W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] -
+ (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
+
+ Examples::
+
+ >>> input = torch.randn(20, 16, 50, 32)
+ >>> nms_coords, nms_val = conv_soft_argmax2d(input, (3,3), (2,2), (1,1))
+ """
+ if not torch.is_tensor(input):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ if temperature <= 0:
+ raise ValueError("Temperature should be positive float or tensor. Got: {}"
+ .format(temperature))
+
+ b, c, h, w = input.shape
+ input = input.view(b * c, 1, h, w)
+
+ center_kernel = _get_center_kernel2d(kernel_size[0], kernel_size[1])
+ window_kernel = _get_window_grid_kernel2d(kernel_size[0], kernel_size[1])
+ window_kernel = window_kernel.to(input.device).to(input.dtype)
+
+ x_exp = (input / temperature).exp()
+
+ # F.avg_pool2d(.., divisor_override = 1.0) - proper way for sum pool in PyTorch 1.2.
+ # Not available yet in version 1.0, so let's do manually
+ pool_coef: float = float(kernel_size[0] * kernel_size[1])
+
+ # softmax denominator
+ den = pool_coef * F.avg_pool2d(x_exp,
+ kernel_size,
+ stride=stride,
+ padding=padding) + 1e-12
+
+ x_softmaxpool = pool_coef * F.avg_pool2d(x_exp * input,
+ kernel_size,
+ stride=stride,
+ padding=padding) / den
+ x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3))
+
+ # We need to output also coordinates
+ # Pooled window center coordinates
+ grid_global: torch.Tensor = create_meshgrid(h, w, False).permute(0, 3, 1, 2)
+ grid_global = grid_global.to(input.device).to(input.dtype)
+ grid_global_pooled = F.conv2d(grid_global,
+ center_kernel.to(input.device).to(input.dtype),
+ stride=stride,
+ padding=padding)
+
+ # Coordinates of maxima residual to window center
+ # prepare kernel
+ coords_max: torch.Tensor = F.conv2d(x_exp,
+ window_kernel,
+ stride=stride,
+ padding=padding)
+
+ coords_max = coords_max / den.expand_as(coords_max)
+ coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
+ # [:,:, 0, ...] is x
+ # [:,:, 1, ...] is y
+
+ if normalized_coordinates:
+ coords_max = normalize_pixel_coordinates(coords_max.permute(0, 2, 3, 1), h, w)
+ coords_max = coords_max.permute(0, 3, 1, 2)
+
+ # Back B*C -> (b, c)
+ coords_max = coords_max.view(b, c, 2, coords_max.size(2), coords_max.size(3))
+
+ if output_value:
+ return coords_max, x_softmaxpool
+ return coords_max
+
+
+def conv_soft_argmax3d(input: torch.Tensor,
+ kernel_size: Tuple[int, int, int] = (3, 3, 3),
+ stride: Tuple[int, int, int] = (1, 1, 1),
+ padding: Tuple[int, int, int] = (1, 1, 1),
+ 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]]:
+ """
+ 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.
+
+ On each window, the function computed is:
+
+ .. math::
+ ijk(X) = \frac{\sum_{(i,j,k) * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}
+
+ val(X) = \frac{\sum_{x * exp(x / T) \in X}} {\sum_{exp(x / T) \in X}}
+
+ - where T is temperature.
+ [:,:, 0, ...] is i == depth (scale)
+ [:,:, 1, ...] is j == x
+ [:,:, 2, ...] is k == y
+
+ Args:
+ kernel_size (Tuple([int,int,int])): the size of the window
+ stride (Tuple([int,int,int])): the stride of the window.
+ padding (Tuple([int,int,int])): input zero padding
+ temperature (torch.Tensor): factor to apply to input. Default is 1.
+ normalized_coordinates (bool): whether to return the
+ coordinates normalized in the range of [-1, 1]. Otherwise,
+ 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
+
+
+ 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_soft_argmax2d(input, (3, 3, 3), (1, 2, 2), (0, 1, 1))
+ """
+ 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))
+ if temperature <= 0:
+ raise ValueError("Temperature should be positive float or tensor. Got: {}"
+ .format(temperature))
+
+ b, c, d, h, w = input.shape
+ input = input.view(b * c, 1, d, h, w)
+
+ center_kernel = _get_center_kernel3d(kernel_size[0], kernel_size[1], kernel_size[2])
+ window_kernel = _get_window_grid_kernel3d(kernel_size[0], kernel_size[1], kernel_size[2])
+ window_kernel = window_kernel.to(input.device).to(input.dtype)
+
+ x_exp = (input / temperature).exp()
+
+ pool_coef: float = float(kernel_size[0] * kernel_size[1] * kernel_size[2])
+
+ # softmax denominator
+ den = pool_coef * F.avg_pool3d(x_exp.view(input.size()),
+ kernel_size,
+ stride=stride,
+ padding=padding) + 1e-12
+
+ x_softmaxpool = pool_coef * F.avg_pool3d(x_exp.view(input.size()) * 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(d, h, w, False).permute(0, 4, 1, 2, 3)
+ grid_global = grid_global.to(input.device).to(input.dtype)
+ grid_global_pooled = F.conv3d(grid_global,
+ center_kernel.to(input.device).to(input.dtype),
+ stride=stride,
+ padding=padding)
+
+ # Coordinates of maxima residual to window center
+ # prepare kernel
+ coords_max: torch.Tensor = F.conv3d(x_exp,
+ window_kernel,
+ stride=stride,
+ padding=padding)
+
+ coords_max = coords_max / den.expand_as(coords_max)
+ coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
+ # [:,:, 0, ...] is depth (scale)
+ # [:,:, 1, ...] is x
+ # [:,:, 2, ...] is y
+
+ if normalized_coordinates:
+ coords_max = normalize_pixel_coordinates3d(coords_max.permute(0, 2, 3, 4, 1), d, h, w)
+ coords_max = coords_max.permute(0, 4, 1, 2, 3)
+
+ # 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
+
+
+def spatial_soft_argmax2d(
+ input: torch.Tensor,
+ temperature: torch.Tensor = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8) -> torch.Tensor:
+ r"""Function that computes the Spatial Soft-Argmax 2D
+ of a given input heatmap.
+
+ Returns the index of the maximum 2d coordinates of the give map.
+ The output order is x-coord and y-coord.
+
+ Arguments:
+ temperature (torch.Tensor): factor to apply to input. Default is 1.
+ normalized_coordinates (bool): whether to return the
+ coordinates normalized in the range of [-1, 1]. Otherwise,
+ it will return the coordinates in the range of the input shape.
+ Default is True.
+ eps (float): small value to avoid zero division. Default is 1e-8.
+
+ Shape:
+ - Input: :math:`(B, N, H, W)`
+ - Output: :math:`(B, N, 2)`
+
+ Examples:
+ >>> input = torch.tensor([[[
+ [0., 0., 0.],
+ [0., 10., 0.],
+ [0., 0., 0.]]]])
+ >>> coords = kornia.spatial_soft_argmax2d(input, False)
+ tensor([[[1.0000, 1.0000]]])
+ """
+ input_soft: torch.Tensor = dsnt.spatial_softmax_2d(input, temperature)
+ output: torch.Tensor = dsnt.spatial_softargmax_2d(input_soft,
+ normalized_coordinates)
+ return output
+
+
+class SpatialSoftArgmax2d(nn.Module):
+ r"""Function that computes the Spatial Soft-Argmax 2D of a given heatmap.
+
+ See :class:`~kornia.contrib.spatial_soft_argmax2d` for details.
+ """
+
+ def __init__(self,
+ temperature: torch.Tensor = torch.tensor(1.0),
+ normalized_coordinates: bool = True,
+ eps: float = 1e-8) -> None:
+ super(SpatialSoftArgmax2d, self).__init__()
+ self.temperature: torch.Tensor = temperature
+ self.normalized_coordinates: bool = normalized_coordinates
+ self.eps: float = eps
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(temperature=' + str(self.temperature) + ', ' +\
+ 'normalized_coordinates=' + str(self.normalized_coordinates) + ', ' + \
+ 'eps=' + str(self.eps) + ')'
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ return spatial_soft_argmax2d(input, self.temperature,
+ self.normalized_coordinates, self.eps)
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 83680c2f3..b4f7f4c6f 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -148,6 +148,14 @@ class ScalePyramid(nn.Module):
self.sigma_step = 2 ** (1. / float(self.n_levels))
return
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(n_levels=' + str(self.n_levels) + ', ' +\
+ 'init_sigma=' + str(self.init_sigma) + ', ' + \
+ 'min_size=' + str(self.min_size) + ', ' + \
+ 'border=' + str(self.border) + ', ' + \
+ 'sigma_step=' + str(self.sigma_step) + ')'
+
def get_kernel_size(self, sigma: float):
ksize = int(2.0 * 3.0 * sigma + 1.0)
if ksize % 2 == 0:
diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.py
index 0f9f9a911..59c1e7380 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -1,5 +1,5 @@
from .one_hot import one_hot
-from .grid import create_meshgrid
+from .grid import create_meshgrid, create_meshgrid3d
from .image import tensor_to_image, image_to_tensor
from .pointcloud_io import save_pointcloud_ply, load_pointcloud_ply
@@ -8,6 +8,7 @@ from kornia.utils.metrics import *
__all__ = [
"one_hot",
"create_meshgrid",
+ "create_meshgrid3d",
"tensor_to_image",
"image_to_tensor",
"save_pointcloud_ply",
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index c2c32c04d..0957f7386 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -17,7 +17,7 @@ def create_meshgrid(
Args:
height (int): the image height (rows).
width (int): the image width (cols).
- normalized_coordinates (Optional[bool]): wether to normalize
+ normalized_coordinates (Optional[bool]): whether to normalize
coordinates in the range [-1, 1] in order to be consistent with the
PyTorch function grid_sample.
@@ -37,3 +37,36 @@ def create_meshgrid(
base_grid: torch.Tensor = torch.stack(
torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
return torch.unsqueeze(base_grid, dim=0).permute(0, 2, 3, 1) # 1xHxWx2
+
+
+def create_meshgrid3d(
+ depth: int,
+ height: int,
+ width: int,
+ normalized_coordinates: Optional[bool] = True) -> torch.Tensor:
+ """Generates a coordinate grid for an image.
+
+ When the flag `normalized_coordinates` is set to True, the grid is
+ normalized to be in the range [-1,1] to be consistent with the pytorch
+ function grid_sample.
+ http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample
+
+ Args:
+ depth (int): the image depth (channels).
+ height (int): the image height (rows).
+ width (int): the image width (cols).
+ normalized_coordinates (Optional[bool]): wether to normalize
+ coordinates in the range [-1, 1] in order to be consistent with the
+ PyTorch function grid_sample.
+
+ Return:
+ torch.Tensor: returns a grid tensor with shape :math:`(1, D, H, W, 3)`.
+ """
+ grid2d = create_meshgrid(height, width, normalized_coordinates)
+ if normalized_coordinates:
+ z = torch.linspace(-1, 1, depth)
+ else:
+ z = torch.linspace(0, depth - 1, depth)
+ z = z.view(depth, 1, 1, 1)
+ grid3d = torch.cat([z.repeat(1, height, width, 1).contiguous(), grid2d.repeat(depth, 1, 1, 1)], dim=3)
+ return grid3d.unsqueeze(0) # 1xDxHxWx3
diff --git a/mypy_files.txt b/mypy_files.txt
index 5d00ca48d..0978b978a 100644
--- a/mypy_files.txt
+++ b/mypy_files.txt
@@ -2,10 +2,8 @@ kornia/color/gray.py
kornia/color/hsv.py
kornia/color/rgb.py
kornia/color/normalize.py
-kornia/contrib/spatial_soft_argmax2d.py
kornia/contrib/extract_patches.py
kornia/contrib/max_blur_pool.py
-kornia/feature/harris.py
kornia/feature/nms.py
kornia/filters/blur.py
kornia/filters/gaussian.py
diff --git a/setup.cfg b/setup.cfg
index 00a759ff1..647758b10 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -12,7 +12,7 @@ max-line-length = 120
[flake8]
max-line-length = 120
-ignore = E305,E402,E721,E722,E741,F401,F403,F405,F821,F841,F999,W605,F811
+ignore = W504,E305,E402,E721,E722,E741,F401,F403,F405,F821,F841,F999,W605,F811
exclude = docs/src
[coverage:report]
diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.py
new file mode 100644
index 000000000..767a345e6
--- /dev/null
+++ b/test/feature/test_affine_shape_estimator.py
@@ -0,0 +1,79 @@
+import pytest
+import kornia.testing as utils # test utils
+import kornia
+
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+from kornia.feature.affine_shape import *
+
+
+class TestPatchAffineShapeEstimator:
+ def test_shape(self):
+ inp = torch.rand(1, 1, 32, 32)
+ ori = PatchAffineShapeEstimator(32)
+ ang = ori(inp)
+ assert ang.shape == torch.Size([1, 1, 3])
+
+ def test_shape_batch(self):
+ inp = torch.rand(10, 1, 32, 32)
+ ori = PatchAffineShapeEstimator(32)
+ ang = ori(inp)
+ assert ang.shape == torch.Size([10, 1, 3])
+
+ def test_print(self):
+ sift = PatchAffineShapeEstimator(32)
+ sift.__repr__()
+
+ def test_toy(self):
+ aff = PatchAffineShapeEstimator(19)
+ inp = torch.zeros(1, 1, 19, 19)
+ inp[:, :, 5:-5, 1:-1] = 1
+ abc = aff(inp)
+ expected = torch.tensor([[[0.0229, 0.0000, 0.0450]]])
+ assert_allclose(abc, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 1, 13, 13
+ ori = PatchAffineShapeEstimator(width)
+ patches = torch.rand(batch_size, channels, height, width)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ assert gradcheck(ori, (patches, ),
+ raise_exception=True)
+
+
+class TestLAFAffineShapeEstimator:
+ def test_shape(self):
+ inp = torch.rand(1, 1, 32, 32)
+ laf = torch.rand(1, 1, 2, 3)
+ ori = LAFAffineShapeEstimator()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_shape_batch(self):
+ inp = torch.rand(2, 1, 32, 32)
+ laf = torch.rand(2, 34, 2, 3)
+ ori = LAFAffineShapeEstimator()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_print(self):
+ sift = LAFAffineShapeEstimator()
+ sift.__repr__()
+
+ def test_toy(self):
+ aff = LAFAffineShapeEstimator(32)
+ inp = torch.zeros(1, 1, 32, 32)
+ inp[:, :, 15:-15, 9:-9] = 1
+ laf = torch.tensor([[[[20., 0., 16.], [0., 20., 16.]]]])
+ new_laf = aff(laf, inp)
+ expected = torch.tensor([[[[36.246, 0., 16.], [0., 11.036, 16.]]]])
+ assert_allclose(new_laf, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 1, 21, 21
+ patches = torch.rand(batch_size, channels, height, width).float()
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ laf = torch.ones(batch_size, 4, 2, 3).float()
+ laf = utils.tensor_to_gradcheck_var(laf) # to var
+ assert gradcheck(LAFAffineShapeEstimator(8), (laf, patches),
+ raise_exception=True, rtol=1e-4, atol=1e-4)
diff --git a/test/feature/test_harris.py b/test/feature/test_harris.py
deleted file mode 100644
index ad1f98e25..000000000
--- a/test/feature/test_harris.py
+++ /dev/null
@@ -1,103 +0,0 @@
-import pytest
-
-import kornia as kornia
-import kornia.testing as utils # test utils
-
-import torch
-from torch.testing import assert_allclose
-from torch.autograd import gradcheck
-
-
-class TestCornerHarris:
- def test_shape(self):
- inp = torch.ones(1, 3, 4, 4)
- sobel = kornia.feature.CornerHarris(k=0.04)
- assert sobel(inp).shape == (1, 3, 4, 4)
-
- def test_shape_batch(self):
- inp = torch.zeros(2, 6, 4, 4)
- sobel = kornia.feature.CornerHarris(k=0.04)
- assert sobel(inp).shape == (2, 6, 4, 4)
-
- def test_corners(self):
- inp = torch.tensor([[[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]]])
-
- expected = torch.tensor([[[
- [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., 1., 0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]]])
-
- scores = kornia.feature.corner_harris(inp, k=0.04)
- assert_allclose(scores, expected)
-
- def test_corners_batch(self):
- inp = torch.tensor([[
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 1., 1., 1., 1., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 1., 1., 1., 1., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]]).repeat(2, 1, 1, 1)
-
- expected = torch.tensor([[
- [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., 1., 0., 0., 0., 1., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ], [
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 1., 0., 0., 1., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- [0., 0., 0., 0., 0., 0., 0.],
- ]])
-
- scores = kornia.feature.corner_harris(inp, k=0.04)
- assert_allclose(scores, expected)
-
- def test_gradcheck(self):
- k = 0.04
- batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width)
- img = utils.tensor_to_gradcheck_var(img) # to var
- assert gradcheck(kornia.feature.corner_harris, (img, k),
- raise_exception=True)
-
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self):
- @torch.jit.script
- def op_script(input, k):
- return kornia.feature.corner_harris(input, k)
- k = torch.tensor(0.04)
- img = torch.rand(2, 3, 4, 5)
- actual = op_script(img, k)
- expected = kornia.feature.corner_harris(img, k)
- assert_allclose(actual, expected)
diff --git a/test/feature/test_laf.py b/test/feature/test_laf.py
index 93c81e7c6..da2170fd7 100644
--- a/test/feature/test_laf.py
+++ b/test/feature/test_laf.py
@@ -7,7 +7,6 @@ import kornia.testing as utils # test utils
import torch
from torch.testing import assert_allclose
from torch.autograd import gradcheck
-import math
class TestAngleToRotationMatrix:
@@ -54,6 +53,36 @@ class TestGetLAFScale:
raise_exception=True)
+class TestScaleLAF:
+ def test_shape_float(self):
+ inp = torch.ones(7, 3, 2, 3).float()
+ scale = 23.
+ assert kornia.feature.scale_laf(inp, scale).shape == inp.shape
+
+ def test_shape_tensor(self):
+ inp = torch.ones(7, 3, 2, 3).float()
+ scale = torch.zeros(7, 1, 1, 1).float()
+ assert kornia.feature.scale_laf(inp, scale).shape == inp.shape
+
+ def test_scale(self):
+ inp = torch.tensor([[5., 1, 0.8], [1, 1, -4.]]).float()
+ inp = inp.view(1, 1, 2, 3)
+ scale = torch.tensor([[[[2.]]]]).float()
+ out = kornia.feature.scale_laf(inp, scale)
+ expected = torch.tensor([[[[10., 2, 0.8], [2, 2, -4.]]]]).float()
+ assert_allclose(out, expected)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 2, 3
+ laf = torch.rand(batch_size, channels, height, width)
+ scale = torch.rand(batch_size)
+ scale = utils.tensor_to_gradcheck_var(scale) # to var
+ laf = utils.tensor_to_gradcheck_var(laf) # to var
+ assert gradcheck(kornia.feature.scale_laf,
+ (laf, scale),
+ raise_exception=True, atol=1e-4)
+
+
class TestMakeUpright:
def test_shape(self):
inp = torch.ones(5, 3, 2, 3)
@@ -67,6 +96,13 @@ class TestMakeUpright:
laf = kornia.feature.make_upright(inp)
assert_allclose(laf, expected)
+ def test_do_nothing_with_scalea(self):
+ inp = torch.tensor([[2, 0, 0], [0, 2, 0]]).float()
+ inp = inp.view(1, 1, 2, 3)
+ expected = torch.tensor([[2, 0, 0], [0, 2, 0]]).float()
+ laf = kornia.feature.make_upright(inp)
+ assert_allclose(laf, expected)
+
def test_check_zeros(self):
inp = torch.rand(4, 5, 2, 3)
laf = kornia.feature.make_upright(inp)
@@ -230,7 +266,7 @@ class TestExtractPatchesSimple:
img = utils.tensor_to_gradcheck_var(img) # to var
nlaf = utils.tensor_to_gradcheck_var(nlaf) # to var
assert gradcheck(kornia.feature.extract_patches_simple,
- (img, nlaf, PS,),
+ (img, nlaf, PS, False),
raise_exception=True)
@@ -243,14 +279,14 @@ class TestExtractPatchesPyr:
assert patches.shape == (5, 4, 3, PS, PS)
# TODO: check what to do to improve timing
- @pytest.mark.skip("The test takes too long to finish.")
+ # @pytest.mark.skip("The test takes too long to finish.")
def test_gradcheck(self):
nlaf = torch.tensor([[0.1, 0.001, 0.5], [0, 0.1, 0.5]]).float()
nlaf = nlaf.view(1, 1, 2, 3)
- img = torch.rand(1, 3, 100, 120)
- PS = 11
+ img = torch.rand(1, 3, 20, 15)
+ PS = 9
img = utils.tensor_to_gradcheck_var(img) # to var
nlaf = utils.tensor_to_gradcheck_var(nlaf) # to var
assert gradcheck(kornia.feature.extract_patches_from_pyramid,
- (img, nlaf, PS,),
+ (img, nlaf, PS, False),
raise_exception=True)
diff --git a/test/feature/test_local_features_orientation.py b/test/feature/test_local_features_orientation.py
new file mode 100644
index 000000000..edb69acb6
--- /dev/null
+++ b/test/feature/test_local_features_orientation.py
@@ -0,0 +1,114 @@
+import pytest
+import kornia.testing as utils # test utils
+import kornia
+
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+from kornia.feature.orientation import *
+
+
+class TestPassLAF:
+ def test_shape(self):
+ inp = torch.rand(1, 1, 32, 32)
+ laf = torch.rand(1, 1, 2, 3)
+ ori = PassLAF()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_shape_batch(self):
+ inp = torch.rand(2, 1, 32, 32)
+ laf = torch.rand(2, 34, 2, 3)
+ ori = PassLAF()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_print(self):
+ sift = PassLAF()
+ sift.__repr__()
+
+ def test_pass(self):
+ inp = torch.rand(1, 1, 32, 32)
+ laf = torch.rand(1, 1, 2, 3)
+ ori = PassLAF()
+ out = ori(laf, inp)
+ assert_allclose(out, laf)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 1, 41, 41
+ patches = torch.rand(batch_size, channels, height, width)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ laf = torch.rand(batch_size, 4, 2, 3)
+ assert gradcheck(PassLAF(), (patches, laf),
+ raise_exception=True)
+
+
+class TestPatchDominantGradientOrientation:
+ def test_shape(self):
+ inp = torch.rand(1, 1, 32, 32)
+ ori = PatchDominantGradientOrientation(32)
+ ang = ori(inp)
+ assert ang.shape == torch.Size([1])
+
+ def test_shape_batch(self):
+ inp = torch.rand(10, 1, 32, 32)
+ ori = PatchDominantGradientOrientation(32)
+ ang = ori(inp)
+ assert ang.shape == torch.Size([10])
+
+ def test_print(self):
+ sift = PatchDominantGradientOrientation(32)
+ sift.__repr__()
+
+ def test_toy(self):
+ ori = PatchDominantGradientOrientation(19)
+ inp = torch.zeros(1, 1, 19, 19)
+ inp[:, :, :10, :] = 1
+ ang = ori(inp)
+ expected = torch.tensor([90.])
+ assert_allclose(kornia.rad2deg(ang), expected)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 1, 13, 13
+ ori = PatchDominantGradientOrientation(width)
+ patches = torch.rand(batch_size, channels, height, width)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ assert gradcheck(ori, (patches, ),
+ raise_exception=True)
+
+
+class TestLAFOrienter:
+ def test_shape(self):
+ inp = torch.rand(1, 1, 32, 32)
+ laf = torch.rand(1, 1, 2, 3)
+ ori = LAFOrienter()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_shape_batch(self):
+ inp = torch.rand(2, 1, 32, 32)
+ laf = torch.rand(2, 34, 2, 3)
+ ori = LAFOrienter()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_print(self):
+ sift = LAFOrienter()
+ sift.__repr__()
+
+ def test_toy(self):
+ ori = LAFOrienter(32)
+ inp = torch.zeros(1, 1, 19, 19)
+ inp[:, :, :10, :] = 1
+ laf = torch.tensor([[[[0, 5., 8.], [5.0, 0., 8.]]]])
+ new_laf = ori(laf, inp)
+ expected = torch.tensor([[[[5., 0., 8.], [0., 5., 8.]]]])
+ assert_allclose(new_laf, expected)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 1, 21, 21
+ patches = torch.rand(batch_size, channels, height, width).float()
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ laf = torch.ones(batch_size, 4, 2, 3).float()
+ laf = utils.tensor_to_gradcheck_var(laf) # to var
+ assert gradcheck(LAFOrienter(8), (laf, patches),
+ raise_exception=True, rtol=1e-4, atol=1e-4)
diff --git a/test/feature/test_responces_local_features.py b/test/feature/test_responces_local_features.py
new file mode 100644
index 000000000..c8fc9e425
--- /dev/null
+++ b/test/feature/test_responces_local_features.py
@@ -0,0 +1,259 @@
+import pytest
+
+import kornia as kornia
+import kornia.testing as utils # test utils
+
+import torch
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+
+class TestCornerHarris:
+ def test_shape(self):
+ inp = torch.ones(1, 3, 4, 4)
+ harris = kornia.feature.CornerHarris(k=0.04)
+ assert harris(inp).shape == (1, 3, 4, 4)
+
+ def test_shape_batch(self):
+ inp = torch.zeros(2, 6, 4, 4)
+ harris = kornia.feature.CornerHarris(k=0.04)
+ assert harris(inp).shape == (2, 6, 4, 4)
+
+ def test_corners(self):
+ inp = torch.tensor([[[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]]).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]]]]).float()
+ harris = kornia.feature.CornerHarris(k=0.04)
+ scores = harris(inp)
+ assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
+
+ def test_corners_batch(self):
+ inp = torch.tensor([[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ], [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]).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.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]
+ ]]).repeat(2, 1, 1, 1)
+ scores = kornia.feature.harris_response(inp, k=0.04)
+ assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self):
+ k = 0.04
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.feature.harris_response, (img, k),
+ raise_exception=True)
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+ @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)
+ actual = op_script(img, k)
+ expected = kornia.feature.harris_response(img, k)
+ assert_allclose(actual, expected)
+
+
+class TestCornerGFTT:
+ def test_shape(self):
+ inp = torch.ones(1, 3, 4, 4)
+ shi_tomasi = kornia.feature.CornerGFTT()
+ assert shi_tomasi(inp).shape == (1, 3, 4, 4)
+
+ def test_shape_batch(self):
+ inp = torch.zeros(2, 6, 4, 4)
+ shi_tomasi = kornia.feature.CornerGFTT()
+ assert shi_tomasi(inp).shape == (2, 6, 4, 4)
+
+ def test_corners(self):
+ inp = torch.tensor([[[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]]).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]]]]).float()
+ shi_tomasi = kornia.feature.CornerGFTT()
+ scores = shi_tomasi(inp)
+ assert_allclose(scores, expected, atol=1e-4, rtol=1e-3)
+
+ def test_corners_batch(self):
+ inp = torch.tensor([[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 1., 1., 1., 1., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ], [
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 1., 1., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]).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.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]
+ ]]).repeat(2, 1, 1, 1)
+ shi_tomasi = kornia.feature.CornerGFTT()
+ scores = shi_tomasi(inp)
+ assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.feature.gftt_response, (img),
+ raise_exception=True)
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input):
+ return kornia.feature.gftt_response(input)
+ img = torch.rand(2, 3, 4, 5)
+ actual = op_script(img)
+ expected = kornia.feature.gftt_response(img)
+ assert_allclose(actual, expected)
+
+
+class TestBlobHessian:
+ def test_shape(self):
+ inp = torch.ones(1, 3, 4, 4)
+ shi_tomasi = kornia.feature.BlobHessian()
+ assert shi_tomasi(inp).shape == (1, 3, 4, 4)
+
+ def test_shape_batch(self):
+ inp = torch.zeros(2, 6, 4, 4)
+ shi_tomasi = kornia.feature.BlobHessian()
+ assert shi_tomasi(inp).shape == (2, 6, 4, 4)
+
+ def test_blobs_batch(self):
+ inp = torch.tensor([[
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 1., 1., 1., 0., 0., 0.],
+ [0., 1., 1., 1., 0., 0., 0.],
+ [0., 1., 1., 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., 1., 1., 0., 0., 0., 0.],
+ [0., 1., 1., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 1., 0., 0.],
+ [0., 0., 0., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0.],
+ ]]).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.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]
+ ]]).repeat(2, 1, 1, 1)
+ shi_tomasi = kornia.feature.BlobHessian()
+ scores = shi_tomasi(inp)
+ assert_allclose(scores, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 5, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(kornia.feature.hessian_response, (img),
+ raise_exception=True)
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input):
+ return kornia.feature.hessian_response(input)
+ img = torch.rand(2, 3, 4, 5)
+ actual = op_script(img)
+ expected = kornia.feature.hessian_response(img)
+ assert_allclose(actual, expected)
diff --git a/test/feature/test_scale_space_detector.py b/test/feature/test_scale_space_detector.py
new file mode 100644
index 000000000..3cdea6569
--- /dev/null
+++ b/test/feature/test_scale_space_detector.py
@@ -0,0 +1,41 @@
+import pytest
+import kornia.testing as utils # test utils
+import kornia
+
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+from kornia.feature.scale_space_detector import *
+
+
+class TestScaleSpaceDetector:
+ def test_shape(self):
+ inp = torch.rand(1, 1, 32, 32)
+ n_feats = 10
+ det = ScaleSpaceDetector(n_feats)
+ lafs, resps = det(inp)
+ assert lafs.shape == torch.Size([1, n_feats, 2, 3])
+ assert resps.shape == torch.Size([1, n_feats])
+
+ def test_print(self):
+ sift = ScaleSpaceDetector()
+ sift.__repr__()
+
+ def test_toy(self):
+ inp = torch.zeros(1, 1, 33, 33)
+ inp[:, :, 8:-8, 8:-8] = 1.0
+ n_feats = 1
+ det = ScaleSpaceDetector(n_feats,
+ resp_module=kornia.feature.BlobHessian(),
+ mr_size=3.0)
+ lafs, resps = det(inp)
+ expected_laf = torch.tensor([[[[12.1187, 0.0000, 15.9958], [0.0, 12.1187, 15.9958]]]])
+ expected_resp = torch.tensor([[0.0699]])
+ assert_allclose(expected_laf, lafs)
+ assert_allclose(expected_resp, resps)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 1, 31, 21
+ patches = torch.rand(batch_size, channels, height, width)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ assert gradcheck(ScaleSpaceDetector(2), (patches),
+ raise_exception=True)
diff --git a/test/geometry/test_spatial_softargmax.py b/test/geometry/test_spatial_softargmax.py
new file mode 100644
index 000000000..dafbf348d
--- /dev/null
+++ b/test/geometry/test_spatial_softargmax.py
@@ -0,0 +1,432 @@
+import pytest
+
+import kornia as kornia
+import kornia.testing as utils # test utils
+from test.common import device_type
+
+import torch
+from torch.nn.functional import mse_loss
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+
+class TestSpatialSoftArgmax2d:
+ def test_smoke(self):
+ input = torch.zeros(1, 1, 2, 3)
+ m = kornia.SpatialSoftArgmax2d()
+ assert m(input).shape == (1, 1, 2)
+
+ def test_smoke_batch(self):
+ input = torch.zeros(2, 1, 2, 3)
+ m = kornia.SpatialSoftArgmax2d()
+ assert m(input).shape == (2, 1, 2)
+
+ def test_top_left(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., 0, 0] = 10.
+
+ coord = kornia.spatial_soft_argmax2d(input, True)
+ assert pytest.approx(coord[..., 0].item(), -1.0)
+ assert pytest.approx(coord[..., 1].item(), -1.0)
+
+ def test_top_left_normalized(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., 0, 0] = 10.
+
+ coord = kornia.spatial_soft_argmax2d(input, False)
+ assert pytest.approx(coord[..., 0].item(), 0.0)
+ assert pytest.approx(coord[..., 1].item(), 0.0)
+
+ def test_bottom_right(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., -1, 1] = 10.
+
+ coord = kornia.spatial_soft_argmax2d(input, True)
+ assert pytest.approx(coord[..., 0].item(), 1.0)
+ assert pytest.approx(coord[..., 1].item(), 1.0)
+
+ def test_bottom_right_normalized(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., -1, 1] = 10.
+
+ coord = kornia.spatial_soft_argmax2d(input, False)
+ assert pytest.approx(coord[..., 0].item(), 2.0)
+ assert pytest.approx(coord[..., 1].item(), 1.0)
+
+ def test_batch2_n2(self):
+ input = torch.zeros(2, 2, 2, 3)
+ input[0, 0, 0, 0] = 10. # top-left
+ input[0, 1, 0, -1] = 10. # top-right
+ input[1, 0, -1, 0] = 10. # bottom-left
+ input[1, 1, -1, -1] = 10. # bottom-right
+
+ coord = kornia.spatial_soft_argmax2d(input)
+ assert pytest.approx(coord[0, 0, 0].item(), -1.0) # top-left
+ assert pytest.approx(coord[0, 0, 1].item(), -1.0)
+ assert pytest.approx(coord[0, 1, 0].item(), 1.0) # top-right
+ assert pytest.approx(coord[0, 1, 1].item(), -1.0)
+ assert pytest.approx(coord[1, 0, 0].item(), -1.0) # bottom-left
+ assert pytest.approx(coord[1, 0, 1].item(), 1.0)
+ assert pytest.approx(coord[1, 1, 0].item(), 1.0) # bottom-right
+ assert pytest.approx(coord[1, 1, 1].item(), 1.0)
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+ @torch.jit.script
+ def op_script(input: torch.Tensor,
+ temperature: torch.Tensor,
+ normalize_coords: bool,
+ eps: float) -> torch.Tensor:
+ return kornia.spatial_soft_argmax2d(
+ input, temperature, normalize_coords, eps)
+
+ input = torch.rand(1, 2, 3, 4)
+ actual = op_script(input, torch.tensor(1.0), True, 1e-8)
+ expected = kornia.spatial_soft_argmax2d(input)
+
+ assert_allclose(actual, expected)
+
+ def test_gradcheck(self):
+ input = torch.rand(2, 3, 3, 2)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(kornia.spatial_soft_argmax2d,
+ (input), raise_exception=True)
+
+
+class TestDSNT:
+ GAUSSIAN = torch.tensor([
+ [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
+ [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
+ [0.021938, 0.098320, 0.162103, 0.098320, 0.021938],
+ [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
+ [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
+ ])
+
+ def test_render_gaussian_2d(self):
+ expected = self.GAUSSIAN
+ actual = kornia.geometry.dsnt.render_gaussian_2d(torch.tensor([2.0, 2.0]),
+ torch.tensor([1.0, 1.0]),
+ (5, 5),
+ normalized_coordinates=False)
+ assert_allclose(actual, expected, rtol=0, atol=1e-5)
+
+ def test_render_gaussian_2d_normalized_coordinates(self):
+ expected = self.GAUSSIAN
+ actual = kornia.geometry.dsnt.render_gaussian_2d(torch.tensor([0.0, 0.0]),
+ torch.tensor([0.25, 0.25]),
+ (5, 5),
+ normalized_coordinates=True)
+ assert_allclose(actual, expected, rtol=0, atol=1e-5)
+
+ @pytest.mark.parametrize('input', [
+ torch.ones(1, 1, 5, 7),
+ torch.randn(2, 3, 16, 16),
+ ])
+ def test_spatial_softmax_2d(self, input):
+ actual = kornia.geometry.dsnt.spatial_softmax_2d(input)
+ assert actual.lt(0).sum().item() == 0, 'expected no negative values'
+ sums = actual.sum(-1).sum(-1)
+ assert_allclose(sums, torch.ones_like(sums))
+
+ @pytest.mark.parametrize('input,expected_norm,expected_px', [
+ (
+ torch.tensor([[[
+ [0.0, 0.0, 1.0],
+ [0.0, 0.0, 0.0],
+ ]]]),
+ torch.tensor([[[1.0, -1.0]]]),
+ torch.tensor([[[2.0, 0.0]]]),
+ ),
+ ])
+ def test_spatial_softargmax_2d(self, input, expected_norm, expected_px):
+ actual_norm = kornia.geometry.dsnt.spatial_softargmax_2d(input, True)
+ assert_allclose(actual_norm, expected_norm)
+ actual_px = kornia.geometry.dsnt.spatial_softargmax_2d(input, False)
+ assert_allclose(actual_px, expected_px)
+
+ def test_end_to_end(self):
+ input = torch.full((1, 2, 7, 7), 1.0, requires_grad=True)
+ target = torch.as_tensor([[[0.0, 0.0], [1.0, 1.0]]])
+ std = torch.tensor([1.0, 1.0])
+
+ hm = kornia.geometry.dsnt.spatial_softmax_2d(input)
+ assert_allclose(hm.sum(-1).sum(-1), 1.0)
+
+ pred = kornia.geometry.dsnt.spatial_softargmax_2d(hm)
+ assert_allclose(pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]]))
+
+ loss1 = mse_loss(pred, target, size_average=None, reduce=None,
+ reduction='none').mean(-1, keepdim=False)
+ expected_loss1 = torch.as_tensor([[0.0, 1.0]])
+ assert_allclose(loss1, expected_loss1)
+
+ target_hm = kornia.geometry.dsnt.render_gaussian_2d(target, std, input.shape[-2:])
+ loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, reduction='none')
+ expected_loss2 = torch.as_tensor([[0.0087, 0.0818]])
+ assert_allclose(loss2, expected_loss2, rtol=0, atol=1e-3)
+
+ loss = (loss1 + loss2).mean()
+ loss.backward()
+
+ @pytest.mark.skip(reason="turn off all jit for a while")
+ def test_jit(self):
+ def op(input: torch.Tensor, target: torch.Tensor,
+ temperature: torch.Tensor, normalized_coordinates: bool,
+ std: torch.Tensor) -> torch.Tensor:
+ hm = kornia.geometry.dsnt.spatial_softmax_2d(input, temperature)
+ pred = kornia.geometry.dsnt.spatial_softargmax_2d(hm, normalized_coordinates)
+ size = (input.shape[-2], input.shape[-1])
+ target_hm = kornia.geometry.dsnt.render_gaussian_2d(target, std, size,
+ normalized_coordinates)
+ loss1 = mse_loss(pred, target, size_average=None, reduce=None,
+ reduction='mean')
+ loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, 'mean')
+ return loss1 + loss2
+
+ op_script = torch.jit.script(op)
+
+ args = [torch.rand(2, 3, 7, 7), torch.rand(2, 3, 2) * 7,
+ torch.tensor(1.0), False, torch.tensor([1.0, 1.0])]
+ actual = op_script(*args)
+ expected = op(*args)
+ assert_allclose(actual, expected)
+
+
+class TestConvSoftArgmax2d:
+ def test_smoke(self):
+ input = torch.zeros(1, 1, 3, 3)
+ m = kornia.ConvSoftArgmax2d((3, 3))
+ assert m(input).shape == (1, 1, 2, 3, 3)
+
+ def test_smoke_batch(self):
+ input = torch.zeros(2, 5, 3, 3)
+ m = kornia.ConvSoftArgmax2d()
+ assert m(input).shape == (2, 5, 2, 3, 3)
+
+ def test_smoke_with_val(self):
+ input = torch.zeros(1, 1, 3, 3)
+ m = kornia.ConvSoftArgmax2d((3, 3), output_value=True)
+ coords, val = m(input)
+ assert coords.shape == (1, 1, 2, 3, 3)
+ assert val.shape == (1, 1, 3, 3)
+
+ def test_smoke_batch_with_val(self):
+ input = torch.zeros(2, 5, 3, 3)
+ m = kornia.ConvSoftArgmax2d((3, 3), output_value=True)
+ coords, val = m(input)
+ assert coords.shape == (2, 5, 2, 3, 3)
+ assert val.shape == (2, 5, 3, 3)
+
+ def test_gradcheck(self):
+ input = torch.rand(2, 3, 5, 5)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(kornia.conv_soft_argmax2d,
+ (input), raise_exception=True)
+
+ def test_cold_diag(self):
+ input = torch.tensor([[[
+ [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.],
+ ]]])
+ softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
+ temperature=0.05,
+ normalized_coordinates=False,
+ output_value=True)
+ expected_val = torch.tensor([[[[1., 0.],
+ [0., 1.]]]])
+ expected_coord = torch.tensor([[[[[1., 3.],
+ [1., 3.]],
+ [[1., 1.],
+ [3., 3.]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
+
+ def test_hot_diag(self):
+ input = torch.tensor([[[
+ [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.],
+ ]]])
+ softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
+ temperature=10.,
+ normalized_coordinates=False,
+ output_value=True)
+ expected_val = torch.tensor([[[[0.1214, 0.],
+ [0., 0.1214]]]])
+ expected_coord = torch.tensor([[[[[1., 3.],
+ [1., 3.]],
+ [[1., 1.],
+ [3., 3.]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
+
+ def test_cold_diag_norm(self):
+ input = torch.tensor([[[
+ [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.],
+ ]]])
+ softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
+ temperature=0.05,
+ normalized_coordinates=True,
+ output_value=True)
+ expected_val = torch.tensor([[[[1., 0.],
+ [0., 1.]]]])
+ expected_coord = torch.tensor([[[[[-0.5, 0.5],
+ [-0.5, 0.5]],
+ [[-0.5, -0.5],
+ [0.5, 0.5]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
+
+ def test_hot_diag_norm(self):
+ input = torch.tensor([[[
+ [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.],
+ ]]])
+ softargmax = kornia.ConvSoftArgmax2d((3, 3), (2, 2), (0, 0),
+ temperature=10.,
+ normalized_coordinates=True,
+ output_value=True)
+ expected_val = torch.tensor([[[[0.1214, 0.],
+ [0., 0.1214]]]])
+ expected_coord = torch.tensor([[[[[-0.5, 0.5],
+ [-0.5, 0.5]],
+ [[-0.5, -0.5],
+ [0.5, 0.5]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
+
+
+class TestConvSoftArgmax3d:
+ def test_smoke(self):
+ input = torch.zeros(1, 1, 3, 3, 3)
+ m = kornia.ConvSoftArgmax3d((3, 3, 3), output_value=False)
+ assert m(input).shape == (1, 1, 3, 3, 3, 3)
+
+ def test_smoke_with_val(self):
+ input = torch.zeros(1, 1, 3, 3, 3)
+ m = kornia.ConvSoftArgmax3d((3, 3, 3), output_value=True)
+ coords, val = m(input)
+ assert coords.shape == (1, 1, 3, 3, 3, 3)
+ assert val.shape == (1, 1, 3, 3, 3)
+
+ def test_gradcheck(self):
+ input = torch.rand(1, 2, 3, 5, 5)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(kornia.conv_soft_argmax3d,
+ (input), raise_exception=True)
+
+ def test_cold_diag(self):
+ input = torch.tensor([[[[
+ [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.],
+ ]]]])
+ softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
+ temperature=0.05,
+ normalized_coordinates=False,
+ output_value=True)
+ expected_val = torch.tensor([[[[[1., 0.],
+ [0., 1.]]]]])
+ expected_coord = torch.tensor([[[
+ [[[0., 0.],
+ [0., 0.]]],
+ [[[1., 3.],
+ [1., 3.]]],
+ [[[1., 1.],
+ [3., 3.]]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
+
+ def test_hot_diag(self):
+ input = torch.tensor([[[[
+ [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.],
+ ]]]])
+ softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
+ temperature=10.,
+ normalized_coordinates=False,
+ output_value=True)
+ expected_val = torch.tensor([[[[[0.1214, 0.],
+ [0., 0.1214]]]]])
+ expected_coord = torch.tensor([[[
+ [[[0., 0.],
+ [0., 0.]]],
+ [[[1., 3.],
+ [1., 3.]]],
+ [[[1., 1.],
+ [3., 3.]]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
+
+ def test_cold_diag_norm(self):
+ input = torch.tensor([[[[
+ [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.],
+ ]]]])
+ softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
+ temperature=0.05,
+ normalized_coordinates=True,
+ output_value=True)
+ expected_val = torch.tensor([[[[[1., 0.],
+ [0., 1.]]]]])
+ expected_coord = torch.tensor([[[
+ [[[-1., -1.],
+ [-1., -1.]]],
+ [[[-0.5, 0.5],
+ [-0.5, 0.5]]],
+ [[[-0.5, -0.5],
+ [0.5, 0.5]]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
+
+ def test_hot_diag_norm(self):
+ input = torch.tensor([[[[
+ [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.],
+ ]]]])
+ softargmax = kornia.ConvSoftArgmax3d((1, 3, 3), (1, 2, 2), (0, 0, 0),
+ temperature=10.,
+ normalized_coordinates=True,
+ output_value=True)
+ expected_val = torch.tensor([[[[[0.1214, 0.],
+ [0., 0.1214]]]]])
+ expected_coord = torch.tensor([[[
+ [[[-1., -1.],
+ [-1., -1.]]],
+ [[[-0.5, 0.5],
+ [-0.5, 0.5]]],
+ [[[-0.5, -0.5],
+ [0.5, 0.5]]]]]])
+ coords, val = softargmax(input)
+ assert_allclose(val, expected_val)
+ assert_allclose(coords, expected_coord)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 8b7acafcb..e5d2c87f8 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -1,11 +1,9 @@
import pytest
import torch
from torch.autograd import gradcheck
-from torch.nn.functional import mse_loss
from torch.testing import assert_allclose
import kornia
-import kornia.contrib.dsnt as dsnt
import kornia.testing as utils # test utils
@@ -160,185 +158,3 @@ class TestExtractTensorPatches:
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.contrib.extract_tensor_patches,
(input, 3,), raise_exception=True)
-
-
-class TestSpatialSoftArgmax2d:
- def test_smoke(self):
- input = torch.zeros(1, 1, 2, 3)
- m = kornia.contrib.SpatialSoftArgmax2d()
- assert m(input).shape == (1, 1, 2)
-
- def test_smoke_batch(self):
- input = torch.zeros(2, 1, 2, 3)
- m = kornia.contrib.SpatialSoftArgmax2d()
- assert m(input).shape == (2, 1, 2)
-
- def test_top_left(self):
- input = torch.zeros(1, 1, 2, 3)
- input[..., 0, 0] = 10.
-
- coord = kornia.contrib.spatial_soft_argmax2d(input, True)
- assert pytest.approx(coord[..., 0].item(), -1.0)
- assert pytest.approx(coord[..., 1].item(), -1.0)
-
- def test_top_left_normalized(self):
- input = torch.zeros(1, 1, 2, 3)
- input[..., 0, 0] = 10.
-
- coord = kornia.contrib.spatial_soft_argmax2d(input, False)
- assert pytest.approx(coord[..., 0].item(), 0.0)
- assert pytest.approx(coord[..., 1].item(), 0.0)
-
- def test_bottom_right(self):
- input = torch.zeros(1, 1, 2, 3)
- input[..., -1, 1] = 10.
-
- coord = kornia.contrib.spatial_soft_argmax2d(input, True)
- assert pytest.approx(coord[..., 0].item(), 1.0)
- assert pytest.approx(coord[..., 1].item(), 1.0)
-
- def test_bottom_right_normalized(self):
- input = torch.zeros(1, 1, 2, 3)
- input[..., -1, 1] = 10.
-
- coord = kornia.contrib.spatial_soft_argmax2d(input, False)
- assert pytest.approx(coord[..., 0].item(), 2.0)
- assert pytest.approx(coord[..., 1].item(), 1.0)
-
- def test_batch2_n2(self):
- input = torch.zeros(2, 2, 2, 3)
- input[0, 0, 0, 0] = 10. # top-left
- input[0, 1, 0, -1] = 10. # top-right
- input[1, 0, -1, 0] = 10. # bottom-left
- input[1, 1, -1, -1] = 10. # bottom-right
-
- coord = kornia.contrib.spatial_soft_argmax2d(input)
- assert pytest.approx(coord[0, 0, 0].item(), -1.0) # top-left
- assert pytest.approx(coord[0, 0, 1].item(), -1.0)
- assert pytest.approx(coord[0, 1, 0].item(), 1.0) # top-right
- assert pytest.approx(coord[0, 1, 1].item(), -1.0)
- assert pytest.approx(coord[1, 0, 0].item(), -1.0) # bottom-left
- assert pytest.approx(coord[1, 0, 1].item(), 1.0)
- assert pytest.approx(coord[1, 1, 0].item(), 1.0) # bottom-right
- assert pytest.approx(coord[1, 1, 1].item(), 1.0)
-
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self):
- @torch.jit.script
- def op_script(input: torch.Tensor,
- temperature: torch.Tensor,
- normalize_coords: bool,
- eps: float) -> torch.Tensor:
- return kornia.spatial_soft_argmax2d(
- input, temperature, normalize_coords, eps)
-
- input = torch.rand(1, 2, 3, 4)
- actual = op_script(input, torch.tensor(1.0), True, 1e-8)
- expected = kornia.spatial_soft_argmax2d(input)
-
- assert_allclose(actual, expected)
-
- def test_gradcheck(self):
- input = torch.rand(2, 3, 3, 2)
- input = utils.tensor_to_gradcheck_var(input) # to var
- assert gradcheck(kornia.contrib.spatial_soft_argmax2d,
- (input), raise_exception=True)
-
-
-class TestDSNT:
- GAUSSIAN = torch.tensor([
- [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
- [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
- [0.021938, 0.098320, 0.162103, 0.098320, 0.021938],
- [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
- [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
- ])
-
- def test_render_gaussian_2d(self):
- expected = self.GAUSSIAN
- actual = dsnt.render_gaussian_2d(torch.tensor([2.0, 2.0]),
- torch.tensor([1.0, 1.0]),
- (5, 5),
- normalized_coordinates=False)
- assert_allclose(actual, expected, rtol=0, atol=1e-5)
-
- def test_render_gaussian_2d_normalized_coordinates(self):
- expected = self.GAUSSIAN
- actual = dsnt.render_gaussian_2d(torch.tensor([0.0, 0.0]),
- torch.tensor([0.25, 0.25]),
- (5, 5),
- normalized_coordinates=True)
- assert_allclose(actual, expected, rtol=0, atol=1e-5)
-
- @pytest.mark.parametrize('input', [
- torch.ones(1, 1, 5, 7),
- torch.randn(2, 3, 16, 16),
- ])
- def test_spatial_softmax_2d(self, input):
- actual = dsnt.spatial_softmax_2d(input)
- assert actual.lt(0).sum().item() == 0, 'expected no negative values'
- sums = actual.sum(-1).sum(-1)
- assert_allclose(sums, torch.ones_like(sums))
-
- @pytest.mark.parametrize('input,expected_norm,expected_px', [
- (
- torch.tensor([[[
- [0.0, 0.0, 1.0],
- [0.0, 0.0, 0.0],
- ]]]),
- torch.tensor([[[1.0, -1.0]]]),
- torch.tensor([[[2.0, 0.0]]]),
- ),
- ])
- def test_spatial_softargmax_2d(self, input, expected_norm, expected_px):
- actual_norm = dsnt.spatial_softargmax_2d(input, True)
- assert_allclose(actual_norm, expected_norm)
- actual_px = dsnt.spatial_softargmax_2d(input, False)
- assert_allclose(actual_px, expected_px)
-
- def test_end_to_end(self):
- input = torch.full((1, 2, 7, 7), 1.0, requires_grad=True)
- target = torch.as_tensor([[[0.0, 0.0], [1.0, 1.0]]])
- std = torch.tensor([1.0, 1.0])
-
- hm = dsnt.spatial_softmax_2d(input)
- assert_allclose(hm.sum(-1).sum(-1), 1.0)
-
- pred = dsnt.spatial_softargmax_2d(hm)
- assert_allclose(pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]]))
-
- loss1 = mse_loss(pred, target, size_average=None, reduce=None,
- reduction='none').mean(-1, keepdim=False)
- expected_loss1 = torch.as_tensor([[0.0, 1.0]])
- assert_allclose(loss1, expected_loss1)
-
- target_hm = dsnt.render_gaussian_2d(target, std, input.shape[-2:])
- loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, reduction='none')
- expected_loss2 = torch.as_tensor([[0.0087, 0.0818]])
- assert_allclose(loss2, expected_loss2, rtol=0, atol=1e-3)
-
- loss = (loss1 + loss2).mean()
- loss.backward()
-
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self):
- def op(input: torch.Tensor, target: torch.Tensor,
- temperature: torch.Tensor, normalized_coordinates: bool,
- std: torch.Tensor) -> torch.Tensor:
- hm = dsnt.spatial_softmax_2d(input, temperature)
- pred = dsnt.spatial_softargmax_2d(hm, normalized_coordinates)
- size = (input.shape[-2], input.shape[-1])
- target_hm = dsnt.render_gaussian_2d(target, std, size,
- normalized_coordinates)
- loss1 = mse_loss(pred, target, size_average=None, reduce=None,
- reduction='mean')
- loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, 'mean')
- return loss1 + loss2
-
- op_script = torch.jit.script(op)
-
- args = [torch.rand(2, 3, 7, 7), torch.rand(2, 3, 2) * 7,
- torch.tensor(1.0), False, torch.tensor([1.0, 1.0])]
- actual = op_script(*args)
- expected = op(*args)
- assert_allclose(actual, expected)
diff --git a/tox.ini b/tox.ini
index 680fc7458..0ac8fe68f 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,4 +1,4 @@
[flake8]
max-line-length = 120
-ignore = E305,E402,E721,E722,E741,F401,F403,F405,F821,F841,F999,W605,F811
+ignore = W504,E305,E402,E721,E722,E741,F401,F403,F405,F821,F841,F999,W605,F811
exclude = docs/src