Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

MKD rebased (#841)

Dmytro Mishkinab9ca844aa49
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index 9cdd09489..dffda8f53 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -24,6 +24,7 @@ Descriptors
-----------
.. autoclass:: SIFTDescriptor
+.. autoclass:: MKDDescriptor
.. autoclass:: HardNet
.. autoclass:: SOSNet
diff --git a/docs/source/geometry.conversions.rst b/docs/source/geometry.conversions.rst
index bfc9a35e7..d66edf444 100644
--- a/docs/source/geometry.conversions.rst
+++ b/docs/source/geometry.conversions.rst
@@ -5,6 +5,8 @@ kornia.geometry.conversions
.. autofunction:: rad2deg
.. autofunction:: deg2rad
+.. autofunction:: pol2cart
+.. autofunction:: cart2pol
.. autofunction:: convert_points_from_homogeneous
.. autofunction:: convert_points_to_homogeneous
.. autofunction:: convert_affinematrix_to_homography
diff --git a/docs/source/references.bib b/docs/source/references.bib
index 1ea090974..db3fe3bc3 100644
--- a/docs/source/references.bib
+++ b/docs/source/references.bib
@@ -19,6 +19,13 @@
year={2017}
}
+@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},
+}
+
@article{zhang2018mixup,
title={mixup: Beyond Empirical Risk Minimization},
author={Hongyi Zhang and Moustapha Cisse nad Yann N. Dauphin and David Lopez-Paz},
diff --git a/kornia/__init__.py b/kornia/__init__.py
index e0ede2062..2d9d4f4b9 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -70,7 +70,8 @@ from kornia.feature import (
harris_response,
hessian_response,
gftt_response,
- SIFTDescriptor
+ SIFTDescriptor,
+ MKDDescriptor
)
from kornia.filters import (
get_gaussian_kernel1d,
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 9270992ba..9926ea844 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -32,6 +32,7 @@ from .laf import (extract_patches_from_pyramid,
laf_to_three_points,
laf_from_three_points)
from .siftdesc import SIFTDescriptor
+from .mkd import MKDDescriptor
from .hardnet import HardNet
from .sosnet import SOSNet
from .scale_space_detector import ScaleSpaceDetector, PassLAF
@@ -67,6 +68,7 @@ __all__ = [
"get_laf_orientation",
"scale_laf",
"SIFTDescriptor",
+ "MKDDescriptor",
"HardNet",
"PassLAF",
"ScaleSpaceDetector",
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
new file mode 100644
index 000000000..6c9e58317
--- /dev/null
+++ b/kornia/feature/mkd.py
@@ -0,0 +1,632 @@
+from typing import Union, Tuple, Dict, List
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from kornia.constants import pi
+from kornia.utils import create_meshgrid
+from kornia.geometry.conversions import cart2pol
+from kornia.filters import SpatialGradient, GaussianBlur2d
+
+
+# Precomputed coefficients for Von Mises kernel, given N and K(appa).
+sqrt2: float = 1.4142135623730951
+COEFFS_N1_K1: List[float] = [0.38214156, 0.48090413]
+COEFFS_N2_K8: List[float] = [0.14343168, 0.268285, 0.21979234]
+COEFFS_N3_K8: List[float] = [0.14343168, 0.268285, 0.21979234, 0.15838885]
+COEFFS: Dict[str, List[float]] = {'xy': COEFFS_N1_K1,
+ 'rhophi': COEFFS_N2_K8,
+ 'theta': COEFFS_N3_K8}
+
+urls: Dict[str, str] = {k: f'https://github.com/manyids2/mkd_pytorch/raw/master/mkd_pytorch/mkd-{k}-64.pth'
+ for k in ['cart', 'polar', 'concat']}
+
+
+def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:
+ """Gets cartesian and polar parametrizations of grid. """
+ kgrid = create_meshgrid(height=patch_size,
+ width=patch_size,
+ normalized_coordinates=True)
+ x = kgrid[0, :, :, 0]
+ y = kgrid[0, :, :, 1]
+ rho, phi = cart2pol(x, y)
+ grid_dict = {'x': x, 'y': y, 'rho': rho, 'phi': phi}
+ return grid_dict
+
+
+def get_kron_order(d1: int, d2: int) -> torch.Tensor:
+ """Gets order for doing kronecker product. """
+ kron_order = torch.zeros([d1 * d2, 2], dtype=torch.int64)
+ for i in range(d1):
+ for j in range(d2):
+ kron_order[i * d2 + j, 0] = i
+ kron_order[i * d2 + j, 1] = j
+ return kron_order
+
+
+class MKDGradients(nn.Module):
+ r"""
+ Module, which computes gradients of given patches,
+ stacked as [magnitudes, orientations].
+ Given gradients $g_x$, $g_y$ with respect to $x$, $y$ respectively,
+ - $\mathbox{mags} = $\sqrt{g_x^2 + g_y^2 + eps}$
+ - $\mathbox{oris} = $\mbox{tan}^{-1}(\nicefrac{g_y}{g_x})$.
+ Args:
+ patch_size: (int) Input patch size in pixels (32 is default)
+ Returns:
+ Tensor: gradients of given patches
+ Shape:
+ - Input: (B, 1, patch_size, patch_size)
+ - Output: (B, 2, patch_size, patch_size)
+ Examples::
+ >>> patches = torch.rand(23, 1, 32, 32)
+ >>> gradient = MKDGradients()
+ >>> g = gradient(patches) # 23x2x32x32
+ """
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.eps = 1e-8
+
+ # Modify 'diff' gradient.
+ self.grad_fn = SpatialGradient(mode='diff', order=1, normalized=False)
+ self.grad = lambda x: -self.grad_fn(x)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(x):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(x)))
+ if not len(x.shape) == 4:
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
+ .format(x.shape))
+ grads_xy = self.grad(x)
+ gx = grads_xy[:, :, 0, :, :]
+ gy = grads_xy[:, :, 1, :, :]
+ y = torch.cat(cart2pol(gx, gy, self.eps), dim=1)
+ return y
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__
+
+
+class VonMisesKernel(nn.Module):
+ """
+ Module, which computes parameters of Von Mises kernel given coefficients,
+ and embeds given patches.
+ Args:
+ patch_size: (int) Input patch size in pixels (32 is default)
+ coeffs: (list) List of coefficients
+ Some examples are hardcoded in COEFFS
+ Returns:
+ Tensor: Von Mises embedding of given parametrization
+ Shape:
+ - Input: (B, 1, patch_size, patch_size)
+ - Output: (B, d, patch_size, patch_size)
+ Examples::
+ >>> oris = torch.rand(23, 1, 32, 32)
+ >>> vm = VonMisesKernel(patch_size=32,
+ ... coeffs=[0.14343168,
+ ... 0.268285,
+ ... 0.21979234])
+ >>> emb = vm(oris) # 23x7x32x32
+ """
+
+ def __init__(self,
+ patch_size: int,
+ coeffs: Union[list, tuple]) -> None:
+ super().__init__()
+
+ self.patch_size = patch_size
+ b_coeffs: torch.Tensor = torch.tensor(coeffs)
+ self.register_buffer('coeffs', b_coeffs)
+
+ # Compute parameters.
+ n: int = len(coeffs) - 1
+ self.n: int = n
+ self.d: int = 2 * n + 1
+
+ # Precompute helper variables.
+ emb0 = torch.ones([1, 1, patch_size, patch_size])
+ frange = torch.arange(n) + 1
+ frange = frange.reshape(-1, 1, 1)
+ weights = torch.zeros([2 * n + 1])
+ weights[:n + 1] = torch.sqrt(b_coeffs)
+ weights[n + 1:] = torch.sqrt(b_coeffs[1:])
+ weights = weights.reshape(-1, 1, 1)
+ self.register_buffer('emb0', emb0)
+ self.register_buffer('frange', frange)
+ self.register_buffer('weights', weights)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(x):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(x)))
+ if not len(x.shape) == 4:
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
+ .format(x.shape))
+ emb0 = self.emb0.to(x).repeat(x.size(0), 1, 1, 1) # type: ignore
+ frange = self.frange.to(x) * x
+ emb1 = torch.cos(frange)
+ emb2 = torch.sin(frange)
+ embedding = torch.cat([emb0, emb1, emb2], dim=1)
+ embedding = self.weights * embedding
+ return embedding
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'patch_size=' + str(self.patch_size) +\
+ ', ' + 'n=' + str(self.n) +\
+ ', ' + 'd=' + str(self.d) +\
+ ', ' + 'coeffs=' + str(self.coeffs) + ')'
+
+
+class EmbedGradients(nn.Module):
+ """
+ Module that computes gradient embedding,
+ weighted by sqrt of magnitudes of given patches.
+ Args:
+ patch_size: (int) Input patch size in pixels (32 is default)
+ relative: (bool) absolute or relative gradients (False is default)
+ Returns:
+ torch.Tensor: Gradient embedding
+ Shape:
+ - Input: (B, 2, patch_size, patch_size)
+ - Output: (B, 7, patch_size, patch_size)
+ Examples::
+ >>> grads = torch.rand(23, 2, 32, 32)
+ >>> emb_grads = EmbedGradients(patch_size=32,
+ ... relative=False)
+ >>> emb = emb_grads(grads) # 23x7x32x32
+ """
+
+ def __init__(self,
+ patch_size: int = 32,
+ relative: bool = False) -> None:
+ super().__init__()
+ self.patch_size = patch_size
+ self.relative = relative
+ self.eps = 1e-8
+
+ # Theta kernel for gradients.
+ self.kernel = VonMisesKernel(patch_size=patch_size,
+ coeffs=COEFFS['theta'])
+
+ # Relative gradients.
+ kgrid = create_meshgrid(height=patch_size,
+ width=patch_size,
+ normalized_coordinates=True)
+ _, phi = cart2pol(kgrid[:, :, :, 0], kgrid[:, :, :, 1])
+ self.register_buffer('phi', phi)
+
+ def emb_mags(self, mags: torch.Tensor) -> torch.Tensor:
+ """Embed square roots of magnitudes with eps for numerical reasons. """
+ mags = torch.sqrt(mags + self.eps)
+ return mags
+
+ def forward(self, grads: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(grads):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(grads)))
+ if not len(grads.shape) == 4:
+ raise ValueError("Invalid input shape, we expect Bx2xHxW. Got: {}"
+ .format(grads.shape))
+ mags = grads[:, :1, :, :]
+ oris = grads[:, 1:, :, :]
+ if self.relative:
+ oris = oris - self.phi.to(oris)
+ y = self.kernel(oris) * self.emb_mags(mags)
+ return y
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'patch_size=' + str(self.patch_size) +\
+ ', ' + 'relative=' + str(self.relative) + ')'
+
+
+def spatial_kernel_embedding(kerneltype, grids: dict) -> torch.Tensor:
+ """Compute embeddings for cartesian and polar parametrizations. """
+ factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}
+ if kerneltype == 'cart':
+ coeffs_ = 'xy'
+ params_ = ['x', 'y']
+ elif kerneltype == 'polar':
+ coeffs_ = 'rhophi'
+ params_ = ['phi', 'rho']
+
+ # Infer patch_size.
+ keys = list(grids.keys())
+ patch_size = grids[keys[0]].shape[-1]
+
+ # Scale appropriately.
+ grids_normed = {k: v * factors[k] for k, v in grids.items()}
+ grids_normed = {k: v.unsqueeze(0).unsqueeze(0).float()
+ for k, v in grids_normed.items()}
+
+ # x,y/rho,phi kernels.
+ vm_a = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS[coeffs_])
+ vm_b = VonMisesKernel(patch_size=patch_size, coeffs=COEFFS[coeffs_])
+
+ emb_a = vm_a(grids_normed[params_[0]]).squeeze()
+ emb_b = vm_b(grids_normed[params_[1]]).squeeze()
+
+ # Final precomputed position embedding.
+ kron_order = get_kron_order(vm_a.d, vm_b.d)
+ spatial_kernel = emb_a.index_select(0,
+ kron_order[:, 0]) * emb_b.index_select(0, kron_order[:, 1])
+ return spatial_kernel
+
+
+class ExplicitSpacialEncoding(nn.Module):
+ """
+ Module that computes explicit cartesian or polar embedding.
+ Args:
+ kerneltype: (str) Parametrization of kernel.
+ 'polar', 'cart' ('polar' is default)
+ fmap_size: (int) Input feature map size in pixels (32 is default)
+ in_dims: (int) Dimensionality of input feature map (7 is default)
+ do_gmask: (bool) Apply gaussian mask (True is default)
+ do_l2: (bool) Apply l2-normalization (True is default)
+ Returns:
+ Tensor: Explicit cartesian or polar embedding
+ Shape:
+ - Input: (B, in_dims, fmap_size, fmap_size)
+ - Output: (B, out_dims, fmap_size, fmap_size)
+ Examples::
+ >>> emb_ori = torch.rand(23, 7, 32, 32)
+ >>> ese = ExplicitSpacialEncoding(kerneltype='polar',
+ ... fmap_size=32,
+ ... in_dims=7,
+ ... do_gmask=True,
+ ... do_l2=True)
+ >>> desc = ese(emb_ori) # 23x175x32x32
+ """
+
+ def __init__(self,
+ kerneltype: str = 'polar',
+ fmap_size: int = 32,
+ in_dims: int = 7,
+ do_gmask: bool = True,
+ do_l2: bool = True) -> None:
+ super().__init__()
+
+ if kerneltype not in ['polar', 'cart']:
+ raise NotImplementedError(f'{kerneltype} is not valid, use polar or cart).')
+
+ self.kerneltype = kerneltype
+ self.fmap_size = fmap_size
+ self.in_dims = in_dims
+ self.do_gmask = do_gmask
+ self.do_l2 = do_l2
+ self.grid = get_grid_dict(fmap_size)
+ self.gmask = None
+
+ # Precompute embedding.
+ emb = spatial_kernel_embedding(self.kerneltype, self.grid)
+
+ # Gaussian mask.
+ if self.do_gmask:
+ self.gmask = self.get_gmask(sigma=1.0)
+ emb = emb * self.gmask
+
+ # Store precomputed embedding.
+ self.register_buffer('emb', emb.unsqueeze(0))
+ self.d_emb: int = self.emb.shape[1] # type: ignore
+ self.out_dims: int = self.in_dims * self.d_emb
+ self.odims: int = self.out_dims
+
+ # Store kronecker form.
+ emb2, idx1 = self.init_kron()
+ self.register_buffer('emb2', emb2)
+ self.register_buffer('idx1', idx1)
+
+ def get_gmask(self, sigma: float) -> torch.Tensor:
+ """Compute Gaussian mask. """
+ norm_rho = self.grid['rho'] / self.grid['rho'].max()
+ gmask = torch.exp(-1 * norm_rho**2 / sigma**2)
+ return gmask
+
+ def init_kron(self) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Initialize helper variables to calculate kronecker. """
+ kron = get_kron_order(self.in_dims, self.d_emb)
+ emb2 = torch.index_select(self.emb, 1, kron[:, 1]) # type: ignore
+ return emb2, kron[:, 0]
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(x):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(x)))
+ if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):
+ raise ValueError("Invalid input shape, we expect Bx{}xHxW. Got: {}"
+ .format(self.in_dims, x.shape))
+ emb1 = torch.index_select(x, 1, self.idx1) # type: ignore
+ output = emb1 * self.emb2
+ output = output.sum(dim=(2, 3))
+ if self.do_l2:
+ output = F.normalize(output, dim=1)
+ return output
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'kerneltype=' + str(self.kerneltype) +\
+ ', ' + 'fmap_size=' + str(self.fmap_size) +\
+ ', ' + 'in_dims=' + str(self.in_dims) +\
+ ', ' + 'out_dims=' + str(self.out_dims) +\
+ ', ' + 'do_gmask=' + str(self.do_gmask) +\
+ ', ' + 'do_l2=' + str(self.do_l2) + ')'
+
+
+class Whitening(nn.Module):
+ """
+ Module, performs supervised or unsupervised whitening.
+
+ This is based on the paper "Understanding and Improving Kernel Local Descriptors".
+ See :cite:`mukundan2019understanding` for more details.
+
+ Args:
+ xform: (str) Variant of whitening to use.
+ None, 'lw', 'pca', 'pcaws', 'pcawt'
+ whitening_model: (dict) Dictionary with keys
+ 'mean', 'eigvecs', 'eigvals' holding torch.Tensors
+ in_dims: (int) Dimensionality of input descriptors
+ output_dims: (int) Dimensionality reduction (128 is default)
+ keval: (int) Shrinkage parameter (40 is default)
+ t: (float) Attenuation parameter (0.7 is default)
+ Returns:
+ Tensor: l2-normalized, whitened descriptors
+ Shape:
+ - Input: (B, in_dims, fmap_size, fmap_size)
+ - Output: (B, out_dims, fmap_size, fmap_size)
+ Examples::
+ >>> descs = torch.rand(23, 238)
+ >>> whitening_model = {'pca': {'mean': torch.zeros(238),
+ ... 'eigvecs': torch.eye(238),
+ ... 'eigvals': torch.ones(238)}}
+ >>> whitening = Whitening(xform='pcawt',
+ ... whitening_model=whitening_model,
+ ... in_dims=238,
+ ... output_dims=128,
+ ... keval=40,
+ ... t=0.7)
+ >>> wdescs = whitening(descs) # 23x128
+ """
+
+ def __init__(self,
+ xform: str,
+ whitening_model: Union[Dict[str, Dict[str, torch.Tensor]], None],
+ in_dims: int,
+ output_dims: int = 128,
+ keval: int = 40,
+ t: float = 0.7) -> None:
+ super().__init__()
+
+ self.xform = xform
+ self.in_dims = in_dims
+ self.keval = keval
+ self.t = t
+ self.pval = 1.0
+
+ # Compute true output_dims.
+ output_dims = min(output_dims, in_dims)
+ self.output_dims = output_dims
+
+ # Initialize identity transform.
+ self.mean = nn.Parameter(torch.zeros(in_dims), requires_grad=True)
+ self.evecs = nn.Parameter(torch.eye(in_dims)[:, :output_dims], requires_grad=True)
+ self.evals = nn.Parameter(torch.ones(in_dims)[:output_dims], requires_grad=True)
+
+ if whitening_model is not None:
+ self.load_whitening_parameters(whitening_model)
+
+ def load_whitening_parameters(self,
+ whitening_model: Dict[str, Dict[str, torch.Tensor]]) -> None:
+ algo = 'lw' if self.xform == 'lw' else 'pca'
+ wh_model = whitening_model[algo]
+ self.mean.data = wh_model['mean']
+ self.evecs.data = wh_model['eigvecs'][:, :self.output_dims]
+ self.evals.data = wh_model['eigvals'][:self.output_dims]
+
+ modifications = {'pca': self._modify_pca,
+ 'lw': self._modify_lw,
+ 'pcaws': self._modify_pcaws,
+ 'pcawt': self._modify_pcawt}
+
+ # Call modification.
+ modifications[self.xform]()
+
+ def _modify_pca(self) -> None:
+ """ Modify powerlaw parameter."""
+ self.pval = 0.5
+
+ def _modify_lw(self) -> None:
+ """ No modification required."""
+
+ def _modify_pcaws(self) -> None:
+ """ Shrinkage for eigenvalues."""
+ alpha = self.evals[self.keval]
+ evals = ((1 - alpha) * self.evals) + alpha
+ self.evecs.data = self.evecs @ torch.diag(torch.pow(evals, -0.5))
+
+ def _modify_pcawt(self) -> None:
+ """ Attenuation for eigenvalues."""
+ m = -0.5 * self.t
+ self.evecs.data = self.evecs @ torch.diag(torch.pow(self.evals, m))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(x):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(x)))
+ if not len(x.shape) == 2:
+ raise ValueError("Invalid input shape, we expect NxD. Got: {}"
+ .format(x.shape))
+ x = x - self.mean # Center the data.
+ x = x @ self.evecs # Apply rotation and/or scaling.
+ x = torch.sign(x) * torch.pow(torch.abs(x), self.pval) # Powerlaw.
+ return F.normalize(x, dim=1)
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'xform=' + str(self.xform) +\
+ ', ' + 'in_dims=' + str(self.in_dims) +\
+ ', ' + 'output_dims=' + str(self.output_dims) + ')'
+
+
+class MKDDescriptor(nn.Module):
+ """
+ Module that computes Multiple Kernel local descriptors.
+
+ This is based on the paper "Understanding and Improving Kernel Local Descriptors".
+ See :cite:`mukundan2019understanding` for more details.
+
+ Args:
+ patch_size: (int) Input patch size in pixels (32 is default)
+ kerneltype: (str) Parametrization of kernel
+ 'concat', 'cart', 'polar' ('concat' is default)
+ whitening: (str) Whitening transform to apply
+ None, 'lw', 'pca', 'pcawt', 'pcaws' ('pcawt' is default)
+ training_set: (str) Set that model was trained on
+ 'liberty', 'notredame', 'yosemite' ('liberty' is default)
+ output_dims: (int) Dimensionality reduction (128 is default)
+ Returns:
+ Tensor: Explicit cartesian or polar embedding
+ Shape:
+ - Input: (B, in_dims, fmap_size, fmap_size)
+ - Output: (B, out_dims, fmap_size, fmap_size)
+ Examples::
+ >>> patches = torch.rand(23, 1, 32, 32)
+ >>> mkd = MKDDescriptor(patch_size=32,
+ ... kerneltype='concat',
+ ... whitening='pcawt',
+ ... training_set='liberty',
+ ... output_dims=128)
+ >>> desc = mkd(patches) # 23x128
+ """
+
+ def __init__(self,
+ patch_size: int = 32,
+ kerneltype: str = 'concat',
+ whitening: str = 'pcawt',
+ training_set: str = 'liberty',
+ output_dims: int = 128) -> None:
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.kerneltype = kerneltype
+ self.whitening = whitening
+ self.training_set = training_set
+
+ self.sigma = 1.4 * (patch_size / 64)
+ self.smoothing = GaussianBlur2d((5, 5),
+ (self.sigma, self.sigma),
+ 'replicate')
+ self.gradients = MKDGradients()
+
+ self.parametrizations = ['polar', 'cart'] if self.kerneltype == 'concat' else [self.kerneltype]
+
+ # Initialize cartesian/polar embedding with absolute/relative gradients.
+ self.odims: int = 0
+ relative_orientations = {'polar': True, 'cart': False}
+ self.feats = {}
+ for parametrization in self.parametrizations:
+ gradient_embedding = EmbedGradients(patch_size=patch_size,
+ relative=relative_orientations[parametrization])
+ spatial_encoding = ExplicitSpacialEncoding(kerneltype=parametrization,
+ fmap_size=patch_size,
+ in_dims=gradient_embedding.kernel.d)
+
+ self.feats[parametrization] = nn.Sequential(gradient_embedding, spatial_encoding)
+ self.odims += spatial_encoding.odims
+
+ # Compute true output_dims.
+ self.output_dims: int = min(output_dims, self.odims)
+
+ # Load supervised(lw)/unsupervised(pca) model trained on training_set.
+ if self.whitening is not None:
+ whitening_models = torch.hub.load_state_dict_from_url(
+ urls[self.kerneltype], map_location=lambda storage, loc: storage
+ )
+ whitening_model = whitening_models[training_set]
+ self.whitening_layer = Whitening(whitening,
+ whitening_model,
+ in_dims=self.odims,
+ output_dims=self.output_dims)
+ self.odims = self.output_dims
+
+ def forward(self, patches: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(patches):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(patches)))
+ if not len(patches.shape) == 4:
+ raise ValueError("Invalid input shape, we expect Bx1xHxW. Got: {}"
+ .format(patches.shape))
+ # Extract gradients.
+ g = self.smoothing(patches)
+ g = self.gradients(g)
+
+ # Extract polar/cart features.
+ features = []
+ for parametrization in self.parametrizations:
+ self.feats[parametrization].to(g.device)
+ features.append(self.feats[parametrization](g))
+
+ # Concatenate.
+ y = torch.cat(features, dim=1)
+
+ # l2-normalize.
+ y = F.normalize(y, dim=1)
+
+ # Whiten descriptors.
+ if self.whitening is not None:
+ y = self.whitening_layer(y)
+
+ return y
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ +\
+ '(' + 'patch_size=' + str(self.patch_size) +\
+ ', ' + 'kerneltype=' + str(self.kerneltype) +\
+ ', ' + 'whitening=' + str(self.whitening) +\
+ ', ' + 'training_set=' + str(self.training_set) +\
+ ', ' + 'output_dims=' + str(self.output_dims) + ')'
+
+
+def load_whitening_model(kerneltype: str, training_set: str) -> Dict:
+ whitening_models = torch.hub.load_state_dict_from_url(
+ urls[kerneltype], map_location=lambda storage, loc: storage
+ )
+ whitening_model = whitening_models[training_set]
+ return whitening_model
+
+
+class SimpleKD(nn.Module):
+ """Example to write custom Kernel Descriptors. """
+
+ def __init__(self,
+ patch_size: int = 32,
+ kerneltype: str = 'polar', # 'cart' 'polar'
+ whitening: str = 'pcawt', # 'lw', 'pca', 'pcaws', 'pcawt
+ training_set: str = 'liberty', # 'liberty', 'notredame', 'yosemite'
+ output_dims: int = 128) -> None:
+ super().__init__()
+
+ relative = kerneltype == 'polar'
+ sigma = 1.4 * (patch_size / 64)
+
+ # Sequence of modules.
+ smoothing = GaussianBlur2d((5, 5), (sigma, sigma), 'replicate')
+ gradients = MKDGradients()
+ ori = EmbedGradients(patch_size=patch_size, relative=relative)
+ ese = ExplicitSpacialEncoding(kerneltype=kerneltype,
+ fmap_size=patch_size, in_dims=ori.kernel.d)
+ wh = Whitening(whitening,
+ load_whitening_model(kerneltype, training_set),
+ in_dims=ese.odims,
+ output_dims=output_dims)
+
+ self.features = nn.Sequential(smoothing,
+ gradients,
+ ori,
+ ese,
+ wh)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.features(x)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index b75f3f947..8fa0aa8b2 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -1,3 +1,4 @@
+from typing import Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
@@ -8,6 +9,8 @@ __all__ = [
# functional api
"rad2deg",
"deg2rad",
+ "pol2cart",
+ "cart2pol",
"convert_points_from_homogeneous",
"convert_points_to_homogeneous",
"convert_affinematrix_to_homography",
@@ -69,6 +72,55 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:
return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.
+def pol2cart(rho: torch.Tensor, phi: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Function that converts polar coordinates to cartesian coordinates.
+
+ Args:
+ rho (torch.Tensor): Tensor of arbitrary shape.
+ phi (torch.Tensor): Tensor of same arbitrary shape.
+
+ Returns:
+ torch.Tensor, torch.Tensor: Tensor with same shape as input.
+
+ Example:
+ >>> rho = torch.rand(1, 3, 3)
+ >>> phi = torch.rand(1, 3, 3)
+ >>> x, y = pol2cart(rho, phi)
+ """
+ if not (isinstance(rho, torch.Tensor) & isinstance(phi, torch.Tensor)):
+ raise TypeError("Input type is not a torch.Tensor. Got {}, {}".format(
+ type(rho), type(phi)))
+
+ x = rho * torch.cos(phi)
+ y = rho * torch.sin(phi)
+ return x, y
+
+
+def cart2pol(x: torch.Tensor, y: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Function that converts cartesian coordinates to polar coordinates.
+
+ Args:
+ rho (torch.Tensor): Tensor of arbitrary shape.
+ phi (torch.Tensor): Tensor of same arbitrary shape.
+ eps (float): To avoid division by zero. Default is 1e-8
+
+ Returns:
+ torch.Tensor, torch.Tensor: Tensor with same shape as input.
+
+ Example:
+ >>> x = torch.rand(1, 3, 3)
+ >>> y = torch.rand(1, 3, 3)
+ >>> rho, phi = cart2pol(x, y)
+ """
+ if not (isinstance(x, torch.Tensor) & isinstance(y, torch.Tensor)):
+ raise TypeError("Input type is not a torch.Tensor. Got {}, {}".format(
+ type(x), type(y)))
+
+ rho = torch.sqrt(x**2 + y**2 + eps)
+ phi = torch.atan2(y, x)
+ return rho, phi
+
+
def convert_points_from_homogeneous(
points: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
r"""Function that converts points from homogeneous to Euclidean space.
diff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.py
new file mode 100644
index 000000000..a47975d32
--- /dev/null
+++ b/test/feature/test_mkd.py
@@ -0,0 +1,412 @@
+import pytest
+import kornia.testing as utils # test utils
+
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+from kornia.feature.mkd import *
+from kornia.constants import pi
+
+
[email protected]("ps", [5, 13, 25])
+def test_get_grid_dict(ps):
+ grid_dict = get_grid_dict(ps)
+ param_keys = ['x', 'y', 'phi', 'rho']
+ assert set(grid_dict.keys()) == set(param_keys)
+ for k in param_keys:
+ assert grid_dict[k].shape == (ps, ps)
+
+
+ [(1, 1), (1, 2), (2, 1), (5, 6)])
+def test_get_kron_order(d1, d2):
+ out = get_kron_order(d1, d2)
+ assert out.shape == (d1 * d2, 2)
+
+
+class TestMKDGradients:
+ @pytest.mark.parametrize("ps", [5, 13, 25])
+ def test_shape(self, ps, device):
+ inp = torch.ones(1, 1, ps, ps).to(device)
+ gradients = MKDGradients().to(device)
+ out = gradients(inp)
+ assert out.shape == (1, 2, ps, ps)
+
+ @pytest.mark.parametrize("bs", [1, 5, 13])
+ def test_batch_shape(self, bs, device):
+ inp = torch.ones(bs, 1, 15, 15).to(device)
+ gradients = MKDGradients().to(device)
+ out = gradients(inp)
+ assert out.shape == (bs, 2, 15, 15)
+
+ def test_print(self, device):
+ gradients = MKDGradients().to(device)
+ gradients.__repr__()
+
+ def test_toy(self, device):
+ patch = torch.ones(1, 1, 6, 6).to(device).float()
+ patch[0, 0, :, 3:] = 0
+ gradients = MKDGradients().to(device)
+ out = gradients(patch)
+ expected_mags_1 = torch.Tensor([0, 0, 1., 1., 0, 0]).to(device)
+ expected_mags = expected_mags_1.unsqueeze(0).repeat(6, 1)
+ expected_oris_1 = torch.Tensor([-pi, -pi, 0, 0, -pi, -pi]).to(device)
+ expected_oris = expected_oris_1.unsqueeze(0).repeat(6, 1)
+ assert_allclose(out[0, 0, :, :], expected_mags, atol=1e-3, rtol=1e-3)
+ assert_allclose(out[0, 1, :, :], expected_oris, atol=1e-3, rtol=1e-3)
+
+ def test_gradcheck(self, device):
+ batch_size, channels, height, width = 1, 1, 13, 13
+ patches = torch.rand(batch_size, channels, height, width).to(device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+
+ def grad_describe(patches):
+ mkd_grads = MKDGradients()
+ mkd_grads.to(device)
+ return mkd_grads(patches)
+ assert gradcheck(grad_describe, (patches),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestVonMisesKernel:
+ @ pytest.mark.parametrize("ps", [5, 13, 25])
+ def test_shape(self, ps, device):
+ inp = torch.ones(1, 1, ps, ps).to(device)
+ vm = VonMisesKernel(patch_size=ps,
+ coeffs=[0.38214156, 0.48090413]).to(device)
+ out = vm(inp)
+ assert out.shape == (1, 3, ps, ps)
+
+ @ pytest.mark.parametrize("bs", [1, 5, 13])
+ def test_batch_shape(self, bs, device):
+ inp = torch.ones(bs, 1, 15, 15).to(device)
+ vm = VonMisesKernel(patch_size=15,
+ coeffs=[0.38214156, 0.48090413]).to(device)
+ out = vm(inp)
+ assert out.shape == (bs, 3, 15, 15)
+
+ @ pytest.mark.parametrize("coeffs", COEFFS.values())
+ def test_coeffs(self, coeffs, device):
+ inp = torch.ones(1, 1, 15, 15).to(device)
+ vm = VonMisesKernel(patch_size=15,
+ coeffs=coeffs).to(device)
+ out = vm(inp)
+ assert out.shape == (1, 2 * len(coeffs) - 1, 15, 15)
+
+ def test_print(self, device):
+ vm = VonMisesKernel(patch_size=32,
+ coeffs=[0.38214156, 0.48090413]).to(device)
+ vm.__repr__()
+
+ def test_toy(self, device):
+ patch = torch.ones(1, 1, 6, 6).float().to(device)
+ patch[0, 0, :, 3:] = 0
+ vm = VonMisesKernel(patch_size=6,
+ coeffs=[0.38214156, 0.48090413]).to(device)
+ out = vm(patch)
+ expected = torch.ones_like(out[0, 0, :, :]).to(device)
+ assert_allclose(out[0, 0, :, :], expected * 0.6182, atol=1e-3, rtol=1e-3)
+
+ expected = torch.Tensor([0.3747, 0.3747, 0.3747,
+ 0.6935, 0.6935, 0.6935]).to(device)
+ expected = expected.unsqueeze(0).repeat(6, 1)
+ assert_allclose(out[0, 1, :, :], expected, atol=1e-3, rtol=1e-3)
+
+ expected = torch.Tensor([0.5835, 0.5835, 0.5835,
+ 0.0000, 0.0000, 0.0000]).to(device)
+ expected = expected.unsqueeze(0).repeat(6, 1)
+ assert_allclose(out[0, 2, :, :], expected, atol=1e-3, rtol=1e-3)
+
+ def test_gradcheck(self, device):
+ batch_size, channels, ps = 1, 1, 13
+ patches = torch.rand(batch_size, channels, ps, ps).to(device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+
+ def vm_describe(patches, ps=13):
+ vmkernel = VonMisesKernel(patch_size=ps, coeffs=[0.38214156, 0.48090413]).double()
+ vmkernel.to(device)
+ return vmkernel(patches.double())
+ assert gradcheck(vm_describe, (patches, ps),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestEmbedGradients:
+
+ @pytest.mark.parametrize("ps,relative", [(5, True), (13, True), (25, True),
+ (5, False), (13, False), (25, False)])
+ def test_shape(self, ps, relative, device):
+ inp = torch.ones(1, 2, ps, ps).to(device)
+ emb_grads = EmbedGradients(patch_size=ps,
+ relative=relative).to(device)
+ out = emb_grads(inp)
+ assert out.shape == (1, 7, ps, ps)
+
+ @pytest.mark.parametrize("bs", [1, 5, 13])
+ def test_batch_shape(self, bs, device):
+ inp = torch.ones(bs, 2, 15, 15).to(device)
+ emb_grads = EmbedGradients(patch_size=15,
+ relative=True).to(device)
+ out = emb_grads(inp)
+ assert out.shape == (bs, 7, 15, 15)
+
+ def test_print(self, device):
+ emb_grads = EmbedGradients(patch_size=15,
+ relative=True).to(device)
+ emb_grads.__repr__()
+
+ def test_toy(self, device):
+ grads = torch.ones(1, 2, 6, 6).float().to(device)
+ grads[0, 0, :, 3:] = 0
+ emb_grads = EmbedGradients(patch_size=6,
+ relative=True).to(device)
+ out = emb_grads(grads)
+ expected = torch.ones_like(out[0, 0, :, :3]).to(device)
+ assert_allclose(out[0, 0, :, :3], expected * .3787, atol=1e-3, rtol=1e-3)
+ assert_allclose(out[0, 0, :, 3:], expected * 0, atol=1e-3, rtol=1e-3)
+
+ def test_gradcheck(self, device):
+ batch_size, channels, ps = 1, 2, 13
+ patches = torch.rand(batch_size, channels, ps, ps).to(device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+
+ def emb_grads_describe(patches, ps=13):
+ emb_grads = EmbedGradients(patch_size=ps, relative=True).double()
+ emb_grads.to(device)
+ return emb_grads(patches.double())
+ assert gradcheck(emb_grads_describe, (patches, ps),
+ raise_exception=True, nondet_tol=1e-4)
+
+
[email protected]("kerneltype,d,ps", [('cart', 9, 9), ('polar', 25, 9),
+ ('cart', 9, 16), ('polar', 25, 16)])
+def test_spatial_kernel_embedding(kerneltype, ps, d):
+ grids = get_grid_dict(ps)
+ spatial_kernel = spatial_kernel_embedding(kerneltype, grids)
+ assert spatial_kernel.shape == (d, ps, ps)
+
+
+class TestExplicitSpacialEncoding:
+
+ @pytest.mark.parametrize("kerneltype,ps,in_dims", [('cart', 9, 3),
+ ('polar', 9, 3), ('cart', 13, 7), ('polar', 13, 7)])
+ def test_shape(self, kerneltype, ps, in_dims, device):
+ inp = torch.ones(1, in_dims, ps, ps).to(device)
+ ese = ExplicitSpacialEncoding(kerneltype=kerneltype,
+ fmap_size=ps,
+ in_dims=in_dims).to(device)
+ out = ese(inp)
+ d_ = 9 if kerneltype == 'cart' else 25
+ assert out.shape == (1, d_ * in_dims)
+
+ @pytest.mark.parametrize("kerneltype,bs", [('cart', 1), ('cart', 5), ('cart', 13),
+ ('polar', 1), ('polar', 5), ('polar', 13)])
+ def test_batch_shape(self, kerneltype, bs, device):
+ inp = torch.ones(bs, 7, 15, 15).to(device)
+ ese = ExplicitSpacialEncoding(kerneltype=kerneltype,
+ fmap_size=15,
+ in_dims=7).to(device)
+ out = ese(inp)
+ d_ = 9 if kerneltype == 'cart' else 25
+ assert out.shape == (bs, d_ * 7)
+
+ @pytest.mark.parametrize("kerneltype", ['cart', 'polar'])
+ def test_print(self, kerneltype, device):
+ ese = ExplicitSpacialEncoding(kerneltype=kerneltype,
+ fmap_size=15,
+ in_dims=7).to(device)
+ ese.__repr__()
+
+ def test_toy(self, device):
+ inp = torch.ones(1, 2, 6, 6).to(device).float()
+ inp[0, 0, :, :] = 0
+ cart_ese = ExplicitSpacialEncoding(kerneltype='cart',
+ fmap_size=6,
+ in_dims=2).to(device)
+ out = cart_ese(inp)
+ out_part = out[:, :9]
+ expected = torch.zeros_like(out_part).to(device)
+ assert_allclose(out_part, expected, atol=1e-3, rtol=1e-3)
+
+ polar_ese = ExplicitSpacialEncoding(kerneltype='polar',
+ fmap_size=6,
+ in_dims=2).to(device)
+ out = polar_ese(inp)
+ out_part = out[:, :25]
+ expected = torch.zeros_like(out_part).to(device)
+ assert_allclose(out_part, expected, atol=1e-3, rtol=1e-3)
+
+ @pytest.mark.parametrize("kerneltype", ['cart', 'polar'])
+ def test_gradcheck(self, kerneltype, device):
+ batch_size, channels, ps = 1, 2, 13
+ patches = torch.rand(batch_size, channels, ps, ps).to(device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+
+ def explicit_spatial_describe(patches, ps=13):
+ ese = ExplicitSpacialEncoding(kerneltype=kerneltype,
+ fmap_size=ps,
+ in_dims=2)
+ ese.to(device)
+ return ese(patches)
+ assert gradcheck(explicit_spatial_describe, (patches, ps),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestWhitening:
+ @pytest.mark.parametrize("kerneltype,xform,output_dims", [('cart', None, 3),
+ ('polar', None, 3), ('cart', 'lw', 7), ('polar', 'lw', 7),
+ ('cart', 'pca', 9), ('polar', 'pca', 9)])
+ def test_shape(self, kerneltype, xform, output_dims, device):
+ in_dims = 63 if kerneltype == 'cart' else 175
+ wh = Whitening(xform=xform,
+ whitening_model=None,
+ in_dims=in_dims,
+ output_dims=output_dims).to(device)
+ inp = torch.ones(1, in_dims).to(device)
+ out = wh(inp)
+ assert out.shape == (1, output_dims)
+
+ @pytest.mark.parametrize("bs", [1, 3, 7])
+ def test_batch_shape(self, bs, device):
+ wh = Whitening(xform='lw',
+ whitening_model=None,
+ in_dims=175,
+ output_dims=128).to(device)
+ inp = torch.ones(bs, 175).to(device)
+ out = wh(inp)
+ assert out.shape == (bs, 128)
+
+ def test_print(self, device):
+ wh = Whitening(xform='lw',
+ whitening_model=None,
+ in_dims=175,
+ output_dims=128).to(device)
+ wh.__repr__()
+
+ def test_toy(self, device):
+ wh = Whitening(xform='lw',
+ whitening_model=None,
+ in_dims=175,
+ output_dims=175).to(device)
+ inp = torch.ones(1, 175).to(device).float()
+ out = wh(inp)
+ expected = torch.ones_like(inp).to(device) * 0.0756
+ assert_allclose(out, expected, atol=1e-3, rtol=1e-3)
+
+ def test_gradcheck(self, device):
+ batch_size, in_dims = 1, 175
+ patches = torch.rand(batch_size, in_dims).to(device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+
+ def whitening_describe(patches, in_dims=175):
+ wh = Whitening(xform='lw',
+ whitening_model=None,
+ in_dims=in_dims).double()
+ wh.to(device)
+ return wh(patches.double())
+ assert gradcheck(whitening_describe, (patches, in_dims),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestMKDDescriptor:
+ dims = {'cart': 63, 'polar': 175, 'concat': 238}
+
+ @pytest.mark.parametrize("ps,kerneltype", [(9, 'concat'),
+ (9, 'cart'), (9, 'polar'), (32, 'concat'), (32, 'cart'), (32, 'polar')])
+ def test_shape(self, ps, kerneltype, device):
+ mkd = MKDDescriptor(patch_size=ps,
+ kerneltype=kerneltype,
+ whitening=None).to(device)
+ inp = torch.ones(1, 1, ps, ps).to(device)
+ out = mkd(inp)
+ assert out.shape == (1, self.dims[kerneltype])
+
+ @pytest.mark.parametrize("ps,kerneltype,whitening", [(9, 'concat', 'lw'),
+ (9, 'cart', 'lw'), (9, 'polar', 'lw'), (9, 'concat', 'pcawt'),
+ (9, 'cart', 'pcawt'), (9, 'polar', 'pcawt')])
+ def test_whitened_shape(self, ps, kerneltype, whitening, device):
+ mkd = MKDDescriptor(patch_size=ps,
+ kerneltype=kerneltype,
+ whitening=whitening).to(device)
+ inp = torch.ones(1, 1, ps, ps).to(device)
+ out = mkd(inp)
+ output_dims = min(self.dims[kerneltype], 128)
+ assert out.shape == (1, output_dims)
+
+ @pytest.mark.parametrize("bs", [1, 3, 7])
+ def test_batch_shape(self, bs, device):
+ mkd = MKDDescriptor(patch_size=19,
+ kerneltype='concat',
+ whitening=None).to(device)
+ inp = torch.ones(bs, 1, 19, 19).to(device)
+ out = mkd(inp)
+ assert out.shape == (bs, 238)
+
+ def test_print(self, device):
+ mkd = MKDDescriptor(patch_size=32,
+ whitening='lw',
+ training_set='liberty',
+ output_dims=128).to(device)
+ mkd.__repr__()
+
+ def test_toy(self, device):
+ inp = torch.ones(1, 1, 6, 6).to(device).float()
+ inp[0, 0, :, :] = 0
+ mkd = MKDDescriptor(patch_size=6,
+ kerneltype='concat',
+ whitening=None).to(device)
+ out = mkd(inp)
+ out_part = out[0, -28:]
+ expected = torch.zeros_like(out_part).to(device)
+ assert_allclose(out_part, expected, atol=1e-3, rtol=1e-3)
+
+ @pytest.mark.parametrize("whitening", [None, 'lw', 'pca'])
+ def test_gradcheck(self, whitening, device):
+ batch_size, channels, ps = 1, 1, 19
+ patches = torch.rand(batch_size, channels, ps, ps).to(device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+
+ def mkd_describe(patches, patch_size=19):
+ mkd = MKDDescriptor(patch_size=patch_size,
+ kerneltype='concat',
+ whitening=whitening).double()
+ mkd.to(device)
+ return mkd(patches.double())
+ assert gradcheck(mkd_describe, (patches, ps),
+ raise_exception=True, nondet_tol=1e-4)
+
+
+class TestSimpleKD:
+ dims = {'cart': 63, 'polar': 175}
+
+ @pytest.mark.parametrize("ps,kerneltype", [(9, 'cart'), (9, 'polar'),
+ (32, 'cart'), (32, 'polar')])
+ def test_shape(self, ps, kerneltype, device):
+ skd = SimpleKD(patch_size=ps,
+ kerneltype=kerneltype).to(device)
+ inp = torch.ones(1, 1, ps, ps).to(device)
+ out = skd(inp)
+ assert out.shape == (1, min(128, self.dims[kerneltype]))
+
+ @pytest.mark.parametrize("bs", [1, 3, 7])
+ def test_batch_shape(self, bs, device):
+ skd = SimpleKD(patch_size=19,
+ kerneltype='polar').to(device)
+ inp = torch.ones(bs, 1, 19, 19).to(device)
+ out = skd(inp)
+ assert out.shape == (bs, 128)
+
+ def test_print(self, device):
+ skd = SimpleKD(patch_size=19, kerneltype='polar').to(device)
+ skd.__repr__()
+
+ def test_gradcheck(self, device):
+ batch_size, channels, ps = 1, 1, 19
+ patches = torch.rand(batch_size, channels, ps, ps).to(device)
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+
+ def skd_describe(patches, patch_size=19):
+ skd = SimpleKD(patch_size=patch_size, kerneltype='polar',
+ whitening='lw').double()
+ skd.to(device)
+ return skd(patches.double())
+ assert gradcheck(skd_describe, (patches, ps),
+ raise_exception=True, nondet_tol=1e-4)
diff --git a/test/geometry/test_conversions.py b/test/geometry/test_conversions.py
index 080af50aa..f1861c7c1 100644
--- a/test/geometry/test_conversions.py
+++ b/test/geometry/test_conversions.py
@@ -364,6 +364,51 @@ def test_deg2rad(batch_shape, device, dtype):
raise_exception=True)
+class TestPolCartConversions:
+ def test_smoke(self, device, dtype):
+ x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
+ assert kornia.pol2cart(x, x) is not None
+ assert kornia.cart2pol(x, x) is not None
+
+ @pytest.mark.parametrize("batch_shape", [
+ (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ def test_pol2cart(self, batch_shape, device, dtype):
+ # generate input data
+ rho = torch.rand(batch_shape, dtype=dtype)
+ phi = kornia.pi * torch.rand(batch_shape, dtype=dtype)
+ rho = rho.to(device)
+ phi = phi.to(device)
+
+ # convert pol/cart
+ x_pol2cart, y_pol2cart = kornia.pol2cart(rho, phi)
+ rho_pol2cart, phi_pol2cart = kornia.cart2pol(x_pol2cart, y_pol2cart, 0)
+
+ assert_allclose(rho, rho_pol2cart)
+ assert_allclose(phi, phi_pol2cart)
+
+ assert gradcheck(kornia.pol2cart, (tensor_to_gradcheck_var(rho),
+ tensor_to_gradcheck_var(phi), ), raise_exception=True)
+
+ @pytest.mark.parametrize("batch_shape", [
+ (2, 3), (1, 2, 3), (2, 3, 3), (5, 5, 3), ])
+ def test_cart2pol(self, batch_shape, device, dtype):
+ # generate input data
+ x = torch.rand(batch_shape, dtype=dtype)
+ y = torch.rand(batch_shape, dtype=dtype)
+ x = x.to(device)
+ y = y.to(device)
+
+ # convert cart/pol
+ rho_cart2pol, phi_cart2pol = kornia.cart2pol(x, y, 0)
+ x_cart2pol, y_cart2pol = kornia.pol2cart(rho_cart2pol, phi_cart2pol)
+
+ assert_allclose(x, x_cart2pol)
+ assert_allclose(y, y_cart2pol)
+
+ assert gradcheck(kornia.cart2pol, (tensor_to_gradcheck_var(x),
+ tensor_to_gradcheck_var(y), ), raise_exception=True)
+
+
class TestConvertPointsToHomogeneous:
def test_convert_points(self, device, dtype):
# generate input data