Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] 3D volumetric crop implementation (#689)

shijianjianf10efd5d885d
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 5df4e435d..e31d852cb 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -166,6 +166,9 @@ Set of operators to perform data augmentation on 3D image tensors and volumetric
.. autoclass:: RandomVerticalFlip3D
.. autoclass:: RandomRotation3D
.. autoclass:: RandomAffine3D
+.. autoclass:: RandomCrop3D
+.. autoclass:: CenterCrop3D
+.. autoclass:: RandomEqualize3D
Functional
----------
diff --git a/kornia/augmentation/__init__.py b/kornia/augmentation/__init__.py
index c9a9b2e5f..21135cd5f 100644
--- a/kornia/augmentation/__init__.py
+++ b/kornia/augmentation/__init__.py
@@ -26,6 +26,8 @@ from .augmentation3d import (
RandomDepthicalFlip3D,
RandomRotation3D,
RandomAffine3D,
+ RandomCrop3D,
+ CenterCrop3D,
RandomEqualize3D
)
from .mix_augmentation import (
@@ -64,5 +66,8 @@ __all__ = [
"RandomVerticalFlip3D",
"RandomHorizontalFlip3D",
"RandomRotation3D",
- "RandomAffine3D"
+ "RandomAffine3D",
+ "RandomCrop3D",
+ "CenterCrop3D",
+ "RandomEqualize3D"
]
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index c95220759..72745c8d1 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -609,7 +609,7 @@ class RandomCrop(AugmentationBase2D):
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
super(RandomCrop, self).__init__(
- p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=1.)
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p)
self.size = size
self.padding = padding
self.pad_if_needed = pad_if_needed
@@ -635,11 +635,14 @@ class RandomCrop(AugmentationBase2D):
def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
if self.padding is not None:
if isinstance(self.padding, int):
+ self.padding = cast(int, self.padding)
padding = [self.padding, self.padding, self.padding, self.padding]
elif isinstance(self.padding, tuple) and len(self.padding) == 2:
+ self.padding = cast(Tuple[int, int], self.padding)
padding = [self.padding[1], self.padding[1], self.padding[0], self.padding[0]]
elif isinstance(self.padding, tuple) and len(self.padding) == 4:
- padding = [self.padding[3], self.padding[2], self.padding[1], self.padding[0]] # type:ignore
+ self.padding = cast(Tuple[int, int, int, int], self.padding)
+ padding = [self.padding[3], self.padding[2], self.padding[1], self.padding[0]]
input = pad(input, padding, value=self.fill, mode=self.padding_mode)
if self.pad_if_needed and input.shape[-2] < self.size[0]:
@@ -660,11 +663,12 @@ class RandomCrop(AugmentationBase2D):
def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
params: Optional[Dict[str, torch.Tensor]] = None, return_transform: Optional[bool] = None
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
if type(input) == tuple:
input = (self.precrop_padding(input[0]), input[1])
else:
- input = self.precrop_padding(input) # type:ignore
+ input = cast(torch.Tensor, input)
+ input = self.precrop_padding(input)
return super().forward(input, params, return_transform)
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 735ffde35..299cf9255 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -323,17 +323,17 @@ class RandomRotation3D(AugmentationBase3D):
>>> input = torch.rand(1, 1, 3, 3, 3)
>>> aug = RandomRotation3D((15., 20., 20.), p=1.0, return_transform=True)
>>> aug(input)
- (tensor([[[[[0.4963, 0.5013, 0.2314],
- [0.1015, 0.3624, 0.4779],
- [0.2669, 0.5749, 0.4081]],
+ (tensor([[[[[0.3819, 0.4886, 0.2111],
+ [0.1196, 0.3833, 0.4722],
+ [0.3432, 0.5951, 0.4223]],
<BLANKLINE>
- [[0.4426, 0.4198, 0.2713],
- [0.2911, 0.1689, 0.4538],
- [0.3939, 0.6022, 0.6166]],
+ [[0.5553, 0.4374, 0.2780],
+ [0.2423, 0.1689, 0.4009],
+ [0.4516, 0.6376, 0.7327]],
<BLANKLINE>
- [[0.1496, 0.3740, 0.3151],
- [0.4169, 0.4803, 0.5804],
- [0.3856, 0.4253, 0.9527]]]]]), tensor([[[ 0.9722, 0.1131, -0.2049, 0.1196],
+ [[0.1605, 0.3112, 0.3673],
+ [0.4931, 0.4620, 0.5700],
+ [0.3505, 0.4685, 0.8092]]]]]), tensor([[[ 0.9722, 0.1131, -0.2049, 0.1196],
[-0.0603, 0.9669, 0.2478, -0.1545],
[ 0.2262, -0.2286, 0.9469, 0.0556],
[ 0.0000, 0.0000, 0.0000, 1.0000]]]))
@@ -374,6 +374,260 @@ class RandomRotation3D(AugmentationBase3D):
return F.apply_rotation3d(input, params, self.flags)
+class CenterCrop3D(AugmentationBase3D):
+ r"""Crops a given image tensor at the center.
+
+ Args:
+ p (float): probability of applying the transformation for the whole batch. Default value is 1.
+ size (sequence or int): Desired output size of the crop. If size is an
+ int instead of sequence like (d, h, w), a square crop (size, size, size) is
+ made.
+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ wont be concatenated.
+ align_corners(bool): interpolation flag. Default: True.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn(1, 1, 3, 3, 3)
+ >>> aug = CenterCrop3D(2, p=1.)
+ >>> aug(inputs)
+ tensor([[[[[-0.2170, 0.1856],
+ [-0.2126, -0.0129]],
+ <BLANKLINE>
+ [[-0.1957, -0.1423],
+ [-0.0310, -0.3132]]]]])
+ """
+
+ def __init__(self, size: Union[int, Tuple[int, int, int]], align_corners: bool = True,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False, p: float = 1.) -> None:
+ # same_on_batch is always True for CenterCrop
+ # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ super(CenterCrop3D, self).__init__(
+ p=1., return_transform=return_transform, same_on_batch=True, p_batch=p)
+ self.size = size
+ self.resample = Resample.get(resample)
+ self.align_corners = align_corners
+ self.flags: Dict[str, torch.Tensor] = dict(
+ interpolation=torch.tensor(self.resample.value),
+ align_corners=torch.tensor(align_corners)
+ )
+
+ def __repr__(self) -> str:
+ repr = f"size={self.size}"
+ return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ if isinstance(self.size, tuple):
+ size_param = (self.size[0], self.size[1], self.size[2])
+ elif isinstance(self.size, int):
+ size_param = (self.size, self.size, self.size)
+ else:
+ raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {self.size}.")
+ return rg.center_crop_generator3d(
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], size_param)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.compute_crop_transformation3d(input, params, self.flags)
+
+ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.apply_crop3d(input, params, self.flags)
+
+
+class RandomCrop3D(AugmentationBase3D):
+ r"""Crops random patches of a tensor image on a given size.
+
+ Args:
+ p (float): probability of applying the transformation for the whole batch. Default value is 1.0.
+ size (tuple): Desired output size of the crop, like (d, h, w).
+ padding (int or sequence, optional): Optional padding on each border of the image.
+ Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to pad
+ left, top, right, bottom, front, back borders respectively.
+ If a sequence of length 3 is provided, it is used to pad left/right,
+ top/bottom, front/back borders, respectively.
+ pad_if_needed (boolean): It will pad the image if smaller than the
+ desired size to avoid raising an exception. Since cropping is done
+ after padding, the padding seems to be done at a random offset.
+ fill: Pixel fill value for constant fill. Default is 0. If a tuple of
+ length 3, it is used to fill R, G, B channels respectively.
+ This value is only used when the padding_mode is constant.
+ padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR
+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each
+ input tensor. If ``False`` and the input is a tuple the applied transformation
+ wont be concatenated
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
+ align_corners(bool): interpolation flag. Default: True.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs = torch.randn(1, 1, 3, 3, 3)
+ >>> aug = RandomCrop3D((2, 2, 2), p=1.)
+ >>> aug(inputs)
+ tensor([[[[[-1.1258, -1.1524],
+ [-0.4339, 0.8487]],
+ <BLANKLINE>
+ [[-1.2633, 0.3500],
+ [ 0.1665, 0.8744]]]]])
+ """
+
+ def __init__(
+ self, size: Tuple[int, int, int],
+ padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None,
+ pad_if_needed: Optional[bool] = False, fill: int = 0, padding_mode: str = 'constant',
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = True, p: float = 1.0
+ ) -> None:
+ # Since PyTorch does not support ragged tensor. So cropping function happens batch-wisely.
+ super(RandomCrop3D, self).__init__(
+ p=1., return_transform=return_transform, same_on_batch=same_on_batch, p_batch=p)
+ self.size = size
+ self.padding = padding
+ self.pad_if_needed = pad_if_needed
+ self.fill = fill
+ self.padding_mode = padding_mode
+ self.resample = Resample.get(resample)
+ self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
+ self.flags: Dict[str, torch.Tensor] = dict(
+ interpolation=torch.tensor(self.resample.value),
+ align_corners=torch.tensor(align_corners)
+ )
+
+ def __repr__(self) -> str:
+ repr = (f"crop_size={self.size}, padding={self.padding}, fill={self.fill}, pad_if_needed={self.pad_if_needed}, "
+ f"padding_mode={self.padding_mode}, resample={self.resample.name}")
+ return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ return rg.random_crop_generator3d(batch_shape[0], (batch_shape[-3], batch_shape[-2], batch_shape[-1]),
+ self.size, same_on_batch=self.same_on_batch)
+
+ def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
+ if self.padding is not None:
+ if isinstance(self.padding, int):
+ padding = [self.padding, self.padding, self.padding, self.padding, self.padding, self.padding]
+ elif isinstance(self.padding, (tuple, list)) and len(self.padding) == 3:
+ padding = [
+ self.padding[0], self.padding[0],
+ self.padding[1], self.padding[1],
+ self.padding[2], self.padding[2],
+ ]
+ elif isinstance(self.padding, (tuple, list)) and len(self.padding) == 6:
+ padding = [
+ self.padding[0], self.padding[1],
+ self.padding[2], self.padding[3], # type: ignore
+ self.padding[4], self.padding[5], # type: ignore
+ ]
+ else:
+ raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {self.padding}.")
+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+
+ if self.pad_if_needed and input.shape[-3] < self.size[0]:
+ padding = [0, 0, 0, 0, self.size[0] - input.shape[-3], self.size[0] - input.shape[-3]]
+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+
+ if self.pad_if_needed and input.shape[-2] < self.size[1]:
+ padding = [0, 0, (self.size[1] - input.shape[-2]), self.size[1] - input.shape[-2], 0, 0]
+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+
+ if self.pad_if_needed and input.shape[-1] < self.size[2]:
+ padding = [self.size[2] - input.shape[-1], self.size[2] - input.shape[-1], 0, 0, 0, 0]
+ input = pad(input, padding, value=self.fill, mode=self.padding_mode)
+
+ return input
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.compute_crop_transformation3d(input, params, self.flags)
+
+ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.apply_crop3d(input, params, self.flags)
+
+ def forward(self, input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ params: Optional[Dict[str, torch.Tensor]] = None, return_transform: Optional[bool] = None
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: # type: ignore
+ if type(input) == tuple:
+ input = (self.precrop_padding(input[0]), input[1])
+ else:
+ input = self.precrop_padding(input) # type:ignore
+ return super().forward(input, params, return_transform)
+
+
+class RandomPerspective3D(AugmentationBase3D):
+ r"""Applies a random perspective transformation to an image tensor with a given probability.
+
+ Args:
+ p (float): probability of the image being perspectively transformed. Default value is 0.5.
+ distortion_scale(float): it controls the degree of distortion and ranges from 0 to 1. Default value is 0.5.
+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR.
+ return_transform (bool): if ``True`` return the matrix describing the transformation
+ applied to each. Default: False.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
+ align_corners(bool): interpolation flag. Default: False.
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> inputs= torch.tensor([[[
+ ... [[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]],
+ ... [[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]],
+ ... [[1., 0., 0.],
+ ... [0., 1., 0.],
+ ... [0., 0., 1.]]
+ ... ]]])
+ >>> aug = RandomPerspective3D(0.5, p=1., align_corners=True)
+ >>> aug(inputs)
+ tensor([[[[[0.1348, 0.2359, 0.0363],
+ [0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000]],
+ <BLANKLINE>
+ [[0.3976, 0.5507, 0.0000],
+ [0.0901, 0.3668, 0.0000],
+ [0.0000, 0.0000, 0.0000]],
+ <BLANKLINE>
+ [[0.2651, 0.4657, 0.0000],
+ [0.1390, 0.5174, 0.0000],
+ [0.0000, 0.0000, 0.0000]]]]])
+ """
+
+ def __init__(
+ self, distortion_scale: Union[torch.Tensor, float] = 0.5,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False, same_on_batch: bool = False,
+ align_corners: bool = False, p: float = 0.5
+ ) -> None:
+ super(RandomPerspective3D, self).__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch)
+ self.distortion_scale = cast(torch.Tensor, distortion_scale) \
+ if isinstance(distortion_scale, torch.Tensor) else torch.tensor(distortion_scale)
+ self.resample = Resample.get(resample)
+ self.align_corners = align_corners
+ self.flags: Dict[str, torch.Tensor] = dict(
+ interpolation=torch.tensor(self.resample.value),
+ align_corners=torch.tensor(align_corners)
+ )
+
+ def __repr__(self) -> str:
+ repr = (f"distortion_scale={self.distortion_scale}, resample={self.resample.name}, "
+ f"align_corners={self.align_corners}")
+ return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ return rg.random_perspective_generator3d(
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1],
+ self.distortion_scale, self.same_on_batch)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.compute_perspective_transformation3d(input, params)
+
+ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.apply_perspective3d(input, params, self.flags)
+
+
class RandomEqualize3D(AugmentationBase3D):
r"""Random 3D equalization of a volumetric image.
diff --git a/kornia/augmentation/functional/functional3d.py b/kornia/augmentation/functional/functional3d.py
index 02335b3f4..61fdbae83 100644
--- a/kornia/augmentation/functional/functional3d.py
+++ b/kornia/augmentation/functional/functional3d.py
@@ -2,17 +2,23 @@ from typing import Tuple, List, Union, Dict, cast, Optional
import torch
+import kornia as K
from kornia.constants import Resample, BorderType, pi
-from kornia.enhance.adjust import equalize3d
from kornia.geometry.transform.affwarp import (
_compute_rotation_matrix3d, _compute_tensor_center3d
)
-from kornia.geometry.transform.projwarp import warp_projective
+from kornia.geometry.transform.projwarp import warp_affine3d
from kornia.geometry import (
+ crop_by_boxes3d,
+ warp_perspective3d,
+ get_perspective_transform3d,
rotate3d,
get_affine_matrix3d,
deg2rad
)
+from kornia.enhance import (
+ equalize3d
+)
from .. import random_generator as rg
from ..utils import (
@@ -180,8 +186,10 @@ def apply_dflip3d(input: torch.Tensor) -> torch.Tensor:
def compute_intensity_transformation3d(input: torch.Tensor):
r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.
+
Args:
input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).
+
Returns:
torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`. Returns identity transformations.
"""
@@ -254,9 +262,9 @@ def apply_affine3d(input: torch.Tensor, params: Dict[str, torch.Tensor],
resample_name: str = Resample(flags['resample'].item()).name.lower()
align_corners: bool = cast(bool, flags['align_corners'].item())
- out_data: torch.Tensor = warp_projective(x_data, transform[:, :3, :],
- (depth, height, width), resample_name,
- align_corners=align_corners)
+ out_data: torch.Tensor = warp_affine3d(x_data, transform[:, :3, :],
+ (depth, height, width), resample_name,
+ align_corners=align_corners)
return out_data.view_as(input)
@@ -352,14 +360,126 @@ def compute_rotate_tranformation3d(input: torch.Tensor, params: Dict[str, torch.
return trans_mat
+def apply_crop3d(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Apply cropping by src bounding box and dst bounding box.
+
+ Order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['src']: The applied cropping src matrix :math: `(*, 8, 3)`.
+ - params['dst']: The applied cropping dst matrix :math: `(*, 8, 3)`.
+ flags (Dict[str, torch.Tensor]):
+ - params['interpolation']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
+
+ Returns:
+ torch.Tensor: The cropped input.
+ """
+ input = _transform_input3d(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+
+ resample_mode: str = Resample.get(flags['interpolation'].item()).name.lower() # type: ignore
+ align_corners: bool = cast(bool, flags['align_corners'].item())
+
+ return crop_by_boxes3d(
+ input, params['src'], params['dst'], resample_mode, align_corners=align_corners)
+
+
+def compute_crop_transformation3d(input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]):
+ r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['src']: The applied cropping src matrix :math: `(*, 8, 3)`.
+ - params['dst']: The applied cropping dst matrix :math: `(*, 8, 3)`.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`
+ """
+ input = _transform_input3d(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+ transform: torch.Tensor = get_perspective_transform3d(params['src'].to(input.dtype), params['dst'].to(input.dtype))
+ transform = transform.expand(input.shape[0], -1, -1).type_as(input)
+ return transform
+
+
+def apply_perspective3d(
+ input: torch.Tensor, params: Dict[str, torch.Tensor], flags: Dict[str, torch.Tensor]
+) -> torch.Tensor:
+ r"""Perform perspective transform of the given torch.Tensor or batch of tensors.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (D, H, W), (C, D, H, W), (B, C, D, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['start_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the orignal image with shape Bx8x3.
+ - params['end_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the transformed image with shape Bx8x3.
+ flags (Dict[str, torch.Tensor]):
+ - params['interpolation']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
+
+ Returns:
+ torch.Tensor: Perspectively transformed tensor.
+ """
+ input = _transform_input3d(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+
+ _, _, depth, height, width = input.shape
+
+ # compute the homography between the input points
+ transform: torch.Tensor = compute_perspective_transformation3d(input, params)
+
+ out_data: torch.Tensor = input.clone()
+
+ # apply the computed transform
+ depth, height, width = input.shape[-3:]
+ resample_name: str = Resample(flags['interpolation'].item()).name.lower()
+ align_corners: bool = cast(bool, flags['align_corners'].item())
+
+ out_data = warp_perspective3d(
+ input, transform, (depth, height, width),
+ flags=resample_name, align_corners=align_corners)
+
+ return out_data.view_as(input)
+
+
+def compute_perspective_transformation3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (D, H, W), (C, D, H, W), (B, C, D, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['start_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the orignal image with shape Bx8x3.
+ - params['end_points']: Tensor containing [top-left, top-right, bottom-right,
+ bottom-left] of the transformed image with shape Bx8x3.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`
+ """
+ input = _transform_input3d(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+ perspective_transform: torch.Tensor = get_perspective_transform3d(
+ params['start_points'], params['end_points']).type_as(input)
+
+ transform: torch.Tensor = K.eye_like(4, input)
+
+ transform = perspective_transform
+
+ return transform
+
+
def apply_equalize3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Equalize a tensor volume or a batch of tensors volumes with given random parameters.
-
Args:
input (torch.Tensor): Tensor to be transformed with shape :math:`(D, H, W)`, :math:`(C, D, H, W)`,
:math:`(*, C, D, H, W)`.
params (Dict[str, torch.Tensor]): shall be empty.
-
Returns:
torch.Tensor: The equalized input. :math:`(D, H, W)`, :math:`(C, D, H, W)`, :math:`(*, C, D, H, W)`.
"""
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index 6d7aa1535..3f9f9196e 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -170,12 +170,12 @@ def random_affine_generator(
# compute tensor ranges
if scale is not None:
_joint_range_check(cast(torch.Tensor, scale[:2]), "scale")
- scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
- if len(scale) == 4:
+ _scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
+ if len(_scale) == 4:
_joint_range_check(cast(torch.Tensor, scale[2:]), "scale_y")
- scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)
+ _scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)
else:
- scale = torch.ones((batch_size, 2))
+ _scale = torch.ones((batch_size, 2))
if translate is not None:
_joint_range_check(cast(torch.Tensor, translate), "translate")
@@ -202,7 +202,7 @@ def random_affine_generator(
return dict(translations=translations,
center=center,
- scale=scale,
+ scale=_scale,
angle=angle,
sx=sx,
sy=sy)
@@ -291,6 +291,7 @@ def random_crop_generator(
size = torch.tensor(size).repeat(batch_size, 1)
assert size.shape == torch.Size([batch_size, 2]), \
f"If `size` is a tensor, it must be shaped as (B, 2). Got {size.shape}."
+ size = size.long()
x_diff = input_size[1] - size[:, 1] + 1
y_diff = input_size[0] - size[:, 0] + 1
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 44e13e5b9..3fee737f5 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -5,6 +5,7 @@ import math
import torch
from kornia.constants import Resample, BorderType
+from kornia.geometry import bbox_generator3d
from ..utils import (
_adapted_uniform,
_tuple_range_reader,
@@ -128,3 +129,203 @@ def random_affine_generator3d(
syz=syz,
szx=szx,
szy=szy)
+
+
+def center_crop_generator3d(
+ batch_size: int,
+ depth: int,
+ height: int,
+ width: int,
+ size: Tuple[int, int, int]
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ depth (int) : depth of the image.
+ height (int) : height of the image.
+ width (int): width of the image.
+ size (tuple): Desired output size of the crop, like (d, h, w).
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ """
+ if not isinstance(size, (tuple, list,)) and len(size) == 3:
+ raise ValueError("Input size must be a tuple/list of length 3. Got {}"
+ .format(size))
+
+ # unpack input sizes
+ dst_d, dst_h, dst_w = size
+ src_d, src_h, src_w = (depth, height, width)
+
+ # compute start/end offsets
+ dst_d_half = dst_d / 2
+ dst_h_half = dst_h / 2
+ dst_w_half = dst_w / 2
+ src_d_half = src_d / 2
+ src_h_half = src_h / 2
+ src_w_half = src_w / 2
+
+ start_x = src_w_half - dst_w_half
+ start_y = src_h_half - dst_h_half
+ start_z = src_d_half - dst_d_half
+
+ end_x = start_x + dst_w - 1
+ end_y = start_y + dst_h - 1
+ end_z = start_z + dst_d - 1
+ # [x, y, z] origin
+ # top-left-front, top-right-front, bottom-right-front, bottom-left-front
+ # top-left-back, top-right-back, bottom-right-back, bottom-left-back
+ points_src: torch.Tensor = torch.tensor([[
+ [start_x, start_y, start_z],
+ [end_x, start_y, start_z],
+ [end_x, end_y, start_z],
+ [start_x, end_y, start_z],
+ [start_x, start_y, end_z],
+ [end_x, start_y, end_z],
+ [end_x, end_y, end_z],
+ [start_x, end_y, end_z],
+ ]])
+
+ # [x, y, z] destination
+ # top-left-front, top-right-front, bottom-right-front, bottom-left-front
+ # top-left-back, top-right-back, bottom-right-back, bottom-left-back
+ points_dst: torch.Tensor = torch.tensor([[
+ [0, 0, 0],
+ [dst_w - 1, 0, 0],
+ [dst_w - 1, dst_h - 1, 0],
+ [0, dst_h - 1, 0],
+ [0, 0, dst_d - 1],
+ [dst_w - 1, 0, dst_d - 1],
+ [dst_w - 1, dst_h - 1, dst_d - 1],
+ [0, dst_h - 1, dst_d - 1],
+ ]]).expand(points_src.shape[0], -1, -1)
+ return dict(src=points_src,
+ dst=points_dst)
+
+
+def random_crop_generator3d(
+ batch_size: int,
+ input_size: Tuple[int, int, int],
+ size: Union[Tuple[int, int, int], torch.Tensor],
+ resize_to: Optional[Tuple[int, int, int]] = None,
+ same_on_batch: bool = False
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```crop``` transformation for crop transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ input_size (tuple): Input image shape, like (d, h, w).
+ size (tuple): Desired size of the crop operation, like (d, h, w).
+ If tensor, it must be (B, 3).
+ resize_to (tuple): Desired output size of the crop, like (d, h, w). If None, no resize will be performed.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ """
+ if not isinstance(size, torch.Tensor):
+ size = torch.tensor(size).repeat(batch_size, 1)
+ assert size.shape == torch.Size([batch_size, 3]), \
+ f"If `size` is a tensor, it must be shaped as (B, 3). Got {size.shape}."
+
+ x_diff = input_size[2] - size[:, 2] + 1
+ y_diff = input_size[1] - size[:, 1] + 1
+ z_diff = input_size[0] - size[:, 0] + 1
+
+ if (x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any():
+ raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."
+ % (str(input_size), str(size)))
+
+ if same_on_batch:
+ # If same_on_batch, select the first then repeat.
+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch).long()
+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch).long()
+ z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch).long()
+ else:
+ x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch).long()
+ y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch).long()
+ z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch).long()
+
+ crop_src = bbox_generator3d(x_start.view(-1), y_start.view(-1), z_start.view(-1),
+ size[:, 2] - 1, size[:, 1] - 1, size[:, 0] - 1)
+
+ if resize_to is None:
+ crop_dst = bbox_generator3d(
+ torch.tensor([0] * batch_size), torch.tensor([0] * batch_size), torch.tensor([0] * batch_size),
+ size[:, 2] - 1, size[:, 1] - 1, size[:, 0] - 1)
+ else:
+ crop_dst = torch.tensor([[
+ [0, 0, 0],
+ [resize_to[-1] - 1, 0, 0],
+ [resize_to[-1] - 1, resize_to[-2] - 1, 0],
+ [0, resize_to[-2] - 1, 0],
+ [0, 0, resize_to[-3] - 1],
+ [resize_to[-1] - 1, 0, resize_to[-3] - 1],
+ [resize_to[-1] - 1, resize_to[-2] - 1, resize_to[-3] - 1],
+ [0, resize_to[-2] - 1, resize_to[-3] - 1],
+ ]]).repeat(batch_size, 1, 1)
+
+ return dict(src=crop_src,
+ dst=crop_dst)
+
+
+def random_perspective_generator3d(
+ batch_size: int,
+ depth: int,
+ height: int,
+ width: int,
+ distortion_scale: torch.Tensor,
+ same_on_batch: bool = False,
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ``perspective`` for a random perspective transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ depth (int) : depth of the image.
+ height (int) : height of the image.
+ width (int): width of the image.
+ distortion_scale (torch.Tensor): it controls the degree of distortion and ranges from 0 to 1.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False.
+
+ Returns:
+ params (Dict[str, torch.Tensor])
+ """
+ assert distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1, \
+ f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}"
+
+ start_points: torch.Tensor = torch.tensor([[
+ [0., 0, 0],
+ [width - 1, 0, 0],
+ [width - 1, height - 1, 0],
+ [0, height - 1, 0],
+ [0., 0, depth - 1],
+ [width - 1, 0, depth - 1],
+ [width - 1, height - 1, depth - 1],
+ [0, height - 1, depth - 1],
+ ]]).expand(batch_size, -1, -1)
+
+ # generate random offset not larger than half of the image
+ fx = distortion_scale * width / 2
+ fy = distortion_scale * height / 2
+ fz = distortion_scale * depth / 2
+
+ factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3)
+
+ # TODO: This line somehow breaks the gradcheck
+ rand_val: torch.Tensor = _adapted_uniform(start_points.shape, 0, 1, same_on_batch)
+
+ pts_norm = torch.tensor([[
+ [1, 1, 1],
+ [-1, 1, 1],
+ [-1, -1, 1],
+ [1, -1, 1],
+ [1, 1, -1],
+ [-1, 1, -1],
+ [-1, -1, -1],
+ [1, -1, -1],
+ ]])
+ end_points = start_points + factor * rand_val * pts_norm
+
+ return dict(start_points=start_points,
+ end_points=end_points)
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 3248d99b2..57907863b 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -7,7 +7,7 @@ from kornia.geometry.transform.imgwarp import (
warp_affine, get_rotation_matrix2d, get_affine_matrix2d
)
from kornia.geometry.transform.projwarp import (
- warp_projective, get_projective_transform
+ warp_affine3d, get_projective_transform
)
__all__ = [
@@ -185,8 +185,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_projective(tensor, matrix, (depth, height, width), mode,
- align_corners=align_corners)
+ warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode,
+ align_corners=align_corners)
# return in the original shape
if is_unbatched:
diff --git a/kornia/geometry/transform/crop/__init__.py b/kornia/geometry/transform/crop/__init__.py
new file mode 100644
index 000000000..697d9de4a
--- /dev/null
+++ b/kornia/geometry/transform/crop/__init__.py
@@ -0,0 +1,2 @@
+from .crop2d import *
+from .crop3d import *
diff --git a/kornia/geometry/transform/crop.py b/kornia/geometry/transform/crop/crop2d.py
similarity index 82%
rename from kornia/geometry/transform/crop.py
rename to kornia/geometry/transform/crop/crop2d.py
index 7a0865e06..270f84461 100644
--- a/kornia/geometry/transform/crop.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -19,22 +19,23 @@ __all__ = [
def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int],
interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
- r"""Extracts crops from the input tensor and resizes them.
+ r"""Extract crops from 2D images (4D tensor) and resize them.
Args:
- tensor (torch.Tensor): the reference tensor of shape BxCxHxW.
- boxes (torch.Tensor): a tensor containing the coordinates of the
- bounding boxes to be extracted. The tensor must have the shape
- of Bx4x2, where each box is defined in the following (clockwise)
- order: top-left, top-right, bottom-right and bottom-left. The
- coordinates must be in the x, y order.
+ tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)
+ order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.
+ The coordinates would compose a rectangle with a shape of (N1, N2).
size (Tuple[int, int]): a tuple with the height and width that will be
- used to resize the extracted patches.
+ used to resize the extracted patches.
interpolation (str): Interpolation flag. Default: 'bilinear'.
align_corners (bool): mode for grid_generation. Default: False. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details.
+
Returns:
- torch.Tensor: tensor containing the patches with shape BxN1xN2
+ torch.Tensor: tensor containing the patches with shape BxCxN1xN2.
+
Example:
>>> input = torch.tensor([[
[1., 2., 3., 4.],
@@ -52,21 +53,18 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
tensor([[[ 6.0000, 7.0000],
[ 10.0000, 11.0000]]])
"""
- 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(boxes):
+ if not isinstance(boxes, torch.Tensor):
raise TypeError("Input boxes type is not a torch.Tensor. Got {}"
.format(type(boxes)))
- if not len(tensor.shape) in (3, 4,):
- raise ValueError("Input tensor must be in the shape of CxHxW or "
- "BxCxHxW. Got {}".format(tensor.shape))
if not isinstance(size, (tuple, list,)) and len(size) == 2:
raise ValueError("Input size must be a tuple/list of length 2. Got {}"
.format(size))
+ assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
# unpack input data
- dst_h: torch.Tensor = torch.tensor(size[0])
- dst_w: torch.Tensor = torch.tensor(size[1])
+ dst_h, dst_w = size
# [x, y] origin
# top-left, top-right, bottom-right, bottom-left
@@ -87,11 +85,10 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
interpolation: str = 'bilinear',
align_corners: bool = True) -> torch.Tensor:
- r"""Crops the given tensor at the center.
+ r"""Crop the 2D images (4D tensor) at the center.
Args:
- tensor (torch.Tensor): the input tensor with shape (C, H, W) or
- (B, C, H, W).
+ tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).
size (Tuple[int, int]): a tuple with the expected height and width
of the output patch.
interpolation (str): Interpolation flag. Default: 'bilinear'.
@@ -111,17 +108,13 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
tensor([[[ 5.0000, 6.0000, 7.0000, 8.0000],
[ 9.0000, 10.0000, 11.0000, 12.0000]]])
"""
- 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 len(tensor.shape) in (3, 4,):
- raise ValueError("Input tensor must be in the shape of CxHxW or "
- "BxCxHxW. Got {}".format(tensor.shape))
-
if not isinstance(size, (tuple, list,)) and len(size) == 2:
raise ValueError("Input size must be a tuple/list of length 2. Got {}"
.format(size))
+ assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
# unpack input sizes
dst_h, dst_w = size
@@ -164,7 +157,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Tensor,
interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
- """A wrapper performs crop transform with bounding boxes.
+ """Perform crop transform on 2D images (4D tensor) by bounding boxes.
Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.
@@ -172,7 +165,7 @@ def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Te
in a batch must be rectangles with same width and height.
Args:
- tensor (torch.Tensor): the input tensor with shape (C, H, W) or (B, C, H, W).
+ tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).
src_box (torch.Tensor): a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
to be extracted. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise
order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.
@@ -211,12 +204,7 @@ def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Te
validate_bboxes(src_box)
validate_bboxes(dst_box)
- if tensor.ndimension() not in [3, 4]:
- raise TypeError("Only tensor with shape (C, H, W) and (B, C, H, W) supported. Got %s" % str(tensor.shape))
- # warping needs data in the shape of BCHW
- is_unbatched: bool = tensor.ndimension() == 3
- if is_unbatched:
- tensor = torch.unsqueeze(tensor, dim=0)
+ assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
# compute transformation between points and warp
# Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
@@ -225,21 +213,17 @@ def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Te
dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)
bbox = infer_box_shape(dst_box)
- assert len(bbox[0].unique()) == 1 and len(bbox[1].unique()) == 1, "cropping height and width" \
- f" must be exact same in a batch. Got height {bbox[0].unique()} and width {bbox[1].unique()}"
+ assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all(), (
+ f"Cropping height, width and depth must be exact same in a batch. Got height {bbox[0]} and width {bbox[1]}.")
patches: torch.Tensor = warp_affine(
- tensor, dst_trans_src[:, :2, :], (int(bbox[0].unique().item()), int(bbox[1].unique().item())),
+ tensor, dst_trans_src[:, :2, :], (int(bbox[0][0].item()), int(bbox[1][0].item())),
flags=interpolation, align_corners=align_corners)
- # return in the original shape
- if is_unbatched:
- patches = torch.squeeze(patches, dim=0)
-
return patches
def infer_box_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
- r"""Auto-infer the output sizes.
+ r"""Auto-infer the output sizes for the given 2D bounding boxes.
Args:
boxes (torch.Tensor): a tensor containing the coordinates of the
@@ -275,7 +259,7 @@ def infer_box_shape(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
def validate_bboxes(boxes: torch.Tensor) -> None:
- """Validate if a bounding box usable or not.
+ """Validate if a 2D bounding box usable or not.
This function checks if the boxes are rectangular or not.
@@ -295,14 +279,12 @@ def validate_bboxes(boxes: torch.Tensor) -> None:
def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
- """Convert bounding boxes to masks. Covered area is 1. and the remaining is 0.
+ """Convert 2D bounding boxes to masks. Covered area is 1. and the remaining is 0.
Args:
- boxes (torch.Tensor): a tensor containing the coordinates of the
- bounding boxes to be extracted. The tensor must have the shape
- of Bx4x2, where each box is defined in the following (clockwise)
- order: top-left, top-right, bottom-right, bottom-left. The
- coordinates must be in the x, y order.
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)
+ order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.
width (int): width of the masked image.
height (int): height of the masked image.
@@ -341,7 +323,7 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:
def bbox_generator(
x_start: torch.Tensor, y_start: torch.Tensor, width: torch.Tensor, height: torch.Tensor
) -> torch.Tensor:
- """Generate bounding boxes according to the provided start coords, width and height.
+ """Generate 2D bounding boxes according to the provided start coords, width and height.
Args:
x_start (torch.Tensor): a tensor containing the x coordinates of the bounding boxes to be extracted.
@@ -376,13 +358,21 @@ def bbox_generator(
f"`x_start` and `y_start` must be a scalar or (B,). Got {x_start}, {y_start}."
assert width.shape == height.shape and width.dim() in [0, 1], \
f"`width` and `height` must be a scalar or (B,). Got {width}, {height}."
+ assert x_start.dtype == y_start.dtype == width.dtype == height.dtype, (
+ "All tensors must be in the same dtype. Got "
+ f"`x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `width`({width.dtype}), `height`({height.dtype})."
+ )
+ assert x_start.device == y_start.device == width.device == height.device, (
+ "All tensors must be in the same device. Got "
+ f"`x_start`({x_start.device}), `y_start`({x_start.device}), `width`({width.device}), `height`({height.device})."
+ )
bbox = torch.tensor([[
[0, 0],
[0, 0],
[0, 0],
[0, 0],
- ]]).repeat(len(x_start), 1, 1)
+ ]], device=x_start.device, dtype=x_start.dtype).repeat(len(x_start), 1, 1)
bbox[:, :, 0] += x_start.view(-1, 1)
bbox[:, :, 1] += y_start.view(-1, 1)
diff --git a/kornia/geometry/transform/crop/crop3d.py b/kornia/geometry/transform/crop/crop3d.py
new file mode 100644
index 000000000..384d8ea52
--- /dev/null
+++ b/kornia/geometry/transform/crop/crop3d.py
@@ -0,0 +1,549 @@
+from typing import Tuple, Union
+
+import torch
+
+from kornia.geometry.transform.projwarp import (
+ get_perspective_transform3d, get_projective_transform, warp_affine3d
+)
+
+__all__ = [
+ "crop_and_resize3d",
+ "crop_by_boxes3d",
+ "center_crop3d",
+ "bbox_to_mask3d",
+ "infer_box_shape3d",
+ "validate_bboxes3d",
+ "bbox_generator3d"
+]
+
+
+def crop_and_resize3d(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int, int],
+ interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
+ r"""Extract crops from 3D volumes (5D tensor) and resize them.
+
+ Args:
+ tensor (torch.Tensor): the 3D volume tensor with shape (B, C, D, H, W).
+ boxes (torch.Tensor): a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
+ to be extracted. The tensor must have the shape of Bx8x3, where each box is defined in the clockwise
+ order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
+ size (Tuple[int, int, int]): a tuple with the height and width that will be
+ used to resize the extracted patches.
+ interpolation (str): Interpolation flag. Default: 'bilinear'.
+ align_corners (bool): mode for grid_generation. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details.
+
+ Returns:
+ torch.Tensor: tensor containing the patches with shape (Bx)CxN1xN2xN3.
+
+ Example:
+ >>> input = torch.arange(64, dtype=torch.float32).view(1, 1, 4, 4, 4)
+ >>> input
+ tensor([[[[[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [12., 13., 14., 15.]],
+ <BLANKLINE>
+ [[16., 17., 18., 19.],
+ [20., 21., 22., 23.],
+ [24., 25., 26., 27.],
+ [28., 29., 30., 31.]],
+ <BLANKLINE>
+ [[32., 33., 34., 35.],
+ [36., 37., 38., 39.],
+ [40., 41., 42., 43.],
+ [44., 45., 46., 47.]],
+ <BLANKLINE>
+ [[48., 49., 50., 51.],
+ [52., 53., 54., 55.],
+ [56., 57., 58., 59.],
+ [60., 61., 62., 63.]]]]])
+ >>> boxes = torch.tensor([[
+ ... [1., 1., 1.],
+ ... [3., 1., 1.],
+ ... [3., 3., 1.],
+ ... [1., 3., 1.],
+ ... [1., 1., 2.],
+ ... [3., 1., 2.],
+ ... [3., 3., 2.],
+ ... [1., 3., 2.],
+ ... ]]) # 1x8x3
+ >>> crop_and_resize3d(input, boxes, (2, 2, 2), align_corners=True)
+ tensor([[[[[21.0000, 23.0000],
+ [29.0000, 31.0000]],
+ <BLANKLINE>
+ [[37.0000, 39.0000],
+ [45.0000, 47.0000]]]]])
+ """
+ if not isinstance(tensor, (torch.Tensor)):
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+ if not isinstance(boxes, (torch.Tensor)):
+ raise TypeError("Input boxes type is not a torch.Tensor. Got {}"
+ .format(type(boxes)))
+ if not isinstance(size, (tuple, list,)) and len(size) != 3:
+ raise ValueError("Input size must be a tuple/list of length 3. Got {}"
+ .format(size))
+ assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
+ # unpack input data
+ dst_d, dst_h, dst_w = size[0], size[1], size[2]
+
+ # [x, y, z] origin
+ # from front to back
+ # top-left, top-right, bottom-right, bottom-left
+ points_src: torch.Tensor = boxes
+
+ # [x, y, z] destination
+ # from front to back
+ # top-left, top-right, bottom-right, bottom-left
+ points_dst: torch.Tensor = torch.tensor([[
+ [0, 0, 0],
+ [dst_w - 1, 0, 0],
+ [dst_w - 1, dst_h - 1, 0],
+ [0, dst_h - 1, 0],
+ [0, 0, dst_d - 1],
+ [dst_w - 1, 0, dst_d - 1],
+ [dst_w - 1, dst_h - 1, dst_d - 1],
+ [0, dst_h - 1, dst_d - 1],
+ ]], dtype=tensor.dtype, device=tensor.device).expand(points_src.shape[0], -1, -1)
+
+ return crop_by_boxes3d(tensor, points_src, points_dst, interpolation, align_corners)
+
+
+def center_crop3d(tensor: torch.Tensor, size: Tuple[int, int, int],
+ interpolation: str = 'bilinear',
+ align_corners: bool = True) -> torch.Tensor:
+ r"""Crop the 3D volumes (5D tensor) at the center.
+
+ Args:
+ tensor (torch.Tensor): the 3D volume tensor with shape (B, C, D, H, W).
+ size (Tuple[int, int, int]): a tuple with the expected depth, height and width
+ of the output patch.
+ interpolation (str): Interpolation flag. Default: 'bilinear'.
+ align_corners (bool): mode for grid_generation. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details.
+
+ Returns:
+ torch.Tensor: the output tensor with patches.
+
+ Examples:
+ >>> input = torch.arange(64, dtype=torch.float32).view(1, 1, 4, 4, 4)
+ >>> input
+ tensor([[[[[ 0., 1., 2., 3.],
+ [ 4., 5., 6., 7.],
+ [ 8., 9., 10., 11.],
+ [12., 13., 14., 15.]],
+ <BLANKLINE>
+ [[16., 17., 18., 19.],
+ [20., 21., 22., 23.],
+ [24., 25., 26., 27.],
+ [28., 29., 30., 31.]],
+ <BLANKLINE>
+ [[32., 33., 34., 35.],
+ [36., 37., 38., 39.],
+ [40., 41., 42., 43.],
+ [44., 45., 46., 47.]],
+ <BLANKLINE>
+ [[48., 49., 50., 51.],
+ [52., 53., 54., 55.],
+ [56., 57., 58., 59.],
+ [60., 61., 62., 63.]]]]])
+ >>> center_crop3d(input, (2, 2, 2), align_corners=True)
+ tensor([[[[[21.0000, 22.0000],
+ [25.0000, 26.0000]],
+ <BLANKLINE>
+ [[37.0000, 38.0000],
+ [41.0000, 42.0000]]]]])
+ """
+ if not isinstance(tensor, (torch.Tensor)):
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+
+ assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
+
+ if not isinstance(size, (tuple, list,)) and len(size) == 3:
+ raise ValueError("Input size must be a tuple/list of length 3. Got {}"
+ .format(size))
+
+ # unpack input sizes
+ dst_d, dst_h, dst_w = size
+ src_d, src_h, src_w = tensor.shape[-3:]
+
+ # compute start/end offsets
+ dst_d_half = dst_d / 2
+ dst_h_half = dst_h / 2
+ dst_w_half = dst_w / 2
+ src_d_half = src_d / 2
+ src_h_half = src_h / 2
+ src_w_half = src_w / 2
+
+ start_x = src_w_half - dst_w_half
+ start_y = src_h_half - dst_h_half
+ start_z = src_d_half - dst_d_half
+
+ end_x = start_x + dst_w - 1
+ end_y = start_y + dst_h - 1
+ end_z = start_z + dst_d - 1
+ # [x, y, z] origin
+ # top-left-front, top-right-front, bottom-right-front, bottom-left-front
+ # top-left-back, top-right-back, bottom-right-back, bottom-left-back
+ points_src: torch.Tensor = torch.tensor([[
+ [start_x, start_y, start_z],
+ [end_x, start_y, start_z],
+ [end_x, end_y, start_z],
+ [start_x, end_y, start_z],
+ [start_x, start_y, end_z],
+ [end_x, start_y, end_z],
+ [end_x, end_y, end_z],
+ [start_x, end_y, end_z],
+ ]], device=tensor.device)
+
+ # [x, y, z] destination
+ # top-left-front, top-right-front, bottom-right-front, bottom-left-front
+ # top-left-back, top-right-back, bottom-right-back, bottom-left-back
+ points_dst: torch.Tensor = torch.tensor([[
+ [0, 0, 0],
+ [dst_w - 1, 0, 0],
+ [dst_w - 1, dst_h - 1, 0],
+ [0, dst_h - 1, 0],
+ [0, 0, dst_d - 1],
+ [dst_w - 1, 0, dst_d - 1],
+ [dst_w - 1, dst_h - 1, dst_d - 1],
+ [0, dst_h - 1, dst_d - 1],
+ ]], device=tensor.device).expand(points_src.shape[0], -1, -1)
+
+ return crop_by_boxes3d(tensor,
+ points_src.to(tensor.dtype),
+ points_dst.to(tensor.dtype),
+ interpolation,
+ align_corners)
+
+
+def crop_by_boxes3d(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Tensor,
+ interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
+ """Perform crop transform on 3D volumes (5D tensor) by bounding boxes.
+
+ Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
+ Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.
+ So far, the ragged tensor is not supported by PyTorch right now. This function hereby requires the bounding boxes
+ in a batch must be rectangles with same width, height and depth.
+
+ Args:
+ tensor (torch.Tensor): the 3D volume tensor with shape (B, C, D, H, W).
+ src_box (torch.Tensor): a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
+ to be extracted. The tensor must have the shape of Bx8x3, where each box is defined in the clockwise
+ order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
+ dst_box (torch.Tensor): a tensor with shape (B, 8, 3) containing the coordinates of the bounding boxes
+ to be placed. The tensor must have the shape of Bx8x3, where each box is defined in the clockwise
+ order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in x, y, z order.
+ interpolation (str): Interpolation flag. Default: 'bilinear'.
+ align_corners (bool): mode for grid_generation. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details.
+
+ Returns:
+ torch.Tensor: the output tensor with patches.
+
+ Examples:
+ >>> input = torch.tensor([[
+ ... [[ 0., 1., 2., 3.],
+ ... [ 4., 5., 6., 7.],
+ ... [ 8., 9., 10., 11.],
+ ... [12., 13., 14., 15.]],
+ ... [[16., 17., 18., 19.],
+ ... [20., 21., 22., 23.],
+ ... [24., 25., 26., 27.],
+ ... [28., 29., 30., 31.]],
+ ... [[32., 33., 34., 35.],
+ ... [36., 37., 38., 39.],
+ ... [40., 41., 42., 43.],
+ ... [44., 45., 46., 47.]]]])
+ >>> src_box = torch.tensor([[
+ ... [1., 1., 1.],
+ ... [3., 1., 1.],
+ ... [3., 3., 1.],
+ ... [1., 3., 1.],
+ ... [1., 1., 2.],
+ ... [3., 1., 2.],
+ ... [3., 3., 2.],
+ ... [1., 3., 2.],
+ ... ]]) # 1x8x3
+ >>> dst_box = torch.tensor([[
+ ... [0., 0., 0.],
+ ... [2., 0., 0.],
+ ... [2., 2., 0.],
+ ... [0., 2., 0.],
+ ... [0., 0., 1.],
+ ... [2., 0., 1.],
+ ... [2., 2., 1.],
+ ... [0., 2., 1.],
+ ... ]]) # 1x8x3
+ >>> crop_by_boxes3d(input, src_box, dst_box, interpolation='nearest', align_corners=True)
+ tensor([[[[21., 22., 23.],
+ [25., 26., 27.],
+ [29., 30., 31.]],
+ <BLANKLINE>
+ [[37., 38., 39.],
+ [41., 42., 43.],
+ [45., 46., 47.]]]])
+
+ """
+ validate_bboxes3d(src_box)
+ validate_bboxes3d(dst_box)
+
+ assert len(tensor.shape) == 5, f"Only tensor with shape (B, C, D, H, W) supported. Got {tensor.shape}."
+
+ # compute transformation between points and warp
+ # Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
+ dst_trans_src: torch.Tensor = get_perspective_transform3d(src_box.to(tensor.dtype), dst_box.to(tensor.dtype))
+ # simulate broadcasting
+ dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)
+
+ bbox = infer_box_shape3d(dst_box)
+ assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all() and (bbox[2] == bbox[2][0]).all(), (
+ "Cropping height, width and depth must be exact same in a batch."
+ f"Got height {bbox[0]}, width {bbox[1]} and depth {bbox[2]}.")
+ patches: torch.Tensor = warp_affine3d(
+ tensor, dst_trans_src[:, :3, :],
+ # TODO: It will break the grads
+ (int(bbox[0][0].item()), int(bbox[1][0].item()), int(bbox[2][0].item())),
+ flags=interpolation, align_corners=align_corners)
+
+ return patches
+
+
+def infer_box_shape3d(boxes: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ r"""Auto-infer the output sizes for the given 3D bounding boxes.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx8x3, where each box is defined in the following (clockwise)
+ order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in the x, y, z order.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ - Bounding box depths, shape of :math:`(B,)`.
+ - Bounding box heights, shape of :math:`(B,)`.
+ - Bounding box widths, shape of :math:`(B,)`.
+
+ Example:
+ >>> boxes = torch.tensor([[[ 0, 1, 2],
+ ... [10, 1, 2],
+ ... [10, 21, 2],
+ ... [ 0, 21, 2],
+ ... [ 0, 1, 32],
+ ... [10, 1, 32],
+ ... [10, 21, 32],
+ ... [ 0, 21, 32]],
+ ... [[ 3, 4, 5],
+ ... [43, 4, 5],
+ ... [43, 54, 5],
+ ... [ 3, 54, 5],
+ ... [ 3, 4, 65],
+ ... [43, 4, 65],
+ ... [43, 54, 65],
+ ... [ 3, 54, 65]]]) # 2x8x3
+ >>> infer_box_shape3d(boxes)
+ (tensor([31, 61]), tensor([21, 51]), tensor([11, 41]))
+ """
+ validate_bboxes3d(boxes)
+
+ left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6]))[:, :, 0]
+ right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7]))[:, :, 0]
+ widths = (left - right + 1)[:, 0]
+
+ bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7]))[:, :, 1]
+ upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5]))[:, :, 1]
+ heights = (bot - upper + 1)[:, 0]
+
+ depths = (boxes[:, 4:, 2] - boxes[:, :4, 2] + 1)[:, 0]
+ return (depths, heights, widths)
+
+
+def validate_bboxes3d(boxes: torch.Tensor) -> None:
+ """Validate if a 3D bounding box usable or not.
+
+ This function checks if the boxes are cube or not.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx8x3, where each box is defined in the following (clockwise)
+ order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in the x, y, z order.
+ """
+ assert len(boxes.shape) == 3 and boxes.shape[1:] == torch.Size([8, 3]), \
+ f"Box shape must be (B, 8, 3). Got {boxes.shape}."
+
+ left = torch.index_select(boxes, 1, torch.tensor([1, 2, 5, 6]))[:, :, 0]
+ right = torch.index_select(boxes, 1, torch.tensor([0, 3, 4, 7]))[:, :, 0]
+ widths = (left - right + 1)
+ assert torch.allclose(widths.permute(1, 0), widths[:, 0]), \
+ f"Boxes must have be cube, while get different widths {widths}."
+
+ bot = torch.index_select(boxes, 1, torch.tensor([2, 3, 6, 7]))[:, :, 1]
+ upper = torch.index_select(boxes, 1, torch.tensor([0, 1, 4, 5]))[:, :, 1]
+ heights = (bot - upper + 1)
+ assert torch.allclose(heights.permute(1, 0), heights[:, 0]), \
+ f"Boxes must have be cube, while get different heights {heights}."
+
+ depths = (boxes[:, 4:, 2] - boxes[:, :4, 2] + 1)
+ assert torch.allclose(depths.permute(1, 0), depths[:, 0]), \
+ f"Boxes must have be cube, while get different depths {depths}."
+
+
+def bbox_to_mask3d(boxes: torch.Tensor, size: Tuple[int, int, int]) -> torch.Tensor:
+ """Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.
+
+ Args:
+ boxes (torch.Tensor): a tensor containing the coordinates of the bounding boxes to be extracted.
+ The tensor must have the shape of Bx8x3, where each box is defined in the following (clockwise)
+ order: front-top-left, front-top-right, front-bottom-right, front-bottom-left, back-top-left,
+ back-top-right, back-bottom-right, back-bottom-left. The coordinates must be in the x, y, z order.
+ size (Tuple[int, int, int]): depth, height and width of the masked image.
+
+ Returns:
+ torch.Tensor: the output mask tensor.
+
+ Examples:
+ >>> boxes = torch.tensor([[
+ ... [1., 1., 1.],
+ ... [2., 1., 1.],
+ ... [2., 2., 1.],
+ ... [1., 2., 1.],
+ ... [1., 1., 2.],
+ ... [2., 1., 2.],
+ ... [2., 2., 2.],
+ ... [1., 2., 2.],
+ ... ]]) # 1x8x3
+ >>> bbox_to_mask3d(boxes, (4, 5, 5))
+ tensor([[[[[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 0., 0., 0.],
+ [0., 1., 1., 0., 0.],
+ [0., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 0., 0., 0.],
+ [0., 1., 1., 0., 0.],
+ [0., 1., 1., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]],
+ <BLANKLINE>
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0.]]]]])
+ """
+ validate_bboxes3d(boxes)
+ mask = torch.zeros((len(boxes), *size))
+
+ mask_out = []
+ # TODO: Looking for a vectorized way
+ for m, box in zip(mask, boxes):
+ m = m.index_fill(0, torch.arange(box[0, 2].item(), box[4, 2].item() + 1, dtype=torch.long), torch.tensor(1))
+ m = m.index_fill(1, torch.arange(box[1, 1].item(), box[2, 1].item() + 1, dtype=torch.long), torch.tensor(1))
+ m = m.index_fill(2, torch.arange(box[0, 0].item(), box[1, 0].item() + 1, dtype=torch.long), torch.tensor(1))
+ m = m.unsqueeze(dim=0)
+ m_out = torch.ones_like(m)
+ m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=1, keepdim=True)
+ m_out = m_out * (m == 1).all(dim=3, keepdim=True).all(dim=1, keepdim=True)
+ m_out = m_out * (m == 1).all(dim=2, keepdim=True).all(dim=3, keepdim=True)
+ mask_out.append(m_out)
+
+ return torch.stack(mask_out, dim=0).float()
+
+
+def bbox_generator3d(
+ x_start: torch.Tensor, y_start: torch.Tensor, z_start: torch.Tensor,
+ width: torch.Tensor, height: torch.Tensor, depth: torch.Tensor
+) -> torch.Tensor:
+ """Generate 3D bounding boxes according to the provided start coords, width, height and depth.
+
+ Args:
+ x_start (torch.Tensor): a tensor containing the x coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ y_start (torch.Tensor): a tensor containing the y coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ z_start (torch.Tensor): a tensor containing the z coordinates of the bounding boxes to be extracted.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ width (torch.Tensor): widths of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ height (torch.Tensor): heights of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+ depth (torch.Tensor): depths of the masked image.
+ Shape must be a scalar tensor or :math:`(B,)`.
+
+ Returns:
+ torch.Tensor: the 3d bounding box tensor :math:`(B, 8, 3)`.
+
+ Examples:
+ >>> x_start = torch.tensor([0, 3])
+ >>> y_start = torch.tensor([1, 4])
+ >>> z_start = torch.tensor([2, 5])
+ >>> width = torch.tensor([10, 40])
+ >>> height = torch.tensor([20, 50])
+ >>> depth = torch.tensor([30, 60])
+ >>> bbox_generator3d(x_start, y_start, z_start, width, height, depth)
+ tensor([[[ 0, 1, 2],
+ [10, 1, 2],
+ [10, 21, 2],
+ [ 0, 21, 2],
+ [ 0, 1, 32],
+ [10, 1, 32],
+ [10, 21, 32],
+ [ 0, 21, 32]],
+ <BLANKLINE>
+ [[ 3, 4, 5],
+ [43, 4, 5],
+ [43, 54, 5],
+ [ 3, 54, 5],
+ [ 3, 4, 65],
+ [43, 4, 65],
+ [43, 54, 65],
+ [ 3, 54, 65]]])
+ """
+ assert x_start.shape == y_start.shape == z_start.shape and x_start.dim() in [0, 1], \
+ f"`x_start`, `y_start` and `z_start` must be a scalar or (B,). Got {x_start}, {y_start}, {z_start}."
+ assert width.shape == height.shape == depth.shape and width.dim() in [0, 1], \
+ f"`width`, `height` and `depth` must be a scalar or (B,). Got {width}, {height}, {depth}."
+ assert x_start.dtype == y_start.dtype == z_start.dtype == width.dtype == height.dtype == depth.dtype, (
+ "All tensors must be in the same dtype. "
+ f"Got `x_start`({x_start.dtype}), `y_start`({x_start.dtype}), `z_start`({x_start.dtype}), "
+ f"`width`({width.dtype}), `height`({height.dtype}) and `depth`({depth.dtype})."
+ )
+ assert x_start.device == y_start.device == z_start.device == width.device == height.device == depth.device, (
+ "All tensors must be in the same device. "
+ f"Got `x_start`({x_start.device}), `y_start`({x_start.device}), `z_start`({x_start.device}), "
+ f"`width`({width.device}), `height`({height.device}) and `depth`({depth.device})."
+ )
+
+ # front
+ bbox = torch.tensor([[
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0],
+ [0, 0, 0],
+ ]], device=x_start.device, dtype=x_start.dtype).repeat(len(x_start), 1, 1)
+
+ bbox[:, :, 0] += x_start.view(-1, 1)
+ bbox[:, :, 1] += y_start.view(-1, 1)
+ bbox[:, :, 2] += z_start.view(-1, 1)
+ bbox[:, 1, 0] += width
+ bbox[:, 2, 0] += width
+ bbox[:, 2, 1] += height
+ bbox[:, 3, 1] += height
+
+ # back
+ bbox_back = bbox.clone()
+ bbox_back[:, :, -1] += depth.unsqueeze(dim=1).repeat(1, 4)
+ bbox = torch.cat([bbox, bbox_back], dim=1)
+
+ return bbox
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 33a4f343a..3ef2501a0 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -4,13 +4,13 @@ import torch
import torch.nn.functional as F
from kornia.geometry.warp import (
- normalize_homography, homography_warp, normalize_homography3d
+ normalize_homography, homography_warp
)
from kornia.geometry.conversions import (
deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography, convert_affinematrix_to_homography3d
)
from kornia.geometry.transform.projwarp import (
- warp_projective, get_projective_transform
+ get_projective_transform
)
from kornia.testing import check_is_tensor
@@ -120,11 +120,11 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
See a working example `here <https://kornia.readthedocs.io/en/latest/
tutorials/warp_affine.html>`__.
"""
- if not torch.is_tensor(src):
+ if not isinstance(src, torch.Tensor):
raise TypeError("Input src type is not a torch.Tensor. Got {}"
.format(type(src)))
- if not torch.is_tensor(M):
+ if not isinstance(M, torch.Tensor):
raise TypeError("Input M type is not a torch.Tensor. Got {}"
.format(type(M)))
@@ -143,10 +143,10 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
M_3x3, dsize_src, out_size)
src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
- grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :], # type: ignore
+ grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :],
[B, C, out_size[0], out_size[1]],
align_corners=align_corners)
- return F.grid_sample(src, grid, # type: ignore
+ return F.grid_sample(src, grid,
align_corners=align_corners,
mode=flags,
padding_mode=padding_mode)
@@ -190,10 +190,10 @@ def get_perspective_transform(src, dst):
- Input: :math:`(B, 4, 2)` and :math:`(B, 4, 2)`
- Output: :math:`(B, 3, 3)`
"""
- if not torch.is_tensor(src):
+ if not isinstance(src, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}"
.format(type(src)))
- if not torch.is_tensor(dst):
+ 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):
@@ -206,35 +206,13 @@ def get_perspective_transform(src, dst):
raise ValueError("Inputs must have same batch size dimension. Expect {} but got {}"
.format(src.shape, dst.shape))
- def ax(p, q):
- ones = torch.ones_like(p)[..., 0:1]
- zeros = torch.zeros_like(p)[..., 0:1]
- return torch.cat(
- [p[:, 0:1], p[:, 1:2], ones, zeros, zeros, zeros,
- -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1]
- ], dim=1)
-
- def ay(p, q):
- ones = torch.ones_like(p)[..., 0:1]
- zeros = torch.zeros_like(p)[..., 0:1]
- return torch.cat(
- [zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], ones,
- -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2]], dim=1)
# we build matrix A by using only 4 point correspondence. The linear
# system is solved with the least square method, so here
# we could even pass more correspondence
p = []
- p.append(ax(src[:, 0], dst[:, 0]))
- p.append(ay(src[:, 0], dst[:, 0]))
-
- p.append(ax(src[:, 1], dst[:, 1]))
- p.append(ay(src[:, 1], dst[:, 1]))
-
- p.append(ax(src[:, 2], dst[:, 2]))
- p.append(ay(src[:, 2], dst[:, 2]))
-
- p.append(ax(src[:, 3], dst[:, 3]))
- p.append(ay(src[:, 3], dst[:, 3]))
+ for i in [0, 1, 2, 3]:
+ p.append(_build_perspective_param(src[:, i], dst[:, i], 'x'))
+ p.append(_build_perspective_param(src[:, i], dst[:, i], 'y'))
# A is Bx8x8
A = torch.stack(p, dim=1)
@@ -257,6 +235,23 @@ def get_perspective_transform(src, dst):
return M.view(-1, 3, 3) # Bx3x3
+def _build_perspective_param(p: torch.Tensor, q: torch.Tensor, axis: str) -> torch.Tensor:
+ ones = torch.ones_like(p)[..., 0:1]
+ zeros = torch.zeros_like(p)[..., 0:1]
+ if axis == 'x':
+ return torch.cat(
+ [p[:, 0:1], p[:, 1:2], ones, zeros, zeros, zeros,
+ -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1]
+ ], dim=1)
+
+ if axis == 'y':
+ return torch.cat(
+ [zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], ones,
+ -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2]], dim=1)
+
+ raise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")
+
+
def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:
r"""Create a rotation matrix out of angles in degrees.
Args:
@@ -326,13 +321,13 @@ def get_rotation_matrix2d(
tensor([[[ 0.7071, 0.7071, 0.0000],
[-0.7071, 0.7071, 0.0000]]])
"""
- if not torch.is_tensor(center):
+ if not isinstance(center, torch.Tensor):
raise TypeError("Input center type is not a torch.Tensor. Got {}"
.format(type(center)))
- 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 not torch.is_tensor(scale):
+ 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):
@@ -404,13 +399,13 @@ def remap(tensor: torch.Tensor, map_x: torch.Tensor,
[0., 0.]]]])
"""
- 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(map_x):
+ 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 torch.is_tensor(map_y):
+ 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:]:
@@ -452,7 +447,7 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
Return:
torch.Tensor: the reverse affine transform.
"""
- if not torch.is_tensor(matrix):
+ 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)):
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index 67deb4d46..0ca2810c5 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -4,21 +4,24 @@ from typing import Tuple, List
import torch
import kornia as K
from kornia.geometry.conversions import convert_affinematrix_to_homography3d
-from kornia.geometry.warp import normalize_homography3d
+from kornia.geometry.warp import normalize_homography3d, homography_warp3d
+from kornia.testing import check_is_tensor
__all__ = [
- "warp_projective",
+ "warp_affine3d",
"get_projective_transform",
"projection_from_Rt",
+ "get_perspective_transform3d",
+ "warp_perspective3d"
]
-def warp_projective(src: torch.Tensor,
- M: torch.Tensor,
- dsize: Tuple[int, int, int],
- flags: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = True) -> torch.Tensor:
+def warp_affine3d(src: torch.Tensor,
+ M: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ flags: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = True) -> torch.Tensor:
r"""Applies a projective transformation a to 3d tensor.
.. warning::
@@ -130,3 +133,213 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
proj_mat = (from_origin_mat @ proj_mat @ to_origin_mat)
return proj_mat[..., :3, :] # Bx3x4
+
+
+def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:
+ r"""Calculate a 3d perspective transform from four pairs of the corresponding points.
+
+ The function calculates the matrix of a perspective transform so that:
+
+ .. math ::
+
+ \begin{bmatrix}
+ t_{i}x_{i}^{'} \\
+ t_{i}y_{i}^{'} \\
+ t_{i}z_{i}^{'} \\
+ t_{i} \\
+ \end{bmatrix}
+ =
+ \textbf{map_matrix} \cdot
+ \begin{bmatrix}
+ x_{i} \\
+ y_{i} \\
+ z_{i} \\
+ 1 \\
+ \end{bmatrix}
+
+ where
+
+ .. math ::
+ dst(i) = (x_{i}^{'},y_{i}^{'},z_{i}^{'}), src(i) = (x_{i}, y_{i}, z_{i}), i = 0,1,2,5,7
+
+ Concrete math is as below:
+
+ .. math ::
+
+ \[ u_i =\frac{c_{00} * x_i + c_{01} * y_i + c_{02} * z_i + c_{03}}
+ {c_{30} * x_i + c_{31} * y_i + c_{32} * z_i + c_{33}} \]
+ \[ v_i =\frac{c_{10} * x_i + c_{11} * y_i + c_{12} * z_i + c_{13}}
+ {c_{30} * x_i + c_{31} * y_i + c_{32} * z_i + c_{33}} \]
+ \[ w_i =\frac{c_{20} * x_i + c_{21} * y_i + c_{22} * z_i + c_{23}}
+ {c_{30} * x_i + c_{31} * y_i + c_{32} * z_i + c_{33}} \]
+
+ .. math ::
+
+ \begin{pmatrix}
+ x_0 & y_0 & z_0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -x_0*u_0 & -y_0*u_0 & -z_0 * u_0 \\
+ x_1 & y_1 & z_1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -x_1*u_1 & -y_1*u_1 & -z_1 * u_1 \\
+ x_2 & y_2 & z_2 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -x_2*u_2 & -y_2*u_2 & -z_2 * u_2 \\
+ x_5 & y_5 & z_5 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -x_5*u_5 & -y_5*u_5 & -z_5 * u_5 \\
+ x_7 & y_7 & z_7 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -x_7*u_7 & -y_7*u_7 & -z_7 * u_7 \\
+ 0 & 0 & 0 & 0 & x_0 & y_0 & z_0 & 1 & 0 & 0 & 0 & 0 & -x_0*v_0 & -y_0*v_0 & -z_0 * v_0 \\
+ 0 & 0 & 0 & 0 & x_1 & y_1 & z_1 & 1 & 0 & 0 & 0 & 0 & -x_1*v_1 & -y_1*v_1 & -z_1 * v_1 \\
+ 0 & 0 & 0 & 0 & x_2 & y_2 & z_2 & 1 & 0 & 0 & 0 & 0 & -x_2*v_2 & -y_2*v_2 & -z_2 * v_2 \\
+ 0 & 0 & 0 & 0 & x_5 & y_5 & z_5 & 1 & 0 & 0 & 0 & 0 & -x_5*v_5 & -y_5*v_5 & -z_5 * v_5 \\
+ 0 & 0 & 0 & 0 & x_7 & y_7 & z_7 & 1 & 0 & 0 & 0 & 0 & -x_7*v_7 & -y_7*v_7 & -z_7 * v_7 \\
+ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & x_0 & y_0 & z_0 & 1 & -x_0*w_0 & -y_0*w_0 & -z_0 * w_0 \\
+ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & x_1 & y_1 & z_1 & 1 & -x_1*w_1 & -y_1*w_1 & -z_1 * w_1 \\
+ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & x_2 & y_2 & z_2 & 1 & -x_2*w_2 & -y_2*w_2 & -z_2 * w_2 \\
+ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & x_5 & y_5 & z_5 & 1 & -x_5*w_5 & -y_5*w_5 & -z_5 * w_5 \\
+ 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & x_7 & y_7 & z_7 & 1 & -x_7*w_7 & -y_7*w_7 & -z_7 * w_7 \\
+ \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.
+
+ Returns:
+ Tensor: the perspective transformation.
+
+ Shape:
+ - Input: :math:`(B, 8, 3)` and :math:`(B, 8, 3)`
+ - Output: :math:`(B, 4, 4)`
+ """
+ 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))
+
+ # we build matrix A by using only 4 point correspondence. The linear
+ # system is solved with the least square method, so here
+ # we could even pass more correspondence
+ p = []
+
+ # 000, 100, 110, 101, 011
+ for i in [0, 1, 2, 5, 7]:
+ p.append(_build_perspective_param3d(src[:, i], dst[:, i], 'x'))
+ p.append(_build_perspective_param3d(src[:, i], dst[:, i], 'y'))
+ p.append(_build_perspective_param3d(src[:, i], dst[:, i], 'z'))
+
+ # A is Bx15x15
+ A = torch.stack(p, dim=1)
+
+ # b is a Bx15x1
+ b = torch.stack([
+ dst[:, 0:1, 0], dst[:, 0:1, 1], dst[:, 0:1, 2],
+ dst[:, 1:2, 0], dst[:, 1:2, 1], dst[:, 1:2, 2],
+ dst[:, 2:3, 0], dst[:, 2:3, 1], dst[:, 2:3, 2],
+ # dst[:, 3:4, 0], dst[:, 3:4, 1], dst[:, 3:4, 2],
+ # dst[:, 4:5, 0], dst[:, 4:5, 1], dst[:, 4:5, 2],
+ dst[:, 5:6, 0], dst[:, 5:6, 1], dst[:, 5:6, 2],
+ # dst[:, 6:7, 0], dst[:, 6:7, 1], dst[:, 6:7, 2],
+ dst[:, 7:8, 0], dst[:, 7:8, 1], dst[:, 7:8, 2],
+ ], dim=1)
+
+ # solve the system Ax = b
+ X, LU = torch.solve(b, A)
+
+ # create variable to return
+ batch_size = src.shape[0]
+ M = torch.ones(batch_size, 16, device=src.device, dtype=src.dtype)
+ M[..., :15] = torch.squeeze(X, dim=-1)
+ return M.view(-1, 4, 4) # Bx4x4
+
+
+def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> torch.Tensor:
+ ones = torch.ones_like(p)[..., 0:1]
+ zeros = torch.zeros_like(p)[..., 0:1]
+
+ if axis == 'x':
+ return torch.cat([
+ p[:, 0:1], p[:, 1:2], p[:, 2:3], ones,
+ zeros, zeros, zeros, zeros,
+ zeros, zeros, zeros, zeros,
+ -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1], -p[:, 2:3] * q[:, 0:1]
+ ], dim=1)
+
+ if axis == 'y':
+ return torch.cat([
+ zeros, zeros, zeros, zeros,
+ p[:, 0:1], p[:, 1:2], p[:, 2:3], ones,
+ zeros, zeros, zeros, zeros,
+ -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2], -p[:, 2:3] * q[:, 1:2]
+ ], dim=1)
+
+ if axis == 'z':
+ return torch.cat([
+ zeros, zeros, zeros, zeros,
+ zeros, zeros, zeros, zeros,
+ p[:, 0:1], p[:, 1:2], p[:, 2:3], ones,
+ -p[:, 0:1] * q[:, 2:3], -p[:, 1:2] * q[:, 2:3], -p[:, 2:3] * q[:, 2:3]
+ ], dim=1)
+
+ raise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")
+
+
+def warp_perspective3d(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int, int],
+ flags: str = 'bilinear', border_mode: str = 'zeros',
+ align_corners: bool = False) -> torch.Tensor:
+ r"""Applies a perspective transformation to an image.
+
+ The function warp_perspective transforms the source image using
+ the specified matrix:
+
+ .. math::
+ \text{dst} (x, y) = \text{src} \left(
+ \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} ,
+ \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}}
+ \right )
+
+ Args:
+ src (torch.Tensor): input image with shape :math:`(B, C, D, H, W)`.
+ M (torch.Tensor): transformation matrix with shape :math:`(B, 4, 4)`.
+ 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.
+
+ Returns:
+ torch.Tensor: the warped input image :math:`(B, C, D, H, W)`.
+
+ """
+ check_is_tensor(src)
+ check_is_tensor(M)
+
+ if not len(src.shape) == 5:
+ raise ValueError("Input src must be a BxCxDxHxW tensor. Got {}"
+ .format(src.shape))
+
+ if not (len(M.shape) == 3 or M.shape[-2:] == (4, 4)):
+ raise ValueError("Input M must be a Bx4x4 tensor. Got {}"
+ .format(M.shape))
+
+ # launches the warper
+ d, h, w = src.shape[-3:]
+ return transform_warp_impl3d(src, M, (d, h, w), dsize, flags, border_mode, align_corners)
+
+
+def transform_warp_impl3d(src: torch.Tensor, dst_pix_trans_src_pix: torch.Tensor,
+ dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int],
+ grid_mode: str, padding_mode: str, align_corners: bool) -> torch.Tensor:
+ """Compute the transform in normalized cooridnates and perform the warping.
+ """
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(
+ dst_pix_trans_src_pix, dsize_src, dsize_dst)
+
+ src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
+ return homography_warp3d(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode,
+ align_corners, True)
diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.py
index 7422c9a3e..e27d07939 100644
--- a/kornia/geometry/warp/homography_warper.py
+++ b/kornia/geometry/warp/homography_warper.py
@@ -4,7 +4,7 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from kornia.utils import create_meshgrid
+from kornia.utils import create_meshgrid, create_meshgrid3d
from kornia.geometry.linalg import transform_points
from kornia.testing import check_is_tensor
@@ -12,7 +12,9 @@ from kornia.testing import check_is_tensor
__all__ = [
"HomographyWarper",
"homography_warp",
+ "homography_warp3d",
"warp_grid",
+ "warp_grid3d",
"normalize_homography",
"normalize_homography3d",
"normal_transform_pixel",
@@ -29,7 +31,6 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
transform all points in the grid. Shape of the homography
has to be :math:`(1, 3, 3)` or :math:`(N, 1, 3, 3)`.
-
Returns:
torch.Tensor: the transformed grid of shape :math:`(N, H, W, 2)`.
"""
@@ -45,6 +46,30 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
return flow.view(batch_size, height, width, 2) # NxHxWx2
+def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
+ r"""Compute the grid to warp the coordinates grid by the homography/ies.
+
+ Args:
+ grid: Unwrapped grid of the shape :math:`(1, D, H, W, 3)`.
+ src_homo_dst (torch.Tensor): Homography or homographies (stacked) to
+ transform all points in the grid. Shape of the homography
+ has to be :math:`(1, 4, 4)` or :math:`(N, 1, 4, 4)`.
+
+ Returns:
+ torch.Tensor: the transformed grid of shape :math:`(N, H, W, 3)`.
+ """
+ batch_size: int = src_homo_dst.size(0)
+ _, depth, height, width, _ = grid.size()
+ # expand grid to match the input batch size
+ grid = grid.expand(batch_size, -1, -1, -1, -1) # NxDxHxWx3
+ if len(src_homo_dst.shape) == 3: # local homography case
+ src_homo_dst = src_homo_dst.view(batch_size, 1, 4, 4) # Nx1x3x3
+ # perform the actual grid transformation,
+ # the grid is copied to input device and casted to the same type
+ flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
+ return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
+
+
# functional api
def homography_warp(patch_src: torch.Tensor,
src_homo_dst: torch.Tensor,
@@ -53,7 +78,7 @@ def homography_warp(patch_src: torch.Tensor,
padding_mode: str = 'zeros',
align_corners: bool = False,
normalized_coordinates: bool = True) -> torch.Tensor:
- r"""Function that warps image patchs or tensors by homographies.
+ r"""Warp image patchs or tensors by normalized 2D homographies.
See :class:`~kornia.geometry.warp.HomographyWarper` for details.
@@ -94,6 +119,53 @@ def homography_warp(patch_src: torch.Tensor,
align_corners=align_corners)
+def homography_warp3d(patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False,
+ normalized_coordinates: bool = True) -> torch.Tensor:
+ r"""Warp image patchs or tensors by normalized 3D homographies.
+
+ Args:
+ patch_src (torch.Tensor): The image or tensor to warp. Should be from
+ source of shape :math:`(N, C, D, H, W)`.
+ src_homo_dst (torch.Tensor): The homography or stack of homographies
+ from destination to source of shape
+ :math:`(N, 4, 4)`.
+ dsize (Tuple[int, int, int]): The height and width of the image to warp.
+ 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): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details.
+ normalized_coordinates (bool): Whether the homography assumes [-1, 1] normalized
+ coordinates or not.
+
+ Return:
+ torch.Tensor: Patch sampled at locations from source to destination.
+
+ Example:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> homography = torch.eye(3).view(1, 3, 3)
+ >>> output = kornia.homography_warp(input, homography, (32, 32))
+ """
+ if not src_homo_dst.device == patch_src.device:
+ raise TypeError("Patch and homography must be on the same device. \
+ Got patch.device: {} src_H_dst.device: {}.".format(
+ patch_src.device, src_homo_dst.device))
+
+ depth, height, width = dsize
+ grid = create_meshgrid3d(depth, height, width, normalized_coordinates=normalized_coordinates,
+ device=patch_src.device)
+ warped_grid = warp_grid3d(grid, src_homo_dst)
+
+ return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode,
+ align_corners=align_corners)
+
+
# layer api
class HomographyWarper(nn.Module):
r"""Warp tensors by homographies.
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index b2850129b..36464160a 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -19,6 +19,7 @@ def create_checkerboard(h, w, nw):
np.ones((h // (2 * nw), w // (2 * nw)))).astype(np.float32)
+# TODO: Isn't this function duplicated with eye_like?
def create_eye_batch(batch_size, eye_size):
"""Creates a batch of identity matrices of shape Bx3x3
"""
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 04df6a866..91b30adf2 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -32,7 +32,7 @@ class TestRandomHorizontalFlip:
repr = "RandomHorizontalFlip(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"
assert str(f) == repr
- def test_random_hflip(self, device):
+ def test_random_hflip(self, device, dtype):
f = RandomHorizontalFlip(p=1.0, return_transform=True)
f1 = RandomHorizontalFlip(p=0., return_transform=True)
@@ -69,7 +69,7 @@ class TestRandomHorizontalFlip:
assert (f2(input) == expected).all()
assert (f3(input) == input).all()
- def test_batch_random_hflip(self, device):
+ def test_batch_random_hflip(self, device, dtype):
f = RandomHorizontalFlip(p=1.0, return_transform=True)
f1 = RandomHorizontalFlip(p=0.0, return_transform=True)
@@ -104,13 +104,13 @@ class TestRandomHorizontalFlip:
assert (f1(input)[0] == input).all()
assert (f1(input)[1] == identity).all()
- def test_same_on_batch(self, device):
+ def test_same_on_batch(self, device, dtype):
f = RandomHorizontalFlip(p=0.5, same_on_batch=True)
- input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
+ input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
- def test_sequential(self, device):
+ def test_sequential(self, device, dtype):
f = nn.Sequential(
RandomHorizontalFlip(p=1.0, return_transform=True),
@@ -178,7 +178,7 @@ class TestRandomHorizontalFlip:
input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]]).all()
@pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
+ def test_jit(self, device, dtype):
@torch.jit.script
def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
@@ -208,8 +208,8 @@ class TestRandomHorizontalFlip:
assert_allclose(actual, expected)
- def test_gradcheck(self, device):
- input = torch.rand((3, 3)).to(device) # 3 x 3
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(RandomHorizontalFlip(p=1.), (input, ), raise_exception=True)
@@ -221,7 +221,7 @@ class TestRandomVerticalFlip:
repr = "RandomVerticalFlip(p=0.5, p_batch=1.0, same_on_batch=False, return_transform=False)"
assert str(f) == repr
- def test_random_vflip(self, device):
+ def test_random_vflip(self, device, dtype):
f = RandomVerticalFlip(p=1.0, return_transform=True)
f1 = RandomVerticalFlip(p=0., return_transform=True)
@@ -255,7 +255,7 @@ class TestRandomVerticalFlip:
assert_allclose(f2(input), expected)
assert_allclose(f3(input), input)
- def test_batch_random_vflip(self, device):
+ def test_batch_random_vflip(self, device, dtype):
f = RandomVerticalFlip(p=1.0, return_transform=True)
f1 = RandomVerticalFlip(p=0.0, return_transform=True)
@@ -290,13 +290,13 @@ class TestRandomVerticalFlip:
assert_allclose(f1(input)[0], input)
assert_allclose(f1(input)[1], identity)
- def test_same_on_batch(self, device):
+ def test_same_on_batch(self, device, dtype):
f = RandomVerticalFlip(p=0.5, same_on_batch=True)
- input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
+ input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 1, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
- def test_sequential(self, device):
+ def test_sequential(self, device, dtype):
f = nn.Sequential(
RandomVerticalFlip(p=1.0, return_transform=True),
@@ -363,7 +363,7 @@ class TestRandomVerticalFlip:
input[..., input_coordinates[0, 1, :], input_coordinates[0, 0, :]]).all()
@pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
+ def test_jit(self, device, dtype):
@torch.jit.script
def op_script(data: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
return kornia.random_vflip(data)
@@ -392,8 +392,8 @@ class TestRandomVerticalFlip:
assert_allclose(actual, expected)
- def test_gradcheck(self, device):
- input = torch.rand((3, 3)).to(device) # 3 x 3
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(RandomVerticalFlip(p=1.), (input, ), raise_exception=True)
@@ -407,48 +407,47 @@ class TestColorJitter:
"p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
assert str(f) == repr
- def test_color_jitter(self, device):
+ def test_color_jitter(self, device, dtype):
f = ColorJitter()
f1 = ColorJitter(return_transform=True)
- input = torch.rand(3, 5, 5).to(device) # 3 x 5 x 5
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype) # 3 x 5 x 5
expected = input
- expected_transform = torch.eye(3).unsqueeze(0).to(device) # 3 x 3
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-5)
assert_allclose(f1(input)[0], expected, atol=1e-4, rtol=1e-5)
assert_allclose(f1(input)[1], expected_transform)
- def test_color_jitter_batch(self, device):
+ def test_color_jitter_batch(self, device, dtype):
f = ColorJitter()
f1 = ColorJitter(return_transform=True)
- input = torch.rand(2, 3, 5, 5).to(device) # 2 x 3 x 5 x 5
+ input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5
expected = input
- expected_transform = torch.eye(3).unsqueeze(0).expand((2, 3, 3)).to(device) # 2 x 3 x 3
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-5)
assert_allclose(f1(input)[0], expected, atol=1e-4, rtol=1e-5)
assert_allclose(f1(input)[1], expected_transform)
- def test_same_on_batch(self, device):
+ def test_same_on_batch(self, device, dtype):
f = ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1, same_on_batch=True)
input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
- def test_random_brightness(self, device):
+ def test_random_brightness(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(brightness=0.2)
input = torch.tensor([[[[0.1, 0.2, 0.3],
[0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
+ [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
- input = input.to(device)
expected = torch.tensor([[[[0.2529, 0.3529, 0.4529],
[0.7529, 0.6529, 0.5529],
@@ -473,20 +472,18 @@ class TestColorJitter:
[[0.2660, 0.3660, 0.4660],
[0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]]]]) # 1 x 1 x 3 x 3
- expected = expected.to(device)
+ [0.8660, 0.9660, 1.0000]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_random_brightness_tuple(self, device):
+ def test_random_brightness_tuple(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(brightness=(0.8, 1.2))
input = torch.tensor([[[[0.1, 0.2, 0.3],
[0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
+ [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
- input = input.to(device)
expected = torch.tensor([[[[0.2529, 0.3529, 0.4529],
[0.7529, 0.6529, 0.5529],
@@ -511,20 +508,19 @@ class TestColorJitter:
[[0.2660, 0.3660, 0.4660],
[0.7660, 0.6660, 0.5660],
- [0.8660, 0.9660, 1.0000]]]]) # 1 x 1 x 3 x 3
+ [0.8660, 0.9660, 1.0000]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
expected = expected.to(device)
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_random_contrast(self, device):
+ def test_random_contrast(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(contrast=0.2)
input = torch.tensor([[[[0.1, 0.2, 0.3],
[0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
+ [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
- input = input.to(device)
expected = torch.tensor([[[[0.0953, 0.1906, 0.2859],
[0.5719, 0.4766, 0.3813],
@@ -549,19 +545,19 @@ class TestColorJitter:
[[0.1184, 0.2367, 0.3551],
[0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]]]])
+ [0.8286, 0.9470, 1.0000]]]], device=device, dtype=dtype)
expected = expected.to(device)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-5)
- def test_random_contrast_list(self, device):
+ def test_random_contrast_list(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(contrast=[0.8, 1.2])
input = torch.tensor([[[[0.1, 0.2, 0.3],
[0.6, 0.5, 0.4],
- [0.7, 0.8, 1.]]]]) # 1 x 1 x 3 x 3
- input = input.repeat(2, 3, 1, 1).to(device) # 2 x 3 x 3
+ [0.7, 0.8, 1.]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 3, 1, 1) # 2 x 3 x 3
expected = torch.tensor([[[[0.0953, 0.1906, 0.2859],
[0.5719, 0.4766, 0.3813],
@@ -586,12 +582,12 @@ class TestColorJitter:
[[0.1184, 0.2367, 0.3551],
[0.7102, 0.5919, 0.4735],
- [0.8286, 0.9470, 1.0000]]]])
+ [0.8286, 0.9470, 1.0000]]]], device=device, dtype=dtype)
expected = expected.to(device)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-5)
- def test_random_saturation(self, device):
+ def test_random_saturation(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(saturation=0.2)
@@ -605,8 +601,8 @@ class TestColorJitter:
[[0.6, 0.8, 0.7],
[0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
- input = input.repeat(2, 1, 1, 1).to(device) # 2 x 3 x 3
+ [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = torch.tensor([[[[1.8763e-01, 2.5842e-01, 3.3895e-01],
[6.2921e-01, 5.0000e-01, 4.0000e-01],
@@ -631,11 +627,11 @@ class TestColorJitter:
[[5.5556e-01, 8.0000e-01, 7.0000e-01],
[9.0000e-01, 2.7651e-01, 1.7651e-01],
- [8.0000e-01, 3.5302e-01, 4.4127e-01]]]])
+ [8.0000e-01, 3.5302e-01, 4.4127e-01]]]], device=device, dtype=dtype)
expected = expected.to(device)
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_random_saturation_tensor(self, device):
+ def test_random_saturation_tensor(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(saturation=torch.tensor(0.2))
@@ -649,8 +645,8 @@ class TestColorJitter:
[[0.6, 0.8, 0.7],
[0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
- input = input.repeat(2, 1, 1, 1).to(device) # 2 x 3 x 3
+ [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = torch.tensor([[[[1.8763e-01, 2.5842e-01, 3.3895e-01],
[6.2921e-01, 5.0000e-01, 4.0000e-01],
@@ -675,12 +671,12 @@ class TestColorJitter:
[[5.5556e-01, 8.0000e-01, 7.0000e-01],
[9.0000e-01, 2.7651e-01, 1.7651e-01],
- [8.0000e-01, 3.5302e-01, 4.4127e-01]]]])
+ [8.0000e-01, 3.5302e-01, 4.4127e-01]]]], device=device, dtype=dtype)
expected = expected.to(device)
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_random_saturation_tuple(self, device):
+ def test_random_saturation_tuple(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(saturation=(0.8, 1.2))
@@ -694,8 +690,8 @@ class TestColorJitter:
[[0.6, 0.8, 0.7],
[0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
- input = input.repeat(2, 1, 1, 1).to(device) # 2 x 3 x 3
+ [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = torch.tensor([[[[1.8763e-01, 2.5842e-01, 3.3895e-01],
[6.2921e-01, 5.0000e-01, 4.0000e-01],
@@ -720,12 +716,12 @@ class TestColorJitter:
[[5.5556e-01, 8.0000e-01, 7.0000e-01],
[9.0000e-01, 2.7651e-01, 1.7651e-01],
- [8.0000e-01, 3.5302e-01, 4.4127e-01]]]])
+ [8.0000e-01, 3.5302e-01, 4.4127e-01]]]], device=device, dtype=dtype)
expected = expected.to(device)
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_random_hue(self, device):
+ def test_random_hue(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(hue=0.1 / pi.item())
@@ -739,8 +735,8 @@ class TestColorJitter:
[[0.6, 0.8, 0.7],
[0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
- input = input.repeat(2, 1, 1, 1).to(device) # 2 x 3 x 3
+ [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = torch.tensor([[[[0.1000, 0.2000, 0.3000],
[0.6000, 0.5000, 0.4000],
@@ -764,12 +760,12 @@ class TestColorJitter:
[[0.6347, 0.8000, 0.7000],
[0.9000, 0.3000, 0.2000],
- [0.8000, 0.3730, 0.4692]]]])
+ [0.8000, 0.3730, 0.4692]]]], device=device, dtype=dtype)
expected = expected.to(device)
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_random_hue_list(self, device):
+ def test_random_hue_list(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(hue=[-0.1 / pi, 0.1 / pi])
@@ -783,8 +779,8 @@ class TestColorJitter:
[[0.6, 0.8, 0.7],
[0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
- input = input.repeat(2, 1, 1, 1).to(device) # 2 x 3 x 3
+ [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = torch.tensor([[[[0.1000, 0.2000, 0.3000],
[0.6000, 0.5000, 0.4000],
@@ -809,12 +805,12 @@ class TestColorJitter:
[[0.6347, 0.8000, 0.7000],
[0.9000, 0.3000, 0.2000],
- [0.8000, 0.3730, 0.4692]]]])
+ [0.8000, 0.3730, 0.4692]]]], device=device, dtype=dtype)
expected = expected.to(device)
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_random_hue_list_batch(self, device):
+ def test_random_hue_list_batch(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(hue=[-0.1 / pi.item(), 0.1 / pi.item()])
@@ -828,8 +824,8 @@ class TestColorJitter:
[[0.6, 0.8, 0.7],
[0.9, 0.3, 0.2],
- [0.8, 0.4, .5]]]]) # 1 x 1 x 3 x 3
- input = input.repeat(2, 1, 1, 1).to(device) # 2 x 3 x 3
+ [0.8, 0.4, .5]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ input = input.repeat(2, 1, 1, 1) # 2 x 3 x 3
expected = torch.tensor([[[[0.1000, 0.2000, 0.3000],
[0.6000, 0.5000, 0.4000],
@@ -854,46 +850,44 @@ class TestColorJitter:
[[0.6347, 0.8000, 0.7000],
[0.9000, 0.3000, 0.2000],
- [0.8000, 0.3730, 0.4692]]]])
+ [0.8000, 0.3730, 0.4692]]]], device=device, dtype=dtype)
expected = expected.to(device)
- assert_allclose(f(input), expected)
+ assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
- def test_sequential(self, device):
+ def test_sequential(self, device, dtype):
f = nn.Sequential(
ColorJitter(return_transform=True),
ColorJitter(return_transform=True),
)
- input = torch.rand(3, 5, 5).to(device) # 3 x 5 x 5
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype) # 3 x 5 x 5
expected = input
- expected_transform = torch.eye(3).unsqueeze(0) # 3 x 3
- expected_transform = expected_transform.to(device)
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
assert_allclose(f(input)[0], expected, atol=1e-4, rtol=1e-5)
assert_allclose(f(input)[1], expected_transform)
- def test_color_jitter_batch_sequential(self, device):
+ def test_color_jitter_batch_sequential(self, device, dtype):
f = nn.Sequential(
ColorJitter(return_transform=True),
ColorJitter(return_transform=True),
)
- input = torch.rand(2, 3, 5, 5).to(device) # 2 x 3 x 5 x 5
+ input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5
expected = input
- expected_transform = torch.eye(3).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3
- expected_transform = expected_transform.to(device)
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3
assert_allclose(f(input)[0], expected, atol=1e-4, rtol=1e-5)
assert_allclose(f(input)[0], expected)
assert_allclose(f(input)[1], expected_transform)
- def test_gradcheck(self, device):
- input = torch.rand((3, 5, 5)).to(device) # 3 x 3
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand((3, 5, 5), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.augmentation.ColorJitter(p=1.), (input, ), raise_exception=True)
@@ -926,7 +920,7 @@ class TestRectangleRandomErasing:
res = f(input)
assert (res[0] == res[1]).all()
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
# test parameters
batch_shape = (2, 3, 11, 7)
erase_scale_range = (.2, .4)
@@ -936,7 +930,7 @@ class TestRectangleRandomErasing:
rect_params = rand_rec.__forward_parameters__(batch_shape, p=1.0, p_batch=1., same_on_batch=False)
# evaluate function gradient
- input = torch.rand(batch_shape).to(device)
+ input = torch.rand(batch_shape, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(
rand_rec,
@@ -945,7 +939,7 @@ class TestRectangleRandomErasing:
)
@pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
+ def test_jit(self, device, dtype):
@torch.jit.script
def op_script(img):
return kornia.augmentation.random_rectangle_erase(img, (.2, .4), (.3, .5))
@@ -966,24 +960,24 @@ class TestRandomGrayscale:
repr = "RandomGrayscale(p=0.1, p_batch=1.0, same_on_batch=False, return_transform=False)"
assert str(f) == repr
- def test_random_grayscale(self, device):
+ def test_random_grayscale(self, device, dtype):
f = RandomGrayscale(return_transform=True)
- input = torch.rand(3, 5, 5).to(device) # 3 x 5 x 5
+ input = torch.rand(3, 5, 5, device=device, dtype=dtype) # 3 x 5 x 5
- expected_transform = torch.eye(3).unsqueeze(0) # 3 x 3
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0) # 3 x 3
expected_transform = expected_transform.to(device)
assert_allclose(f(input)[1], expected_transform)
- def test_same_on_batch(self, device):
+ def test_same_on_batch(self, device, dtype):
f = RandomGrayscale(p=0.5, same_on_batch=True)
- input = torch.eye(3).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
+ input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
- def test_opencv_true(self, device):
+ def test_opencv_true(self, device, dtype):
data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
[0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
[0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
@@ -1026,7 +1020,7 @@ class TestRandomGrayscale:
img_gray = kornia.augmentation.RandomGrayscale(p=1.)(data)
assert_allclose(img_gray, expected)
- def test_opencv_false(self, device):
+ def test_opencv_false(self, device, dtype):
data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
[0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
[0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
@@ -1051,7 +1045,7 @@ class TestRandomGrayscale:
img_gray = kornia.augmentation.RandomGrayscale(p=0.)(data)
assert_allclose(img_gray, expected)
- def test_opencv_true_batch(self, device):
+ def test_opencv_true_batch(self, device, dtype):
data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
[0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
[0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
@@ -1096,7 +1090,7 @@ class TestRandomGrayscale:
img_gray = kornia.augmentation.RandomGrayscale(p=1.)(data)
assert_allclose(img_gray, expected)
- def test_opencv_false_batch(self, device):
+ def test_opencv_false_batch(self, device, dtype):
data = torch.tensor([[[0.3944633, 0.8597369, 0.1670904, 0.2825457, 0.0953912],
[0.1251704, 0.8020709, 0.8933256, 0.9170977, 0.1497008],
[0.2711633, 0.1111478, 0.0783281, 0.2771807, 0.5487481],
@@ -1122,23 +1116,23 @@ class TestRandomGrayscale:
img_gray = kornia.augmentation.RandomGrayscale(p=0.)(data)
assert_allclose(img_gray, expected)
- def test_random_grayscale_sequential_batch(self, device):
+ def test_random_grayscale_sequential_batch(self, device, dtype):
f = nn.Sequential(
RandomGrayscale(p=0., return_transform=True),
RandomGrayscale(p=0., return_transform=True),
)
- input = torch.rand(2, 3, 5, 5).to(device) # 2 x 3 x 5 x 5
+ input = torch.rand(2, 3, 5, 5, device=device, dtype=dtype) # 2 x 3 x 5 x 5
expected = input
- expected_transform = torch.eye(3).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3
+ expected_transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).expand((2, 3, 3)) # 2 x 3 x 3
expected_transform = expected_transform.to(device)
assert_allclose(f(input)[0], expected)
assert_allclose(f(input)[1], expected_transform)
- def test_gradcheck(self, device):
- input = torch.rand((3, 5, 5)).to(device) # 3 x 3
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand((3, 5, 5), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.augmentation.RandomGrayscale(p=1.), (input,), raise_exception=True)
assert gradcheck(kornia.augmentation.RandomGrayscale(p=0.), (input,), raise_exception=True)
@@ -1146,25 +1140,25 @@ class TestRandomGrayscale:
class TestCenterCrop:
- def test_no_transform(self, device):
- inp = torch.rand(1, 2, 4, 4).to(device)
+ def test_no_transform(self, device, dtype):
+ inp = torch.rand(1, 2, 4, 4, device=device, dtype=dtype)
out = kornia.augmentation.CenterCrop(2)(inp)
assert out.shape == (1, 2, 2, 2)
- def test_transform(self, device):
- inp = torch.rand(1, 2, 5, 4).to(device)
+ def test_transform(self, device, dtype):
+ inp = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
out = kornia.augmentation.CenterCrop(2, return_transform=True)(inp)
assert len(out) == 2
assert out[0].shape == (1, 2, 2, 2)
assert out[1].shape == (1, 3, 3)
- def test_no_transform_tuple(self, device):
- inp = torch.rand(1, 2, 5, 4).to(device)
+ def test_no_transform_tuple(self, device, dtype):
+ inp = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
out = kornia.augmentation.CenterCrop((3, 4))(inp)
assert out.shape == (1, 2, 3, 4)
- def test_gradcheck(self, device):
- input = torch.rand(1, 2, 3, 4).to(device)
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.augmentation.CenterCrop(3), (input,), raise_exception=True)
@@ -1179,7 +1173,7 @@ class TestRandomRotation:
"p_batch=1.0, same_on_batch=False, return_transform=False)"
assert str(f) == repr
- def test_random_rotation(self, device):
+ def test_random_rotation(self, device, dtype):
# This is included in doctest
torch.manual_seed(0) # for random reproductibility
@@ -1214,7 +1208,7 @@ class TestRandomRotation:
assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4)
assert_allclose(f1(input), expected_2, rtol=1e-6, atol=1e-4)
- def test_batch_random_rotation(self, device):
+ def test_batch_random_rotation(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
@@ -1251,13 +1245,13 @@ class TestRandomRotation:
assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4)
- def test_same_on_batch(self, device):
+ def test_same_on_batch(self, device, dtype):
f = RandomRotation(degrees=40, same_on_batch=True)
- input = torch.eye(6).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
+ input = torch.eye(6, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
- def test_sequential(self, device):
+ def test_sequential(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
@@ -1299,7 +1293,7 @@ class TestRandomRotation:
assert_allclose(mat_2, expected_transform_2, rtol=1e-6, atol=1e-4)
@pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
+ def test_jit(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
@@ -1328,11 +1322,11 @@ class TestRandomRotation:
assert_allclose(actual, expected, rtol=1e-6, atol=1e-4)
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
- input = torch.rand((3, 3)).to(device) # 3 x 3
+ input = torch.rand((3, 3), device=device, dtype=dtype) # 3 x 3
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(RandomRotation(degrees=(15.0, 15.0), p=1.), (input, ), raise_exception=True)
@@ -1344,126 +1338,155 @@ class TestRandomCrop:
"resample=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, return_transform=False)"
assert str(f) == repr
- def test_no_padding(self, device):
+ def test_no_padding(self, device, dtype):
torch.manual_seed(0)
inp = torch.tensor([[[
[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]
- ]]]).to(device)
+ ]]], device=device, dtype=dtype)
expected = torch.tensor([[[
[3., 4., 5.],
[6., 7., 8.]
- ]]]).to(device)
+ ]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected)
- def test_no_padding_batch(self, device):
+ def test_no_padding_batch(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]
- ]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch.tensor([[
[0., 1., 2.],
[3., 4., 5.],
- ]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
rc = RandomCrop(size=(2, 3), padding=None, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected)
- def test_same_on_batch(self, device):
+ def test_same_on_batch(self, device, dtype):
f = RandomCrop(size=(2, 3), padding=1, same_on_batch=True, align_corners=True, p=1.)
- input = torch.eye(6).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
+ input = torch.eye(3, device=device, dtype=dtype).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
- def test_padding_batch_1(self, device):
+ def test_padding_batch_1(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]
- ]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch.tensor([[[
[0., 0., 0.],
[0., 1., 2.]
]], [[
[0., 0., 0.],
[1., 2., 0.]
- ]]]).to(device)
+ ]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), padding=1, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected)
- def test_padding_batch_2(self, device):
+ def test_padding_batch_2(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]
- ]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch.tensor([[[
[0., 1., 2.],
[3., 4., 5.]
]], [[
[1., 2., 10.],
[4., 5., 10.]
- ]]]).to(device)
+ ]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), padding=(0, 1), fill=10, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected)
- def test_padding_batch_3(self, device):
+ def test_padding_batch_3(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]
- ]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch.tensor([[[
[8., 8., 8.],
[8., 0., 1.]
]], [[
[8., 8., 8.],
[1., 2., 8.]
- ]]]).to(device)
+ ]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1.)
out = rc(inp)
- assert_allclose(out, expected)
+ assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
- def test_pad_if_needed(self, device):
+ def test_pad_if_needed(self, device, dtype):
torch.manual_seed(0)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
- ]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch.tensor([[
[9., 9., 9.],
[0., 1., 2.]
- ]]).repeat(batch_size, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1.)
out = rc(inp)
assert_allclose(out, expected)
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
- inp = torch.rand((3, 3, 3)).to(device) # 3 x 3
+ inp = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3
inp = utils.tensor_to_gradcheck_var(inp) # to var
assert gradcheck(RandomCrop(size=(3, 3), p=1.), (inp, ), raise_exception=True)
+ @pytest.mark.skip("Need to fix Union type")
+ def test_jit(self, device, dtype):
+ # Define script
+ op = RandomCrop(size=(3, 3), p=1.).forward
+ op_script = torch.jit.script(op)
+ img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
+
+ actual = op_script(img)
+ expected = kornia.center_crop3d(img)
+ assert_allclose(actual, expected)
+
+ @pytest.mark.skip("Need to fix Union type")
+ def test_jit_trace(self, device, dtype):
+ # Define script
+ op = RandomCrop(size=(3, 3), p=1.).forward
+ op_script = torch.jit.script(op)
+ # 1. Trace op
+ img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
+
+ op_trace = torch.jit.trace(op_script, (img,))
+
+ # 2. Generate new input
+ img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
+
+ # 3. Evaluate
+ actual = op_trace(img)
+ expected = op(img)
+ assert_allclose(actual, expected)
+
class TestRandomResizedCrop:
def test_smoke(self):
@@ -1489,14 +1512,14 @@ class TestRandomResizedCrop:
out = rrc(inp)
assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
- def test_same_on_batch(self, device):
+ def test_same_on_batch(self, device, dtype):
f = RandomResizedCrop(
size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0), same_on_batch=True)
input = torch.tensor([[
[0., 1., 2.],
[3., 4., 5.],
[6., 7., 8.]
- ]]).repeat(2, 1, 1, 1).to(device)
+ ]], device=device, dtype=dtype).repeat(2, 1, 1, 1)
res = f(input)
assert (res[0] == res[1]).all()
@@ -1539,9 +1562,9 @@ class TestRandomResizedCrop:
out = rrc(inp)
assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
- inp = torch.rand((1, 3, 3)).to(device) # 3 x 3
+ inp = torch.rand((1, 3, 3), device=device, dtype=dtype) # 3 x 3
inp = utils.tensor_to_gradcheck_var(inp) # to var
assert gradcheck(RandomResizedCrop(
size=(3, 3), scale=(1., 1.), ratio=(1., 1.)), (inp, ), raise_exception=True)
@@ -1554,9 +1577,9 @@ class TestRandomMotionBlur:
"border_type='constant', p=0.5, p_batch=1.0, same_on_batch=True, return_transform=False)"
assert str(f) == repr
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device, dtype):
torch.manual_seed(0) # for random reproductibility
- inp = torch.rand((1, 3, 11, 7)).to(device)
+ inp = torch.rand((1, 3, 11, 7), device=device, dtype=dtype)
inp = utils.tensor_to_gradcheck_var(inp) # to var
# TODO: Gradcheck for param random gen failed. Suspect get_motion_kernel2d issue.
params = {
diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.py
index 816f51dd5..bd548961d 100644
--- a/test/augmentation/test_augmentation_3d.py
+++ b/test/augmentation/test_augmentation_3d.py
@@ -16,6 +16,8 @@ from kornia.augmentation import (
RandomVerticalFlip3D,
RandomAffine3D,
RandomRotation3D,
+ RandomCrop3D,
+ CenterCrop3D,
RandomEqualize3D
)
@@ -765,6 +767,165 @@ class TestRandomRotation3D:
assert gradcheck(RandomRotation3D(degrees=(15.0, 15.0)), (input, ), raise_exception=True)
+class TestRandomCrop3D:
+ def test_smoke(self):
+ f = RandomCrop3D(size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, p=1.)
+ repr = "RandomCrop3D(crop_size=(2, 3, 4), padding=(0, 1, 2), fill=10, pad_if_needed=False, "\
+ "padding_mode=constant, resample=BILINEAR, p=1.0, p_batch=1.0, same_on_batch=False, "\
+ "return_transform=False)"
+ assert str(f) == repr
+
+ @pytest.mark.parametrize("batch_size", [1, 2])
+ def test_no_padding(self, batch_size, device, dtype):
+ torch.manual_seed(0)
+ inp = torch.tensor([[[[
+ [0., 1., 2., 3., 4.],
+ [5., 6., 7., 8., 9.],
+ [10, 11, 12, 13, 14],
+ [15, 16, 17, 18, 19],
+ [20, 21, 22, 23, 24]
+ ]]]], device=device, dtype=dtype).repeat(batch_size, 1, 5, 1, 1)
+ f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1.)
+ out = f(inp)
+ if batch_size == 1:
+ expected = torch.tensor([[[[
+ [10, 11, 12, 13],
+ [15, 16, 17, 18],
+ [20, 21, 22, 23]
+ ]]]], device=device, dtype=dtype).repeat(batch_size, 1, 2, 1, 1)
+ if batch_size == 2:
+ expected = torch.tensor([[[
+ [[0., 1., 2., 3.],
+ [5., 6., 7., 8.],
+ [10, 11, 12, 13]],
+ [[0., 1., 2., 3.],
+ [5., 6., 7., 8.],
+ [10, 11, 12, 13]],
+ ]], [[
+ [[1., 2., 3., 4.],
+ [6., 7., 8., 9.],
+ [11, 12, 13, 14]],
+ [[1., 2., 3., 4.],
+ [6., 7., 8., 9.],
+ [11, 12, 13, 14]],
+ ]]], device=device, dtype=dtype)
+
+ assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
+
+ def test_same_on_batch(self, device, dtype):
+ f = RandomCrop3D(size=(2, 3, 4), padding=None, align_corners=True, p=1., same_on_batch=True)
+ input = torch.eye(6).unsqueeze(dim=0).unsqueeze(dim=0).unsqueeze(dim=0).repeat(2, 3, 5, 1, 1)
+ res = f(input)
+ assert (res[0] == res[1]).all()
+
+ @pytest.mark.parametrize("padding", [1, (1, 1, 1), (1, 1, 1, 1, 1, 1)])
+ def test_padding_batch(self, padding, device, dtype):
+ torch.manual_seed(0)
+ batch_size = 2
+ inp = torch.tensor([[[
+ [0., 1., 2.],
+ [3., 4., 5.],
+ [6., 7., 8.]
+ ]]], device=device, dtype=dtype).repeat(batch_size, 1, 3, 1, 1)
+ expected = torch.tensor([[[
+ [[10, 10, 10, 10],
+ [10, 0., 1., 2.],
+ [10, 3., 4., 5.]],
+ [[10, 10, 10, 10],
+ [10, 0., 1., 2.],
+ [10, 3., 4., 5.]],
+ ]], [[
+ [[10, 10, 10, 10],
+ [0., 1., 2., 10],
+ [3., 4., 5., 10]],
+ [[10, 10, 10, 10],
+ [0., 1., 2., 10],
+ [3., 4., 5., 10]],
+ ]]], device=device, dtype=dtype)
+ f = RandomCrop3D(size=(2, 3, 4), fill=10., padding=padding, align_corners=True, p=1.)
+ out = f(inp)
+
+ assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
+
+ def test_pad_if_needed(self, device, dtype):
+ torch.manual_seed(0)
+ inp = torch.tensor([[
+ [0., 1., 2.],
+ ]], device=device, dtype=dtype)
+ expected = torch.tensor([[[
+ [[9., 9., 9., 9.],
+ [9., 9., 9., 9.],
+ [9., 9., 9., 9.]],
+ [[9., 0., 1., 2.],
+ [9., 9., 9., 9.],
+ [9., 9., 9., 9.]],
+ ]]], device=device, dtype=dtype)
+ rc = RandomCrop3D(size=(2, 3, 4), pad_if_needed=True, fill=9, align_corners=True, p=1.)
+ out = rc(inp)
+
+ assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self, device, dtype):
+ torch.manual_seed(0) # for random reproductibility
+ inp = torch.rand((3, 3, 3), device=device, dtype=dtype) # 3 x 3
+ inp = utils.tensor_to_gradcheck_var(inp) # to var
+ assert gradcheck(RandomCrop3D(size=(3, 3, 3), p=1.), (inp, ), raise_exception=True)
+
+ @pytest.mark.skip("Need to fix Union type")
+ def test_jit(self, device, dtype):
+ # Define script
+ op = RandomCrop(size=(3, 3), p=1.).forward
+ op_script = torch.jit.script(op)
+ img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
+
+ actual = op_script(img)
+ expected = kornia.center_crop3d(img)
+ assert_allclose(actual, expected)
+
+ @pytest.mark.skip("Need to fix Union type")
+ def test_jit_trace(self, device, dtype):
+ # Define script
+ op = RandomCrop(size=(3, 3), p=1.).forward
+ op_script = torch.jit.script(op)
+ # 1. Trace op
+ img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
+
+ op_trace = torch.jit.trace(op_script, (img,))
+
+ # 2. Generate new input
+ img = torch.ones(1, 1, 5, 6, device=device, dtype=dtype)
+
+ # 3. Evaluate
+ actual = op_trace(img)
+ expected = op(img)
+ assert_allclose(actual, expected)
+
+
+class TestCenterCrop3D:
+
+ def test_no_transform(self, device, dtype):
+ inp = torch.rand(1, 2, 4, 4, 4, device=device, dtype=dtype)
+ out = kornia.augmentation.CenterCrop3D(2)(inp)
+ assert out.shape == (1, 2, 2, 2, 2)
+
+ def test_transform(self, device, dtype):
+ inp = torch.rand(1, 2, 5, 4, 8, device=device, dtype=dtype)
+ out = kornia.augmentation.CenterCrop3D(2, return_transform=True)(inp)
+ assert len(out) == 2
+ assert out[0].shape == (1, 2, 2, 2, 2)
+ assert out[1].shape == (1, 4, 4)
+
+ def test_no_transform_tuple(self, device, dtype):
+ inp = torch.rand(1, 2, 5, 4, 8, device=device, dtype=dtype)
+ out = kornia.augmentation.CenterCrop3D((3, 4, 5))(inp)
+ assert out.shape == (1, 2, 3, 4, 5)
+
+ def test_gradcheck(self, device, dtype):
+ input = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(kornia.augmentation.CenterCrop3D(3), (input,), raise_exception=True)
+
+
class TestRandomEqualize3D:
def test_smoke(self, device, dtype):
f = RandomEqualize3D(p=0.5)
diff --git a/test/geometry/epipolar/test_essential.py b/test/geometry/epipolar/test_essential.py
index 6703916d7..0b5749297 100644
--- a/test/geometry/epipolar/test_essential.py
+++ b/test/geometry/epipolar/test_essential.py
@@ -168,6 +168,7 @@ class TestEssentalFromRt:
E_from_Rt_norm = epi.normalize_transformation(E_from_Rt)
E_from_F_norm = epi.normalize_transformation(E_from_F)
+ # TODO: occasionally failed with error > 0.04
assert_allclose(E_from_Rt_norm, E_from_F_norm, rtol=1e-3, atol=1e-3)
def test_gradcheck(self, device):
diff --git a/test/geometry/transform/crop/test_crop2d.py b/test/geometry/transform/crop/test_crop2d.py
new file mode 100644
index 000000000..536e7f83b
--- /dev/null
+++ b/test/geometry/transform/crop/test_crop2d.py
@@ -0,0 +1,371 @@
+from typing import Tuple
+
+import pytest
+
+import kornia as kornia
+import kornia.testing as utils # test utils
+
+import torch
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+
+class TestBoundingBoxInferring:
+ def test_bounding_boxes_dim_inferring(self, device, dtype):
+ boxes = torch.tensor([[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype)
+
+ h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
+ assert (h, w) == (2, 3)
+
+ def test_bounding_boxes_dim_inferring_batch(self, device, dtype):
+ boxes = torch.tensor([[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ], [
+ [2., 2.],
+ [4., 2.],
+ [4., 3.],
+ [2., 3.],
+ ]], device=device, dtype=dtype)
+ h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
+ assert (h.unique().item(), w.unique().item()) == (2, 3)
+
+ def test_gradcheck(self, device, dtype):
+ boxes = torch.tensor([[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype)
+ boxes = utils.tensor_to_gradcheck_var(boxes)
+ assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape,
+ (boxes,), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = kornia.geometry.transform.crop.infer_box_shape
+ op_script = torch.jit.script(op)
+ # Define input
+ boxes = torch.tensor([[
+ [1., 1.],
+ [3., 1.],
+ [3., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype)
+
+ actual = op_script(boxes)
+ expected = op(boxes)
+ assert_allclose(actual, expected)
+
+
+class TestCropAndResize:
+ def test_crop(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]], device=device, dtype=dtype)
+
+ height, width = 2, 3
+ expected = torch.tensor(
+ [[[[6.7222, 7.1667, 7.6111],
+ [9.3889, 9.8333, 10.2778]]]], device=device, dtype=dtype)
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ patches = kornia.crop_and_resize(inp, boxes, (height, width))
+ assert_allclose(patches, expected)
+
+ def test_crop_batch(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]], [[
+ [1., 5., 9., 13.],
+ [2., 6., 10., 14.],
+ [3., 7., 11., 15.],
+ [4., 8., 12., 16.],
+ ]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[
+ [6., 7.],
+ [10., 11.],
+ ]], [[
+ [7., 15.],
+ [8., 16.],
+ ]]], device=device, dtype=dtype)
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ], [
+ [1., 2.],
+ [3., 2.],
+ [3., 3.],
+ [1., 3.],
+ ]], device=device, dtype=dtype) # 2x4x2
+
+ patches = kornia.crop_and_resize(inp, boxes, (2, 2), align_corners=True)
+ assert_allclose(patches, expected)
+
+ def test_crop_batch_broadcast(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]], [[
+ [1., 5., 9., 13.],
+ [2., 6., 10., 14.],
+ [3., 7., 11., 15.],
+ [4., 8., 12., 16.],
+ ]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[
+ [6., 7.],
+ [10., 11.],
+ ]], [[
+ [6., 10.],
+ [7., 11.],
+ ]]], device=device, dtype=dtype)
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ patches = kornia.crop_and_resize(inp, boxes, (2, 2), align_corners=True)
+ assert_allclose(patches, expected)
+
+ def test_gradcheck(self, device, dtype):
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype) # 1x4x2
+ boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var
+
+ assert gradcheck(kornia.crop_and_resize,
+ (img, boxes, (4, 2),),
+ raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = kornia.crop_and_resize
+ op_script = torch.jit.script(op)
+ # Define input
+ img = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]], device=device, dtype=dtype)
+ boxes = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ crop_height, crop_width = 4, 2
+ actual = op_script(img, boxes, (crop_height, crop_width))
+ expected = op(img, boxes, (crop_height, crop_width))
+ assert_allclose(actual, expected)
+
+
+class TestCenterCrop:
+ def test_center_crop_h2_w4(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ ]]], device=device, dtype=dtype)
+
+ out_crop = kornia.center_crop(inp, (2, 4))
+ assert_allclose(out_crop, expected)
+
+ def test_center_crop_h4_w2(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]], device=device, dtype=dtype)
+
+ height, width = 4, 2
+ expected = torch.tensor([[[
+ [2., 3.],
+ [6., 7.],
+ [10., 11.],
+ [14., 15.],
+ ]]], device=device, dtype=dtype)
+
+ out_crop = kornia.center_crop(inp, (4, 2))
+ assert_allclose(out_crop, expected)
+
+ def test_center_crop_h4_w2_batch(self, device, dtype):
+ inp = torch.tensor([
+ [[[1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.]]],
+ [[[1., 5., 9., 13.],
+ [2., 6., 10., 14.],
+ [3., 7., 11., 15.],
+ [4., 8., 12., 16.]]]
+ ], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[
+ [2., 3.],
+ [6., 7.],
+ [10., 11.],
+ [14., 15.],
+ ]], [[
+ [5., 9.],
+ [6., 10.],
+ [7., 11.],
+ [8., 12.],
+ ]]], device=device, dtype=dtype)
+
+ out_crop = kornia.center_crop(inp, (4, 2))
+ assert_allclose(out_crop, expected)
+
+ def test_gradcheck(self, device, dtype):
+ img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+
+ assert gradcheck(kornia.center_crop, (img, (4, 2),), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = kornia.center_crop
+ op_script = torch.jit.script(op)
+ # Define input
+ img = torch.ones(1, 2, 5, 4, device=device, dtype=dtype)
+
+ actual = op_script(img, (4, 2))
+ expected = op(img, (4, 2))
+ assert_allclose(actual, expected)
+
+ def test_jit_trace(self, device, dtype):
+ # Define script
+ op = kornia.center_crop
+ op_script = torch.jit.script(op)
+ # Define input
+ img = torch.ones(2, 1, 6, 3, device=device, dtype=dtype)
+ op_trace = torch.jit.trace(op_script, (img, (torch.tensor(2), torch.tensor(3))))
+ img = torch.ones(2, 1, 6, 3, device=device, dtype=dtype)
+ # Run
+ actual = op_trace(img, (torch.tensor(2), torch.tensor(3)))
+ expected = op(img, (2, 3))
+ assert_allclose(actual, expected)
+
+
+class TestCropByBoxes:
+ def test_crop_by_boxes_no_resizing(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]], device=device, dtype=dtype)
+
+ src = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ dst = torch.tensor([[
+ [0., 0.],
+ [1., 0.],
+ [1., 1.],
+ [0., 1.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ expected = torch.tensor([[[
+ [6., 7.],
+ [10., 11.],
+ ]]], device=device, dtype=dtype)
+
+ patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst, align_corners=True)
+ assert_allclose(patches, expected)
+
+ def test_crop_by_boxes_resizing(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]], device=device, dtype=dtype)
+
+ src = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ dst = torch.tensor([[
+ [0., 0.],
+ [2., 0.],
+ [2., 1.],
+ [0., 1.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ expected = torch.tensor([[[
+ [6., 6.5, 7.],
+ [10., 10.5, 11.],
+ ]]], device=device, dtype=dtype)
+
+ patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst, align_corners=True)
+ assert_allclose(patches, expected)
+
+ def test_gradcheck(self, device, dtype):
+ inp = torch.randn((1, 1, 3, 3), device=device, dtype=dtype)
+ src = torch.tensor([[
+ [1., 0.],
+ [2., 0.],
+ [2., 1.],
+ [1., 1.]]], device=device, dtype=dtype)
+ dst = torch.tensor([[
+ [0., 0.],
+ [1., 0.],
+ [1., 1.],
+ [0., 1.]]], device=device, dtype=dtype)
+
+ inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
+
+ assert gradcheck(kornia.geometry.transform.crop.crop_by_boxes,
+ (inp, src, dst,),
+ raise_exception=True)
diff --git a/test/geometry/transform/crop/test_crop3d.py b/test/geometry/transform/crop/test_crop3d.py
new file mode 100644
index 000000000..6ade68d72
--- /dev/null
+++ b/test/geometry/transform/crop/test_crop3d.py
@@ -0,0 +1,366 @@
+from typing import Tuple
+
+import pytest
+
+import kornia as kornia
+import kornia.testing as utils # test utils
+
+import torch
+from torch.testing import assert_allclose
+from torch.autograd import gradcheck
+
+
+class TestBoundingBoxInferring3D:
+ def test_bounding_boxes_dim_inferring(self, device):
+ boxes = torch.tensor([
+ [[0, 1, 2],
+ [10, 1, 2],
+ [10, 21, 2],
+ [0, 21, 2],
+ [0, 1, 32],
+ [10, 1, 32],
+ [10, 21, 32],
+ [0, 21, 32]],
+ [[3, 4, 5],
+ [43, 4, 5],
+ [43, 54, 5],
+ [3, 54, 5],
+ [3, 4, 65],
+ [43, 4, 65],
+ [43, 54, 65],
+ [3, 54, 65]]]) # 2x8x3
+ d, h, w = kornia.geometry.transform.crop.infer_box_shape3d(boxes)
+
+ assert (d == torch.tensor([31, 61])).all()
+ assert (h == torch.tensor([21, 51])).all()
+ assert (w == torch.tensor([11, 41])).all()
+
+ def test_gradcheck(self, device, dtype):
+ boxes = torch.tensor([[
+ [0, 1, 2],
+ [10, 1, 2],
+ [10, 21, 2],
+ [0, 21, 2],
+ [0, 1, 32],
+ [10, 1, 32],
+ [10, 21, 32],
+ [0, 21, 32]
+ ]], device=device, dtype=dtype)
+ boxes = utils.tensor_to_gradcheck_var(boxes)
+ assert gradcheck(kornia.kornia.geometry.transform.crop.infer_box_shape3d,
+ (boxes,), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = kornia.infer_box_shape3d
+ op_script = torch.jit.script(op)
+
+ boxes = torch.tensor([[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]], device=device, dtype=dtype) # 1x8x3
+
+ actual = op_script(boxes)
+ expected = op(boxes)
+ assert_allclose(actual, expected)
+
+
+class TestCropAndResize3D:
+ def test_crop(self, device, dtype):
+ inp = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+
+ depth, height, width = 2, 2, 2
+ expected = torch.tensor([[[
+ [[25.1667, 27.1667],
+ [30.5000, 32.5000]],
+ [[46.5000, 48.5000],
+ [51.8333, 53.8333]]]]], device=device, dtype=dtype)
+
+ boxes = torch.tensor([[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]], device=device, dtype=dtype) # 1x8x3
+
+ patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width))
+ assert_allclose(patches, expected)
+
+ def test_crop_batch(self, device, dtype):
+ inp = torch.cat([
+ torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4),
+ torch.arange(0., 128., step=2, device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ ], dim=0)
+
+ depth, height, width = 2, 2, 2
+ expected = torch.tensor([
+ [[[[16.0000, 19.0000],
+ [24.0000, 27.0000]],
+ [[48.0000, 51.0000],
+ [56.0000, 59.0000]]]],
+ [[[[0.0000, 6.0000],
+ [16.0000, 22.0000]],
+ [[64.0000, 70.0000],
+ [80.0000, 86.0000]]]]
+ ], device=device, dtype=dtype)
+
+ boxes = torch.tensor([[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ], [
+ [0, 0, 0],
+ [3, 0, 0],
+ [3, 2, 0],
+ [0, 2, 0],
+ [0, 0, 2],
+ [3, 0, 2],
+ [3, 2, 2],
+ [0, 2, 2],
+ ]], device=device, dtype=dtype) # 2x8x3
+
+ patches = kornia.crop_and_resize3d(inp, boxes, (depth, height, width), align_corners=True)
+ assert_allclose(patches, expected)
+
+ def test_gradcheck(self, device, dtype):
+ img = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+
+ boxes = torch.tensor([[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]], device=device, dtype=dtype) # 1x8x3
+ boxes = utils.tensor_to_gradcheck_var(boxes, requires_grad=False) # to var
+
+ assert gradcheck(kornia.crop_and_resize3d, (img, boxes, (4, 3, 2),), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = kornia.crop_and_resize3d
+ op_script = torch.jit.script(op)
+
+ img = torch.arange(0., 64., device=device, dtype=dtype).view(1, 1, 4, 4, 4)
+
+ boxes = torch.tensor([[
+ [0, 0, 1],
+ [3, 0, 1],
+ [3, 2, 1],
+ [0, 2, 1],
+ [0, 0, 3],
+ [3, 0, 3],
+ [3, 2, 3],
+ [0, 2, 3],
+ ]], device=device, dtype=dtype) # 1x8x3
+
+ actual = op_script(img, boxes, (4, 3, 2))
+ expected = op(img, boxes, (4, 3, 2))
+ assert_allclose(actual, expected)
+
+
+class TestCenterCrop3D:
+ @pytest.mark.parametrize("crop_size", [(3, 5, 7), (5, 3, 7), (7, 3, 5)])
+ def test_center_crop_357(self, crop_size, device, dtype):
+ inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ expected = inp[
+ :, :,
+ (inp.size(2) // 2 - crop_size[0] // 2):(inp.size(2) // 2 + crop_size[0] // 2 + 1),
+ (inp.size(3) // 2 - crop_size[1] // 2):(inp.size(3) // 2 + crop_size[1] // 2 + 1),
+ (inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)
+ ]
+ out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)
+ assert_allclose(out_crop, expected)
+
+ @pytest.mark.parametrize("crop_size", [(3, 5, 7), (5, 3, 7), (7, 3, 5)])
+ def test_center_crop_357_batch(self, crop_size, device, dtype):
+ inp = torch.cat([
+ torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7),
+ torch.arange(343., 686., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ ])
+ expected = inp[
+ :, :,
+ (inp.size(2) // 2 - crop_size[0] // 2):(inp.size(2) // 2 + crop_size[0] // 2 + 1),
+ (inp.size(3) // 2 - crop_size[1] // 2):(inp.size(3) // 2 + crop_size[1] // 2 + 1),
+ (inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)
+ ]
+ out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)
+ assert_allclose(out_crop, expected)
+
+ def test_gradcheck(self, device, dtype):
+ img = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+
+ assert gradcheck(kornia.center_crop3d, (img, (3, 5, 7),), raise_exception=True)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = kornia.center_crop3d
+ op_script = torch.jit.script(op)
+ img = torch.ones(4, 3, 5, 6, 7, device=device, dtype=dtype)
+
+ actual = op_script(img, (4, 3, 2))
+ expected = kornia.center_crop3d(img, (4, 3, 2))
+ assert_allclose(actual, expected)
+
+ def test_jit_trace(self, device, dtype):
+ # Define script
+ op = kornia.center_crop3d
+ op_script = torch.jit.script(op)
+ # 1. Trace op
+ img = torch.ones(4, 3, 5, 6, 7, device=device, dtype=dtype)
+
+ op_trace = torch.jit.trace(
+ op_script,
+ (img, (torch.tensor(4), torch.tensor(3), torch.tensor(2))))
+
+ # 2. Generate new input
+ img = torch.ones(4, 3, 5, 6, 7, device=device, dtype=dtype)
+
+ # 3. Evaluate
+ crop_height, crop_width = 2, 3
+ actual = op_trace(
+ img, (torch.tensor(4), torch.tensor(3), torch.tensor(2)))
+ expected = op(img, (4, 3, 2))
+ assert_allclose(actual, expected)
+
+
+class TestCropByBoxes3D:
+ def test_crop_by_boxes_no_resizing(self, device, dtype):
+ inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ src_box = torch.tensor([[
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]], device=device, dtype=dtype) # 1x8x3
+ dst_box = torch.tensor([[
+ [0., 0., 0.],
+ [2., 0., 0.],
+ [2., 2., 0.],
+ [0., 2., 0.],
+ [0., 0., 1.],
+ [2., 0., 1.],
+ [2., 2., 1.],
+ [0., 2., 1.],
+ ]], device=device, dtype=dtype) # 1x8x3
+
+ expected = inp[:, :, 1:3, 1:4, 1:4]
+
+ patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)
+ assert_allclose(patches, expected)
+
+ def test_crop_by_boxes_resizing(self, device, dtype):
+ inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)
+ src_box = torch.tensor([[
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]], device=device, dtype=dtype) # 1x8x3
+ dst_box = torch.tensor([[
+ [0., 0., 0.],
+ [1., 0., 0.],
+ [1., 1., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ [1., 0., 1.],
+ [1., 1., 1.],
+ [0., 1., 1.],
+ ]], device=device, dtype=dtype) # 1x8x3
+
+ expected = torch.tensor([[[
+ [[57.0000, 59.0000],
+ [71.0000, 73.0000]],
+ [[106.0000, 108.0000],
+ [120.0000, 122.0000]]
+ ]]], device=device, dtype=dtype)
+
+ patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)
+ assert_allclose(patches, expected)
+
+ def test_jit(self, device, dtype):
+ # Define script
+ op = kornia.geometry.transform.crop.crop_by_boxes3d
+ op_script = torch.jit.script(op)
+ # Define input
+ inp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)
+ src_box = torch.tensor([[
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]], device=device, dtype=dtype) # 1x8x3
+ dst_box = torch.tensor([[
+ [0., 0., 0.],
+ [1., 0., 0.],
+ [1., 1., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ [1., 0., 1.],
+ [1., 1., 1.],
+ [0., 1., 1.],
+ ]], device=device, dtype=dtype) # 1x8x3
+
+ actual = op_script(inp, src_box, dst_box, align_corners=True)
+ expected = op(inp, src_box, dst_box, align_corners=True)
+ assert_allclose(actual, expected)
+
+ def test_gradcheck(self, device, dtype):
+ inp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)
+ src_box = torch.tensor([[
+ [1., 1., 1.],
+ [3., 1., 1.],
+ [3., 3., 1.],
+ [1., 3., 1.],
+ [1., 1., 2.],
+ [3., 1., 2.],
+ [3., 3., 2.],
+ [1., 3., 2.],
+ ]], device=device, dtype=dtype) # 1x8x3
+ dst_box = torch.tensor([[
+ [0., 0., 0.],
+ [1., 0., 0.],
+ [1., 1., 0.],
+ [0., 1., 0.],
+ [0., 0., 1.],
+ [1., 0., 1.],
+ [1., 1., 1.],
+ [0., 1., 1.],
+ ]], device=device, dtype=dtype) # 1x8x3
+
+ inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
+
+ assert gradcheck(kornia.geometry.transform.crop.crop_by_boxes3d,
+ (inp, src_box, dst_box,), raise_exception=True)
diff --git a/test/geometry/transform/test_crop.py b/test/geometry/transform/test_crop.py
deleted file mode 100644
index 997e2246c..000000000
--- a/test/geometry/transform/test_crop.py
+++ /dev/null
@@ -1,391 +0,0 @@
-from typing import Tuple
-
-import pytest
-
-import kornia as kornia
-import kornia.testing as utils # test utils
-
-import torch
-from torch.testing import assert_allclose
-from torch.autograd import gradcheck
-
-
-class TestBoundingBoxInferring:
- def test_bounding_boxes_dim_inferring(self, device):
- boxes = torch.tensor([[
- [1., 1.],
- [3., 1.],
- [3., 2.],
- [1., 2.],
- ]]).to(device)
- expected_height = 2
- expected_width = 3
- h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
- assert (h, w) == (expected_height, expected_width)
-
- def test_bounding_boxes_dim_inferring_batch(self, device):
- boxes = torch.tensor([[
- [1., 1.],
- [3., 1.],
- [3., 2.],
- [1., 2.],
- ], [
- [2., 2.],
- [4., 2.],
- [4., 3.],
- [2., 3.],
- ]]).to(device)
- expected_height = 2
- expected_width = 3
- h, w = kornia.geometry.transform.crop.infer_box_shape(boxes)
- assert (h.unique().item(), w.unique().item()) == (expected_height, expected_width)
-
- @pytest.mark.skip(reason="Crashes with pytorch internal error")
- # RuntimeError: isDifferentiableType(variable.scalar_type()) INTERNAL ASSERT FAILED at
- # "/opt/conda/conda-bld/pytorch_1595629417679/work/torch/csrc/autograd/functions/utils.h":59,
- # please report a bug to PyTorch.
- def test_gradcheck(self, device):
- boxes = torch.tensor([[
- [1., 1.],
- [3., 1.],
- [3., 2.],
- [1., 2.],
- ]]).to(device)
- boxes = utils.tensor_to_gradcheck_var(boxes)
- assert gradcheck(kornia.kornia.geometry.transform.crop._infer_bounding_box,
- (boxes,), raise_exception=True)
-
-
-class TestCropAndResize:
- def test_crop(self, device):
- inp = torch.tensor([[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]).to(device)
-
- height, width = 2, 3
- expected = torch.tensor(
- [[[6.7222, 7.1667, 7.6111],
- [9.3889, 9.8333, 10.2778]]]).to(device)
-
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]]).to(device) # 1x4x2
-
- patches = kornia.crop_and_resize(inp, boxes, (height, width))
- assert_allclose(patches, expected)
-
- def test_crop_batch(self, device):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]], [[
- [1., 5., 9., 13.],
- [2., 6., 10., 14.],
- [3., 7., 11., 15.],
- [4., 8., 12., 16.],
- ]]]).to(device)
-
- height, width = 2, 2
- expected = torch.tensor([[[
- [6., 7.],
- [10., 11.],
- ]], [[
- [7., 15.],
- [8., 16.],
- ]]]).to(device)
-
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ], [
- [1., 2.],
- [3., 2.],
- [3., 3.],
- [1., 3.],
- ]]).to(device) # 2x4x2
-
- patches = kornia.crop_and_resize(inp, boxes, (height, width), align_corners=True)
- assert_allclose(patches, expected)
-
- def test_crop_batch_broadcast(self, device):
- inp = torch.tensor([[[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]], [[
- [1., 5., 9., 13.],
- [2., 6., 10., 14.],
- [3., 7., 11., 15.],
- [4., 8., 12., 16.],
- ]]]).to(device)
-
- height, width = 2, 2
- expected = torch.tensor([[[
- [6., 7.],
- [10., 11.],
- ]], [[
- [6., 10.],
- [7., 11.],
- ]]]).to(device)
-
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]]).to(device) # 1x4x2
-
- patches = kornia.crop_and_resize(inp, boxes, (height, width), align_corners=True)
- assert_allclose(patches, expected)
-
- def test_gradcheck(self, device):
- batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width).to(device)
- img = utils.tensor_to_gradcheck_var(img) # to var
-
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]]).to(device) # 1x4x2
- boxes = utils.tensor_to_gradcheck_var(
- boxes, requires_grad=False) # to var
-
- crop_height, crop_width = 4, 2
- assert gradcheck(kornia.crop_and_resize,
- (img, boxes, (crop_height, crop_width),),
- raise_exception=True)
-
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- @torch.jit.script
- def op_script(input: torch.Tensor,
- boxes: torch.Tensor,
- size: Tuple[int, int]) -> torch.Tensor:
- return kornia.crop_and_resize(input, boxes, size)
- img = torch.tensor([[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]).to(device)
- boxes = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]]).to(device) # 1x4x2
-
- crop_height, crop_width = 4, 2
- actual = op_script(img, boxes, (crop_height, crop_width))
- expected = kornia.crop_and_resize(img, boxes, (crop_height, crop_width))
- assert_allclose(actual, expected)
-
-
-class TestCenterCrop:
- def test_center_crop_h2_w4(self, device):
- inp = torch.tensor([[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]).to(device)
-
- height, width = 2, 4
- expected = torch.tensor([[
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- ]]).to(device)
-
- out_crop = kornia.center_crop(inp, (height, width))
- assert_allclose(out_crop, expected)
-
- def test_center_crop_h4_w2(self, device):
- inp = torch.tensor([[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]).to(device)
-
- height, width = 4, 2
- expected = torch.tensor([[
- [2., 3.],
- [6., 7.],
- [10., 11.],
- [14., 15.],
- ]]).to(device)
-
- out_crop = kornia.center_crop(inp, (height, width))
- assert_allclose(out_crop, expected)
-
- def test_center_crop_h4_w2_batch(self, device):
- inp = torch.tensor([[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ], [
- [1., 5., 9., 13.],
- [2., 6., 10., 14.],
- [3., 7., 11., 15.],
- [4., 8., 12., 16.],
- ]]).to(device)
-
- height, width = 4, 2
- expected = torch.tensor([[
- [2., 3.],
- [6., 7.],
- [10., 11.],
- [14., 15.],
- ], [
- [5., 9.],
- [6., 10.],
- [7., 11.],
- [8., 12.],
- ]]).to(device)
-
- out_crop = kornia.center_crop(inp, (height, width))
- assert_allclose(out_crop, expected)
-
- def test_gradcheck(self, device):
- batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.rand(batch_size, channels, height, width).to(device)
- img = utils.tensor_to_gradcheck_var(img) # to var
-
- crop_height, crop_width = 4, 2
- assert gradcheck(kornia.center_crop, (img, (crop_height, crop_width),),
- raise_exception=True)
-
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- @torch.jit.script
- def op_script(input: torch.Tensor,
- size: Tuple[int, int]) -> torch.Tensor:
- return kornia.center_crop(input, size)
- batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.ones(batch_size, channels, height, width).to(device)
-
- crop_height, crop_width = 4, 2
- actual = op_script(img, (crop_height, crop_width))
- expected = kornia.center_crop(img, (crop_height, crop_width))
- assert_allclose(actual, expected)
-
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit_trace(self, device):
- @torch.jit.script
- def op_script(input: torch.Tensor,
- size: Tuple[int, int]) -> torch.Tensor:
- return kornia.center_crop(input, size)
- # 1. Trace op
- batch_size, channels, height, width = 1, 2, 5, 4
- img = torch.ones(batch_size, channels, height, width).to(device)
-
- crop_height, crop_width = 4, 2
- op_trace = torch.jit.trace(
- op_script,
- (img, (torch.tensor(crop_height), torch.tensor(crop_width))))
-
- # 2. Generate new input
- batch_size, channels, height, width = 2, 1, 6, 3
- img = torch.ones(batch_size, channels, height, width).to(device)
-
- # 3. Evaluate
- crop_height, crop_width = 2, 3
- actual = op_trace(
- img, (torch.tensor(crop_height), torch.tensor(crop_width)))
- expected = kornia.center_crop(img, (crop_height, crop_width))
- assert_allclose(actual, expected)
-
-
-class TestCropByBoxes:
- def test_crop_by_boxes_no_resizing(self, device):
- inp = torch.tensor([[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]).to(device)
-
- src = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]]).to(device) # 1x4x2
-
- dst = torch.tensor([[
- [0., 0.],
- [1., 0.],
- [1., 1.],
- [0., 1.],
- ]]).to(device) # 1x4x2
-
- expected = torch.tensor([[
- [6., 7.],
- [10., 11.],
- ]]).to(device)
-
- patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst, align_corners=True)
- assert_allclose(patches, expected)
-
- def test_crop_by_boxes_resizing(self, device):
- inp = torch.tensor([[
- [1., 2., 3., 4.],
- [5., 6., 7., 8.],
- [9., 10., 11., 12.],
- [13., 14., 15., 16.],
- ]]).to(device)
-
- src = torch.tensor([[
- [1., 1.],
- [2., 1.],
- [2., 2.],
- [1., 2.],
- ]]).to(device) # 1x4x2
-
- dst = torch.tensor([[
- [0., 0.],
- [2., 0.],
- [2., 1.],
- [0., 1.],
- ]]).to(device) # 1x4x2
-
- expected = torch.tensor([[
- [6., 6.5, 7.],
- [10., 10.5, 11.],
- ]]).to(device)
-
- patches = kornia.geometry.transform.crop_by_boxes(inp, src, dst, align_corners=True)
- assert_allclose(patches, expected)
-
- def test_gradcheck(self, device):
- inp = torch.randn((1, 3, 3)).to(device)
- src = torch.tensor([[
- [1., 0.],
- [2., 0.],
- [2., 1.],
- [1., 1.]]]).to(device)
- dst = torch.tensor([[
- [0., 0.],
- [1., 0.],
- [1., 1.],
- [0., 1.]]]).to(device)
-
- inp = utils.tensor_to_gradcheck_var(inp, requires_grad=True) # to var
-
- assert gradcheck(kornia.geometry.transform.crop_by_boxes,
- (inp, src, dst,),
- raise_exception=True)
diff --git a/test/geometry/test_projwarp.py b/test/geometry/transform/test_projwarp.py
similarity index 77%
rename from test/geometry/test_projwarp.py
rename to test/geometry/transform/test_projwarp.py
index 68b1e2131..f3221adc8 100644
--- a/test/geometry/test_projwarp.py
+++ b/test/geometry/transform/test_projwarp.py
@@ -5,6 +5,7 @@ from torch.autograd import gradcheck
from torch.testing import assert_allclose
import kornia
+import kornia.testing as utils # test utils
import kornia.geometry.transform.projwarp as proj
@@ -17,7 +18,7 @@ class TestWarpProjective:
def test_smoke(self, device, dtype):
input = torch.rand(1, 3, 3, 4, 5, device=device, dtype=dtype)
P = torch.rand(1, 3, 4, device=device, dtype=dtype)
- output = proj.warp_projective(input, P, (3, 4, 5))
+ output = proj.warp_affine3d(input, P, (3, 4, 5))
assert output.shape == (1, 3, 3, 4, 5)
@pytest.mark.parametrize("batch_size", [1, 3])
@@ -27,14 +28,14 @@ class TestWarpProjective:
B, C = batch_size, num_channels
input = torch.rand(B, C, 3, 4, 5, device=device, dtype=dtype)
P = torch.rand(B, 3, 4, device=device, dtype=dtype)
- output = proj.warp_projective(input, P, out_shape)
+ output = proj.warp_affine3d(input, P, out_shape)
assert list(output.shape) == [B, C] + list(out_shape)
def test_gradcheck(self, device):
# generate input data
input = torch.rand(1, 3, 3, 4, 5, device=device, dtype=torch.float64, requires_grad=True)
P = torch.rand(1, 3, 4, device=device, dtype=torch.float64)
- assert gradcheck(proj.warp_projective, (input, P, (3, 3, 3)), raise_exception=True)
+ assert gradcheck(proj.warp_affine3d, (input, P, (3, 3, 3)), raise_exception=True)
def test_forth_back(self, device, dtype):
out_shape = (3, 4, 5)
@@ -42,7 +43,7 @@ class TestWarpProjective:
P = torch.rand(2, 3, 4, device=device, dtype=dtype)
P = kornia.geometry.convert_affinematrix_to_homography3d(P)
P_hat = (P.inverse() @ P)[:, :3]
- output = proj.warp_projective(input, P_hat, out_shape)
+ output = proj.warp_affine3d(input, P_hat, out_shape)
assert_allclose(output, input, rtol=1e-4, atol=1e-4)
def test_rotate_x(self, device, dtype):
@@ -82,7 +83,7 @@ class TestWarpProjective:
scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
- output = proj.warp_projective(input, P, (3, 3, 3))
+ output = proj.warp_affine3d(input, P, (3, 3, 3))
assert_allclose(output, expected)
def test_rotate_y(self, device, dtype):
@@ -122,7 +123,7 @@ class TestWarpProjective:
scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
- output = proj.warp_projective(input, P, (3, 3, 3))
+ output = proj.warp_affine3d(input, P, (3, 3, 3))
assert_allclose(output, expected)
def test_rotate_z(self, device, dtype):
@@ -162,7 +163,7 @@ class TestWarpProjective:
scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
- output = proj.warp_projective(input, P, (3, 3, 3))
+ output = proj.warp_affine3d(input, P, (3, 3, 3))
assert_allclose(output, expected)
def test_rotate_y_large(self, device, dtype):
@@ -227,7 +228,7 @@ class TestWarpProjective:
scales: torch.Tensor = torch.ones_like(angles)
P = proj.get_projective_transform(center, angles, scales)
- output = proj.warp_projective(input, P, (3, 3, 3))
+ output = proj.warp_affine3d(input, P, (3, 3, 3))
assert_allclose(output, expected)
@@ -302,3 +303,54 @@ class TestGetRotationMatrix3d:
angle = torch.rand(1, 3, device=device, dtype=torch.float64)
scales: torch.Tensor = torch.ones_like(angle)
assert gradcheck(proj.get_projective_transform, (center, angle, scales), raise_exception=True)
+
+
[email protected]("batch_size", [1, 2])
+def test_get_perspective_transform3d(batch_size, device, dtype):
+ torch.manual_seed(0)
+ src = kornia.bbox_generator3d(
+ torch.randint_like(torch.ones(batch_size), 0, 50, device=device, dtype=dtype),
+ torch.randint_like(torch.ones(batch_size), 0, 50, device=device, dtype=dtype),
+ torch.randint_like(torch.ones(batch_size), 0, 50, device=device, dtype=dtype),
+ torch.randint(0, 50, (1,), device=device, dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1,), device=device, dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1,), device=device, dtype=dtype).repeat(batch_size),
+ )
+ dst = kornia.bbox_generator3d(
+ torch.randint_like(torch.ones(batch_size), 0, 50, device=device, dtype=dtype),
+ torch.randint_like(torch.ones(batch_size), 0, 50, device=device, dtype=dtype),
+ torch.randint_like(torch.ones(batch_size), 0, 50, device=device, dtype=dtype),
+ torch.randint(0, 50, (1,), device=device, dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1,), device=device, dtype=dtype).repeat(batch_size),
+ torch.randint(0, 50, (1,), device=device, dtype=dtype).repeat(batch_size),
+ )
+ out = kornia.get_perspective_transform3d(src, dst)
+ if batch_size == 1:
+ expected = torch.tensor([[
+ [3.3000, 0.0000, 0.0000, -118.2000],
+ [0.0000, 0.0769, 0.0000, 0.0000],
+ [0.0000, 0.0000, 0.5517, 28.7930],
+ [0.0000, 0.0000, 0.0000, 1.0000]
+ ]])
+ if batch_size == 2:
+ expected = torch.tensor([
+ [[0.9630, 0.0000, 0.0000, -9.3702],
+ [0.0000, 2.0000, 0.0000, -49.9999],
+ [0.0000, 0.0000, 0.3830, 44.0213],
+ [0.0000, 0.0000, 0.0000, 1.0000]],
+ [[0.9630, 0.0000, 0.0000, -36.5555],
+ [0.0000, 2.0000, 0.0000, -14.0000],
+ [0.0000, 0.0000, 0.3830, 16.8940],
+ [0.0000, 0.0000, 0.0000, 1.0000]],
+ ])
+
+ assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
+
+ # compute gradient check
+ points_src = utils.tensor_to_gradcheck_var(src) # to var
+ points_dst = utils.tensor_to_gradcheck_var(dst) # to var
+ assert gradcheck(
+ kornia.get_perspective_transform3d, (
+ points_src,
+ points_dst,
+ ), raise_exception=True)
diff --git a/test/geometry/warp/test_homography_warper.py b/test/geometry/warp/test_homography_warper.py
index a181781e7..8851d44f7 100644
--- a/test/geometry/warp/test_homography_warper.py
+++ b/test/geometry/warp/test_homography_warper.py
@@ -292,3 +292,79 @@ class TestHomographyNormalTransform:
transform = kornia.normal_transform_pixel3d(depth, height, width)
output = kornia.transform_points(transform, input)
assert_allclose(output, expected)
+
+
+class TestHomographyWarper3D:
+
+ num_tests = 10
+ threshold = 0.1
+
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ def test_normalize_homography_identity(self, batch_size, device, dtype):
+ # create input data
+ input_shape = (4, 8, 5)
+ dst_homo_src = utils.create_eye_batch(batch_size=batch_size, eye_size=4).to(device=device, dtype=dtype)
+
+ res = torch.tensor([[[0.5000, 0.0, 0.0, -1.0],
+ [0.0, 0.2857, 0.0, -1.0],
+ [0.0, 0.0, 0.6667, -1.0],
+ [0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ norm = kornia.normal_transform_pixel3d(
+ input_shape[0], input_shape[1], input_shape[2]).to(device=device, dtype=dtype)
+ assert_allclose(norm, res, rtol=1e-4, atol=1e-4)
+
+ norm_homo = kornia.normalize_homography3d(
+ dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)
+ assert_allclose(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
+
+ norm_homo = kornia.normalize_homography3d(
+ dst_homo_src, input_shape, input_shape).to(device=device, dtype=dtype)
+ assert_allclose(norm_homo, dst_homo_src, rtol=1e-4, atol=1e-4)
+
+ # change output scale
+ norm_homo = kornia.normalize_homography3d(
+ dst_homo_src, input_shape, (input_shape[0] // 2, input_shape[1] * 2, input_shape[2] // 2)
+ ).to(device=device, dtype=dtype)
+ res = torch.tensor([[[4.0, 0.0, 0.0, 3.0],
+ [0.0, 0.4667, 0.0, -0.5333],
+ [0.0, 0.0, 3.0, 2.0],
+ [0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ assert_allclose(norm_homo, res, rtol=1e-4, atol=1e-4)
+
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ def test_normalize_homography_general(self, batch_size, device, dtype):
+ # create input data
+ dst_homo_src = torch.eye(4).to(device)
+ dst_homo_src[..., 0, 0] = 0.5
+ dst_homo_src[..., 1, 1] = 0.5
+ dst_homo_src[..., 2, 2] = 2.0
+ dst_homo_src[..., 0, 3] = 1.0
+ dst_homo_src[..., 1, 3] = 2.0
+ dst_homo_src[..., 2, 3] = 3.0
+ dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)
+
+ norm_homo = kornia.normalize_homography3d(dst_homo_src, (2, 2, 5), (2, 2, 5))
+ res = torch.tensor([[[0.5, 0.0, 0.0, 0.0],
+ [0.0, 0.5, 0.0, 3.5],
+ [0.0, 0.0, 2.0, 7.0],
+ [0.0, 0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ assert (norm_homo == res).all()
+
+ @pytest.mark.parametrize("offset", [1, 3, 7])
+ @pytest.mark.parametrize("shape", [(4, 5, 6), (2, 4, 6), (4, 3, 9), (5, 7, 8)])
+ def test_warp_grid_translation(self, shape, offset, device):
+ # create input data
+ depth, height, width = shape
+ dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=4).to(device)
+ dst_homo_src[..., 0, 3] = offset # apply offset in x
+ grid = kornia.create_meshgrid3d(depth, height, width, normalized_coordinates=False)
+ flow = kornia.warp_grid3d(grid, dst_homo_src)
+
+ # the grid the src plus the offset should be equal to the flow
+ # on the x-axis, y-axis remains the same.
+ assert_allclose(
+ grid[..., 0].to(device) + offset, flow[..., 0])
+ assert_allclose(
+ grid[..., 1].to(device), flow[..., 1])
+ assert_allclose(
+ grid[..., 2].to(device), flow[..., 2])