Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feature] implement hardnet descriptor (#498)

Edgar Riba1e8c153d716d
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index b3bd8b033..d75e124e3 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -33,6 +33,7 @@ kornia.feature
.. autoclass:: CornerGFTT
.. autoclass:: CornerHarris
.. autoclass:: SIFTDescriptor
+.. autoclass:: HardNet
.. autoclass:: ScaleSpaceDetector
:members: forward
.. autoclass:: PassLAF
diff --git a/docs/source/references.bib b/docs/source/references.bib
index c664af9d0..3f3aab3c2 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -5,8 +5,14 @@
year={2019}
}
@inproceedings{baumberg2000,
+ title={Reliable feature matching across widely separated views},
author={A. {Baumberg}},
booktitle={CVPR},
- title={Reliable feature matching across widely separated views},
year={2000}
-}
\ No newline at end of file
+}
+@inproceedings{HardNet2017,
+ title={Working hard to know your neighbor's margins: Local descriptor learning loss},
+ author={Anastasiya Mishchuk and Dmytro Mishkin and Filip Radenovic and Jiri Matas},
+ booktitle={Proceedings of NIPS},
+ year={2017}
+}
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 984d07bf4..9b406a091 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -30,6 +30,7 @@ from .laf import (extract_patches_from_pyramid,
laf_to_three_points,
laf_from_three_points)
from .siftdesc import SIFTDescriptor
+from .hardnet import HardNet
from .scale_space_detector import ScaleSpaceDetector, PassLAF
from .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator
from .orientation import LAFOrienter, PatchDominantGradientOrientation
@@ -59,6 +60,7 @@ __all__ = [
"get_laf_orientation",
"scale_laf",
"SIFTDescriptor",
+ "HardNet",
"PassLAF",
"ScaleSpaceDetector",
"LAFAffineShapeEstimator",
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
new file mode 100644
index 000000000..5e2a3b50f
--- /dev/null
+++ b/kornia/feature/hardnet.py
@@ -0,0 +1,80 @@
+from typing import Dict
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+urls: Dict[str, str] = dict()
+urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"
+urls["liberty_aug"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" # noqa pylint: disable
+
+
+class HardNet(nn.Module):
+ """
+ Module, which computes HardNet descriptors of given grayscale patches of 32x32.
+
+ This is based on the original code from paper "Working hard to know your neighbor's
+ margins: Local descriptor learning loss". See :cite:`HardNet2017` for more details.
+
+ Args:
+ pretrained: (bool) Download and set pretrained weights to the model. Default: false.
+
+ Returns:
+ torch.Tensor: HardeNet descriptor of the patches.
+
+ Shape:
+ - Input: (B, 1, 32, 32)
+ - Output: (B, 128)
+
+ Examples:
+ >>> input = torch.rand(16, 1, 32, 32)
+ >>> hardnet = kornia.feature.HardNet()
+ >>> descs = hardnet(input) # 16x128
+ """
+ def __init__(self, pretrained: bool = False) -> None:
+ super(HardNet, self).__init__()
+ self.features = nn.Sequential(
+ nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False),
+ nn.BatchNorm2d(32, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(32, 32, kernel_size=3, padding=1, bias=False),
+ nn.BatchNorm2d(32, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(64, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False),
+ nn.BatchNorm2d(64, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(128, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False),
+ nn.BatchNorm2d(128, affine=False),
+ nn.ReLU(),
+ nn.Dropout(0.3),
+ nn.Conv2d(128, 128, kernel_size=8, bias=False),
+ nn.BatchNorm2d(128, affine=False),
+ )
+
+ # use torch.hub to load pretrained model
+ if pretrained:
+ pretrained_dict = torch.hub.load_state_dict_from_url(
+ urls['liberty_aug'], map_location=lambda storage, loc: storage
+ )
+ self.load_state_dict(pretrained_dict['state_dict'], strict=True)
+
+ @staticmethod
+ def _normalize_input(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
+ "Utility function that normalizes the input by batch."""
+ sp, mp = torch.std_mean(x, dim=(-3, -2, -1), keepdim=True)
+ # WARNING: we need to .detach() input, otherwise the gradients produced by
+ # the patches extractor with F.grid_sample are very noisy, making the detector
+ # training totally unstable.
+ return (x - mp.detach()) / (sp.detach() + eps)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ x_norm: torch.Tensor = self._normalize_input(input)
+ x_features: torch.Tensor = self.features(x_norm)
+ x_out = x_features.view(x_features.size(0), -1)
+ return F.normalize(x_out, dim=1)
diff --git a/test/feature/test_hardnet.py b/test/feature/test_hardnet.py
new file mode 100644
index 000000000..f89e4d138
--- /dev/null
+++ b/test/feature/test_hardnet.py
@@ -0,0 +1,32 @@
+import pytest
+from test.common import device
+
+import torch
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+from kornia.feature import HardNet
+import kornia.testing as utils # test utils
+
+
+class TestHardNet:
+ def test_shape(self, device):
+ inp = torch.ones(1, 1, 32, 32, device=device)
+ hardnet = HardNet().to(device)
+ hardnet.eval() # batchnorm with size 1 is not allowed in train mode
+ out = hardnet(inp)
+ assert out.shape == (1, 128)
+
+ def test_shape_batch(self, device):
+ inp = torch.ones(16, 1, 32, 32, device=device)
+ hardnet = HardNet().to(device)
+ out = hardnet(inp)
+ assert out.shape == (16, 128)
+
+ @pytest.mark.skip("jacobian not well computed")
+ def test_gradcheck(self, device):
+ patches = torch.rand(2, 1, 32, 32, device=device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ hardnet = HardNet().to(patches.device, patches.dtype)
+ assert gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4,
+ raise_exception=True, )