Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

added default params for laf construction from xy and new tensor shape check (#1633)

Dmytro Mishkind24ae7ffcd80
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 90694710c..33c9d3a14 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -7,6 +7,7 @@ import torch.nn as nn
from kornia.filters.kernels import get_gaussian_kernel2d
from kornia.filters.sobel import SpatialGradient
+from kornia.testing import KORNIA_CHECK_SHAPE
from .laf import (
ellipse_to_laf,
@@ -49,16 +50,7 @@ class PatchAffineShapeEstimator(nn.Module):
patch: (torch.Tensor) shape [Bx1xHxW]
Returns:
torch.Tensor: ellipse_shape shape [Bx1x3]"""
- if not isinstance(patch, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(patch)}")
- if not len(patch.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {patch.shape}")
- _, CH, W, H = patch.size()
- if (W != self.patch_size) or (H != self.patch_size) or (CH != 1):
- raise TypeError(
- "input shape should be must be [Bx1x{}x{}]. "
- "Got {}".format(self.patch_size, self.patch_size, patch.size())
- )
+ KORNIA_CHECK_SHAPE(patch, ["B", "1", "H", "W"])
self.weighting = self.weighting.to(patch.dtype).to(patch.device)
grads: torch.Tensor = self.gradient(patch) * self.weighting
# unpack the edges
@@ -137,13 +129,7 @@ class LAFAffineShapeEstimator(nn.Module):
Returns:
torch.Tensor: laf_out shape [BxNx2x3]"""
raise_error_if_laf_is_not_valid(laf)
- img_message: str = f"Invalid img shape, we expect BxCxHxW. Got: {img.shape}"
- if not isinstance(img, torch.Tensor):
- raise TypeError(f"img type is not a torch.Tensor. Got {type(img)}")
- if len(img.shape) != 4:
- raise ValueError(img_message)
- if laf.size(0) != img.size(0):
- raise ValueError(f"Batch size of laf and img should be the same. Got {img.size(0)}, {laf.size(0)}")
+ KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
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)
@@ -235,13 +221,7 @@ class LAFAffNetShapeEstimator(nn.Module):
laf_out shape [BxNx2x3]
"""
raise_error_if_laf_is_not_valid(laf)
- img_message: str = f"Invalid img shape, we expect BxCxHxW. Got: {img.shape}"
- if not torch.is_tensor(img):
- raise TypeError(f"img type is not a torch.Tensor. Got {type(img)}")
- if len(img.shape) != 4:
- raise ValueError(img_message)
- if laf.size(0) != img.size(0):
- raise ValueError(f"Batch size of laf and img should be the same. Got {img.size(0)}, {laf.size(0)}")
+ KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])
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)
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 0eff69fcb..30b4f1567 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -4,6 +4,8 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
+from kornia.testing import KORNIA_CHECK_SHAPE
+
urls: Dict[str, str] = {}
urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"
urls[
@@ -79,6 +81,7 @@ class HardNet(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
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)
@@ -165,6 +168,7 @@ class HardNet8(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
x_norm: torch.Tensor = self._normalize_input(input)
x_features: torch.Tensor = self.features(x_norm)
mean: torch.Tensor = torch.jit.annotate(torch.Tensor, self.mean)
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index fdcfeccff..e89099f03 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -1,5 +1,5 @@
import math
-from typing import Union
+from typing import Optional, Union
import torch
import torch.nn.functional as F
@@ -7,6 +7,7 @@ import torch.nn.functional as F
from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2deg
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import pyrdown
+from kornia.testing import KORNIA_CHECK_SHAPE
def raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:
@@ -15,14 +16,7 @@ def raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:
Args:
laf: [BxNx2x3] shape.
"""
- laf_message: str = f"Invalid laf shape, we expect BxNx2x3. Got: {laf.shape}"
- if not isinstance(laf, torch.Tensor):
- raise TypeError(f"Laf type is not a torch.Tensor. Got {type(laf)}")
- if len(laf.shape) != 4:
- raise ValueError(laf_message)
- if laf.size(2) != 2 or laf.size(3) != 3:
- raise ValueError(laf_message)
- return
+ KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"])
def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
@@ -115,30 +109,29 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc
return laf_out
-def laf_from_center_scale_ori(xy: torch.Tensor, scale: torch.Tensor, ori: torch.Tensor) -> torch.Tensor:
+def laf_from_center_scale_ori(xy: torch.Tensor,
+ scale: Optional[torch.Tensor] = None,
+ ori: Optional[torch.Tensor] = None) -> torch.Tensor:
"""Return orientation of the LAFs, in radians. Useful to create kornia LAFs from OpenCV keypoints.
Args:
xy: tensor [BxNx2].
- scale: tensor [BxNx1x1].
- ori: tensor [BxNx1].
+ scale: tensor [BxNx1x1]. If not provided, scale = 1 is assumed
+ ori: tensor [BxNx1]. If not provided orientation = 0 is assumed
Returns:
tensor BxNx2x3.
"""
- names = ['xy', 'scale', 'ori']
- for var_name, var, req_shape in zip(names, [xy, scale, ori], [("B", "N", 2), ("B", "N", 1, 1), ("B", "N", 1)]):
- if not isinstance(var, torch.Tensor):
- raise TypeError(f"{var_name} type is not a torch.Tensor. Got {type(var)}")
- if len(var.shape) != len(req_shape): # type: ignore # because it does not like len(tensor.shape)
- raise TypeError("{} shape should be must be [{}]. " "Got {}".format(var_name, str(req_shape), var.size()))
- for i, dim in enumerate(req_shape): # type: ignore # because it wants typing for dim
- if dim is not int:
- continue
- if var.size(i) != dim:
- raise TypeError(
- "{} shape should be must be [{}]. " "Got {}".format(var_name, str(req_shape), var.size())
- )
+ KORNIA_CHECK_SHAPE(xy, ["B", "N", "2"])
+ device = xy.device
+ dtype = xy.dtype
+ B, N = xy.shape[:2]
+ if scale is None:
+ scale = torch.ones(B, N, 1, 1, device=device, dtype=dtype)
+ if ori is None:
+ ori = torch.zeros(B, N, 1, device=device, dtype=dtype)
+ KORNIA_CHECK_SHAPE(scale, ["B", "N", "1", "1"])
+ KORNIA_CHECK_SHAPE(ori, ["B", "N", "1"])
unscaled_laf: torch.Tensor = torch.cat([angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)
laf: torch.Tensor = scale_laf(unscaled_laf, scale)
return laf
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 750ec327a..6a85c6b83 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -3,6 +3,8 @@ from typing import Optional, Tuple
import torch
import torch.nn as nn
+from kornia.testing import KORNIA_CHECK_SHAPE
+
def match_nn(
desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = None
@@ -21,10 +23,8 @@ def match_nn(
- Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`.
- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
"""
- if len(desc1.shape) != 2:
- raise AssertionError
- if len(desc2.shape) != 2:
- raise AssertionError
+ KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
+ KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
if dm is None:
dm = torch.cdist(desc1, desc2)
@@ -56,10 +56,8 @@ def match_mnn(
- Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
where 0 <= B3 <= min(B1, B2)
"""
- if len(desc1.shape) != 2:
- raise AssertionError
- if len(desc2.shape) != 2:
- raise AssertionError
+ KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
+ KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
if dm is None:
dm = torch.cdist(desc1, desc2)
@@ -104,10 +102,9 @@ def match_snn(
- Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
where 0 <= B3 <= B1.
"""
- if len(desc1.shape) != 2:
- raise AssertionError
- if len(desc2.shape) != 2:
- raise AssertionError
+ KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
+ KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
+
if desc2.shape[0] < 2:
raise AssertionError
@@ -148,10 +145,9 @@ def match_smnn(
- Long tensor indexes of matching descriptors in desc1 and desc2,
shape of :math:`(B3, 2)` where 0 <= B3 <= B1.
"""
- if len(desc1.shape) != 2:
- raise AssertionError
- if len(desc2.shape) != 2:
- raise AssertionError
+ KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])
+ KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
+
if desc1.shape[0] < 2:
raise AssertionError
if desc2.shape[0] < 2:
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 30eef5807..670d2f7ce 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -8,6 +8,7 @@ import torch.nn.functional as F
from kornia.constants import pi
from kornia.filters import SpatialGradient, get_gaussian_kernel2d
from kornia.geometry import rad2deg
+from kornia.testing import KORNIA_CHECK_SHAPE
from .laf import extract_patches_from_pyramid, get_laf_orientation, raise_error_if_laf_is_not_valid, set_laf_orientation
@@ -228,11 +229,7 @@ class LAFOrienter(nn.Module):
laf_out, shape [BxNx2x3]
"""
raise_error_if_laf_is_not_valid(laf)
- img_message: str = f"Invalid img shape, we expect BxCxHxW. Got: {img.shape}"
- if not isinstance(img, torch.Tensor):
- raise TypeError(f"img type is not a torch.Tensor. Got {type(img)}")
- if len(img.shape) != 4:
- raise ValueError(img_message)
+ KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"])
if laf.size(0) != img.size(0):
raise ValueError(f"Batch size of laf and img should be the same. Got {img.size(0)}, {laf.size(0)}")
B, N = laf.shape[:2]
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index eea96da15..3c5cacd21 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -4,6 +4,7 @@ import torch
import torch.nn as nn
from kornia.filters import gaussian_blur2d, spatial_gradient
+from kornia.testing import KORNIA_CHECK_SHAPE
def harris_response(
@@ -63,11 +64,7 @@ def harris_response(
[0.0012, 0.0039, 0.0020, 0.0000, 0.0020, 0.0039, 0.0012]]]])
"""
# TODO: Recompute doctest
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if sigmas is not None:
if not isinstance(sigmas, torch.Tensor):
@@ -147,11 +144,7 @@ def gftt_response(
[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])
"""
# TODO: Recompute doctest
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
gradients: torch.Tensor = spatial_gradient(input, grads_mode)
dx: torch.Tensor = gradients[:, :, 0]
@@ -229,11 +222,7 @@ def hessian_response(
[0.0155, 0.0334, 0.0194, 0.0000, 0.0194, 0.0334, 0.0155]]]])
"""
# TODO: Recompute doctest
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if sigmas is not None:
if not isinstance(sigmas, torch.Tensor):
@@ -265,11 +254,7 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:
the response map per channel with shape :math:`(B, C, D-1, H, W)`.
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
-
- if not len(input.shape) == 5:
- raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "L", "H", "W"])
return input[:, :, 1:] - input[:, :, :-1]
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index e3d32b6b5..0871cdb7f 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -7,6 +7,7 @@ import torch.nn.functional as F
from kornia.filters import get_gaussian_kernel2d, spatial_gradient
from kornia.geometry.conversions import pi
+from kornia.testing import KORNIA_CHECK_SHAPE
def _get_reshape_kernel(kd: int, ky: int, kx: int) -> torch.Tensor:
@@ -140,16 +141,8 @@ class SIFTDescriptor(nn.Module):
return self.gk.detach()
def forward(self, input):
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
- if not len(input.shape) == 4:
- raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {input.shape}")
- B, CH, W, H = input.size()
- if (W != self.patch_size) or (H != self.patch_size) or (CH != 1):
- raise TypeError(
- "input shape should be must be [Bx1x{}x{}]. "
- "Got {}".format(self.patch_size, self.patch_size, input.size())
- )
+ KORNIA_CHECK_SHAPE(input, ["B", "1", f"{self.patch_size}", f"{self.patch_size}"])
+ B: int = input.shape[0]
self.pk = self.pk.to(input.dtype).to(input.device)
grads: torch.Tensor = spatial_gradient(input, 'diff')
@@ -268,12 +261,8 @@ class DenseSIFTDescriptor(nn.Module):
return self.bin_pooling_kernel.weight.detach()
def forward(self, input):
- if not isinstance(input, torch.Tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(input)))
- if not len(input.shape) == 4:
- raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
- .format(input.shape))
+ KORNIA_CHECK_SHAPE(input, ["B", "1", "H", "W"])
+
B, CH, W, H = input.size()
self.bin_pooling_kernel = self.bin_pooling_kernel.to(input.dtype).to(input.device)
self.PoolingConv = self.PoolingConv.to(input.dtype).to(input.device)
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index e4acabb28..a9674a802 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -3,6 +3,8 @@ from typing import Dict
import torch
import torch.nn as nn
+from kornia.testing import KORNIA_CHECK_SHAPE
+
urls: Dict[str, str] = {}
urls["lib"] = "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_liberty.pth"
urls["hp_a"] = "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_hpatches_a.pth"
@@ -63,6 +65,7 @@ class SOSNet(nn.Module):
return
def forward(self, input: torch.Tensor, eps: float = 1e-10) -> torch.Tensor:
+ KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
descr = self.desc_norm(self.layers(input) + eps)
descr = descr.view(descr.size(0), -1)
return descr
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index 2ca4b4e09..c572e4b9b 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -3,6 +3,8 @@ from typing import Dict
import torch
import torch.nn as nn
+from kornia.testing import KORNIA_CHECK_SHAPE
+
urls: Dict[str, str] = {}
urls[
"liberty"
@@ -59,6 +61,7 @@ class TFeat(nn.Module):
self.eval()
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
x = self.features(input)
x = x.view(x.size(0), -1)
x = self.descr(x)
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index eb5f57ed4..e2bfde586 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -4,7 +4,7 @@ import importlib
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
-from typing import Any, Iterable, Optional, Tuple, Type, TypeVar, Union, cast
+from typing import Any, Iterable, List, Optional, Tuple, Type, TypeVar, Union, cast
import torch
from torch import Tensor
@@ -183,6 +183,26 @@ except ImportError:
# Logger api
+def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:
+ # Desired shape here is list and not tuple, because torch.jit
+ # does not like variable-length tuples
+ KORNIA_CHECK_IS_TENSOR(x)
+ if '*' == shape[0]:
+ start_idx: int = 1
+ x_shape_to_check = x.shape[-len(shape) - 1:]
+ else:
+ start_idx = 0
+ x_shape_to_check = x.shape
+
+ for i in range(start_idx, len(shape)):
+ # The voodoo below is because torchscript does not like
+ # that dim can be both int and str
+ dim_: str = shape[i]
+ if not dim_.isnumeric():
+ continue
+ dim = int(dim_)
+ if x_shape_to_check[i] != dim:
+ raise TypeError(f"{x} shape should be must be [{shape}]. Got {x.shape}")
def KORNIA_CHECK(condition, msg: Optional[str] = None):
diff --git a/test/feature/test_laf.py b/test/feature/test_laf.py
index b813988df..f7776bdc3 100644
--- a/test/feature/test_laf.py
+++ b/test/feature/test_laf.py
@@ -468,6 +468,12 @@ class TestGetCreateLAF:
laf = kornia.feature.laf_from_center_scale_ori(xy, scale, ori)
assert_close(laf, expected)
+ def test_laf_def(self, device):
+ xy = torch.ones(1, 1, 2, device=device)
+ expected = torch.tensor([[[[1, 0, 1], [0, 1, 1]]]], device=device).float()
+ laf = kornia.feature.laf_from_center_scale_ori(xy)
+ assert_close(laf, expected)
+
def test_cross_consistency(self, device):
batch_size, channels = 3, 2
xy = torch.rand(batch_size, channels, 2, device=device)