Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Docs/contrib docstrings (#3715)

Jeevang1-epic860747eb84a0
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 2104e8191..8c1e5fd53 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -153,6 +153,25 @@ class DistanceTransform(nn.Module):
self.h = h
def forward(self, image: torch.Tensor) -> torch.Tensor:
+ """Compute the distance transform while preserving the original tensor layout.
+
+ The underlying functional implementation expects a single-channel tensor.
+ For multi-channel inputs, channels are temporarily folded into the batch
+ dimension, processed independently, and then reshaped back.
+
+ Args:
+ image: Input tensor with shape :math:`(B, C, H, W)` for 2D data or
+ :math:`(B, C, D, H, W)` for 3D data, where:
+ - ``B`` is batch size,
+ - ``C`` is the number of channels,
+ - ``D`` is depth (only for 3D volumes),
+ - ``H`` is height,
+ - ``W`` is width.
+
+ Returns:
+ A distance-transform tensor with the same shape as ``image``.
+ Each channel is processed independently.
+ """
# Reshape multi-channel inputs to batch dimension to ensure independent processing
if image.shape[1] > 1:
# Dynamically determine spatial dimensions (works for H,W or D,H,W)
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 6c9b33546..1ffd12dd2 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -194,6 +194,21 @@ class ExtractTensorPatches(nn.Module):
self.allow_auto_padding: bool = allow_auto_padding
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Extract sliding-window patches from a batched image tensor.
+
+ Args:
+ input: Input tensor with shape :math:`(B, C, H, W)`, where:
+ - ``B`` is the batch size (number of images),
+ - ``C`` is the number of channels,
+ - ``H`` is height,
+ - ``W`` is width.
+
+ Returns:
+ A tensor containing stacked patches with shape
+ :math:`(B, N, C, H_{out}, W_{out})`, where:
+ - ``N`` is the number of extracted windows per image,
+ - ``H_{out}`` and ``W_{out}`` are patch height and patch width.
+ """
return extract_tensor_patches(
input,
self.window_size,
@@ -287,6 +302,19 @@ class CombineTensorPatches(nn.Module):
self.allow_auto_unpadding: bool = allow_auto_unpadding
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Reconstruct full images from extracted patches.
+
+ Args:
+ input: Patch tensor with shape :math:`(B, N, C, H_{out}, W_{out})`, where:
+ - ``B`` is the batch size,
+ - ``N`` is the number of patches,
+ - ``C`` is the number of channels,
+ - ``H_{out}`` and ``W_{out}`` are patch height and width.
+
+ Returns:
+ A reconstructed tensor with shape :math:`(B, C, H, W)`, where ``H``
+ and ``W`` correspond to ``original_size`` after optional unpadding.
+ """
return combine_tensor_patches(
input,
self.original_size,
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index 29afd80e7..83ed4e28a 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -186,9 +186,39 @@ class FaceDetector(nn.Module):
self.nms = nms_kornia
def preprocess(self, image: torch.Tensor) -> torch.Tensor:
+ """Preprocess input images before feeding them to YuNet.
+
+ Args:
+ image: Batch of RGB images with shape :math:`(B, 3, H, W)`, where:
+ - ``B`` is batch size,
+ - ``3`` is the RGB channel dimension,
+ - ``H`` is image height,
+ - ``W`` is image width.
+
+ Returns:
+ The preprocessed image tensor. The current implementation returns the
+ input unchanged and acts as an extension point for custom pipelines.
+ """
return image
def postprocess(self, data: Dict[str, torch.Tensor], height: int, width: int) -> List[torch.Tensor]:
+ """Decode model outputs into filtered face detections.
+
+ Args:
+ data: Raw output dictionary from YuNet containing ``loc``, ``conf``,
+ and ``iou`` tensors.
+ height: Input image height used to scale decoded box coordinates.
+ width: Input image width used to scale decoded box coordinates.
+
+ Returns:
+ A list with one tensor per batch element. Each tensor is shaped
+ :math:`(N, 15)`, where ``N`` is the number of detections kept after
+ confidence filtering and non-maximum suppression (NMS).
+
+ The 15 values per detection are:
+ - 14 geometry values (bounding box + five keypoints),
+ - 1 confidence score.
+ """
loc, conf, iou = data["loc"], data["conf"], data["iou"]
scale = torch.tensor(
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index 6e021ba7f..5c66123ce 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -112,6 +112,20 @@ class ImageStitcher(nn.Module):
return input_dict
def postprocess(self, image: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ """Crop redundant empty columns from a stitched panorama.
+
+ Args:
+ image: Stitched image tensor, typically shaped
+ :math:`(B, C, H, W_{panorama})`, where ``W_{panorama}`` is the
+ panorama width after concatenation/warping.
+ mask: Validity mask aligned with ``image`` where non-zero values mark
+ pixels covered by at least one input view.
+
+ Returns:
+ The stitched image cropped to remove trailing invalid columns
+ (columns that contain no valid pixels in the mask).
+ If no redundant area is found, the original ``image`` is returned.
+ """
# NOTE: assumes no batch mode. This method keeps all valid regions after stitching.
mask_ = mask.sum((0, 1))
index = int(mask_.bool().any(0).long().argmin().item())
@@ -120,6 +134,17 @@ class ImageStitcher(nn.Module):
return image[..., :index]
def on_matcher(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ """Run the configured feature matcher on preprocessed inputs.
+
+ Args:
+ data: Matcher input dictionary, usually containing ``image0`` and
+ ``image1`` tensors.
+
+ Returns:
+ A correspondence dictionary produced by ``self.matcher``.
+ Typical entries are matched keypoints and batch indices used later
+ for homography estimation.
+ """
return self.matcher(data)
def stitch_pair(
@@ -129,6 +154,24 @@ class ImageStitcher(nn.Module):
mask_left: Optional[torch.Tensor] = None,
mask_right: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Stitch two images into a shared panorama frame.
+
+ Args:
+ images_left: Reference image tensor, shaped :math:`(B, C, H, W_l)`.
+ images_right: Image tensor to be warped onto the reference frame,
+ shaped :math:`(B, C, H, W_r)`.
+ mask_left: Optional validity mask for ``images_left`` with the same
+ shape as ``images_left``.
+ mask_right: Optional validity mask for ``images_right`` with the same
+ shape as ``images_right``.
+
+ Returns:
+ A tuple ``(stitched_image, stitched_mask)``:
+ - ``stitched_image`` is the blended panorama tensor with width
+ ``W_l + W_r`` before final cropping.
+ - ``stitched_mask`` is a mask tensor indicating which panorama
+ pixels are valid after warping and blending.
+ """
# Compute the transformed images
input_dict = self.preprocess(images_left, images_right)
out_shape = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
@@ -148,6 +191,17 @@ class ImageStitcher(nn.Module):
return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)
def forward(self, *imgs: torch.Tensor) -> torch.Tensor:
+ """Iteratively stitch a sequence of overlapping images.
+
+ Args:
+ *imgs: Ordered image tensors from left to right. Each tensor is expected
+ to share a common height and overlap with the next image.
+ Each tensor typically follows :math:`(B, C, H, W)`.
+
+ Returns:
+ A single panorama tensor obtained by stitching all provided images
+ in order and cropping trailing empty space.
+ """
img_out = imgs[0]
mask_left = torch.ones_like(img_out)
for i in range(len(imgs) - 1):
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index 2301ee12b..51175c588 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -69,6 +69,20 @@ class KMeans:
@property
def cluster_centers(self) -> torch.Tensor:
+ """Return the current cluster centers.
+
+ Returns:
+ A tensor with shape :math:`(C, D)`:
+ - ``C`` is the number of clusters.
+ - ``D`` is the feature dimension of each sample.
+
+ If :meth:`fit` has already been called, this returns the learned
+ final centers. Otherwise, it returns the initialization provided
+ during construction.
+
+ Raises:
+ TypeError: If no initial centers were provided and ``fit`` has not been run.
+ """
if isinstance(self._final_cluster_centers, torch.Tensor):
return self._final_cluster_centers
if isinstance(self._cluster_centers, torch.Tensor):
@@ -78,6 +92,16 @@ class KMeans:
@property
def cluster_assignments(self) -> torch.Tensor:
+ """Return cluster labels assigned during the most recent ``fit`` call.
+
+ Returns:
+ A 1D tensor with shape :math:`(N,)`, where ``N`` is the number of
+ samples given to :meth:`fit`. Each value is the cluster index
+ assigned to the corresponding sample.
+
+ Raises:
+ TypeError: If ``fit`` has not been run yet.
+ """
if isinstance(self._final_cluster_assignments, torch.Tensor):
return self._final_cluster_assignments
else:
diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.py
index 89cbf154b..ab09458cc 100644
--- a/kornia/contrib/lambda_module.py
+++ b/kornia/contrib/lambda_module.py
@@ -47,4 +47,21 @@ class Lambda(nn.Module):
self.func = func
def forward(self, img: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor:
+ """Run the user-provided transform function.
+
+ This method simply forwards all arguments to ``self.func``.
+ It is useful when you want to insert a custom Python callable inside a
+ ``torch.nn.Module`` pipeline.
+
+ Args:
+ img: Primary input tensor passed as the first positional argument.
+ For image tasks this is commonly shaped ``(B, C, H, W)``, where
+ ``B`` = batch size, ``C`` = number of channels,
+ ``H`` = height, and ``W`` = width.
+ *args: Additional positional arguments forwarded to ``self.func``.
+ **kwargs: Additional keyword arguments forwarded to ``self.func``.
+
+ Returns:
+ The output tensor returned by ``self.func``.
+ """
return self.func(img, *args, **kwargs)
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index a5d4b9605..6e71e8a48 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -167,6 +167,25 @@ class RRDBNetBuilder:
@staticmethod
def build(model_name: str = "RealESRNet_x4plus", pretrained: bool = True) -> SuperResolution:
+ """Build a preconfigured RRDB (Residual-in-Residual Dense Block) model.
+
+ The returned object is a :class:`SuperResolution` wrapper configured for
+ inference. Internally, this factory selects architecture hyperparameters
+ based on ``model_name``, and optionally loads pretrained weights.
+
+ Args:
+ model_name: Name of the RRDB variant to construct. Supported options are:
+ ``"RealESRGAN_x4plus"``, ``"RealESRNet_x4plus"``,
+ ``"RealESRGAN_x4plus_anime_6B"``, and ``"RealESRGAN_x2plus"``.
+ pretrained: If ``True``, download and load pretrained weights for the
+ selected model variant.
+
+ Returns:
+ A :class:`SuperResolution` wrapper ready for inference.
+
+ Raises:
+ ValueError: If ``model_name`` is not one of the supported variants.
+ """
if model_name == "RealESRGAN_x4plus":
model = basicsr.archs.rrdbnet_arch.RRDBNet( # type: ignore
num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4
@@ -213,6 +232,28 @@ class SmallSRBuilder:
def build(
model_name: str = "small_sr", pretrained: bool = True, upscale_factor: int = 3, image_size: Optional[int] = None
) -> SuperResolution:
+ """Build a lightweight super-resolution (SR) model wrapper.
+
+ SR stands for *super-resolution*, which means generating a higher
+ resolution output from a lower resolution input.
+
+ Args:
+ model_name: Name of the model variant to build. Currently only
+ ``"small_sr"`` is supported.
+ pretrained: If ``True``, load pretrained weights for the selected model.
+ upscale_factor: Integer scale used by ``SmallSRNetWrapper``.
+ For example, ``3`` maps an input image of size ``H x W`` to an
+ output image of approximately ``3H x 3W``.
+ image_size: Optional fixed input size. When provided, output metadata is
+ configured as ``image_size * upscale_factor``.
+
+ Returns:
+ A :class:`SuperResolution` instance configured with resizing pre-processing
+ and identity post-processing.
+
+ Raises:
+ ValueError: If ``model_name`` is not supported.
+ """
if model_name.lower() == "small_sr":
model = SmallSRNetWrapper(upscale_factor, pretrained=pretrained)
else:
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 75742df27..77688ffb4 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -321,6 +321,18 @@ class VisualPrompter:
return results
def reset_image(self) -> None:
+ """Clear cached image state and prompt-transform metadata.
+
+ This method invalidates previously computed image embeddings and resets all
+ size/transform bookkeeping so a new call to :meth:`set_image` starts from a
+ clean state.
+
+ In practice, this resets:
+ - transformed-image parameters,
+ - original/input/encoder spatial sizes,
+ - cached image embeddings,
+ - ``is_image_set`` status flag.
+ """
self._tfs_params = None
self._original_image_size = None
self._input_image_size = None