Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

padding_mode augmentations (#640)

Sam Toyer55fdeb4bfdb6
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 9033d8b28..a7db2ff6a 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -104,4 +104,4 @@ from kornia.utils import (
)
from kornia.geometry import *
-from kornia.constants import pi
+from kornia.constants import *
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index efb7a06d2..8c157f013 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
from torch.nn.functional import pad
-from kornia.constants import Resample, BorderType
+from kornia.constants import Resample, BorderType, SamplePadding
from . import functional as F
from . import random_generator as rg
from .utils import (
@@ -412,6 +412,7 @@ class RandomAffine(AugmentationBase):
x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in (shear[1][0], shear[1][1]) will be applied.
Will not apply shear by default
resample (int, str or kornia.Resample): Default: Resample.BILINEAR
+ padding_mode (int, str or kornia.SamplePadding): Default: SamplePadding.ZEROS
return_transform (bool): if ``True`` return the matrix describing the transformation
applied to each. Default: False.
same_on_batch (bool): apply the same transformation across the batch. Default: False
@@ -435,7 +436,8 @@ class RandomAffine(AugmentationBase):
scale: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
- return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False
+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False,
+ padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
) -> None:
super(RandomAffine, self).__init__(return_transform)
degrees = cast(torch.Tensor, degrees) if isinstance(degrees, torch.Tensor) else torch.tensor(degrees)
@@ -455,6 +457,7 @@ class RandomAffine(AugmentationBase):
_range_bound(shear[2:], 'shear-y', 0, (-360, 360))
])
self.resample: Resample = Resample.get(resample)
+ self.padding_mode: SamplePadding = SamplePadding.get(padding_mode)
self.same_on_batch = same_on_batch
self.align_corners = align_corners
@@ -466,7 +469,7 @@ class RandomAffine(AugmentationBase):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_affine_generator(
batch_shape[0], batch_shape[-2], batch_shape[-1], self.degrees, self.translate, self.scale, self.shear,
- self.resample, self.same_on_batch, self.align_corners)
+ self.resample, self.same_on_batch, self.align_corners, self.padding_mode)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_affine_transformation(input, params)
diff --git a/kornia/augmentation/functional.py b/kornia/augmentation/functional.py
index 002b7b49a..f2ed25d45 100644
--- a/kornia/augmentation/functional.py
+++ b/kornia/augmentation/functional.py
@@ -3,7 +3,7 @@ from typing import Tuple, List, Union, Dict, cast, Optional
import torch
import torch.nn as nn
-from kornia.constants import Resample, BorderType, pi
+from kornia.constants import Resample, BorderType, SamplePadding, pi
from kornia.geometry import (
get_perspective_transform,
get_rotation_matrix2d,
@@ -489,6 +489,7 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.
- params['sx']: Shear param toward x-axis.
- params['sy']: Shear param toward y-axis.
- params['resample']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['padding_mode']: Integer tensor, see SamplePadding enum.
- params['align_corners']: Boolean tensor.
Returns:
@@ -510,11 +511,13 @@ def apply_affine(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.
transform: torch.Tensor = compute_affine_transformation(input, params)
resample_name: str = Resample(params['resample'].item()).name.lower()
+ padding_mode: str = SamplePadding(params['padding_mode'].item()).name.lower()
align_corners: bool = cast(bool, params['align_corners'].item())
out_data: torch.Tensor = warp_affine(x_data, transform[:, :2, :],
(height, width), resample_name,
- align_corners=align_corners)
+ align_corners=align_corners,
+ padding_mode=padding_mode)
return out_data.view_as(input)
diff --git a/kornia/augmentation/random_generator.py b/kornia/augmentation/random_generator.py
index e768592ff..89609d765 100644
--- a/kornia/augmentation/random_generator.py
+++ b/kornia/augmentation/random_generator.py
@@ -4,7 +4,7 @@ import math
import torch
-from kornia.constants import Resample, BorderType
+from kornia.constants import Resample, BorderType, SamplePadding
from .utils import (
_adapted_uniform,
_joint_range_check
@@ -147,7 +147,8 @@ def random_affine_generator(
shear: Optional[torch.Tensor] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
- align_corners: bool = False
+ align_corners: bool = False,
+ padding_mode: Union[str, int, SamplePadding] = SamplePadding.ZEROS.name,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``affine`` for a random affine transform.
@@ -174,6 +175,7 @@ def random_affine_generator(
same_on_batch (bool): apply the same transformation across the batch. Default: False
align_corners(bool): interpolation flag. Default: False.See
https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+ padding_mode (int, str or kornia.SamplePadding): Default: SamplePadding.ZEROS
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
@@ -219,6 +221,7 @@ def random_affine_generator(
sx=sx,
sy=sy,
resample=torch.tensor(Resample.get(resample).value),
+ padding_mode=torch.tensor(SamplePadding.get(padding_mode).value),
align_corners=torch.tensor(align_corners))
diff --git a/kornia/constants.py b/kornia/constants.py
index 827b053de..ab9089530 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -3,16 +3,13 @@ from enum import Enum
import torch
-pi = torch.tensor(3.14159265358979323846)
-T = TypeVar('T', bound='Resample')
-U = TypeVar('U', bound='BorderType')
+__all__ = ['pi', 'Resample', 'BorderType', 'SamplePadding']
+pi = torch.tensor(3.14159265358979323846)
+T = TypeVar('T', bound='ConstantBase')
-class Resample(Enum):
- NEAREST = 0
- BILINEAR = 1
- BICUBIC = 2
+class ConstantBase:
@classmethod
def get(cls, value: Union[str, int, T]) -> T: # type: ignore
if type(value) == str:
@@ -24,18 +21,20 @@ class Resample(Enum):
raise TypeError()
-class BorderType(Enum):
+class Resample(ConstantBase, Enum):
+ NEAREST = 0
+ BILINEAR = 1
+ BICUBIC = 2
+
+
+class BorderType(ConstantBase, Enum):
CONSTANT = 0
REFLECT = 1
REPLICATE = 2
CIRCULAR = 3
- @classmethod
- def get(cls, value: Union[str, int, U]) -> U: # type: ignore
- if type(value) == str:
- return cls[value.upper()] # type: ignore
- if type(value) == int:
- return cls(value) # type: ignore
- if type(value) == cls:
- return value # type: ignore
- raise TypeError()
+
+class SamplePadding(ConstantBase, Enum):
+ ZEROS = 0
+ BORDER = 1
+ REFLECTION = 2