Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): convention blocks and pins for lines, planes and ImageRegistrator (batch 10c) (#5070)

Dmytro Mishkin191ffdc52230
diff --git a/changelog.d/5070.added.md b/changelog.d/5070.added.md
new file mode 100644
index 000000000..9e5709558
--- /dev/null
+++ b/changelog.d/5070.added.md
@@ -0,0 +1 @@
+Convention blocks for `ParametrizedLine`, `fit_line`, `Hyperplane`, `fit_plane` and `ImageRegistrator` (unnormalized line directions, the `n . x + d = 0` plane and the orientation of `through`, the built-in destination-to-source registration models in normalized coordinates), `fit_plane` and the `Hyperplane` methods on the line API page, and 13 convention and wart pins; the wart is documented and linked (#4923), not fixed.
diff --git a/docs/source/geometry.line.rst b/docs/source/geometry.line.rst
index 3e4bb7825..af901c77a 100644
--- a/docs/source/geometry.line.rst
+++ b/docs/source/geometry.line.rst
@@ -2,7 +2,7 @@ kornia.geometry.line
====================
.. meta::
- :description: The kornia.geometry.line module provides functionality for working with lines and line segments in geometric space. It includes classes such as ParametrizedLine for line representation, Hyperplane for handling high-dimensional planes, and functions like fit_line for fitting lines to data points. This module is essential for tasks like line segment matching and line fitting in computer vision and geometric analysis.
+ :description: The kornia.geometry.line module provides functionality for working with lines and line segments in geometric space. It includes classes such as ParametrizedLine for line representation, Hyperplane for planes in 3D space, and functions like fit_line and fit_plane for fitting lines and planes to data points. This module is essential for tasks like line segment matching and line fitting in computer vision and geometric analysis.
.. currentmodule:: kornia.geometry.line
@@ -10,6 +10,13 @@ kornia.geometry.line
:members:
:special-members: __init__
+``kornia.geometry.ray.Ray`` is an alias of :class:`ParametrizedLine`.
+
.. autofunction:: fit_line
+.. currentmodule:: kornia.geometry.plane
+
.. autoclass:: Hyperplane
+ :members:
+
+.. autofunction:: fit_plane
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index fa98481e7..933fbdb75 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -35,14 +35,22 @@ __all__ = ["ParametrizedLine", "fit_line"]
class ParametrizedLine(nn.Module):
- """Class that describes a parametrize line.
+ r"""Class that describes a parametrized line.
- A parametrized line is defined by an origin point :math:`o` and a unit
+ A parametrized line is defined by an origin point :math:`o` and a
direction vector :math:`d` such that the line corresponds to the set
.. math::
l(t) = o + t * d
+
+ Convention:
+ - The constructor does not normalise or check ``direction``, so :meth:`point_at` steps ``t`` in units of its
+ length. :meth:`through` and :func:`fit_line` return a unit direction; after :meth:`through`, ``t`` is the
+ Euclidean distance from ``p0``.
+ - :meth:`projection`, :meth:`squared_distance` and :meth:`distance` require a unit ``direction``.
+ - :meth:`intersect` returns ``(lambda, point)`` with ``point = point_at(lambda)``: ``lambda`` is in units of
+ the stored direction, and the plane's normal need not be unit.
"""
def __init__(self, origin: torch.Tensor, direction: torch.Tensor) -> None:
@@ -50,11 +58,11 @@ class ParametrizedLine(nn.Module):
Args:
origin: any point on the line of any dimension.
- direction: the normalized vector direction of any dimension.
+ direction: the direction vector of the line, of the same dimension.
Example:
>>> o = torch.tensor([0.0, 0.0])
- >>> d = torch.tensor([1.0, 1.0])
+ >>> d = torch.tensor([0.6, 0.8])
>>> l = ParametrizedLine(o, d)
"""
@@ -153,7 +161,7 @@ class ParametrizedLine(nn.Module):
return torch.sum(perp * perp, dim=-1)
def distance(self, point: torch.Tensor) -> torch.Tensor:
- """Return the distance of a point to its projections onto the line.
+ """Return the distance of a point to its projection onto the line.
Args:
point: the point to calculate the distance onto the line.
@@ -177,7 +185,7 @@ class ParametrizedLine(nn.Module):
Args:
plane: the plane to compute the intersection point.
- eps: epsilon for numerical stability.
+ eps: absolute threshold on ``|normal . direction|`` below which the line counts as parallel to the plane.
Return:
- the lambda value used to compute the look at point.
@@ -315,21 +323,24 @@ def _reject_degenerate_line(points: torch.Tensor, weights: Optional[torch.Tensor
def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> ParametrizedLine:
- """Fit a line from a set of points by total least squares.
+ r"""Fit a line from a set of points by total least squares.
- The line minimises the perpendicular distances to the points, for every dimensionality.
- For 2-D inputs the direction is computed in closed form and always has a non-negative
- x component, so an exactly vertical line gets the direction (0, 1); higher-dimensional
- inputs take the principal direction of the scatter matrix, whose sign is not specified.
+ Convention:
+ - Returns a :class:`ParametrizedLine` (see its conventions) through the centroid of the points, weighted
+ when ``weights`` are given, whose unit direction minimises the (weighted) sum of squared perpendicular
+ distances to the points, for every dimensionality. Each batch row is fitted on its own.
+ - For 2-D points the direction is computed in closed form and has a non-negative x component, so an exactly
+ vertical line gets the direction ``(0, 1)`` up to rounding. For :math:`D \ge 3` it is the principal
+ direction of the scatter matrix, whose sign is not specified.
Args:
points: tensor containing a batch of sets of n-dimensional points. The expected
shape of the tensor is :math:`(B, N, D)`.
- weights: weights to use to solve the equations system. The expected
+ weights: per-point weights, used in the centroid and in the fit. The expected
shape of the tensor is :math:`(B, N)`.
Return:
- A tensor containing the direction of the fitted line of shape :math:`(B, D)`.
+ The fitted line, with origin and direction of shape :math:`(B, D)`.
Raises:
ValueCheckError: if the points do not determine a line β€” fewer than two points,
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index c9ec09970..0214979d5 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -34,11 +34,25 @@ __all__ = ["Hyperplane", "fit_plane"]
class Hyperplane(nn.Module):
- """Represent a hyperplane in n-dimensional space.
+ r"""Represent a plane in 3D space by its normal :math:`n` and offset :math:`d`.
+
+ Convention:
+ - The plane is :math:`n \cdot x + d = 0`, and :meth:`signed_distance` is :math:`n \cdot x + d`: positive on
+ the side the normal points to, and ``d`` at the origin. :meth:`from_vector` sets :math:`d = -n \cdot e`.
+ :func:`~kornia.geometry.depth.depth_from_plane_equation` takes :math:`n \cdot X = d` instead: pass it
+ ``-offset``.
+ - The normal must be unit for :meth:`signed_distance`, :meth:`abs_distance` and :meth:`projection` to give
+ Euclidean distances and the closest point. :meth:`through` and :func:`fit_plane` return a unit normal; the
+ constructor and :meth:`from_vector` do not normalise it.
+ - :meth:`through` points the normal along :math:`(p_2 - p_0) \times (p_1 - p_0)`, as Eigen's
+ ``Hyperplane::Through`` does: the opposite of the right-hand normal of the loop
+ :math:`p_0 \to p_1 \to p_2`. Swapping two points flips it.
+ - Known defect: ``normal`` and ``offset`` are not registered module state, so ``state_dict()`` is empty and
+ ``.to()`` neither moves nor casts them (`#4923 <https://github.com/kornia/kornia/issues/4923>`_).
Args:
- n: The normal vector of the hyperplane.
- d: The scalar distance from the origin.
+ n: The normal vector :math:`n`, a :class:`~kornia.geometry.vector.Vector3`.
+ d: The offset :math:`d`, a :class:`~kornia.geometry.vector.Scalar`.
"""
def __init__(self, n: Vector3, d: Scalar) -> None:
@@ -251,9 +265,13 @@ def _rank_tolerance(dtype: torch.dtype) -> float:
def fit_plane(points: Vector3) -> Hyperplane:
"""Fit a plane from a set of points using SVD.
+ Convention:
+ Returns a :class:`Hyperplane` (see its conventions) through the centroid of the points, with a unit normal
+ of unspecified sign. Each batch row is fitted on its own.
+
Args:
- points: tensor containing a batch of sets of n-dimensional points. The expected
- shape of the tensor is :math:`(N, D)`.
+ points: a tensor or a :class:`~kornia.geometry.vector.Vector3` of 3D points, of shape :math:`(N, 3)` or
+ :math:`(B, N, 3)`. Another number of coordinates raises ``TypeError``.
Return:
The computed hyperplane object.
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 1a819e2da..7d24770a0 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -42,21 +42,22 @@ class BaseModel(nn.Module):
@abstractmethod
def forward(self) -> torch.Tensor:
- """Return the transform that maps source coordinates toward target coordinates.
+ """Return the transform used to warp the source image into the destination image.
+
+ The built-in models map destination coordinates to source coordinates. A custom model's coordinates must
+ match its supplied warper; see :class:`ImageRegistrator`.
Returns:
- Transform matrix tensor for the current model state. Concrete
- models return the matrix shape required by their warp function.
+ Transform tensor for the current model state, in the shape required by the warper.
"""
...
@abstractmethod
def forward_inverse(self) -> torch.Tensor:
- """Return the inverse mapping for the current registration transform.
+ """Return the transform used to warp the destination image into the source image.
Returns:
- Transform matrix tensor that maps target coordinates back toward
- source coordinates.
+ Transform tensor for the inverse warp, in the coordinates expected by the warper.
"""
...
@@ -77,7 +78,7 @@ class Homography(BaseModel):
torch.nn.init.eye_(self.model)
def forward(self) -> torch.Tensor:
- r"""Single-batch homography".
+ r"""Single-batch homography, scaled so that its ``[2, 2]`` entry is 1.
Returns:
Homography matrix with shape :math:`(1, 3, 3)`.
@@ -86,10 +87,10 @@ class Homography(BaseModel):
return torch.unsqueeze(self.model / self.model[2, 2], dim=0) # 1x3x3
def forward_inverse(self) -> torch.Tensor:
- r"""Interted Single-batch homography".
+ r"""Inverted single-batch homography.
Returns:
- Homography martix with shape :math:`(1, 3, 3)`.
+ Homography matrix with shape :math:`(1, 3, 3)`.
"""
return torch.unsqueeze(_torch_inverse_cast(self.model), dim=0)
@@ -113,8 +114,8 @@ class Similarity(BaseModel):
Args:
rotation: if True, the rotation is optimizable, else constant zero.
- scale: if True, the scale is optimizable, else constant zero.
- shift: if True, the shift is optimizable, else constant one.
+ scale: if True, the scale is optimizable, else constant one.
+ shift: if True, the shift is optimizable, else constant zero.
"""
@@ -159,7 +160,7 @@ class Similarity(BaseModel):
self.width = width
def forward(self) -> torch.Tensor:
- r"""Single-batch similarity transform".
+ r"""Single-batch similarity transform.
Returns:
Similarity with shape :math:`(1, 3, 3)`
@@ -174,7 +175,7 @@ class Similarity(BaseModel):
return convert_affinematrix_to_homography(torch.cat([rot, self.shift], dim=2))
def forward_inverse(self) -> torch.Tensor:
- r"""Single-batch inverse similarity transform".
+ r"""Single-batch inverse similarity transform.
Returns:
Similarity with shape :math:`(1, 3, 3)`
@@ -186,15 +187,35 @@ class Similarity(BaseModel):
class ImageRegistrator(nn.Module):
r"""nn.Module, which performs optimization-based image registration.
+ Convention:
+ - :meth:`register` returns ``self.model()`` unchanged. For the built-in string ``model_type`` values, this
+ maps **destination** coordinates to **source** coordinates, normalized to :math:`[-1, 1]` with
+ ``align_corners=False``: the ``src_homo_dst`` argument of
+ :func:`~kornia.geometry.transform.homography_warp`. :meth:`warp_src_into_dst` uses this model, and
+ :meth:`warp_dst_into_src` uses ``self.model.forward_inverse()``. A custom ``model_type`` and ``warper``
+ determine their own coordinate system; their forward and inverse mappings must agree with that warper.
+ - For the built-in models, ``denormalize_homography(M, (H, W), (H, W), align_corners=False)`` converts the
+ returned ``M`` to pixels: content that moves by :math:`(t_x, t_y)` pixels from ``src_img`` to ``dst_img``
+ gives a shift of :math:`(-t_x, -t_y)`.
+ - :meth:`register` always starts from the identity, so a loaded ``state_dict`` drives the warps but is not a
+ warm start.
+
Args:
- model_type: Geometrical model for registration. Can be string or nn.Module.
+ model_type: Geometrical model for registration: ``'homography'``, ``'similarity'``, or ``'translation'``,
+ ``'rotation'`` or ``'scale'`` (a :class:`Similarity` that optimizes only that parameter), or a
+ :class:`BaseModel` instance together with ``warper``.
optimizer: optimizer class used for the optimization.
- loss_fn: torch loss function.
+ loss_fn: torch loss function, called with ``reduction='none'``.
pyramid_levels: number of scale pyramid levels.
lr: learning rate for optimization.
- num_iterations: maximum number of iterations.
- tolerance: stop optimizing if loss difference is less. default 1e-4.
- warper: if model_type is not string, one needs to provide warper object.
+ num_iterations: maximum number of iterations at each pyramid level, from coarse to fine.
+ tolerance: stop a pyramid level when successive losses at that level differ by less than this value.
+ The first iteration at each level always runs. Default 1e-4.
+ warper: the warper class, called as ``warper(height, width)``. Required when ``model_type`` is a module;
+ a string ``model_type`` uses :class:`~kornia.geometry.transform.HomographyWarper`.
+ allow_shape_mismatch: if True, :meth:`register` resizes ``src_img`` bilinearly to the height and width of
+ ``dst_img``, and a different batch or channel size still raises ``ValueError``; if False, images of
+ different shapes raise ``ValueError``.
Example:
>>> from kornia.geometry import ImageRegistrator
@@ -283,8 +304,6 @@ class ImageRegistrator(nn.Module):
) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
r"""Estimate the transformation which warps src_img into dst_img by gradient descent.
- The shape of the tensors is not checked, because it may depend on the model, e.g. volume registration.
-
Args:
src_img: Input image torch.Tensor.
dst_img: Input image torch.Tensor.
diff --git a/tests/geometry/test_line.py b/tests/geometry/test_line.py
index 072f13119..4b5ad5e3b 100644
--- a/tests/geometry/test_line.py
+++ b/tests/geometry/test_line.py
@@ -744,3 +744,79 @@ class TestFitLine(BaseTester):
@pytest.mark.skip(reason="not implemented yet")
def test_module(self, device, dtype):
pass
+
+
+class TestConventionsParametrizedLine(BaseTester):
+ def test_convention_parametrized_line_direction_is_not_normalized(self, device, dtype):
+ # The constructor does not normalise the direction, so point_at(t) = origin + t * direction steps in units of
+ # ||direction||. through(p0, p1) normalises p1 - p0, so there t is the Euclidean distance from p0. The
+ # distance methods assume a unit direction, which the constructor does not enforce.
+ origin = torch.tensor([1.0, 2.0], device=device, dtype=dtype)
+ direction = torch.tensor([3.0, 4.0], device=device, dtype=dtype)
+ assert torch.linalg.vector_norm(direction).item() == 5.0 # not a unit direction
+
+ line = ParametrizedLine(origin, direction)
+ self.assert_close(line.direction, direction)
+ self.assert_close(line.point_at(1.0), torch.tensor([4.0, 6.0], device=device, dtype=dtype))
+
+ through = ParametrizedLine.through(origin, origin + direction)
+ self.assert_close(through.origin, origin)
+ self.assert_close(through.direction, torch.tensor([0.6, 0.8], device=device, dtype=dtype))
+ self.assert_close(through.point_at(5.0), torch.tensor([4.0, 6.0], device=device, dtype=dtype))
+
+ def test_convention_parametrized_line_intersect_lambda_units(self, device, dtype):
+ # intersect returns (lambda, point) with point = point_at(lambda), so lambda is in units of the stored
+ # direction: a unit direction gives the Euclidean distance from the origin, a non-unit direction a different
+ # lambda for the same point, and the reversed direction a negative one. A non-unit normal gives the same
+ # lambda. lambda = -(offset + n . origin) / (n . direction).
+ normal = torch.tensor([1.0, 2.0, 2.0], device=device, dtype=dtype) / 3
+ assert (normal.abs() >= 0.1).all() # a tilted plane: no normal component near 0
+ plane = Hyperplane.from_vector(Vector3(normal), Vector3(torch.ones(3, device=device, dtype=dtype)))
+ origin = torch.tensor([0.5, -1.0, 2.0], device=device, dtype=dtype)
+ direction = torch.tensor([2.0, 1.0, -0.5], device=device, dtype=dtype)
+ # origin + 5/6 * direction lies on the plane; ||direction|| = sqrt(5.25).
+ expected_point = torch.tensor([13 / 6, -1 / 6, 19 / 12], device=device, dtype=dtype)
+
+ lmbda, point = ParametrizedLine(origin, direction / torch.linalg.vector_norm(direction)).intersect(plane)
+ self.assert_close(lmbda, torch.tensor(5.25**0.5 * 5 / 6, device=device, dtype=dtype)) # 1.9094
+ self.assert_close(point, expected_point)
+ self.assert_close(plane.signed_distance(point).data, torch.zeros((), device=device, dtype=dtype))
+
+ lmbda, point = ParametrizedLine(origin, direction).intersect(plane)
+ self.assert_close(lmbda, torch.tensor(5 / 6, device=device, dtype=dtype)) # 0.8333
+ self.assert_close(point, expected_point)
+
+ lmbda, point = ParametrizedLine(origin, -direction).intersect(plane)
+ self.assert_close(lmbda, torch.tensor(-5 / 6, device=device, dtype=dtype))
+ self.assert_close(point, expected_point)
+
+ nonunit_plane = Hyperplane.from_vector(Vector3(3 * normal), Vector3(torch.ones(3, device=device, dtype=dtype)))
+ lmbda, point = ParametrizedLine(origin, direction).intersect(nonunit_plane)
+ self.assert_close(lmbda, torch.tensor(5 / 6, device=device, dtype=dtype))
+ self.assert_close(point, expected_point)
+
+
+class TestConventionsFitLine(BaseTester):
+ @pytest.mark.parametrize("dim", [2, 3])
+ @pytest.mark.parametrize("weighted", [False, True])
+ def test_convention_fit_line_centroid_and_unit_direction(self, device, dtype, dim, weighted):
+ # fit_line returns, for each batch row on its own, a line through the centroid of that row's points (the
+ # weighted centroid sum(w p) / sum(w) with weights) and a unit direction, for D = 2 and D >= 3 alike. The
+ # weights are uneven, so the two centroids differ, and the points are off any single line. Each row's direction
+ # is compared with the fit of that row alone, up to sign (the D >= 3 sign is unspecified).
+ points = torch.tensor(
+ [[0.0, 0.0, 0.3], [1.0, 0.4, -0.2], [2.5, 0.9, 0.1], [3.0, 1.6, 0.4], [4.2, 1.7, -0.3]],
+ device=device,
+ dtype=dtype,
+ )[:, :dim]
+ rows = torch.stack([points, 2.0 * points.flip(-1) + 1.0]) # the second row: another line elsewhere
+ w = torch.tensor([[3.0, 0.5, 1.0, 0.25, 2.0], [0.5, 2.0, 1.0, 4.0, 0.25]], device=device, dtype=dtype)
+
+ line = fit_line(rows, w if weighted else None)
+ for i in range(2):
+ centroid = (w[i, :, None] * rows[i]).sum(0) / w[i].sum() if weighted else rows[i].mean(0)
+ self.assert_close(line.origin[i], centroid)
+ one = torch.ones((), device=device, dtype=dtype)
+ self.assert_close(torch.linalg.vector_norm(line.direction[i]), one)
+ single = fit_line(rows[i : i + 1], w[i : i + 1] if weighted else None).direction[0]
+ self.assert_close(line.direction[i], torch.sign((line.direction[i] * single).sum()) * single)
diff --git a/tests/geometry/test_plane.py b/tests/geometry/test_plane.py
index 3b61cef4f..0d3197f2c 100644
--- a/tests/geometry/test_plane.py
+++ b/tests/geometry/test_plane.py
@@ -437,3 +437,121 @@ class TestHyperplane(BaseTester):
finally:
if checks_were_enabled:
enable_checks()
+
+
+class TestConventionsHyperplane(BaseTester):
+ def test_convention_hyperplane_offset_sign(self, device, dtype):
+ # The plane is n . x + d = 0: from_vector(n, e) sets d = -n . e, and signed_distance(x) = n . x + d is positive
+ # on the side the normal points to, negative on the other side, and equals d at the origin. With a unit
+ # normal it is the Euclidean distance. Neither the constructor nor from_vector normalises the normal, so a
+ # normal of length 3 triples the offset and signed_distance.
+ normal = torch.tensor([2.0, 1.0, -2.0], device=device, dtype=dtype) / 3
+ assert (normal.abs() >= 0.1).all() # a tilted plane: no normal component near 0
+ e = torch.tensor([1.0, 2.0, 0.5], device=device, dtype=dtype)
+ plane = Hyperplane.from_vector(Vector3(normal), Vector3(e))
+
+ self.assert_close(plane.offset.data, torch.tensor(-1.0, device=device, dtype=dtype)) # -n . e
+ self.assert_close(plane.signed_distance(e).data, torch.tensor(0.0, device=device, dtype=dtype))
+ self.assert_close(plane.signed_distance(e + 0.7 * normal).data, torch.tensor(0.7, device=device, dtype=dtype))
+ self.assert_close(plane.signed_distance(e - 0.4 * normal).data, torch.tensor(-0.4, device=device, dtype=dtype))
+ self.assert_close(plane.abs_distance(e - 0.4 * normal).data, torch.tensor(0.4, device=device, dtype=dtype))
+ self.assert_close(plane.signed_distance(torch.zeros(3, device=device, dtype=dtype)).data, plane.offset.data)
+
+ scaled = Hyperplane.from_vector(Vector3(3 * normal), Vector3(e))
+ built = Hyperplane(Vector3(3 * normal), scaled.offset)
+ for p in (scaled, built):
+ self.assert_close(p.normal.data, 3 * normal)
+ self.assert_close(p.offset.data, torch.tensor(-3.0, device=device, dtype=dtype))
+ self.assert_close(p.signed_distance(e + 0.7 * normal).data, torch.tensor(2.1, device=device, dtype=dtype))
+
+ def test_convention_hyperplane_through_normal_orientation(self, device, dtype):
+ # through(p0, p1, p2) takes its normal along c = (p2 - p0) x (p1 - p0), Eigen's order: the opposite of the
+ # right-hand normal of the loop p0 -> p1 -> p2. Swapping two points flips the normal and a cyclic shift keeps
+ # it. Only the direction is compared; the length of the returned normal is not part of this convention.
+ p0 = torch.tensor([1.0, 0.0, 0.2], device=device, dtype=dtype)
+ p1 = torch.tensor([0.1, 1.2, 0.0], device=device, dtype=dtype)
+ p2 = torch.tensor([0.3, 0.0, 1.5], device=device, dtype=dtype)
+ c = torch.tensor([-1.56, -1.31, -0.84], device=device, dtype=dtype) # (p2 - p0) x (p1 - p0)
+ assert (c.abs() >= 0.1).all() # a tilted plane: no normal component near 0
+ c = c / torch.linalg.vector_norm(c)
+
+ def unit_normal(plane: Hyperplane) -> torch.Tensor:
+ normal = plane.normal.data
+ return normal / torch.linalg.vector_norm(normal, dim=-1, keepdim=True)
+
+ one = torch.tensor(1.0, device=device, dtype=dtype)
+ plane = Hyperplane.through(p0, p1, p2)
+ self.assert_close((unit_normal(plane) * c).sum(-1), one)
+ self.assert_close((unit_normal(Hyperplane.through(p0, p2, p1)) * c).sum(-1), -one)
+ self.assert_close((unit_normal(Hyperplane.through(p1, p2, p0)) * c).sum(-1), one)
+ # The plane passes through the three points: d = -n . p0 for the returned normal.
+ for p in (p0, p1, p2):
+ self.assert_close(
+ plane.signed_distance(p).data / torch.linalg.vector_norm(plane.normal.data), torch.zeros_like(one)
+ )
+
+ def test_wart_hyperplane_state_not_registered_4923(self, device, dtype):
+ # Hyperplane keeps its normal and offset as Vector3 / Scalar wrappers outside the module state (#4923), so
+ # state_dict() is empty and .to() leaves both in the original dtype. Registering them, as ParametrizedLine
+ # does, flips both assertions.
+ normal = torch.tensor([2.0, 1.0, -2.0], device=device, dtype=dtype) / 3
+ e = torch.tensor([1.0, 2.0, 0.5], device=device, dtype=dtype)
+ plane = Hyperplane.from_vector(Vector3(normal), Vector3(e))
+ assert list(plane.state_dict()) == []
+
+ other = torch.float16 if dtype == torch.float32 else torch.float32 # float64 is unavailable on MPS
+ moved = plane.to(other)
+ assert moved.normal.data.dtype == dtype
+ assert moved.offset.data.dtype == dtype
+
+
+class TestConventionsFitPlane(BaseTester):
+ def test_convention_fit_plane_input_forms(self, device, dtype):
+ # fit_plane takes a tensor or a Vector3 of shape (N, 3), or a batch (B, N, 3) that it fits row by row. The
+ # normal is unit, its sign is the SVD's and unspecified, so normals are compared up to sign (and the offset
+ # with them); the plane passes through the centroid. Other coordinate counts raise TypeError.
+ true_normal = torch.tensor([0.36, -0.48, 0.8], device=device, dtype=dtype)
+ assert (true_normal.abs() >= 0.1).all() # a tilted plane: no normal component near 0
+ # Six points near the plane through (1, -2, 0.5) with this normal (offsets up to 0.02 along it).
+ points = torch.tensor(
+ [
+ [1.0036, -2.0048, 0.5080],
+ [0.7129, -0.3310, 1.6056],
+ [-0.3940, -3.1425, 0.4606],
+ [3.0525, -0.9923, 0.1810],
+ [-0.0298, 0.4593, 2.4265],
+ [1.8415, -2.1787, 0.0204],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ # A second plane for the batch: the same points with their coordinates permuted, normal (-0.48, 0.8, 0.36).
+ permuted = points[:, [1, 2, 0]]
+
+ def assert_same_plane(normal: torch.Tensor, offset: torch.Tensor, other: Hyperplane) -> None:
+ sign = torch.sign((normal * other.normal.data).sum(-1))
+ self.assert_close(normal, sign * other.normal.data)
+ self.assert_close(offset, sign * other.offset.data)
+
+ plane = fit_plane(points)
+ assert plane.normal.shape == (3,)
+ assert plane.offset.shape == ()
+ self.assert_close(torch.linalg.vector_norm(plane.normal.data), torch.tensor(1.0, device=device, dtype=dtype))
+ assert (plane.normal.data * true_normal).sum().abs().item() > 0.999
+ centroid = points.mean(0)
+ self.assert_close(plane.signed_distance(centroid).data, torch.tensor(0.0, device=device, dtype=dtype))
+
+ from_vector3 = fit_plane(Vector3(points))
+ assert_same_plane(from_vector3.normal.data, from_vector3.offset.data, plane)
+
+ batch = fit_plane(torch.stack([points, permuted]))
+ assert batch.normal.shape == (2, 3)
+ assert batch.offset.shape == (2,)
+ rows = [plane, fit_plane(permuted)]
+ assert (rows[0].normal.data * rows[1].normal.data).sum().abs().item() < 0.5 # the two rows differ
+ for i, row in enumerate(rows):
+ assert_same_plane(batch.normal.data[i], batch.offset.data[i], row)
+
+ for wrong in (points[:, :2], torch.cat([points, points[:, :1]], -1)):
+ with pytest.raises(TypeError, match=r"vector must be \(\*, 3\)"):
+ fit_plane(wrong)
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index adb0fa5d4..5a88c2267 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -26,7 +26,7 @@ import kornia
from kornia.core._compat import torch_version
from kornia.geometry import transform_points
from kornia.geometry.conversions import angle_to_rotation_matrix, denormalize_homography, normalize_homography
-from kornia.geometry.transform import ImageRegistrator
+from kornia.geometry.transform import Homography, ImageRegistrator, Similarity, homography_warp
from testing.base import BaseTester, supports_bilinear_2d_grid_sample_backward, supports_reflect_padding
from testing.casts import dict_to
@@ -284,3 +284,126 @@ class TestImageRegistrator(BaseTester):
ir = ImageRegistrator("rotation", lr=0.1, num_iterations=60, pyramid_levels=1, tolerance=0.0).to(device, dtype)
ir.register(scene(0.0), scene(6.0))
assert abs(ir.model.rot.item() + 6.0) < 0.4
+
+
+class TestConventionsImageRegistrator(BaseTester):
+ height, width = 32, 48
+
+ def _scene(self, dx: float, dy: float, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ # Four Gaussian blobs, moved by (dx, dy) pixels. Analytic, so the fixture needs no seed; register() draws no
+ # random numbers either, so every run is deterministic.
+ ys, xs = torch.meshgrid(
+ torch.arange(self.height, device=device, dtype=dtype),
+ torch.arange(self.width, device=device, dtype=dtype),
+ indexing="ij",
+ )
+ blobs = [(12.0, 9.0, 4.0, 1.0), (30.0, 20.0, 6.0, 0.8), (38.0, 7.0, 3.0, 0.6), (20.0, 24.0, 3.5, 0.9)]
+ img = torch.zeros(self.height, self.width, device=device, dtype=dtype)
+ for cx, cy, sigma, amplitude in blobs:
+ img = img + amplitude * torch.exp(-((xs - dx - cx) ** 2 + (ys - dy - cy) ** 2) / (2 * sigma**2))
+ return img[None, None]
+
+ @staticmethod
+ def _skip_without_kernels(device: torch.device, dtype: torch.dtype) -> None:
+ # Registration differentiates through a bilinear grid_sample and builds its pyramid with reflection padding.
+ # torch 2.5.1 has neither kernel for float16 on CPU, nor the grid_sample one for bfloat16.
+ if not supports_bilinear_2d_grid_sample_backward(device, dtype):
+ pytest.skip(f"torch has no {dtype} bilinear grid_sample kernel with backward on {device.type}")
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip(f"torch has no {dtype} reflection padding kernel on {device.type}")
+
+ def _register(
+ self, device: torch.device, dtype: torch.dtype, num_iterations: int, pyramid_levels: int
+ ) -> tuple[ImageRegistrator, torch.Tensor, torch.Tensor, torch.Tensor]:
+ src = self._scene(0.0, 0.0, device, dtype)
+ dst = self._scene(3.0, -1.5, device, dtype) # the content moves by (+3, -1.5) px from src to dst
+ ir = ImageRegistrator(
+ "translation", lr=1e-2, num_iterations=num_iterations, pyramid_levels=pyramid_levels, tolerance=1e-9
+ ).to(device, dtype)
+ model = ir.register(src, dst).detach()
+ return ir, model, src, dst
+
+ def test_convention_image_registrator_model_maps_dst_to_src(self, device, dtype):
+ # register(src, dst) returns the (1, 3, 3) model that maps destination coordinates to source coordinates
+ # (homography_warp's src_homo_dst: a pull warp), in normalised [-1, 1] coordinates with align_corners=False.
+ # Content moved by (+3, -1.5) px from src to dst gives a model shift of (-3, +1.5) px; the inverse model would
+ # give (+3, -1.5).
+ self._skip_without_kernels(device, dtype)
+ _, model, _, _ = self._register(device, dtype, num_iterations=60, pyramid_levels=2)
+ size = (self.height, self.width)
+ shift = denormalize_homography(model.float(), size, size, align_corners=False)[0, :2, 2]
+ # Measured about (-3.0, 1.5); the 0.5 px margins absorb the half-precision error.
+ assert -3.5 < shift[0].item() < -2.5
+ assert 1.0 < shift[1].item() < 2.0
+
+ def test_convention_image_registrator_warp_matches_homography_warp(self, device, dtype):
+ # warp_src_into_dst(src) is homography_warp(src, model, (H, W), align_corners=False): the default
+ # HomographyWarper reads the model in normalised coordinates with align_corners=False.
+ self._skip_without_kernels(device, dtype)
+ ir, model, src, _ = self._register(device, dtype, num_iterations=20, pyramid_levels=1)
+ assert (model[0, :2, 2].abs() > 0.05).all() # a model far from the identity
+ size = (self.height, self.width)
+ warped = ir.warp_src_into_dst(src).detach()
+ self.assert_close(warped, homography_warp(src, model, size, align_corners=False))
+ # The other align_corners convention samples elsewhere under this model (0.015 in float32).
+ assert (warped - homography_warp(src, model, size, align_corners=True)).abs().max().item() > 5e-3
+
+ def test_convention_image_registrator_register_resets_model(self, device, dtype):
+ # A loaded state_dict drives the warps, but register() always starts again from the identity: the loaded
+ # state is not a warm start, so a register() without iterations returns the identity.
+ self._skip_without_kernels(device, dtype)
+ ir, model, src, dst = self._register(device, dtype, num_iterations=20, pyramid_levels=1)
+ assert (model[0, :2, 2].abs() > 0.05).all() # a model far from the identity
+ loaded = ImageRegistrator("translation", num_iterations=0).to(device, dtype)
+ loaded.load_state_dict(ir.state_dict())
+ self.assert_close(loaded.model().detach(), model)
+ self.assert_close(loaded.warp_src_into_dst(src).detach(), ir.warp_src_into_dst(src).detach())
+ identity = torch.eye(3, device=device, dtype=dtype)[None]
+ self.assert_close(loaded.register(src, dst).detach(), identity)
+
+ def test_convention_similarity_rotation_in_degrees(self, device, dtype):
+ # Without an image shape, Similarity.forward() is [[scale * R(rot), shift], [0, 0, 1]], with
+ # R = [[cos, sin], [-sin, cos]] from angle_to_rotation_matrix: rot is in degrees.
+ sim = Similarity().to(device, dtype)
+ with torch.no_grad():
+ sim.rot.fill_(30.0)
+ sim.scale.fill_(1.5)
+ sim.shift.copy_(torch.tensor([[[0.2], [-0.1]]], device=device, dtype=dtype))
+ c, s = 1.5 * math.cos(math.radians(30.0)), 1.5 * math.sin(math.radians(30.0)) # 1.299, 0.75
+ expected = torch.tensor([[[c, s, 0.2], [-s, c, -0.1], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(sim().detach(), expected)
+
+ @pytest.mark.parametrize(
+ ("model_type", "optimized"),
+ [
+ ("homography", ["model"]),
+ ("similarity", ["rot", "scale", "shift"]),
+ ("translation", ["shift"]),
+ ("rotation", ["rot"]),
+ ("scale", ["scale"]),
+ ],
+ )
+ def test_convention_image_registrator_model_type_parameters(self, model_type, optimized):
+ # 'homography' optimizes a Homography; the other strings a Similarity that optimizes only the named parameters.
+ ir = ImageRegistrator(model_type)
+ assert isinstance(ir.model, Homography if model_type == "homography" else Similarity)
+ assert sorted(name for name, _ in ir.model.named_parameters()) == optimized
+
+ def test_convention_image_registrator_shape_mismatch_resizes_src(self, device, dtype):
+ # allow_shape_mismatch=True resizes src_img to the height and width of dst_img before the loss, and a
+ # different channel count still raises.
+ self._skip_without_kernels(device, dtype)
+ seen = []
+
+ def l1(a: torch.Tensor, b: torch.Tensor, reduction: str = "none") -> torch.Tensor:
+ seen.append((tuple(a.shape), tuple(b.shape)))
+ return torch.nn.functional.l1_loss(a, b, reduction=reduction)
+
+ ir = ImageRegistrator(
+ "translation", num_iterations=1, pyramid_levels=1, loss_fn=l1, allow_shape_mismatch=True
+ ).to(device, dtype)
+ dst = self._scene(0.0, 0.0, device, dtype)
+ ir.register(dst[..., ::2, ::2], dst)
+ assert set(seen) == {((1, 1, self.height, self.width), (1, 1, self.height, self.width))}
+ with pytest.raises(ValueError):
+ ir.register(dst.expand(1, 3, -1, -1), dst)