Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fixed RandomAffine3D

Jian S43571ba73629
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index eca5bdeed..28c7e740c 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -201,18 +201,21 @@ class RandomAffine3D(AugmentationBase3D):
If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
(a, b), (m, n) and (x, y).
Set to 0 to deactivate rotations.
- translate (tuple, optional): tuple of maximum absolute fraction for horizontal
- and vertical translations. For example translate=(a, b), then horizontal shift
- is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
- randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
+ translate (tuple, optional): tuple of maximum absolute fraction for depthical, horizontal
+ and vertical translations. For example translate=(a, b, c), then
+ depthical shift will be randomly sampled in the range -img_depth * a < dx < img_depth * a
+ horizontal shift will be randomly sampled in the range -img_width * b < dy < img_width * b.
+ vertical shift will be randomly sampled in the range -img_height * b < dy < img_height * b.
+ Will not translate by default.
scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
randomly sampled from the range a <= scale <= b. Will keep original scale by default.
shear (sequence or float, optional): Range of degrees to select from.
- If shear is a number, a shear parallel to the x axis in the range (-shear, +shear)
- will be apllied. Else if shear is a tuple or list of 2 values a shear parallel to the x axis in the
- range (shear[0], shear[1]) will be applied. Else if shear is a tuple or list of 4 values,
- a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
- Will not apply shear by default
+ If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be apllied.
+ If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
+ If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
+ will be applied.
+ If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
+ will be applied.
resample (int, str or kornia.Resample): Default: Resample.BILINEAR
return_transform (bool): if ``True`` return the matrix describing the transformation
applied to each. Default: False.
@@ -223,12 +226,28 @@ class RandomAffine3D(AugmentationBase3D):
>>> input = torch.rand(1, 1, 3, 3, 3)
>>> aug = RandomAffine3D((15., 20., 20.), return_transform=True)
>>> aug(input)
+ (tensor([[[[[0.4503, 0.4763, 0.1680],
+ [0.2029, 0.4267, 0.3515],
+ [0.3195, 0.5436, 0.3706]],
+ <BLANKLINE>
+ [[0.5255, 0.3508, 0.4858],
+ [0.0795, 0.1689, 0.4220],
+ [0.5306, 0.7234, 0.6879]],
+ <BLANKLINE>
+ [[0.2971, 0.2746, 0.3471],
+ [0.4924, 0.4960, 0.6460],
+ [0.3187, 0.4556, 0.7596]]]]]), tensor([[[ 0.9722, -0.0603, 0.2262, -0.1381],
+ [ 0.1131, 0.9669, -0.2286, 0.1486],
+ [-0.2049, 0.2478, 0.9469, 0.0102],
+ [ 0.0000, 0.0000, 0.0000, 1.0000]]]))
"""
def __init__(
self, degrees: Union[float, Tuple[float, float, float]],
translate: Optional[Tuple[float, float, float]] = None, scale: Optional[Tuple[float, float]] = None,
- shear: Optional[Union[float, Tuple[float, float]]] = None,
+ shear: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float],
+ Tuple[float, 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
) -> None:
diff --git a/kornia/augmentation/functional3d.py b/kornia/augmentation/functional3d.py
index 05a0c5157..f6b9d6bcf 100644
--- a/kornia/augmentation/functional3d.py
+++ b/kornia/augmentation/functional3d.py
@@ -241,12 +241,15 @@ def apply_affine3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torc
input (torch.Tensor): Tensor to be transformed with shape (D, H, W), (C, D, H, W), (B, C, D, H, W).
params (Dict[str, torch.Tensor]):
- params['angles']: Degrees of rotation with the shape of :math: `(*, 3)` for yaw, pitch, roll.
- - params['translations']: Horizontal and vertical translations.
+ - params['translations']: Depthical, Horizontal and vertical translations.
- params['center']: Rotation center.
- - params['scale']: Scaling params.
- - params['sx']: Shear param toward x-axis.
- - params['sy']: Shear param toward y-axis.
- - params['sz']: Shear param toward y-axis.
+ - params['scale']: Isotropic scaling params.
+ - params['sxy']: Shear param toward x-y-axis.
+ - params['sxz']: Shear param toward x-z-axis.
+ - params['syx']: Shear param toward y-x-axis.
+ - params['syz']: Shear param toward y-z-axis.
+ - params['szx']: Shear param toward z-x-axis.
+ - params['szy']: Shear param toward z-y-axis.
- params['resample']: Integer tensor. NEAREST = 0, BILINEAR = 1.
- params['align_corners']: Boolean tensor.
@@ -286,7 +289,7 @@ def compute_affine_transformation3d(input: torch.Tensor, params: Dict[str, torch
- params['angles']: Degrees of rotation with the shape of :math: `(*, 3)` for yaw, pitch, roll.
- params['translations']: Depthical, Horizontal and vertical translations.
- params['center']: Rotation center.
- - params['scale']: Scaling params.
+ - params['scale']: Isotropic scaling params.
- params['sxy']: Shear param toward x-y-axis.
- params['sxz']: Shear param toward x-z-axis.
- params['syx']: Shear param toward y-x-axis.
diff --git a/kornia/augmentation/random_generator3d.py b/kornia/augmentation/random_generator3d.py
index 56b54e047..8ed59e60c 100644
--- a/kornia/augmentation/random_generator3d.py
+++ b/kornia/augmentation/random_generator3d.py
@@ -8,7 +8,7 @@ from kornia.constants import Resample, BorderType
from .utils import (
_adapted_uniform,
_check_and_bound,
- _rotation_range_reader
+ _tuple_range_reader,
)
@@ -38,7 +38,7 @@ def random_rotation_generator3d(
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
- _degrees = _rotation_range_reader(degrees)
+ _degrees = _tuple_range_reader(degrees, 3)
yaw = _adapted_uniform((batch_size,), _degrees[0][0], _degrees[0][1], same_on_batch)
pitch = _adapted_uniform((batch_size,), _degrees[1][0], _degrees[1][1], same_on_batch)
@@ -60,7 +60,9 @@ def random_affine_generator3d(
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
translate: Optional[Tuple[float, float, float]] = None,
scale: Optional[Tuple[float, float]] = None,
- shear: Optional[Union[float, Tuple[float, float]]] = None,
+ shears: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float, float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float], Tuple[float, float],
+ Tuple[float, float], Tuple[float, float]]] = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = False
@@ -82,11 +84,12 @@ def random_affine_generator3d(
scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
randomly sampled from the range a <= scale <= b. Will keep original scale by default.
shear (sequence or float, optional): Range of degrees to select from.
- If shear is a number, a shear parallel to the x axis in the range (-shear, +shear)
- will be apllied. Else if shear is a tuple or list of 2 values a shear parallel to the x axis in the
- range (shear[0], shear[1]) will be applied. Else if shear is a tuple or list of 4 values,
- a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
- Will not apply shear by default
+ If shear is a number, a shear to the 6 facets in the range (-shear, +shear) will be apllied.
+ If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
+ If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
+ will be applied.
+ If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
+ will be applied.
resample (int, str or kornia.Resample): Default: Resample.BILINEAR
same_on_batch (bool): apply the same transformation across the batch. Default: False
align_corners(bool): interpolation flag. Default: False.See
@@ -95,7 +98,11 @@ def random_affine_generator3d(
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
- degrees_tmp = _rotation_range_reader(degrees)
+ degrees_tmp = _tuple_range_reader(degrees, 3)
+ if shears is not None:
+ shears_tmp = _tuple_range_reader(shears, 6)
+ else:
+ shears_tmp = None
# check translation range
if translate is not None:
@@ -113,22 +120,8 @@ def random_affine_generator3d(
if s <= 0:
raise ValueError("scale values should be positive")
- # check shear range
- shear_tmp: Optional[Tuple[float, float]]
- if shear is not None:
- if isinstance(shear, float):
- if shear < 0:
- raise ValueError("If shear is a single number, it must be positive.")
- shear_tmp = (-shear, shear)
- else:
- assert isinstance(shear, (tuple, list)) and len(shear) == 2, \
- "shear should be a list or tuple and it must be of length 2."
- shear_tmp = shear
- else:
- shear_tmp = shear
-
return _get_random_affine_params(
- batch_size, depth, height, width, degrees_tmp, translate, scale, shear_tmp,
+ batch_size, depth, height, width, degrees_tmp, translate, scale, shears_tmp,
resample, same_on_batch, align_corners)
@@ -140,12 +133,12 @@ def _get_random_affine_params(
degrees: torch.Tensor,
translate: Optional[Tuple[float, float, float]],
scales: Optional[Tuple[float, float]],
- shears: Optional[Tuple[float, float]],
+ shears: torch.Tensor = None,
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
align_corners: bool = False
) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ```affine``` transformation random affine transform.
+ r"""Get parameters for ```3d affine``` transformation random affine transform.
The returned matrix is Bx4x4.
Returns:
@@ -179,12 +172,12 @@ def _get_random_affine_params(
center = center.expand(batch_size, -1)
if shears is not None:
- sxy = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
- sxz = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
- syx = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
- syz = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
- szx = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
- szy = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
+ sxy = _adapted_uniform((batch_size,), shears[0, 0], shears[0, 1], same_on_batch)
+ sxz = _adapted_uniform((batch_size,), shears[1, 0], shears[1, 1], same_on_batch)
+ syx = _adapted_uniform((batch_size,), shears[2, 0], shears[2, 1], same_on_batch)
+ syz = _adapted_uniform((batch_size,), shears[3, 0], shears[3, 1], same_on_batch)
+ szx = _adapted_uniform((batch_size,), shears[4, 0], shears[4, 1], same_on_batch)
+ szy = _adapted_uniform((batch_size,), shears[5, 0], shears[5, 1], same_on_batch)
else:
sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size)
diff --git a/kornia/augmentation/utils.py b/kornia/augmentation/utils.py
index 9678287b5..595e2acfc 100644
--- a/kornia/augmentation/utils.py
+++ b/kornia/augmentation/utils.py
@@ -164,49 +164,45 @@ def _check_and_bound(factor: Union[torch.Tensor, float, Tuple[float, float], Lis
return factor_bound
-def _rotation_range_reader(
- degrees: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float],
- Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]
+def _tuple_range_reader(
+ shears: Union[torch.Tensor, float, tuple],
+ target_size: int
) -> torch.Tensor:
+ """
+ Given target_size, it will generate the correponding (target_size, 2) range tensor for tasks like
+ affine transformation.
+ """
+ target_shape = torch.Size([target_size, 2])
+ if not torch.is_tensor(shears):
+ if isinstance(shears, (float, int)):
+ if shears < 0:
+ raise ValueError(f"If shears is only one number it must be a positive number. Got{shears}")
+ shears_tmp = torch.tensor([-shears, shears]).repeat(target_shape[0], 1).to(torch.float32)
+
+ elif isinstance(shears, (tuple)) and len(shears) == 2 \
+ and isinstance(shears[0], (float, int)) and isinstance(shears[1], (float, int)):
+ shears_tmp = torch.tensor(shears).repeat(target_shape[0], 1).to(torch.float32)
+
+ elif isinstance(shears, (tuple)) and len(shears) == target_shape[0] \
+ and all([isinstance(x, (float, int)) for x in shears]):
+ shears_tmp = torch.tensor([(-s, s) for s in shears]).to(torch.float32)
+
+ elif isinstance(shears, (tuple)) and len(shears) == target_shape[0] \
+ and all([isinstance(x, (tuple)) for x in shears]):
+ shears_tmp = torch.tensor(shears).to(torch.float32)
- if not torch.is_tensor(degrees):
- if isinstance(degrees, (float, int)):
- if degrees < 0:
- raise ValueError(f"If Degrees is only one number it must be a positive number. Got{degrees}")
- yaw = torch.tensor([-degrees, degrees]).to(torch.float32)
- pitch = torch.tensor([-degrees, degrees]).to(torch.float32)
- roll = torch.tensor([-degrees, degrees]).to(torch.float32)
-
- elif isinstance(degrees, (tuple)) and len(degrees) == 2 \
- and isinstance(degrees[0], (float, int)) and isinstance(degrees[1], (float, int)):
- yaw = torch.tensor(degrees).to(torch.float32)
- pitch = torch.tensor(degrees).to(torch.float32)
- roll = torch.tensor(degrees).to(torch.float32)
-
- elif isinstance(degrees, (tuple)) and len(degrees) == 3 \
- and isinstance(degrees[0], (tuple)) and isinstance(degrees[1], (tuple)) \
- and isinstance(degrees[2], (tuple)):
- yaw = torch.tensor(degrees[0]).to(torch.float32)
- pitch = torch.tensor(degrees[1]).to(torch.float32)
- roll = torch.tensor(degrees[2]).to(torch.float32)
-
- elif isinstance(degrees, (tuple)) and len(degrees) == 3 \
- and isinstance(degrees[0], (float, int)) and isinstance(degrees[1], (float, int)) \
- and isinstance(degrees[2], (float, int)):
- yaw = torch.tensor((-degrees[0], degrees[0])).to(torch.float32)
- pitch = torch.tensor((-degrees[1], degrees[1])).to(torch.float32)
- roll = torch.tensor((-degrees[2], degrees[2])).to(torch.float32)
else:
- raise TypeError(f"Degrees should be a float number a sequence or a tensor. Got {degrees}")
+ raise TypeError(
+ "If not pass a tensor, it must be float, (float, float) for isotropic shearing or a tuple of"
+ f"{target_size} floats or {target_size} (float, float) for independent shearing. Got {shears}.")
else:
# https://mypy.readthedocs.io/en/latest/casts.html cast to please mypy gods
- degrees = cast(torch.Tensor, degrees)
- if len(degrees) != 3 and len(degrees[0]) != len(degrees[1]) != len(degrees[2]) != 2:
+ shears = cast(torch.Tensor, shears)
+ if shears.shape != target_shape:
raise ValueError(
- f"Degrees must be a 3x2 tensor for the degree range of yaw, pitch, roll. Got {degrees.shape}")
- yaw = degrees[0]
- pitch = degrees[1]
- roll = degrees[2]
+ f"Degrees must be a {list(target_shape)} tensor for the degree range for independent shearing."
+ f"Got {shears}")
+ shears_tmp = shears
- return torch.stack([yaw, pitch, roll], dim=0)
+ return shears_tmp
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 9ffa8145a..f0a54ce2a 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -42,7 +42,7 @@ def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
"""Computes the center of tensor plane for (D, H, W), (C, D, H, W) and (B, C, D, H, W)."""
- assert 3 <= len(tensor) <= 5, f"Must be a 3D tensor as DHW, CDHW and BCDHW. Got {tensor.shape}."
+ assert 3 <= len(tensor.shape) <= 5, f"Must be a 3D tensor as DHW, CDHW and BCDHW. Got {tensor.shape}."
depth, height, width = tensor.shape[-3:]
center_x: float = float(depth - 1) / 2
center_y: float = float(height - 1) / 2
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 8332d3db1..9044c331e 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -495,7 +495,38 @@ def get_affine_matrix3d(translations: torch.Tensor, center: torch.Tensor, scale:
transform[..., 3] += translations # tx/ty/tz
# pad transform to get Bx3x3
transform_h = convert_affinematrix_to_homography3d(transform)
+ shear_mat = get_shear_matrix3d(center, sxy, sxz, syx, syz, szx, szy)
+ transform_h = transform_h @ shear_mat
+ return transform_h
+
+def get_shear_matrix3d(
+ center: torch.Tensor,
+ sxy: Optional[torch.Tensor] = None, sxz: Optional[torch.Tensor] = None,
+ syx: Optional[torch.Tensor] = None, syz: Optional[torch.Tensor] = None,
+ szx: Optional[torch.Tensor] = None, szy: Optional[torch.Tensor] = None,
+):
+ r"""Composes shear matrix Bx4x4 from the components.
+ .. math::
+ \begin{bmatrix}
+ 1 & o & r & oy + rz \\
+ m & p & s & mx + py + sz -y \\
+ n & q & t & nx + qy + tz -z \\
+ 0 & 0 & 0 & 1 \\
+ \end{bmatrix}
+ Where:
+ m = S_{xy}
+ n = S_{xz}
+ o = S_{yx}
+ p = S_{xy}S_{yx} + S_{yz}
+ q = S_{xz}S_{yx}
+ r = S_{zx} + S_{yx}S_{zy}
+ s = S_{xy}S_{zx} + (S_{xy}S_{yx} + S_{yz})S_{zy}
+ t = S_{xz}S_{zx} + S_{xz}S_{yx}S_{zy} + 1
+ Returns:
+ torch.Tensor: params to be passed to the affine transformation.
+
+ """
sxy = torch.tensor(0) if sxy is None else sxy
sxz = torch.tensor(0) if sxz is None else sxz
syx = torch.tensor(0) if syx is None else syx
@@ -504,28 +535,45 @@ def get_affine_matrix3d(translations: torch.Tensor, center: torch.Tensor, scale:
szy = torch.tensor(0) if szy is None else szy
x, y, z = torch.split(center, 1, dim=-1)
- x = x.view(-1)
- y = y.view(-1)
- z = z.view(-1)
+ x, y, z = x.view(-1), y.view(-1), z.view(-1)
+ # Prepare parameters
sxy_tan = torch.tan(sxy) # type: ignore
sxz_tan = torch.tan(sxz) # type: ignore
syx_tan = torch.tan(syx) # type: ignore
syz_tan = torch.tan(syz) # type: ignore
szx_tan = torch.tan(szx) # type: ignore
szy_tan = torch.tan(szy) # type: ignore
- zeros = torch.zeros_like(sxy) # type: ignore
- ones = torch.ones_like(sxy) # type: ignore
- m00, m01, m02 = ones, -sxy_tan, -sxz_tan
- m10, m11, m12 = -syx_tan, sxy_tan * syx_tan + ones, sxz_tan * syx_tan - syz_tan
- m20 = syx_tan * szy_tan - szx_tan
- m21 = sxy_tan * szx_tan - szy_tan * m11
- m22 = sxz_tan * szx_tan - szy_tan * m12 +ones
- # TODO: translation math
+
+ # compute translation matrix
+ m00, m10, m20, m01, m11, m21, m02, m12, m22 = _computer_shear_matrix(
+ sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan)
+
+ m03 = m01 * y + m02 * z
+ m13 = m10 * x + m11 * y + m12 * z - y
+ m23 = m20 * x + m21 * y + m22 * z - z
+
+ # shear matrix is implemented with negative values
+ sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan = \
+ - sxy_tan, - sxz_tan, - syx_tan, - syz_tan, - szx_tan, - szy_tan
+ m00, m10, m20, m01, m11, m21, m02, m12, m22 = _computer_shear_matrix(
+ sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan)
+
shear_mat = torch.stack([
- m00, m10, m20, zeros,
- m01, m11, m21, zeros,
- m02, m12, m22, zeros
+ m00, m01, m02, m03,
+ m10, m11, m12, m13,
+ m20, m21, m22, m23
], dim=-1).view(-1, 3, 4)
shear_mat = convert_affinematrix_to_homography3d(shear_mat)
- transform_h = transform_h @ shear_mat
- return transform_h
+ return shear_mat
+
+
+def _computer_shear_matrix(sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan):
+ zeros = torch.zeros_like(sxy_tan) # type: ignore
+ ones = torch.ones_like(sxy_tan) # type: ignore
+
+ m00, m10, m20 = ones, sxy_tan, sxz_tan
+ m01, m11, m21 = syx_tan, sxy_tan * syx_tan + ones, sxz_tan * syx_tan + syz_tan
+ m02 = syx_tan * szy_tan + szx_tan
+ m12 = sxy_tan * szx_tan + szy_tan * m11
+ m22 = sxz_tan * szx_tan + szy_tan * m21 + ones
+ return m00, m10, m20, m01, m11, m21, m02, m12, m22