Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add orientation-preserving option for AffNet and make it default (#1620)

Dmytro Mishkina5e5c8387746
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 6bd562c1e..90694710c 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -1,4 +1,5 @@
import math
+import warnings
from typing import Dict, Optional
import torch
@@ -10,10 +11,12 @@ from kornia.filters.sobel import SpatialGradient
from .laf import (
ellipse_to_laf,
extract_patches_from_pyramid,
+ get_laf_orientation,
get_laf_scale,
make_upright,
raise_error_if_laf_is_not_valid,
scale_laf,
+ set_laf_orientation,
)
urls: Dict[str, str] = {}
@@ -87,17 +90,29 @@ class LAFAffineShapeEstimator(nn.Module):
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.
+ so it is recommended to first run LAFAffineShapeEstimator and then LAFOrienter,
+
Args:
patch_size: the input image patch size.
affine_shape_detector: Patch affine shape estimator, :class:`~kornia.feature.PatchAffineShapeEstimator`.
+ preserve_orientation: if True, the original orientation is preserved.
""" # pylint: disable
- def __init__(self, patch_size: int = 32, affine_shape_detector: Optional[nn.Module] = None) -> None:
+ def __init__(self,
+ patch_size: int = 32,
+ affine_shape_detector: Optional[nn.Module] = None,
+ preserve_orientation: bool = True) -> None:
super().__init__()
self.patch_size = patch_size
self.affine_shape_detector = affine_shape_detector or PatchAffineShapeEstimator(self.patch_size)
+ self.preserve_orientation = preserve_orientation
+ if preserve_orientation:
+ warnings.warn("`LAFAffineShapeEstimator` default behaviour is changed"
+ "and now it does preserve original LAF orientation"
+ "Make sure your code accounts for this",
+ DeprecationWarning,
+ stacklevel=2)
def __repr__(self):
return (
@@ -107,6 +122,9 @@ class LAFAffineShapeEstimator(nn.Module):
+ ', '
+ 'affine_shape_detector='
+ str(self.affine_shape_detector)
+ + ', '
+ + 'preserve_orientation='
+ + str(self.preserve_orientation)
+ ')'
)
@@ -132,9 +150,13 @@ class LAFAffineShapeEstimator(nn.Module):
ellipse_shape: torch.Tensor = self.affine_shape_detector(patches)
ellipses = torch.cat([laf.view(-1, 2, 3)[..., 2].unsqueeze(1), ellipse_shape], dim=2).view(B, N, 5)
scale_orig = get_laf_scale(laf)
+ if self.preserve_orientation:
+ ori_orig = get_laf_orientation(laf)
laf_out = ellipse_to_laf(ellipses)
ellipse_scale = get_laf_scale(laf_out)
laf_out = scale_laf(laf_out, scale_orig / ellipse_scale)
+ if self.preserve_orientation:
+ laf_out = set_laf_orientation(laf_out, ori_orig)
return laf_out
@@ -152,7 +174,7 @@ class LAFAffNetShapeEstimator(nn.Module):
pretrained: Download and set pretrained weights to the model.
"""
- def __init__(self, pretrained: bool = False):
+ def __init__(self, pretrained: bool = False, preserve_orientation: bool = True):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),
@@ -185,6 +207,13 @@ class LAFAffNetShapeEstimator(nn.Module):
urls['affnet'], map_location=lambda storage, loc: storage
)
self.load_state_dict(pretrained_dict['state_dict'], strict=False)
+ self.preserve_orientation = preserve_orientation
+ if preserve_orientation:
+ warnings.warn("`LAFAffNetShapeEstimator` default behaviour is changed"
+ "and now it does preserve original LAF orientation"
+ "Make sure your code accounts for this",
+ DeprecationWarning,
+ stacklevel=2)
self.eval()
@staticmethod
@@ -222,6 +251,10 @@ class LAFAffNetShapeEstimator(nn.Module):
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)
+ if self.preserve_orientation:
+ ori_orig = get_laf_orientation(laf)
ellipse_scale = get_laf_scale(new_laf)
laf_out = scale_laf(make_upright(new_laf), scale_orig / ellipse_scale)
+ if self.preserve_orientation:
+ laf_out = set_laf_orientation(laf_out, ori_orig)
return laf_out
diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.py
index 306e72822..8a3df45b3 100644
--- a/test/feature/test_affine_shape_estimator.py
+++ b/test/feature/test_affine_shape_estimator.py
@@ -66,13 +66,31 @@ class TestLAFAffineShapeEstimator:
sift = LAFAffineShapeEstimator()
sift.__repr__()
- def test_toy(self, device):
- aff = LAFAffineShapeEstimator(32).to(device)
+ def test_toy(self, device, dtype):
+ aff = LAFAffineShapeEstimator(32, preserve_orientation=False).to(device, dtype)
+ inp = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
+ inp[:, :, 15:-15, 9:-9] = 1
+ laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
+ new_laf = aff(laf, inp)
+ expected = torch.tensor([[[[36.643, 0.0, 16.0], [0.0, 10.916, 16.0]]]], device=device, dtype=dtype)
+ assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+
+ def test_toy_preserve(self, device, dtype):
+ aff = LAFAffineShapeEstimator(32, preserve_orientation=True).to(device, dtype)
+ inp = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
+ inp[:, :, 15:-15, 9:-9] = 1
+ laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device, dtype=dtype)
+ new_laf = aff(laf, inp)
+ expected = torch.tensor([[[[0.0, 36.643, 16.0], [-10.916, 0, 16.0]]]], device=device, dtype=dtype)
+ assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
+
+ def test_toy_not_preserve(self, device):
+ aff = LAFAffineShapeEstimator(32, preserve_orientation=False).to(device)
inp = torch.zeros(1, 1, 32, 32, device=device)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device)
+ laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[36.643, 0.0, 16.0], [0.0, 10.916, 16.0]]]], device=device)
+ expected = torch.tensor([[[[36.643, 0, 16.0], [0, 10.916, 16.0]]]], device=device)
assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):