π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(3d): state that yaw/pitch/roll is one axis-angle vector, not Euler angles (#5393)
yi111bb4c8133ba57
diff --git a/changelog.d/5393.fixed.md b/changelog.d/5393.fixed.mdnew file mode 100644index 000000000..14d42c465--- /dev/null+++ b/changelog.d/5393.fixed.md@@ -0,0 +1 @@+The docstrings of `rotate3d`, `RandomRotation3D`, `RandomAffine3D`, `RandomMotionBlur3D`, their 3D parameter generators and `motion_blur3d` read as if `yaw`, `pitch` and `roll` were Euler angles, most of them as rotations about the x, y and z axes. They now say that the three form one axis-angle vector in degrees, converted with Rodrigues' formula: a single non-zero component is the rotation about its axis, while `(90, 90, 0)` is one turn of 127.3 degrees about `(1, 1, 0) / sqrt(2)`, which neither Euler order gives. `MotionBlur3D` says the same. The behaviour is unchanged.diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.pyindex 8ee6dd59c..1cb6b7a8c 100644--- a/kornia/augmentation/_3d/geometric/affine.py+++ b/kornia/augmentation/_3d/geometric/affine.py@@ -32,7 +32,9 @@ class RandomAffine3D(GeometricAugmentationBase3D):The transformation is computed so that the center is kept invariant.Args:- degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from. The three+ are sampled independently and concatenated into one axis-angle vector, not composed+ as per-axis Euler rotations; see :class:`RandomRotation3D` for the convention.If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)@@ -73,9 +75,12 @@ class RandomAffine3D(GeometricAugmentationBase3D):Convention:See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.- - ``degrees`` is ordered ``(yaw, pitch, roll)`` about the ``(x, y, z)`` voxel-coordinate axes. A positive- roll turns a displayed ``H x W`` slice counter-clockwise, and the rotation block is the transpose of- :class:`RandomRotation3D`'s (`#4408 <https://github.com/kornia/kornia/issues/4408>`_).+ - each sampled ``degrees`` triple ``(yaw, pitch, roll) = (rx, ry, rz)`` is **one axis-angle vector**+ in degrees and is converted into a single Rodrigues rotation, not composed as per-axis Euler+ rotations; see :class:`RandomRotation3D` for the convention.+ - A positive roll turns a displayed ``H x W`` slice counter-clockwise, and the rotation+ block is the transpose of :class:`RandomRotation3D`'s+ (`#4408 <https://github.com/kornia/kornia/issues/4408>`_).- the default is bilinear resampling with ``align_corners=False``.- a two-value ``scale=(a, b)`` is isotropic: one factor per sample is drawn from ``[a, b]`` and appliedto all three axes, as the 2D :class:`~kornia.augmentation.RandomAffine` does. The three-pair formdiff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.pyindex 28dc38d64..1d2412fe4 100644--- a/kornia/augmentation/_3d/geometric/rotation.py+++ b/kornia/augmentation/_3d/geometric/rotation.py@@ -57,9 +57,19 @@ class RandomRotation3D(GeometricAugmentationBase3D):Convention:See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.- - ``degrees`` is ordered ``(yaw, pitch, roll)`` about the ``(x, y, z)`` voxel-coordinate axes. A positive- roll turns a displayed ``H x W`` slice clockwise, as :func:`kornia.geometry.transform.rotate3d` does;- :class:`RandomAffine3D`, the 2D :class:`~kornia.augmentation.RandomRotation` and+ - each sampled ``degrees`` triple ``(yaw, pitch, roll) = (rx, ry, rz)`` is **one axis-angle vector**+ in degrees and is converted into a single Rodrigues rotation, not composed as per-axis Euler+ rotations, exactly as :func:`kornia.geometry.transform.rotate3d` does. The rotation axis+ is ``(rx, ry, rz) / ||(rx, ry, rz)||`` and the angle is ``||(rx, ry, rz)||`` degrees, so a+ sampled ``(90, 90, 0)`` turns through ``90 * sqrt(2)`` degrees about ``(1, 1, 0) / sqrt(2)``+ while a sampled ``(30, 0, 0)`` is a 30-degree turn about ``x``. One non-zero component is+ therefore the per-axis rotation it names; two or more are not, and neither Euler order+ reproduces the axis-angle result. To rotate about the axes in turn, compose the rotation+ matrix yourself and convert it with+ :func:`~kornia.geometry.conversions.rotation_matrix_to_axis_angle`, which returns radians.+ - A positive roll turns a displayed ``H x W`` slice clockwise, as+ :func:`kornia.geometry.transform.rotate3d` does; :class:`RandomAffine3D`, the 2D+ :class:`~kornia.augmentation.RandomRotation` and:func:`kornia.geometry.transform.rotate` turn it counter-clockwise(`#4408 <https://github.com/kornia/kornia/issues/4408>`_).- the default interpolation is bilinear with ``align_corners=False``.diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.pyindex ede28128e..c1e3d3131 100644--- a/kornia/augmentation/_3d/intensity/motion_blur.py+++ b/kornia/augmentation/_3d/intensity/motion_blur.py@@ -62,9 +62,12 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):Convention:See :class:`~kornia.augmentation.IntensityAugmentationBase3D` for the shared 3D intensity contract.- - ``angle`` is ordered ``(yaw, pitch, roll)`` about the ``(x, y, z)`` voxel-coordinate axes. A positive- roll turns the blur kernel clockwise as displayed, as :class:`RandomRotation3D` does and- opposite to the 2D :class:`~kornia.augmentation.RandomMotionBlur`+ - each sampled ``angle`` triple ``(yaw, pitch, roll) = (rx, ry, rz)`` is **one axis-angle vector**+ in degrees and is converted into a single Rodrigues rotation, not composed as per-axis Euler+ rotations; see :class:`RandomRotation3D` for the convention.+ - A positive roll turns the blur kernel clockwise as displayed, as+ :class:`RandomRotation3D` does and opposite to the 2D+ :class:`~kornia.augmentation.RandomMotionBlur`(`#4408 <https://github.com/kornia/kornia/issues/4408>`_). Its default resampling isnearest-neighbour, unlike the geometric 3D defaults.- an integer ``kernel_size`` is one odd scalar applied to all three spatial axes. A tuple ``kernel_size``diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.pyindex 4659779a7..8e6cb733a 100644--- a/kornia/augmentation/random_generator/_3d/affine.py+++ b/kornia/augmentation/random_generator/_3d/affine.py@@ -36,7 +36,9 @@ class AffineGenerator3D(RandomGeneratorBase):See the Convention block on :class:`~kornia.augmentation.RandomAffine3D`.Args:- degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from. The three+ slots are sampled independently and form one axis-angle vector, not per-axis Euler+ rotations; see the Convention block on :class:`~kornia.augmentation.RandomAffine3D`.If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.pyindex 32f4005a0..d3e3ba548 100644--- a/kornia/augmentation/random_generator/_3d/motion_blur.py+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py@@ -33,7 +33,9 @@ class MotionBlurGenerator3D(RandomGeneratorBase):kernel_size: motion kernel size (odd and at least 3).If int, the kernel will have a fixed size.If Tuple[int, int], it will randomly generate one value from the range for the whole batch.- angle: ``(yaw, pitch, roll)`` of the motion blur in degrees; a positive roll turns the kernel+ angle: ``(yaw, pitch, roll)`` of the motion blur in degrees, as one axis-angle vector rather+ than per-axis Euler rotations (see the Convention block on+ :class:`~kornia.augmentation.RandomMotionBlur3D`); a positive roll turns the kernelclockwise as displayed, unlike the 2D generator.If float, it will generate the value from (-angle, angle).direction: forward/backward direction of the motion blur.diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.pyindex d45367eb6..d06467bc3 100644--- a/kornia/augmentation/random_generator/_3d/rotation.py+++ b/kornia/augmentation/random_generator/_3d/rotation.py@@ -30,7 +30,10 @@ class RotationGenerator3D(RandomGeneratorBase):See the Convention block on :class:`~kornia.augmentation.RandomRotation3D`.Args:- degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.+ degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from. The three+ slots are sampled independently and form one axis-angle vector, not per-axis Euler+ rotations; see the Convention block on+ :class:`~kornia.augmentation.RandomRotation3D`.If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)diff --git a/kornia/filters/motion.py b/kornia/filters/motion.pyindex eb60fa693..eab9500ba 100644--- a/kornia/filters/motion.py+++ b/kornia/filters/motion.py@@ -119,7 +119,8 @@ class MotionBlur3D(nn.Module):Args:kernel_size: motion kernel width and height. It should be odd and positive.- angle: Rotation components in degrees. A scalar sets all three components to the same value;+ angle: Components of one Rodrigues axis-angle vector ``(rx, ry, rz)`` in degrees, not Euler angles; see+ :func:`~kornia.filters.get_motion_kernel3d`. A scalar sets all three components to the same value;a three-element sequence sets each component, and a tensor must have shape :math:`(B, 3)`.direction: forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),@@ -267,8 +268,8 @@ def motion_blur3d(Args:input: the input torch.Tensor with shape :math:`(B, C, D, H, W)`.kernel_size: motion kernel width, height and depth. It should be odd and positive.- angle: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.- If torch.Tensor, it must be :math:`(B, 3)`.+ angle: ``(yaw, pitch, roll)``, one Rodrigues axis-angle vector ``(rx, ry, rz)`` in degrees, not Euler+ angles; see :func:`~kornia.filters.get_motion_kernel3d`. If torch.Tensor, it must be :math:`(B, 3)`.direction: forward/backward direction of the motion blur.Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),while higher values towards 1.0 will point the motion blur forward. A value of 0.0 leads to adiff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex be77a554c..863c582e8 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -338,15 +338,24 @@ def rotate3d(Convention:- ``center`` is ``(x, y, z)`` in pixels, origin at the top-left of the first depthslice (``z = 0``); defaults to the tensor center+ - ``yaw``, ``pitch`` and ``roll`` are **one axis-angle vector** ``(rx, ry, rz)`` in degrees,+ not three composed per-axis Euler rotations: the three are concatenated and handed to+ :func:`~kornia.geometry.transform.get_projective_transform`, which applies Rodrigues'+ formula. The rotation axis is ``(rx, ry, rz) / ||(rx, ry, rz)||`` and the angle is+ ``||(rx, ry, rz)||`` degrees, so ``(90, 90, 0)`` turns through ``90 * sqrt(2)`` degrees+ about ``(1, 1, 0) / sqrt(2)`` while ``(30, 0, 0)`` is a 30-degree turn about ``x``. A+ single non-zero component therefore *is* the per-axis rotation it names, which is why+ one angle reads the same under either reading; two or more do not, and neither Euler+ order reproduces the axis-angle result.- align_corners: ``False`` by default (the 2D :func:`rotate` defaults to ``True``)Args:tensor: The image tensor to be warped in shapes of :math:`(B, C, D, H, W)`.- yaw: The yaw angle through which to rotate. The tensor+ yaw: The ``rx`` component of the axis-angle vector. The tensormust have a shape of (B), where B is batch size.- pitch: The pitch angle through which to rotate. The tensor+ pitch: The ``ry`` component of the axis-angle vector. The tensormust have a shape of (B), where B is batch size.- roll: The roll angle through which to rotate. The tensor+ roll: The ``rz`` component of the axis-angle vector. The tensormust have a shape of (B), where B is batch size.center: The center through which to rotate. The tensormust have a shape of (B, 3), where B is batch size and lastdiff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.pyindex c771a0b1b..9cc9514a6 100644--- a/tests/augmentation/test_conventions_3d.py+++ b/tests/augmentation/test_conventions_3d.py@@ -17,6 +17,7 @@from __future__ import annotations+import mathimport warningsimport pytest@@ -357,6 +358,63 @@ class Test3DAugmentationConventions(BaseTester):expected[(0, 0, *line)] = 1 / 3self.assert_close(output, expected, atol=1e-4, rtol=0)+ @staticmethod+ def _rodrigues(degrees: tuple[float, float, float]) -> torch.Tensor:+ """Rodrigues' rotation matrix for an axis-angle vector given in degrees.++ Written out rather than taken from kornia, so the pin below compares the implementation+ against the formula its docstrings now describe and not against itself.+ """+ vector = torch.tensor(degrees, dtype=torch.float64)+ axis = vector / vector.norm()+ angle = math.radians(float(vector.norm()))+ skew = torch.tensor(+ [[0.0, -axis[2], axis[1]], [axis[2], 0.0, -axis[0]], [-axis[1], axis[0], 0.0]], dtype=torch.float64+ )+ return torch.eye(3, dtype=torch.float64) + math.sin(angle) * skew + (1 - math.cos(angle)) * (skew @ skew)++ @pytest.mark.device_agnostic+ def test_convention_degrees_are_one_axis_angle_vector_not_euler_5286(self):+ # test_convention_degrees_and_motion_angle_follow_xyz_order and+ # test_convention_motion_blur3d_kernel_uses_the_yaw_pitch_roll_order each move ONE angle, which cannot+ # tell the axis-angle reading apart from per-axis Euler rotations: a single non-zero component behaves+ # the same under both. Two non-zero components do not, so this moves two.+ augmentation = K.RandomRotation3D(((90.0, 90.0), (90.0, 90.0), (0.0, 0.0)), p=1.0)+ augmentation(torch.zeros(1, 1, 3, 3, 3))+ rotation = augmentation.transform_matrix[0, :3, :3].to(dtype=torch.float64)++ # (90, 90, 0) is one axis-angle vector, so it turns through 90 * sqrt(2) = 127.28 degrees+ # about (1, 1, 0) / sqrt(2). Neither Euler order gives that matrix: a quarter turn about+ # x and then about y, or the reverse, differs from it by 0.80 in its largest entry.+ expected = self._rodrigues((90.0, 90.0, 0.0))+ self.assert_close(rotation, expected, atol=1e-6, rtol=0)+ quarter_x = torch.tensor([[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], dtype=torch.float64)+ quarter_y = torch.tensor([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]], dtype=torch.float64)+ for name, euler in (("x-then-y", quarter_y @ quarter_x), ("y-then-x", quarter_x @ quarter_y)):+ assert not torch.allclose(rotation, euler, atol=1e-3), name++ @pytest.mark.device_agnostic+ def test_convention_rotate3d_matches_random_rotation3d_on_a_mixed_axis_5286(self):+ # The same (90, 90, 0) triple through the geometry entry point the augmentation docstrings+ # point at: both are the single Rodrigues rotation, and both differ from either Euler+ # composition, so the two docstrings describe one convention rather than two.+ rotate3d = kornia.geometry.transform.rotate3d+ z, y, x = torch.meshgrid(*(torch.arange(9.0) - 4.0,) * 3, indexing="ij")+ volume = torch.exp(-((x + 3.0) ** 2 + y**2 + z**2) / 0.5)[None, None]++ def peak(result: torch.Tensor) -> tuple[int, int, int]:+ index = int(result[0, 0].flatten().argmax())+ return (index % 9 - 4, index // 9 % 9 - 4, index // 81 - 4) # (x, y, z)++ def rotate(yaw: float, pitch: float, roll: float, source: torch.Tensor | None = None) -> torch.Tensor:+ return rotate3d(volume if source is None else source, *[torch.tensor([v]) for v in (yaw, pitch, roll)])++ assert peak(rotate(90.0, 90.0, 0.0)) == (-1, -2, 2)+ assert peak(K.RandomRotation3D(((90.0, 90.0), (90.0, 90.0), (0.0, 0.0)), p=1.0)(volume)) == (-1, -2, 2)+ # Euler, x then y and y then x, puts the blob on the z axis or the y axis instead.+ assert peak(rotate(0.0, 90.0, 0.0, rotate(90.0, 0.0, 0.0))) == (0, 0, 3)+ assert peak(rotate(90.0, 0.0, 0.0, rotate(0.0, 90.0, 0.0))) == (0, -3, 0)+@pytest.mark.device_agnosticdef test_convention_3d_augmentations_have_no_direct_inverse(self):augmentations = (