Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): document shear conventions (#5682)

Puttala Jeevan Kumar89749574157e
diff --git a/changelog.d/5682.added.md b/changelog.d/5682.added.md
new file mode 100644
index 000000000..fd4e491cd
--- /dev/null
+++ b/changelog.d/5682.added.md
@@ -0,0 +1 @@
+The docstrings of `shear`, `Shear`, `Affine`, `get_affine_matrix2d`, `get_shear_matrix2d` and `RandomAffine` now say what their shear arguments mean: raw factors about pixel (0, 0) for `shear` and `Shear`, and angles in radians about the centre, sheared by their negative tangent, for `Affine`, the two matrix helpers and `RandomAffine` (in degrees there). That two entry points read `shear` differently is a known defect (#5661).
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 9cbcccbe7..7f539d323 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -69,6 +69,9 @@ class RandomAffine(GeometricAugmentationBase2D):
move content right and down.
- a positive ``degrees`` rotates the displayed image clockwise, unlike :class:`RandomRotation`
(:doc:`/get-started/conventions`, `#4408 <https://github.com/kornia/kornia/issues/4408>`_).
+ - ``shear`` draws degrees, converted to radians and applied about the image centre with the sign and the
+ x-then-y order of :func:`~kornia.geometry.transform.get_shear_matrix2d`, as
+ :class:`~kornia.geometry.transform.Affine` applies its ``shear``.
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index b47e1d156..c80dd7915 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -543,14 +543,18 @@ def shear(
.. image:: _static/img/shear.png
Convention:
- - ``shear`` is ``(shx, shy)``
+ - ``shear`` is a pair of raw factors ``(shx, shy)`` about pixel ``(0, 0)``:
+ ``x_out = x + shx * y``, ``y_out = y + shy * x`` (x right, y down).
+ - Known defect: :class:`Affine` reads its ``shear`` as angles in radians about the image centre and shears
+ by their negative tangent, so the same tensor shears the other way there while its values stay below
+ ``pi / 2`` in magnitude (`#5661 <https://github.com/kornia/kornia/issues/5661>`_).
- align_corners: ``False`` by default (differs from the other 2D affine warps and from
:class:`Shear`, which default to ``True``)
Args:
tensor: The image tensor to be skewed with shape of :math:`(B, C, H, W)`.
- shear: tensor containing the angle to shear
- in the x and y direction. The tensor must have a shape of
+ shear: tensor containing raw shear factors
+ in the x and y direction about pixel (0, 0). The tensor must have a shape of
(B, 2), where B is batch size, last dimension contains shx shy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
@@ -883,7 +887,12 @@ class Affine(nn.Module):
r"""Apply multiple elementary affine transforms simultaneously.
Convention:
- - See the convention block of :func:`affine`.
+ - ``shear`` contains angles in radians, using the negative-tangent, x-then-y convention
+ of :func:`get_shear_matrix2d` about ``center`` (by default ``((W - 1) / 2, (H - 1) / 2)``).
+ - Known defect: :func:`shear` and :class:`Shear` read their ``shear`` as raw factors about pixel ``(0, 0)``,
+ without the negative tangent, so the same tensor shears the other way there while its values stay below
+ ``pi / 2`` in magnitude (`#5661 <https://github.com/kornia/kornia/issues/5661>`_).
+ - ``align_corners`` defaults to ``True``. See the convention block of :func:`affine`.
Args:
angle: Angle in degrees for counter-clockwise rotation around the center. The tensor
@@ -892,7 +901,7 @@ class Affine(nn.Module):
have a shape of (B, 2), where B is the batch size and the last dimension contains dx and dy.
scale_factor: Factor for scaling. The tensor must have a shape of (B,2), where B is the
batch size and the last dimension contains scale factors for x and y direction.
- shear: Factor for shearing in x- and y-direction around the center. The
+ shear: Angles in radians for shearing in x- and y-direction around the center. The
tensor must have a shape of (B, 2), where B is the batch size and the last dimension
contains sx and sy.
center: Transformation center in pixels. The tensor must have a shape of (B, 2), where
@@ -1238,8 +1247,8 @@ class Shear(nn.Module):
- See the convention block of :func:`shear`.
Args:
- shear: tensor containing the angle to shear
- in the x and y direction. The tensor must have a shape of
+ shear: tensor containing raw shear factors
+ in the x and y direction about pixel (0, 0). The tensor must have a shape of
(B, 2), where B is batch size, last dimension contains shx shy.
mode: interpolation mode to calculate output values
``'bilinear'`` | ``'nearest'``.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index f5af23383..264ee5cd5 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -947,6 +947,8 @@ def get_affine_matrix2d(
- ``center`` is ``(x, y)`` in pixels, origin at top-left
- positive ``angle`` rotates **clockwise** as displayed β€” this function negates ``angle``
before delegating to :func:`get_rotation_matrix2d`, whose convention is CCW-positive
+ - ``sx`` and ``sy`` are angles in radians, using :func:`get_shear_matrix2d`'s
+ negative-tangent, x-then-y shear about ``center``, applied before rotation, scale and translation
- returns :math:`(B, 3, 3)` affine matrix in pixel coordinates
Args:
@@ -954,8 +956,8 @@ def get_affine_matrix2d(
center: torch.Tensor containing the center vector with shape :math:`(B, 2)`.
scale: torch.Tensor containing the scale factor with shape :math:`(B, 2)`.
angle: torch.Tensor of angles in degrees :math:`(B)`.
- sx: torch.Tensor containing the shear factor in the x-direction with shape :math:`(B)`.
- sy: torch.Tensor containing the shear factor in the y-direction with shape :math:`(B)`.
+ sx: torch.Tensor containing the shear angle in radians in the x-direction with shape :math:`(B)`.
+ sy: torch.Tensor containing the shear angle in radians in the y-direction with shape :math:`(B)`.
Returns:
the affine transformation matrix :math:`(B, 3, 3)`.
@@ -1013,14 +1015,19 @@ def get_shear_matrix2d(
a & ab + 1 \\
\end{bmatrix}
+ Here :math:`a = -\tan(sy)` and :math:`b = -\tan(sx)`.
+
Convention:
- ``center`` is ``(x, y)`` in pixels, origin at top-left
+ - ``sx`` and ``sy`` are angles in radians; about ``center = (cx, cy)``, the forward mapping is
+ ``x_out = x - tan(sx) * (y - cy)``, then ``y_out = y - tan(sy) * (x_out - cx)``.
+ Pixel x increases rightward and y downward. This differs from :func:`shear`'s raw factors.
- returns :math:`(B, 3, 3)` affine matrix in pixel coordinates
Args:
center: shearing center coordinates of (x, y).
- sx: shearing angle along x axis in radiants.
- sy: shearing angle along y axis in radiants
+ sx: shearing angle along x axis in radians.
+ sy: shearing angle along y axis in radians
Returns:
params to be passed to the affine transformation with shape :math:`(B, 3, 3)`.
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index 405972f8d..31bde55ef 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
@@ -750,19 +752,64 @@ class TestAffine2d(BaseTester):
expected = kornia.geometry.transform.scale(input, scale_factor)
self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
- @pytest.mark.skip(
- "_compute_shear_matrix and get_affine_matrix2d yield different results. "
- "See https://github.com/kornia/kornia/issues/629 for details."
- )
- def test_affine_shear(self, device, dtype):
- torch.manual_seed(0)
- shear = torch.rand(1, 2, device=device, dtype=dtype)
- input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ @pytest.mark.parametrize("as_module", [False, True])
+ def test_convention_shear_raw_factors_5661(self, device, dtype, as_module):
+ # Both off-diagonal factors act on the original coordinates, about pixel (0, 0).
+ shear = torch.tensor([[0.5, 0.25]], device=device, dtype=dtype)
+ image = torch.arange(81, device=device, dtype=dtype).reshape(1, 1, 9, 9) / 80
+ matrix = torch.tensor([[[1.0, 0.5, 0.0], [0.25, 1.0, 0.0]]], device=device, dtype=dtype)
+ expected = kornia.geometry.transform.warp_affine(image, matrix, (9, 9), align_corners=True)
+ if as_module:
+ actual = kornia.geometry.transform.Shear(shear, align_corners=True)(image)
+ else:
+ actual = kornia.geometry.transform.shear(image, shear, align_corners=True)
+ self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("custom_center", [False, True])
+ def test_convention_affine_shear_radians_5661(self, device, dtype, custom_center):
+ # tan(sx) = 1 and tan(sy) = 2: x' = x - (y - cy), then y' = y - 2 (x' - cx).
+ shear = torch.tensor([[math.pi / 4, math.atan(2.0)]], device=device, dtype=dtype)
+ center = torch.tensor([[2.0, 3.0] if custom_center else [4.0, 4.0]], device=device, dtype=dtype)
+ cx, cy = (2.0, 3.0) if custom_center else (4.0, 4.0)
+ matrix = torch.tensor(
+ [[[1.0, -1.0, cy], [-2.0, 3.0, 2.0 * (cx - cy)], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ )
+ angle = torch.zeros(1, device=device, dtype=dtype)
+ translation = torch.zeros(1, 2, device=device, dtype=dtype)
+ scale = torch.ones(1, 2, device=device, dtype=dtype)
+ # Float16 rounds the angles before tan (versus errors >= 1 for a wrong order or swapped angles).
+ tolerance = {"atol": 5e-3, "rtol": 1e-3} if dtype == torch.float16 else {}
+ self.assert_close(
+ kornia.geometry.transform.get_shear_matrix2d(center, shear[:, 0], shear[:, 1]), matrix, **tolerance
+ )
+ self.assert_close(
+ kornia.geometry.transform.get_affine_matrix2d(translation, center, scale, angle, shear[:, 0], shear[:, 1]),
+ matrix,
+ **tolerance,
+ )
+ image = torch.zeros(1, 1, 9, 9, device=device, dtype=dtype)
+ image[0, 0, 6, 5] = 1
+ expected = torch.zeros_like(image)
+ row, col = (6, 2) if custom_center else (8, 3)
+ expected[0, 0, row, col] = 1
+ # Explicit typed zero rotation avoids the separate shear-only dtype/device inference bug (#5662).
+ transform = kornia.geometry.transform.Affine(
+ angle=angle, shear=shear, center=center if custom_center else None, mode="nearest", align_corners=True
+ )
+ self.assert_close(transform(image), expected)
- transform = kornia.geometry.transform.Affine(shear=shear).to(device, dtype)
- actual = transform(input)
- expected = kornia.geometry.transform.shear(input, shear)
- self.assert_close(actual, expected, atol=1e-4, rtol=1e-4)
+ def test_wart_shear_and_affine_shear_the_other_way_5661(self, device, dtype):
+ # One pixel at row 8, column 4. shear() reads 0.5 as a factor about pixel (0, 0) and moves it to column
+ # 4 + 0.5 * 8 = 8; Affine reads it as an angle about the centre and moves it to 4 - tan(0.5) * (8 - 4) = 1.8.
+ shear = torch.tensor([[0.5, 0.0]], device=device, dtype=dtype)
+ image = torch.zeros(1, 1, 9, 9, device=device, dtype=dtype)
+ image[0, 0, 8, 4] = 1
+ sheared = kornia.geometry.transform.shear(image, shear, mode="nearest", align_corners=True)
+ # a typed zero angle, as above (#5662)
+ angle = torch.zeros(1, device=device, dtype=dtype)
+ affine = kornia.geometry.transform.Affine(angle=angle, shear=shear, mode="nearest", align_corners=True)
+ assert sheared[0, 0, 8].argmax().item() == 8
+ assert affine(image)[0, 0, 8].argmax().item() == 2
def test_affine_rotate_translate(self, device, dtype):
batch_size = 2