π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Docs] Improve docs for geometry transform (#913)
Edgar Riba3212fc1c971e
diff --git a/.github/workflows/tests_cuda_versions.yml b/.github/workflows/tests_cuda_versions.ymlindex 5d687e434..af1b8051f 100644--- a/.github/workflows/tests_cuda_versions.yml+++ b/.github/workflows/tests_cuda_versions.yml@@ -21,7 +21,8 @@ jobs:pytorch-version: [1.6.0, 1.7.0, 1.7.1, 1.8.0]cuda-version: [9.2, 10.1, 10.2]exclude:- - pytorch-version: 1.8.0+ - python-version: 3.7+ pytorch-version: 1.8.0cuda-version: 9.2steps:- uses: actions/checkout@v2diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rstindex 493285e5b..054140754 100644--- a/docs/source/geometry.transform.rst+++ b/docs/source/geometry.transform.rst@@ -5,10 +5,20 @@ kornia.geometry.transformThe functions in this section perform various geometrical transformations of 2D images.+Warp operators+--------------+.. autofunction:: warp_perspective.. autofunction:: warp_perspective3d.. autofunction:: warp_affine.. autofunction:: warp_affine3d+.. autofunction:: warp_points_tps+.. autofunction:: warp_image_tps+.. autofunction:: remap++Matrix transformations+----------------------+.. autofunction:: get_perspective_transform.. autofunction:: get_perspective_transform3d.. autofunction:: get_projective_transform@@ -17,22 +27,26 @@ The functions in this section perform various geometrical transformations of 2D.. autofunction:: get_shear_matrix3d.. autofunction:: get_affine_matrix2d.. autofunction:: get_affine_matrix3d-.. autofunction:: remap.. autofunction:: invert_affine_transform.. autofunction:: projection_from_Rt+.. autofunction:: get_tps_transform++Crop operators+--------------+.. autofunction:: crop_by_boxes.. autofunction:: center_crop.. autofunction:: crop_and_resize++Bounding Box+------------+.. autofunction:: bbox_to_mask.. autofunction:: infer_box_shape.. autofunction:: validate_bboxes-.. autofunction:: pyrdown-.. autofunction:: pyrup-.. autofunction:: build_pyramid-.. autofunction:: elastic_transform2d-.. autofunction:: get_tps_transform-.. autofunction:: warp_points_tps-.. autofunction:: warp_image_tps++Image 2d transforms+-------------------.. autofunction:: affine.. autofunction:: rotate@@ -44,6 +58,13 @@ The functions in this section perform various geometrical transformations of 2D.. autofunction:: rot180.. autofunction:: resize.. autofunction:: rescale+.. autofunction:: elastic_transform2d+.. autofunction:: pyrdown+.. autofunction:: pyrup+.. autofunction:: build_pyramid++Module+------.. autoclass:: Rotate.. autoclass:: Translatediff --git a/kornia/enhance/equalization.py b/kornia/enhance/equalization.pyindex f6549784d..ff6c24312 100644--- a/kornia/enhance/equalization.py+++ b/kornia/enhance/equalization.py@@ -228,7 +228,8 @@ def _compute_equalized_tiles(interp_tiles: torch.Tensor, luts: torch.Tensor) ->tiles_equalized: torch.Tensor = torch.zeros_like(interp_tiles, dtype=torch.long)# compute the interpolation weights (shapes are 2 x TH x TW because they must be applied to 2 interp tiles)- ih = torch.arange(2 * th - 1, -1, -1, device=interp_tiles.device).div(2. * th - 1)[None].T.expand(2 * th, tw)+ ih = torch.arange(2 * th - 1, -1, -1, device=interp_tiles.device).div(+ 2. * th - 1)[None].transpose(-2, -1).expand(2 * th, tw)ih = ih.unfold(0, th, th).unfold(1, tw, tw) # 2 x 1 x TH x TWiw = torch.arange(2 * tw - 1, -1, -1, device=interp_tiles.device).div(2. * tw - 1).expand(th, 2 * tw)iw = iw.unfold(0, th, th).unfold(1, tw, tw) # 1 x 2 x TH x TWdiff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.pyindex 5158c4141..04a65f58c 100644--- a/kornia/filters/blur_pool.py+++ b/kornia/filters/blur_pool.py@@ -46,6 +46,7 @@ class BlurPool2D(nn.Module):[0.0625, 0.3750, 0.0625],[0.0000, 0.0625, 0.3125]]]])"""+def __init__(self, kernel_size: int, stride: int = 2):super(BlurPool2D, self).__init__()self.kernel_size = kernel_size@@ -89,6 +90,7 @@ class MaxBlurPool2D(nn.Module):tensor([[[[0.5625, 0.3125],[0.3125, 0.8750]]]])"""+def __init__(self, kernel_size: int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False):super(MaxBlurPool2D, self).__init__()self.kernel_size = kernel_sizediff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.pyindex c23f1deb2..3ad7339b7 100644--- a/kornia/geometry/camera/perspective.py+++ b/kornia/geometry/camera/perspective.py@@ -79,7 +79,7 @@ def unproject_points(depth (torch.Tensor): tensor containing the depth value of each 2dpoints. The tensor shape must be equal to point2d :math:`(*, 1)`.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)`.normalize (bool, optional): whether to normalize the pointcloud. Thismust be set to `True` when the depth is represented as the Euclideanray length from the camera position. Default is `False`.@@ -114,6 +114,7 @@ def unproject_points(if not camera_matrix.shape[-2:] == (3, 3):raise ValueError("Input camera_matrix must be in the shape of (*, 3, 3).")+# projection eq. K_inv * [u v 1]'# x = (u - cx) * Z / fx# y = (v - cy) * Z / fydiff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex 385fb328d..d54383062 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -121,20 +121,30 @@ def _compute_shear_matrix(shear: torch.Tensor) -> torch.Tensor:# based on:# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L166-def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',- align_corners: bool = False) -> torch.Tensor:+def affine(tensor: torch.Tensor, matrix: torch.Tensor,+ mode: str = 'bilinear', padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> torch.Tensor:r"""Apply an affine transformation to the image.Args:tensor (torch.Tensor): The image tensor to be warped in shapes of:math:`(H, W)`, :math:`(D, H, W)` and :math:`(B, C, H, W)`.matrix (torch.Tensor): The 2x3 affine transformation matrix.- mode (str): 'bilinear' | 'nearest'- align_corners(bool): interpolation flag. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.Returns:- torch.Tensor: The warped image.+ torch.Tensor: The warped image with the same shape as the input.++ Example:+ >>> img = torch.rand(1, 2, 3, 5)+ >>> aff = torch.eye(2, 3)[None]+ >>> out = affine(img, aff)+ >>> print(out.shape)+ torch.Size([1, 2, 3, 5])"""# warping needs data in the shape of BCHWis_unbatched: bool = tensor.ndimension() == 3@@ -148,8 +158,8 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',# warp the input tensorheight: int = tensor.shape[-2]width: int = tensor.shape[-1]- warped: torch.Tensor = warp_affine(tensor, matrix, (height, width), mode,- align_corners=align_corners)+ warped: torch.Tensor = warp_affine(tensor, matrix, (height, width),+ mode, padding_mode, align_corners)# return in the original shapeif is_unbatched:@@ -158,20 +168,30 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',return warped-def affine3d(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',+def affine3d(tensor: torch.Tensor, matrix: torch.Tensor,+ mode: str = 'bilinear', padding_mode: str = 'zeros',align_corners: bool = False) -> torch.Tensor:r"""Apply an affine transformation to the 3d volume.Args:tensor (torch.Tensor): The image tensor to be warped in shapes of:math:`(D, H, W)`, :math:`(C, D, H, W)` and :math:`(B, C, D, H, W)`.- matrix (torch.Tensor): The 3x4 affine transformation matrix.- mode (str): 'bilinear' | 'nearest'- align_corners(bool): interpolation flag. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ matrix (torch.Tensor): The affine transformation matrix with shape :math:`(B, 3, 4)`.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: False.Returns:torch.Tensor: The warped image.++ Example:+ >>> img = torch.rand(1, 2, 4, 3, 5)+ >>> aff = torch.eye(3, 4)[None]+ >>> out = affine3d(img, aff)+ >>> print(out.shape)+ torch.Size([1, 2, 4, 3, 5])"""# warping needs data in the shape of BCDHWis_unbatched: bool = tensor.ndimension() == 4@@ -186,8 +206,8 @@ def affine3d(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',depth: int = tensor.shape[-3]height: int = tensor.shape[-2]width: int = tensor.shape[-1]- warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode,- align_corners=align_corners)+ warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width),+ mode, padding_mode, align_corners)# return in the original shapeif is_unbatched:@@ -200,21 +220,46 @@ def affine3d(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L185def rotate(tensor: torch.Tensor, angle: torch.Tensor,- center: Union[None, torch.Tensor] = None, mode: str = 'bilinear',- align_corners: bool = False) -> torch.Tensor:- r"""Rotate the image anti-clockwise about the centre.+ center: Union[None, torch.Tensor] = None,+ mode: str = 'bilinear', padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> torch.Tensor:+ r"""Rotate the tensor anti-clockwise about the centre.- See :class:`~kornia.Rotate` for details.+ Args:+ tensor (torch.Tensor): The image tensor to be warped in shapes of :math:`(B, C, H, W)`.+ angle (torch.Tensor): The angle through which to rotate. The tensor+ must have a shape of (B), where B is batch size.+ center (torch.Tensor): The center through which to rotate. The tensor+ must have a shape of (B, 2), where B is batch size and last+ dimension contains cx and cy.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.++ Returns:+ torch.Tensor: The rotated tensor with shape as input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> angle = torch.tensor([90.])+ >>> out = rotate(img, angle)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""- if not torch.is_tensor(tensor):+ if not isinstance(tensor, torch.Tensor):raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))- if not torch.is_tensor(angle):++ if not isinstance(angle, torch.Tensor):raise TypeError("Input angle type is not a torch.Tensor. Got {}".format(type(angle)))- if center is not None and not torch.is_tensor(center):++ if center is not None and not isinstance(center, torch.Tensor):raise TypeError("Input center type is not a torch.Tensor. Got {}".format(type(center)))+if len(tensor.shape) not in (3, 4,):raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. ""Got: {}".format(tensor.shape))@@ -230,28 +275,53 @@ def rotate(tensor: torch.Tensor, angle: torch.Tensor,rotation_matrix: torch.Tensor = _compute_rotation_matrix(angle, center)# warp using the affine transform- return affine(tensor, rotation_matrix[..., :2, :3], mode, align_corners)+ return affine(tensor, rotation_matrix[..., :2, :3], mode, padding_mode, align_corners)-def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor,- center: Union[None, torch.Tensor] = None, mode: str = 'bilinear',+def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor,+ pitch: torch.Tensor, roll: torch.Tensor,+ center: Union[None, torch.Tensor] = None,+ mode: str = 'bilinear', padding_mode: str = 'zeros',align_corners: bool = False) -> torch.Tensor:- r"""Rotate the image anti-clockwise about the centre.+ r"""Rotate 3D the tensor anti-clockwise about the centre.++ Args:+ tensor (torch.Tensor): The image tensor to be warped in shapes of :math:`(B, C, D, H, W)`.+ yaw(torch.Tensor): The yaw angle through which to rotate. The tensor+ must have a shape of (B), where B is batch size.+ pitch (torch.Tensor): The pitch angle through which to rotate. The tensor+ must have a shape of (B), where B is batch size.+ roll (torch.Tensor): The roll angle through which to rotate. The tensor+ must have a shape of (B), where B is batch size.+ center (torch.Tensor): The center through which to rotate. The tensor+ must have a shape of (B, 2), where B is batch size and last+ dimension contains cx and cy.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: False.- See :class:`~kornia.Rotate` for details.+ Returns:+ torch.Tensor: The rotated tensor with shape as input."""- if not torch.is_tensor(tensor):+ if not isinstance(tensor, torch.Tensor):raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))- if not torch.is_tensor(yaw):++ if not isinstance(yaw, torch.Tensor):raise TypeError("yaw is not a torch.Tensor. Got {}".format(type(yaw)))- if not torch.is_tensor(pitch):++ if not isinstance(pitch, torch.Tensor):raise TypeError("pitch is not a torch.Tensor. Got {}".format(type(pitch)))- if not torch.is_tensor(roll):++ if not isinstance(roll, torch.Tensor):raise TypeError("roll is not a torch.Tensor. Got {}".format(type(roll)))- if center is not None and not torch.is_tensor(center):++ if center is not None and not isinstance(center, torch.Tensor):raise TypeError("Input center type is not a torch.Tensor. Got {}".format(type(center)))+if len(tensor.shape) not in (4, 5,):raise ValueError("Invalid tensor shape, we expect CxDxHxW or BxCxDxHxW. ""Got: {}".format(tensor.shape))@@ -269,21 +339,43 @@ def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor, pitch: torch.Tensor, roll:rotation_matrix: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center)# warp using the affine transform- return affine3d(tensor, rotation_matrix[..., :3, :4], mode, align_corners)+ return affine3d(tensor, rotation_matrix[..., :3, :4], mode, padding_mode, align_corners)def translate(tensor: torch.Tensor, translation: torch.Tensor,- align_corners: bool = False) -> torch.Tensor:+ mode: str = 'bilinear', padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> torch.Tensor:r"""Translate the tensor in pixel units.- See :class:`~kornia.Translate` for details.+ Args:+ tensor (torch.Tensor): The image tensor to be warped in shapes of :math:`(B, C, H, W)`.+ translation (torch.Tensor): tensor containing the amount of pixels to+ translate in the x and y direction. The tensor must have a shape of+ (B, 2), where B is batch size, last dimension contains dx dy.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.++ Returns:+ torch.Tensor: The translated tensor with shape as input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> translation = torch.tensor([[1., 0.]])+ >>> out = translate(img, translation)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""- if not torch.is_tensor(tensor):+ if not isinstance(tensor, torch.Tensor):raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))- if not torch.is_tensor(translation):++ if not isinstance(translation, torch.Tensor):raise TypeError("Input translation type is not a torch.Tensor. Got {}".format(type(translation)))+if len(tensor.shape) not in (3, 4,):raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. ""Got: {}".format(tensor.shape))@@ -292,20 +384,45 @@ def translate(tensor: torch.Tensor, translation: torch.Tensor,translation_matrix: torch.Tensor = _compute_translation_matrix(translation)# warp using the affine transform- return affine(tensor, translation_matrix[..., :2, :3], align_corners=align_corners)+ return affine(tensor, translation_matrix[..., :2, :3], mode, padding_mode, align_corners)def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,center: Union[None, torch.Tensor] = None,- align_corners: bool = False) -> torch.Tensor:- r"""Scales the input image.+ mode: str = 'bilinear', padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> torch.Tensor:+ r"""Scale the tensor by a factor.- See :class:`~kornia.Scale` for details.+ Args:+ tensor (torch.Tensor): The image tensor to be warped in shapes of :math:`(B, C, H, W)`.+ scale_factor (torch.Tensor): The scale factor apply. The tensor+ must have a shape of (B) or (B, 2), where B is batch size.+ If (B), isotropic scaling will perform.+ If (B, 2), x-y-direction specific scaling will perform.+ center (torch.Tensor): The center through which to scale. The tensor+ must have a shape of (B, 2), where B is batch size and last+ dimension contains cx and cy.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.++ Returns:+ torch.Tensor: The scaled tensor with the same shape as the input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> scale_factor = torch.tensor([[2., 2.]])+ >>> out = scale(img, scale_factor)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""- if not torch.is_tensor(tensor):+ if not isinstance(tensor, torch.Tensor):raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))- if not torch.is_tensor(scale_factor):++ if not isinstance(scale_factor, torch.Tensor):raise TypeError("Input scale_factor type is not a torch.Tensor. Got {}".format(type(scale_factor)))@@ -324,20 +441,43 @@ def scale(tensor: torch.Tensor, scale_factor: torch.Tensor,scaling_matrix: torch.Tensor = _compute_scaling_matrix(scale_factor, center)# warp using the affine transform- return affine(tensor, scaling_matrix[..., :2, :3], align_corners=align_corners)+ return affine(tensor, scaling_matrix[..., :2, :3], mode, padding_mode, align_corners)-def shear(tensor: torch.Tensor, shear: torch.Tensor, align_corners: bool = False) -> torch.Tensor:+def shear(tensor: torch.Tensor, shear: torch.Tensor,+ mode: str = 'bilinear', padding_mode: str = 'zeros',+ align_corners: bool = False) -> torch.Tensor:r"""Shear the tensor.- See :class:`~kornia.Shear` for details.+ Args:+ tensor (torch.Tensor): The image tensor to be skewed with shape of :math:`(B, C, H, W)`.+ shear (torch.Tensor): tensor containing the angle to shear+ in the x and y direction. The tensor must have a shape of+ (B, 2), where B is batch size, last dimension contains shx shy.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.++ Returns:+ torch.Tensor: The skewed tensor with shape same as the input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> shear_factor = torch.tensor([[0.5, 0.0]])+ >>> out = shear(img, shear_factor)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""- if not torch.is_tensor(tensor):+ if not isinstance(tensor, torch.Tensor):raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))- if not torch.is_tensor(shear):++ if not isinstance(shear, torch.Tensor):raise TypeError("Input shear type is not a torch.Tensor. Got {}".format(type(shear)))+if len(tensor.shape) not in (3, 4,):raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. ""Got: {}".format(tensor.shape))@@ -346,7 +486,7 @@ def shear(tensor: torch.Tensor, shear: torch.Tensor, align_corners: bool = Falseshear_matrix: torch.Tensor = _compute_shear_matrix(shear)# warp using the affine transform- return affine(tensor, shear_matrix[..., :2, :3], align_corners=align_corners)+ return affine(tensor, shear_matrix[..., :2, :3], mode, padding_mode, align_corners)def _side_to_image_size(@@ -365,13 +505,33 @@ def _side_to_image_size(def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]],- interpolation: str = 'bilinear', align_corners: bool = False,+ interpolation: str = 'bilinear', align_corners: Optional[bool] = None,side: str = "short") -> torch.Tensor:r"""Resize the input torch.Tensor to the given size.- See :class:`~kornia.Resize` for details.+ Args:+ tensor (torch.Tensor): The image tensor to be skewed with shape of :math:`(B, C, H, W)`.+ size (int, tuple(int, int)): Desired output size. If size is a sequence like (h, w),+ output size will be matched to this. If size is an int, smaller edge of the image will+ be matched to this number. i.e, if height > width, then image will be rescaled+ to (size * height / width, size)+ interpolation (str): algorithm used for upsampling: 'nearest' | 'linear' | 'bilinear' |+ 'bicubic' | 'trilinear' | 'area'. Default: 'bilinear'.+ align_corners(bool): interpolation flag. Default: None. See+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ side (str): Corresponding side if ``size`` is an integer. Can be one of ``"short"``, ``"long"``, ``"vert"``,+ or ``"horz"``. Defaults to ``"short"``.++ Returns:+ torch.Tensor: The resized tensor with the shape as the specified size.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> out = resize(img, (6, 8))+ >>> print(out.shape)+ torch.Size([1, 3, 6, 8])"""- if not torch.is_tensor(input):+ if not isinstance(input, torch.Tensor):raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(input)))@@ -386,6 +546,42 @@ def resize(input: torch.Tensor, size: Union[int, Tuple[int, int]],return torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)+def rescale(+ input: torch.Tensor,+ factor: Union[float, Tuple[float, float]],+ interpolation: str = "bilinear",+ align_corners: Optional[bool] = None,+) -> torch.Tensor:+ r"""Rescale the input torch.Tensor with the given factor.++ Args:+ input(torch.Tensor): The image tensor to be scale with shape of :math:`(B, C, H, W)`.+ interpolation (str): algorithm used for upsampling: 'nearest' | 'linear' | 'bilinear' |+ 'bicubic' | 'trilinear' | 'area'. Default: 'bilinear'.+ align_corners(bool): interpolation flag. Default: None. See+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ side (str): Corresponding side if ``size`` is an integer. Can be one of ``"short"``, ``"long"``, ``"vert"``,+ or ``"horz"``. Defaults to ``"short"``.++ Returns:+ torch.Tensor: The rescaled tensor with the shape as the specified size.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> out = rescale(img, (2, 3))+ >>> print(out.shape)+ torch.Size([1, 3, 8, 12])+ """+ if isinstance(factor, float):+ factor_vert = factor_horz = factor+ else:+ factor_vert, factor_horz = factor++ height, width = input.size()[-2:]+ size = (int(height * factor_vert), int(width * factor_horz))+ return resize(input, size, interpolation=interpolation, align_corners=align_corners)++class Resize(nn.Module):r"""Resize the input torch.Tensor to the given size.@@ -396,24 +592,30 @@ class Resize(nn.Module):to (size * height / width, size)interpolation (str): algorithm used for upsampling: 'nearest' | 'linear' | 'bilinear' |'bicubic' | 'trilinear' | 'area'. Default: 'bilinear'.- align_corners(bool): interpolation flag. Default: False. See+ align_corners(bool): interpolation flag. Default: None. Seehttps://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detailside (str): Corresponding side if ``size`` is an integer. Can be one of ``"short"``, ``"long"``, ``"vert"``,or ``"horz"``. Defaults to ``"short"``.Returns:- torch.Tensor: The resized tensor.+ torch.Tensor: The resized tensor with the shape of the given size.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> out = Resize((6, 8))(img)+ >>> print(out.shape)+ torch.Size([1, 3, 6, 8])"""def __init__(self, size: Union[int, Tuple[int, int]], interpolation: str = 'bilinear',- align_corners: bool = False, side: str = "short") -> None:+ align_corners: Optional[bool] = None, side: str = "short") -> None:super(Resize, self).__init__()self.size: Union[int, Tuple[int, int]] = sizeself.interpolation: str = interpolation- self.align_corners: bool = align_corners- self.side = side+ self.align_corners: Optional[bool] = align_corners+ self.side: str = side- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore+ def forward(self, input: torch.Tensor) -> torch.Tensor:return resize(input, self.size, self.interpolation, align_corners=self.align_corners, side=self.side)@@ -432,14 +634,24 @@ class Affine(nn.Module):center (torch.Tensor, optional): Transformation center in pixels. The tensor must have a shape of (B, 2), whereB is the batch size and the last dimension contains cx and cy. Defaults to the center of image to betransformed.- align_corners (bool): interpolation flag. Default: False. See :func:`~torch.nn.functional.interpolate` for- details.+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.Raises:RuntimeError: If not one of ``angle``, ``translation``, ``scale_factor``, or ``shear`` is set.Returns:- torch.Tensor: The transformed tensor.+ torch.Tensor: The transformed tensor with same shape as input.++ Example:+ >>> img = torch.rand(1, 2, 3, 5)+ >>> angle = 90. * torch.rand(1)+ >>> out = Affine(angle)(img)+ >>> print(out.shape)+ torch.Size([1, 2, 3, 5])"""def __init__(@@ -449,7 +661,9 @@ class Affine(nn.Module):scale_factor: Optional[torch.Tensor] = None,shear: Optional[torch.Tensor] = None,center: Optional[torch.Tensor] = None,- align_corners: bool = False,+ mode: str = 'bilinear',+ padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> None:batch_sizes = [arg.size()[0] for arg in (angle, translation, scale_factor, shear) if arg is not None]if not batch_sizes:@@ -482,6 +696,8 @@ class Affine(nn.Module):self.shear = shearself.center = center+ self.mode = mode+ self.padding_mode = padding_modeself.align_corners = align_cornersdef forward(self, input: torch.Tensor) -> torch.Tensor:@@ -496,27 +712,7 @@ class Affine(nn.Module):center = self.centermatrix = get_affine_matrix2d(self.translation, center, self.scale_factor, -self.angle, sx=sx, sy=sy)- return affine(input, matrix[..., :2, :3], align_corners=self.align_corners)---def rescale(- input: torch.Tensor,- factor: Union[float, Tuple[float, float]],- interpolation: str = "bilinear",- align_corners: bool = False,-) -> torch.Tensor:- r"""Rescale the input torch.Tensor with the given factor.-- See :class:`~kornia.Rescale` for details.- """- if isinstance(factor, float):- factor_vert = factor_horz = factor- else:- factor_vert, factor_horz = factor-- height, width = input.size()[-2:]- size = (int(height * factor_vert), int(width * factor_horz))- return resize(input, size, interpolation=interpolation, align_corners=align_corners)+ return affine(input, matrix[..., :2, :3], self.mode, self.padding_mode, self.align_corners)class Rescale(nn.Module):@@ -527,20 +723,29 @@ class Rescale(nn.Module):for both the x- and y-direction.interpolation (str): Algorithm used for upsampling. Can be one of ``"nearest"``, ``"linear"``, ``"bilinear"``,``"bicubic"``, ``"trilinear"``, or ``"area"``. Default: ``"bilinear"``.- align_corners(bool): Interpolation flag. Default: False. See :func:`~torch.nn.functional.interpolate` for+ align_corners(bool): Interpolation flag. Default: None. See :func:`~torch.nn.functional.interpolate` fordetails.Returns:- torch.Tensor: The rescaled tensor.+ torch.Tensor: The rescaled tensor with the shape according to the given factor.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> out = Rescale((2, 3))(img)+ >>> print(out.shape)+ torch.Size([1, 3, 8, 12])"""def __init__(- self, factor: Union[float, Tuple[float, float]], interpolation: str = "bilinear", align_corners: bool = False+ self,+ factor: Union[float, Tuple[float, float]],+ interpolation: str = "bilinear",+ align_corners: Optional[bool] = None) -> None:super().__init__()self.factor: Union[float, Tuple[float, float]] = factorself.interpolation: str = interpolation- self.align_corners: bool = align_corners+ self.align_corners: Optional[bool] = align_cornersdef forward(self, input: torch.Tensor) -> torch.Tensor:return rescale(input, self.factor, self.interpolation, align_corners=self.align_corners)@@ -555,22 +760,37 @@ class Rotate(nn.Module):center (torch.Tensor): The center through which to rotate. The tensormust have a shape of (B, 2), where B is batch size and lastdimension contains cx and cy.- align_corners(bool): interpolation flag. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.+Returns:- torch.Tensor: The rotated tensor.+ torch.Tensor: The rotated tensor with the same shape as the input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> angle = torch.tensor([90.])+ >>> out = Rotate(angle)(img)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""def __init__(self, angle: torch.Tensor,center: Union[None, torch.Tensor] = None,- align_corners: bool = False) -> None:+ mode: str = 'bilinear',+ padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> None:super(Rotate, self).__init__()self.angle: torch.Tensor = angleself.center: Union[None, torch.Tensor] = center- self.align_corners: bool = align_corners+ self.mode: str = mode+ self.padding_mode: str = padding_mode+ self.align_corners: Optional[bool] = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- return rotate(input, self.angle, self.center, align_corners=self.align_corners)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return rotate(input, self.angle, self.center, self.mode, self.padding_mode, self.align_corners)class Translate(nn.Module):@@ -580,19 +800,35 @@ class Translate(nn.Module):translation (torch.Tensor): tensor containing the amount of pixels totranslate in the x and y direction. The tensor must have a shape of(B, 2), where B is batch size, last dimension contains dx dy.- align_corners(bool): interpolation flag. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.+Returns:- torch.Tensor: The translated tensor.+ torch.Tensor: The translated tensor with the same shape as the input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> translation = torch.tensor([[1., 0.]])+ >>> out = Translate(translation)(img)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""- def __init__(self, translation: torch.Tensor, align_corners: bool = False) -> None:+ def __init__(self, translation: torch.Tensor,+ mode: str = 'bilinear',+ padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> None:super(Translate, self).__init__()self.translation: torch.Tensor = translation- self.align_corners: bool = align_corners+ self.mode: str = mode+ self.padding_mode: str = padding_mode+ self.align_corners: Optional[bool] = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- return translate(input, self.translation, self.align_corners)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return translate(input, self.translation, self.mode, self.padding_mode, self.align_corners)class Scale(nn.Module):@@ -606,22 +842,37 @@ class Scale(nn.Module):center (torch.Tensor): The center through which to scale. The tensormust have a shape of (B, 2), where B is batch size and lastdimension contains cx and cy.- align_corners(bool): interpolation flag. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: None.+Returns:- torch.Tensor: The scaled tensor.+ torch.Tensor: The scaled tensor with the same shape as the input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> scale_factor = torch.tensor([[2., 2.]])+ >>> out = Scale(scale_factor)(img)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""def __init__(self, scale_factor: torch.Tensor,center: Union[None, torch.Tensor] = None,- align_corners: bool = False) -> None:+ mode: str = 'bilinear',+ padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> None:super(Scale, self).__init__()self.scale_factor: torch.Tensor = scale_factorself.center: Union[None, torch.Tensor] = center- self.align_corners: bool = align_corners+ self.mode: str = mode+ self.padding_mode: str = padding_mode+ self.align_corners: Optional[bool] = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- return scale(input, self.scale_factor, self.center, self.align_corners)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return scale(input, self.scale_factor, self.center, self.mode, self.padding_mode, self.align_corners)class Shear(nn.Module):@@ -632,17 +883,32 @@ class Shear(nn.Module):shear (torch.Tensor): tensor containing the angle to shearin the x and y direction. The tensor must have a shape of(B, 2), where B is batch size, last dimension contains shx shy.- align_corners(bool): interpolation flag. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners(bool, optional): interpolation flag. Default: False.+Returns:- torch.Tensor: The skewed tensor.+ torch.Tensor: The skewed tensor with the same shape as the input.++ Example:+ >>> img = torch.rand(1, 3, 4, 4)+ >>> shear_factor = torch.tensor([[0.5, 0.0]])+ >>> out = Shear(shear_factor)(img)+ >>> print(out.shape)+ torch.Size([1, 3, 4, 4])"""def __init__(self, shear: torch.Tensor,+ mode: str = 'bilinear',+ padding_mode: str = 'zeros',align_corners: bool = False) -> None:super(Shear, self).__init__()self.shear: torch.Tensor = shear+ self.mode: str = mode+ self.padding_mode: str = padding_modeself.align_corners: bool = align_corners- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore- return shear(input, self.shear, self.align_corners)+ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return shear(input, self.shear, self.mode, self.padding_mode, self.align_corners)diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex e1db6babb..990b4e03b 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -67,8 +67,11 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],torch.Size([1, 4, 4, 2]).. note::- See a working example `here <https://kornia.readthedocs.io/en/latest/- tutorials/warp_perspective.html>`_.+ This function is often used in conjuntion with :func:`get_perspective_transform`.++ .. note::+ See a working example `here <https://kornia.readthedocs.io/en/latest/+ tutorials/warp_perspective.html>`_."""if not isinstance(src, torch.Tensor):raise TypeError("Input src type is not a torch.Tensor. Got {}"@@ -149,6 +152,10 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,>>> print(out.shape)torch.Size([1, 4, 4, 2])+ .. note::+ This function is often used in conjuntion with :func:`get_rotation_matrix2d`,+ :func:`get_shear_matrix2d`, :func:`get_affine_matrix2d`, :func:`invert_affine_transform`.+.. note::See a working example `here <https://kornia.readthedocs.io/en/latest/tutorials/warp_affine.html>`__.@@ -225,29 +232,32 @@ def get_perspective_transform(src, dst):dst(i) = (x_{i}^{'},y_{i}^{'}), src(i) = (x_{i}, y_{i}), i = 0,1,2,3Args:- src (Tensor): coordinates of quadrangle vertices in the source image.- dst (Tensor): coordinates of the corresponding quadrangle vertices in- the destination image.+ src (torch.Tensor): coordinates of quadrangle vertices in the source image with shape :math:`(B, 4, 2)`.+ dst (torch.Tensor): coordinates of the corresponding quadrangle vertices in+ the destination image with shape :math:`(B, 4, 2)`.Returns:- Tensor: the perspective transformation.+ torch.Tensor: the perspective transformation with shape :math:`(B, 3, 3)`.- Shape:- - Input: :math:`(B, 4, 2)` and :math:`(B, 4, 2)`- - Output: :math:`(B, 3, 3)`+ .. note::+ This function is often used in conjuntion with :func:`warp_perspective`."""if not isinstance(src, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(src)))+if not isinstance(dst, torch.Tensor):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(dst)))+if not src.shape[-2:] == (4, 2):raise ValueError("Inputs must be a Bx4x2 tensor. Got {}".format(src.shape))+if not src.shape == dst.shape:raise ValueError("Inputs must have the same shape. Got {}".format(dst.shape))+if not (src.shape[0] == dst.shape[0]):raise ValueError("Inputs must have same batch size dimension. Expect {} but got {}".format(src.shape, dst.shape))@@ -278,6 +288,7 @@ def get_perspective_transform(src, dst):batch_size = src.shape[0]M = torch.ones(batch_size, 9, device=src.device, dtype=src.dtype)M[..., :8] = torch.squeeze(X, dim=-1)+return M.view(-1, 3, 3) # Bx3x3@@ -346,18 +357,14 @@ def get_rotation_matrix2d(If this is not the target, adjust the shift.Args:- center (Tensor): center of the rotation in the source image.- angle (Tensor): rotation angle in degrees. Positive values mean+ center (torch.Tensor): center of the rotation in the source image with shape :math:`(B, 2)`.+ angle (torch.Tensor): rotation angle in degrees. Positive values meancounter-clockwise rotation (the coordinate origin is assumed to- be the top-left corner).- scale (Tensor): scale factor for x, y scaling with shape :math:`(B, 2)`+ be the top-left corner) with shape :math:`(B)`.+ scale (torch.Tensor): scale factor for x, y scaling with shape :math:`(B, 2)`.Returns:- Tensor: the affine matrix of 2D rotation.-- Shape:- - Input: :math:`(B, 2)`, :math:`(B)` and :math:`(B, 2)`- - Output: :math:`(B, 2, 3)`+ torch.Tensor: the affine matrix of 2D rotation with shape :math:`(B, 2, 3)`.Example:>>> center = torch.zeros(1, 2)@@ -366,36 +373,48 @@ def get_rotation_matrix2d(>>> get_rotation_matrix2d(center, angle, scale)tensor([[[ 0.7071, 0.7071, 0.0000],[-0.7071, 0.7071, 0.0000]]])++ .. note::+ This function is often used in conjuntion with :func:`warp_affine`."""if not isinstance(center, torch.Tensor):raise TypeError("Input center type is not a torch.Tensor. Got {}".format(type(center)))+if not isinstance(angle, torch.Tensor):raise TypeError("Input angle type is not a torch.Tensor. Got {}".format(type(angle)))+if not isinstance(scale, torch.Tensor):raise TypeError("Input scale type is not a torch.Tensor. Got {}".format(type(scale)))+if not (len(center.shape) == 2 and center.shape[1] == 2):raise ValueError("Input center must be a Bx2 tensor. Got {}".format(center.shape))+if not len(angle.shape) == 1:raise ValueError("Input angle must be a B tensor. Got {}".format(angle.shape))+if not (len(scale.shape) == 2 and scale.shape[1] == 2):raise ValueError("Input scale must be a Bx2 tensor. Got {}".format(scale.shape))+if not (center.shape[0] == angle.shape[0] == scale.shape[0]):raise ValueError("Inputs must have same batch size dimension. Got center {}, angle {} and scale {}".format(center.shape, angle.shape, scale.shape))+if not (center.device == angle.device == scale.device) or not (center.dtype == angle.dtype == scale.dtype):raise ValueError("Inputs must have same device Got center ({}, {}), angle ({}, {}) and scale ({}, {})".format(center.device, center.dtype, angle.device, angle.dtype, scale.device, scale.dtype))+# convert angle and apply scalerotation_matrix: torch.Tensor = angle_to_rotation_matrix(angle)scaling_matrix: torch.Tensor = torch.zeros((2, 2), device=rotation_matrix.device, dtype=rotation_matrix.dtype).fill_diagonal_(1).repeat(rotation_matrix.size(0), 1, 1)+scaling_matrix = scaling_matrix * scale.unsqueeze(dim=2).repeat(1, 1, 2)scaled_rotation: torch.Tensor = rotation_matrix @ scaling_matrixalpha: torch.Tensor = scaled_rotation[:, 0, 0]@@ -410,15 +429,16 @@ def get_rotation_matrix2d(one = torch.tensor(1., device=center.device, dtype=center.dtype)M: torch.Tensor = torch.zeros(batch_size, 2, 3, device=center.device, dtype=center.dtype)+M[..., 0:2, 0:2] = scaled_rotationM[..., 0, 2] = (one - alpha) * x - beta * yM[..., 1, 2] = beta * x + (one - alpha) * yreturn M-def remap(tensor: torch.Tensor, map_x: torch.Tensor,- map_y: torch.Tensor,- align_corners: bool = False) -> torch.Tensor:+def remap(tensor: torch.Tensor, map_x: torch.Tensor, map_y: torch.Tensor,+ mode: str = 'bilinear', padding_mode: str = 'zeros',+ align_corners: Optional[bool] = None) -> torch.Tensor:r"""Applies a generic geometrical transformation to a tensor.The function remap transforms the source tensor using the specified map:@@ -433,11 +453,14 @@ def remap(tensor: torch.Tensor, map_x: torch.Tensor,The tensor must be in the shape of (B, H, W).map_y (torch.Tensor): the flow in the y-direction in pixel coordinates.The tensor must be in the shape of (B, H, W).- align_corners(bool): interpolation flag. Default: False. See- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners (bool, optional): mode for grid_generation. Default: None.Returns:- torch.Tensor: the warped tensor.+ torch.Tensor: the warped tensor with same shape as the input grid maps.Example:>>> from kornia.utils import create_meshgrid@@ -448,16 +471,21 @@ def remap(tensor: torch.Tensor, map_x: torch.Tensor,tensor([[[[1., 0.],[0., 0.]]]])+ .. note::+ This function is often used in conjuntion with :func:`create_meshgrid`."""if not isinstance(tensor, torch.Tensor):raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(tensor)))+if not isinstance(map_x, torch.Tensor):raise TypeError("Input map_x type is not a torch.Tensor. Got {}".format(type(map_x)))+if not isinstance(map_y, torch.Tensor):raise TypeError("Input map_y type is not a torch.Tensor. Got {}".format(type(map_y)))+if not tensor.shape[-2:] == map_x.shape[-2:] == map_y.shape[-2:]:raise ValueError("Inputs last two dimensions must match.")@@ -472,7 +500,9 @@ def remap(tensor: torch.Tensor, map_x: torch.Tensor,map_xy_norm = map_xy_norm.expand(batch_size, -1, -1, -1)# warp ans return- tensor_warped: torch.Tensor = F.grid_sample(tensor, map_xy_norm, align_corners=align_corners) # type: ignore+ tensor_warped: torch.Tensor = F.grid_sample(+ tensor, map_xy_norm, mode=mode, padding_mode=padding_mode, align_corners=align_corners+ )return tensor_warped@@ -492,19 +522,25 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:Args:matrix (torch.Tensor): original affine transform. The tensor must be- in the shape of (B, 2, 3).+ in the shape of :math:`(B, 2, 3)`.Return:- torch.Tensor: the reverse affine transform.+ torch.Tensor: the reverse affine transform with shape :math:`(B, 2, 3)`.++ .. note::+ This function is often used in conjuntion with :func:`warp_affine`."""if not isinstance(matrix, torch.Tensor):raise TypeError("Input matrix type is not a torch.Tensor. Got {}".format(type(matrix)))+if not (len(matrix.shape) == 3 and matrix.shape[-2:] == (2, 3)):raise ValueError("Input matrix must be a Bx2x3 tensor. Got {}".format(matrix.shape))+matrix_tmp: torch.Tensor = convert_affinematrix_to_homography(matrix)matrix_inv: torch.Tensor = torch.inverse(matrix_tmp)+return matrix_inv[..., :2, :3]@@ -516,21 +552,26 @@ def get_affine_matrix2d(translations: torch.Tensor, center: torch.Tensor, scale:translations (torch.Tensor): tensor containing the translation vector with shape :math:`(B, 2)`.center (torch.Tensor): tensor containing the center vector with shape :math:`(B, 2)`.scale (torch.Tensor): tensor containing the scale factor with shape :math:`(B, 2)`.- angle: (torch.Tensor): tensor of angles in degrees :math:`(B)`.+ angle (torch.Tensor): tensor of angles in degrees :math:`(B)`.sx (torch.Tensor, optional): tensor containing the shear factor in the x-direction with shape :math:`(B)`.sy (torch.Tensor, optional): tensor containing the shear factor in the y-direction with shape :math:`(B)`.Returns:torch.Tensor: the affine transformation matrix :math:`(B, 3, 3)`.++ .. note::+ This function is often used in conjuntion with :func:`warp_affine`, :func:`warp_perspective`."""transform: torch.Tensor = get_rotation_matrix2d(center, -angle, scale)transform[..., 2] += translations # tx/ty+# pad transform to get Bx3x3transform_h = convert_affinematrix_to_homography(transform)if any([s is not None for s in [sx, sy]]):shear_mat = get_shear_matrix2d(center, sx, sy)transform_h = transform_h @ shear_mat+return transform_h@@ -551,7 +592,7 @@ def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None,sy (torch.Tensor, optional): shearing degree along y axis.Returns:- torch.Tensor: params to be passed to the affine transformation.+ torch.Tensor: params to be passed to the affine transformation with shape :math:`(B, 3, 3)`.Examples:>>> rng = torch.manual_seed(0)@@ -563,6 +604,9 @@ def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None,tensor([[[ 1.0000, -33.5468, 0.0000],[ -0.0000, 1.0000, 0.0000],[ 0.0000, 0.0000, 1.0000]]])++ .. note::+ This function is often used in conjuntion with :func:`warp_affine`, :func:`warp_perspective`."""sx = torch.tensor([0.]).repeat(center.size(0)) if sx is None else sxsy = torch.tensor([0.]).repeat(center.size(0)) if sy is None else sy@@ -577,6 +621,7 @@ def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None,ones, -sx_tan, sx_tan * y, # type: ignore # noqa: E241-sy_tan, ones + sx_tan * sy_tan, sy_tan * (sx_tan * y + x) # noqa: E241], dim=-1).view(-1, 2, 3)+shear_mat = convert_affinematrix_to_homography(shear_mat)return shear_mat@@ -602,15 +647,20 @@ def get_affine_matrix3d(translations: torch.Tensor, center: torch.Tensor, scale:szy (torch.Tensor, optional): tensor containing the shear factor in the zy-direction with shape :math:`(B)`.Returns:- torch.Tensor: the 3d affine transformation matrix :math:`(B, 4, 4)`.+ torch.Tensor: the 3d affine transformation matrix :math:`(B, 3, 3)`.++ .. note::+ This function is often used in conjuntion with :func:`warp_perspective`."""transform: torch.Tensor = get_projective_transform(center, -angles, scale)transform[..., 3] += translations # tx/ty/tz+# pad transform to get Bx3x3transform_h = convert_affinematrix_to_homography3d(transform)if any([s is not None for s in [sxy, sxz, syx, syz, szx, szy]]):shear_mat = get_shear_matrix3d(center, sxy, sxz, syx, syz, szx, szy)transform_h = transform_h @ shear_mat+return transform_h@@ -663,6 +713,9 @@ def get_shear_matrix3d([-33.5468, 49.2039, 0.0000, 0.0000],[ 0.3022, -1.0729, 1.0000, 0.0000],[ 0.0000, 0.0000, 0.0000, 1.0000]]])++ .. note::+ This function is often used in conjuntion with :func:`warp_perspective3d`."""sxy = torch.tensor([0.]).repeat(center.size(0)) if sxy is None else sxysxz = torch.tensor([0.]).repeat(center.size(0)) if sxz is None else sxz@@ -701,6 +754,7 @@ def get_shear_matrix3d(m20, m21, m22, m23], dim=-1).view(-1, 3, 4)shear_mat = convert_affinematrix_to_homography3d(shear_mat)+return shear_matdiff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.pyindex f1d132b77..a952f2a42 100644--- a/kornia/geometry/transform/projwarp.py+++ b/kornia/geometry/transform/projwarp.py@@ -40,6 +40,8 @@ def warp_affine3d(src: torch.Tensor,Returns:torch.Tensor: the warped 3d tensor with shape :math:`(B, C, D, H, W)`.+ .. note::+ This function is often used in conjuntion with :func:`get_perspective_transform3d`."""assert len(src.shape) == 5, src.shapeassert len(M.shape) == 3 and M.shape[-2:] == (3, 4), M.shape@@ -105,6 +107,8 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:Returns:torch.Tensor: the projection matrix of 3D rotation with shape :math:`(B, 3, 4)`.+ .. note::+ This function is often used in conjuntion with :func:`warp_affine3d`."""assert len(center.shape) == 2 and center.shape[-1] == 3, center.shapeassert len(angles.shape) == 2 and angles.shape[-1] == 3, angles.shape@@ -194,32 +198,36 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T\end{pmatrix}Args:- src (Tensor): coordinates of quadrangle vertices in the source image.- dst (Tensor): coordinates of the corresponding quadrangle vertices in- the destination image.+ src (torch.Tensor): coordinates of quadrangle vertices in the source image with shape :math:`(B, 8, 3)`.+ dst (torch.Tensor): coordinates of the corresponding quadrangle vertices in+ the destination image with shape :math:`(B, 8, 3)`.Returns:- Tensor: the perspective transformation.+ torch.Tensor: the perspective transformation with shape :math:`(B, 4, 4)`.- Shape:- - Input: :math:`(B, 8, 3)` and :math:`(B, 8, 3)`- - Output: :math:`(B, 4, 4)`+ .. note::+ This function is often used in conjuntion with :func:`warp_perspective3d`."""if not isinstance(src, (torch.Tensor)):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(src)))+if not isinstance(dst, (torch.Tensor)):raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(dst)))+if not src.shape[-2:] == (8, 3):raise ValueError("Inputs must be a Bx8x3 tensor. Got {}".format(src.shape))+if not src.shape == dst.shape:raise ValueError("Inputs must have the same shape. Got {}".format(dst.shape))+if not (src.shape[0] == dst.shape[0]):raise ValueError("Inputs must have same batch size dimension. Expect {} but got {}".format(src.shape, dst.shape))+assert src.device == dst.device and src.dtype == dst.dtype, (f"Expect `src` and `dst` to be in the same device (Got {src.dtype}, {dst.dtype}) "f"with the same dtype (Got {src.dtype}, {dst.dtype})."@@ -319,6 +327,8 @@ def warp_perspective3d(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, intReturns:torch.Tensor: the warped input image :math:`(B, C, D, H, W)`.+ .. note::+ This function is often used in conjuntion with :func:`get_perspective_transform3d`."""check_is_tensor(src)check_is_tensor(M)diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.pyindex d7850bf42..c7b485a78 100644--- a/kornia/geometry/transform/thin_plate_spline.py+++ b/kornia/geometry/transform/thin_plate_spline.py@@ -53,6 +53,9 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> Tup>>> points_src = torch.rand(1, 5, 2)>>> points_dst = torch.rand(1, 5, 2)>>> kernel_weights, affine_weights = get_tps_transform(points_src, points_dst)++ .. note::+ This function is often used in conjuntion with :func:`warp_points_tps`, :func:`warp_image_tps`."""if not isinstance(points_src, torch.Tensor):raise TypeError(f"Input points_src is not torch.Tensor. Got {type(points_src)}")@@ -115,6 +118,9 @@ def warp_points_tps(points_src: torch.Tensor, kernel_centers: torch.Tensor,>>> kernel_weights, affine_weights = get_tps_transform(points_src, points_dst)>>> warped = warp_points_tps(points_src, points_dst, kernel_weights, affine_weights)>>> warped_correct = torch.allclose(warped, points_dst)++ .. note::+ This function is often used in conjuntion with :func:`get_tps_transform`."""if not isinstance(points_src, torch.Tensor):raise TypeError(f"Input points_src is not torch.Tensor. Got {type(points_src)}")@@ -184,6 +190,9 @@ def warp_image_tps(image: torch.Tensor, kernel_centers: torch.Tensor, kernel_wei>>> # note that we are getting the reverse transform: dst -> src>>> kernel_weights, affine_weights = get_tps_transform(points_dst, points_src)>>> warped_image = warp_image_tps(image, points_src, kernel_weights, affine_weights)++ .. note::+ This function is often used in conjuntion with :func:`get_tps_transform`."""if not isinstance(image, torch.Tensor):raise TypeError(f"Input image is not torch.Tensor. Got {type(image)}")diff --git a/kornia/utils/draw.py b/kornia/utils/draw.pyindex 1c7fa8002..0556cfff4 100644--- a/kornia/utils/draw.py+++ b/kornia/utils/draw.py@@ -9,7 +9,8 @@ def draw_rectangle(fill: Optional[bool] = None,width: int = 1) -> torch.Tensor:- """Draws N rectangles on a batch of image tensors+ r"""Draws N rectangles on a batch of image tensors.+Args:image (torch.Tensor): is tensor of BxCxHxW.rectangle (torch.Tensor): represents number of rectangles to draw in BxNx4@@ -20,8 +21,8 @@ def draw_rectangle(fill (bool, optional): is a flag used to fill the boxes with color if True. Default: False.width (int): The line width. Default: 1. (Not implemented yet).Returns:- torch.Tensor: This operation modifies image inplace but also returns- the drawn tensor for convenience with same shape the of the input BxCxHxW.+ torch.Tensor: This operation modifies image inplace but also returns the drawn tensor for+ convenience with same shape the of the input BxCxHxW.Example:>>> img = torch.rand(2, 3, 10, 12)diff --git a/test/enhance/test_core.py b/test/enhance/test_core.pyindex 33126e513..b5de824a3 100644--- a/test/enhance/test_core.py+++ b/test/enhance/test_core.py@@ -41,7 +41,7 @@ class TestAddWeighted:op = TestAddWeighted.fcnop_script = torch.jit.script(op)- assert_allclose(op(*inputs), op_script(*inputs))+ assert_allclose(op(*inputs), op_script(*inputs), atol=1e-4, rtol=1e-4)@pytest.mark.parametrize("size", [2, 3])def test_gradcheck(self, size, device, dtype):