Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Dense SIFT (#962)

Dmytro Mishkinbde816e32bda
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 8f89d56a4..c8ce7381c 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -15,6 +15,7 @@ Detectors
Descriptors
-----------
+.. autoclass:: DenseSIFTDescriptor
.. autoclass:: SIFTDescriptor
.. autoclass:: MKDDescriptor
.. autoclass:: HardNet
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 478ee5618..b8076ebb5 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -45,7 +45,7 @@ from .responses import (
hessian_response,
)
from .scale_space_detector import PassLAF, ScaleSpaceDetector
-from .siftdesc import SIFTDescriptor
+from .siftdesc import DenseSIFTDescriptor, SIFTDescriptor
from .sosnet import SOSNet
from .tfeat import TFeat
@@ -84,6 +84,7 @@ __all__ = [
"get_laf_descriptors",
"scale_laf",
"SIFTDescriptor",
+ "DenseSIFTDescriptor",
"MKDDescriptor",
"HardNet",
"HardNet8",
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index d69a2eac0..e3d32b6b5 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -9,6 +9,13 @@ from kornia.filters import get_gaussian_kernel2d, spatial_gradient
from kornia.geometry.conversions import pi
+def _get_reshape_kernel(kd: int, ky: int, kx: int) -> torch.Tensor:
+ """Utility function, which returns neigh2channels conv kernel."""
+ numel: int = kd * ky * kx
+ weight = torch.eye(numel)
+ return weight.view(numel, kd, ky, kx)
+
+
def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
r"""Return a weighted pooling kernel for SIFT descriptor.
@@ -55,7 +62,7 @@ class SIFTDescriptor(nn.Module):
patch_size: Input patch size in pixels.
num_ang_bins: Number of angular bins.
num_spatial_bins: Number of spatial bins.
- clipval:
+ clipval: clipping value to reduce single-bin dominance
rootsift: if ``True``, RootSIFT (Arandjelović et. al, 2012) is computed.
Returns:
@@ -176,16 +183,123 @@ class SIFTDescriptor(nn.Module):
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"""Compute the sift descriptor.
-
+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)
+
+
+class DenseSIFTDescriptor(nn.Module):
+ """Module, which computes SIFT descriptor densely over the image.
+
+ Args:
+ num_ang_bins: Number of angular bins. (8 is default)
+ num_spatial_bins: Number of spatial bins per descriptor (4 is default).
+ You might want to set odd number and relevant padding to keep feature map size
+ spatial_bin_size: Size of a spatial bin in pixels (4 is default)
+ clipval: clipping value to reduce single-bin dominance
+ rootsift: (bool) if True, RootSIFT (Arandjelović et. al, 2012) is computed
+ stride: default 1
+ padding: default 0
+
+ Returns:
+ torch.Tensor: DenseSIFT descriptor of the image
+
+ Shape:
+ - Input: (B, 1, H, W)
+ - Output: (B, num_ang_bins * num_spatial_bins ** 2, (H+padding)/stride, (W+padding)/stride)
+
+ Examples::
+ >>> input = torch.rand(2, 1, 200, 300)
+ >>> SIFT = DenseSIFTDescriptor()
+ >>> descs = SIFT(input) # 2x128x194x294
+ """
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'num_ang_bins=' + str(self.num_ang_bins) +\
+ ', ' + 'num_spatial_bins=' + str(self.num_spatial_bins) +\
+ ', ' + 'spatial_bin_size=' + str(self.spatial_bin_size) +\
+ ', ' + 'rootsift=' + str(self.rootsift) +\
+ ', ' + 'stride=' + str(self.stride) +\
+ ', ' + 'clipval=' + str(self.clipval) + ')'
+
+ def __init__(self,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+ spatial_bin_size: int = 4,
+ rootsift: bool = True,
+ clipval: float = 0.2,
+ stride: int = 1,
+ padding: int = 1,
+ ) -> None:
+ super().__init__()
+ self.eps = 1e-10
+ self.num_ang_bins = num_ang_bins
+ self.num_spatial_bins = num_spatial_bins
+ self.spatial_bin_size = spatial_bin_size
+ self.clipval = clipval
+ self.rootsift = rootsift
+ self.stride = stride
+ self.pad = padding
+ nw = get_sift_pooling_kernel(ksize=self.spatial_bin_size).float()
+ self.bin_pooling_kernel = nn.Conv2d(1, 1, kernel_size=(nw.size(0), nw.size(1)),
+ stride=(1, 1),
+ bias=False,
+ padding=(nw.size(0) // 2, nw.size(1) // 2))
+ self.bin_pooling_kernel.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1)))
+ self.PoolingConv = nn.Conv2d(num_ang_bins,
+ num_ang_bins * num_spatial_bins**2,
+ kernel_size=(num_spatial_bins, num_spatial_bins),
+ stride=(self.stride, self.stride), bias=False, padding=(self.pad, self.pad))
+ self.PoolingConv.weight.data.copy_(_get_reshape_kernel(num_ang_bins,
+ num_spatial_bins,
+ num_spatial_bins).float())
+ return
+
+ def get_pooling_kernel(self) -> torch.Tensor:
+ return self.bin_pooling_kernel.weight.detach()
+
+ def forward(self, input):
+ if not isinstance(input, torch.Tensor):
+ 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()
+ self.bin_pooling_kernel = self.bin_pooling_kernel.to(input.dtype).to(input.device)
+ self.PoolingConv = self.PoolingConv.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
+ 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.bin_pooling_kernel((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)
+ out_no_norm = self.PoolingConv(ang_bins)
+ out = F.normalize(out_no_norm, dim=1, p=2).clamp_(0, float(self.clipval))
+ out = F.normalize(out, dim=1, p=2)
+ if self.rootsift:
+ out = torch.sqrt(F.normalize(out, p=1) + self.eps)
+ return out
diff --git a/test/feature/test_siftdesc.py b/test/feature/test_siftdesc.py
index 08b5b0950..b3926cd3f 100644
--- a/test/feature/test_siftdesc.py
+++ b/test/feature/test_siftdesc.py
@@ -3,7 +3,12 @@ import torch
from torch.autograd import gradcheck
import kornia.testing as utils # test utils
-from kornia.feature.siftdesc import SIFTDescriptor, get_sift_bin_ksize_stride_pad, get_sift_pooling_kernel
+from kornia.feature.siftdesc import (
+ DenseSIFTDescriptor,
+ SIFTDescriptor,
+ get_sift_bin_ksize_stride_pad,
+ get_sift_pooling_kernel,
+)
from kornia.testing import assert_close
@@ -58,6 +63,41 @@ class TestSIFTDescriptor:
def test_jit(self, device, dtype):
B, C, H, W = 1, 1, 32, 32
patches = torch.ones(B, C, H, W, device=device, dtype=dtype)
- model = SIFTDescriptor(32).to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(model)
+ model = SIFTDescriptor(41).to(patches.device, patches.dtype).eval()
+ model_jit = torch.jit.script(SIFTDescriptor(41).to(patches.device, patches.dtype).eval())
assert_close(model(patches), model_jit(patches))
+
+
+class TestDenseSIFTDescriptor:
+ def test_shape_default(self, device, dtype):
+ bs, h, w = 1, 40, 30
+ inp = torch.rand(1, 1, h, w, device=device, dtype=dtype)
+ sift = DenseSIFTDescriptor().to(device, dtype)
+ out = sift(inp)
+ assert out.shape == torch.Size([bs, 128, h, w])
+
+ def test_batch_shape(self, device, dtype):
+ bs, h, w = 2, 32, 15
+ inp = torch.rand(bs, 1, h, w, device=device, dtype=dtype)
+ sift = DenseSIFTDescriptor().to(device, dtype)
+ out = sift(inp)
+ assert out.shape == torch.Size([bs, 128, h, w])
+
+ def test_batch_shape_custom(self, device, dtype):
+ bs, h, w = 2, 40, 30
+ inp = torch.rand(bs, 1, h, w, device=device, dtype=dtype)
+ sift = DenseSIFTDescriptor(5, 3, 3, padding=1, stride=2).to(device, dtype)
+ out = sift(inp)
+ assert out.shape == torch.Size([bs, 45, h // 2, w // 2])
+
+ def test_print(self, device):
+ sift = DenseSIFTDescriptor()
+ sift.__repr__()
+
+ @pytest.mark.xfail(reason='May raise checkIfNumericalAnalyticAreClose.')
+ def test_gradcheck(self, device):
+ batch_size, channels, height, width = 1, 1, 32, 32
+ patches = torch.rand(batch_size, channels, height, width, device=device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ assert gradcheck(DenseSIFTDescriptor(4, 2, 2), (patches),
+ raise_exception=True, nondet_tol=1e-4)