Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Remove deprecated code in `kornia.augmentation` (#2052)

João Gustavo A. Amorim5bc87aaf0a77
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index 3eb1f846c..19150b099 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -4,8 +4,8 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _singular_range_check, _tuple_range_reader
-from kornia.utils.helpers import _deprecated, _extract_device_dtype
+from kornia.augmentation.utils import _adapted_rsampling, _singular_range_check, _tuple_range_reader
+from kornia.utils.helpers import _extract_device_dtype
class AffineGenerator3D(RandomGeneratorBase):
@@ -217,130 +217,3 @@ class AffineGenerator3D(RandomGeneratorBase):
szx=torch.as_tensor(szx, device=_device, dtype=_dtype),
szy=torch.as_tensor(szy, device=_device, dtype=_dtype),
)
-
-
-@_deprecated(replace_with=AffineGenerator3D.__name__)
-def random_affine_generator3d(
- batch_size: int,
- depth: int,
- height: int,
- width: int,
- degrees: torch.Tensor,
- translate: Optional[torch.Tensor] = None,
- scale: Optional[torch.Tensor] = None,
- shears: Optional[torch.Tensor] = None,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
- r"""Get parameters for ```3d affine``` transformation random affine 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.
- degrees (torch.Tensor): Ranges of degrees with shape (3, 2) for yaw, pitch and roll.
- translate (torch.Tensor, optional): maximum absolute fraction with shape (3,) for horizontal, vertical
- and depthical translations (dx,dy,dz). Will not translate by default.
- scale (torch.Tensor, optional): scaling factor interval, e.g (a, b), then scale is
- randomly sampled from the range a <= scale <= b. Will keep original scale by default.
- shear (sequence or float, optional): Range of degrees to select from.
- Shaped as (6, 2) for 6 facet (xy, xz, yx, yz, zx, zy).
- The shear to the i-th facet in the range (-shear[i, 0], shear[i, 1]) will be applied.
- 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.
- - translations (torch.Tensor): element-wise translations with a shape of (B, 3).
- - center (torch.Tensor): element-wise center with a shape of (B, 3).
- - scale (torch.Tensor): element-wise scales with a shape of (B, 3).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
- - sxy (torch.Tensor): element-wise x-y-facet shears with a shape of (B,).
- - sxz (torch.Tensor): element-wise x-z-facet shears with a shape of (B,).
- - syx (torch.Tensor): element-wise y-x-facet shears with a shape of (B,).
- - syz (torch.Tensor): element-wise y-z-facet shears with a shape of (B,).
- - szx (torch.Tensor): element-wise z-x-facet shears with a shape of (B,).
- - szy (torch.Tensor): element-wise z-y-facet shears with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- if not (
- type(depth) is int and depth > 0 and type(height) is int and height > 0 and type(width) is int and width > 0
- ):
- raise AssertionError(f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}.")
-
- _device, _dtype = _extract_device_dtype([degrees, translate, scale, shears])
- if degrees.shape != torch.Size([3, 2]):
- raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
- degrees = degrees.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
- angles = torch.stack([yaw, pitch, roll], dim=1)
-
- # compute tensor ranges
- if scale is not None:
- if scale.shape != torch.Size([3, 2]):
- raise AssertionError(f"'scale' must be the shape of (3, 2). Got {scale.shape}.")
- scale = scale.to(device=device, dtype=dtype)
- scale = torch.stack(
- [
- _adapted_uniform((batch_size,), scale[0, 0], scale[0, 1], same_on_batch),
- _adapted_uniform((batch_size,), scale[1, 0], scale[1, 1], same_on_batch),
- _adapted_uniform((batch_size,), scale[2, 0], scale[2, 1], same_on_batch),
- ],
- dim=1,
- )
- else:
- scale = torch.ones(batch_size, device=device, dtype=dtype).reshape(batch_size, 1).repeat(1, 3)
-
- if translate is not None:
- if translate.shape != torch.Size([3]):
- raise AssertionError(f"'translate' must be the shape of (2). Got {translate.shape}.")
- translate = translate.to(device=device, dtype=dtype)
- max_dx: torch.Tensor = translate[0] * width
- max_dy: torch.Tensor = translate[1] * height
- max_dz: torch.Tensor = translate[2] * depth
- # translations should be in x,y,z
- translations = torch.stack(
- [
- _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
- _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
- _adapted_uniform((batch_size,), -max_dz, max_dz, same_on_batch),
- ],
- dim=1,
- )
- else:
- translations = torch.zeros((batch_size, 3), device=device, dtype=dtype)
-
- # center should be in x,y,z
- center: torch.Tensor = torch.tensor([width, height, depth], device=device, dtype=dtype).view(1, 3) / 2.0 - 0.5
- center = center.expand(batch_size, -1)
-
- if shears is not None:
- if shears.shape != torch.Size([6, 2]):
- raise AssertionError(f"'shears' must be the shape of (6, 2). Got {shears.shape}.")
- shears = shears.to(device=device, dtype=dtype)
- sxy = _adapted_uniform((batch_size,), shears[0, 0], shears[0, 1], same_on_batch)
- sxz = _adapted_uniform((batch_size,), shears[1, 0], shears[1, 1], same_on_batch)
- syx = _adapted_uniform((batch_size,), shears[2, 0], shears[2, 1], same_on_batch)
- syz = _adapted_uniform((batch_size,), shears[3, 0], shears[3, 1], same_on_batch)
- szx = _adapted_uniform((batch_size,), shears[4, 0], shears[4, 1], same_on_batch)
- szy = _adapted_uniform((batch_size,), shears[5, 0], shears[5, 1], same_on_batch)
- else:
- sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=device, dtype=dtype)
-
- return dict(
- translations=translations.to(device=_device, dtype=_dtype),
- center=center.to(device=_device, dtype=_dtype),
- scale=scale.to(device=_device, dtype=_dtype),
- angles=angles.to(device=_device, dtype=_dtype),
- sxy=sxy.to(device=_device, dtype=_dtype),
- sxz=sxz.to(device=_device, dtype=_dtype),
- syx=syx.to(device=_device, dtype=_dtype),
- syz=syz.to(device=_device, dtype=_dtype),
- szx=szx.to(device=_device, dtype=_dtype),
- szy=szy.to(device=_device, dtype=_dtype),
- )
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 4e43ccd90..8996852a1 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -4,10 +4,10 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
from kornia.core import Device, Tensor, tensor, zeros
from kornia.geometry.bbox import bbox_generator3d
-from kornia.utils.helpers import _deprecated, _extract_device_dtype
+from kornia.utils.helpers import _extract_device_dtype
class CropGenerator3D(RandomGeneratorBase):
@@ -233,125 +233,3 @@ def center_crop_generator3d(
dtype=torch.long,
).expand(batch_size, -1, -1)
return dict(src=points_src, dst=points_dst)
-
-
-@_deprecated(replace_with=CropGenerator3D.__name__)
-def random_crop_generator3d(
- batch_size: int,
- input_size: Tuple[int, int, int],
- size: Union[Tuple[int, int, int], Tensor],
- resize_to: Optional[Tuple[int, int, int]] = None,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, 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.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
-
- Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - src (Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (Tensor): output bounding boxes with a shape (B, 8, 3).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _device, _dtype = _extract_device_dtype([size if isinstance(size, Tensor) else None])
- if not isinstance(size, Tensor):
- size = tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
- else:
- size = size.to(device=device, dtype=dtype)
- if size.shape != torch.Size([batch_size, 3]):
- raise AssertionError(
- "If `size` is a tensor, it must be shaped as (B, 3). "
- f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}."
- )
- if not (
- len(input_size) == 3
- and isinstance(input_size[0], (int,))
- and isinstance(input_size[1], (int,))
- and isinstance(input_size[2], (int,))
- and input_size[0] > 0
- and input_size[1] > 0
- and input_size[2] > 0
- ):
- raise AssertionError(f"`input_size` must be a tuple of 3 positive integers. Got {input_size}.")
-
- 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(f"input_size {str(input_size)} cannot be smaller than crop size {str(size)} in any dimension.")
-
- if batch_size == 0:
- return dict(
- src=zeros([0, 8, 3], device=_device, dtype=_dtype), dst=zeros([0, 8, 3], device=_device, dtype=_dtype)
- )
-
- 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).floor()
- y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch).floor()
- z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch).floor()
- else:
- x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch).floor()
- y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch).floor()
- z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch).floor()
-
- crop_src = bbox_generator3d(
- x_start.to(device=_device, dtype=_dtype).view(-1),
- y_start.to(device=_device, dtype=_dtype).view(-1),
- z_start.to(device=_device, dtype=_dtype).view(-1),
- size[:, 2].to(device=_device, dtype=_dtype) - 1,
- size[:, 1].to(device=_device, dtype=_dtype) - 1,
- size[:, 0].to(device=_device, dtype=_dtype) - 1,
- )
-
- if resize_to is None:
- crop_dst = bbox_generator3d(
- tensor([0] * batch_size, device=_device, dtype=_dtype),
- tensor([0] * batch_size, device=_device, dtype=_dtype),
- tensor([0] * batch_size, device=_device, dtype=_dtype),
- size[:, 2].to(device=_device, dtype=_dtype) - 1,
- size[:, 1].to(device=_device, dtype=_dtype) - 1,
- size[:, 0].to(device=_device, dtype=_dtype) - 1,
- )
- else:
- if not (
- len(resize_to) == 3
- and isinstance(resize_to[0], (int,))
- and isinstance(resize_to[1], (int,))
- and isinstance(resize_to[2], (int,))
- and resize_to[0] > 0
- and resize_to[1] > 0
- and resize_to[2] > 0
- ):
- raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {resize_to}.")
- crop_dst = 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],
- ]
- ],
- device=_device,
- dtype=_dtype,
- ).repeat(batch_size, 1, 1)
-
- return dict(src=crop_src.to(device=_device), dst=crop_dst.to(device=_device))
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index fd3d601ed..472ee52b5 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -4,16 +4,9 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import (
- _adapted_rsampling,
- _adapted_uniform,
- _common_param_check,
- _joint_range_check,
- _range_bound,
- _tuple_range_reader,
-)
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound, _tuple_range_reader
from kornia.core import Tensor, stack
-from kornia.utils.helpers import _deprecated, _extract_device_dtype
+from kornia.utils.helpers import _extract_device_dtype
class MotionBlurGenerator3D(RandomGeneratorBase):
@@ -102,70 +95,3 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
angle_factor=angle_factor.to(device=_device, dtype=_dtype),
direction_factor=direction_factor.to(device=_device, dtype=_dtype),
)
-
-
-@_deprecated(replace_with=MotionBlurGenerator3D.__name__)
-def random_motion_blur_generator3d(
- batch_size: int,
- kernel_size: Union[int, Tuple[int, int]],
- angle: Tensor,
- direction: Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, Tensor]:
- r"""Get parameters for motion blur.
-
- Args:
- batch_size (int): the tensor batch size.
- kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.
- angle (Tensor): yaw, pitch and roll range of the motion blur in degrees :math:`(3, 2)`.
- direction (Tensor): forward/backward direction of the motion blur.
- Lower values towards -1.0 will point the motion blur towards the back (with
- angle provided via angle), while higher values towards 1.0 will point the motion
- blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur.
- same_on_batch (bool): apply the same transformation across the batch. Default: False.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
-
- Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (Tensor): element-wise center with a shape of (B,).
- - direction_factor (Tensor): element-wise scales with a shape of (B,).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- _device, _dtype = _extract_device_dtype([angle, direction])
- _joint_range_check(direction, 'direction', (-1, 1))
- if isinstance(kernel_size, int):
- if not (kernel_size >= 3 and kernel_size % 2 == 1):
- raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
- ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype).int()
- elif isinstance(kernel_size, tuple):
- if not (len(kernel_size) == 2 and kernel_size[0] >= 3 and kernel_size[0] <= kernel_size[1]):
- raise AssertionError(f"`kernel_size` must be greater than 3. Got range {kernel_size}.")
- # kernel_size is fixed across the batch
- ksize_factor = (
- _adapted_uniform((batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
- )
- else:
- raise TypeError(f"Unsupported type: {type(kernel_size)}")
-
- if angle.shape != torch.Size([3, 2]):
- raise AssertionError(f"'angle' must be the shape of (3, 2). Got {angle.shape}.")
- angle = angle.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), angle[0][0], angle[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), angle[1][0], angle[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), angle[2][0], angle[2][1], same_on_batch)
- angle_factor = stack([yaw, pitch, roll], 1)
-
- direction = direction.to(device=device, dtype=dtype)
- direction_factor = _adapted_uniform((batch_size,), direction[0], direction[1], same_on_batch)
-
- return dict(
- ksize_factor=ksize_factor.to(device=_device),
- angle_factor=angle_factor.to(device=_device, dtype=_dtype),
- direction_factor=direction_factor.to(device=_device, dtype=_dtype),
- )
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index 79d3b6247..1f8278e74 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -4,9 +4,9 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check
from kornia.core import Tensor, as_tensor, stack, tensor
-from kornia.utils.helpers import _deprecated, _extract_device_dtype
+from kornia.utils.helpers import _extract_device_dtype
class PerspectiveGenerator3D(RandomGeneratorBase):
@@ -87,80 +87,3 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
end_points = start_points + factor * rand_val * pts_norm
return dict(start_points=start_points, end_points=end_points)
-
-
-@_deprecated(replace_with=PerspectiveGenerator3D.__name__)
-def random_perspective_generator3d(
- batch_size: int,
- depth: int,
- height: int,
- width: int,
- distortion_scale: Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, 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 (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.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
-
- Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - src (Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
- - dst (Tensor): perspective target bounding boxes with a shape (B, 8, 3).
-
- Note:
- The generated random numbers are not reproducible across different devices and dtypes.
- """
- if not (distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1):
- raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}")
- _device, _dtype = _extract_device_dtype([distortion_scale])
- distortion_scale = distortion_scale.to(device=device, dtype=dtype)
-
- start_points: Tensor = tensor(
- [
- [
- [0.0, 0, 0],
- [width - 1, 0, 0],
- [width - 1, height - 1, 0],
- [0, height - 1, 0],
- [0.0, 0, depth - 1],
- [width - 1, 0, depth - 1],
- [width - 1, height - 1, depth - 1],
- [0, height - 1, depth - 1],
- ]
- ],
- device=device,
- dtype=dtype,
- ).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 = stack([fx, fy, fz], 0).view(-1, 1, 3)
-
- rand_val: Tensor = _adapted_uniform(
- start_points.shape, tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch
- )
-
- pts_norm = 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]]],
- device=device,
- dtype=dtype,
- )
- end_points = start_points + factor * rand_val * pts_norm
-
- return dict(
- start_points=start_points.to(device=_device, dtype=_dtype),
- end_points=end_points.to(device=_device, dtype=_dtype),
- )
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
index 249fb78b3..371db6a48 100644
--- a/kornia/augmentation/random_generator/_3d/rotation.py
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -4,9 +4,9 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _tuple_range_reader
+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _tuple_range_reader
from kornia.core import Tensor
-from kornia.utils.helpers import _deprecated, _extract_device_dtype
+from kornia.utils.helpers import _extract_device_dtype
class RotationGenerator3D(RandomGeneratorBase):
@@ -66,41 +66,3 @@ class RotationGenerator3D(RandomGeneratorBase):
pitch=_adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch).to(device=_device, dtype=_dtype),
roll=_adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch).to(device=_device, dtype=_dtype),
)
-
-
-@_deprecated(replace_with=RotationGenerator3D.__name__)
-def random_rotation_generator3d(
- batch_size: int,
- degrees: Tensor,
- same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
- dtype: torch.dtype = torch.float32,
-) -> Dict[str, Tensor]:
- r"""Get parameters for ``rotate`` for a random rotate transform.
-
- Args:
- batch_size (int): the tensor batch size.
- degrees (Tensor): Ranges of degrees (3, 2) for yaw, pitch and roll.
- same_on_batch (bool): apply the same transformation across the batch. Default: False.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
- dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
-
- Returns:
- params Dict[str, Tensor]: parameters to be passed for transformation.
- - yaw (Tensor): element-wise rotation yaws with a shape of (B,).
- - pitch (Tensor): element-wise rotation pitches with a shape of (B,).
- - roll (Tensor): element-wise rotation rolls with a shape of (B,).
- """
- if degrees.shape != torch.Size([3, 2]):
- raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
- _device, _dtype = _extract_device_dtype([degrees])
- degrees = degrees.to(device=device, dtype=dtype)
- yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
- roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
-
- return dict(
- yaw=yaw.to(device=_device, dtype=_dtype),
- pitch=pitch.to(device=_device, dtype=_dtype),
- roll=roll.to(device=_device, dtype=_dtype),
- )
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 66a95a980..f89b93d8d 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -1,7 +1,9 @@
-from typing import List, Optional, Tuple, Union, cast
+from typing import List, Optional, Tuple, Union
import torch
+from kornia.core import Tensor, as_tensor, tensor
+
def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
"""Valid batch_size and same_on_batch params."""
@@ -12,18 +14,18 @@ def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
def _range_bound(
- factor: Union[torch.Tensor, float, Tuple[float, float], List[float]],
+ factor: Union[Tensor, float, Tuple[float, float], List[float]],
name: str,
center: float = 0.0,
bounds: Tuple[float, float] = (0, float('inf')),
check: Optional[str] = 'joint',
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.get_default_dtype(),
-) -> torch.Tensor:
+) -> Tensor:
r"""Check inputs and compute the corresponding factor bounds."""
- if not isinstance(factor, (torch.Tensor)):
- factor = torch.tensor(factor, device=device, dtype=dtype)
- factor_bound: torch.Tensor
+ if not isinstance(factor, (Tensor)):
+ factor = tensor(factor, device=device, dtype=dtype)
+ factor_bound: Tensor
if factor.dim() == 0:
if factor < 0:
@@ -31,10 +33,10 @@ def _range_bound(
# Should be something other than clamp
# Currently, single value factor will not out of scope as long as the user provided it.
# Note: I personally think throw an error will be better than a coarse clamp.
- factor_bound = factor.repeat(2) * torch.tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center
+ factor_bound = factor.repeat(2) * tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center
factor_bound = factor_bound.clamp(bounds[0], bounds[1]).to(device=device, dtype=dtype)
else:
- factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)
+ factor_bound = as_tensor(factor, device=device, dtype=dtype)
if check is not None:
if check == 'joint':
@@ -47,7 +49,7 @@ def _range_bound(
return factor_bound
-def _joint_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None:
+def _joint_range_check(ranged_factor: Tensor, name: str, bounds: Optional[Tuple[float, float]] = None) -> None:
"""Check if bounds[0] <= ranged_factor[0] <= ranged_factor[1] <= bounds[1]"""
if bounds is None:
bounds = (float('-inf'), float('inf'))
@@ -64,7 +66,7 @@ def _joint_range_check(ranged_factor: torch.Tensor, name: str, bounds: Optional[
def _singular_range_check(
- ranged_factor: torch.Tensor,
+ ranged_factor: Tensor,
name: str,
bounds: Optional[Tuple[float, float]] = None,
skip_none: bool = False,
@@ -94,28 +96,51 @@ def _singular_range_check(
def _tuple_range_reader(
- input_range: Union[torch.Tensor, float, tuple],
+ input_range: Union[Tensor, float, tuple],
target_size: int,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
-) -> torch.Tensor:
+) -> Tensor:
"""Given target_size, it will generate the corresponding (target_size, 2) range tensor for element-wise params.
Example:
- >>> degree = torch.tensor([0.2, 0.3])
+ >>> degree = tensor([0.2, 0.3])
>>> _tuple_range_reader(degree, 3) # read degree for yaw, pitch and roll.
tensor([[0.2000, 0.3000],
[0.2000, 0.3000],
[0.2000, 0.3000]])
"""
target_shape = torch.Size([target_size, 2])
- if not torch.is_tensor(input_range):
- if isinstance(input_range, (float, int)):
+
+ if isinstance(input_range, Tensor):
+ # TODO: Investigate if we should keeping ignoring the `device` argument when `input_range` is a Tensor
+ if (len(input_range.shape) == 0) or (len(input_range.shape) == 1 and len(input_range) == 1):
if input_range < 0:
raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")
- input_range_tmp = torch.tensor([-input_range, input_range], device=device, dtype=dtype).repeat(
- target_shape[0], 1
+ input_range_tmp = input_range.repeat(2) * tensor([-1, 1], device=input_range.device, dtype=dtype)
+ input_range_tmp = input_range_tmp.repeat(target_shape[0], 1)
+
+ elif len(input_range.shape) == 1 and len(input_range) == 2:
+ input_range_tmp = input_range.repeat(target_shape[0], 1)
+
+ elif len(input_range.shape) == 1 and len(input_range) == target_shape[0]:
+ input_range_tmp = input_range.unsqueeze(1).repeat(1, 2) * tensor(
+ [-1, 1], device=input_range.device, dtype=dtype
+ )
+
+ elif input_range.shape == target_shape:
+ input_range_tmp = input_range.to(device=input_range.device, dtype=dtype)
+
+ else:
+ raise ValueError(
+ f"Degrees must be a {list(target_shape)} tensor for the degree range for independent operation."
+ f"Got {input_range}"
)
+ else:
+ if isinstance(input_range, (float, int)):
+ if input_range < 0:
+ raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")
+ input_range_tmp = tensor([-input_range, input_range], device=device, dtype=dtype).repeat(target_shape[0], 1)
elif (
isinstance(input_range, (tuple, list))
@@ -123,21 +148,21 @@ def _tuple_range_reader(
and isinstance(input_range[0], (float, int))
and isinstance(input_range[1], (float, int))
):
- input_range_tmp = torch.tensor(input_range, device=device, dtype=dtype).repeat(target_shape[0], 1)
+ input_range_tmp = tensor(input_range, device=device, dtype=dtype).repeat(target_shape[0], 1)
elif (
isinstance(input_range, (tuple, list))
and len(input_range) == target_shape[0]
and all(isinstance(x, (float, int)) for x in input_range)
):
- input_range_tmp = torch.tensor([(-s, s) for s in input_range], device=device, dtype=dtype)
+ input_range_tmp = tensor([(-s, s) for s in input_range], device=device, dtype=dtype)
elif (
isinstance(input_range, (tuple, list))
and len(input_range) == target_shape[0]
and all(isinstance(x, (tuple, list)) for x in input_range)
):
- input_range_tmp = torch.tensor(input_range, device=device, dtype=dtype)
+ input_range_tmp = tensor(input_range, device=device, dtype=dtype)
else:
raise TypeError(
@@ -145,32 +170,4 @@ def _tuple_range_reader(
f"{target_size} floats or {target_size} (float, float) for independent operation. Got {input_range}."
)
- else:
- # https://mypy.readthedocs.io/en/latest/casts.html cast to please mypy gods
- input_range = cast(torch.Tensor, input_range)
- if (len(input_range.shape) == 0) or (len(input_range.shape) == 1 and len(input_range) == 1):
- if input_range < 0:
- raise ValueError(f"If input_range is only one number it must be a positive number. Got{input_range}")
- input_range_tmp = input_range.repeat(2) * torch.tensor(
- [-1.0, 1.0], device=input_range.device, dtype=input_range.dtype
- )
- input_range_tmp = input_range_tmp.repeat(target_shape[0], 1)
-
- elif len(input_range.shape) == 1 and len(input_range) == 2:
- input_range_tmp = input_range.repeat(target_shape[0], 1)
-
- elif len(input_range.shape) == 1 and len(input_range) == target_shape[0]:
- input_range_tmp = input_range.unsqueeze(1).repeat(1, 2) * torch.tensor(
- [-1, 1], device=input_range.device, dtype=input_range.dtype
- )
-
- elif input_range.shape == target_shape:
- input_range_tmp = input_range
-
- else:
- raise ValueError(
- f"Degrees must be a {list(target_shape)} tensor for the degree range for independent operation."
- f"Got {input_range}"
- )
-
return input_range_tmp
diff --git a/test/augmentation/test_random_generator_3d.py b/test/augmentation/test_random_generator_3d.py
index 16f41dad4..9d9de4559 100644
--- a/test/augmentation/test_random_generator_3d.py
+++ b/test/augmentation/test_random_generator_3d.py
@@ -2,12 +2,12 @@ import pytest
import torch
from kornia.augmentation.random_generator import (
+ AffineGenerator3D,
+ CropGenerator3D,
+ MotionBlurGenerator3D,
+ PerspectiveGenerator3D,
+ RotationGenerator3D,
center_crop_generator3d,
- random_affine_generator3d,
- random_crop_generator3d,
- random_motion_blur_generator3d,
- random_perspective_generator3d,
- random_rotation_generator3d,
)
from kornia.testing import assert_close
@@ -34,21 +34,13 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
def test_valid_param_combinations(
self, depth, height, width, distortion_scale, batch_size, same_on_batch, device, dtype
):
- random_perspective_generator3d(
- batch_size=batch_size,
- depth=depth,
- height=height,
- width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch,
- )
+ param_gen = PerspectiveGenerator3D(distortion_scale=distortion_scale.to(device=device, dtype=dtype))
+ param_gen(batch_shape=torch.Size((batch_size, depth, height, width)), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
'depth,height,width,distortion_scale',
[
# Should be failed if distortion_scale > 1. or distortion_scale < 0.
- (-100, 100, 100, torch.tensor(0.5)),
- (100, -100, 100, torch.tensor(0.5)),
(100, 100, -100, torch.tensor(-0.5)),
(100, 100, 100, torch.tensor(1.5)),
(100, 100, 100, torch.tensor([0.0, 0.5])),
@@ -56,17 +48,16 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, depth, height, width, distortion_scale, device, dtype):
with pytest.raises(Exception):
- random_perspective_generator3d(
- batch_size=8,
- height=height,
- width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype),
- )
+ param_gen = PerspectiveGenerator3D(distortion_scale=distortion_scale.to(device=device, dtype=dtype))
+ param_gen(batch_shape=torch.Size((2, depth, height, width)))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- res = random_perspective_generator3d(batch_size, 200, 200, 200, torch.tensor(0.5, device=device, dtype=dtype))
+
+ param_gen = PerspectiveGenerator3D(distortion_scale=torch.tensor(0.5, device=device, dtype=dtype))
+ res = param_gen(batch_shape=torch.Size((batch_size, 200, 200, 200)))
+
expected = dict(
start_points=torch.tensor(
[
@@ -128,9 +119,10 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
batch_size = 2
- res = random_perspective_generator3d(
- batch_size, 200, 200, 200, torch.tensor(0.5, device=device, dtype=dtype), same_on_batch=True
- )
+
+ param_gen = PerspectiveGenerator3D(distortion_scale=torch.tensor(0.5, device=device, dtype=dtype))
+ res = param_gen(batch_shape=torch.Size((batch_size, 200, 200, 200)), same_on_batch=True)
+
expected = dict(
start_points=torch.tensor(
[
@@ -191,27 +183,30 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
class TestRandomAffineGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('depth,height,width', [(200, 300, 400)])
- @pytest.mark.parametrize('degrees', [torch.tensor([(0, 30), (0, 30), (0, 30)])])
+ @pytest.mark.parametrize('batch_shape', [(0, 200, 300, 400), (1, 200, 300, 400), (8, 200, 300, 400)])
+ @pytest.mark.parametrize('degrees', [torch.tensor([(0.0, 30.0), (0.0, 30.0), (0.0, 30.0)])])
@pytest.mark.parametrize('translate', [None, torch.tensor([0.1, 0.1, 0.1])])
- @pytest.mark.parametrize('scale', [None, torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]])])
- @pytest.mark.parametrize('shear', [None, torch.tensor([[0, 20], [0, 20], [0, 20], [0, 20], [0, 20], [0, 20]])])
+ @pytest.mark.parametrize(
+ 'scale', [None, torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]]), torch.tensor([0.7, 1.2])]
+ )
+ @pytest.mark.parametrize(
+ 'shear', [None, torch.tensor([[0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0], [0.0, 20.0]])]
+ )
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
- self, batch_size, depth, height, width, degrees, translate, scale, shear, same_on_batch, device, dtype
+ self, batch_shape, degrees, translate, scale, shear, same_on_batch, device, dtype
):
- random_affine_generator3d(
- batch_size=batch_size,
- depth=depth,
- height=height,
- width=width,
- degrees=degrees.to(device=device, dtype=dtype),
- translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
- scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shears=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=same_on_batch,
- )
+ if isinstance(degrees, torch.Tensor):
+ degrees.to(dtype=dtype, device=device)
+ if isinstance(translate, torch.Tensor):
+ translate.to(dtype=dtype, device=device)
+ if isinstance(scale, torch.Tensor):
+ scale.to(dtype=dtype, device=device)
+ if isinstance(shear, torch.Tensor):
+ shear.to(dtype=dtype, device=device)
+
+ param_gen = AffineGenerator3D(degrees=degrees, translate=translate, scale=scale, shears=shear)
+ param_gen(batch_shape=torch.Size(batch_shape), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
'depth,height,width,degrees,translate,scale,shear',
@@ -226,38 +221,33 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([[0.2, 0.2, 0.2]]), None),
(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, torch.tensor([0.2]), None),
(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, torch.tensor([[20, 20, 30]])),
- (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, torch.tensor([20])),
+ # (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, torch.tensor([20])),
],
)
def test_invalid_param_combinations(self, depth, height, width, degrees, translate, scale, shear, device, dtype):
+ if isinstance(degrees, torch.Tensor):
+ degrees.to(dtype=dtype, device=device)
+ if isinstance(translate, torch.Tensor):
+ translate.to(dtype=dtype, device=device)
+ if isinstance(scale, torch.Tensor):
+ scale.to(dtype=dtype, device=device)
+ if isinstance(shear, torch.Tensor):
+ shear.to(dtype=dtype, device=device)
+
with pytest.raises(Exception):
- random_affine_generator3d(
- batch_size=8,
- depth=depth,
- height=height,
- width=width,
- degrees=degrees.to(device=device, dtype=dtype),
- translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
- scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shears=shear.to(device=device, dtype=dtype) if shear is not None else None,
- )
+ param_gen = AffineGenerator3D(degrees=degrees, translate=translate, scale=scale, shears=shear)
+ param_gen(batch_shape=torch.Size((2, depth, height, width)))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- degrees = torch.tensor([[10, 20], [10, 20], [10, 20]])
- translate = torch.tensor([0.1, 0.1, 0.1])
- scale = torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]])
- shear = torch.tensor([[0, 20], [0, 20], [0, 20], [0, 20], [0, 20], [0, 20]])
- res = random_affine_generator3d(
- batch_size=2,
- depth=200,
- height=200,
- width=200,
- degrees=degrees.to(device=device, dtype=dtype),
- translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
- scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shears=shear.to(device=device, dtype=dtype) if shear is not None else None,
- )
+ degrees = torch.tensor([[10, 20], [10, 20], [10, 20]], device=device, dtype=dtype)
+ translate = torch.tensor([0.1, 0.1, 0.1], device=device, dtype=dtype)
+ scale = torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]], device=device, dtype=dtype)
+ shear = torch.tensor([[0, 20], [0, 20], [0, 20], [0, 20], [0, 20], [0, 20]], device=device, dtype=dtype)
+
+ param_gen = AffineGenerator3D(degrees=degrees, translate=translate, scale=scale, shears=shear)
+ res = param_gen(batch_shape=torch.Size((2, 200, 200, 200)))
+
expected = dict(
translations=torch.tensor(
[[14.7762, 9.6438, 15.4177], [2.7086, -2.8238, 2.9562]], device=device, dtype=dtype
@@ -286,21 +276,14 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- degrees = torch.tensor([[10, 20], [10, 20], [10, 20]])
- translate = torch.tensor([0.1, 0.1, 0.1])
- scale = torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]])
- shear = torch.tensor([[0, 20], [0, 20], [0, 20], [0, 20], [0, 20], [0, 20]])
- res = random_affine_generator3d(
- batch_size=2,
- depth=200,
- height=200,
- width=200,
- degrees=degrees.to(device=device, dtype=dtype),
- translate=translate.to(device=device, dtype=dtype) if translate is not None else None,
- scale=scale.to(device=device, dtype=dtype) if scale is not None else None,
- shears=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=True,
- )
+ degrees = torch.tensor([[10, 20], [10, 20], [10, 20]], device=device, dtype=dtype)
+ translate = torch.tensor([0.1, 0.1, 0.1], device=device, dtype=dtype)
+ scale = torch.tensor([[0.7, 1.2], [0.7, 1.2], [0.7, 1.2]], device=device, dtype=dtype)
+ shear = torch.tensor([[0, 20], [0, 20], [0, 20], [0, 20], [0, 20], [0, 20]], device=device, dtype=dtype)
+
+ param_gen = AffineGenerator3D(degrees=degrees, translate=translate, scale=scale, shears=shear)
+ res = param_gen(batch_shape=torch.Size((2, 200, 200, 200)), same_on_batch=True)
+
expected = dict(
translations=torch.tensor(
[[-9.7371, 11.7457, 17.6309], [-9.7371, 11.7457, 17.6309]], device=device, dtype=dtype
@@ -330,27 +313,27 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
class TestRandomRotationGen3D(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 1, 8])
- @pytest.mark.parametrize('degrees', [torch.tensor([[0, 30], [0, 30], [0, 30]])])
@pytest.mark.parametrize('same_on_batch', [True, False])
- def test_valid_param_combinations(self, batch_size, degrees, same_on_batch, device, dtype):
- random_rotation_generator3d(
- batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch
- )
+ def test_valid_param_combinations(self, batch_size, same_on_batch, device, dtype):
+ degrees = torch.tensor([[0.0, 30.0], [0.0, 30.0], [0.0, 30.0]], device=device, dtype=dtype)
+ param_gen = RotationGenerator3D(degrees=degrees.to(device=device, dtype=dtype))
+ param_gen(torch.Size((batch_size,)), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
'degrees',
- [(torch.tensor(10)), (torch.tensor([10])), (torch.tensor([[0, 30]])), (torch.tensor([[0, 30], [0, 30]]))],
+ [(torch.tensor(-10)), (torch.tensor([-10])), (torch.tensor([[0, 30]])), (torch.tensor([[0, 30], [0, 30]]))],
)
def test_invalid_param_combinations(self, degrees, device, dtype):
with pytest.raises(Exception):
- random_rotation_generator3d(batch_size=8, degrees=degrees.to(device=device, dtype=dtype))
+ param_gen = RotationGenerator3D(degrees=degrees.to(device=device, dtype=dtype))
+ param_gen(torch.Size((2,)))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- degrees = torch.tensor([[0, 30], [0, 30], [0, 30]])
- res = random_rotation_generator3d(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False
- )
+ degrees = torch.tensor([[0.0, 30.0], [0.0, 30.0], [0.0, 30.0]], device=device, dtype=dtype)
+ param_gen = RotationGenerator3D(degrees=degrees)
+ res = param_gen(torch.Size((2,)), same_on_batch=False)
+
expected = dict(
yaw=torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),
pitch=torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),
@@ -363,10 +346,10 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- degrees = torch.tensor([[0, 30], [0, 30], [0, 30]])
- res = random_rotation_generator3d(
- batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True
- )
+ degrees = torch.tensor([[0.0, 30.0], [0.0, 30.0], [0.0, 30.0]], device=device, dtype=dtype)
+ param_gen = RotationGenerator3D(degrees=degrees)
+ res = param_gen(torch.Size((2,)), same_on_batch=True)
+
expected = dict(
yaw=torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),
pitch=torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),
@@ -387,13 +370,9 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
def test_valid_param_combinations(self, batch_size, input_size, size, resize_to, same_on_batch, device, dtype):
if isinstance(size, torch.Tensor):
size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)
- random_crop_generator3d(
- batch_size=batch_size,
- input_size=input_size,
- size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
- resize_to=resize_to,
- same_on_batch=same_on_batch,
- )
+
+ param_gen = CropGenerator3D(size=size, resize_to=resize_to)
+ param_gen(batch_shape=torch.Size((batch_size, 1, *input_size)), same_on_batch=same_on_batch)
@pytest.mark.parametrize(
'input_size,size,resize_to',
@@ -406,21 +385,19 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
with pytest.raises(Exception):
- random_crop_generator3d(
- batch_size=2,
- input_size=input_size,
+ param_gen = CropGenerator3D(
size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
resize_to=resize_to,
)
+ param_gen(batch_shape=torch.Size((2, 1, *input_size)))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- res = random_crop_generator3d(
- batch_size=2,
- input_size=(200, 200, 200),
- size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype),
- resize_to=(100, 100, 100),
+ param_gen = CropGenerator3D(
+ size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype), resize_to=(100, 100, 100)
)
+ res = param_gen(batch_shape=torch.Size((2, 1, 200, 200, 200)))
+
expected = dict(
src=torch.tensor(
[
@@ -481,13 +458,12 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- res = random_crop_generator3d(
- batch_size=2,
- input_size=(200, 200, 200),
- size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype),
- resize_to=(100, 100, 100),
- same_on_batch=True,
+
+ param_gen = CropGenerator3D(
+ size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype), resize_to=(100, 100, 100)
)
+ res = param_gen(batch_shape=torch.Size((2, 1, 200, 200, 200)), same_on_batch=True)
+
expected = dict(
src=torch.tensor(
[
@@ -616,18 +592,20 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):
class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
@pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('kernel_size', [3, (3, 5)])
- @pytest.mark.parametrize('angle', [torch.tensor([(10, 30), (30, 60), (60, 90)])])
- @pytest.mark.parametrize('direction', [torch.tensor([-1, -1]), torch.tensor([-1, 1]), torch.tensor([1, 1])])
+ @pytest.mark.parametrize('angle', [torch.tensor([(10.0, 30.0), (30.0, 60.0), (60.0, 90.0)])])
+ @pytest.mark.parametrize(
+ 'direction', [torch.tensor([-1.0, -1.0]), torch.tensor([-1.0, 1.0]), torch.tensor([1.0, 1.0])]
+ )
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, kernel_size, angle, direction, same_on_batch, device, dtype):
- random_motion_blur_generator3d(
- batch_size=batch_size,
+ param_gen = MotionBlurGenerator3D(
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch,
)
+ param_gen(batch_shape=torch.Size((batch_size,)), same_on_batch=same_on_batch)
+
@pytest.mark.parametrize(
'kernel_size,angle,direction',
[
@@ -640,24 +618,22 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
)
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
with pytest.raises(Exception):
- random_motion_blur_generator3d(
- batch_size=8,
+ param_gen = MotionBlurGenerator3D(
kernel_size=kernel_size,
angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype),
)
+ param_gen(batch_shape=torch.Size((2,)))
+
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- angle = torch.tensor([(10, 30), (30, 60), (60, 90)])
- direction = torch.tensor([-1, 1])
- res = random_motion_blur_generator3d(
- batch_size=2,
- kernel_size=3,
- angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype),
- same_on_batch=False,
- )
+ angle = torch.tensor([(10, 30), (30, 60), (60, 90)], device=device, dtype=dtype)
+ direction = torch.tensor([-1, 1], device=device, dtype=dtype)
+ param_gen = MotionBlurGenerator3D(kernel_size=3, angle=angle, direction=direction)
+
+ res = param_gen(batch_shape=torch.Size((2,)), same_on_batch=False)
+
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor(
@@ -672,15 +648,12 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- angle = torch.tensor([(10, 30), (30, 60), (60, 90)])
- direction = torch.tensor([-1, 1])
- res = random_motion_blur_generator3d(
- batch_size=2,
- kernel_size=3,
- angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype),
- same_on_batch=True,
- )
+ angle = torch.tensor([(10, 30), (30, 60), (60, 90)], device=device, dtype=dtype)
+ direction = torch.tensor([-1, 1], device=device, dtype=dtype)
+ param_gen = MotionBlurGenerator3D(kernel_size=3, angle=angle, direction=direction)
+
+ res = param_gen(batch_shape=torch.Size((2,)), same_on_batch=True)
+
expected = dict(
ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor(