π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Feat] Add elastic transform 2d (#853)
Edgar Ribae09814688439
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rstindex adccc47d8..5d5d339d3 100644--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@ -161,8 +161,6 @@ Transforms3DSet of operators to perform data augmentation on 3D image tensors and volumetric data.-.. autoclass:: Denormalize3D-.. autoclass:: Normalize3D.. autoclass:: RandomDepthicalFlip3D.. autoclass:: RandomHorizontalFlip3D.. autoclass:: RandomVerticalFlip3Ddiff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rstindex 113ef8066..39897c3d9 100644--- a/docs/source/geometry.transform.rst+++ b/docs/source/geometry.transform.rst@@ -29,6 +29,7 @@ The functions in this section perform various geometrical transformations of 2D.. autofunction:: pyrdown.. autofunction:: pyrup.. autofunction:: build_pyramid+.. autofunction:: elastic_transform2d.. autofunction:: affine.. autofunction:: rotatediff --git a/docs/source/references.bib b/docs/source/references.bibindex ad7897385..1916ac15d 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -69,3 +69,11 @@year={2017},journal={arXiv ePrint 1706.05721}}++@article{Simard2003BestPF,+ title={Best practices for convolutional neural networks applied to visual document analysis},+ author={P. Simard and David Steinkraus and John C. Platt},+ journal={Seventh International Conference on Document Analysis and Recognition, 2003. Proceedings.},+ year={2003},+ pages={958-963}+}diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.pyindex a8292c7e0..2dd20d91a 100644--- a/kornia/augmentation/augmentation.py+++ b/kornia/augmentation/augmentation.py@@ -907,6 +907,7 @@ class Normalize(AugmentationBase2D):>>> out.shapetorch.Size([1, 4, 3, 3])"""+def __init__(self, mean: torch.Tensor, std: torch.Tensor,return_transform: bool = False, p: float = 1., keepdim: bool = False@@ -953,6 +954,7 @@ class Denormalize(AugmentationBase2D):>>> out.shapetorch.Size([1, 4, 3, 3])"""+def __init__(self, mean: torch.Tensor, std: torch.Tensor,return_transform: bool = False, p: float = 1., keepdim: bool = Falsediff --git a/kornia/augmentation/functional/functional3d.py b/kornia/augmentation/functional/functional3d.pyindex e1645ed4d..4fcfb5afc 100644--- a/kornia/augmentation/functional/functional3d.py+++ b/kornia/augmentation/functional/functional3d.py@@ -508,10 +508,12 @@ def compute_perspective_transformation3d(input: torch.Tensor, params: Dict[str,def apply_equalize3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:r"""Equalize a tensor volume or a batch of tensors volumes with given random parameters.+Args:- input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,- :math:`(*, C, D, H, W)`.+ input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`,+ :math:`(C, D, H, W)`, :math:`(*, C, D, H, W)`.params (Dict[str, torch.Tensor]): shall be empty.+Returns:torch.Tensor: The equalized input. :math:`(D, H, W)`, :math:`(C, D, H, W)`, :math:`(*, C, D, H, W)`."""diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 269de40d4..54dc12018 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -82,7 +82,8 @@ class LAFAffineShapeEstimator(nn.Module):Args:patch_size: int, default = 32- affine_shape_detector: nn.Module. Patch affine shape estimator, e.g. PatchAffineShapeEstimator. Default: None """ # noqa pylint: disable+ affine_shape_detector: nn.Module. Patch affine shape estimator, e.g. PatchAffineShapeEstimator. Default: None """ # noqa pylint: disable+def __init__(self,patch_size: int = 32,affine_shape_detector: Optional[nn.Module] = None) -> None:@@ -140,6 +141,7 @@ class LAFAffNetShapeEstimator(nn.Module):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(diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 702fbd618..f4d91708d 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -126,6 +126,7 @@ class OriNet(nn.Module):>>> orinet = OriNet()>>> angle = orinet(input) # 16"""+def __init__(self, pretrained: bool = False, eps: float = 1e-8):super(OriNet, self).__init__()self.features = nn.Sequential(@@ -188,7 +189,7 @@ class LAFOrienter(nn.Module):Args:patch_size: int, default = 32num_angular_bins: int, default is 36- angle_detector: nn.Module. Patch orientation estimator, e.g. PatchDominantGradientOrientation or OriNet. Default: None """ # noqa pylint: disable+ angle_detector: nn.Module. Patch orientation estimator, e.g. PatchDominantGradientOrientation or OriNet. Default: None """ # noqa pylint: disabledef __init__(self,patch_size: int = 32,diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 3cec6073e..d0781dc9b 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -18,7 +18,10 @@ def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:def gaussian(window_size: int, sigma: float) -> torch.Tensor:- x = torch.arange(window_size) - window_size // 2+ device, dtype = None, None+ if isinstance(sigma, torch.Tensor):+ device, dtype = sigma.device, sigma.dtype+ x = torch.arange(window_size, device=device, dtype=dtype) - window_size // 2if window_size % 2 == 0:x = x + 0.5gauss = torch.exp((-x.pow(2.0) / (2 * sigma ** 2)))diff --git a/kornia/geometry/transform/__init__.py b/kornia/geometry/transform/__init__.pyindex 903db82c0..095ddf18d 100644--- a/kornia/geometry/transform/__init__.py+++ b/kornia/geometry/transform/__init__.py@@ -6,3 +6,4 @@ from kornia.geometry.transform.pyramid import *from kornia.geometry.transform.affwarp import *from kornia.geometry.transform.flips import *from kornia.geometry.transform.projwarp import *+from kornia.geometry.transform.elastic_transform import *diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.pynew file mode 100644index 000000000..32b6dca4e--- /dev/null+++ b/kornia/geometry/transform/elastic_transform.py@@ -0,0 +1,90 @@+from typing import Tuple, Optional++import torch+import torch.nn.functional as F++import kornia+from kornia.filters.kernels import get_gaussian_kernel2d+++__all__ = ["elastic_transform2d"]+++def elastic_transform2d(image: torch.Tensor,+ noise: torch.Tensor,+ kernel_size: Tuple[int, int] = (3, 3),+ sigma: Tuple[float, float] = (4., 4.),+ alpha: Tuple[float, float] = (32., 32.),+ align_corners: bool = False) -> torch.Tensor:+ r"""Applies elastic transform of images as described in :cite:`Simard2003BestPF`.++ Args:+ image (torch.Tensor): Input image to be transformed with shape :math:`(B, C, H, W)`.+ noise (torch.Tensor): Noise image used to spatially transform the input image. Same+ resolution as the input image with shape :math:`(B, 2, H, W)`. The coordinates order+ it is expected to be in x-y.+ kernel_size (Tuple[int, int]): the size of the Gaussian kernel. Default: (3, 3).+ sigma (Tuple[float, float]): The standard deviation of the Gaussian in the y and x directions,+ respecitvely. Larger sigma results in smaller pixel displacements. Default: (4, 4).+ alpha (Tuple[float, float]): The scaling factor that controls the intensity of the deformation+ in the y and x directions, respectively. Default: 32.+ align_corners (bool): Interpolation flag used by `grid_sample`. Default: False.++ .. note:+ `sigma` and `alpha` can also be a `torch.Tensor`. However, you could not torchscript+ this function with tensor until PyTorch 1.8 is released.++ Returns:+ torch.Tensor: the elastically transformed input image with shape :math:`(B,C,H,W)`.++ Example:+ >>> image = torch.rand(1, 3, 5, 5)+ >>> noise = torch.rand(1, 2, 5, 5, requires_grad=True)+ >>> image_hat = elastic_transform2d(image, noise, (3, 3))+ >>> image_hat.mean().backward()++ >>> image = torch.rand(1, 3, 5, 5)+ >>> noise = torch.rand(1, 2, 5, 5)+ >>> sigma = torch.tensor([4., 4.], requires_grad=True)+ >>> image_hat = elastic_transform2d(image, noise, (3, 3), sigma)+ >>> image_hat.mean().backward()++ >>> image = torch.rand(1, 3, 5, 5)+ >>> noise = torch.rand(1, 2, 5, 5)+ >>> alpha = torch.tensor([16., 32.], requires_grad=True)+ >>> image_hat = elastic_transform2d(image, noise, (3, 3), alpha=alpha)+ >>> image_hat.mean().backward()+ """+ if not isinstance(image, torch.Tensor):+ raise TypeError(f"Input image is not torch.Tensor. Got {type(image)}")++ if not isinstance(noise, torch.Tensor):+ raise TypeError(f"Input noise is not torch.Tensor. Got {type(noise)}")++ if not len(image.shape) == 4:+ raise ValueError(f"Invalid image shape, we expect BxCxHxW. Got: {image.shape}")++ if not len(noise.shape) == 4 or noise.shape[1] != 2:+ raise ValueError(f"Invalid noise shape, we expect Bx2xHxW. Got: {noise.shape}")++ # Get Gaussian kernel for 'y' and 'x' displacement+ kernel_x: torch.Tensor = get_gaussian_kernel2d(kernel_size, (sigma[0], sigma[0]))[None]+ kernel_y: torch.Tensor = get_gaussian_kernel2d(kernel_size, (sigma[1], sigma[1]))[None]++ # Convolve over a random displacement matrix and scale them with 'alpha'+ disp_x: torch.Tensor = noise[:, :1]+ disp_y: torch.Tensor = noise[:, 1:]++ disp_x = kornia.filters.filter2D(disp_x, kernel=kernel_y, border_type='constant') * alpha[0]+ disp_y = kornia.filters.filter2D(disp_y, kernel=kernel_x, border_type='constant') * alpha[1]++ # stack and normalize displacement+ disp = torch.cat([disp_x, disp_y], dim=1).permute(0, 2, 3, 1)++ # Warp image based on displacement matrix+ b, c, h, w = image.shape+ grid = kornia.utils.create_meshgrid(h, w, device=image.device).to(image.dtype)+ warped = F.grid_sample(+ image, (grid + disp).clamp(-1, 1), align_corners=align_corners)++ return warpeddiff --git a/test/feature/test_mkd.py b/test/feature/test_mkd.pyindex 16edf7542..9c82b45cf 100644--- a/test/feature/test_mkd.py+++ b/test/feature/test_mkd.py@@ -480,6 +480,6 @@ class TestSimpleKD:def test_jit(self, device, dtype):batch_size, channels, ps = 1, 1, 19patches = torch.rand(batch_size, channels, ps, ps).to(device)- model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval() # noqa- model_jit = torch.jit.script( SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()) # noqa+ model = SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval() # noqa+ model_jit = torch.jit.script(SimpleKD(patch_size=ps, kernel_type='polar', whitening='lw').to(patches.device, patches.dtype).eval()) # noqaassert_allclose(model(patches), model_jit(patches))diff --git a/test/geometry/transform/test_elastic_transform.py b/test/geometry/transform/test_elastic_transform.pynew file mode 100644index 000000000..8b322148d--- /dev/null+++ b/test/geometry/transform/test_elastic_transform.py@@ -0,0 +1,88 @@+import pytest++import torch+from torch.autograd import gradcheck+from torch.testing import assert_allclose++import kornia+from kornia.geometry.transform import elastic_transform2d+++class TestElasticTransform:++ def test_smoke(self, device, dtype):+ image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)+ noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)+ assert elastic_transform2d(image, noise) is not None++ @pytest.mark.parametrize(+ "batch, channels, height, width", [(1, 3, 3, 4), (2, 2, 2, 4), (1, 5, 4, 1)])+ def test_cardinality(self, device, dtype, batch, channels, height, width):+ shape = batch, channels, height, width+ img = torch.ones(shape, device=device, dtype=dtype)+ noise = torch.ones((batch, 2, height, width), device=device, dtype=dtype)+ assert elastic_transform2d(img, noise).shape == shape++ def test_exception(self, device, dtype):+ with pytest.raises(TypeError):+ assert elastic_transform2d([0.])++ with pytest.raises(TypeError):+ assert elastic_transform2d(torch.tensor(), 1)++ with pytest.raises(ValueError):+ img = torch.ones(1, 1, 1, device=device, dtype=dtype)+ noise = torch.ones(1, 2, 1, 1, device=device, dtype=dtype)+ assert elastic_transform2d(img, noise)++ with pytest.raises(ValueError):+ img = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)+ noise = torch.ones(1, 3, 1, 1, device=device, dtype=dtype)+ assert elastic_transform2d(img, noise)++ @pytest.mark.parametrize("kernel_size, sigma, alpha", [+ [(3, 3), (4., 4.), (32., 32.)],+ [(5, 3), (4., 8.), (16., 32.)],+ [(5, 5), torch.tensor([2., 8.]), torch.tensor([16., 64.])],+ ])+ def test_valid_paramters(self, device, dtype, kernel_size, sigma, alpha):+ image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)+ noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)+ if isinstance(sigma, torch.Tensor):+ sigma = sigma.to(device, dtype)+ if isinstance(alpha, torch.Tensor):+ alpha = alpha.to(device, dtype)+ assert elastic_transform2d(image, noise, kernel_size, sigma, alpha) is not None++ def test_values(self, device, dtype):+ image = torch.tensor([[+ [[0.0018, 0.7521, 0.7550],+ [0.2053, 0.4249, 0.1369],+ [0.1027, 0.3992, 0.8773]]+ ]], device=device, dtype=dtype)++ noise = torch.ones(1, 2, 3, 3, device=device, dtype=dtype)++ expected = torch.tensor([[+ [[0.2193, 0.2193, 0.2193],+ [0.2193, 0.2193, 0.2193],+ [0.2193, 0.2193, 0.2193]]+ ]], device=device, dtype=dtype)++ actual = elastic_transform2d(image, noise)+ assert_allclose(actual, expected, atol=1e-3, rtol=1e-3)++ @pytest.mark.parametrize("requires_grad", [True, False])+ def test_gradcheck(self, device, dtype, requires_grad):+ image = torch.rand(1, 1, 3, 3, device=device, dtype=torch.float64, requires_grad=requires_grad)+ noise = torch.rand(1, 2, 3, 3, device=device, dtype=torch.float64, requires_grad=not requires_grad)+ assert gradcheck(elastic_transform2d, (image, noise,), raise_exception=True)++ def test_jit(self, device, dtype):+ image = torch.rand(1, 4, 5, 5, device=device, dtype=dtype)+ noise = torch.rand(1, 2, 5, 5, device=device, dtype=dtype)++ op = kornia.geometry.transform.elastic_transform2d+ op_jit = torch.jit.script(op)++ assert_allclose(op(image, noise), op_jit(image, noise))