Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[DOCS] clean docs warnings (#604)

Edgar Riba5c585c177108
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 47d76fd36..a306a8012 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -19,7 +19,6 @@ This is the base class for creating a new transform. The user only needs to over
.. autoclass:: AugmentationBase
- :members: return_transform
.. automethod:: generate_parameters
.. automethod:: compute_transformation
diff --git a/docs/source/geometry.epipolar.rst b/docs/source/geometry.epipolar.rst
index 30a6a6e53..e461a6db8 100644
--- a/docs/source/geometry.epipolar.rst
+++ b/docs/source/geometry.epipolar.rst
@@ -39,7 +39,6 @@ Projection
.. autofunction:: projection_from_KRt
.. autofunction:: projections_from_fundamental
-.. autofunction:: scale_intrinsics
.. autofunction:: intrinsics_like
.. autofunction:: scale_intrinsics
.. autofunction:: random_intrinsics
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index 864740d9d..79e8050d8 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -25,12 +25,11 @@ Coordinates Subpixel
.. autofunction:: spatial_expectation2d
.. autofunction:: render_gaussian2d
-
Homography
---------------------
+----------
-.. autofunction:: find_homography
.. autofunction:: find_homography_dlt
+.. autofunction:: find_homography_dlt_iterated
Module
diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rst
index ff0d695f1..3cf7f0576 100644
--- a/docs/source/geometry.transform.rst
+++ b/docs/source/geometry.transform.rst
@@ -15,7 +15,6 @@ The functions in this section perform various geometrical transformations of 2D
.. autofunction:: invert_affine_transform
.. autofunction:: matrix_to_homogeneous
.. autofunction:: projection_from_Rt
-.. autofunction:: normal_transform_pixel
.. autofunction:: normal_transform3d_pixel
.. autofunction:: center_crop
.. autofunction:: crop_and_resize
diff --git a/docs/source/geometry.warp.rst b/docs/source/geometry.warp.rst
index f620faa30..22bde8b7b 100644
--- a/docs/source/geometry.warp.rst
+++ b/docs/source/geometry.warp.rst
@@ -11,3 +11,6 @@ kornia.geometry.warp
.. autofunction:: homography_warp
.. autofunction:: depth_warp
+.. autofunction:: warp_grid
+.. autofunction:: normalize_homography
+.. autofunction:: normal_transform_pixel
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index 83766b70a..d1e89ecf0 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -1,4 +1,7 @@
from .augmentation import (
+ AugmentationBase,
+ CenterCrop,
+ ColorJitter,
RandomAffine,
RandomCrop,
RandomErasing,
@@ -8,8 +11,6 @@ from .augmentation import (
RandomPerspective,
RandomResizedCrop,
RandomRotation,
- CenterCrop,
- ColorJitter,
RandomSolarize,
RandomPosterize,
RandomSharpness,
@@ -27,6 +28,11 @@ from kornia.color.normalize import (
)
__all__ = [
+ "AugmentationBase",
+ "CenterCrop",
+ "ColorJitter",
+ "Normalize",
+ "Denormalize",
"RandomAffine",
"RandomCrop",
"RandomErasing",
@@ -39,13 +45,9 @@ __all__ = [
"RandomPerspective",
"RandomResizedCrop",
"RandomRotation",
- "CenterCrop",
- "ColorJitter",
"RandomSolarize",
"RandomPosterize",
"RandomSharpness",
"RandomEqualize",
"RandomMotionBlur",
- "Normalize",
- "Denormalize",
]
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 3b3ea5d41..4295ad2db 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -4,24 +4,29 @@ from typing import Tuple, Optional
def match_nn(desc1: torch.Tensor, desc2: torch.Tensor,
dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
- """Function, which finds nearest neightbors in desc2 for each vector in desc1.
+ r"""Function, which finds nearest neightbors in desc2 for each vector in desc1.
+
If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+
Args:
desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
- dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
- desc2, shape of :math:`(B1, B2)`.
+ dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1
+ to each descriptor in desc2, shape of :math:`(B1, B2)`.
- Return:
- torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B1, 1)
- torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B1, 2)
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]:
+ - Descriptor distance of matching descriptors, shape of :math:`(B1, 1)`.
+ - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B1, 2)`.
"""
assert len(desc1.shape) == 2
assert len(desc2.shape) == 2
+
if dm is None:
dm = torch.cdist(desc1, desc2)
else:
assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+
match_dists, idxs_in_2 = torch.min(dm, dim=1)
idxs_in1: torch.Tensor = torch.arange(0, idxs_in_2.size(0), device=idxs_in_2.device)
matches_idxs: torch.Tensor = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)
@@ -31,28 +36,34 @@ def match_nn(desc1: torch.Tensor, desc2: torch.Tensor,
def match_mnn(desc1: torch.Tensor, desc2: torch.Tensor,
dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function, which finds mutual nearest neightbors in desc2 for each vector in desc1.
+
If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+
Args:
desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
- dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
- desc2, shape of :math:`(B1, B2)`.
+ dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1
+ to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)
- torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)
- where 0 <= B3 <= min(B1, B2)
+ Tuple[torch.Tensor, torch.Tensor]:
+ - Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
+ - Long tensor indexes of matching descriptors in desc1 and desc2, shape of :math:`(B3, 2)`,
+ where 0 <= B3 <= min(B1, B2)
"""
assert len(desc1.shape) == 2
assert len(desc2.shape) == 2
+
if dm is None:
dm = torch.cdist(desc1, desc2)
else:
assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+
ms = min(dm.size(0), dm.size(1))
match_dists, idxs_in_2 = torch.min(dm, dim=1)
match_dists2, idxs_in_1 = torch.min(dm, dim=0)
minsize_idxs = torch.arange(ms, device=dm.device)
+
if dm.size(0) <= dm.size(1):
mutual_nns = minsize_idxs == idxs_in_1[idxs_in_2][:ms]
matches_idxs = torch.cat([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)[mutual_nns]
@@ -68,18 +79,21 @@ def match_snn(desc1: torch.Tensor, desc2: torch.Tensor,
th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function, which finds nearest neightbors in desc2 for each vector in desc1.
which satisfy first to second nearest neighbor distance <= th.
+
If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+
Args:
desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
th (float): distance ratio threshold.
- dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
- desc2, shape of :math:`(B1, B2)`.
+ dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1
+ to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)
- torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)
- where 0 <= B3 <= B1
+ Tuple[torch.Tensor, torch.Tensor]:
+ - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,
+ where 0 <= B3 <= B1.
"""
assert len(desc1.shape) == 2
assert len(desc2.shape) == 2
@@ -89,6 +103,7 @@ def match_snn(desc1: torch.Tensor, desc2: torch.Tensor,
dm = torch.cdist(desc1, desc2)
else:
assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+
vals, idxs_in_2 = torch.topk(dm, 2, dim=1, largest=False)
ratio = vals[:, 0] / vals[:, 1]
mask = ratio <= th
@@ -103,18 +118,21 @@ def match_smnn(desc1: torch.Tensor, desc2: torch.Tensor,
th: float = 0.8, dm: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
"""Function, which finds mutual nearest neightbors in desc2 for each vector in desc1.
which satisfy first to second nearest neighbor distance <= th.
+
If the distance matrix dm is not provided, torch.cdist(desc1, desc2) is used.
+
Args:
desc1 (torch.Tensor): Batch of descriptors of a shape :math:`(B1, D)`.
desc2 (torch.Tensor): Batch of descriptors of a shape :math:`(B2, D)`.
th (float): distance ratio threshold.
- dm (torch.Tensor): optional. Tensor containing the distances from each descriptor in desc1 to each descriptor in
- desc2, shape of :math:`(B1, B2)`.
+ dm (torch.Tensor, optional): Tensor containing the distances from each descriptor in desc1
+ to each descriptor in desc2, shape of :math:`(B1, B2)`.
Return:
- torch.Tensor: Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)
- torch.Tensor: Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)
- where 0 <= B3 <= B1
+ Tuple[torch.Tensor, torch.Tensor]:
+ - Descriptor distance of matching descriptors, shape of. :math:`(B3, 1)`.
+ - Long tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` where 0 <= B3 <= B1.
"""
assert len(desc1.shape) == 2
assert len(desc2.shape) == 2
@@ -125,8 +143,10 @@ def match_smnn(desc1: torch.Tensor, desc2: torch.Tensor,
dm = torch.cdist(desc1, desc2)
else:
assert (dm.size(0) == desc1.size(0)) and (dm.size(1) == desc2.size(0))
+
dists1, idx1 = match_snn(desc1, desc2, th, dm)
dists2, idx2 = match_snn(desc2, desc1, th, dm.t())
+
if len(dists2) > 0 and len(dists1) > 0:
idx2 = idx2.flip(1)
idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1)
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index f4cb8b5d4..d0bf2c715 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -63,7 +63,7 @@ class SIFTDescriptor(nn.Module):
is computed
Returns:
- Tensor: SIFT descriptor of the patches
+ torch.Tensor: SIFT descriptor of the patches
Shape:
- Input: (B, 1, num_spatial_bins, num_spatial_bins)
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 0704c0fd6..c89becb67 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -9,17 +9,18 @@ urls["hp_a"] = "https://github.com/yuruntian/SOSNet/tree/master/sosnet-weights/s
class SOSNet(nn.Module):
- """
- 128-dimensional SOSNet model definition for 32x32 patches.
+ """128-dimensional SOSNet model definition for 32x32 patches.
+
This is based on the original code from paper
"SOSNet:Second Order Similarity Regularization for Local Descriptor Learning".
+
Args:
- pretrained: (bool) Download and set pretrained weights to the model. Default: false.
- Returns:
- torch.Tensor: SOSNet descriptor of the patches.
+ pretrained (bool): Download and set pretrained weights to the model. Default: false.
+
Shape:
- Input: (B, 1, 32, 32)
- Output: (B, 128)
+
Examples:
>>> input = torch.rand(8, 1, 32, 32)
>>> sosnet = kornia.feature.SOSNet()
diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.py
index e9083b6a1..c23f1deb2 100644
--- a/kornia/geometry/camera/perspective.py
+++ b/kornia/geometry/camera/perspective.py
@@ -18,7 +18,7 @@ def project_points(
point3d (torch.Tensor): tensor containing the 3d points to be projected
to the camera plane. The shape of the tensor can be :math:`(*, 3)`.
camera_matrix (torch.Tensor): tensor containing the intrinsics camera
- matrix. The tensor shape must be Bx4x4.
+ matrix. The tensor shape must be :math:`(*, 3, 3)`.
Returns:
torch.Tensor: array of (u, v) cam coordinates with shape :math:`(*, 2)`.
@@ -26,17 +26,22 @@ def project_points(
if not torch.is_tensor(point_3d):
raise TypeError("Input point_3d type is not a torch.Tensor. Got {}"
.format(type(point_3d)))
+
if not torch.is_tensor(camera_matrix):
raise TypeError("Input camera_matrix type is not a torch.Tensor. Got {}"
.format(type(camera_matrix)))
+
if not (point_3d.device == camera_matrix.device):
raise ValueError("Input tensors must be all in the same device.")
+
if not point_3d.shape[-1] == 3:
raise ValueError("Input points_3d must be in the shape of (*, 3)."
" Got {}".format(point_3d.shape))
+
if not camera_matrix.shape[-2:] == (3, 3):
raise ValueError(
"Input camera_matrix must be in the shape of (*, 3, 3).")
+
# projection eq. [u, v, w]' = K * [x y z 1]'
# u = fx * X / Z + cx
# v = fy * Y / Z + cy
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index 6bf007ee2..923be9813 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -64,7 +64,7 @@ def find_homography_dlt_iterated(points1: torch.Tensor,
weights: torch.Tensor,
soft_inl_th: float = 3.0,
n_iter: int = 5) -> torch.Tensor:
- r"""Computes the homography matrix using the iteratively-reweighted least squares (IRWLS)
+ r"""Computes the homography matrix using the iteratively-reweighted least squares (IRWLS).
The linear system is solved by using the Reweighted Least Squares Solution for the 4 Points algorithm.
@@ -72,8 +72,8 @@ def find_homography_dlt_iterated(points1: torch.Tensor,
points1 (torch.Tensor): A set of points in the first image with a tensor shape :math:`(B, N, 2)`.
points2 (torch.Tensor): A set of points in the second image with a tensor shape :math:`(B, N, 2)`.
weights (torch.Tensor): Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.
- Used for the first iteration of the IRWLS.
- soft_inl_th (float): Soft inlier threshold used for weight calculation
+ Used for the first iteration of the IRWLS.
+ soft_inl_th (float): Soft inlier threshold used for weight calculation.
n_iter (int): number of iterations. Default is 5.
Returns:
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 7b6f0d3ee..c27b5e8e1 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -55,22 +55,17 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
\right )
Args:
- src (torch.Tensor): input image.
- M (Tensor): transformation matrix.
+ src (torch.Tensor): input image with shape :math:`(B, C, H, W)`.
+ M (torch.Tensor): transformation matrix with shape :math:`(B, 3, 3)`.
dsize (tuple): size of the output image (height, width).
flags (str): interpolation mode to calculate output values
'bilinear' | 'nearest'. Default: 'bilinear'.
border_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
- align_corners(bool): interpolation flag. Default: False. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+ align_corners(bool): interpolation flag. Default: False.
Returns:
- Tensor: the warped input image.
-
- Shape:
- - Input: :math:`(B, C, H, W)` and :math:`(B, 3, 3)`
- - Output: :math:`(B, C, H, W)`
+ torch.Tensor: the warped input image :math:`(B, C, H, W)`.
.. note::
See a working example `here <https://kornia.readthedocs.io/en/latest/
@@ -113,14 +108,10 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
'bilinear' | 'nearest'. Default: 'bilinear'.
padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
- align_corners (bool): mode for grid_generation. Default: False. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
+ align_corners (bool): mode for grid_generation. Default: False.
Returns:
- torch.Tensor: the warped tensor.
-
- Shape:
- - Output: :math:`(B, C, H, W)`
+ torch.Tensor: the warped tensor with shape :math:`(B, C, H, W)`.
.. note::
See a working example `here <https://kornia.readthedocs.io/en/latest/
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index ffeb8f41e..edd4647a9 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -21,6 +21,7 @@ def warp_projective(src: torch.Tensor,
align_corners: bool = True) -> torch.Tensor:
r"""Applies a projective transformation a to 3d tensor.
+ Args:
src (torch.Tensor): input tensor of shape :math:`(B, C, D, H, W)`.
M (torch.Tensor): projective transformation matrix of shape :math:`(B, 3, 4)`.
dsize (Tuple[int, int, int]): size of the output image (depth, height, width).
@@ -28,8 +29,7 @@ def warp_projective(src: torch.Tensor,
'bilinear' | 'nearest'. Default: 'bilinear'.
padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
- align_corners (bool): mode for grid_generation. Default: True. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
+ align_corners (bool): mode for grid_generation. Default: True.
Returns:
torch.Tensor: the warped 3d tensor with shape :math:`(B, C, D, H, W)`.
@@ -148,16 +148,16 @@ def normal_transform3d_pixel(depth: int, height: int, width: int) -> torch.Tenso
def get_projective_transform(center: torch.Tensor, angles: torch.Tensor) -> torch.Tensor:
r"""Calculates the projection matrix for a 3D rotation.
- The function computes the projection matrix given the center, scales and angles per axis.
+ The function computes the projection matrix given the center and angles per axis.
Args:
center (torch.Tensor): center of the rotation in the source with shape :math:`(B, 3)`.
- angles (Tensor): angle axis vector containing the rotation angles in degrees in the form
+ angles (torch.Tensor): angle axis vector containing the rotation angles in degrees in the form
of (rx, ry, rz) with shape :math:`(B, 3)`. Internally it calls Rodrigues to compute
the rotation matrix from axis-angle.
Returns:
- Tensor: the projection matrix of 3D rotation with shape :math:`(B, 3, 4)`.
+ torch.Tensor: the projection matrix of 3D rotation with shape :math:`(B, 3, 4)`.
"""
assert len(center.shape) == 2 and center.shape[-1] == 3, center.shape
diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.py
index bcc45661f..a1a0729bc 100644
--- a/kornia/geometry/warp/homography_warper.py
+++ b/kornia/geometry/warp/homography_warper.py
@@ -212,10 +212,7 @@ def normal_transform_pixel(height: int, width: int) -> torch.Tensor:
width (int): image width.
Returns:
- Tensor: normalized transform.
-
- Shape:
- Output: :math:`(1, 3, 3)`
+ torch.Tensor: normalized transform with shape :math:`(1, 3, 3)`
"""
tr_mat = torch.tensor([[1.0, 0.0, -1.0],
[0.0, 1.0, -1.0],
@@ -236,13 +233,10 @@ def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
dst_pix_trans_src_pix (torch.Tensor): homography/ies from source to destiantion to be
normalized. :math:`(B, 3, 3)`
dsize_src (tuple): size of the source image (height, width).
- dsize_src (tuple): size of the destination image (height, width).
+ dsize_dst (tuple): size of the destination image (height, width).
Returns:
- Tensor: the normalized homography.
-
- Shape:
- Output: :math:`(B, 3, 3)`
+ torch.Tensor: the normalized homography of shape :math:`(B, 3, 3)`.
"""
check_is_tensor(dst_pix_trans_src_pix)
@@ -253,12 +247,14 @@ def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
# source and destination sizes
src_h, src_w = dsize_src
dst_h, dst_w = dsize_dst
+
# compute the transformation pixel/norm for src/dst
src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(
src_h, src_w).to(dst_pix_trans_src_pix)
src_pix_trans_src_norm = torch.inverse(src_norm_trans_src_pix)
dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel(
dst_h, dst_w).to(dst_pix_trans_src_pix)
+
# compute chain transformations
dst_norm_trans_src_norm: torch.Tensor = (
dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
diff --git a/kornia/losses/psnr.py b/kornia/losses/psnr.py
index a4987a379..f7fd881b2 100644
--- a/kornia/losses/psnr.py
+++ b/kornia/losses/psnr.py
@@ -32,7 +32,7 @@ class PSNRLoss(nn.Module):
>>> kornia.losses.psnr_loss(torch.ones(1), 1.2*torch.ones(1), 2)
tensor(20.0000) # 10 * log(4/((1.2-1)**2)) / log(10)
- reference:
+ Reference:
https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio#Definition
"""
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index 6aa14416d..a71618635 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -3,16 +3,20 @@ import torch.nn as nn
class TotalVariation(nn.Module):
- r"""Computes the Total Variation according to
- [1] https://en.wikipedia.org/wiki/Total_variation
+ r"""Computes the Total Variation according to [1].
+
Shape:
- Input: :math:`(N, C, H, W)` or :math:`(C, H, W)` where C = number of classes.
- Output: :math:`(N,)` or :math:`()`
+
Examples:
>>> kornia.losses.total_variation(torch.ones(3,4,4)) # tensor(0.)
>>> tv = kornia.losses.TotalVariation()
>>> output = tv(torch.ones(2,3,4,4)) # tensor([0., 0.])
>>> output.backward()
+
+ Reference:
+ [1] https://en.wikipedia.org/wiki/Total_variation
"""
def __init__(self) -> None:
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 525e2abc7..1e02c81b7 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -6,11 +6,13 @@ import torch
def image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor:
"""Converts a numpy image to a PyTorch 4d tensor image.
+
Args:
image (numpy.ndarray): image of the form :math:`(H, W, C)`, :math:`(H, W)` or
:math:`(B, H, W, C)`.
keepdim (bool): If ``False`` unsqueeze the input image to match the shape
:math:`(B, H, W, C)`. Default: ``True``
+
Returns:
torch.Tensor: tensor of the form :math:`(B, C, H, W)` if keepdim is ``False``,
:math:`(C, H, W)` otherwise.
@@ -63,8 +65,10 @@ def _to_bchw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) -> t
if len(tensor.shape) == 2:
tensor = tensor.unsqueeze(0)
+
if len(tensor.shape) == 3:
tensor = tensor.unsqueeze(0)
+
if color_channel_num is not None and color_channel_num != 1:
channel_list = [0, 1, 2, 3]
channel_list.insert(1, channel_list.pop(color_channel_num))
@@ -73,8 +77,9 @@ def _to_bchw(tensor: torch.Tensor, color_channel_num: Optional[int] = None) -> t
def tensor_to_image(tensor: torch.Tensor) -> np.array:
- """Converts a PyTorch tensor image to a numpy image. In case the tensor is in the GPU,
- it will be copied back to CPU.
+ """Converts a PyTorch tensor image to a numpy image.
+
+ In case the tensor is in the GPU, it will be copied back to CPU.
Args:
tensor (torch.Tensor): image of the form :math:`(H, W)`, :math:`(C, H, W)` or
@@ -94,6 +99,7 @@ def tensor_to_image(tensor: torch.Tensor) -> np.array:
input_shape = tensor.shape
image: np.array = tensor.cpu().detach().numpy()
+
if len(input_shape) == 2:
# (H, W) -> (H, W)
image = image