Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[ready to review] SIFT descriptor as in https://github.com/ducha-aiki/pytorch-sift (#183)

Dmytro Mishkind46673af5c70
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 4462b2407..ea7ce84ca 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -33,6 +33,7 @@ from kornia.contrib import (
from kornia.feature import (
non_maxima_suppression2d,
corner_harris,
+ SIFTDescriptor
)
from kornia.filters import (
get_gaussian_kernel1d,
@@ -62,3 +63,4 @@ from kornia.utils import (
load_pointcloud_ply,
)
from kornia.geometry import *
+from kornia.geometry import pi
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 7005f3fe1..fdf963ba1 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -1,9 +1,10 @@
from .harris import CornerHarris, corner_harris
from .nms import NonMaximaSuppression2d, non_maxima_suppression2d
-
+from .siftdesc import SIFTDescriptor
__all__ = [
"non_maxima_suppression2d",
"corner_harris",
- "NonMaximaSupression2d",
+ "NonMaximaSuppression2d",
"CornerHarris",
+ "SIFTDescriptor"
]
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
new file mode 100644
index 000000000..88ef11e31
--- /dev/null
+++ b/kornia/feature/siftdesc.py
@@ -0,0 +1,181 @@
+from typing import Tuple
+import torch
+import math
+import torch.nn as nn
+import torch.nn.functional as F
+from kornia.filters import get_gaussian_kernel2d
+from kornia.filters import spatial_gradient
+from kornia.geometry import pi
+
+
+def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
+ """
+ Returns a weighted pooling kernel for SIFT descriptor
+ Args:
+ ksize: (int): kernel_size
+
+ Returns:
+ torch.Tensor: kernel
+
+ Shape:
+ - Output: :math: `(ksize,ksize)`
+ """
+ ks_2: float = float(ksize) / 2.0
+ xc2: torch.Tensor = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs() # type: ignore # noqa
+ kernel: torch.Tensor = torch.ger(xc2, xc2) / (ks_2**2)
+ return kernel
+
+
+def get_sift_bin_ksize_stride_pad(patch_size: int,
+ num_spatial_bins: int) -> Tuple:
+ """
+ Returns a tuple with SIFT parameters, given the patch size
+ and number of spatial bins.
+ Args:
+ patch_size: (int)
+ num_spatial_bins: (int)
+
+ Returns:
+ ksize, stride, pad: ints
+ """
+ ksize: int = 2 * int(patch_size / (num_spatial_bins + 1))
+ stride: int = patch_size // num_spatial_bins
+ pad: int = ksize // 4
+ return ksize, stride, pad
+
+
+class SIFTDescriptor(nn.Module):
+ """
+ Module, which computes SIFT descriptors of given patches
+ Args:
+ patch_size: (int): Input patch size in pixels
+ (41 is default)
+ num_ang_bins: (int): Number of angular bins.
+ (8 is default)
+ num_spatial_bins: (int): Number of spatial bins
+ (4 is default)
+ clipval: (float): default 0.2
+ rootsift: (bool): if True, RootSIFT (Arandjelović et. al, 2012)
+ is computed
+
+ Returns:
+ Tensor: SIFT descriptor of the patches
+
+ Shape:
+ - Input: :math:`(B, 1, num_spatial_bins, num_spatial_bins)`
+ - Output: :math:`(B, num_ang_bins * num_spatial_bins ** 2)`
+
+ Examples::
+ >>> input = torch.rand(23, 1, 32, 32)
+ >>> SIFT = kornia.SIFTDescriptor(32, 8, 4)
+ >>> descs = SIFT(input) # 23x128
+ """
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'num_ang_bins=' + str(self.num_ang_bins) +\
+ ', ' + 'num_spatial_bins=' + str(self.num_spatial_bins) +\
+ ', ' + 'patch_size=' + str(self.patch_size) +\
+ ', ' + 'rootsift=' + str(self.rootsift) +\
+ ', ' + 'clipval=' + str(self.clipval) + ')'
+
+ def __init__(self,
+ patch_size: int = 41,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+ rootsift: bool = True,
+ clipval: float = 0.2,
+ ) -> None:
+ super(SIFTDescriptor, self).__init__()
+ self.eps = 1e-10
+ self.num_ang_bins = num_ang_bins
+ self.num_spatial_bins = num_spatial_bins
+ self.clipval = clipval
+ self.rootsift = rootsift
+ self.patch_size = patch_size
+
+ ks: int = self.patch_size
+ sigma: float = float(ks) / math.sqrt(2.0)
+ self.gk = get_gaussian_kernel2d((ks, ks), (sigma, sigma), True)
+
+ (self.bin_ksize,
+ self.bin_stride,
+ self.pad) = get_sift_bin_ksize_stride_pad(patch_size,
+ num_spatial_bins)
+
+ nw = get_sift_pooling_kernel(ksize=self.bin_ksize).float()
+ self.pk = nn.Conv2d(1, 1, kernel_size=(nw.size(0), nw.size(1)),
+ stride=(self.bin_stride, self.bin_stride),
+ padding=(self.pad, self.pad),
+ bias=False)
+ self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1))) # type: ignore # noqa
+ return
+
+ def get_pooling_kernel(self) -> torch.Tensor:
+ return self.pk.weight.detach()
+
+ def get_weighting_kernel(self) -> torch.Tensor:
+ return self.gk.detach()
+
+ def forward(self, input):
+ 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 Bx1xHxW. Got: {}"
+ .format(input.shape))
+ B, CH, W, H = input.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, input.size()))
+ self.pk = self.pk.to(input.dtype).to(input.device)
+
+ grads: torch.Tensor = spatial_gradient(input, 'diff')
+ # 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
+ mag = mag * self.gk.expand_as(mag).type_as(mag).to(mag.device)
+ o_big: torch.Tensor = float(self.num_ang_bins) * ori / (2.0 * pi)
+
+ bo0_big_: torch.Tensor = torch.floor(o_big)
+ wo1_big_: torch.Tensor = (o_big - bo0_big_)
+ bo0_big: torch.Tensor = bo0_big_ % self.num_ang_bins
+ bo1_big: torch.Tensor = (bo0_big + 1) % self.num_ang_bins
+ wo0_big: torch.Tensor = (1.0 - wo1_big_) * mag # type: ignore
+ wo1_big: torch.Tensor = wo1_big_ * mag
+
+ ang_bins = []
+ for i in range(0, self.num_ang_bins):
+ out = self.pk((bo0_big == i).to(input.dtype) * wo0_big + # noqa
+ (bo1_big == i).to(input.dtype) * wo1_big)
+ ang_bins.append(out)
+ ang_bins = torch.cat(ang_bins, dim=1)
+ ang_bins = ang_bins.view(B, -1)
+ ang_bins = F.normalize(ang_bins, p=2)
+ ang_bins = torch.clamp(ang_bins, 0., float(self.clipval))
+ ang_bins = F.normalize(ang_bins, p=2)
+ if self.rootsift:
+ ang_bins = torch.sqrt(F.normalize(ang_bins, p=1) + self.eps)
+ return ang_bins
+
+
+def sift_describe(input: torch.Tensor,
+ patch_size: int = 41,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+ rootsift: bool = True,
+ clipval: float = 0.2,
+ ) -> torch.Tensor:
+ r"""Computes the sift descriptor.
+
+ See :class:`~kornia.feature.SIFTDescriptor` for details.
+ """
+
+ return SIFTDescriptor(patch_size,
+ num_ang_bins,
+ num_spatial_bins,
+ rootsift,
+ clipval)(input)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index ee6fa0e2b..f4e6dae94 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -15,12 +15,10 @@ def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:
def gaussian(window_size, sigma):
- def gauss_fcn(x):
- return -(x - window_size // 2) ** 2 / float(2 * sigma ** 2)
-
- gauss = torch.stack(
- [torch.exp(torch.tensor(gauss_fcn(x))) for x in range(window_size)]
- )
+ x = torch.arange(window_size).float() - window_size // 2
+ if window_size % 2 == 0:
+ x = x + 0.5
+ gauss = torch.exp((-x.pow(2.0) / float(2 * sigma ** 2)))
return gauss / gauss.sum()
@@ -151,12 +149,15 @@ def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:
return kernel
-def get_gaussian_kernel1d(kernel_size: int, sigma: float) -> torch.Tensor:
+def get_gaussian_kernel1d(kernel_size: int,
+ sigma: float,
+ force_even: bool = False) -> torch.Tensor:
r"""Function that returns Gaussian filter coefficients.
Args:
kernel_size (int): filter size. It should be odd and positive.
sigma (float): gaussian standard deviation.
+ force_even (bool): overrides requirement for odd kernel size.
Returns:
Tensor: 1D tensor with gaussian filter coefficients.
@@ -172,7 +173,8 @@ def get_gaussian_kernel1d(kernel_size: int, sigma: float) -> torch.Tensor:
>>> kornia.image.get_gaussian_kernel(5, 1.5)
tensor([0.1201, 0.2339, 0.2921, 0.2339, 0.1201])
"""
- if (not isinstance(kernel_size, int) or (kernel_size % 2 == 0) or (
+ if (not isinstance(kernel_size, int) or (
+ (kernel_size % 2 == 0) and not force_even) or (
kernel_size <= 0)):
raise TypeError(
"kernel_size must be an odd positive integer. "
@@ -184,7 +186,8 @@ def get_gaussian_kernel1d(kernel_size: int, sigma: float) -> torch.Tensor:
def get_gaussian_kernel2d(
kernel_size: Tuple[int, int],
- sigma: Tuple[float, float]) -> torch.Tensor:
+ sigma: Tuple[float, float],
+ force_even: bool = False) -> torch.Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
@@ -192,6 +195,7 @@ def get_gaussian_kernel2d(
Sizes should be odd and positive.
sigma (Tuple[int, int]): gaussian standard deviation in the x and y
direction.
+ force_even (bool): overrides requirement for odd kernel size.
Returns:
Tensor: 2D tensor with gaussian filter matrix coefficients.
@@ -223,8 +227,8 @@ def get_gaussian_kernel2d(
)
ksize_x, ksize_y = kernel_size
sigma_x, sigma_y = sigma
- kernel_x: torch.Tensor = get_gaussian_kernel1d(ksize_x, sigma_x)
- kernel_y: torch.Tensor = get_gaussian_kernel1d(ksize_y, sigma_y)
+ kernel_x: torch.Tensor = get_gaussian_kernel1d(ksize_x, sigma_x, force_even)
+ kernel_y: torch.Tensor = get_gaussian_kernel1d(ksize_y, sigma_y, force_even)
kernel_2d: torch.Tensor = torch.matmul(
kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t()
)
diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.py
new file mode 100644
index 000000000..f19fabb63
--- /dev/null
+++ b/test/feature/test_siftdesc.py
@@ -0,0 +1,67 @@
+import pytest
+import kornia.testing as utils # test utils
+
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+from kornia.feature.siftdesc import *
+
+
[email protected]("ksize", [5, 13, 25])
+def test_get_sift_pooling_kernel(ksize):
+ kernel = get_sift_pooling_kernel(ksize)
+ assert kernel.shape == (ksize, ksize)
+
+
[email protected]("ps,n_bins,ksize,stride,pad",
+ [(41, 3, 20, 13, 5),
+ (32, 4, 12, 8, 3)])
+def test_get_sift_bin_ksize_stride_pad(ps,
+ n_bins,
+ ksize,
+ stride,
+ pad):
+ out = get_sift_bin_ksize_stride_pad(ps, n_bins)
+ assert out == (ksize, stride, pad)
+
+
+class TestSIFTDescriptor:
+ def test_shape(self):
+ inp = torch.ones(1, 1, 32, 32)
+ sift = SIFTDescriptor(32)
+ out = sift(inp)
+ assert out.shape == (1, 128)
+
+ def test_batch_shape(self):
+ inp = torch.ones(13, 1, 41, 41)
+ sift = SIFTDescriptor(41)
+ out = sift(inp)
+ assert out.shape == (13, 128)
+
+ def test_batch_shape_non_std(self):
+ inp = torch.ones(13, 1, 41, 41)
+ sift = SIFTDescriptor(41, 5, 3)
+ out = sift(inp)
+ assert out.shape == (13, (3 ** 2) * 5)
+
+ def test_print(self):
+ sift = SIFTDescriptor(41)
+ sift.__repr__()
+
+ def test_toy(self):
+ patch = torch.ones(1, 1, 6, 6).float()
+ patch[0, 0, :, 3:] = 0
+ sift = SIFTDescriptor(6,
+ num_ang_bins=4,
+ num_spatial_bins=1,
+ clipval=0.2,
+ rootsift=False)
+ out = sift(patch)
+ expected = torch.tensor([[0, 0, 1., 0]])
+ assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
+
+ 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
+ assert gradcheck(sift_describe, (patches, 41),
+ raise_exception=True)