Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Math fixes for 3d affine transformation & doc updates

Jian Sb5f76390ac89
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 6a8d0819e..eca5bdeed 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -217,6 +217,12 @@ class RandomAffine3D(AugmentationBase3D):
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
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3, 3)
+ >>> aug = RandomAffine3D((15., 20., 20.), return_transform=True)
+ >>> aug(input)
"""
def __init__(
diff --git a/kornia/augmentation/functional3d.py b/kornia/augmentation/functional3d.py
index de20835ce..05a0c5157 100644
--- a/kornia/augmentation/functional3d.py
+++ b/kornia/augmentation/functional3d.py
@@ -287,9 +287,12 @@ def compute_affine_transformation3d(input: torch.Tensor, params: Dict[str, torch
- 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['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.
@@ -300,7 +303,8 @@ def compute_affine_transformation3d(input: torch.Tensor, params: Dict[str, torch
_validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
transform = get_affine_matrix3d(
params['translations'], params['center'], params['scale'], params['angles'],
- deg2rad(params['sx']), deg2rad(params['sy']), deg2rad(params['sz'])
+ deg2rad(params['sxy']), deg2rad(params['sxz']), deg2rad(params['syx']),
+ deg2rad(params['syz']), deg2rad(params['szx']), deg2rad(params['szy'])
).type_as(input)
return transform
diff --git a/kornia/augmentation/random_generator3d.py b/kornia/augmentation/random_generator3d.py
index 2207b318c..56b54e047 100644
--- a/kornia/augmentation/random_generator3d.py
+++ b/kornia/augmentation/random_generator3d.py
@@ -179,18 +179,24 @@ def _get_random_affine_params(
center = center.expand(batch_size, -1)
if shears is not None:
- sx = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
- sy = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
- sz = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
+ 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)
else:
- sx = sy = sz = torch.tensor([0] * batch_size)
+ sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size)
return dict(translations=translations,
center=center,
scale=scale,
angles=angles,
- sx=sx,
- sy=sy,
- sz=sz,
+ sxy=sxy,
+ sxz=sxz,
+ syx=syx,
+ syz=syz,
+ szx=szx,
+ szy=szy,
resample=torch.tensor(Resample.get(resample).value),
align_corners=torch.tensor(align_corners))
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 4fe36efba..4739e27c1 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -117,6 +117,12 @@ def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:
return torch.nn.functional.pad(points, [0, 1], "constant", 1.0)
+def _convert_affinematrix_to_homography_impl(A: torch.Tensor) -> torch.Tensor:
+ H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.)
+ H[..., -1, -1] += 1.0
+ return H
+
+
def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:
r"""Function that converts batch of affine matrices from [Bx2x3] to [Bx3x3].
@@ -131,9 +137,7 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:
if not (len(A.shape) == 3 and A.shape[-2:] == (2, 3)):
raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}"
.format(A.shape))
- H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.)
- H[..., -1, -1] += 1.0
- return H
+ return _convert_affinematrix_to_homography_impl(A)
def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
@@ -150,9 +154,7 @@ def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
if not (len(A.shape) == 3 and A.shape[-2:] == (3, 4)):
raise ValueError("Input matrix must be a Bx3x4 tensor. Got {}"
.format(A.shape))
- H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.)
- H[..., -1, -1] += 1.0
- return H
+ return _convert_affinematrix_to_homography_impl(A)
def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 8143192e2..9ffa8145a 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -29,7 +29,8 @@ __all__ = [
def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
- """Computes the center of tensor plane."""
+ """Computes the center of tensor plane for (H, W), (C, H, W) and (B, C, H, W)."""
+ assert 2 <= len(tensor) <=4, f"Must be a 3D tensor as HW, CHW and BCHW. Got {tensor.shape}."
height, width = tensor.shape[-2:]
center_x: float = float(width - 1) / 2
center_y: float = float(height - 1) / 2
@@ -40,7 +41,8 @@ def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:
def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:
- """Computes the center of tensor plane."""
+ """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}."
depth, height, width = tensor.shape[-3:]
center_x: float = float(depth - 1) / 2
center_y: float = float(height - 1) / 2
@@ -76,7 +78,8 @@ def _compute_rotation_matrix3d(yaw: torch.Tensor, pitch: torch.Tensor, roll: tor
f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}."
angles: torch.Tensor = torch.cat([yaw, pitch, roll], dim=1)
- matrix: torch.Tensor = get_projective_transform(center, angles)
+ scales: torch.Tensor = torch.ones_like(yaw)
+ matrix: torch.Tensor = get_projective_transform(center, angles, scales)
return matrix
@@ -119,7 +122,8 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',
r"""Apply an affine transformation to the image.
Args:
- tensor (torch.Tensor): The image tensor to be warped.
+ tensor (torch.Tensor): The image tensor to be warped in shapes of
+ :math:`(H, W)`, :math:`(D, H, W)` and :math:`(B, C, H, W)`.
matrix (torch.Tensor): The 2x3 affine transformation matrix.
mode (str): 'bilinear' | 'nearest'
align_corners(bool): interpolation flag. Default: False. See
@@ -155,7 +159,8 @@ def affine3d(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',
r"""Apply an affine transformation to the 3d volume.
Args:
- tensor (torch.Tensor): The image tensor to be warped.
+ tensor (torch.Tensor): The image tensor to be warped in shapes of
+ :math:`(D, H, W)`, :math:`(C, D, H, W)` and :math:`(B, C, D, H, W)`.
matrix (torch.Tensor): The 3x4 affine transformation matrix.
mode (str): 'bilinear' | 'nearest'
align_corners(bool): interpolation flag. Default: False. See
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 8d03fedc4..8332d3db1 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -484,33 +484,48 @@ def get_affine_matrix2d(translations: torch.Tensor, center: torch.Tensor, scale:
def get_affine_matrix3d(translations: torch.Tensor, center: torch.Tensor, scale: torch.Tensor, angles: torch.Tensor,
- sx: Optional[torch.Tensor] = None, sy: Optional[torch.Tensor] = None,
- sz: Optional[torch.Tensor] = None) -> 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) -> torch.Tensor:
r"""Composes affine matrix Bx4x4 from the components
Returns:
torch.Tensor: params to be passed to the affine transformation.
"""
- # TODO: scale is not implemented here
- transform: torch.Tensor = get_projective_transform(center, -angles)
+ transform: torch.Tensor = get_projective_transform(center, -angles, scale)
transform[..., 3] += translations # tx/ty/tz
# pad transform to get Bx3x3
transform_h = convert_affinematrix_to_homography3d(transform)
- if sx is not None or sy is not None or sz is not None:
- x, y, z = torch.split(center, 1, dim=-1)
- x = x.view(-1)
- y = y.view(-1)
- z = z.view(-1)
- sx_tan = torch.tan(sx) # type: ignore
- sy_tan = torch.tan(sy) # type: ignore
- sz_tan = torch.tan(sz) # type: ignore
- zeros = torch.zeros_like(sx) # type: ignore
- ones = torch.ones_like(sx) # type: ignore
- shear_mat = torch.stack([
- ones, -sx_tan, -sx_tan, zeros,
- -sy_tan, ones, -sy_tan, zeros,
- -sz_tan, -sz_tan, ones, zeros,
- ], dim=-1).view(-1, 3, 4)
- shear_mat = convert_affinematrix_to_homography3d(shear_mat)
- transform_h = transform_h @ shear_mat
+ 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
+ syz = torch.tensor(0) if syz is None else syz
+ szx = torch.tensor(0) if szx is None else szx
+ 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)
+ 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
+ shear_mat = torch.stack([
+ m00, m10, m20, zeros,
+ m01, m11, m21, zeros,
+ m02, m12, m22, zeros
+ ], dim=-1).view(-1, 3, 4)
+ shear_mat = convert_affinematrix_to_homography3d(shear_mat)
+ transform_h = transform_h @ shear_mat
return transform_h
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index 5c69225e5..df2453e89 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -78,7 +78,7 @@ def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
return torch.cat([rmat, tvec], dim=-1) # Bx3x4
-def get_projective_transform(center: torch.Tensor, angles: torch.Tensor) -> torch.Tensor:
+def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
r"""Calculates the projection matrix for a 3D rotation.
The function computes the projection matrix given the center and angles per axis.
@@ -88,6 +88,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor) -> torc
angles (torch.Tensor): angle axis vector containing the rotation angles in degrees in the form
of (rx, ry, rz) with shape :math:`(B, 3)`. Internally it calls Rodrigues to compute
the rotation matrix from axis-angle.
+ scales (torch.Tensor): isotropic scale factor.
Returns:
torch.Tensor: the projection matrix of 3D rotation with shape :math:`(B, 3, 4)`.
@@ -100,7 +101,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor) -> torc
# create rotation matrix
angle_axis_rad: torch.Tensor = K.deg2rad(angles)
- rmat: torch.Tensor = K.angle_axis_to_rotation_matrix(angle_axis_rad) # Bx3x3
+ rmat: torch.Tensor = K.angle_axis_to_rotation_matrix(angle_axis_rad) * scales.view(-1, 1, 1) # Bx3x3
# define matrix to move forth and back to origin
from_origin_mat = torch.eye(4)[None].repeat(rmat.shape[0], 1, 1).type_as(center) # Bx4x4