π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] implement deep descriptor sosnet (#521)
yurund1b9553c9393
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 9b406a091..1547f6cfc 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -31,6 +31,7 @@ from .laf import (extract_patches_from_pyramid,laf_from_three_points)from .siftdesc import SIFTDescriptorfrom .hardnet import HardNet+from .sosnet import SOSNetfrom .scale_space_detector import ScaleSpaceDetector, PassLAFfrom .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimatorfrom .orientation import LAFOrienter, PatchDominantGradientOrientationdiff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.pynew file mode 100644index 000000000..f8310a699--- /dev/null+++ b/kornia/feature/sosnet.py@@ -0,0 +1,70 @@+from typing import Dict++import torch+import torch.nn as nn++urls: Dict[str, str] = dict()+urls["lib"] = "https://github.com/yuruntian/SOSNet/tree/master/sosnet-weights/sosnet-32x32-liberty.pth"+urls["hp_a"] = "https://github.com/yuruntian/SOSNet/tree/master/sosnet-weights//sosnet-32x32-hpatches_a.pth"+++class SOSNet(nn.Module):+ """+ 128-dimensional SOSNet model definition for 32x32 patches.+ This is based on the original code from paper+ "SOSNet:Second Order Similarity Regularization for Local Descriptor Learning".+ Args:+ pretrained: (bool) Download and set pretrained weights to the model. Default: false.+ Returns:+ torch.Tensor: SOSNet descriptor of the patches.+ Shape:+ - Input: (B, 1, 32, 32)+ - Output: (B, 128)+ Examples:+ >>> input = torch.rand(8, 1, 32, 32)+ >>> sosnet = kornia.feature.SOSNet()+ >>> descs = sosnet(input) # 8x128+ """+ def __init__(self, pretrained: bool = False) -> None:+ super(SOSNet, self).__init__()++ self.layers = nn.Sequential(+ nn.InstanceNorm2d(1, affine=False),+ 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.1),+ nn.Conv2d(128, 128, kernel_size=8, bias=False),+ nn.BatchNorm2d(128, affine=False),+ )+ self.desc_norm = nn.Sequential(+ nn.LocalResponseNorm(256, alpha=256, beta=0.5, k=0)+ )+ # load pretrained model+ if pretrained:+ pretrained_dict = torch.hub.load_state_dict_from_url(+ urls['lib'], map_location=lambda storage, loc: storage+ )+ self.load_state_dict(pretrained_dict['state_dict'], strict=True)++ return++ def forward(self, input: torch.Tensor, eps: float = 1e-10) -> torch.Tensor: # type: ignore+ descr = self.desc_norm(self.layers(input) + eps)+ descr = descr.view(descr.size(0), -1)+ return descrdiff --git a/test/feature/test_sosnet.py b/test/feature/test_sosnet.pynew file mode 100644index 000000000..c084f75bc--- /dev/null+++ b/test/feature/test_sosnet.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 SOSNet+import kornia.testing as utils # test utils+++class TestSOSNet:+ def test_shape(self, device):+ inp = torch.ones(1, 1, 32, 32, device=device)+ sosnet = SOSNet().to(device)+ sosnet.eval() # batchnorm with size 1 is not allowed in train mode+ out = sosnet(inp)+ assert out.shape == (1, 128)++ def test_shape_batch(self, device):+ inp = torch.ones(16, 1, 32, 32, device=device)+ sosnet = SOSNet().to(device)+ out = sosnet(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+ sosnet = SOSNet().to(patches.device, patches.dtype)+ assert gradcheck(sosnet, (patches,), eps=1e-4, atol=1e-4,+ raise_exception=True, )