π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Hardnet8 (#955)
Dmytro Mishkin0a3624972286
diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex c5ea16b9c..8380b9add 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -26,6 +26,7 @@ Descriptors.. autoclass:: SIFTDescriptor.. autoclass:: MKDDescriptor.. autoclass:: HardNet+.. autoclass:: HardNet8.. autoclass:: TFeat.. autoclass:: SOSNetdiff --git a/docs/source/references.bib b/docs/source/references.bibindex 1916ac15d..5ba592a4a 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -19,6 +19,14 @@year={2017}}++@article{HardNet2020,+ title={Improving the HardNet Descriptor},+ author={Milan Pultar},+ journal={arXiv ePrint 2007.09699},+ year={2020}+}+@inproceedings{TFeat2016,author = {Vassileios Balntas and Edgar Riba and Daniel Ponsa and Krystian Mikolajczyk},title = {Learning local feature descriptors with triplets and shallow convolutional neural networks},diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex fb7d53114..1c62526dd 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -34,7 +34,7 @@ from .laf import (extract_patches_from_pyramid,laf_from_three_points)from .siftdesc import SIFTDescriptorfrom .mkd import MKDDescriptor-from .hardnet import HardNet+from .hardnet import HardNet, HardNet8from .tfeat import TFeatfrom .sosnet import SOSNetfrom .scale_space_detector import ScaleSpaceDetector, PassLAF@@ -73,6 +73,7 @@ __all__ = ["SIFTDescriptor","MKDDescriptor","HardNet",+ "HardNet8","TFeat","OriNet","LAFAffNetShapeEstimator",diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.pyindex 78b323681..20f6fa50a 100644--- a/kornia/feature/hardnet.py+++ b/kornia/feature/hardnet.py@@ -7,6 +7,7 @@ import torch.nn.functional as Furls: 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+urls["hardnet8v2"] = "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt" # noqa pylint: disableclass HardNet(nn.Module):@@ -79,3 +80,91 @@ class HardNet(nn.Module):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)+++class HardNet8(nn.Module):+ """+ Module, which computes HardNet8 descriptors of given grayscale patches of 32x32.++ This is based on the original code from paper "Improving the HardNet Descriptor".+ See :cite:`HardNet2020` for more details.++ Args:+ pretrained: (bool) Download and set pretrained weights to the model. Default: false.++ Returns:+ torch.Tensor: HardNet8 descriptor of the patches.++ Shape:+ - Input: (B, 1, 32, 32)+ - Output: (B, 128)++ Examples:+ >>> input = torch.rand(16, 1, 32, 32)+ >>> hardnet = HardNet8()+ >>> descs = hardnet(input) # 16x128+ """++ def __init__(self, pretrained: bool = False):+ super(HardNet8, 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.Conv2d(128, 256, kernel_size=3, padding=1, bias=False),+ nn.BatchNorm2d(256, affine=False),+ nn.ReLU(),+ nn.Dropout(0.3),+ nn.Conv2d(256, 512, kernel_size=8, bias=False),+ nn.BatchNorm2d(512, affine=False),+ )+ self.features.apply(self.weights_init)+ self.register_buffer('components', torch.ones(512, 128, dtype=torch.float))+ self.register_buffer('mean', torch.zeros(512, dtype=torch.float))+ # use torch.hub to load pretrained model+ if pretrained:+ pretrained_dict = torch.hub.load_state_dict_from_url(+ urls['hardnet8v2'], map_location=lambda storage, loc: storage+ )+ self.load_state_dict(pretrained_dict, strict=True)++ @staticmethod+ def weights_init(m):+ if isinstance(m, nn.Conv2d):+ nn.init.orthogonal_(m.weight.data, gain=0.6)+ try:+ nn.init.constant_(m.bias.data, 0.01)+ except:+ pass++ @staticmethod+ def _normalize_input(x: torch.Tensor, eps: float = 1e-7) -> 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:+ x_norm: torch.Tensor = self._normalize_input(input)+ x_features: torch.Tensor = self.features(x_norm)+ x_prePCA = F.normalize(x_features.view(x_features.size(0), -1))+ pca = torch.mm(x_prePCA - self.mean, self.components) # type: ignore+ # somehow type does not like using torch.mm and buffer...+ return F.normalize(pca, dim=1)diff --git a/test/feature/test_hardnet.py b/test/feature/test_hardnet.pyindex ffe19064e..82455409b 100644--- a/test/feature/test_hardnet.py+++ b/test/feature/test_hardnet.py@@ -4,7 +4,7 @@ import torchfrom torch.testing import assert_allclosefrom torch.autograd import gradcheck-from kornia.feature import HardNet+from kornia.feature import HardNet, HardNet8import kornia.testing as utils # test utils@@ -37,3 +37,34 @@ class TestHardNet:model = HardNet().to(patches.device, patches.dtype).eval()model_jit = torch.jit.script(HardNet().to(patches.device, patches.dtype).eval())assert_allclose(model(patches), model_jit(patches))+++class TestHardNet8:+ def test_shape(self, device):+ inp = torch.ones(1, 1, 32, 32, device=device)+ hardnet = HardNet8().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 = HardNet8().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 = HardNet8().to(patches.device, patches.dtype)+ assert gradcheck(hardnet, (patches,), eps=1e-4, atol=1e-4,+ raise_exception=True, )++ @pytest.mark.jit+ def test_jit(self, device, dtype):+ B, C, H, W = 2, 1, 32, 32+ patches = torch.ones(B, C, H, W, device=device, dtype=dtype)+ model = HardNet8().to(patches.device, patches.dtype).eval()+ model_jit = torch.jit.script(HardNet8().to(patches.device, patches.dtype).eval())+ assert_allclose(model(patches), model_jit(patches))