Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Added TFeat, AffNet, OriNet to kornia.features (#846)

Dmytro Mishkin7ff43958ace5
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index dffda8f53..c5ea16b9c 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -26,6 +26,7 @@ Descriptors
.. autoclass:: SIFTDescriptor
.. autoclass:: MKDDescriptor
.. autoclass:: HardNet
+.. autoclass:: TFeat
.. autoclass:: SOSNet
@@ -82,3 +83,9 @@ Module
:members: forward
.. autoclass:: PatchDominantGradientOrientation
:members: forward
+.. autoclass:: OriNet
+ :members: forward
+.. autoclass:: LAFAffNetShapeEstimator
+ :members: forward
+
+
diff --git a/docs/source/references.bib b/docs/source/references.bib
index db3fe3bc3..ad7897385 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -15,46 +15,57 @@
@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},
+ booktitle={Proceedings of NeurIPS},
year={2017}
}
+@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},
+ booktitle = {British Machine Vision Conference {(BMVC)}},
+ year = {2016}
+}
+
@article{mukundan2019understanding,
title={Understanding and improving kernel local descriptors},
author={Mukundan, Arun and Tolias, Giorgos and Bursuc, Andrei and J{\'e}gou, Herv{\'e} and Chum, Ond{\v{r}}ej},
journal={International Journal of Computer Vision},
- year={2019},
+ year={2019}
}
+
@article{zhang2018mixup,
title={mixup: Beyond Empirical Risk Minimization},
author={Hongyi Zhang and Moustapha Cisse nad Yann N. Dauphin and David Lopez-Paz},
journal={International Conference on Learning Representations},
year={2018},
- url={https://openreview.net/forum?id=r1Ddp1-Rb},
+ url={https://openreview.net/forum?id=r1Ddp1-Rb}
+}
+
+@inproceedings{AffNet2018,
+ author = {D. Mishkin and F. Radenovic and J. Matas},
+ title = {{Repeatability is Not Enough: Learning Affine Regions via Discriminability}},
+ booktitle = {ECCV},
+ year = {2018}
}
@inproceedings{yun2019cutmix,
title={CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features},
author={Yun, Sangdoo and Han, Dongyoon and Oh, Seong Joon and Chun, Sanghyuk and Choe, Junsuk and Yoo, Youngjoon},
booktitle = {International Conference on Computer Vision (ICCV)},
- year={2019},
+ year={2019}
}
-@misc{lin2018focal,
+@article{lin2018focal,
title={Focal Loss for Dense Object Detection},
author={Tsung-Yi Lin and Priya Goyal and Ross Girshick and Kaiming He and Piotr Dollár},
year={2018},
- eprint={1708.02002},
- archivePrefix={arXiv},
- primaryClass={cs.CV}
+ journal={arXiv ePrint 1708.02002}
}
-@misc{salehi2017tversky,
+@article{salehi2017tversky,
title={Tversky loss function for image segmentation using 3D fully convolutional deep networks},
author={Seyed Sadegh Mohseni Salehi and Deniz Erdogmus and Ali Gholipour},
year={2017},
- eprint={1706.05721},
- archivePrefix={arXiv},
- primaryClass={cs.CV}
+ journal={arXiv ePrint 1706.05721}
}
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 9926ea844..7c48effbc 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -34,10 +34,11 @@ from .laf import (extract_patches_from_pyramid,
from .siftdesc import SIFTDescriptor
from .mkd import MKDDescriptor
from .hardnet import HardNet
+from .tfeat import TFeat
from .sosnet import SOSNet
from .scale_space_detector import ScaleSpaceDetector, PassLAF
-from .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator
-from .orientation import LAFOrienter, PatchDominantGradientOrientation
+from .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator, LAFAffNetShapeEstimator
+from .orientation import LAFOrienter, PatchDominantGradientOrientation, OriNet
from .matching import match_nn, match_mnn, match_snn, match_smnn
@@ -70,6 +71,9 @@ __all__ = [
"SIFTDescriptor",
"MKDDescriptor",
"HardNet",
+ "TFeat",
+ "OriNet",
+ "LAFAffNetShapeEstimator",
"PassLAF",
"ScaleSpaceDetector",
"LAFAffineShapeEstimator",
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 864ba38e0..931c7f5ff 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -1,4 +1,4 @@
-from typing import Tuple
+from typing import Tuple, Dict, Optional
import torch
import torch.nn as nn
@@ -11,6 +11,9 @@ from kornia.feature.laf import (ellipse_to_laf,
scale_laf, make_upright)
from kornia.feature import extract_patches_from_pyramid
+urls: Dict[str, str] = dict()
+urls["affnet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/AffNet.pth"
+
class PatchAffineShapeEstimator(nn.Module):
"""Module, which estimates the second moment matrix of the patch gradients in order to determine the
@@ -34,11 +37,11 @@ class PatchAffineShapeEstimator(nn.Module):
'patch_size=' + str(self.patch_size) + ', ' + \
'eps=' + str(self.eps) + ')'
- def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, patch: torch.Tensor) -> torch.Tensor:
"""Args:
patch: (torch.Tensor) shape [Bx1xHxW]
Returns:
- ellipse_shape: 3d tensor, shape [Bx1x5] """
+ torch.Tensor: ellipse_shape shape [Bx1x3] """
if not torch.is_tensor(patch):
raise TypeError("Input type is not a torch.Tensor. Got {}"
.format(type(patch)))
@@ -72,15 +75,17 @@ class PatchAffineShapeEstimator(nn.Module):
class LAFAffineShapeEstimator(nn.Module):
"""Module, which extracts patches using input images and local affine frames (LAFs),
- then runs :class:`~kornia.feature.PatchAffineShapeEstimator` on patches to estimate LAFs shape.
+ then runs :class:`~kornia.feature.PatchAffineShapeEstimator`
+ on patches to estimate LAFs shape.
Then original LAF shape is replaced with estimated one. The original LAF orientation is not preserved,
so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter.
Args:
- patch_size: int, default = 32"""
-
+ patch_size: int, default = 32
+ affine_shape_detector: nn.Module. Patch affine shape estimator, e.g. PatchAffineShapeEstimator. Default: None """ # noqa pylint: disable
def __init__(self,
- patch_size: int = 32) -> None:
+ patch_size: int = 32,
+ affine_shape_detector: Optional[nn.Module] = None) -> None:
super(LAFAffineShapeEstimator, self).__init__()
self.patch_size = patch_size
self.affine_shape_detector = PatchAffineShapeEstimator(self.patch_size)
@@ -88,16 +93,17 @@ class LAFAffineShapeEstimator(nn.Module):
def __repr__(self):
return self.__class__.__name__ + '('\
- 'patch_size=' + str(self.patch_size) + ')'
+ 'patch_size=' + str(self.patch_size) + ', ' + \
+ 'affine_shape_detector=' + str(self.affine_shape_detector) + ')'
- def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
"""
Args:
laf: (torch.Tensor) shape [BxNx2x3]
img: (torch.Tensor) shape [Bx1xHxW]
Returns:
- laf_out: (torch.Tensor) shape [BxNx2x3]"""
+ torch.Tensor: laf_out shape [BxNx2x3]"""
raise_error_if_laf_is_not_valid(laf)
img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
if not torch.is_tensor(img):
@@ -120,3 +126,93 @@ class LAFAffineShapeEstimator(nn.Module):
ellipse_scale = get_laf_scale(laf_out)
laf_out = scale_laf(laf_out, scale_orig / ellipse_scale)
return laf_out
+
+
+class LAFAffNetShapeEstimator(nn.Module):
+ """Module, which extracts patches using input images and local affine frames (LAFs),
+ then runs AffNet on patches to estimate LAFs shape.
+ This is based on the original code from paper "Repeatability Is Not Enough:
+ Learning Discriminative Affine Regions via Discriminability"".
+ See :cite:`AffNet2018` for more details.
+ Then original LAF shape is replaced with estimated one. The original LAF orientation is not preserved,
+ so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter.
+
+ Args:
+ pretrained: (bool) Download and set pretrained weights to the model. Default: false.
+ """
+ def __init__(self, pretrained: bool = False):
+ super(LAFAffNetShapeEstimator, self).__init__()
+ self.features = nn.Sequential(
+ nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),
+ nn.BatchNorm2d(16, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False),
+ nn.BatchNorm2d(16, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(32, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(32, 32, kernel_size=3, stride=1, 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, stride=1, padding=1, bias=False),
+ nn.BatchNorm2d(64, affine=False),
+ nn.ReLU(),
+ nn.Dropout(0.25),
+ nn.Conv2d(64, 3, kernel_size=8, stride=1, padding=0, bias=True),
+ nn.Tanh(),
+ nn.AdaptiveAvgPool2d(1)
+ )
+ self.patch_size = 32
+ # use torch.hub to load pretrained model
+ if pretrained:
+ pretrained_dict = torch.hub.load_state_dict_from_url(
+ urls['affnet'], map_location=lambda storage, loc: storage
+ )
+ self.load_state_dict(pretrained_dict['state_dict'], strict=False)
+ return
+
+ @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, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ laf: (torch.Tensor) shape [BxNx2x3]
+ img: (torch.Tensor) shape [Bx1xHxW]
+
+ Returns:
+ torch.Tensor: laf_out shape [BxNx2x3]"""
+ raise_error_if_laf_is_not_valid(laf)
+ img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
+ if not torch.is_tensor(img):
+ raise TypeError("img type is not a torch.Tensor. Got {}"
+ .format(type(img)))
+ if len(img.shape) != 4:
+ raise ValueError(img_message)
+ if laf.size(0) != img.size(0):
+ raise ValueError("Batch size of laf and img should be the same. Got {}, {}"
+ .format(img.size(0), laf.size(0)))
+ B, N = laf.shape[:2]
+ PS: int = self.patch_size
+ patches: torch.Tensor = extract_patches_from_pyramid(img,
+ make_upright(laf),
+ PS, True).view(-1, 1, PS, PS)
+ xy = self.features(self._normalize_input(patches)).view(-1, 3)
+ a1 = torch.cat([1.0 + xy[:, 0].reshape(-1, 1, 1), 0 * xy[:, 0].reshape(-1, 1, 1)], dim=2)
+ a2 = torch.cat([xy[:, 1].reshape(-1, 1, 1), 1.0 + xy[:, 2].reshape(-1, 1, 1)], dim=2)
+ new_laf_no_center = torch.cat([a1, a2], dim=1).reshape(B, N, 2, 2)
+ new_laf = torch.cat([new_laf_no_center, laf[:, :, :, 2:3]], dim=3)
+ scale_orig = get_laf_scale(laf)
+ ellipse_scale = get_laf_scale(new_laf)
+ laf_out = scale_laf(make_upright(new_laf), scale_orig / ellipse_scale)
+ return laf_out
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 7ea0094aa..f8ba8e486 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -1,4 +1,4 @@
-from typing import Tuple
+from typing import Tuple, Dict, Optional
import torch
import torch.nn as nn
@@ -11,6 +11,9 @@ from kornia.feature import (extract_patches_from_pyramid, make_upright,
normalize_laf, raise_error_if_laf_is_not_valid)
from kornia.geometry import rad2deg, angle_to_rotation_matrix
+urls: Dict[str, str] = dict()
+urls["orinet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/OriNet.pth"
+
class PassLAF(nn.Module):
"""Dummy module to use instead of local feature orientation or affine shape estimator"""
@@ -56,11 +59,11 @@ class PatchDominantGradientOrientation(nn.Module):
'num_ang_bins=' + str(self.num_ang_bins) + ', ' + \
'eps=' + str(self.eps) + ')'
- def forward(self, patch: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, patch: torch.Tensor) -> torch.Tensor:
"""Args:
patch: (torch.Tensor) shape [Bx1xHxW]
Returns:
- patch: (torch.Tensor) shape [Bx1] """
+ torch.Tensor: angle shape [B] """
if not torch.is_tensor(patch):
raise TypeError("Input type is not a torch.Tensor. Got {}"
.format(type(patch)))
@@ -100,37 +103,119 @@ class PatchDominantGradientOrientation(nn.Module):
return angle
+class OriNet(nn.Module):
+ """Network, which estimates the canonical orientation of the given 32x32 patches, in radians.
+ Zero angle points towards right.
+ This is based on the original code from paper "Repeatability Is Not Enough:
+ Learning Discriminative Affine Regions via Discriminability"".
+ See :cite:`AffNet2018` for more details.
+
+ Args:
+ pretrained: (bool) Download and set pretrained weights to the model. Default: false.
+ eps: (float) to avoid division by zero in atan2. Default: 1e-6.
+
+ Returns:
+ torch.Tensor: Angle in radians.
+
+ Shape:
+ - Input: (B, 1, 32, 32)
+ - Output: (B)
+
+ Examples:
+ >>> input = torch.rand(16, 1, 32, 32)
+ >>> orinet = OriNet()
+ >>> angle = orinet(input) # 16
+ """
+ def __init__(self, pretrained: bool = False, eps: float = 1e-8):
+ super(OriNet, self).__init__()
+ self.features = nn.Sequential(
+ nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),
+ nn.BatchNorm2d(16, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(16, 16, kernel_size=3, stride=1, padding=1, bias=False),
+ nn.BatchNorm2d(16, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1, bias=False),
+ nn.BatchNorm2d(32, affine=False),
+ nn.ReLU(),
+ nn.Conv2d(32, 32, kernel_size=3, stride=1, 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, stride=1, padding=1, bias=False),
+ nn.BatchNorm2d(64, affine=False),
+ nn.ReLU(),
+ nn.Dropout(0.25),
+ nn.Conv2d(64, 2, kernel_size=8, stride=1, padding=1, bias=True),
+ nn.Tanh(),
+ nn.AdaptiveAvgPool2d(1)
+ )
+ self.eps = eps
+ # use torch.hub to load pretrained model
+ if pretrained:
+ pretrained_dict = torch.hub.load_state_dict_from_url(
+ urls['orinet'], map_location=lambda storage, loc: storage
+ )
+ self.load_state_dict(pretrained_dict['state_dict'], strict=False)
+ return
+
+ @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, patch: torch.Tensor) -> torch.Tensor: # type: ignore
+ """Args:
+ patch: (torch.Tensor) shape [Bx1xHxW]
+ Returns:
+ patch: (torch.Tensor) shape [B] """
+ xy = self.features(self._normalize_input(patch)).view(-1, 2)
+ angle = torch.atan2(xy[:, 0] + 1e-8, xy[:, 1] + self.eps)
+ return angle
+
+
class LAFOrienter(nn.Module):
"""Module, which extracts patches using input images and local affine frames (LAFs),
- then runs :class:`~kornia.feature.PatchDominantGradientOrientation`
- on patches and then rotates the LAFs by the estimated angles
+ then runs :class:`~kornia.feature.PatchDominantGradientOrientation` or
+ :class:`~kornia.feature.OriNet` on patches and then rotates the LAFs by the estimated angles
Args:
patch_size: int, default = 32
- num_angular_bins: int, default is 36"""
+ num_angular_bins: int, default is 36
+ angle_detector: nn.Module. Patch orientation estimator, e.g. PatchDominantGradientOrientation or OriNet. Default: None """ # noqa pylint: disable
def __init__(self,
patch_size: int = 32,
- num_angular_bins: int = 36):
+ num_angular_bins: int = 36,
+ angle_detector: Optional[nn.Module] = None): # type: ignore
super(LAFOrienter, self).__init__()
self.patch_size = patch_size
self.num_ang_bins = num_angular_bins
- self.angle_detector = PatchDominantGradientOrientation(self.patch_size, self.num_ang_bins)
+ if angle_detector is None:
+ self.angle_detector = PatchDominantGradientOrientation(self.patch_size, self.num_ang_bins) # type: ignore
+ else:
+ self.angle_detector = angle_detector # type: ignore
return
def __repr__(self):
return self.__class__.__name__ + '('\
'patch_size=' + str(self.patch_size) + ', ' + \
- 'num_ang_bins=' + str(self.num_ang_bins) + ')'
+ 'angle_detector=' + str(self.angle_detector) + ')'
- def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
"""
Args:
laf: (torch.Tensor), shape [BxNx2x3]
img: (torch.Tensor), shape [Bx1xHxW]
Returns:
- laf_out: (torch.Tensor), shape [BxNx2x3] """
+ torch.Tensor: laf_out, shape [BxNx2x3] """
raise_error_if_laf_is_not_valid(laf)
img_message: str = "Invalid img shape, we expect BxCxHxW. Got: {}".format(img.shape)
if not torch.is_tensor(img):
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
new file mode 100644
index 000000000..8acb21d36
--- /dev/null
+++ b/kornia/feature/tfeat.py
@@ -0,0 +1,62 @@
+from typing import Dict
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+urls: Dict[str, str] = dict()
+urls["liberty"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # noqa pylint: disable
+urls["notredame"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-notredame.params" # noqa pylint: disable
+urls["yosemite"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-yosemite.params" # noqa pylint: disable
+
+
+class TFeat(nn.Module):
+ """
+ Module, which computes TFeat descriptors of given grayscale patches of 32x32.
+
+ This is based on the original code from paper "Learning local feature descriptors
+ with triplets and shallow convolutional neural networks".
+ See :cite:`TFeat2016` for more details
+
+ Args:
+ pretrained: (bool) Download and set pretrained weights to the model. Default: false.
+
+ Returns:
+ torch.Tensor: TFeat descriptor of the patches.
+
+ Shape:
+ - Input: (B, 1, 32, 32)
+ - Output: (B, 128)
+
+ Examples:
+ >>> input = torch.rand(16, 1, 32, 32)
+ >>> tfeat = TFeat()
+ >>> descs = tfeat(input) # 16x128
+ """
+
+ def __init__(self, pretrained: bool = False) -> None:
+ super(TFeat, self).__init__()
+ self.features = nn.Sequential(
+ nn.InstanceNorm2d(1, affine=False),
+ nn.Conv2d(1, 32, kernel_size=7),
+ nn.Tanh(),
+ nn.MaxPool2d(kernel_size=2, stride=2),
+ nn.Conv2d(32, 64, kernel_size=6),
+ nn.Tanh()
+ )
+ self.descr = nn.Sequential(
+ nn.Linear(64 * 8 * 8, 128),
+ nn.Tanh()
+ )
+ # use torch.hub to load pretrained model
+ if pretrained:
+ pretrained_dict = torch.hub.load_state_dict_from_url(
+ urls['liberty'], map_location=lambda storage, loc: storage
+ )
+ self.load_state_dict(pretrained_dict, strict=True)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ x = self.features(input)
+ x = x.view(x.size(0), -1)
+ x = self.descr(x)
+ return x
diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.py
index f5f01d7e5..8624e90f6 100644
--- a/test/feature/test_affine_shape_estimator.py
+++ b/test/feature/test_affine_shape_estimator.py
@@ -77,3 +77,59 @@ class TestLAFAffineShapeEstimator:
laf = utils.tensor_to_gradcheck_var(laf) # to var
assert gradcheck(LAFAffineShapeEstimator(11).to(device), (laf, patches),
raise_exception=True, rtol=1e-3, atol=1e-3, nondet_tol=1e-4)
+
+
+class TestLAFAffNetShapeEstimator:
+ def test_shape(self, device):
+ inp = torch.rand(1, 1, 32, 32, device=device)
+ laf = torch.rand(1, 1, 2, 3, device=device)
+ ori = LAFAffNetShapeEstimator(False).to(device).eval()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_pretrained(self, device):
+ inp = torch.rand(1, 1, 32, 32, device=device)
+ laf = torch.rand(1, 1, 2, 3, device=device)
+ ori = LAFAffNetShapeEstimator(True).to(device).eval()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_shape_batch(self, device):
+ inp = torch.rand(2, 1, 32, 32, device=device)
+ laf = torch.rand(2, 5, 2, 3, device=device)
+ ori = LAFAffNetShapeEstimator().to(device).eval()
+ out = ori(laf, inp)
+ assert out.shape == laf.shape
+
+ def test_print(self, device):
+ sift = LAFAffNetShapeEstimator()
+ sift.__repr__()
+
+ def test_toy(self, device):
+ aff = LAFAffNetShapeEstimator(True).to(device).eval()
+ inp = torch.zeros(1, 1, 32, 32, device=device)
+ inp[:, :, 15:-15, 9:-9] = 1
+ laf = torch.tensor([[[[20., 0., 16.], [0., 20., 16.]]]], device=device)
+ new_laf = aff(laf, inp)
+ expected = torch.tensor([[[[40.8758, 0., 16.], [-0.3824, 9.7857, 16.]]]], device=device)
+ assert_allclose(new_laf, expected, atol=1e-4, rtol=1e-4)
+
+ @pytest.mark.skip("jacobian not well computed")
+ def test_gradcheck(self, device):
+ batch_size, channels, height, width = 1, 1, 35, 35
+ patches = torch.rand(batch_size, channels, height, width, device=device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ laf = torch.tensor([[[[8., 0., 16.], [0., 8., 16.]]]], device=device)
+ laf = utils.tensor_to_gradcheck_var(laf) # to var
+ assert gradcheck(LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype), (laf, patches),
+ raise_exception=True, rtol=1e-3, atol=1e-3, nondet_tol=1e-4)
+
+ @pytest.mark.jit
+ @pytest.mark.skip("Laf type is not a torch.Tensor????")
+ def test_jit(self, device, dtype):
+ B, C, H, W = 1, 1, 32, 32
+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ laf = torch.tensor([[[[8., 0., 16.], [0., 8., 16.]]]], device=device)
+ laf_estimator = LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype).eval()
+ laf_estimator_jit = torch.jit.script(LAFAffNetShapeEstimator(True).to(device, dtype=patches.dtype).eval())
+ assert_allclose(laf_estimator(laf, patches), laf_estimator_jit(laf, patches))
diff --git a/test/feature/test_local_features_orientation.py b/test/feature/test_local_features_orientation.py
index 738fa656e..1bd3d18a4 100644
--- a/test/feature/test_local_features_orientation.py
+++ b/test/feature/test_local_features_orientation.py
@@ -76,6 +76,54 @@ class TestPatchDominantGradientOrientation:
raise_exception=True)
+class TestOriNet:
+ def test_shape(self, device):
+ inp = torch.rand(1, 1, 32, 32, device=device)
+ ori = OriNet().to(device=device, dtype=inp.dtype).eval()
+ ang = ori(inp)
+ assert ang.shape == torch.Size([1])
+
+ def test_pretrained(self, device):
+ inp = torch.rand(1, 1, 32, 32, device=device)
+ ori = OriNet(True).to(device=device, dtype=inp.dtype).eval()
+ ang = ori(inp)
+ assert ang.shape == torch.Size([1])
+
+ def test_shape_batch(self, device):
+ inp = torch.rand(2, 1, 32, 32, device=device)
+ ori = OriNet(True).to(device=device, dtype=inp.dtype).eval()
+ ang = ori(inp)
+ assert ang.shape == torch.Size([2])
+
+ def test_print(self, device):
+ sift = OriNet(32)
+ sift.__repr__()
+
+ def test_toy(self, device):
+ inp = torch.zeros(1, 1, 32, 32, device=device)
+ inp[:, :, :16, :] = 1
+ ori = OriNet(True).to(device=device, dtype=inp.dtype).eval()
+ ang = ori(inp)
+ expected = torch.tensor([70.58], device=device)
+ assert_allclose(kornia.rad2deg(ang), expected, atol=1e-2, rtol=1e-3)
+
+ @pytest.mark.skip("jacobian not well computed")
+ def test_gradcheck(self, device):
+ batch_size, channels, height, width = 2, 1, 32, 32
+ patches = torch.rand(batch_size, channels, height, width, device=device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ ori = OriNet().to(device=device, dtype=patches.dtype)
+ assert gradcheck(ori, (patches, ), 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)
+ tfeat = OriNet(True).to(patches.device, patches.dtype).eval()
+ tfeat_jit = torch.jit.script(OriNet(True).to(patches.device, patches.dtype).eval())
+ assert_allclose(tfeat_jit(patches), tfeat(patches))
+
+
class TestLAFOrienter:
def test_shape(self, device):
inp = torch.rand(1, 1, 32, 32, device=device)
diff --git a/test/feature/test_tfeat.py b/test/feature/test_tfeat.py
new file mode 100644
index 000000000..606a2bd65
--- /dev/null
+++ b/test/feature/test_tfeat.py
@@ -0,0 +1,45 @@
+import pytest
+
+import torch
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+from kornia.feature import TFeat
+import kornia.testing as utils # test utils
+
+
+class TestTFeat:
+ def test_shape(self, device):
+ inp = torch.ones(1, 1, 32, 32, device=device)
+ tfeat = TFeat().to(device)
+ tfeat.eval() # batchnorm with size 1 is not allowed in train mode
+ out = tfeat(inp)
+ assert out.shape == (1, 128)
+
+ def test_pretrained(self, device):
+ inp = torch.ones(1, 1, 32, 32, device=device)
+ tfeat = TFeat(True).to(device)
+ tfeat.eval() # batchnorm with size 1 is not allowed in train mode
+ out = tfeat(inp)
+ assert out.shape == (1, 128)
+
+ def test_shape_batch(self, device):
+ inp = torch.ones(16, 1, 32, 32, device=device)
+ tfeat = TFeat().to(device)
+ out = tfeat(inp)
+ assert out.shape == (16, 128)
+
+ def test_gradcheck(self, device):
+ patches = torch.rand(2, 1, 32, 32, device=device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ tfeat = TFeat().to(patches.device, patches.dtype)
+ assert gradcheck(tfeat, (patches,), eps=1e-2, atol=1e-2,
+ 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)
+ tfeat = TFeat(True).to(patches.device, patches.dtype).eval()
+ tfeat_jit = torch.jit.script(TFeat(True).to(patches.device, patches.dtype).eval())
+ assert_allclose(tfeat_jit(patches), tfeat(patches))