Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): add detailed missing public docstrings (#3731)

Jeevang1-epiced3d0a75b865
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 6e2deb976..b9bd40f68 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -247,6 +247,15 @@ class Boxes:
@property
def shape(self) -> tuple[int, ...] | Size:
+ """Return the tensor shape used to store the boxes.
+
+ Returns:
+ Shape of :attr:`data`. For unbatched boxes this is usually
+ :math:`(N, 4, 2)`, where :math:`N` is the number of boxes, ``4``
+ is the number of corner vertices, and ``2`` stores ``(x, y)``.
+ For batched boxes the shape is usually :math:`(B, N, 4, 2)`, where
+ :math:`B` is the batch size.
+ """
return self.data.shape
def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor]:
@@ -293,6 +302,25 @@ class Boxes:
values: torch.Tensor | Boxes,
inplace: bool = False,
) -> Boxes:
+ """Write box coordinates at selected tensor indices.
+
+ This mirrors :meth:`torch.Tensor.index_put_` for the internal
+ quadrilateral tensor. It is useful when a subset of boxes in a batch
+ must be replaced while keeping the :class:`Boxes` wrapper and metadata.
+
+ Args:
+ indices: Index tuple or list accepted by ``Tensor.index_put_``.
+ The indices address entries in the stored tensor, commonly
+ shaped :math:`(B, N, 4, 2)` or :math:`(N, 4, 2)`.
+ values: Replacement coordinates. If a :class:`Boxes` object is
+ passed, its :attr:`data` tensor is used.
+ inplace: If ``True``, update this object and return ``self``. If
+ ``False``, clone the current data first and return a new
+ :class:`Boxes` instance.
+
+ Returns:
+ :class:`Boxes` containing the updated coordinates.
+ """
if inplace:
_data = self._data
else:
@@ -342,6 +370,25 @@ class Boxes:
botright: Optional[torch.Tensor | tuple[int, int]] = None,
inplace: bool = False,
) -> Boxes:
+ """Clamp every box vertex inside per-image coordinate limits.
+
+ Coordinates below ``topleft`` are raised to the lower bound and
+ coordinates above ``botright`` are lowered to the upper bound. The
+ implementation expects tensor bounds with one ``(x, y)`` pair per batch
+ element.
+
+ Args:
+ topleft: Tensor of shape :math:`(B, 2)` containing the minimum
+ ``x`` and ``y`` coordinate allowed for each batch item.
+ botright: Tensor of shape :math:`(B, 2)` containing the maximum
+ ``x`` and ``y`` coordinate allowed for each batch item.
+ inplace: If ``True``, clamp this object in place. Otherwise, return
+ a new :class:`Boxes` object with clamped data.
+
+ Returns:
+ :class:`Boxes` whose vertex coordinates are restricted to the
+ provided bounds.
+ """
if not (isinstance(topleft, torch.Tensor) and isinstance(botright, torch.Tensor)):
raise NotImplementedError
if inplace:
@@ -399,6 +446,25 @@ class Boxes:
def filter_boxes_by_area(
self, min_area: Optional[float] = None, max_area: Optional[float] = None, inplace: bool = False
) -> Boxes:
+ """Remove boxes whose polygon area is outside the requested range.
+
+ The box area is computed from its four vertices. Boxes smaller than
+ ``min_area`` or larger than ``max_area`` are not dropped from the
+ tensor; their coordinates are replaced with zeros so the original batch
+ and box dimensions stay unchanged.
+
+ Args:
+ min_area: Optional lower inclusive area threshold. Boxes with area
+ below this value are zeroed.
+ max_area: Optional upper inclusive area threshold. Boxes with area
+ above this value are zeroed.
+ inplace: If ``True``, update this object in place. Otherwise,
+ return a filtered clone.
+
+ Returns:
+ :class:`Boxes` with the same shape as the input container and
+ out-of-range boxes replaced by zero coordinates.
+ """
area = self.compute_area()
if inplace:
_data = self._data
@@ -704,10 +770,25 @@ class Boxes:
@property
def data(self) -> torch.Tensor:
+ """Return the raw quadrilateral coordinate tensor.
+
+ Returns:
+ Tensor storing four vertices per box in ``(x, y)`` order. The
+ common shapes are :math:`(N, 4, 2)` for unbatched boxes and
+ :math:`(B, N, 4, 2)` for batched boxes, where :math:`B` is batch
+ size and :math:`N` is the number of boxes.
+ """
return self._data
@property
def mode(self) -> str:
+ """Return the box format remembered by this container.
+
+ Returns:
+ Mode string used as the default by :meth:`to_tensor`, such as
+ ``"xyxy"``, ``"xywh"``, ``"vertices"``, or their ``"_plus"``
+ variants.
+ """
return self._mode
@property
@@ -729,6 +810,13 @@ class Boxes:
return self
def clone(self) -> Boxes:
+ """Create an independent copy of the box container.
+
+ Returns:
+ New :class:`Boxes` object with cloned tensor storage. Metadata such
+ as the current mode, original list lengths, and batched flag is
+ preserved.
+ """
obj = type(self)(self._data.clone(), False)
obj._mode = self._mode
obj._N = self._N
@@ -736,6 +824,14 @@ class Boxes:
return obj
def type(self, dtype: torch.dtype) -> Boxes:
+ """Cast the stored box coordinates to a new dtype.
+
+ Args:
+ dtype: Target floating-point dtype for the coordinate tensor.
+
+ Returns:
+ ``self`` after converting :attr:`data` in place.
+ """
self._data = self._data.type(dtype)
return self
@@ -828,6 +924,14 @@ class Boxes3D:
@property
def shape(self) -> tuple[int, ...] | Size:
+ """Return the tensor shape used to store 3D boxes.
+
+ Returns:
+ Shape of :attr:`data`. For unbatched boxes this is usually
+ :math:`(N, 8, 3)`, where :math:`N` is the number of boxes, ``8`` is
+ the number of cuboid corners, and ``3`` stores ``(x, y, z)``. For
+ batched boxes the shape is usually :math:`(B, N, 8, 3)`.
+ """
return self.data.shape
def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
@@ -1119,10 +1223,22 @@ class Boxes3D:
@property
def data(self) -> torch.Tensor:
+ """Return the raw 3D corner-coordinate tensor.
+
+ Returns:
+ Tensor containing eight 3D corner coordinates per box, usually
+ shaped :math:`(N, 8, 3)` or :math:`(B, N, 8, 3)`.
+ """
return self._data
@property
def mode(self) -> str:
+ """Return the 3D box format remembered by this container.
+
+ Returns:
+ Mode string describing how this container should be interpreted
+ during tensor conversion.
+ """
return self._mode
@property
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index fca915469..09230b8c8 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -390,6 +390,30 @@ class PinholeCamera:
device: Union[str, torch.device, None],
dtype: torch.dtype,
) -> "PinholeCamera":
+ r"""Construct a batched pinhole camera from scalar parameter tensors.
+
+ This helper allocates batched :math:`4 \times 4` intrinsic and
+ extrinsic matrices, fills focal lengths/principal point/translation,
+ and wraps them into a :class:`PinholeCamera` instance.
+
+ Args:
+ fx: Horizontal focal length per batch element.
+ fy: Vertical focal length per batch element.
+ cx: Principal point x-coordinate per batch element.
+ cy: Principal point y-coordinate per batch element.
+ height: Image height in pixels.
+ width: Image width in pixels.
+ tx: Camera translation along x per batch element.
+ ty: Camera translation along y per batch element.
+ tz: Camera translation along z per batch element.
+ batch_size: Number of cameras in the batch.
+ device: Target device for the created tensors.
+ dtype: Target floating-point dtype for the created tensors.
+
+ Returns:
+ Batched :class:`PinholeCamera` configured from the provided
+ intrinsic and translation parameters.
+ """
# create the camera matrix
intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
intrinsics[..., 0, 0] += fx
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index 0875b8f92..8b69519c7 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -77,10 +77,24 @@ class Keypoints:
@property
def shape(self) -> Union[Tuple[int, ...], Size]:
+ """Return the tensor shape used to store 2D keypoints.
+
+ Returns:
+ Shape of :attr:`data`. The common layouts are :math:`(N, 2)` for
+ unbatched keypoints and :math:`(B, N, 2)` for batched keypoints,
+ where :math:`B` is the batch size, :math:`N` is the number of
+ keypoints, and the final dimension stores ``(x, y)`` coordinates.
+ """
return self.data.shape
@property
def data(self) -> torch.torch.Tensor:
+ """Return the raw 2D keypoint coordinate tensor.
+
+ Returns:
+ Tensor storing keypoint coordinates in ``(..., 2)`` format, where
+ the last dimension contains ``x`` and ``y``.
+ """
return self._data
@property
@@ -99,6 +113,19 @@ class Keypoints:
values: Union[torch.torch.Tensor, "Keypoints"],
inplace: bool = False,
) -> "Keypoints":
+ """Write keypoint coordinates at selected tensor indices.
+
+ Args:
+ indices: Index tuple or list accepted by ``Tensor.index_put_`` for
+ the stored coordinate tensor.
+ values: Replacement coordinates, either as a raw tensor or another
+ :class:`Keypoints` object.
+ inplace: If ``True``, update this object in place. Otherwise,
+ clone the coordinates first and return a new wrapper.
+
+ Returns:
+ :class:`Keypoints` object containing the updated coordinates.
+ """
if inplace:
_data = self._data
else:
@@ -169,6 +196,15 @@ class Keypoints:
@classmethod
def from_tensor(cls, keypoints: torch.torch.Tensor) -> "Keypoints":
+ """Validate and wrap a tensor of 2D keypoint coordinates.
+
+ Args:
+ keypoints: Tensor in :math:`(N, 2)` or :math:`(B, N, 2)` format.
+ The last dimension stores ``(x, y)`` coordinates.
+
+ Returns:
+ New :class:`Keypoints` instance containing the input coordinates.
+ """
return cls(keypoints)
def to_tensor(self, as_padded_sequence: bool = False) -> Union[torch.torch.Tensor, List[torch.torch.Tensor]]:
@@ -189,9 +225,18 @@ class Keypoints:
return self._data
def clone(self) -> "Keypoints":
+ """Create an independent copy of the 2D keypoints."""
return Keypoints(self._data.clone(), False)
def type(self, dtype: torch.dtype) -> "Keypoints":
+ """Cast stored keypoint coordinates to a target dtype.
+
+ Args:
+ dtype: Destination floating-point dtype for the coordinate tensor.
+
+ Returns:
+ ``self`` after converting the stored coordinates in place.
+ """
self._data = self._data.type(dtype)
return self
@@ -281,10 +326,23 @@ class Keypoints3D:
@property
def shape(self) -> Size:
+ """Return the tensor shape used to store 3D keypoints.
+
+ Returns:
+ Shape of :attr:`data`. The common layouts are :math:`(N, 3)` and
+ :math:`(B, N, 3)`, where the final dimension stores ``(x, y, z)``
+ coordinates.
+ """
return self.data.shape
@property
def data(self) -> torch.torch.Tensor:
+ """Return the raw 3D keypoint coordinate tensor.
+
+ Returns:
+ Tensor storing coordinates in ``(..., 3)`` format, with the final
+ dimension ordered as ``(x, y, z)``.
+ """
return self._data
def pad(self, padding_size: torch.torch.Tensor) -> "Keypoints3D":
@@ -324,6 +382,15 @@ class Keypoints3D:
@classmethod
def from_tensor(cls, keypoints: torch.Tensor) -> "Keypoints3D":
+ """Validate and wrap a tensor of 3D keypoint coordinates.
+
+ Args:
+ keypoints: Tensor in :math:`(N, 3)` or :math:`(B, N, 3)` format,
+ where the last dimension stores ``(x, y, z)``.
+
+ Returns:
+ New :class:`Keypoints3D` instance containing the input coordinates.
+ """
return cls(keypoints)
def to_tensor(self, as_padded_sequence: bool = False) -> Union[torch.torch.Tensor, List[torch.torch.Tensor]]:
@@ -344,4 +411,5 @@ class Keypoints3D:
return self._data
def clone(self) -> "Keypoints3D":
+ """Create an independent copy of the 3D keypoints."""
return Keypoints3D(self._data.clone(), False)
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 5299c00db..defecad92 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -63,24 +63,76 @@ class Hyperplane(nn.Module):
@property
def normal(self) -> Vector3:
+ """Return the vector perpendicular to the hyperplane.
+
+ Returns:
+ :class:`~kornia.geometry.vector.Vector3` storing the normal
+ direction. For a 3D plane this is the vector :math:`n` in
+ :math:`n^T x + d = 0`.
+ """
return self._n
@property
def offset(self) -> Scalar:
+ """Return the scalar offset in the implicit plane equation.
+
+ Returns:
+ :class:`~kornia.geometry.vector.Scalar` containing the ``d`` term
+ in :math:`n^T x + d = 0`. The value controls where the plane sits
+ relative to the origin for the stored normal direction.
+ """
return self._d
def abs_distance(self, p: Vector3) -> Scalar:
+ """Compute unsigned distances from points to the hyperplane.
+
+ Args:
+ p: Point or batch of points wrapped as
+ :class:`~kornia.geometry.vector.Vector3`. The last coordinate
+ dimension represents ``(x, y, z)``.
+
+ Returns:
+ :class:`~kornia.geometry.vector.Scalar` with non-negative distance
+ values. Leading batch dimensions follow the broadcasted point and
+ plane inputs.
+ """
return Scalar(self.signed_distance(p).abs())
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L145
# TODO: tests
def signed_distance(self, p: Vector3) -> Scalar:
+ """Compute signed distances from points to the hyperplane.
+
+ The sign is determined by the stored normal vector. Points in the
+ normal direction have positive values; points on the opposite side have
+ negative values; points on the plane evaluate to zero.
+
+ Args:
+ p: Point or batch of points as
+ :class:`~kornia.geometry.vector.Vector3`, or a compatible
+ tensor-like vector accepted by the dot-product routine.
+
+ Returns:
+ :class:`~kornia.geometry.vector.Scalar` containing signed distance
+ values for each input point.
+ """
KORNIA_CHECK(isinstance(p, Vector3 | torch.Tensor))
return self.normal.dot(p) + self.offset
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L154
# TODO: tests
def projection(self, p: Vector3) -> Vector3:
+ """Project points onto the hyperplane along the normal direction.
+
+ Args:
+ p: Point or batch of points wrapped as
+ :class:`~kornia.geometry.vector.Vector3`.
+
+ Returns:
+ :class:`~kornia.geometry.vector.Vector3` containing the closest
+ point on the hyperplane for each input point, preserving leading
+ batch dimensions.
+ """
dist = self.signed_distance(p)
if len(dist.shape) != len(self.normal):
# non batched plane project a batch of points
@@ -92,12 +144,36 @@ class Hyperplane(nn.Module):
@classmethod
def from_vector(self, n: Vector3, e: Vector3) -> "Hyperplane":
+ """Create a hyperplane from a normal and one point on the plane.
+
+ Args:
+ n: Normal vector :math:`n` defining the plane orientation.
+ e: Point :math:`e` that lies on the target plane.
+
+ Returns:
+ :class:`Hyperplane` whose offset is chosen so that
+ :math:`n^T e + d = 0`.
+ """
normal: Vector3 = n
offset = -normal.dot(e)
return Hyperplane(normal, Scalar(offset))
@classmethod
def through(cls, p0: torch.Tensor, p1: torch.Tensor, p2: Optional[torch.Tensor] = None) -> "Hyperplane":
+ """Construct a line-like 2D hyperplane or a 3D plane through points.
+
+ Args:
+ p0: First point tensor, shaped ``(..., 2)`` for the 2D case or
+ ``(..., 3)`` for the 3D case.
+ p1: Second point tensor with the same shape as ``p0``.
+ p2: Optional third point tensor. If omitted, the method builds the
+ 2D line representation from ``p0`` and ``p1``. If provided, it
+ builds the 3D plane passing through all three points.
+
+ Returns:
+ :class:`Hyperplane` with a normal and offset determined by the
+ provided point set.
+ """
# 2d case
if p2 is None:
# TODO: improve tests
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 0a35e43e5..fb16e7c91 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -69,6 +69,25 @@ class NonMaximaSuppression2d(nn.Module):
return (pad(ky), pad(kx), pad(ky), pad(kx))
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor:
+ """Keep only strict local maxima in a 2D response map.
+
+ Each spatial location is compared with the surrounding values inside
+ ``self.kernel_size``. Locations that are not strictly larger than their
+ neighbors are suppressed. This is commonly used to turn dense corner or
+ keypoint response maps into sparse candidate locations.
+
+ Args:
+ x: Response tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is the batch size, :math:`C` is the number of
+ response channels, :math:`H` is height, and :math:`W` is width.
+ mask_only: If ``True``, return the boolean maxima mask. If
+ ``False``, return ``x`` masked by local-maxima positions.
+
+ Returns:
+ If ``mask_only`` is ``True``, a boolean tensor with shape
+ :math:`(B, C, H, W)`. Otherwise, a tensor with the same shape and
+ dtype as ``x`` where non-maxima have been set to zero.
+ """
if len(x.shape) != 4:
raise AssertionError(x.shape)
B, CH, H, W = x.size()
@@ -225,6 +244,25 @@ class NonMaximaSuppression3d(nn.Module):
return (kd, kd, ky, ky, kx, kx)
def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor:
+ """Keep only strict local maxima in a 3D response volume.
+
+ Each voxel is compared with its neighbors across depth, height, and
+ width. This is used by scale-space detectors to keep responses that are
+ locally maximal both in image position and in scale/depth.
+
+ Args:
+ x: Response tensor with shape :math:`(B, C, D, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channel count,
+ :math:`D` is depth or scale level, :math:`H` is height, and
+ :math:`W` is width.
+ mask_only: If ``True``, return only the maxima mask; otherwise
+ return suppressed responses.
+
+ Returns:
+ Boolean maxima mask with shape :math:`(B, C, D, H, W)` when
+ ``mask_only`` is ``True``. Otherwise, an NMS-filtered tensor with
+ the same shape and dtype as ``x``.
+ """
if len(x.shape) != 5:
raise AssertionError(x.shape)
# find local maximum values
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 16f406e84..2c6e3334a 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -204,6 +204,22 @@ class ConvSoftArgmax2d(nn.Module):
)
def forward(self, x: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
+ """Estimate local 2D coordinates from heatmap windows.
+
+ The operation applies soft-argmax inside sliding windows. Instead of
+ choosing the hard maximum location, it computes an expectation over
+ window coordinates, which gives differentiable subpixel coordinates.
+
+ Args:
+ x: Heatmap tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is the number of heatmap
+ channels, :math:`H` is height, and :math:`W` is width.
+
+ Returns:
+ Coordinates from :func:`conv_soft_argmax2d`. If
+ ``self.output_value`` is ``True``, returns ``(coords, values)``,
+ where ``values`` are the corresponding window responses.
+ """
return conv_soft_argmax2d(
x,
self.kernel_size,
@@ -258,6 +274,19 @@ class ConvSoftArgmax3d(nn.Module):
)
def forward(self, x: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
+ """Estimate local 3D coordinates from response-volume windows.
+
+ Args:
+ x: Response tensor with shape :math:`(B, C, D, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channel count,
+ :math:`D` is depth or scale level, :math:`H` is height, and
+ :math:`W` is width.
+
+ Returns:
+ Coordinates from :func:`conv_soft_argmax3d`. If
+ ``self.output_value`` is ``True``, returns ``(coords, values)``;
+ otherwise returns only coordinates.
+ """
return conv_soft_argmax3d(
x,
self.kernel_size,
@@ -566,6 +595,22 @@ class SpatialSoftArgmax2d(nn.Module):
)
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Compute one differentiable 2D coordinate per channel map.
+
+ The full spatial map is converted into a probability distribution and
+ the coordinate expectation is returned. This is a smooth alternative to
+ taking the hard argmax of each heatmap.
+
+ Args:
+ input: Heatmap tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channel count,
+ :math:`H` is height, and :math:`W` is width.
+
+ Returns:
+ Coordinate tensor from :func:`spatial_soft_argmax2d`. Coordinate
+ values are normalized or pixel-based according to
+ ``self.normalized_coordinates``.
+ """
return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates)
@@ -920,6 +965,23 @@ class ConvQuadInterp3d(nn.Module):
def forward(
self, x: torch.Tensor, precomputed_nms_mask: Optional[torch.Tensor] = None
) -> tuple[torch.Tensor, torch.Tensor]:
+ """Refine 3D extrema with convolution-based quadratic interpolation.
+
+ The method starts from local maxima in a scale-space response volume
+ and fits a local quadratic model around each candidate. The fitted
+ offset gives a subpixel position in scale, x, and y coordinates.
+
+ Args:
+ x: Response tensor with shape :math:`(B, C, D, H, W)`, where
+ :math:`D` is the scale/depth dimension.
+ precomputed_nms_mask: Optional boolean NMS mask with the same shape
+ as ``x``. Passing it avoids recomputing local maxima.
+
+ Returns:
+ Tuple ``(coords, values)``. ``coords`` stores refined coordinates
+ for scale, x, and y; ``values`` stores the corrected response
+ scores.
+ """
return conv_quad_interp3d(
x,
self.n_iters,
@@ -1182,6 +1244,18 @@ class IterativeQuadInterp3d(nn.Module):
x: torch.Tensor,
precomputed_nms_mask: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor, torch.Tensor]:
+ """Refine 3D extrema by iteratively fitting local quadratic patches.
+
+ Args:
+ x: Response tensor with shape :math:`(B, C, D, H, W)`.
+ precomputed_nms_mask: Optional boolean local-maxima mask with the
+ same shape as ``x``.
+
+ Returns:
+ Tuple ``(coords, values)`` from :func:`iterative_quad_interp3d`.
+ ``coords`` contains refined scale, x, and y locations, while
+ ``values`` contains their response scores.
+ """
return iterative_quad_interp3d(
x,
self.n_iters,
@@ -1276,6 +1350,21 @@ class AdaptiveQuadInterp3d(nn.Module):
x: torch.Tensor,
precomputed_nms_mask: Optional[torch.Tensor] = None,
) -> tuple[torch.Tensor, torch.Tensor]:
+ """Refine 3D extrema with the selected interpolation backend.
+
+ The backend is chosen according to ``self.mode`` (or device when
+ ``mode='auto'``), then delegated to either
+ :func:`conv_quad_interp3d` or :func:`iterative_quad_interp3d`.
+
+ Args:
+ x: Response tensor with shape :math:`(B, C, D, H, W)`.
+ precomputed_nms_mask: Optional boolean local-maxima mask with the
+ same shape as ``x``.
+
+ Returns:
+ Tuple ``(coords, values)`` containing refined scale-space
+ coordinates and corresponding response scores.
+ """
use_conv = self.mode == "conv" or (self.mode == "auto" and x.is_cuda)
if use_conv:
return conv_quad_interp3d(
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index b4a36af5c..58abc48f1 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -757,6 +757,19 @@ class Resize(nn.Module):
self.antialias: bool = antialias
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Resize the spatial dimensions of an image or feature tensor.
+
+ Args:
+ input: Tensor with image-like layout :math:`(*, C, H, W)`, where
+ ``*`` represents optional leading batch dimensions,
+ :math:`C` is channels, :math:`H` is height, and :math:`W` is
+ width.
+
+ Returns:
+ Resized tensor produced by :func:`resize`. The output keeps the
+ same leading and channel dimensions as ``input``; the height and
+ width are determined by ``self.size`` and ``self.side``.
+ """
return resize(
input,
self.size,
@@ -851,6 +864,21 @@ class Affine(nn.Module):
self.align_corners = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Warp the input with the affine transform configured in this module.
+
+ The transform matrix is built from this module's stored angle,
+ translation, scale, optional shear, and center. The resulting matrix is
+ passed to :func:`affine` for sampling.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channel count,
+ :math:`H` is height, and :math:`W` is width.
+
+ Returns:
+ Affine-warped tensor with shape :math:`(B, C, H, W)`. Values
+ sampled outside the input image are handled by ``self.padding_mode``.
+ """
if self.shear is None:
sx = sy = None
else:
@@ -904,6 +932,17 @@ class Rescale(nn.Module):
self.antialias: bool = antialias
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Resize spatial dimensions by the stored scale factor.
+
+ Args:
+ input: Tensor with shape :math:`(*, C, H, W)`, where ``*`` is any
+ leading batch shape, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Tensor with the same leading and channel dimensions as ``input``.
+ The output height and width are computed from ``self.factor``.
+ """
return rescale(
input, self.factor, self.interpolation, align_corners=self.align_corners, antialias=self.antialias
)
@@ -952,6 +991,18 @@ class Rotate(nn.Module):
self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Rotate an image batch around the configured center.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Rotated tensor with shape :math:`(B, C, H, W)`. The image extent is
+ kept fixed; newly exposed pixels are filled according to
+ ``self.padding_mode``.
+ """
return rotate(input, self.angle, self.center, self.mode, self.padding_mode, self.align_corners)
@@ -994,6 +1045,17 @@ class Translate(nn.Module):
self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Shift an image batch by the stored pixel translation.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Translated tensor with shape :math:`(B, C, H, W)`. Translation is
+ measured in pixels along the x and y image axes.
+ """
return translate(input, self.translation, self.mode, self.padding_mode, self.align_corners)
@@ -1042,6 +1104,17 @@ class Scale(nn.Module):
self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Scale an image batch around the configured center point.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Scaled tensor with the same shape as ``input``. The sampling grid
+ is built from ``self.scale_factor`` and ``self.center``.
+ """
return scale(input, self.scale_factor, self.center, self.mode, self.padding_mode, self.align_corners)
@@ -1080,4 +1153,16 @@ class Shear(nn.Module):
self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Skew an image batch with the configured x/y shear factors.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Sheared tensor with shape :math:`(B, C, H, W)`. The output image
+ size is unchanged; pixels outside the sampled area use the
+ configured padding mode.
+ """
return shear(input, self.shear, self.mode, self.padding_mode, self.align_corners)
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 4bbac44a1..78cb5838f 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -434,6 +434,21 @@ class CenterCrop2D(nn.Module):
}
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Crop the central region of each input image to ``self.size``.
+
+ Depending on ``cropping_mode``, the crop is produced either by
+ perspective-resampling (subpixel/interpolated) or by direct slicing.
+
+ Args:
+ input: Image batch with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ source height, and :math:`W` is source width.
+
+ Returns:
+ Center-cropped tensor with shape :math:`(B, C, h, w)`, where
+ :math:`h` and :math:`w` are the requested crop height and width
+ stored in ``self.size``.
+ """
batch_size = input.shape[0]
dst_h, dst_w = self.size
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index a7a3696a0..f0ec4c2a0 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -47,6 +47,17 @@ class Vflip(nn.Module):
"""
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Flip the image content along the vertical image axis.
+
+ Args:
+ input: Tensor containing one image or a batch of images, typically
+ shaped :math:`(*, C, H, W)`, where :math:`H` is height and
+ :math:`W` is width.
+
+ Returns:
+ Tensor with the same shape as ``input`` whose rows are reversed
+ from top to bottom.
+ """
return vflip(input)
def __repr__(self) -> str:
@@ -79,6 +90,17 @@ class Hflip(nn.Module):
"""
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Flip the image content along the horizontal image axis.
+
+ Args:
+ input: Tensor containing one image or a batch of images, typically
+ shaped :math:`(*, C, H, W)`, where :math:`H` is height and
+ :math:`W` is width.
+
+ Returns:
+ Tensor with the same shape as ``input`` whose columns are reversed
+ from left to right.
+ """
return hflip(input)
def __repr__(self) -> str:
@@ -108,6 +130,17 @@ class Rot180(nn.Module):
"""
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Rotate image content by 180 degrees without changing tensor shape.
+
+ Args:
+ input: Tensor containing one image or a batch of images, typically
+ shaped :math:`(*, C, H, W)`, where :math:`H` is height and
+ :math:`W` is width.
+
+ Returns:
+ Tensor with the same shape as ``input`` and both spatial axes
+ reversed.
+ """
return rot180(input)
def __repr__(self) -> str:
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 3abe29c63..595b034f8 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -40,10 +40,33 @@ class BaseWarper(nn.Module):
self.width = width
@abstractmethod
- def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor: ...
+ def forward(self, patch_src: torch.Tensor, src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Sample a source patch on this warper's destination grid.
+
+ Args:
+ patch_src: Source image or patch tensor with shape
+ :math:`(B, C, H, W)`, where :math:`B` is batch size,
+ :math:`C` is channels, :math:`H` is source height, and
+ :math:`W` is source width.
+ src_homo_dst: Optional homography with shape :math:`(B, 3, 3)`
+ mapping destination coordinates into the source image. Concrete
+ implementations may also use a grid precomputed from this
+ matrix.
+
+ Returns:
+ Tensor sampled in the destination frame managed by this warper.
+ """
+ ...
@abstractmethod
- def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None: ...
+ def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None:
+ """Precompute a sampling grid for repeated homography warps.
+
+ Args:
+ src_homo_dst: Homography tensor with shape :math:`(B, 3, 3)` used
+ to transform destination grid points into source coordinates.
+ """
+ ...
class HomographyWarper(BaseWarper):
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 1fde5f413..63c96ce17 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -34,13 +34,29 @@ class BaseModel(nn.Module):
"""Provide an abstract base class for image registration models."""
@abstractmethod
- def reset_model(self) -> None: ...
+ def reset_model(self) -> None:
+ """Reset learnable registration parameters to the identity transform."""
+ ...
@abstractmethod
- def forward(self) -> torch.Tensor: ...
+ def forward(self) -> torch.Tensor:
+ """Return the transform that maps source coordinates toward target coordinates.
+
+ Returns:
+ Transform matrix tensor for the current model state. Concrete
+ models return the matrix shape required by their warp function.
+ """
+ ...
@abstractmethod
- def forward_inverse(self) -> torch.Tensor: ...
+ def forward_inverse(self) -> torch.Tensor:
+ """Return the inverse mapping for the current registration transform.
+
+ Returns:
+ Transform matrix tensor that maps target coordinates back toward
+ source coordinates.
+ """
+ ...
class Homography(BaseModel):
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index a15e5c09d..a33ccde01 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -77,6 +77,22 @@ class PyrDown(nn.Module):
self.factor: float = factor
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Build the next lower-resolution Gaussian pyramid level.
+
+ The input is smoothed before resizing so high-frequency content is not
+ directly subsampled. This is the standard pyramid-down step used by
+ many multi-scale image algorithms.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Downsampled tensor from :func:`pyrdown`. The channel and batch
+ dimensions are preserved, while spatial dimensions are reduced
+ according to ``self.factor``.
+ """
return pyrdown(input, self.border_type, self.align_corners, self.factor)
@@ -108,6 +124,21 @@ class PyrUp(nn.Module):
self.align_corners: bool = align_corners
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Build the next higher-resolution Gaussian pyramid level.
+
+ The operation upsamples the image and applies pyramid smoothing so the
+ enlarged result is spatially consistent with Gaussian pyramid
+ reconstruction.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Upsampled tensor from :func:`pyrup`, typically with doubled height
+ and width, preserving batch and channel dimensions.
+ """
return pyrup(input, self.border_type, self.align_corners)
@@ -213,6 +244,15 @@ class ScalePyramid(nn.Module):
return F.conv2d(F.pad(tmp, (0, 0, pad, pad), mode="reflect"), k_v, groups=C)
def get_kernel_size(self, sigma: float) -> int:
+ """Choose an odd Gaussian kernel size for a given blur sigma.
+
+ Args:
+ sigma: Gaussian standard deviation measured in pixels.
+
+ Returns:
+ Odd integer kernel size large enough to cover the effective support
+ used by this scale-pyramid implementation.
+ """
ksize = int(2.0 * 4.0 * sigma + 1.0)
# matches OpenCV, but may cause padding problem for small images
@@ -224,6 +264,20 @@ class ScalePyramid(nn.Module):
return ksize
def get_first_level(self, input: torch.Tensor) -> tuple[torch.Tensor, float, float]:
+ """Create the first image level and its scale metadata.
+
+ The method optionally doubles image resolution, then applies initial
+ Gaussian blur so the first level reaches ``self.init_sigma``.
+
+ Args:
+ input: Image tensor with shape :math:`(B, C, H, W)`.
+
+ Returns:
+ Tuple ``(cur_level, cur_sigma, pixel_distance)``. ``cur_level`` is
+ the first image level, ``cur_sigma`` is its effective blur sigma,
+ and ``pixel_distance`` tells how one pixel in this level maps back
+ to the original input image.
+ """
pixel_distance = 1.0
cur_sigma = 0.5
# Same as in OpenCV up to interpolation difference
@@ -249,6 +303,23 @@ class ScalePyramid(nn.Module):
return cur_level, cur_sigma, pixel_distance
def forward(self, x: torch.Tensor) -> tuple[list[torch.Tensor], list[torch.Tensor], list[torch.Tensor]]:
+ """Construct a Gaussian scale pyramid over several octaves.
+
+ Each octave stores multiple progressively blurred versions of the same
+ image resolution. The next octave starts from a downsampled image, so
+ feature detectors can search both spatial location and scale.
+
+ Args:
+ x: Input image tensor with shape :math:`(B, C, H, W)`, where
+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is
+ height, and :math:`W` is width.
+
+ Returns:
+ Three lists with one entry per octave. ``pyr`` contains stacked
+ image levels, ``sigmas`` contains the absolute blur sigma for each
+ level, and ``pixel_dists`` contains the pixel spacing of each level
+ relative to the original image.
+ """
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index 45c744270..0deb9f1f6 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -50,23 +50,49 @@ class Vector3(TensorWrapper):
@property
def x(self) -> torch.Tensor:
+ """Return the x-coordinate stored in the last tensor dimension."""
return self.data[..., 0]
@property
def y(self) -> torch.Tensor:
+ """Return the y-coordinate stored in the last tensor dimension."""
return self.data[..., 1]
@property
def z(self) -> torch.Tensor:
+ """Return the z-coordinate stored in the last tensor dimension."""
return self.data[..., 2]
def normalized(self) -> "Vector3":
+ """Return a copy with unit Euclidean length.
+
+ Returns:
+ New :class:`Vector3` with the same leading shape as this vector.
+ The last dimension is normalized with the L2 norm, so each
+ ``(x, y, z)`` vector has length one when the input norm is nonzero.
+ """
return Vector3(F.normalize(self.data, p=2, dim=-1))
def dot(self, right: "Vector3") -> Scalar:
+ """Compute dot products with another 3D vector wrapper.
+
+ Args:
+ right: Right-hand :class:`Vector3` operand with compatible leading
+ dimensions.
+
+ Returns:
+ :class:`Scalar` containing :math:`x_1 x_2 + y_1 y_2 + z_1 z_2` for
+ each leading element.
+ """
return Scalar(batched_dot_product(self.data, right.data))
def squared_norm(self) -> Scalar:
+ """Compute squared Euclidean lengths of the wrapped vectors.
+
+ Returns:
+ :class:`Scalar` containing :math:`x^2 + y^2 + z^2` for each
+ vector.
+ """
return Scalar(batched_squared_norm(self.data))
@classmethod
@@ -76,6 +102,19 @@ class Vector3(TensorWrapper):
device: Optional[Union[str, torch.device]] = None,
dtype: Optional[torch.dtype] = None,
) -> "Vector3":
+ """Create random 3D vectors with optional leading dimensions.
+
+ Args:
+ shape: Optional leading dimensions before the final coordinate
+ dimension. For example, ``shape=(B, N)`` creates
+ :math:`(B, N, 3)` vectors.
+ device: Target device for the generated tensor.
+ dtype: Target dtype for the generated tensor.
+
+ Returns:
+ :class:`Vector3` wrapping a random tensor with shape
+ ``(*shape, 3)``.
+ """
if shape is None:
shape = ()
return cls(torch.rand((*shape, 3), device=device, dtype=dtype))
@@ -109,6 +148,22 @@ class Vector3(TensorWrapper):
device: Optional[Union[str, torch.device]] = None,
dtype: Optional[torch.dtype] = None,
) -> "Vector3":
+ """Construct a 3D vector wrapper from x, y, and z coordinates.
+
+ All coordinate inputs must share the same Python type (all floats or
+ all tensors). For tensor inputs, coordinates are stacked along the last
+ dimension to produce ``(..., 3)`` output.
+
+ Args:
+ x: X-coordinate value or tensor.
+ y: Y-coordinate value or tensor.
+ z: Z-coordinate value or tensor.
+ device: Device used when scalar inputs are converted to tensor.
+ dtype: Dtype used when scalar inputs are converted to tensor.
+
+ Returns:
+ :class:`Vector3` containing the assembled coordinates.
+ """
KORNIA_CHECK(type(x) is type(y) is type(z))
KORNIA_CHECK(isinstance(x, torch.Tensor | float))
if isinstance(x, float):
@@ -133,19 +188,43 @@ class Vector2(TensorWrapper):
@property
def x(self) -> torch.Tensor:
+ """Return the x-coordinate stored in the last tensor dimension."""
return self.data[..., 0]
@property
def y(self) -> torch.Tensor:
+ """Return the y-coordinate stored in the last tensor dimension."""
return self.data[..., 1]
def normalized(self) -> "Vector2":
+ """Return a copy with unit Euclidean length.
+
+ Returns:
+ New :class:`Vector2` with the same leading shape as this vector.
+ The last dimension is normalized so each ``(x, y)`` vector has
+ length one when the input norm is nonzero.
+ """
return Vector2(F.normalize(self.data, p=2, dim=-1))
def dot(self, right: "Vector2") -> Scalar:
+ """Compute dot products with another 2D vector wrapper.
+
+ Args:
+ right: Right-hand :class:`Vector2` operand with compatible leading
+ dimensions.
+
+ Returns:
+ :class:`Scalar` containing :math:`x_1 x_2 + y_1 y_2` for each
+ leading element.
+ """
return Scalar(batched_dot_product(self.data, right.data))
def squared_norm(self) -> Scalar:
+ """Compute squared Euclidean lengths of the wrapped vectors.
+
+ Returns:
+ :class:`Scalar` containing :math:`x^2 + y^2` for each vector.
+ """
return Scalar(batched_squared_norm(self.data))
@classmethod
@@ -155,6 +234,19 @@ class Vector2(TensorWrapper):
device: Optional[Union[str, torch.device]] = None,
dtype: Optional[torch.dtype] = None,
) -> "Vector2":
+ """Create random 2D vectors with optional leading dimensions.
+
+ Args:
+ shape: Optional leading dimensions before the final coordinate
+ dimension. For example, ``shape=(B, N)`` creates
+ :math:`(B, N, 2)` vectors.
+ device: Target device for the generated tensor.
+ dtype: Target dtype for the generated tensor.
+
+ Returns:
+ :class:`Vector2` wrapping a random tensor with shape
+ ``(*shape, 2)``.
+ """
if shape is None:
shape = ()
return cls(torch.rand((*shape, 2), device=device, dtype=dtype))
@@ -167,6 +259,21 @@ class Vector2(TensorWrapper):
device: Optional[Union[str, torch.device]] = None,
dtype: Optional[torch.dtype] = None,
) -> "Vector2":
+ """Construct a 2D vector wrapper from x and y coordinates.
+
+ Both coordinates must share the same Python type (both floats or both
+ tensors). For tensor inputs, coordinates are stacked along the last
+ dimension to produce ``(..., 2)`` output.
+
+ Args:
+ x: X-coordinate value or tensor.
+ y: Y-coordinate value or tensor.
+ device: Device used when scalar inputs are converted to tensor.
+ dtype: Dtype used when scalar inputs are converted to tensor.
+
+ Returns:
+ :class:`Vector2` containing the assembled coordinates.
+ """
KORNIA_CHECK(type(x) is type(y))
KORNIA_CHECK(isinstance(x, torch.Tensor | float))
if isinstance(x, float):