Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Exposed rng generation device and dtype for augmentations. (#770)

shijianjianbd71ec1ef70a
diff --git a/Makefile b/Makefile
index f23f61651..e76033447 100644
--- a/Makefile
+++ b/Makefile
@@ -39,7 +39,7 @@ autopep8: FORCE
autopep8 --in-place --aggressive --recursive kornia/ test/ examples/
doctest:
- pytest -v --doctest-modules kornia/color #kornia/augmentation ... etc
+ pytest -v --doctest-modules kornia/color kornia/augmentation #... etc
docstyle: FORCE
pydocstyle kornia/
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index d6f250c25..03ca094cc 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -194,7 +194,8 @@ class ColorJitter(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_color_jitter_generator(
- batch_shape[0], self.brightness, self.contrast, self.saturation, self.hue, self.same_on_batch)
+ batch_shape[0], self.brightness, self.contrast, self.saturation, self.hue, self.same_on_batch,
+ self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_intensity_transformation(input)
@@ -317,7 +318,7 @@ class RandomErasing(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_rectangles_params_generator(
batch_shape[0], batch_shape[-2], batch_shape[-1], scale=self.scale, ratio=self.ratio,
- value=self.value, same_on_batch=self.same_on_batch)
+ value=self.value, same_on_batch=self.same_on_batch, device=self.device, dtype=self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_intensity_transformation(input)
@@ -391,7 +392,8 @@ class RandomPerspective(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_perspective_generator(
- batch_shape[0], batch_shape[-2], batch_shape[-1], self.distortion_scale, self.same_on_batch)
+ batch_shape[0], batch_shape[-2], batch_shape[-1], self.distortion_scale, self.same_on_batch,
+ self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_perspective_transformation(input, params)
@@ -508,7 +510,7 @@ class RandomAffine(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_affine_generator(
batch_shape[0], batch_shape[-2], batch_shape[-1], self.degrees, self.translate, self.scale, self.shear,
- self.same_on_batch)
+ self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_affine_transformation(input, params)
@@ -541,11 +543,16 @@ class CenterCrop(AugmentationBase2D):
Examples:
>>> rng = torch.manual_seed(0)
- >>> inputs = torch.randn(1, 1, 3, 3)
+ >>> inputs = torch.randn(1, 1, 4, 4)
+ >>> inputs
+ tensor([[[[-1.1258, -1.1524, -0.2506, -0.4339],
+ [ 0.8487, 0.6920, -0.3160, -2.1152],
+ [ 0.3223, -1.2633, 0.3500, 0.3081],
+ [ 0.1198, 1.2377, 1.1168, -0.2473]]]])
>>> aug = CenterCrop(2, p=1.)
>>> aug(inputs)
- tensor([[[[ 0.1829, -1.2388],
- [ 0.1813, -0.5911]]]])
+ tensor([[[[ 0.6920, -0.3160],
+ [-1.2633, 0.3500]]]])
"""
def __init__(self, size: Union[int, Tuple[int, int]], align_corners: bool = True,
@@ -576,7 +583,7 @@ class CenterCrop(AugmentationBase2D):
raise Exception(f"Invalid size type. Expected (int, tuple(int, int). "
f"Got: {type(self.size)}.")
return rg.center_crop_generator(
- batch_shape[0], batch_shape[-2], batch_shape[-1], size_param)
+ batch_shape[0], batch_shape[-2], batch_shape[-1], size_param, self.device)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_crop_transformation(input, params, self.flags)
@@ -655,7 +662,7 @@ class RandomRotation(AugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_rotation_generator(batch_shape[0], self.degrees, self.same_on_batch)
+ return rg.random_rotation_generator(batch_shape[0], self.degrees, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_rotate_tranformation(input, params)
@@ -726,7 +733,6 @@ class RandomCrop(AugmentationBase2D):
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),
@@ -740,7 +746,7 @@ class RandomCrop(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), self.size,
- same_on_batch=self.same_on_batch)
+ same_on_batch=self.same_on_batch, device=self.device, dtype=self.dtype)
def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
if self.padding is not None:
@@ -852,9 +858,10 @@ class RandomResizedCrop(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
target_size: torch.Tensor = rg.random_crop_size_generator(
- batch_shape[0], self.size, self.scale, self.ratio, same_on_batch=self.same_on_batch)['size']
+ batch_shape[0], self.size, self.scale, self.ratio, self.same_on_batch, self.device, self.dtype)['size']
return rg.random_crop_generator(batch_shape[0], (batch_shape[-2], batch_shape[-1]), target_size,
- resize_to=self.size, same_on_batch=self.same_on_batch)
+ resize_to=self.size, same_on_batch=self.same_on_batch,
+ device=self.device, dtype=self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_crop_transformation(input, params, self.flags)
@@ -895,14 +902,14 @@ class RandomMotionBlur(AugmentationBase2D):
Examples:
>>> rng = torch.manual_seed(0)
- >>> input = torch.rand(1, 1, 5, 5)
+ >>> input = torch.ones(1, 1, 5, 5)
>>> motion_blur = RandomMotionBlur(3, 35., 0.5, p=1.)
>>> motion_blur(input)
- tensor([[[[0.2972, 0.5154, 0.4153, 0.1641, 0.1765],
- [0.3045, 0.6160, 0.6123, 0.6701, 0.4225],
- [0.1914, 0.3224, 0.2456, 0.1485, 0.1799],
- [0.2974, 0.6258, 0.6399, 0.4802, 0.1939],
- [0.3919, 0.6911, 0.6984, 0.5462, 0.5357]]]])
+ tensor([[[[-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],
+ [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],
+ [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],
+ [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094],
+ [-0.5761, 1.0000, 1.0000, 1.0000, 1.9094]]]])
"""
def __init__(
@@ -934,7 +941,7 @@ class RandomMotionBlur(AugmentationBase2D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_motion_blur_generator(
- batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch)
+ batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_intensity_transformation(input)
@@ -1001,7 +1008,8 @@ class RandomSolarize(AugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_solarize_generator(batch_shape[0], self.thresholds, self.additions, self.same_on_batch)
+ return rg.random_solarize_generator(batch_shape[0], self.thresholds, self.additions, self.same_on_batch,
+ self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_intensity_transformation(input)
@@ -1065,7 +1073,7 @@ class RandomPosterize(AugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_posterize_generator(batch_shape[0], self.bits, self.same_on_batch)
+ return rg.random_posterize_generator(batch_shape[0], self.bits, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_intensity_transformation(input)
@@ -1101,9 +1109,9 @@ class RandomSharpness(AugmentationBase2D):
>>> sharpness = RandomSharpness(1., p=1.)
>>> sharpness(input)
tensor([[[[0.4963, 0.7682, 0.0885, 0.1320, 0.3074],
- [0.6341, 0.7059, 0.9403, 0.6860, 0.6323],
- [0.3489, 0.6549, 0.4361, 0.5206, 0.2939],
- [0.5185, 0.8256, 0.8847, 0.5161, 0.2823],
+ [0.6341, 0.4810, 0.7367, 0.4177, 0.6323],
+ [0.3489, 0.4428, 0.1562, 0.2443, 0.2939],
+ [0.5185, 0.6462, 0.7050, 0.2288, 0.2823],
[0.6816, 0.9152, 0.3971, 0.8742, 0.4194]]]])
"""
@@ -1126,7 +1134,8 @@ class RandomSharpness(AugmentationBase2D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_sharpness_generator(batch_shape[0], self.sharpness, self.same_on_batch)
+ return rg.random_sharpness_generator(batch_shape[0], self.sharpness, self.same_on_batch,
+ self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_intensity_transformation(input)
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 0673b14a0..802ffeeb1 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -326,7 +326,7 @@ class RandomAffine3D(AugmentationBase3D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_affine_generator3d(
batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.degrees,
- self.translate, self.scale, self.shear, self.same_on_batch)
+ self.translate, self.scale, self.shear, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_affine_transformation3d(input, params)
@@ -421,7 +421,7 @@ class RandomRotation3D(AugmentationBase3D):
return self.__class__.__name__ + f"({repr}, {super().__repr__()})"
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
- return rg.random_rotation_generator3d(batch_shape[0], self.degrees, self.same_on_batch)
+ return rg.random_rotation_generator3d(batch_shape[0], self.degrees, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_rotate_tranformation3d(input, params)
@@ -519,7 +519,7 @@ class RandomMotionBlur3D(AugmentationBase3D):
def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
return rg.random_motion_blur_generator3d(
- batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch)
+ batch_shape[0], self.kernel_size, self.angle, self.direction, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_intensity_transformation3d(input)
@@ -555,14 +555,24 @@ class CenterCrop3D(AugmentationBase3D):
Examples:
>>> rng = torch.manual_seed(0)
- >>> inputs = torch.randn(1, 1, 3, 3, 3)
+ >>> inputs = torch.randn(1, 1, 2, 4, 6)
+ >>> inputs
+ tensor([[[[[-1.1258, -1.1524, -0.2506, -0.4339, 0.8487, 0.6920],
+ [-0.3160, -2.1152, 0.3223, -1.2633, 0.3500, 0.3081],
+ [ 0.1198, 1.2377, 1.1168, -0.2473, -1.3527, -1.6959],
+ [ 0.5667, 0.7935, 0.5988, -1.5551, -0.3414, 1.8530]],
+ <BLANKLINE>
+ [[ 0.7502, -0.5855, -0.1734, 0.1835, 1.3894, 1.5863],
+ [ 0.9463, -0.8437, -0.6136, 0.0316, -0.4927, 0.2484],
+ [ 0.4397, 0.1124, 0.6408, 0.4412, -0.1023, 0.7924],
+ [-0.2897, 0.0525, 0.5229, 2.3022, -1.4689, -1.5867]]]]])
>>> aug = CenterCrop3D(2, p=1.)
>>> aug(inputs)
- tensor([[[[[-0.2170, 0.1856],
- [-0.2126, -0.0129]],
+ tensor([[[[[ 0.3223, -1.2633],
+ [ 1.1168, -0.2473]],
<BLANKLINE>
- [[-0.1957, -0.1423],
- [-0.0310, -0.3132]]]]])
+ [[-0.6136, 0.0316],
+ [ 0.6408, 0.4412]]]]])
"""
def __init__(self, size: Union[int, Tuple[int, int, int]], align_corners: bool = True,
@@ -669,7 +679,6 @@ class RandomCrop3D(AugmentationBase3D):
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),
@@ -683,7 +692,8 @@ class RandomCrop3D(AugmentationBase3D):
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)
+ self.size, same_on_batch=self.same_on_batch, device=self.device,
+ dtype=self.dtype)
def precrop_padding(self, input: torch.Tensor) -> torch.Tensor:
if self.padding is not None:
@@ -811,7 +821,7 @@ class RandomPerspective3D(AugmentationBase3D):
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)
+ self.distortion_scale, self.same_on_batch, self.device, self.dtype)
def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
return F.compute_perspective_transformation3d(input, params)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 787238b73..4ae462ee9 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -20,6 +20,8 @@ class _BasicAugmentationBase(nn.Module):
r"""_BasicAugmentationBase base class for customized augmentation implementations.
Plain augmentation base class without the functionality of transformation matrix calculations.
+ By default, the random computations will be happened on CPU with ``torch.get_default_dtype()``.
+ To change this behaviour, please use ``set_rng_device_and_dtype``.
Args:
p (float): probability for applying an augmentation. This param controls the augmentation
@@ -43,6 +45,7 @@ class _BasicAugmentationBase(nn.Module):
self._p_gen = Bernoulli(self.p)
if p_batch != 0. or p_batch != 1.:
self._p_batch_gen = Bernoulli(self.p_batch)
+ self.set_rng_device_and_dtype(torch.device('cpu'), torch.get_default_dtype())
def __repr__(self) -> str:
return f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"
@@ -67,6 +70,15 @@ class _BasicAugmentationBase(nn.Module):
def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
raise NotImplementedError
+ def set_rng_device_and_dtype(self, device: torch.device, dtype: torch.dtype) -> None:
+ """Change the random generation device and dtype.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
+ """
+ self.device = device
+ self.dtype = dtype
+
def __selective_param_gen__(
self, batch_shape: torch.Size, to_apply: torch.Tensor) -> Dict[str, torch.Tensor]:
_params = self.generate_parameters(
diff --git a/kornia/augmentation/random_generator/random_generator.py b/kornia/augmentation/random_generator/random_generator.py
index a630fd762..2abe88140 100644
--- a/kornia/augmentation/random_generator/random_generator.py
+++ b/kornia/augmentation/random_generator/random_generator.py
@@ -17,24 +17,32 @@ from kornia.utils import _extract_device_dtype
def random_prob_generator(
- batch_size: int, p: float = 0.5, same_on_batch: bool = False) -> torch.Tensor:
+ batch_size: int, p: float = 0.5, same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'), dtype: torch.dtype = torch.float32) -> torch.Tensor:
r"""Generate random probabilities for a batch of inputs.
Args:
batch_size (int): the number of images.
p (float): probability to generate an 1-d binary mask. Default value is 0.5.
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:
torch.Tensor: parameters to be passed for transformation.
+ - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
if not isinstance(p, (int, float)) or p > 1 or p < 0:
raise TypeError(f"The probability should be a float number within [0, 1]. Got {type(p)}.")
- probs: torch.Tensor = _adapted_sampling((batch_size,), Bernoulli(p), same_on_batch).bool()
+ _bernoulli = Bernoulli(torch.tensor(float(p), device=device, dtype=dtype))
+ probs_mask: torch.Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
- return probs
+ return probs_mask
def random_color_jitter_generator(
@@ -43,7 +51,9 @@ def random_color_jitter_generator(
contrast: Optional[torch.Tensor] = None,
saturation: Optional[torch.Tensor] = None,
hue: Optional[torch.Tensor] = None,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Generate random color jiter parameters for a batch of images.
@@ -58,20 +68,28 @@ def random_color_jitter_generator(
hue (torch.Tensor, optional): Saturation factor tensor of range (a, b).
The provided range must follow -0.5 <= a <= b < 0.5. Default value is [0., 0.].
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, torch.Tensor]: parameters to be passed for transformation.
+ - brightness_factor (torch.Tensor): element-wise brightness factors with a shape of (B,).
+ - contrast_factor (torch.Tensor): element-wise contrast factors with a shape of (B,).
+ - hue_factor (torch.Tensor): element-wise hue factors with a shape of (B,).
+ - saturation_factor (torch.Tensor): element-wise saturation factors with a shape of (B,).
+ - order (torch.Tensor): applying orders of the color adjustments with a shape of (4). In which,
+ 0 is brightness adjustment; 1 is contrast adjustment;
+ 2 is saturation adjustment; 3 is hue adjustment.
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
- device, dtype = _extract_device_dtype([brightness, contrast, hue, saturation])
- brightness = torch.tensor([0., 0.], device=device, dtype=dtype) \
- if brightness is None else cast(torch.Tensor, brightness)
- contrast = torch.tensor([0., 0.], device=device, dtype=dtype) \
- if contrast is None else cast(torch.Tensor, contrast)
- hue = torch.tensor([0., 0.], device=device, dtype=dtype) \
- if hue is None else cast(torch.Tensor, hue)
- saturation = torch.tensor([0., 0.], device=device, dtype=dtype) \
- if saturation is None else cast(torch.Tensor, saturation)
+ _device, _dtype = _extract_device_dtype([brightness, contrast, hue, saturation])
+ brightness = torch.as_tensor([0., 0.] if brightness is None else brightness, device=device, dtype=dtype)
+ contrast = torch.as_tensor([0., 0.] if contrast is None else contrast, device=device, dtype=dtype)
+ hue = torch.as_tensor([0., 0.] if hue is None else hue, device=device, dtype=dtype)
+ saturation = torch.as_tensor([0., 0.] if saturation is None else saturation, device=device, dtype=dtype)
_joint_range_check(brightness, "brightness", (0, 2))
_joint_range_check(contrast, "contrast", (0, float('inf')))
@@ -83,11 +101,11 @@ def random_color_jitter_generator(
hue_factor = _adapted_uniform((batch_size,), hue[0], hue[1], same_on_batch)
saturation_factor = _adapted_uniform((batch_size,), saturation[0], saturation[1], same_on_batch)
- return dict(brightness_factor=brightness_factor,
- contrast_factor=contrast_factor,
- hue_factor=hue_factor,
- saturation_factor=saturation_factor,
- order=torch.randperm(4))
+ return dict(brightness_factor=brightness_factor.to(device=_device, dtype=_dtype),
+ contrast_factor=contrast_factor.to(device=_device, dtype=_dtype),
+ hue_factor=hue_factor.to(device=_device, dtype=_dtype),
+ saturation_factor=saturation_factor.to(device=_device, dtype=_dtype),
+ order=torch.randperm(4, device=_device, dtype=_dtype).long())
def random_perspective_generator(
@@ -96,6 +114,8 @@ def random_perspective_generator(
width: int,
distortion_scale: torch.Tensor,
same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``perspective`` for a random perspective transform.
@@ -105,9 +125,16 @@ def random_perspective_generator(
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.
+ 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, torch.Tensor])
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
+ - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
assert distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1, \
@@ -129,8 +156,10 @@ def random_perspective_generator(
factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2)
# TODO: This line somehow breaks the gradcheck
- rand_val: torch.Tensor = _adapted_uniform(start_points.shape, 0, 1, same_on_batch).to(
- device=distortion_scale.device, dtype=distortion_scale.dtype)
+ rand_val: torch.Tensor = _adapted_uniform(
+ start_points.shape, torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype), same_on_batch
+ ).to(device=distortion_scale.device, dtype=distortion_scale.dtype)
pts_norm = torch.tensor([[
[1, 1],
@@ -153,6 +182,8 @@ def random_affine_generator(
scale: Optional[torch.Tensor] = None,
shear: 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 ``affine`` for a random affine transform.
@@ -160,7 +191,7 @@ def random_affine_generator(
batch_size (int): the tensor batch size.
height (int) : height of the image.
width (int): width of the image.
- degrees (tensor): Range of degrees to select from like (min, max).
+ degrees (torch.Tensor): Range of degrees to select from like (min, max).
translate (tensor, optional): tuple of maximum absolute fraction for horizontal
and vertical translations. For example translate=(a, b), then horizontal shift
is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
@@ -171,29 +202,48 @@ def random_affine_generator(
Shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in
(shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
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, torch.Tensor]: parameters to be passed for transformation.
+ - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
+ - center (torch.Tensor): element-wise center with a shape of (B, 2).
+ - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
+ - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
+ - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
+ - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(degrees, "degrees")
assert isinstance(width, (int,)) and isinstance(height, (int,)) and width > 0 and height > 0, \
f"`width` and `height` must be positive integers. Got {width}, {height}."
- device, dtype = _extract_device_dtype([degrees, translate, scale, shear])
+ _device, _dtype = _extract_device_dtype([degrees, translate, scale, shear])
+ degrees = degrees.to(device=device, dtype=dtype)
angle = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
+ angle = angle.to(device=_device, dtype=_dtype)
# compute tensor ranges
if scale is not None:
+ scale = scale.to(device=device, dtype=dtype)
+ assert len(scale.shape) == 1 and (len(scale) == 2 or len(scale) == 4), \
+ f"`scale` shall have 2 or 4 elements. Got {scale}."
_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:
_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)
+ _scale = _scale.to(device=_device, dtype=_dtype)
else:
- _scale = torch.ones((batch_size, 2), device=device, dtype=dtype)
+ _scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
if translate is not None:
+ translate = translate.to(device=device, dtype=dtype)
_joint_range_check(cast(torch.Tensor, translate), "translate")
max_dx: torch.Tensor = translate[0] * width
max_dy: torch.Tensor = translate[1] * height
@@ -201,20 +251,24 @@ def random_affine_generator(
_adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
_adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch)
], dim=-1)
+ translations = translations.to(device=_device, dtype=_dtype)
else:
- translations = torch.zeros((batch_size, 2), device=device, dtype=dtype)
+ translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
center: torch.Tensor = torch.tensor(
- [width, height], device=device, dtype=dtype).view(1, 2) / 2. - 0.5
+ [width, height], device=_device, dtype=_dtype).view(1, 2) / 2. - 0.5
center = center.expand(batch_size, -1)
if shear is not None:
+ shear = shear.to(device=device, dtype=dtype)
_joint_range_check(cast(torch.Tensor, shear)[0], "shear")
_joint_range_check(cast(torch.Tensor, shear)[1], "shear")
sx = _adapted_uniform((batch_size,), shear[0][0], shear[0][1], same_on_batch)
sy = _adapted_uniform((batch_size,), shear[1][0], shear[1][1], same_on_batch)
+ sx = sx.to(device=_device, dtype=_dtype)
+ sy = sy.to(device=_device, dtype=_dtype)
else:
- sx = sy = torch.tensor([0] * batch_size)
+ sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
return dict(translations=translations,
center=center,
@@ -227,7 +281,9 @@ def random_affine_generator(
def random_rotation_generator(
batch_size: int,
degrees: torch.Tensor,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``rotate`` for a random rotate transform.
@@ -235,16 +291,24 @@ def random_rotation_generator(
batch_size (int): the tensor batch size.
degrees (torch.Tensor): range of degrees with shape (2) to select from.
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, torch.Tensor]: parameters to be passed for transformation.
+ - degrees (torch.Tensor): element-wise rotation degrees with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(degrees, "degrees")
- degrees = _adapted_uniform((batch_size,), degrees[0], degrees[1], same_on_batch)
+ _degrees = _adapted_uniform((batch_size,), degrees[0].to(device=device, dtype=dtype),
+ degrees[1].to(device=device, dtype=dtype), same_on_batch)
+ _degrees = _degrees.to(device=degrees.device, dtype=degrees.dtype)
- return dict(degrees=degrees)
+ return dict(degrees=_degrees)
def random_crop_generator(
@@ -252,7 +316,9 @@ def random_crop_generator(
input_size: Tuple[int, int],
size: Union[Tuple[int, int], torch.Tensor],
resize_to: Optional[Tuple[int, int]] = None,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
@@ -263,52 +329,58 @@ def random_crop_generator(
If tensor, it must be (B, 2).
resize_to (tuple): Desired output size of the crop, like (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, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
Example:
>>> _ = torch.manual_seed(0)
- >>> crop_size = random_crop_size_generator(
- ... 3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))['size']
- >>> crop_size
- tensor([[26, 29],
- [27, 28],
- [25, 28]], dtype=torch.int32)
+ >>> crop_size = torch.tensor([[25, 28], [27, 29], [26, 28]])
>>> random_crop_generator(3, (30, 30), size=crop_size, same_on_batch=False)
- {'src': tensor([[[ 1, 3],
- [29, 3],
- [29, 28],
- [ 1, 28]],
+ {'src': tensor([[[ 1, 0],
+ [28, 0],
+ [28, 24],
+ [ 1, 24]],
<BLANKLINE>
- [[ 2, 3],
- [29, 3],
- [29, 29],
- [ 2, 29]],
+ [[ 1, 1],
+ [29, 1],
+ [29, 27],
+ [ 1, 27]],
<BLANKLINE>
- [[ 0, 2],
- [27, 2],
- [27, 26],
- [ 0, 26]]]), 'dst': tensor([[[ 0, 0],
- [28, 0],
- [28, 25],
- [ 0, 25]],
+ [[ 0, 3],
+ [27, 3],
+ [27, 28],
+ [ 0, 28]]]), 'dst': tensor([[[ 0, 0],
+ [27, 0],
+ [27, 24],
+ [ 0, 24]],
<BLANKLINE>
[[ 0, 0],
- [27, 0],
- [27, 26],
+ [28, 0],
+ [28, 26],
[ 0, 26]],
<BLANKLINE>
[[ 0, 0],
[27, 0],
- [27, 24],
- [ 0, 24]]])}
+ [27, 25],
+ [ 0, 25]]])}
"""
_common_param_check(batch_size, same_on_batch)
+ _device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])
if not isinstance(size, torch.Tensor):
- 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 = torch.tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
+ else:
+ size = size.to(device=device, dtype=dtype)
+ assert size.shape == torch.Size([batch_size, 2]), (
+ "If `size` is a tensor, it must be shaped as (B, 2). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 2])}.")
size = size.long()
x_diff = input_size[1] - size[:, 1] + 1
@@ -318,28 +390,37 @@ def random_crop_generator(
raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."
% (str(input_size), str(size)))
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 4, 2], device=_device, dtype=torch.long),
+ dst=torch.zeros([0, 4, 2], device=_device, dtype=torch.long),
+ )
+
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()
+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0].to(device=device, dtype=dtype), same_on_batch).long()
+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0].to(device=device, dtype=dtype), 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()
-
- crop_src = bbox_generator(x_start.view(-1), y_start.view(-1), size[:, 1] - 1, size[:, 0] - 1)
+ x_start = _adapted_uniform((1,), 0, x_diff.to(device=device, dtype=dtype), same_on_batch).long()
+ y_start = _adapted_uniform((1,), 0, y_diff.to(device=device, dtype=dtype), same_on_batch).long()
+ crop_src = bbox_generator(
+ x_start.view(-1), y_start.view(-1), size[:, 1], size[:, 0]).to(device=_device, dtype=torch.long)
if resize_to is None:
crop_dst = bbox_generator(
- torch.tensor([0] * batch_size, device=x_start.device, dtype=x_start.dtype),
- torch.tensor([0] * batch_size, device=x_start.device, dtype=x_start.dtype),
- size[:, 1] - 1, size[:, 0] - 1)
+ torch.tensor([0] * batch_size, device=device, dtype=torch.long),
+ torch.tensor([0] * batch_size, device=device, dtype=torch.long),
+ size[:, 1], size[:, 0]).to(device=_device, dtype=torch.long)
else:
+ assert len(resize_to) == 2 and isinstance(resize_to[0], (int,)) and isinstance(resize_to[1], (int,)) \
+ and resize_to[0] > 0 and resize_to[1] > 0, \
+ f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}."
crop_dst = torch.tensor([[
[0, 0],
[resize_to[1] - 1, 0],
[resize_to[1] - 1, resize_to[0] - 1],
[0, resize_to[0] - 1],
- ]], device=x_start.device, dtype=x_start.dtype).repeat(batch_size, 1, 1)
+ ]], device=_device, dtype=torch.long).repeat(batch_size, 1, 1)
return dict(src=crop_src,
dst=crop_dst)
@@ -350,36 +431,50 @@ def random_crop_size_generator(
size: Tuple[int, int],
scale: torch.Tensor,
ratio: torch.Tensor,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
Args:
batch_size (int): the tensor batch size.
size (Tuple[int, int]): expected output size of each edge.
- scale (tensor): range of size of the origin size cropped with (2,) shape.
- ratio (tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
+ scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
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, torch.Tensor]: parameters to be passed for transformation.
+ - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
- Examples:
- >>> _ = torch.manual_seed(0)
- >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
- {'size': tensor([[26, 29],
- [27, 28],
- [25, 28]], dtype=torch.int32)}
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
+
+ # TODO: Add a doctest to this function. The following code failed on the cloud environment.
+ # Examples:
+ # >>> _ = torch.manual_seed(42)
+ # >>> random_crop_size_generator(3, (30, 30), scale=torch.tensor([.7, 1.3]), ratio=torch.tensor([.9, 1.]))
+ # {'size': tensor([[26, 27],
+ # [27, 28],
+ # [24, 26]])}
+
_common_param_check(batch_size, same_on_batch)
_joint_range_check(scale, "scale")
_joint_range_check(ratio, "ratio")
assert len(size) == 2 and type(size[0]) == int and size[1] > 0 and type(size[1]) == int and size[1] > 0, \
f"'height' and 'width' must be integers. Got {size}."
+ _device, _dtype = _extract_device_dtype([scale, ratio])
+
if batch_size == 0:
- return dict(size=torch.zeros([0, 2]))
+ return dict(size=torch.zeros([0, 2], device=_device, dtype=_dtype))
+ scale = scale.to(device=device, dtype=dtype)
+ ratio = ratio.to(device=device, dtype=dtype)
# 10 trails for each element
area = _adapted_uniform(
(batch_size, 10), scale[0] * size[0] * size[1], scale[1] * size[0] * size[1], same_on_batch)
@@ -387,34 +482,34 @@ def random_crop_size_generator(
(batch_size, 10), torch.log(ratio[0]), torch.log(ratio[1]), same_on_batch)
aspect_ratio = torch.exp(log_ratio)
- w = torch.sqrt(area * aspect_ratio).int()
- h = torch.sqrt(area / aspect_ratio).int()
+ w = torch.sqrt(area * aspect_ratio).round().int()
+ h = torch.sqrt(area / aspect_ratio).round().int()
# Element-wise w, h condition
cond = ((0 < w) * (w < size[1]) * (0 < h) * (h < size[0])).int()
cond_bool = torch.sum(cond, dim=1) > 0
- h_out = w[torch.arange(0, batch_size), torch.argmax(cond, dim=1)]
- w_out = h[torch.arange(0, batch_size), torch.argmax(cond, dim=1)]
+ h_out = w[torch.arange(0, batch_size, device=device, dtype=torch.long), torch.argmax(cond, dim=1)]
+ w_out = h[torch.arange(0, batch_size, device=device, dtype=torch.long), torch.argmax(cond, dim=1)]
if not cond_bool.all():
# Fallback to center crop
in_ratio = float(size[0]) / float(size[1])
if (in_ratio < min(ratio)):
- h_ct = torch.tensor(size[0])
+ h_ct = torch.tensor(size[0], device=device, dtype=dtype)
w_ct = torch.round(h_ct / min(ratio))
elif (in_ratio > max(ratio)):
- w_ct = torch.tensor(size[1])
+ w_ct = torch.tensor(size[1], device=device, dtype=dtype)
h_ct = torch.round(w_ct * max(ratio))
else: # whole image
- h_ct = torch.tensor(size[0])
- w_ct = torch.tensor(size[1])
+ h_ct = torch.tensor(size[0], device=device, dtype=dtype)
+ w_ct = torch.tensor(size[1], device=device, dtype=dtype)
h_ct = h_ct.int()
w_ct = w_ct.int()
h_out = h_out.where(cond_bool, h_ct)
w_out = w_out.where(cond_bool, w_ct)
- return dict(size=torch.stack([h_out, w_out], dim=1))
+ return dict(size=torch.stack([h_out, w_out], dim=1).to(device=_device, dtype=torch.long))
def random_rectangles_params_generator(
@@ -424,7 +519,9 @@ def random_rectangles_params_generator(
scale: torch.Tensor,
ratio: torch.Tensor,
value: float = 0.,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```erasing``` transformation for erasing transform.
@@ -436,12 +533,22 @@ def random_rectangles_params_generator(
ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
value (float): value to be filled in the erased area.
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, torch.Tensor]: parameters to be passed for transformation.
+ - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
+ - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
+ - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
+ - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
+ - values (torch.Tensor): element-wise filling values with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
- device, dtype = _extract_device_dtype([ratio, scale])
+ _device, _dtype = _extract_device_dtype([ratio, scale])
assert type(height) == int and height > 0 and type(width) == int and width > 0, \
f"'height' and 'width' must be integers. Got {height}, {width}."
assert isinstance(value, (int, float)) and value >= 0 and value <= 1, \
@@ -450,11 +557,11 @@ def random_rectangles_params_generator(
_joint_range_check(ratio, 'ratio', bounds=(0, float('inf')))
images_area = height * width
- target_areas = _adapted_uniform(
- (batch_size,), scale[0], scale[1], same_on_batch) * images_area
+ target_areas = _adapted_uniform((batch_size,), scale[0].to(device=device, dtype=dtype),
+ scale[1].to(device=device, dtype=dtype), same_on_batch) * images_area
if ratio[0] < 1. and ratio[1] > 1.:
- aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0], 1, same_on_batch)
- aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1], same_on_batch)
+ aspect_ratios1 = _adapted_uniform((batch_size,), ratio[0].to(device=device, dtype=dtype), 1, same_on_batch)
+ aspect_ratios2 = _adapted_uniform((batch_size,), 1, ratio[1].to(device=device, dtype=dtype), same_on_batch)
if same_on_batch:
rand_idxs = torch.round(_adapted_uniform(
(1,), torch.tensor(0, device=device, dtype=dtype),
@@ -465,7 +572,9 @@ def random_rectangles_params_generator(
torch.tensor(1, device=device, dtype=dtype), same_on_batch)).bool()
aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
else:
- aspect_ratios = _adapted_uniform((batch_size,), ratio[0], ratio[1], same_on_batch)
+ aspect_ratios = _adapted_uniform(
+ (batch_size,), ratio[0].to(device=device, dtype=dtype),
+ ratio[1].to(device=device, dtype=dtype), same_on_batch)
# based on target areas and aspect ratios, rectangle params are computed
heights = torch.min(
@@ -480,28 +589,27 @@ def random_rectangles_params_generator(
torch.tensor(width, device=device, dtype=dtype)
)
- xs_ratio = _adapted_uniform(
- (batch_size,), torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch)
- ys_ratio = _adapted_uniform(
- (batch_size,), torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype), same_on_batch)
+ xs_ratio = _adapted_uniform((batch_size,), torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype), same_on_batch)
+ ys_ratio = _adapted_uniform((batch_size,), torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype), same_on_batch)
xs = xs_ratio * (torch.tensor(width, device=device, dtype=dtype) - widths + 1)
ys = ys_ratio * (torch.tensor(height, device=device, dtype=dtype) - heights + 1)
- return dict(widths=widths.int(),
- heights=heights.int(),
- xs=xs.int(),
- ys=ys.int(),
- values=torch.tensor([value] * batch_size, device=device, dtype=dtype))
+ return dict(widths=widths.to(device=_device, dtype=torch.int32),
+ heights=heights.to(device=_device, dtype=torch.int32),
+ xs=xs.to(device=_device, dtype=torch.int32),
+ ys=ys.to(device=_device, dtype=torch.int32),
+ values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype))
def center_crop_generator(
batch_size: int,
height: int,
width: int,
- size: Tuple[int, int]
+ size: Tuple[int, int],
+ device: torch.device = torch.device('cpu')
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
@@ -510,9 +618,15 @@ def center_crop_generator(
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (h, w).
+ device (torch.device): the device on which the random numbers will be generated. Default: cpu.
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+
+ Note:
+ No random number will be generated.
"""
_common_param_check(batch_size)
if not isinstance(size, (tuple, list,)) and len(size) == 2:
@@ -546,7 +660,7 @@ def center_crop_generator(
[end_x, start_y],
[end_x, end_y],
[start_x, end_y],
- ]]).expand(batch_size, -1, -1).long()
+ ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
@@ -555,7 +669,7 @@ def center_crop_generator(
[dst_w - 1, 0],
[dst_w - 1, dst_h - 1],
[0, dst_h - 1],
- ]]).expand(batch_size, -1, -1).long()
+ ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
return dict(src=points_src,
dst=points_dst)
@@ -565,7 +679,9 @@ def random_motion_blur_generator(
kernel_size: Union[int, Tuple[int, int]],
angle: torch.Tensor,
direction: torch.Tensor,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for motion blur.
@@ -578,42 +694,57 @@ def random_motion_blur_generator(
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, torch.Tensor]: parameters to be passed for transformation.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(angle, 'angle')
_joint_range_check(direction, 'direction', (-1, 1))
- device, dtype = _extract_device_dtype([angle, direction])
+ _device, _dtype = _extract_device_dtype([angle, direction])
if isinstance(kernel_size, int):
+ assert kernel_size >= 3 and kernel_size % 2 == 1, \
+ 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)
elif isinstance(kernel_size, tuple):
# kernel_size is fixed across the batch
assert len(kernel_size) == 2, f"`kernel_size` must be (2,) if it is a tuple. Got {kernel_size}."
ksize_factor = _adapted_uniform(
- (batch_size,), kernel_size[0] // 2, kernel_size[1] // 2, same_on_batch=True).int() * 2 + 1
+ (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)}")
angle_factor = _adapted_uniform(
- (batch_size,), angle[0], angle[1], same_on_batch)
+ (batch_size,), angle[0].to(device=device, dtype=dtype),
+ angle[1].to(device=device, dtype=dtype), same_on_batch)
direction_factor = _adapted_uniform(
- (batch_size,), direction[0], direction[1], same_on_batch)
+ (batch_size,), direction[0].to(device=device, dtype=dtype),
+ direction[1].to(device=device, dtype=dtype), same_on_batch)
- return dict(ksize_factor=ksize_factor.int(),
- angle_factor=angle_factor,
- direction_factor=direction_factor)
+ return dict(ksize_factor=ksize_factor.to(device=_device, dtype=torch.int32),
+ angle_factor=angle_factor.to(device=_device, dtype=_dtype),
+ direction_factor=direction_factor.to(device=_device, dtype=_dtype))
def random_solarize_generator(
batch_size: int,
thresholds: torch.Tensor = torch.tensor([0.4, 0.6]),
additions: torch.Tensor = torch.tensor([-0.1, 0.1]),
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Generate random solarize parameters for a batch of images.
@@ -626,30 +757,43 @@ def random_solarize_generator(
Takes in a range tensor of (0, 1). Default value will be sampled from [0.4, 0.6].
additions (torch.Tensor): The value is between -0.5 and 0.5. Default value will be sampled from [-0.1, 0.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, torch.Tensor]: parameters to be passed for transformation.
+ - thresholds_factor (torch.Tensor): element-wise thresholds factors with a shape of (B,).
+ - additions_factor (torch.Tensor): element-wise additions factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(thresholds, 'thresholds', (0, 1))
_joint_range_check(additions, 'additions', (-0.5, 0.5))
+ _device, _dtype = _extract_device_dtype([thresholds, additions])
+
thresholds_factor = _adapted_uniform(
- (batch_size,), thresholds[0], thresholds[1], same_on_batch)
+ (batch_size,), thresholds[0].to(device=device, dtype=dtype),
+ thresholds[1].to(device=device, dtype=dtype), same_on_batch)
additions_factor = _adapted_uniform(
- (batch_size,), additions[0], additions[1], same_on_batch)
+ (batch_size,), additions[0].to(device=device, dtype=dtype),
+ additions[1].to(device=device, dtype=dtype), same_on_batch)
return dict(
- thresholds_factor=thresholds_factor,
- additions_factor=additions_factor
+ thresholds_factor=thresholds_factor.to(device=_device, dtype=_dtype),
+ additions_factor=additions_factor.to(device=_device, dtype=_dtype)
)
def random_posterize_generator(
batch_size: int,
bits: torch.Tensor = torch.tensor([3, 5]),
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Generate random posterize parameters for a batch of images.
@@ -657,23 +801,33 @@ def random_posterize_generator(
batch_size (int): the number of images.
bits (int or tuple): Takes in an integer tuple tensor that ranged from 0 ~ 8. Default value is [3, 5].
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, torch.Tensor]: parameters to be passed for transformation.
+ - bits_factor (torch.Tensor): element-wise bit factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(bits, 'bits', (0, 8))
- bits_factor = _adapted_uniform((batch_size,), bits[0], bits[1], same_on_batch).int()
+ bits_factor = _adapted_uniform(
+ (batch_size,), bits[0].to(device=device, dtype=dtype), bits[1].to(device=device, dtype=dtype),
+ same_on_batch).int()
return dict(
- bits_factor=bits_factor
+ bits_factor=bits_factor.to(device=bits.device, dtype=torch.int32)
)
def random_sharpness_generator(
batch_size: int,
sharpness: torch.Tensor = torch.tensor([0, 1.]),
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Generate random sharpness parameters for a batch of images.
@@ -681,17 +835,24 @@ def random_sharpness_generator(
batch_size (int): the number of images.
sharpness (torch.Tensor): Must be above 0. Default value is sampled from (0, 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, torch.Tensor]: parameters to be passed for transformation.
+ - sharpness_factor (torch.Tensor): element-wise sharpness factors with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
_common_param_check(batch_size, same_on_batch)
_joint_range_check(sharpness, 'sharpness', bounds=(0, float('inf')))
- sharpness_factor = _adapted_uniform((batch_size,), sharpness[0], sharpness[1], same_on_batch)
+ sharpness_factor = _adapted_uniform((batch_size,), sharpness[0].to(device=device, dtype=dtype),
+ sharpness[1].to(device=device, dtype=dtype), same_on_batch)
return dict(
- sharpness_factor=sharpness_factor
+ sharpness_factor=sharpness_factor.to(device=sharpness.device, dtype=sharpness.dtype)
)
@@ -699,7 +860,9 @@ def random_mixup_generator(
batch_size: int,
p: float = 0.5,
lambda_val: Optional[torch.Tensor] = None,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Generate mixup indexes and lambdas for a batch of inputs.
@@ -709,9 +872,16 @@ def random_mixup_generator(
lambda_val (torch.Tensor, optional): min-max strength for mixup images, ranged from [0., 1.].
If None, it will be set to tensor([0., 1.]), which means no restrictions.
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, torch.Tensor]: parameters to be passed for transformation.
+ - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (B,).
+ - mixup_lambdas (torch.Tensor): element-wise probabilities with a shape of (B,).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
Examples:
>>> rng = torch.manual_seed(0)
@@ -719,19 +889,21 @@ def random_mixup_generator(
{'mixup_pairs': tensor([4, 0, 3, 1, 2]), 'mixup_lambdas': tensor([0.6323, 0.0000, 0.4017, 0.0223, 0.1689])}
"""
_common_param_check(batch_size, same_on_batch)
- if lambda_val is None:
- lambda_val = torch.tensor([0., 1.], dtype=torch.float64)
+ _device, _dtype = _extract_device_dtype([lambda_val])
+ lambda_val = torch.as_tensor([0., 1.] if lambda_val is None else lambda_val, device=device, dtype=dtype)
_joint_range_check(lambda_val, 'lambda_val', bounds=(0, 1))
- batch_probs: torch.Tensor = random_prob_generator(batch_size, p, same_on_batch=same_on_batch)
- mixup_pairs: torch.Tensor = torch.randperm(batch_size)
+ batch_probs: torch.Tensor = random_prob_generator(
+ batch_size, p, same_on_batch=same_on_batch, device=device, dtype=dtype
+ )
+ mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=device, dtype=dtype).long()
mixup_lambdas: torch.Tensor = _adapted_uniform(
(batch_size,), lambda_val[0], lambda_val[1], same_on_batch=same_on_batch)
- mixup_lambdas = mixup_lambdas * batch_probs.to(device=lambda_val.device, dtype=lambda_val.dtype)
+ mixup_lambdas = mixup_lambdas * batch_probs
return dict(
- mixup_pairs=mixup_pairs,
- mixup_lambdas=mixup_lambdas
+ mixup_pairs=mixup_pairs.to(device=_device, dtype=torch.long),
+ mixup_lambdas=mixup_lambdas.to(device=_device, dtype=_dtype)
)
@@ -743,7 +915,9 @@ def random_cutmix_generator(
num_mix: int = 1,
beta: Optional[torch.Tensor] = None,
cut_size: Optional[torch.Tensor] = None,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Generate cutmix indexes and lambdas for a batch of inputs.
@@ -758,23 +932,30 @@ def random_cutmix_generator(
cut_size (torch.Tensor, optional): controlling the minimum and maximum cut ratio from [0, 1].
If None, it will be set to [0, 1], which means no restriction.
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, torch.Tensor]: parameters to be passed for transformation.
+ - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (num_mix, B).
+ - crop_src (torch.Tensor): element-wise probabilities with a shape of (num_mix, B, 4, 2).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
Examples:
>>> rng = torch.manual_seed(0)
>>> random_cutmix_generator(3, 224, 224, p=0.5, num_mix=2)
{'mix_pairs': tensor([[2, 0, 1],
- [1, 2, 0]]), 'crop_src': tensor([[[[ 36, 25],
- [209, 25],
- [209, 198],
- [ 36, 198]],
+ [1, 2, 0]]), 'crop_src': tensor([[[[ 35, 25],
+ [208, 25],
+ [208, 198],
+ [ 35, 198]],
<BLANKLINE>
- [[157, 137],
- [156, 137],
- [156, 136],
- [157, 136]],
+ [[156, 137],
+ [155, 137],
+ [155, 136],
+ [156, 136]],
<BLANKLINE>
[[ 3, 12],
[210, 12],
@@ -782,27 +963,24 @@ def random_cutmix_generator(
[ 3, 219]]],
<BLANKLINE>
<BLANKLINE>
- [[[ 83, 126],
- [177, 126],
- [177, 220],
- [ 83, 220]],
+ [[[ 83, 125],
+ [177, 125],
+ [177, 219],
+ [ 83, 219]],
<BLANKLINE>
- [[ 55, 8],
- [206, 8],
- [206, 159],
- [ 55, 159]],
+ [[ 54, 8],
+ [205, 8],
+ [205, 159],
+ [ 54, 159]],
<BLANKLINE>
[[ 97, 70],
[ 96, 70],
[ 96, 69],
[ 97, 69]]]])}
-
"""
- device, dtype = _extract_device_dtype([beta, cut_size])
- if beta is None:
- beta = torch.tensor(1., device=device, dtype=dtype)
- if cut_size is None:
- cut_size = torch.tensor([0., 1.], device=device, dtype=dtype)
+ _device, _dtype = _extract_device_dtype([beta, cut_size])
+ beta = torch.as_tensor(1. if beta is None else beta, device=device, dtype=dtype)
+ cut_size = torch.as_tensor([0., 1.] if cut_size is None else cut_size, device=device, dtype=dtype)
assert num_mix >= 1 and isinstance(num_mix, (int,)), \
f"`num_mix` must be an integer greater than 1. Got {num_mix}."
assert type(height) == int and height > 0 and type(width) == int and width > 0, \
@@ -810,17 +988,23 @@ def random_cutmix_generator(
_joint_range_check(cut_size, 'cut_size', bounds=(0, 1))
_common_param_check(batch_size, same_on_batch)
+ if batch_size == 0:
+ return dict(
+ mix_pairs=torch.zeros([0, 3], device=_device, dtype=torch.long),
+ crop_src=torch.zeros([0, 4, 2], device=_device, dtype=torch.long)
+ )
+
batch_probs: torch.Tensor = random_prob_generator(
- batch_size * num_mix, p, same_on_batch).to(device=device, dtype=dtype)
- mix_pairs: torch.Tensor = torch.rand(num_mix, batch_size).argsort(dim=1)
+ batch_size * num_mix, p, same_on_batch, device=device, dtype=dtype)
+ mix_pairs: torch.Tensor = torch.rand(num_mix, batch_size, device=device, dtype=dtype).argsort(dim=1)
cutmix_betas: torch.Tensor = _adapted_beta((batch_size * num_mix,), beta, beta, same_on_batch=same_on_batch)
# Note: torch.clamp does not accept tensor, cutmix_betas.clamp(cut_size[0], cut_size[1]) throws:
# Argument 1 to "clamp" of "_TensorBase" has incompatible type "Tensor"; expected "float"
cutmix_betas = torch.min(torch.max(cutmix_betas, cut_size[0]), cut_size[1])
cutmix_rate = torch.sqrt(1. - cutmix_betas) * batch_probs
- cut_height = (cutmix_rate * height).long() - 1
- cut_width = (cutmix_rate * width).long() - 1
+ cut_height = (cutmix_rate * height).long()
+ cut_width = (cutmix_rate * width).long()
_gen_shape = (1,)
if same_on_batch:
@@ -830,11 +1014,11 @@ def random_cutmix_generator(
# Reserve at least 1 pixel for cropping.
x_start = _adapted_uniform(
- _gen_shape, torch.zeros_like(cut_width, device=device, dtype=torch.long),
- (width - cut_width - 1).to(device=device, dtype=torch.long), same_on_batch)
+ _gen_shape, torch.zeros_like(cut_width, device=device, dtype=dtype),
+ (width - cut_width - 1).to(device=device, dtype=dtype), same_on_batch).to(device=device, dtype=torch.long)
y_start = _adapted_uniform(
- _gen_shape, torch.zeros_like(cut_height, device=device, dtype=torch.long),
- (height - cut_height - 1).to(device=device, dtype=torch.long), same_on_batch)
+ _gen_shape, torch.zeros_like(cut_height, device=device, dtype=dtype),
+ (height - cut_height - 1).to(device=device, dtype=dtype), same_on_batch).to(device=device, dtype=torch.long)
crop_src = bbox_generator(x_start.squeeze(), y_start.squeeze(), cut_width, cut_height)
@@ -842,6 +1026,6 @@ def random_cutmix_generator(
crop_src = crop_src.view(num_mix, batch_size, 4, 2)
return dict(
- mix_pairs=mix_pairs,
- crop_src=crop_src
+ mix_pairs=mix_pairs.to(device=_device, dtype=torch.long),
+ crop_src=crop_src.to(device=_device, dtype=torch.long)
)
diff --git a/kornia/augmentation/random_generator/random_generator3d.py b/kornia/augmentation/random_generator/random_generator3d.py
index 8e1af8b15..c21b6a3e4 100644
--- a/kornia/augmentation/random_generator/random_generator3d.py
+++ b/kornia/augmentation/random_generator/random_generator3d.py
@@ -8,6 +8,7 @@ from kornia.constants import Resample, BorderType
from kornia.geometry import bbox_generator3d
from ..utils import (
_adapted_uniform,
+ _joint_range_check,
_tuple_range_reader,
)
from kornia.utils import _extract_device_dtype
@@ -16,26 +17,35 @@ from kornia.utils import _extract_device_dtype
def random_rotation_generator3d(
batch_size: int,
degrees: torch.Tensor,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``rotate`` for a random rotate transform.
Args:
batch_size (int): the tensor batch size.
degrees (torch.Tensor): Ranges of degrees (3, 2) for yaw, pitch and roll.
- same_on_batch (bool): apply the same transformation across the batch. Default: False
+ 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, torch.Tensor]: parameters to be passed for transformation.
+ - yaw (torch.Tensor): element-wise roataion yaws with a shape of (B,).
+ - pitch (torch.Tensor): element-wise roataion pitchs with a shape of (B,).
+ - roll (torch.Tensor): element-wise roataion rolls with a shape of (B,).
"""
assert degrees.shape == torch.Size([3, 2]), 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,
- pitch=pitch,
- roll=roll)
+ return dict(yaw=yaw.to(device=_device, dtype=_dtype),
+ pitch=pitch.to(device=_device, dtype=_dtype),
+ roll=roll.to(device=_device, dtype=_dtype))
def random_affine_generator3d(
@@ -48,6 +58,8 @@ def random_affine_generator3d(
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.
@@ -68,9 +80,27 @@ def random_affine_generator3d(
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.
"""
- device, dtype = _extract_device_dtype([degrees, translate, scale, shears])
+ assert type(depth) == int and depth > 0 and \
+ type(height) == int and height > 0 and type(width) == int and width > 0, \
+ f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}."
+
+ _device, _dtype = _extract_device_dtype([degrees, translate, scale, shears])
assert degrees.shape == torch.Size([3, 2]), 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)
@@ -79,6 +109,7 @@ def random_affine_generator3d(
# compute tensor ranges
if scale is not None:
assert scale.shape == torch.Size([3, 2]), 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),
@@ -89,6 +120,7 @@ def random_affine_generator3d(
if translate is not None:
assert translate.shape == torch.Size([3]), 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
@@ -108,6 +140,7 @@ def random_affine_generator3d(
if shears is not None:
assert shears.shape == torch.Size([6, 2]), 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)
@@ -117,16 +150,16 @@ def random_affine_generator3d(
else:
sxy = sxz = syx = syz = szx = szy = torch.tensor([0] * batch_size, device=device, dtype=dtype)
- return dict(translations=translations,
- center=center,
- scale=scale,
- angles=angles,
- sxy=sxy,
- sxz=sxz,
- syx=syx,
- syz=syz,
- szx=szx,
- szy=szy)
+ 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))
def random_motion_blur_generator3d(
@@ -134,7 +167,9 @@ def random_motion_blur_generator3d(
kernel_size: Union[int, Tuple[int, int]],
angle: torch.Tensor,
direction: torch.Tensor,
- same_on_batch: bool = False
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for motion blur.
@@ -147,33 +182,47 @@ def random_motion_blur_generator3d(
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, torch.Tensor]: parameters to be passed for transformation.
+ - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise center with a shape of (B,).
+ - direction_factor (torch.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])
+ _device, _dtype = _extract_device_dtype([angle, direction])
+ _joint_range_check(direction, 'direction', (-1, 1))
if isinstance(kernel_size, int):
- ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype)
+ assert kernel_size >= 3 and kernel_size % 2 == 1, \
+ 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):
+ assert len(kernel_size) == 2 and kernel_size[0] >= 3 and kernel_size[0] <= kernel_size[1], \
+ 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
- ksize_factor = ksize_factor.to(device=device, dtype=dtype)
+ 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)}")
assert angle.shape == torch.Size([3, 2]), 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 = torch.stack([yaw, pitch, roll], dim=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.int(),
- angle_factor=angle_factor,
- direction_factor=direction_factor)
+ 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))
def center_crop_generator3d(
@@ -181,7 +230,8 @@ def center_crop_generator3d(
depth: int,
height: int,
width: int,
- size: Tuple[int, int, int]
+ size: Tuple[int, int, int],
+ device: torch.device = torch.device('cpu')
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
@@ -191,16 +241,30 @@ def center_crop_generator3d(
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (d, h, w).
+ device (torch.device): the device on which the random numbers will be generated. Default: cpu.
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+
+ Note:
+ No random number will be generated.
"""
- # TODO: This function does not accept tensors at all.
- # Can't infer the device and dtype
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 type(depth) == int and depth > 0 and \
+ type(height) == int and height > 0 and type(width) == int and width > 0, \
+ f"'depth', 'height' and 'width' must be integers. Got {depth}, {height}, {width}."
+ assert depth >= size[0] and height >= size[1] and width >= size[2], \
+ f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}."
+
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 8, 3]),
+ dst=torch.zeros([0, 8, 3]),
+ )
# unpack input sizes
dst_d, dst_h, dst_w = size
src_d, src_h, src_w = (depth, height, width)
@@ -232,7 +296,7 @@ def center_crop_generator3d(
[end_x, start_y, end_z],
[end_x, end_y, end_z],
[start_x, end_y, end_z],
- ]])
+ ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
# [x, y, z] destination
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
@@ -246,9 +310,9 @@ def center_crop_generator3d(
[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.long(),
- dst=points_dst.long())
+ ]], device=device, dtype=torch.long).expand(batch_size, -1, -1)
+ return dict(src=points_src,
+ dst=points_dst)
def random_crop_generator3d(
@@ -256,7 +320,9 @@ def random_crop_generator3d(
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
+ same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
@@ -267,15 +333,25 @@ def random_crop_generator3d(
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, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.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, torch.Tensor) else None])
if not isinstance(size, torch.Tensor):
- size = torch.tensor(size).repeat(batch_size, 1)
- device, dtype = size.device, size.dtype
- assert size.shape == torch.Size([batch_size, 3]), \
- f"If `size` is a tensor, it must be shaped as (B, 3). Got {size.shape}."
+ size = torch.tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
+ else:
+ size = size.to(device=device, dtype=dtype)
+ assert size.shape == torch.Size([batch_size, 3]), (
+ "If `size` is a tensor, it must be shaped as (B, 3). "
+ f"Got {size.shape} while expecting {torch.Size([batch_size, 3])}.")
assert 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, \
f"`input_size` must be a tuple of 3 positive integers. Got {input_size}."
@@ -288,23 +364,29 @@ def random_crop_generator3d(
raise ValueError("input_size %s cannot be smaller than crop size %s in any dimension."
% (str(input_size), str(size)))
+ if batch_size == 0:
+ return dict(
+ src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ dst=torch.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).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()
+ x_start = _adapted_uniform((batch_size,), 0, x_diff[0], same_on_batch)
+ y_start = _adapted_uniform((batch_size,), 0, y_diff[0], same_on_batch)
+ z_start = _adapted_uniform((batch_size,), 0, z_diff[0], same_on_batch)
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()
+ x_start = _adapted_uniform((1,), 0, x_diff, same_on_batch)
+ y_start = _adapted_uniform((1,), 0, y_diff, same_on_batch)
+ z_start = _adapted_uniform((1,), 0, z_diff, same_on_batch)
crop_src = bbox_generator3d(
- x_start.view(-1).to(device=device, dtype=dtype),
- y_start.view(-1).to(device=device, dtype=dtype),
- z_start.view(-1).to(device=device, dtype=dtype),
+ x_start.view(-1),
+ y_start.view(-1),
+ z_start.view(-1),
size[:, 2] - 1,
size[:, 1] - 1,
- size[:, 0] - 1)
+ size[:, 0] - 1).long()
if resize_to is None:
crop_dst = bbox_generator3d(
@@ -313,7 +395,7 @@ def random_crop_generator3d(
torch.tensor([0] * batch_size, device=device, dtype=dtype),
size[:, 2] - 1,
size[:, 1] - 1,
- size[:, 0] - 1)
+ size[:, 0] - 1).long()
else:
assert 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, \
@@ -327,10 +409,10 @@ def random_crop_generator3d(
[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)
+ ]], device=device, dtype=torch.long).repeat(batch_size, 1, 1)
- return dict(src=crop_src,
- dst=crop_dst)
+ return dict(src=crop_src.to(device=_device),
+ dst=crop_dst.to(device=_device))
def random_perspective_generator3d(
@@ -340,6 +422,8 @@ def random_perspective_generator3d(
width: int,
distortion_scale: torch.Tensor,
same_on_batch: bool = False,
+ device: torch.device = torch.device('cpu'),
+ dtype: torch.dtype = torch.float32,
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ``perspective`` for a random perspective transform.
@@ -350,13 +434,21 @@ def random_perspective_generator3d(
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.
+ 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, torch.Tensor])
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ - src (torch.Tensor): perspecive source bounding boxes with a shape of (B, 8, 3).
+ - dst (torch.Tensor): perspecive target bounding boxes with a shape (B, 8, 3).
+
+ Note:
+ The generated random numbers are not reproducible across different devices and dtypes.
"""
assert distortion_scale.dim() == 0 and 0 <= distortion_scale <= 1, \
f"'distortion_scale' must be a scalar within [0, 1]. Got {distortion_scale}"
- device, dtype = distortion_scale.device, distortion_scale.dtype
+ _device, _dtype = _extract_device_dtype([distortion_scale])
+ distortion_scale = distortion_scale.to(device=device, dtype=dtype)
start_points: torch.Tensor = torch.tensor([[
[0., 0, 0],
@@ -376,9 +468,8 @@ def random_perspective_generator3d(
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).to(
- device=device, dtype=dtype)
+ rand_val: torch.Tensor = _adapted_uniform(start_points.shape, torch.tensor(0, device=device, dtype=dtype),
+ torch.tensor(1, device=device, dtype=dtype), same_on_batch)
pts_norm = torch.tensor([[
[1, 1, 1],
@@ -392,5 +483,5 @@ def random_perspective_generator3d(
]], device=device, dtype=dtype)
end_points = start_points + factor * rand_val * pts_norm
- return dict(start_points=start_points,
- end_points=end_points)
+ 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/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index e92171b54..810b3a216 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -1,9 +1,11 @@
-from typing import Tuple, Union, List, Callable
+from typing import Tuple, Union, List, Callable, Optional
import torch
from torch.distributions import Uniform, Beta
from functools import wraps
+from kornia.utils import _extract_device_dtype
+
def _validate_input(f: Callable) -> Callable:
r"""Validates the 2D input of the wrapped function.
@@ -49,8 +51,6 @@ def _validate_input3D(f: Callable) -> Callable:
return wrapper
-from kornia.utils import _extract_device_dtype
-
def _infer_batch_shape(input: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]) -> torch.Size:
r"""Infer input shape. Input may be either (tensor,) or (tensor, transform_matrix)
@@ -226,51 +226,48 @@ def _adapted_uniform(
shape: Union[Tuple, torch.Size],
low: Union[float, int, torch.Tensor],
high: Union[float, int, torch.Tensor],
- same_on_batch=False
+ same_on_batch: bool = False
) -> torch.Tensor:
r"""The uniform sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).
By default, same_on_batch is set to False.
+
+ By default, sampling happens on the default device and dtype. If low/high is a tensor, sampling will happen
+ in the same device/dtype as low/high tensor.
"""
device, dtype = _extract_device_dtype([
low if isinstance(low, torch.Tensor) else None,
high if isinstance(high, torch.Tensor) else None,
])
- if not isinstance(low, torch.Tensor):
- low = torch.tensor(low, device=device, dtype=torch.float64)
- if not isinstance(high, torch.Tensor):
- high = torch.tensor(high, device=device, dtype=torch.float64)
- dist = Uniform(low.to(torch.float64), high.to(torch.float64))
- return _adapted_rsampling(shape, dist, same_on_batch).to(device=device, dtype=dtype)
+ low = torch.as_tensor(low, device=device, dtype=dtype)
+ high = torch.as_tensor(high, device=device, dtype=dtype)
+ dist = Uniform(low, high)
+ return _adapted_rsampling(shape, dist, same_on_batch)
def _adapted_beta(
shape: Union[Tuple, torch.Size],
a: Union[float, int, torch.Tensor],
b: Union[float, int, torch.Tensor],
- same_on_batch=False
+ same_on_batch: bool = False
) -> torch.Tensor:
r""" The beta sampling function that accepts 'same_on_batch'.
If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]).
By default, same_on_batch is set to False.
+
+ By default, sampling happens on the default device and dtype. If a/b is a tensor, sampling will happen
+ in the same device/dtype as a/b tensor.
"""
device, dtype = _extract_device_dtype([
a if isinstance(a, torch.Tensor) else None,
b if isinstance(b, torch.Tensor) else None,
])
- dtype = torch.float32 if dtype is None else dtype
- if not isinstance(a, torch.Tensor):
- a = torch.tensor(a, dtype=torch.float64)
- else:
- a = a.to(torch.float64)
- if not isinstance(b, torch.Tensor):
- b = torch.tensor(b, dtype=torch.float64)
- else:
- b = b.to(torch.float64)
+ a = torch.as_tensor(a, device=device, dtype=dtype)
+ b = torch.as_tensor(b, device=device, dtype=dtype)
dist = Beta(a, b)
- return _adapted_rsampling(shape, dist, same_on_batch).to(device=device, dtype=dtype)
+ return _adapted_rsampling(shape, dist, same_on_batch)
def _check_and_bound(factor: Union[torch.Tensor, float, Tuple[float, float], List[float]], name: str,
diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.py
index 08bd28281..ab1476f54 100644
--- a/kornia/geometry/transform/crop/crop2d.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -376,9 +376,9 @@ def bbox_generator(
bbox[:, :, 0] += x_start.view(-1, 1)
bbox[:, :, 1] += y_start.view(-1, 1)
- bbox[:, 1, 0] += width
- bbox[:, 2, 0] += width
- bbox[:, 2, 1] += height
- bbox[:, 3, 1] += height
+ bbox[:, 1, 0] += width - 1
+ bbox[:, 2, 0] += width - 1
+ bbox[:, 2, 1] += height - 1
+ bbox[:, 3, 1] += height - 1
return bbox
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index c1cc83921..b8edb8390 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -3,10 +3,10 @@ from typing import Tuple, Union, List, cast, Optional
import torch
-def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]):
- """This function will check if all the input tensors are in the same device.
+def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]) -> Tuple[torch.device, torch.dtype]:
+ """Check if all the input tensors are in the same device.
- If so, it would return a tuple of (device, dtype)
+ If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).
"""
device, dtype = None, None
for tensor in tensor_list:
@@ -21,4 +21,9 @@ def _extract_device_dtype(tensor_list: List[Optional[torch.Tensor]]):
elif device != _device or dtype != _dtype:
raise ValueError("Passed values are not in the same device and dtype."
f"Got ({device}, {dtype}) and ({_device}, {_dtype}).")
+ if device is None:
+ # TODO: update this when having torch.get_default_device()
+ device = torch.device('cpu')
+ if dtype is None:
+ dtype = torch.get_default_dtype()
return (device, dtype)
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index aad07235c..2432e49d4 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -448,6 +448,27 @@ class TestColorJitter:
res = f(input)
assert (res[0] == res[1]).all()
+ def _get_expected_brightness(self, device, dtype):
+ return torch.tensor([
+ [[[0.2529, 0.3529, 0.4529],
+ [0.7529, 0.6529, 0.5529],
+ [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529],
+ [0.7529, 0.6529, 0.5529],
+ [0.8529, 0.9529, 1.0000]],
+ [[0.2529, 0.3529, 0.4529],
+ [0.7529, 0.6529, 0.5529],
+ [0.8529, 0.9529, 1.0000]]],
+ [[[0.2660, 0.3660, 0.4660],
+ [0.7660, 0.6660, 0.5660],
+ [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660],
+ [0.7660, 0.6660, 0.5660],
+ [0.8660, 0.9660, 1.0000]],
+ [[0.2660, 0.3660, 0.4660],
+ [0.7660, 0.6660, 0.5660],
+ [0.8660, 0.9660, 1.0000]]]], device=device, dtype=dtype)
+
def test_random_brightness(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(brightness=0.2)
@@ -457,24 +478,7 @@ class TestColorJitter:
[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.0000, 0.0233, 0.1233],
- [0.4233, 0.3233, 0.2233],
- [0.5233, 0.6233, 0.8233]],
- [[0.0000, 0.0233, 0.1233],
- [0.4233, 0.3233, 0.2233],
- [0.5233, 0.6233, 0.8233]],
- [[0.0000, 0.0233, 0.1233],
- [0.4233, 0.3233, 0.2233],
- [0.5233, 0.6233, 0.8233]]],
- [[[0.0000, 0.0252, 0.1252],
- [0.4252, 0.3252, 0.2252],
- [0.5252, 0.6252, 0.8252]],
- [[0.0000, 0.0252, 0.1252],
- [0.4252, 0.3252, 0.2252],
- [0.5252, 0.6252, 0.8252]],
- [[0.0000, 0.0252, 0.1252],
- [0.4252, 0.3252, 0.2252],
- [0.5252, 0.6252, 0.8252]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ expected = self._get_expected_brightness(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
@@ -487,27 +491,31 @@ class TestColorJitter:
[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.0000, 0.0233, 0.1233],
- [0.4233, 0.3233, 0.2233],
- [0.5233, 0.6233, 0.8233]],
- [[0.0000, 0.0233, 0.1233],
- [0.4233, 0.3233, 0.2233],
- [0.5233, 0.6233, 0.8233]],
- [[0.0000, 0.0233, 0.1233],
- [0.4233, 0.3233, 0.2233],
- [0.5233, 0.6233, 0.8233]]],
- [[[0.0000, 0.0252, 0.1252],
- [0.4252, 0.3252, 0.2252],
- [0.5252, 0.6252, 0.8252]],
- [[0.0000, 0.0252, 0.1252],
- [0.4252, 0.3252, 0.2252],
- [0.5252, 0.6252, 0.8252]],
- [[0.0000, 0.0252, 0.1252],
- [0.4252, 0.3252, 0.2252],
- [0.5252, 0.6252, 0.8252]]]], device=device, dtype=dtype) # 1 x 1 x 3 x 3
+ expected = self._get_expected_brightness(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
+ def _get_expected_contrast(self, device, dtype):
+ return torch.tensor([
+ [[[0.0953, 0.1906, 0.2859],
+ [0.5719, 0.4766, 0.3813],
+ [0.6672, 0.7625, 0.9531]],
+ [[0.0953, 0.1906, 0.2859],
+ [0.5719, 0.4766, 0.3813],
+ [0.6672, 0.7625, 0.9531]],
+ [[0.0953, 0.1906, 0.2859],
+ [0.5719, 0.4766, 0.3813],
+ [0.6672, 0.7625, 0.9531]]],
+ [[[0.1184, 0.2367, 0.3551],
+ [0.7102, 0.5919, 0.4735],
+ [0.8286, 0.9470, 1.0000]],
+ [[0.1184, 0.2367, 0.3551],
+ [0.7102, 0.5919, 0.4735],
+ [0.8286, 0.9470, 1.0000]],
+ [[0.1184, 0.2367, 0.3551],
+ [0.7102, 0.5919, 0.4735],
+ [0.8286, 0.9470, 1.0000]]]], device=device, dtype=dtype)
+
def test_random_contrast(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(contrast=0.2)
@@ -517,24 +525,7 @@ class TestColorJitter:
[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.0849, 0.1699, 0.2548],
- [0.5097, 0.4247, 0.3398],
- [0.5946, 0.6795, 0.8494]],
- [[0.0849, 0.1699, 0.2548],
- [0.5097, 0.4247, 0.3398],
- [0.5946, 0.6795, 0.8494]],
- [[0.0849, 0.1699, 0.2548],
- [0.5097, 0.4247, 0.3398],
- [0.5946, 0.6795, 0.8494]]],
- [[[0.0821, 0.1642, 0.2463],
- [0.4926, 0.4105, 0.3284],
- [0.5747, 0.6568, 0.8210]],
- [[0.0821, 0.1642, 0.2463],
- [0.4926, 0.4105, 0.3284],
- [0.5747, 0.6568, 0.8210]],
- [[0.0821, 0.1642, 0.2463],
- [0.4926, 0.4105, 0.3284],
- [0.5747, 0.6568, 0.8210]]]], device=device, dtype=dtype)
+ expected = self._get_expected_contrast(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-5)
@@ -547,27 +538,31 @@ class TestColorJitter:
[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.0849, 0.1699, 0.2548],
- [0.5097, 0.4247, 0.3398],
- [0.5946, 0.6795, 0.8494]],
- [[0.0849, 0.1699, 0.2548],
- [0.5097, 0.4247, 0.3398],
- [0.5946, 0.6795, 0.8494]],
- [[0.0849, 0.1699, 0.2548],
- [0.5097, 0.4247, 0.3398],
- [0.5946, 0.6795, 0.8494]]],
- [[[0.0821, 0.1642, 0.2463],
- [0.4926, 0.4105, 0.3284],
- [0.5747, 0.6568, 0.8210]],
- [[0.0821, 0.1642, 0.2463],
- [0.4926, 0.4105, 0.3284],
- [0.5747, 0.6568, 0.8210]],
- [[0.0821, 0.1642, 0.2463],
- [0.4926, 0.4105, 0.3284],
- [0.5747, 0.6568, 0.8210]]]], device=device, dtype=dtype)
+ expected = self._get_expected_contrast(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-5)
+ def _get_expected_saturation(self, device, dtype):
+ return torch.tensor([
+ [[[0.1876, 0.2584, 0.3389],
+ [0.6292, 0.5000, 0.4000],
+ [0.7097, 0.8000, 1.0000]],
+ [[1.0000, 0.5292, 0.6097],
+ [0.6292, 0.3195, 0.2195],
+ [0.8000, 0.1682, 0.2779]],
+ [[0.6389, 0.8000, 0.7000],
+ [0.9000, 0.3195, 0.2195],
+ [0.8000, 0.4389, 0.5487]]],
+ [[[0.0000, 0.1295, 0.2530],
+ [0.5648, 0.5000, 0.4000],
+ [0.6883, 0.8000, 1.0000]],
+ [[1.0000, 0.4648, 0.5883],
+ [0.5648, 0.2765, 0.1765],
+ [0.8000, 0.0178, 0.1060]],
+ [[0.5556, 0.8000, 0.7000],
+ [0.9000, 0.2765, 0.1765],
+ [0.8000, 0.3530, 0.4413]]]], device=device, dtype=dtype)
+
def test_random_saturation(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(saturation=0.2)
@@ -585,24 +580,7 @@ class TestColorJitter:
[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.0000, 0.0907, 0.2272],
- [0.5454, 0.5000, 0.4000],
- [0.6818, 0.8000, 1.0000]],
- [[1.0000, 0.4454, 0.5818],
- [0.5454, 0.2636, 0.1636],
- [0.8000, 0.0000, 0.0543]],
- [[0.5556, 0.8000, 0.7000],
- [0.9000, 0.2636, 0.1636],
- [0.8000, 0.3429, 0.4090]]],
- [[[0.0000, 0.0971, 0.2314],
- [0.5485, 0.5000, 0.4000],
- [0.6828, 0.8000, 1.0000]],
- [[1.0000, 0.4485, 0.5828],
- [0.5485, 0.2657, 0.1657],
- [0.8000, 0.0000, 0.0628]],
- [[0.5556, 0.8000, 0.7000],
- [0.9000, 0.2657, 0.1657],
- [0.8000, 0.3429, 0.4142]]]], device=device, dtype=dtype)
+ expected = self._get_expected_saturation(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
def test_random_saturation_tensor(self, device, dtype):
@@ -622,24 +600,7 @@ class TestColorJitter:
[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.0000, 0.0907, 0.2272],
- [0.5454, 0.5000, 0.4000],
- [0.6818, 0.8000, 1.0000]],
- [[1.0000, 0.4454, 0.5818],
- [0.5454, 0.2636, 0.1636],
- [0.8000, 0.0000, 0.0543]],
- [[0.5556, 0.8000, 0.7000],
- [0.9000, 0.2636, 0.1636],
- [0.8000, 0.3429, 0.4090]]],
- [[[0.0000, 0.0971, 0.2314],
- [0.5485, 0.5000, 0.4000],
- [0.6828, 0.8000, 1.0000]],
- [[1.0000, 0.4485, 0.5828],
- [0.5485, 0.2657, 0.1657],
- [0.8000, 0.0000, 0.0628]],
- [[0.5556, 0.8000, 0.7000],
- [0.9000, 0.2657, 0.1657],
- [0.8000, 0.3429, 0.4142]]]], device=device, dtype=dtype)
+ expected = self._get_expected_saturation(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
@@ -660,27 +621,31 @@ class TestColorJitter:
[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.0000, 0.0907, 0.2272],
- [0.5454, 0.5000, 0.4000],
- [0.6818, 0.8000, 1.0000]],
- [[1.0000, 0.4454, 0.5818],
- [0.5454, 0.2636, 0.1636],
- [0.8000, 0.0000, 0.0543]],
- [[0.5556, 0.8000, 0.7000],
- [0.9000, 0.2636, 0.1636],
- [0.8000, 0.3429, 0.4090]]],
- [[[0.0000, 0.0971, 0.2314],
- [0.5485, 0.5000, 0.4000],
- [0.6828, 0.8000, 1.0000]],
- [[1.0000, 0.4485, 0.5828],
- [0.5485, 0.2657, 0.1657],
- [0.8000, 0.0000, 0.0628]],
- [[0.5556, 0.8000, 0.7000],
- [0.9000, 0.2657, 0.1657],
- [0.8000, 0.3429, 0.4142]]]], device=device, dtype=dtype)
+ expected = self._get_expected_saturation(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
+ def _get_expected_hue(self, device, dtype):
+ return torch.tensor([
+ [[[0.1000, 0.2000, 0.3000],
+ [0.6000, 0.5000, 0.4000],
+ [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.5251, 0.6167],
+ [0.6126, 0.3000, 0.2000],
+ [0.8000, 0.1000, 0.2000]],
+ [[0.5623, 0.8000, 0.7000],
+ [0.9000, 0.3084, 0.2084],
+ [0.7958, 0.4293, 0.5335]]],
+ [[[0.1000, 0.2000, 0.3000],
+ [0.6116, 0.5000, 0.4000],
+ [0.7000, 0.8000, 1.0000]],
+ [[1.0000, 0.4769, 0.5846],
+ [0.6000, 0.3077, 0.2077],
+ [0.7961, 0.1000, 0.2000]],
+ [[0.6347, 0.8000, 0.7000],
+ [0.9000, 0.3000, 0.2000],
+ [0.8000, 0.3730, 0.4692]]]], device=device, dtype=dtype)
+
def test_random_hue(self, device, dtype):
torch.manual_seed(42)
f = ColorJitter(hue=0.1 / pi.item())
@@ -698,25 +663,7 @@ class TestColorJitter:
[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.6030, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.4940, 0.5960],
- [0.6000, 0.3020, 0.2020],
- [0.7990, 0.1000, 0.2000]],
- [[0.6090, 0.8000, 0.7000],
- [0.9000, 0.3000, 0.2000],
- [0.8000, 0.3930, 0.4920]]],
- [[[0.1000, 0.2000, 0.3000],
- [0.6000, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.5053, 0.6035],
- [0.6027, 0.3000, 0.2000],
- [0.8000, 0.1000, 0.2000]],
- [[0.5920, 0.8000, 0.7000],
- [0.9000, 0.3018, 0.2018],
- [0.7991, 0.4062, 0.5071]]]], device=device, dtype=dtype)
- expected = expected.to(device)
+ expected = self._get_expected_hue(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
@@ -737,24 +684,7 @@ class TestColorJitter:
[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.6030, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.4940, 0.5960],
- [0.6000, 0.3020, 0.2020],
- [0.7990, 0.1000, 0.2000]],
- [[0.6090, 0.8000, 0.7000],
- [0.9000, 0.3000, 0.2000],
- [0.8000, 0.3930, 0.4920]]],
- [[[0.1000, 0.2000, 0.3000],
- [0.6000, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.5053, 0.6035],
- [0.6027, 0.3000, 0.2000],
- [0.8000, 0.1000, 0.2000]],
- [[0.5920, 0.8000, 0.7000],
- [0.9000, 0.3018, 0.2018],
- [0.7991, 0.4062, 0.5071]]]], device=device, dtype=dtype)
+ expected = self._get_expected_hue(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
@@ -775,24 +705,7 @@ class TestColorJitter:
[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.6030, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.4940, 0.5960],
- [0.6000, 0.3020, 0.2020],
- [0.7990, 0.1000, 0.2000]],
- [[0.6090, 0.8000, 0.7000],
- [0.9000, 0.3000, 0.2000],
- [0.8000, 0.3930, 0.4920]]],
- [[[0.1000, 0.2000, 0.3000],
- [0.6000, 0.5000, 0.4000],
- [0.7000, 0.8000, 1.0000]],
- [[1.0000, 0.5053, 0.6035],
- [0.6027, 0.3000, 0.2000],
- [0.8000, 0.1000, 0.2000]],
- [[0.5920, 0.8000, 0.7000],
- [0.9000, 0.3018, 0.2018],
- [0.7991, 0.4062, 0.5071]]]], device=device, dtype=dtype)
+ expected = self._get_expected_hue(device, dtype)
assert_allclose(f(input), expected, atol=1e-4, rtol=1e-4)
@@ -1126,19 +1039,19 @@ class TestRandomRotation:
[0., 1., 2., 0.],
[0., 0., 1., 2.]], device=device, dtype=dtype) # 4 x 4
- expected = torch.tensor([[[[0.0000, 0.2645, 0.4798, 0.0000],
- [0.2399, 0.0000, 0.7409, 0.3652],
- [0.1323, 0.4232, 1.3269, 1.2947],
- [0.0000, 0.0877, 0.0465, 0.2285]]]], device=device, dtype=dtype) # 1 x 4 x 4
+ expected = torch.tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
+ [0.0000, 0.0029, 0.0000, 0.0176],
+ [0.0029, 1.0000, 1.9883, 0.0000],
+ [0.0000, 0.0088, 1.0117, 1.9649]]]], device=device, dtype=dtype) # 1 x 4 x 4
- expected_transform = torch.tensor([[[0.7396, 0.6731, -0.6190],
- [-0.6731, 0.7396, 1.4002],
+ expected_transform = torch.tensor([[[1.0000, -0.0059, 0.0088],
+ [0.0059, 1.0000, -0.0088],
[0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 1 x 3 x 3
- expected_2 = torch.tensor([[[[0.2631, 0.0000, 0.6914, 0.5261],
- [0.3457, 0.0000, 0.3235, 0.0000],
- [0.0000, 0.7043, 1.6793, 1.0616],
- [0.0000, 0.1307, 0.4526, 0.8613]]]], device=device, dtype=dtype) # 1 x 4 x 4
+ expected_2 = torch.tensor([[[[0.1322, 0.0000, 0.7570, 0.2644],
+ [0.3785, 0.0000, 0.4166, 0.0000],
+ [0.0000, 0.6309, 1.5910, 1.2371],
+ [0.0000, 0.1444, 0.3177, 0.6499]]]], device=device, dtype=dtype) # 1 x 4 x 4
out, mat = f(input)
assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
@@ -1156,20 +1069,20 @@ class TestRandomRotation:
[0., 1., 2., 0.],
[0., 0., 1., 2.]]]], device=device, dtype=dtype) # 1 x 1 x 4 x 4
- expected = torch.tensor([[[[0.0000, 0.2645, 0.4798, 0.0000],
- [0.2399, 0.0000, 0.7409, 0.3652],
- [0.1323, 0.4232, 1.3269, 1.2947],
- [0.0000, 0.0877, 0.0465, 0.2285]]],
- [[[0.2631, 0.0000, 0.6914, 0.5261],
- [0.3457, 0.0000, 0.3235, 0.0000],
- [0.0000, 0.7043, 1.6793, 1.0616],
- [0.0000, 0.1307, 0.4526, 0.8613]]]], device=device, dtype=dtype) # 2 x 1 x 4 x 4
-
- expected_transform = torch.tensor([[[0.7396, 0.6731, -0.6190],
- [-0.6731, 0.7396, 1.4002],
+ expected = torch.tensor([[[[0.9824, 0.0088, 0.0000, 1.9649],
+ [0.0000, 0.0029, 0.0000, 0.0176],
+ [0.0029, 1.0000, 1.9883, 0.0000],
+ [0.0000, 0.0088, 1.0117, 1.9649]]],
+ [[[0.1322, 0.0000, 0.7570, 0.2644],
+ [0.3785, 0.0000, 0.4166, 0.0000],
+ [0.0000, 0.6309, 1.5910, 1.2371],
+ [0.0000, 0.1444, 0.3177, 0.6499]]]], device=device, dtype=dtype) # 2 x 1 x 4 x 4
+
+ expected_transform = torch.tensor([[[1.0000, -0.0059, 0.0088],
+ [0.0059, 1.0000, -0.0088],
[0.0000, 0.0000, 1.0000]],
- [[0.9472, 0.3207, -0.4018],
- [-0.3207, 0.9472, 0.5602],
+ [[0.9125, 0.4090, -0.4823],
+ [-0.4090, 0.9125, 0.7446],
[0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 2 x 3 x 3
input = input.repeat(2, 1, 1, 1) # 5 x 3 x 3 x 3
@@ -1202,17 +1115,17 @@ class TestRandomRotation:
[0., 1., 2., 0.],
[0., 0., 1., 2.]], device=device, dtype=dtype) # 4 x 4
- expected = torch.tensor([[[[1.2791, 0.1719, 0.2457, 1.3764],
- [0.1720, 0.0772, 1.8012, 0.9797],
- [0.0860, 0.0361, 0.9309, 0.1257],
- [0.6396, 0.0873, 0.0299, 0.0037]]]], device=device, dtype=dtype) # 1 x 4 x 4
+ expected = torch.tensor([[[[0.1314, 0.1050, 0.6649, 0.2628],
+ [0.3234, 0.0202, 0.4256, 0.1671],
+ [0.0525, 0.5976, 1.5199, 1.1306],
+ [0.0000, 0.1453, 0.3224, 0.5796]]]], device=device, dtype=dtype) # 1 x 4 x 4
- expected_transform = torch.tensor([[[-0.0049, 1.0000, 0.0073],
- [-1.0000, -0.0049, 3.0073],
+ expected_transform = torch.tensor([[[0.8864, 0.4629, -0.5240],
+ [-0.4629, 0.8864, 0.8647],
[0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 1 x 3 x 3
- expected_transform_2 = torch.tensor([[[0.9562, 0.2927, -0.3733],
- [-0.2927, 0.9562, 0.5046],
+ expected_transform_2 = torch.tensor([[[0.8381, -0.5455, 1.0610],
+ [0.5455, 0.8381, -0.5754],
[0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype) # 1 x 3 x 3
out, mat = f(input)
@@ -1287,7 +1200,7 @@ class TestRandomCrop:
assert_allclose(out, expected)
def test_no_padding_batch(self, device, dtype):
- torch.manual_seed(0)
+ torch.manual_seed(42)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
@@ -1311,7 +1224,7 @@ class TestRandomCrop:
assert (res[0] == res[1]).all()
def test_padding_batch_1(self, device, dtype):
- torch.manual_seed(0)
+ torch.manual_seed(42)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
@@ -1331,7 +1244,7 @@ class TestRandomCrop:
assert_allclose(out, expected)
def test_padding_batch_2(self, device, dtype):
- torch.manual_seed(0)
+ torch.manual_seed(42)
batch_size = 2
inp = torch.tensor([[
[0., 1., 2.],
@@ -1359,11 +1272,11 @@ class TestRandomCrop:
[6., 7., 8.]
]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch.tensor([[[
- [2., 8., 8.],
- [5., 8., 8.]
+ [8., 8., 8.],
+ [8., 0., 1.]
]], [[
- [4., 5., 8.],
- [7., 8., 8.]
+ [8., 8., 8.],
+ [1., 2., 8.]
]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), padding=(0, 1, 2, 3), fill=8, align_corners=True, p=1.)
out = rc(inp)
@@ -1379,8 +1292,8 @@ class TestRandomCrop:
expected = torch.tensor([
[[[9., 9., 9.],
[0., 1., 2.]]],
- [[[0., 1., 2.],
- [9., 9., 9.]]]], device=device, dtype=dtype)
+ [[[9., 9., 9.],
+ [0., 1., 2.]]]], device=device, dtype=dtype)
rc = RandomCrop(size=(2, 3), pad_if_needed=True, fill=9, align_corners=True, p=1.)
out = rc(inp)
@@ -1441,8 +1354,8 @@ class TestRandomResizedCrop:
]], device=device, dtype=dtype)
expected = torch.tensor(
- [[[[3.0937, 4.3750, 4.8750],
- [3.9375, 5.4688, 5.9062]]]], device=device, dtype=dtype)
+ [[[[5.3750, 5.8750, 4.5938],
+ [6.3437, 6.7812, 5.2500]]]], device=device, dtype=dtype)
rrc = RandomResizedCrop(
size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
@@ -1470,9 +1383,9 @@ class TestRandomResizedCrop:
]], device=device, dtype=dtype)
expected = torch.tensor(
- [[[[0.0000, 0.2500, 0.7500],
- [2.2500, 3.2500, 3.7500],
- [4.5000, 6.2500, 6.7500]]]], device=device, dtype=dtype)
+ [[[[1.2500, 1.7500, 1.5000],
+ [4.2500, 4.7500, 3.7500],
+ [7.2500, 7.7500, 6.0000]]]], device=device, dtype=dtype)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
@@ -1487,13 +1400,13 @@ class TestRandomResizedCrop:
[6., 7., 8.]
]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
- expected = torch. tensor(
- [[[[0.0000, 0.2500, 0.7500],
- [2.2500, 3.2500, 3.7500],
- [4.5000, 6.2500, 6.7500]]],
- [[[0.0000, 0.2500, 0.7500],
- [2.2500, 3.2500, 3.7500],
- [4.5000, 6.2500, 6.7500]]]], device=device, dtype=dtype)
+ expected = torch. tensor([
+ [[[1.2500, 1.7500, 1.5000],
+ [4.2500, 4.7500, 3.7500],
+ [7.2500, 7.7500, 6.0000]]],
+ [[[0.0000, 0.2500, 0.7500],
+ [2.2500, 3.2500, 3.7500],
+ [4.5000, 6.2500, 6.7500]]]], device=device, dtype=dtype)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
diff --git a/test/augmentation/test_augmentation_3d.py b/test/augmentation/test_augmentation_3d.py
index 6b7d62abe..8c720219d 100644
--- a/test/augmentation/test_augmentation_3d.py
+++ b/test/augmentation/test_augmentation_3d.py
@@ -527,9 +527,9 @@ class TestRandomRotation3D:
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
def test_smoke(self):
f = RandomRotation3D(degrees=45.5)
- repr = """RandomRotation3D(degrees=tensor([[-45.5000, 45.5000],
- [-45.5000, 45.5000],
- [-45.5000, 45.5000]]), resample=BILINEAR, align_corners=False, p=0.5, """\
+ repr = """RandomRotation3D(degrees=tensor([[-45.5000, 45.5000],
+ [-45.5000, 45.5000],
+ [-45.5000, 45.5000]]), resample=BILINEAR, align_corners=False, p=0.5, """\
"""p_batch=1.0, same_on_batch=False, return_transform=False)"""
assert str(f) == repr
@@ -553,45 +553,34 @@ class TestRandomRotation3D:
[0., 1., 2., 0.],
[0., 0., 1., 2.]]], device=device, dtype=dtype) # 3 x 4 x 4
- expected = torch.tensor([[[[[0.2771, 0.0000, 0.0036, 0.0000],
- [0.5751, 0.0183, 0.7505, 0.4702],
- [0.0262, 0.2591, 0.5776, 0.4764],
- [0.0000, 0.0093, 0.0000, 0.0393]],
- [[0.0000, 0.0000, 0.0583, 0.0222],
- [0.1665, 0.0000, 1.0424, 1.0224],
- [0.1296, 0.4846, 1.4200, 1.2287],
- [0.0078, 0.3851, 0.3965, 0.3612]],
- [[0.0000, 0.7704, 0.6704, 0.0000],
- [0.0000, 0.0332, 0.2414, 0.0524],
- [0.0000, 0.3349, 1.4545, 1.3689],
- [0.0000, 0.0312, 0.5874, 0.8702]]]]], device=device, dtype=dtype)
-
- expected_transform = torch.tensor([[[0.5784, 0.7149, -0.3929, -0.0471],
- [-0.3657, 0.6577, 0.6585, 0.4035],
- [0.7292, -0.2372, 0.6419, -0.3799],
+ expected = torch.tensor([[[[[0.0000, 0.0000, 0.6810, 0.5250],
+ [0.5052, 0.0000, 0.0000, 0.0613],
+ [0.1159, 0.1072, 0.5324, 0.0870],
+ [0.0000, 0.0000, 0.1927, 0.0000]],
+ [[0.0000, 0.1683, 0.6963, 0.1131],
+ [0.0566, 0.0000, 0.5215, 0.2796],
+ [0.0694, 0.6039, 1.4519, 1.1240],
+ [0.0000, 0.1325, 0.1542, 0.2510]],
+ [[0.0000, 0.2054, 0.0000, 0.0000],
+ [0.0026, 0.6088, 0.7358, 0.2319],
+ [0.1261, 1.0830, 1.3687, 1.4940],
+ [0.0000, 0.0416, 0.2012, 0.3124]]]]], device=device, dtype=dtype)
+
+ expected_transform = torch.tensor([[[0.6523, 0.3666, -0.6635, 0.6352],
+ [-0.6185, 0.7634, -0.1862, 1.4689],
+ [0.4382, 0.5318, 0.7247, -1.1797],
[0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
- expected_2 = torch.tensor([[[[[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]],
- [[1., 0., 0., 2.],
- [0., 0., 0., 0.],
- [0., 1., 2., 0.],
- [0., 0., 1., 2.]]]]], device=device, dtype=dtype)
-
out, mat = f(input)
assert_allclose(out, expected, rtol=1e-6, atol=1e-4)
assert_allclose(mat, expected_transform, rtol=1e-6, atol=1e-4)
- assert_allclose(f1(input), expected_2, rtol=1e-6, atol=1e-4)
+
+ torch.manual_seed(0) # for random reproductibility
+ assert_allclose(f1(input), expected, rtol=1e-6, atol=1e-4)
def test_batch_random_rotation(self, device, dtype):
- torch.manual_seed(0) # for random reproductibility
+ torch.manual_seed(24) # for random reproductibility
f = RandomRotation3D(degrees=45.0, return_transform=True)
@@ -608,19 +597,7 @@ class TestRandomRotation3D:
[0., 1., 2., 0.],
[0., 0., 1., 2.]]]], device=device, dtype=dtype) # 1 x 1 x 4 x 4
- expected = torch.tensor([[[[[0.0000, 0.5106, 0.1146, 0.0000],
- [0.0000, 0.1261, 0.0000, 0.4723],
- [0.1714, 0.9931, 0.5442, 0.4684],
- [0.0193, 0.5802, 0.4195, 0.0000]],
- [[0.0000, 0.2386, 0.0000, 0.0000],
- [0.0187, 0.3527, 0.0000, 0.6119],
- [0.1294, 1.2251, 0.9130, 0.0942],
- [0.0962, 1.0769, 0.8448, 0.0000]],
- [[0.0000, 0.0202, 0.0000, 0.0000],
- [0.1092, 0.5845, 0.1038, 0.4598],
- [0.0000, 1.1218, 1.0796, 0.0000],
- [0.0780, 0.9513, 1.1278, 0.0000]]]],
- [[[[1.0000, 0.0000, 0.0000, 2.0000],
+ expected = torch.tensor([[[[[1.0000, 0.0000, 0.0000, 2.0000],
[0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 1.0000, 2.0000, 0.0000],
[0.0000, 0.0000, 1.0000, 2.0000]],
@@ -631,15 +608,27 @@ class TestRandomRotation3D:
[[1.0000, 0.0000, 0.0000, 2.0000],
[0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 1.0000, 2.0000, 0.0000],
- [0.0000, 0.0000, 1.0000, 2.0000]]]]], device=device, dtype=dtype)
-
- expected_transform = torch.tensor([[[0.7894, -0.6122, 0.0449, 1.1892],
- [0.5923, 0.7405, -0.3176, -0.1816],
- [0.1612, 0.2773, 0.9472, -0.6049],
- [0.0000, 0.0000, 0.0000, 1.0000]],
- [[1.0000, 0.0000, 0.0000, 0.0000],
+ [0.0000, 0.0000, 1.0000, 2.0000]]]],
+ [[[[0.0000, 0.0726, 0.0000, 0.0000],
+ [0.1038, 1.0134, 0.5566, 0.1519],
+ [0.0000, 1.0849, 1.1068, 0.0000],
+ [0.1242, 1.1065, 0.9681, 0.0000]],
+ [[0.0000, 0.0047, 0.0166, 0.0000],
+ [0.0579, 0.4459, 0.0000, 0.4728],
+ [0.1864, 1.3349, 0.7530, 0.3251],
+ [0.1431, 1.2481, 0.4471, 0.0000]],
+ [[0.0000, 0.4840, 0.2314, 0.0000],
+ [0.0000, 0.0328, 0.0000, 0.1434],
+ [0.1899, 0.5580, 0.0000, 0.9170],
+ [0.0000, 0.2042, 0.1571, 0.0855]]]]], device=device, dtype=dtype)
+
+ expected_transform = torch.tensor([[[1.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 1.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 1.0000, 0.0000],
+ [0.0000, 0.0000, 0.0000, 1.0000]],
+ [[0.7522, -0.6326, -0.1841, 1.5047],
+ [0.6029, 0.5482, 0.5796, -0.8063],
+ [-0.2657, -0.5470, 0.7938, 1.4252],
[0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
input = input.repeat(2, 1, 1, 1, 1) # 5 x 4 x 4 x 3
@@ -656,7 +645,7 @@ class TestRandomRotation3D:
def test_sequential(self, device, dtype):
- torch.manual_seed(0) # for random reproductibility
+ torch.manual_seed(24) # for random reproductibility
f = nn.Sequential(
RandomRotation3D(torch.tensor([-45.0, 90]), return_transform=True),
@@ -680,27 +669,27 @@ class TestRandomRotation3D:
[0., 1., 2., 0.],
[0., 0., 1., 2.]]], device=device, dtype=dtype) # 3 x 4 x 4
- expected = torch.tensor([[[[[0.2752, 0.0000, 0.0000, 0.0000],
- [0.5767, 0.0059, 0.6440, 0.4307],
- [0.0000, 0.2793, 0.6638, 0.5716],
- [0.0000, 0.0049, 0.0000, 0.0685]],
- [[0.0000, 0.0000, 0.1806, 0.0000],
- [0.2138, 0.0000, 0.9061, 0.7966],
- [0.0657, 0.5395, 1.4299, 1.2912],
- [0.0000, 0.3600, 0.3088, 0.3655]],
- [[0.0000, 0.6515, 0.8861, 0.0000],
- [0.0000, 0.0000, 0.2278, 0.0000],
- [0.0027, 0.4403, 1.5462, 1.3480],
- [0.0000, 0.1182, 0.6297, 0.8623]]]]], device=device, dtype=dtype)
-
- expected_transform = torch.tensor([[[0.6306, 0.6496, -0.4247, 0.0044],
- [-0.3843, 0.7367, 0.5563, 0.4151],
- [0.6743, -0.1876, 0.7142, -0.4443],
+ expected = torch.tensor([[[[[0.3431, 0.1239, 0.0000, 1.0348],
+ [0.0000, 0.2035, 0.1139, 0.1770],
+ [0.0789, 0.9057, 1.7780, 0.0000],
+ [0.0000, 0.2286, 1.2498, 1.2643]],
+ [[0.5460, 0.2131, 0.0000, 1.1453],
+ [0.0000, 0.0899, 0.0000, 0.4293],
+ [0.0797, 1.0193, 1.6677, 0.0000],
+ [0.0000, 0.2458, 1.2765, 1.0920]],
+ [[0.6322, 0.2614, 0.0000, 0.9207],
+ [0.0000, 0.0037, 0.0000, 0.6551],
+ [0.0689, 0.9251, 1.3442, 0.0000],
+ [0.0000, 0.2449, 0.9856, 0.6862]]]]], device=device, dtype=dtype)
+
+ expected_transform = torch.tensor([[[0.9857, -0.1686, -0.0019, 0.2762],
+ [0.1668, 0.9739, 0.1538, -0.3650],
+ [-0.0241, -0.1520, 0.9881, 0.2760],
[0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
- expected_transform_2 = torch.tensor([[[0.9611, 0.0495, -0.2717, 0.2557],
- [0.1255, 0.7980, 0.5894, -0.4747],
- [0.2460, -0.6006, 0.7608, 0.7710],
+ expected_transform_2 = torch.tensor([[[0.2348, -0.1615, 0.9585, 0.4316],
+ [0.1719, 0.9775, 0.1226, -0.3467],
+ [-0.9567, 0.1360, 0.2573, 1.9738],
[0.0000, 0.0000, 0.0000, 1.0000]]], device=device, dtype=dtype)
out, mat = f(input)
@@ -775,7 +764,7 @@ class TestRandomCrop3D:
@pytest.mark.parametrize("batch_size", [1, 2])
def test_no_padding(self, batch_size, device, dtype):
- torch.manual_seed(0)
+ torch.manual_seed(42)
inp = torch.tensor([[[[
[0., 1., 2., 3., 4.],
[5., 6., 7., 8., 9.],
@@ -816,7 +805,7 @@ class TestRandomCrop3D:
@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)
+ torch.manual_seed(42)
batch_size = 2
inp = torch.tensor([[[
[0., 1., 2.],
@@ -834,8 +823,8 @@ class TestRandomCrop3D:
[[3., 4., 5., 10.],
[6., 7., 8., 10.],
[10, 10, 10, 10.]],
- [[10, 10, 10, 10.],
- [10, 10, 10, 10.],
+ [[3., 4., 5., 10.],
+ [6., 7., 8., 10.],
[10, 10, 10, 10.]],
]]], device=device, dtype=dtype)
f = RandomCrop3D(size=(2, 3, 4), fill=10., padding=padding, align_corners=True, p=1.)
@@ -844,7 +833,7 @@ class TestRandomCrop3D:
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
def test_pad_if_needed(self, device, dtype):
- torch.manual_seed(0)
+ torch.manual_seed(42)
inp = torch.tensor([[
[0., 1., 2.],
]], device=device, dtype=dtype)
diff --git a/test/augmentation/test_augmentation_mix.py b/test/augmentation/test_augmentation_mix.py
index 91431f037..ff0c09b31 100644
--- a/test/augmentation/test_augmentation_mix.py
+++ b/test/augmentation/test_augmentation_mix.py
@@ -28,7 +28,7 @@ class TestRandomMixUp:
torch.zeros(1, 3, 4, device=device, dtype=dtype)
])
label = torch.tensor([1, 0], device=device)
- lam = torch.tensor([0.0562, 0.0726], device=device, dtype=dtype)
+ lam = torch.tensor([0.1320, 0.3074], device=device, dtype=dtype)
expected = torch.stack([
torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),
@@ -89,7 +89,7 @@ class TestRandomMixUp:
torch.zeros(1, 3, 4, device=device, dtype=dtype)
])
label = torch.tensor([1, 0], device=device)
- lam = torch.tensor([0.7078, 0.7078], device=device, dtype=dtype)
+ lam = torch.tensor([0.0885, 0.0885], device=device, dtype=dtype)
expected = torch.stack([
torch.ones(1, 3, 4, device=device, dtype=dtype) * (1 - lam[0]),
@@ -163,11 +163,11 @@ class TestRandomCutMix:
])
label = torch.tensor([1, 0], device=device)
- expected = torch.tensor([[[[1., 0., 0., 1.],
- [1., 0., 0., 1.],
+ expected = torch.tensor([[[[0., 0., 1., 1.],
+ [0., 0., 1., 1.],
[1., 1., 1., 1.]]],
- [[[0., 1., 1., 0.],
- [0., 1., 1., 0.],
+ [[[1., 1., 0., 0.],
+ [1., 1., 0., 0.],
[0., 0., 0., 0.]]]], device=device, dtype=dtype)
out_image, out_label = f(input, label)
@@ -206,7 +206,7 @@ class TestRandomCutMix:
device=device, dtype=dtype), rtol=1e-4, atol=1e-4)
def test_random_mixup_same_on_batch(self, device, dtype):
- torch.manual_seed(0)
+ torch.manual_seed(42)
f = RandomCutMix(same_on_batch=True, width=4, height=3, p=1.)
input = torch.stack([
@@ -216,11 +216,11 @@ class TestRandomCutMix:
label = torch.tensor([1, 0], device=device)
lam = torch.tensor([0.0885, 0.0885], device=device, dtype=dtype)
- expected = torch.tensor([[[[0., 0., 1., 1.],
- [1., 1., 1., 1.],
+ expected = torch.tensor([[[[0., 0., 0., 1.],
+ [0., 0., 0., 1.],
[1., 1., 1., 1.]]],
- [[[1., 1., 0., 0.],
- [0., 0., 0., 0.],
+ [[[1., 1., 1., 0.],
+ [1., 1., 1., 0.],
[0., 0., 0., 0.]]]], device=device, dtype=dtype)
out_image, out_label = f(input, label)
@@ -229,4 +229,4 @@ class TestRandomCutMix:
assert (out_label[0, :, 0] == label).all()
assert (out_label[0, :, 1] == torch.tensor([0, 1], device=device, dtype=dtype)).all()
assert_allclose(out_label[0, :, 2],
- torch.tensor([0.1667, 0.1667], device=device, dtype=dtype), rtol=1e-4, atol=1e-4)
+ torch.tensor([0.5000, 0.5000], device=device, dtype=dtype), rtol=1e-4, atol=1e-4)
diff --git a/test/augmentation/test_perspective.py b/test/augmentation/test_perspective.py
index 5fa54f17e..978fd7a16 100644
--- a/test/augmentation/test_perspective.py
+++ b/test/augmentation/test_perspective.py
@@ -102,19 +102,19 @@ class TestRandomPerspective:
torch.manual_seed(0)
x_data = torch.rand(1, 2, 4, 5).to(device)
- expected_output = torch.tensor([[[[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.2770, 0.6475, 0.0335, 0.0000],
- [0.0000, 0.4842, 0.5532, 0.0445, 0.0000],
+ expected_output = torch.tensor([[[[0.0000, 0.0000, 0.0000, 0.0197, 0.0429],
+ [0.0000, 0.5632, 0.5322, 0.3677, 0.1430],
+ [0.0000, 0.3083, 0.4032, 0.1761, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000]],
- [[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
- [0.0000, 0.2417, 0.1325, 0.0193, 0.0000],
- [0.0000, 0.0296, 0.6933, 0.1170, 0.0000],
+ [[0.0000, 0.0000, 0.0000, 0.1189, 0.0586],
+ [0.0000, 0.7087, 0.5420, 0.3995, 0.0863],
+ [0.0000, 0.2695, 0.5981, 0.5888, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]],
device=device, dtype=x_data.dtype)
- expected_transform = torch.tensor([[[0.5445, -0.2336, 1.1866],
- [0.0364, 0.4761, 0.2652],
- [0.0475, -0.0936, 1.0000]]],
+ expected_transform = torch.tensor([[[1.0523, 0.3493, 0.3046],
+ [-0.1066, 1.0426, 0.5846],
+ [0.0351, 0.1213, 1.0000]]],
device=device, dtype=x_data.dtype)
out_perspective = kornia.augmentation.RandomPerspective(p=.99999999, # step one the random state
diff --git a/test/augmentation/test_random_generator.py b/test/augmentation/test_random_generator.py
index 97bb1ae91..247cc8a07 100644
--- a/test/augmentation/test_random_generator.py
+++ b/test/augmentation/test_random_generator.py
@@ -40,18 +40,19 @@ class RandomGeneratorBaseTests():
class TestRandomProbGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('p', [0., 0.5, 1.])
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, p, batch_size, same_on_batch, device, dtype):
random_prob_generator(batch_size=batch_size, p=p, same_on_batch=same_on_batch)
@pytest.mark.parametrize('p', [
# Should be failed if p > 1. or p < 0.
- pytest.param(-1., marks=pytest.mark.xfail),
- pytest.param(2., marks=pytest.mark.xfail)
+ (-1.),
+ (2.)
])
def test_invalid_param_combinations(self, p, device, dtype):
- random_prob_generator(batch_size=8, p=p)
+ with pytest.raises(Exception):
+ random_prob_generator(batch_size=8, p=p)
@pytest.mark.parametrize('p,expected', [
(0., [False] * 8),
@@ -81,7 +82,7 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('contrast', [None, torch.tensor([0.8, 1.2])])
@pytest.mark.parametrize('saturation', [None, torch.tensor([0.8, 1.2])])
@pytest.mark.parametrize('hue', [None, torch.tensor([-0.1, 0.1])])
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
self, brightness, contrast, saturation, hue, batch_size, same_on_batch, device, dtype
@@ -97,38 +98,39 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('brightness,contrast,saturation,hue', [
# Should be failed if value out of bounds or tensor.shape != [1, 2]
- pytest.param(torch.tensor([-1., 2.]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0., 3.]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(torch.tensor(0.), None, None, None, marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0.]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0., 1., 2.]), None, None, None, marks=pytest.mark.xfail),
-
- pytest.param(None, torch.tensor([-1., 2.]), None, None, marks=pytest.mark.xfail),
- pytest.param(None, torch.tensor(0.), None, None, marks=pytest.mark.xfail),
- pytest.param(None, torch.tensor([0.]), None, None, marks=pytest.mark.xfail),
- pytest.param(None, torch.tensor([0., 1., 2.]), None, None, marks=pytest.mark.xfail),
-
- pytest.param(None, None, torch.tensor([-1., 2.]), None, marks=pytest.mark.xfail),
- pytest.param(None, None, torch.tensor(0.), None, marks=pytest.mark.xfail),
- pytest.param(None, None, torch.tensor([0.]), None, marks=pytest.mark.xfail),
- pytest.param(None, None, torch.tensor([0., 1., 2.]), None, marks=pytest.mark.xfail),
-
- pytest.param(None, None, None, torch.tensor([-1., 0.]), marks=pytest.mark.xfail),
- pytest.param(None, None, None, torch.tensor([0, 1.]), marks=pytest.mark.xfail),
- pytest.param(None, None, None, torch.tensor(0.), marks=pytest.mark.xfail),
- pytest.param(None, None, None, torch.tensor([0.]), marks=pytest.mark.xfail),
- pytest.param(None, None, None, torch.tensor([0., 1., 2.]), marks=pytest.mark.xfail),
+ (torch.tensor([-1., 2.]), None, None, None),
+ (torch.tensor([0., 3.]), None, None, None),
+ (torch.tensor(0.), None, None, None),
+ (torch.tensor([0.]), None, None, None),
+ (torch.tensor([0., 1., 2.]), None, None, None),
+
+ (None, torch.tensor([-1., 2.]), None, None),
+ (None, torch.tensor(0.), None, None),
+ (None, torch.tensor([0.]), None, None),
+ (None, torch.tensor([0., 1., 2.]), None, None),
+
+ (None, None, torch.tensor([-1., 2.]), None),
+ (None, None, torch.tensor(0.), None),
+ (None, None, torch.tensor([0.]), None),
+ (None, None, torch.tensor([0., 1., 2.]), None),
+
+ (None, None, None, torch.tensor([-1., 0.])),
+ (None, None, None, torch.tensor([0, 1.])),
+ (None, None, None, torch.tensor(0.)),
+ (None, None, None, torch.tensor([0.])),
+ (None, None, None, torch.tensor([0., 1., 2.])),
])
def test_invalid_param_combinations(
self, brightness, contrast, saturation, hue, device, dtype
):
- random_color_jitter_generator(
- 8,
- brightness.to(device=device, dtype=dtype) if brightness is not None else None,
- contrast.to(device=device, dtype=dtype) if contrast is not None else None,
- saturation.to(device=device, dtype=dtype) if saturation is not None else None,
- hue.to(device=device, dtype=dtype) if hue is not None else None
- )
+ with pytest.raises(Exception):
+ random_color_jitter_generator(
+ 8,
+ brightness.to(device=device, dtype=dtype) if brightness is not None else None,
+ contrast.to(device=device, dtype=dtype) if contrast is not None else None,
+ saturation.to(device=device, dtype=dtype) if saturation is not None else None,
+ hue.to(device=device, dtype=dtype) if hue is not None else None
+ )
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -141,14 +143,14 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
expected_jitter_params = {
'brightness_factor': torch.tensor(
- [0.8233, 0.8252, 0.8494, 0.8210, 1.0105, 0.9907, 1.1821, 1.1715], device=device, dtype=dtype),
+ [1.1529, 1.1660, 0.9531, 1.1837, 0.9562, 1.0404, 0.9026, 1.1175], device=device, dtype=dtype),
'contrast_factor': torch.tensor(
- [0.7501, 0.7796, 0.7942, 0.9252, 1.2055, 1.2223, 0.9265, 1.0675], device=device, dtype=dtype),
+ [1.2645, 0.7799, 1.2608, 1.0561, 1.2216, 1.0406, 1.1447, 0.9576], device=device, dtype=dtype),
'hue_factor': torch.tensor(
- [-0.0824, 0.0402, 0.0247, -0.0125, -0.0851, 0.0367, -0.0376, -0.0382], device=device, dtype=dtype),
+ [0.0771, 0.0148, -0.0467, 0.0255, -0.0461, -0.0117, -0.0406, 0.0663], device=device, dtype=dtype),
'saturation_factor': torch.tensor(
- [0.6251, 0.6323, 1.3455, 0.7217, 0.8120, 0.7043, 0.8015, 0.7867], device=device, dtype=dtype),
- 'order': torch.tensor([2, 3, 1, 0], device=device, dtype=dtype)
+ [0.6843, 0.8156, 0.8871, 0.7595, 1.0378, 0.6049, 1.3612, 0.6602], device=device, dtype=dtype),
+ 'order': torch.tensor([3, 2, 0, 1], device=device, dtype=dtype)
}
assert set(list(jitter_params.keys())) == set([
@@ -177,10 +179,10 @@ class TestColorJitterGen(RandomGeneratorBaseTests):
hue=torch.tensor([-0.1, 0.1], device=device, dtype=dtype), same_on_batch=True)
expected_res = {
- 'brightness_factor': torch.tensor([0.8233] * batch_size, device=device, dtype=dtype),
- 'contrast_factor': torch.tensor([0.7377] * batch_size, device=device, dtype=dtype),
- 'hue_factor': torch.tensor([-0.0753] * batch_size, device=device, dtype=dtype),
- 'saturation_factor': torch.tensor([0.6421] * batch_size, device=device, dtype=dtype),
+ 'brightness_factor': torch.tensor([1.1529] * batch_size, device=device, dtype=dtype),
+ 'contrast_factor': torch.tensor([1.2490] * batch_size, device=device, dtype=dtype),
+ 'hue_factor': torch.tensor([-0.0234] * batch_size, device=device, dtype=dtype),
+ 'saturation_factor': torch.tensor([1.3674] * batch_size, device=device, dtype=dtype),
'order': torch.tensor([2, 3, 0, 1], device=device, dtype=dtype)
}
@@ -200,7 +202,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('height,width', [(200, 200)])
@pytest.mark.parametrize('distortion_scale', [torch.tensor(0.), torch.tensor(0.5), torch.tensor(1.)])
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(
self, height, width, distortion_scale, batch_size, same_on_batch, device, dtype
@@ -211,16 +213,17 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
@pytest.mark.parametrize('height,width,distortion_scale', [
# Should be failed if distortion_scale > 1. or distortion_scale < 0.
- pytest.param(-100, 100, torch.tensor(0.5), marks=pytest.mark.xfail),
- pytest.param(100, -100, torch.tensor(0.5), marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor(-0.5), marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor(1.5), marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([0., 0.5]), marks=pytest.mark.xfail),
+ (-100, 100, torch.tensor(0.5)),
+ (100, -100, torch.tensor(0.5)),
+ (100, 100, torch.tensor(-0.5)),
+ (100, 100, torch.tensor(1.5)),
+ (100, 100, torch.tensor([0., 0.5])),
])
def test_invalid_param_combinations(self, height, width, distortion_scale, device, dtype):
- random_perspective_generator(
- batch_size=8, height=height, width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_perspective_generator(
+ batch_size=8, height=height, width=width,
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -237,14 +240,14 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
[199., 199.],
[0., 199.]]], device=device, dtype=dtype),
end_points=torch.tensor([
- [[2.9077, 3.1455],
- [192.8207, 2.6290],
- [172.6914, 175.1608],
- [47.7618, 152.5624]],
- [[4.1772, 6.6320],
- [191.1473, 18.7684],
- [156.8740, 155.4749],
- [18.8766, 168.3782]]], device=device, dtype=dtype),
+ [[44.1135, 45.7502],
+ [179.8568, 47.9653],
+ [179.4776, 168.9552],
+ [12.8286, 159.3179]],
+ [[47.0386, 6.6593],
+ [152.2701, 29.6790],
+ [155.5298, 170.6142],
+ [37.0547, 177.5298]]], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'])
@@ -262,10 +265,10 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
[199., 199.],
[0., 199.]]], device=device, dtype=dtype).repeat(2, 1, 1),
end_points=torch.tensor([
- [[2.9077, 3.1455],
- [192.8207, 2.6290],
- [172.6914, 175.1608],
- [47.7618, 152.5624]]], device=device, dtype=dtype).repeat(2, 1, 1),
+ [[44.1135, 45.7502],
+ [179.8568, 47.9653],
+ [179.4776, 168.9552],
+ [12.8286, 159.3179]]], device=device, dtype=dtype).repeat(2, 1, 1),
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'])
@@ -274,7 +277,7 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):
class TestRandomAffineGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 4])
+ @pytest.mark.parametrize('batch_size', [0, 1, 4])
@pytest.mark.parametrize('height', [200])
@pytest.mark.parametrize('width', [300])
@pytest.mark.parametrize('degrees', [torch.tensor([0, 30])])
@@ -293,49 +296,46 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('height,width,degrees,translate,scale,shear', [
- pytest.param(-100, 100, torch.tensor([10, 20]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, -100, torch.tensor([10, 20]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 0.5, None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([10, 20, 30]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([10, 20]), torch.tensor([0.1]), None, None, marks=pytest.mark.xfail),
- pytest.param(10, 10, torch.tensor([1, 2]), torch.tensor([0.1, 0.2, 0.3]), None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([10, 20]), None, torch.tensor([1]), None, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([10, 20]), None, torch.tensor([1, 2, 3]), None, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1]), marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1, 2]), marks=pytest.mark.xfail),
- pytest.param(10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3]), marks=pytest.mark.xfail),
- pytest.param(10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4]), marks=pytest.mark.xfail),
- pytest.param(10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4, 5]), marks=pytest.mark.xfail),
+ (-100, 100, torch.tensor([10, 20]), None, None, None),
+ (100, -100, torch.tensor([10, 20]), None, None, None),
+ (100, 100, 0.5, None, None, None),
+ (100, 100, torch.tensor([10, 20, 30]), None, None, None),
+ (100, 100, torch.tensor([10, 20]), torch.tensor([0.1]), None, None),
+ (10, 10, torch.tensor([1, 2]), torch.tensor([0.1, 0.2, 0.3]), None, None),
+ (100, 100, torch.tensor([10, 20]), None, torch.tensor([1]), None),
+ (100, 100, torch.tensor([10, 20]), None, torch.tensor([1, 2, 3]), None),
+ (100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1])),
+ (100, 100, torch.tensor([10, 20]), None, None, torch.tensor([1, 2])),
+ (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3])),
+ (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4])),
+ (10, 10, torch.tensor([1, 2]), None, None, torch.tensor([1, 2, 3, 4, 5])),
])
def test_invalid_param_combinations(
- self, batch_size, height, width, degrees, translate, scale, shear, device, dtype
+ self, height, width, degrees, translate, scale, shear, device, dtype
):
- batch_size = 8
- random_affine_generator(
- batch_size=batch_size, 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,
- shear=shear.to(device=device, dtype=dtype) if shear is not None else None)
+ with pytest.raises(Exception):
+ random_affine_generator(
+ batch_size=8, 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,
+ shear=shear.to(device=device, dtype=dtype) if shear is not None else None)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
- degrees = torch.tensor([10, 20])
- translate = torch.tensor([0.1, 0.1])
- scale = torch.tensor([0.7, 1.2])
- shear = torch.tensor([[10, 20], [10, 20]])
+ degrees = torch.tensor([10, 20], device=device, dtype=dtype)
+ translate = torch.tensor([0.1, 0.1], device=device, dtype=dtype)
+ scale = torch.tensor([0.7, 1.2], device=device, dtype=dtype)
+ shear = torch.tensor([[10, 20], [10, 20]], device=device, dtype=dtype)
res = random_affine_generator(
- batch_size=2, 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,
- shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=False)
+ batch_size=2, height=200, width=200, degrees=degrees,
+ translate=translate, scale=scale, shear=shear, same_on_batch=False)
expected = dict(
- translations=torch.tensor([[1.0469, 18.2094], [-0.9286, 17.1501]], device=device, dtype=dtype),
+ translations=torch.tensor([[-4.3821, -9.7371], [4.0358, 11.7457]], device=device, dtype=dtype),
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
- scale=torch.tensor([[0.7618, 0.7618], [0.7263, 0.7263]], device=device, dtype=dtype),
- angle=torch.tensor([10.5815, 10.6291], device=device, dtype=dtype),
- sx=torch.tensor([10.8354, 11.3264], device=device, dtype=dtype),
- sy=torch.tensor([11.5705, 13.7537], device=device, dtype=dtype)
+ scale=torch.tensor([[0.8914, 0.8914], [1.1797, 1.1797]], device=device, dtype=dtype),
+ angle=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype),
+ sx=torch.tensor([19.4077, 11.3319], device=device, dtype=dtype),
+ sy=torch.tensor([19.3460, 15.9358], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
@@ -347,23 +347,20 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
def test_same_on_batch(self, device, dtype):
torch.manual_seed(42)
- degrees = torch.tensor([10, 20])
- translate = torch.tensor([0.1, 0.1])
- scale = torch.tensor([0.7, 1.2])
- shear = torch.tensor([[10, 20], [10, 20]])
+ degrees = torch.tensor([10, 20], device=device, dtype=dtype)
+ translate = torch.tensor([0.1, 0.1], device=device, dtype=dtype)
+ scale = torch.tensor([0.7, 1.2], device=device, dtype=dtype)
+ shear = torch.tensor([[10, 20], [10, 20]], device=device, dtype=dtype)
res = random_affine_generator(
- batch_size=2, 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,
- shear=shear.to(device=device, dtype=dtype) if shear is not None else None,
- same_on_batch=True)
+ batch_size=2, height=200, width=200, degrees=degrees,
+ translate=translate, scale=scale, shear=shear, same_on_batch=True)
expected = dict(
- translations=torch.tensor([[-15.0566, -17.8968], [-15.0566, -17.8968]], device=device, dtype=dtype),
+ translations=torch.tensor([[-4.6854, 18.3722], [-4.6854, 18.3722]], device=device, dtype=dtype),
center=torch.tensor([[99.5000, 99.5000], [99.5000, 99.5000]], device=device, dtype=dtype),
- scale=torch.tensor([[0.7315, 0.7315], [0.7315, 0.7315]], device=device, dtype=dtype),
- angle=torch.tensor([10.5815, 10.5815], device=device, dtype=dtype),
- sx=torch.tensor([15.2617, 15.2617], device=device, dtype=dtype),
- sy=torch.tensor([14.7678, 14.7678], device=device, dtype=dtype)
+ scale=torch.tensor([[1.1575, 1.1575], [1.1575, 1.1575]], device=device, dtype=dtype),
+ angle=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype),
+ sx=torch.tensor([13.9045, 13.9045], device=device, dtype=dtype),
+ sy=torch.tensor([16.0090, 16.0090], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
@@ -376,7 +373,7 @@ class TestRandomAffineGen(RandomGeneratorBaseTests):
class TestRandomRotationGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('degrees', [torch.tensor([0, 30])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, degrees, same_on_batch, device, dtype):
@@ -384,14 +381,15 @@ class TestRandomRotationGen(RandomGeneratorBaseTests):
batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
@pytest.mark.parametrize('degrees', [
- pytest.param(torch.tensor(10), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([10]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([10, 20, 30]), marks=pytest.mark.xfail)
+ (torch.tensor(10)),
+ (torch.tensor([10])),
+ (torch.tensor([10, 20, 30]))
])
def test_invalid_param_combinations(self, degrees, device, dtype):
batch_size = 8
- random_rotation_generator(
- batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_rotation_generator(
+ batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -399,7 +397,7 @@ class TestRandomRotationGen(RandomGeneratorBaseTests):
res = random_rotation_generator(
batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False)
expected = dict(
- degrees=torch.tensor([10.5815, 10.6291], device=device, dtype=dtype)
+ degrees=torch.tensor([18.8227, 19.1500], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['degrees'], expected['degrees'])
@@ -410,7 +408,7 @@ class TestRandomRotationGen(RandomGeneratorBaseTests):
res = random_rotation_generator(
batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True)
expected = dict(
- degrees=torch.tensor([10.5815, 10.5815], device=device, dtype=dtype)
+ degrees=torch.tensor([18.8227, 18.8227], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['degrees'], expected['degrees'])
@@ -418,32 +416,35 @@ class TestRandomRotationGen(RandomGeneratorBaseTests):
class TestRandomCropGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [2])
+ @pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('input_size', [(200, 200)])
- @pytest.mark.parametrize('size', [(100, 100), torch.tensor([[50, 50], [60, 60]])])
+ @pytest.mark.parametrize('size', [(100, 100), torch.tensor([50, 50])])
@pytest.mark.parametrize('resize_to', [None, (100, 100)])
@pytest.mark.parametrize('same_on_batch', [True, False])
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_generator(
batch_size=batch_size, input_size=input_size,
- size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
+ size=size,
resize_to=resize_to,
same_on_batch=same_on_batch)
@pytest.mark.parametrize('input_size,size,resize_to', [
- pytest.param((-300, 300), (200, 200), (100, 100), marks=pytest.mark.xfail),
- pytest.param((100, 100), (200, 200), (100, 100), marks=pytest.mark.xfail),
- pytest.param((200, 200), torch.tensor([50, 50]), (100, 100), marks=pytest.mark.xfail),
- pytest.param((100, 100), torch.tensor([[200, 200], [200, 200]]), (100, 100), marks=pytest.mark.xfail),
+ ((-300, 300), (200, 200), (100, 100)),
+ ((100, 100), (200, 200), (100, 100)),
+ ((200, 200), torch.tensor([50, 50]), (100, 100)),
+ ((100, 100), torch.tensor([[200, 200], [200, 200]]), (100, 100)),
])
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
batch_size = 2
- random_crop_generator(
- 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)
+ with pytest.raises(Exception):
+ random_crop_generator(
+ 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)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -454,14 +455,14 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
resize_to=(200, 200))
expected = dict(
src=torch.tensor([
- [[2, 6],
- [61, 6],
- [61, 55],
- [2, 55]],
- [[1, 1],
- [80, 1],
- [80, 70],
- [1, 70]]], device=device, dtype=torch.long),
+ [[36, 19],
+ [95, 19],
+ [95, 68],
+ [36, 68]],
+ [[19, 29],
+ [98, 29],
+ [98, 98],
+ [19, 98]]], device=device, dtype=torch.long),
dst=torch.tensor([
[[0, 0],
[199, 0],
@@ -485,14 +486,14 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
resize_to=(200, 200), same_on_batch=True)
expected = dict(
src=torch.tensor([
- [[2, 3],
- [61, 3],
- [61, 52],
- [2, 52]],
- [[2, 3],
- [81, 3],
- [81, 72],
- [2, 72]]], device=device, dtype=torch.long),
+ [[36, 46],
+ [95, 46],
+ [95, 95],
+ [36, 95]],
+ [[36, 46],
+ [115, 46],
+ [115, 115],
+ [36, 115]]], device=device, dtype=torch.long),
dst=torch.tensor([
[[0, 0],
[199, 0],
@@ -510,7 +511,7 @@ class TestRandomCropGen(RandomGeneratorBaseTests):
class TestRandomCropSizeGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('size', [(200, 200)])
@pytest.mark.parametrize('scale', [torch.tensor([.7, 1.3])])
@pytest.mark.parametrize('ratio', [torch.tensor([.9, 1.1])])
@@ -525,20 +526,21 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('size,scale,ratio', [
- pytest.param((100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1]), marks=pytest.mark.xfail),
- pytest.param((100, 100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1]), marks=pytest.mark.xfail),
- pytest.param((100, 100), torch.tensor([.7]), torch.tensor([.9, 1.1]), marks=pytest.mark.xfail),
- pytest.param((100, 100), torch.tensor([.7, 1.3, 1.5]), torch.tensor([.9, 1.1]), marks=pytest.mark.xfail),
- pytest.param((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9]), marks=pytest.mark.xfail),
- pytest.param((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1, 1.3]), marks=pytest.mark.xfail),
+ ((100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1])),
+ ((100, 100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1])),
+ ((100, 100), torch.tensor([.7]), torch.tensor([.9, 1.1])),
+ ((100, 100), torch.tensor([.7, 1.3, 1.5]), torch.tensor([.9, 1.1])),
+ ((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9])),
+ ((100, 100), torch.tensor([.7, 1.3]), torch.tensor([.9, 1.1, 1.3])),
])
def test_invalid_param_combinations(self, size, scale, ratio, device, dtype):
batch_size = 2
- random_crop_size_generator(
- batch_size=batch_size, size=size,
- scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype),
- same_on_batch=same_on_batch)
+ with pytest.raises(Exception):
+ random_crop_size_generator(
+ batch_size=batch_size, size=size,
+ scale=scale.to(device=device, dtype=dtype),
+ ratio=ratio.to(device=device, dtype=dtype),
+ same_on_batch=same_on_batch)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -550,14 +552,25 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
same_on_batch=False)
expected = dict(
size=torch.tensor([
- [84, 92],
- [87, 86],
- [89, 87],
- [98, 97],
- [89, 84],
- [90, 96],
[89, 87],
- [92, 95]], device=device, dtype=torch.long)
+ [91, 95],
+ [81, 87],
+ [92, 98],
+ [89, 92],
+ [88, 90],
+ [87, 95],
+ [92, 87]], device=device, dtype=torch.long)
+ )
+ assert res.keys() == expected.keys()
+ assert_allclose(res['size'], expected['size'])
+
+ res = random_crop_size_generator(
+ batch_size=100, size=(100, 100),
+ scale=torch.tensor([0.999, 1.], device=device, dtype=dtype),
+ ratio=torch.tensor([1., 1.], device=device, dtype=dtype),
+ same_on_batch=False)
+ expected = dict(
+ size=torch.tensor([[100, 100]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_allclose(res['size'], expected['size'])
@@ -572,14 +585,14 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
same_on_batch=True)
expected = dict(
size=torch.tensor([
- [87, 89],
- [87, 89],
- [87, 89],
- [87, 89],
- [87, 89],
- [87, 89],
- [87, 89],
- [87, 89]], device=device, dtype=torch.long),
+ [89, 87],
+ [89, 87],
+ [89, 87],
+ [89, 87],
+ [89, 87],
+ [89, 87],
+ [89, 87],
+ [89, 87]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_allclose(res['size'], expected['size'])
@@ -587,7 +600,7 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):
class TestRandomRectangleGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('height', [200])
@pytest.mark.parametrize('width', [300])
@pytest.mark.parametrize('scale', [torch.tensor([.7, 1.1])])
@@ -602,24 +615,25 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
ratio=ratio.to(device=device, dtype=dtype), value=value, same_on_batch=same_on_batch)
@pytest.mark.parametrize('height,width,scale,ratio,value', [
- pytest.param(-100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0, marks=pytest.mark.xfail),
- pytest.param(100, -100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0, marks=pytest.mark.xfail),
- pytest.param(100, -100, torch.tensor([0.7]), torch.tensor([0.7, 1.3]), 0, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([0.7, 1.3, 1.5]), torch.tensor([0.7, 1.3]), 0, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7]), 0, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3, 1.5]), 0, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), -1, marks=pytest.mark.xfail),
- pytest.param(100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 2, marks=pytest.mark.xfail),
- pytest.param(
- 100, 100, torch.tensor([.5, .7]), torch.tensor([.7, .9]), torch.tensor(0.5), marks=pytest.mark.xfail),
+ (-100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
+ (100, -100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 0),
+ (100, -100, torch.tensor([0.7]), torch.tensor([0.7, 1.3]), 0),
+ (100, 100, torch.tensor([0.7, 1.3, 1.5]), torch.tensor([0.7, 1.3]), 0),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7]), 0),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3, 1.5]), 0),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), -1),
+ (100, 100, torch.tensor([0.7, 1.3]), torch.tensor([0.7, 1.3]), 2),
+ (
+ 100, 100, torch.tensor([.5, .7]), torch.tensor([.7, .9]), torch.tensor(0.5)),
])
def test_invalid_param_combinations(
self, height, width, scale, ratio, value, device, dtype
):
batch_size = 8
- random_rectangles_params_generator(
- batch_size=batch_size, height=height, width=width, scale=scale.to(device=device, dtype=dtype),
- ratio=ratio.to(device=device, dtype=dtype), value=value, same_on_batch=same_on_batch)
+ with pytest.raises(Exception):
+ random_rectangles_params_generator(
+ batch_size=batch_size, height=height, width=width, scale=scale.to(device=device, dtype=dtype),
+ ratio=ratio.to(device=device, dtype=dtype), value=value, same_on_batch=same_on_batch)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -634,7 +648,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
widths=torch.tensor([100, 100], device=device, dtype=torch.int32),
heights=torch.tensor([0, 0], device=device, dtype=torch.int32),
xs=torch.tensor([0, 0], device=device, dtype=torch.int32),
- ys=torch.tensor([9, 23], device=device, dtype=torch.int32),
+ ys=torch.tensor([6, 8], device=device, dtype=torch.int32),
values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
@@ -657,7 +671,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
widths=torch.tensor([100, 100], device=device, dtype=torch.int32),
heights=torch.tensor([0, 0], device=device, dtype=torch.int32),
xs=torch.tensor([0, 0], device=device, dtype=torch.int32),
- ys=torch.tensor([20, 20], device=device, dtype=torch.int32),
+ ys=torch.tensor([10, 10], device=device, dtype=torch.int32),
values=torch.tensor([0.5000, 0.5000], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
@@ -670,7 +684,7 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):
class TestCenterCropGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [2])
+ @pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('height', [200])
@pytest.mark.parametrize('width', [200])
@pytest.mark.parametrize('size', [(100, 100)])
@@ -680,15 +694,16 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
center_crop_generator(batch_size=batch_size, height=height, width=width, size=size)
@pytest.mark.parametrize('height,width,size', [
- pytest.param(200, -200, (100, 100), marks=pytest.mark.xfail),
- pytest.param(-200, 200, (100, 100), marks=pytest.mark.xfail),
- pytest.param(100, 100, (120, 120), marks=pytest.mark.xfail),
- pytest.param(150, 100, (120, 120), marks=pytest.mark.xfail),
- pytest.param(100, 150, (120, 120), marks=pytest.mark.xfail),
+ (200, -200, (100, 100)),
+ (-200, 200, (100, 100)),
+ (100, 100, (120, 120)),
+ (150, 100, (120, 120)),
+ (100, 150, (120, 120)),
])
def test_invalid_param_combinations(self, height, width, size, device, dtype):
batch_size = 2
- center_crop_generator(batch_size=batch_size, height=height, width=width, size=size)
+ with pytest.raises(Exception):
+ center_crop_generator(batch_size=batch_size, height=height, width=width, size=size)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -714,8 +729,8 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
[0, 119]]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
- assert_allclose(res['src'], expected['src'])
- assert_allclose(res['dst'], expected['dst'])
+ assert_allclose(res['src'].to(device=device), expected['src'])
+ assert_allclose(res['dst'].to(device=device), expected['dst'])
def test_same_on_batch(self, device, dtype):
pass
@@ -723,8 +738,8 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
class TestRandomMotionBlur(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
- @pytest.mark.parametrize('kernel_size', [1, (3, 5)])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
+ @pytest.mark.parametrize('kernel_size', [3, (3, 5)])
@pytest.mark.parametrize('angle', [torch.tensor([10, 30])])
@pytest.mark.parametrize('direction', [torch.tensor([-1, -1]), torch.tensor([1, 1])])
@pytest.mark.parametrize('same_on_batch', [True, False])
@@ -736,16 +751,17 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('kernel_size,angle,direction', [
- pytest.param(4, torch.tensor([30, 100]), torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param(1, torch.tensor([30, 100]), torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param((1, 2, 3), torch.tensor([30, 100]), torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param(3, torch.tensor([30, 100]), torch.tensor([-2, 1]), marks=pytest.mark.xfail),
- pytest.param(3, torch.tensor([30, 100]), torch.tensor([-1, 2]), marks=pytest.mark.xfail),
+ (4, torch.tensor([30, 100]), torch.tensor([-1, 1])),
+ (1, torch.tensor([30, 100]), torch.tensor([-1, 1])),
+ ((1, 2, 3), torch.tensor([30, 100]), torch.tensor([-1, 1])),
+ (3, torch.tensor([30, 100]), torch.tensor([-2, 1])),
+ (3, torch.tensor([30, 100]), torch.tensor([-1, 2])),
])
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
- random_motion_blur_generator(
- batch_size=8, kernel_size=kernel_size, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_motion_blur_generator(
+ batch_size=8, kernel_size=kernel_size, angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -755,9 +771,9 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype), same_on_batch=False)
expected = dict(
- ksize_factor=torch.tensor([3., 3.], device=device, dtype=torch.int32),
- angle_factor=torch.tensor([33.4893, 33.7746], device=device, dtype=dtype),
- direction_factor=torch.tensor([-0.7528, -0.8948], device=device, dtype=dtype)
+ ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
+ angle_factor=torch.tensor([82.9362, 84.9002], device=device, dtype=dtype),
+ direction_factor=torch.tensor([-0.2343, 0.9186], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
@@ -772,9 +788,9 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype), same_on_batch=True)
expected = dict(
- ksize_factor=torch.tensor([3., 3.], device=device, dtype=torch.int32),
- angle_factor=torch.tensor([33.4893, 33.4893], device=device, dtype=dtype),
- direction_factor=torch.tensor([-0.8742, -0.8742], device=device, dtype=dtype)
+ ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
+ angle_factor=torch.tensor([82.9362, 82.9362], device=device, dtype=dtype),
+ direction_factor=torch.tensor([0.8300, 0.8300], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
@@ -784,7 +800,7 @@ class TestRandomMotionBlur(RandomGeneratorBaseTests):
class TestRandomSolarizeGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('thresholds', [torch.tensor([0, 1]), torch.tensor([0.4, 0.6])])
@pytest.mark.parametrize('additions', [torch.tensor([-0.5, 0.5])])
@pytest.mark.parametrize('same_on_batch', [True, False])
@@ -794,17 +810,18 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
additions=additions.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
@pytest.mark.parametrize('thresholds,additions', [
- pytest.param(torch.tensor([0, 2]), torch.tensor([-0.5, 0.5]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([-1, 1]), torch.tensor([-0.5, 0.5]), marks=pytest.mark.xfail),
- pytest.param([0, 1], torch.tensor([-0.5, 0.5]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0, 1]), torch.tensor([-0.5, 1]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0, 1]), torch.tensor([-1, 0.5]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0, 1]), [-0.5, 0.5], marks=pytest.mark.xfail),
+ (torch.tensor([0, 2]), torch.tensor([-0.5, 0.5])),
+ (torch.tensor([-1, 1]), torch.tensor([-0.5, 0.5])),
+ ([0, 1], torch.tensor([-0.5, 0.5])),
+ (torch.tensor([0, 1]), torch.tensor([-0.5, 1])),
+ (torch.tensor([0, 1]), torch.tensor([-1, 0.5])),
+ (torch.tensor([0, 1]), [-0.5, 0.5]),
])
def test_invalid_param_combinations(self, thresholds, additions, device, dtype):
- random_solarize_generator(
- batch_size=batch_size, thresholds=thresholds.to(device=device, dtype=dtype),
- additions=additions.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_solarize_generator(
+ batch_size=batch_size, thresholds=thresholds.to(device=device, dtype=dtype),
+ additions=additions.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -814,9 +831,9 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype), same_on_batch=False)
expected = dict(
thresholds_factor=torch.tensor(
- [0.0582, 0.0629, 0.1236, 0.0526, 0.5262, 0.4768, 0.9552, 0.9288], device=device, dtype=dtype),
+ [0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype),
additions_factor=torch.tensor(
- [-0.4165, -0.3674, -0.3429, -0.1246, 0.3425, 0.3705, -0.1225, 0.1124], device=device, dtype=dtype),
+ [0.4408, -0.3668, 0.4346, 0.0936, 0.3694, 0.0677, 0.2411, -0.0706], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['thresholds_factor'], expected['thresholds_factor'], rtol=1e-4, atol=1e-4)
@@ -830,9 +847,9 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
additions=torch.tensor([-0.5, 0.5], device=device, dtype=dtype), same_on_batch=True)
expected = dict(
thresholds_factor=torch.tensor(
- [0.0582, 0.0582, 0.0582, 0.0582, 0.0582, 0.0582, 0.0582, 0.0582], device=device, dtype=dtype),
+ [0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype),
additions_factor=torch.tensor(
- [-0.4371, -0.4371, -0.4371, -0.4371, -0.4371, -0.4371, -0.4371, -0.4371], device=device, dtype=dtype),
+ [0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150, 0.4150], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['thresholds_factor'], expected['thresholds_factor'], rtol=1e-4, atol=1e-4)
@@ -841,7 +858,7 @@ class TestRandomSolarizeGen(RandomGeneratorBaseTests):
class TestRandomPosterizeGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('bits', [torch.tensor([0, 8])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, bits, same_on_batch, device, dtype):
@@ -849,14 +866,15 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
@pytest.mark.parametrize('bits', [
- pytest.param(torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0, 9]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([3]), marks=pytest.mark.xfail),
- pytest.param([0, 8], marks=pytest.mark.xfail),
+ (torch.tensor([-1, 1])),
+ (torch.tensor([0, 9])),
+ (torch.tensor([3])),
+ ([0, 8]),
])
def test_invalid_param_combinations(self, bits, device, dtype):
- random_posterize_generator(
- batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
+ with pytest.raises(Exception):
+ random_posterize_generator(
+ batch_size=batch_size, bits=bits.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
def test_random_gen(self, device, dtype):
torch.manual_seed(9)
@@ -865,7 +883,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=False)
expected = dict(
bits_factor=torch.tensor(
- [1, 6, 2, 0, 0, 4, 0, 0], device=device, dtype=torch.int32)
+ [5, 2, 3, 6, 7, 7, 2, 7], device=device, dtype=torch.int32)
)
assert res.keys() == expected.keys()
assert_allclose(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
@@ -877,7 +895,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
batch_size=batch_size, bits=torch.tensor([0, 8], device=device, dtype=dtype), same_on_batch=True)
expected = dict(
bits_factor=torch.tensor(
- [1, 1, 1, 1, 1, 1, 1, 1], device=device, dtype=torch.int32)
+ [5, 5, 5, 5, 5, 5, 5, 5], device=device, dtype=torch.int32)
)
assert res.keys() == expected.keys()
assert_allclose(res['bits_factor'], expected['bits_factor'], rtol=1e-4, atol=1e-4)
@@ -885,7 +903,7 @@ class TestRandomPosterizeGen(RandomGeneratorBaseTests):
class TestRandomSharpnessGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('sharpness', [torch.tensor([0., 1.])])
@pytest.mark.parametrize('same_on_batch', [True, False])
def test_valid_param_combinations(self, batch_size, sharpness, same_on_batch, device, dtype):
@@ -893,13 +911,14 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
@pytest.mark.parametrize('sharpness', [
- pytest.param(torch.tensor([-1, 5]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([3]), marks=pytest.mark.xfail),
- pytest.param([0, 1.], marks=pytest.mark.xfail),
+ (torch.tensor([-1, 5])),
+ (torch.tensor([3])),
+ ([0, 1.]),
])
def test_invalid_param_combinations(self, sharpness, device, dtype):
- random_sharpness_generator(
- batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
+ with pytest.raises(Exception):
+ random_sharpness_generator(
+ batch_size=batch_size, sharpness=sharpness.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -908,7 +927,7 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
batch_size=batch_size, sharpness=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=False)
expected = dict(
sharpness_factor=torch.tensor(
- [0.0582, 0.0629, 0.1236, 0.0526, 0.5262, 0.4768, 0.9552, 0.9288], device=device, dtype=dtype)
+ [0.8823, 0.9150, 0.3829, 0.9593, 0.3904, 0.6009, 0.2566, 0.7936], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)
@@ -920,7 +939,7 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
batch_size=batch_size, sharpness=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=True)
expected = dict(
sharpness_factor=torch.tensor(
- [0.0582, 0.0582, 0.0582, 0.0582, 0.0582, 0.0582, 0.0582, 0.0582], device=device, dtype=dtype)
+ [0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823, 0.8823], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['sharpness_factor'], expected['sharpness_factor'], rtol=1e-4, atol=1e-4)
@@ -928,7 +947,7 @@ class TestRandomSharpnessGen(RandomGeneratorBaseTests):
class TestRandomMixUpGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('p', [0., 0.5, 1.])
@pytest.mark.parametrize('lambda_val', [None, torch.tensor([0., 1.])])
@pytest.mark.parametrize('same_on_batch', [True, False])
@@ -940,14 +959,15 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('lambda_val', [
- pytest.param(torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0, 2]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([0, 0.5, 1]), marks=pytest.mark.xfail),
- pytest.param([0., 1.], marks=pytest.mark.xfail),
+ (torch.tensor([-1, 1])),
+ (torch.tensor([0, 2])),
+ (torch.tensor([0, 0.5, 1])),
+ ([0., 1.]),
])
def test_invalid_param_combinations(self, lambda_val, device, dtype):
- random_mixup_generator(
- batch_size=8, lambda_val=lambda_val.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_mixup_generator(
+ batch_size=8, lambda_val=lambda_val.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -958,7 +978,7 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
expected = dict(
mixup_pairs=torch.tensor([6, 1, 0, 7, 2, 5, 3, 4], device=device, dtype=torch.long),
mixup_lambdas=torch.tensor(
- [0.0000, 0.0000, 0.0196, 0.0000, 0.6535, 0.0000, 0.5949, 0.0000], device=device, dtype=dtype)
+ [0.0000, 0.0000, 0.5739, 0.0000, 0.6274, 0.0000, 0.4414, 0.0000], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
@@ -973,7 +993,7 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
expected = dict(
mixup_pairs=torch.tensor([4, 6, 7, 5, 0, 1, 3, 2], device=device, dtype=torch.long),
mixup_lambdas=torch.tensor(
- [0.0435, 0.0435, 0.0435, 0.0435, 0.0435, 0.0435, 0.0435, 0.0435], device=device, dtype=dtype)
+ [0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804, 0.3804], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['mixup_pairs'], expected['mixup_pairs'], rtol=1e-4, atol=1e-4)
@@ -982,7 +1002,7 @@ class TestRandomMixUpGen(RandomGeneratorBaseTests):
class TestRandomCutMixGen(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('p', [0, 0.5, 1.])
@pytest.mark.parametrize('width,height', [(200, 200)])
@pytest.mark.parametrize('num_mix', [1, 3])
@@ -999,20 +1019,21 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('width,height,num_mix,beta,cut_size', [
- pytest.param(200, -200, 1, None, None, marks=pytest.mark.xfail),
- pytest.param(-200, 200, 1, None, None, marks=pytest.mark.xfail),
- pytest.param(200, 200, 0, None, None, marks=pytest.mark.xfail),
- pytest.param(200, 200, 1.5, None, None, marks=pytest.mark.xfail),
- pytest.param(200, 200, 1, torch.tensor([0., 1.]), None, marks=pytest.mark.xfail),
- pytest.param(200, 200, 1, None, torch.tensor([-1., 1.]), marks=pytest.mark.xfail),
- pytest.param(200, 200, 1, None, torch.tensor([0., 2.]), marks=pytest.mark.xfail),
+ (200, -200, 1, None, None),
+ (-200, 200, 1, None, None),
+ (200, 200, 0, None, None),
+ (200, 200, 1.5, None, None),
+ (200, 200, 1, torch.tensor([0., 1.]), None),
+ (200, 200, 1, None, torch.tensor([-1., 1.])),
+ (200, 200, 1, None, torch.tensor([0., 2.])),
])
def test_invalid_param_combinations(self, width, height, num_mix, beta, cut_size, device, dtype):
- random_cutmix_generator(
- batch_size=8, p=p, width=width, height=height,
- beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (torch.Tensor)) else beta,
- cut_size=beta.to(device=device, dtype=dtype) if isinstance(cut_size, (torch.Tensor)) else cut_size,
- same_on_batch=same_on_batch)
+ with pytest.raises(Exception):
+ random_cutmix_generator(
+ batch_size=8, p=p, width=width, height=height,
+ beta=beta.to(device=device, dtype=dtype) if isinstance(beta, (torch.Tensor)) else beta,
+ cut_size=beta.to(device=device, dtype=dtype) if isinstance(cut_size, (torch.Tensor)) else cut_size,
+ same_on_batch=same_on_batch)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -1022,16 +1043,16 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
beta=torch.tensor(1., device=device, dtype=dtype),
cut_size=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=False)
expected = dict(
- mix_pairs=torch.tensor([[0., 1.]], device=device, dtype=torch.long),
+ mix_pairs=torch.tensor([[0, 1]], device=device, dtype=torch.long),
crop_src=torch.tensor([[
- [[174, 122],
- [173, 122],
- [173, 121],
- [174, 121]],
- [[75, 17],
- [74, 17],
- [74, 16],
- [75, 16]]]], device=device, dtype=torch.long)
+ [[71, 108],
+ [70, 108],
+ [70, 107],
+ [71, 107]],
+ [[39, 1],
+ [38, 1],
+ [38, 0],
+ [39, 0]]]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_allclose(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
@@ -1045,16 +1066,16 @@ class TestRandomCutMixGen(RandomGeneratorBaseTests):
beta=torch.tensor(1., device=device, dtype=dtype),
cut_size=torch.tensor([0., 1.], device=device, dtype=dtype), same_on_batch=True)
expected = dict(
- mix_pairs=torch.tensor([[1., 0.]], device=device, dtype=torch.long),
+ mix_pairs=torch.tensor([[1, 0]], device=device, dtype=torch.long),
crop_src=torch.tensor([[
- [[118, 3],
- [117, 3],
- [117, 2],
- [118, 2]],
- [[118, 3],
- [117, 3],
- [117, 2],
- [118, 2]]]], device=device, dtype=torch.long)
+ [[114, 53],
+ [113, 53],
+ [113, 52],
+ [114, 52]],
+ [[114, 53],
+ [113, 53],
+ [113, 52],
+ [114, 52]]]], device=device, dtype=torch.long)
)
assert res.keys() == expected.keys()
assert_allclose(res['mix_pairs'], expected['mix_pairs'], rtol=1e-4, atol=1e-4)
diff --git a/test/augmentation/test_random_generator_3d.py b/test/augmentation/test_random_generator_3d.py
index d69c1c097..56267afb9 100644
--- a/test/augmentation/test_random_generator_3d.py
+++ b/test/augmentation/test_random_generator_3d.py
@@ -29,7 +29,7 @@ class RandomGeneratorBaseTests():
class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @pytest.mark.parametrize('batch_size', [0, 1, 8])
@pytest.mark.parametrize('depth,height,width', [(200, 200, 200)])
@pytest.mark.parametrize('distortion_scale', [torch.tensor(0.), torch.tensor(0.5), torch.tensor(1.)])
@pytest.mark.parametrize('same_on_batch', [True, False])
@@ -42,16 +42,17 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
@pytest.mark.parametrize('depth,height,width,distortion_scale', [
# Should be failed if distortion_scale > 1. or distortion_scale < 0.
- pytest.param(-100, 100, 100, torch.tensor(0.5), marks=pytest.mark.xfail),
- pytest.param(100, -100, 100, torch.tensor(0.5), marks=pytest.mark.xfail),
- pytest.param(100, 100, -100, torch.tensor(-0.5), marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor(1.5), marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([0., 0.5]), marks=pytest.mark.xfail),
+ (-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.5])),
])
def test_invalid_param_combinations(self, depth, height, width, distortion_scale, device, dtype):
- random_perspective_generator3d(
- batch_size=8, height=height, width=width,
- distortion_scale=distortion_scale.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_perspective_generator3d(
+ batch_size=8, height=height, width=width,
+ distortion_scale=distortion_scale.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -75,22 +76,23 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
[199., 0., 199.],
[199., 199., 199.],
[0., 199., 199.]]], device=device, dtype=dtype),
- end_points=torch.tensor([[[2.9077, 3.1455, 6.1793],
- [196.3710, 26.3086, 23.8392],
- [151.2382, 152.5624, 4.1772],
- [6.6320, 191.1473, 18.7684],
- [42.1260, 43.5251, 180.1234],
- [168.3782, 4.4055, 163.9409],
- [167.8298, 177.1361, 195.2633],
- [34.1715, 183.3881, 183.5471]],
- [[1.5670, 2.0183, 46.5954],
- [191.3937, 13.2522, 6.5217],
- [186.4072, 187.3296, 11.2833],
- [15.8784, 168.2796, 29.8886],
- [42.4501, 1.6248, 183.5378],
- [177.3848, 46.7149, 192.8844],
- [177.6152, 184.5908, 149.9299],
- [42.2815, 179.7861, 194.0347]]], device=device, dtype=dtype),
+ end_points=torch.tensor(
+ [[[44.1135, 45.7502, 19.1432],
+ [151.0347, 19.5224, 30.0448],
+ [186.1714, 159.3179, 47.0386],
+ [6.6593, 152.2701, 29.6790],
+ [43.4702, 28.3858, 161.9453],
+ [177.5298, 44.2721, 170.3048],
+ [185.6710, 167.6275, 185.5184],
+ [22.0682, 184.1540, 157.4157]],
+ [[5.2657, 13.4747, 17.9406],
+ [189.0318, 27.3596, 0.3080],
+ [151.4223, 195.2367, 44.3007],
+ [29.1605, 182.1176, 40.4487],
+ [28.8963, 45.1991, 171.2670],
+ [181.8843, 31.7171, 180.7795],
+ [163.4786, 151.6794, 159.5485],
+ [14.0707, 159.5684, 169.5268]]], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)
@@ -118,22 +120,23 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
[199., 0., 199.],
[199., 199., 199.],
[0., 199., 199.]]], device=device, dtype=dtype),
- end_points=torch.tensor([[[2.9077, 3.1455, 6.1793],
- [196.3710, 26.3086, 23.8392],
- [151.2382, 152.5624, 4.1772],
- [6.6320, 191.1473, 18.7684],
- [42.1260, 43.5251, 180.1234],
- [168.3782, 4.4055, 163.9409],
- [167.8298, 177.1361, 195.2633],
- [34.1715, 183.3881, 183.5471]],
- [[2.9077, 3.1455, 6.1793],
- [196.3710, 26.3086, 23.8392],
- [151.2382, 152.5624, 4.1772],
- [6.6320, 191.1473, 18.7684],
- [42.1260, 43.5251, 180.1234],
- [168.3782, 4.4055, 163.9409],
- [167.8298, 177.1361, 195.2633],
- [34.1715, 183.3881, 183.5471]]], device=device, dtype=dtype)
+ end_points=torch.tensor(
+ [[[44.1135, 45.7502, 19.1432],
+ [151.0347, 19.5224, 30.0448],
+ [186.1714, 159.3179, 47.0386],
+ [6.6593, 152.2701, 29.6790],
+ [43.4702, 28.3858, 161.9453],
+ [177.5298, 44.2721, 170.3048],
+ [185.6710, 167.6275, 185.5184],
+ [22.0682, 184.1540, 157.4157]],
+ [[44.1135, 45.7502, 19.1432],
+ [151.0347, 19.5224, 30.0448],
+ [186.1714, 159.3179, 47.0386],
+ [6.6593, 152.2701, 29.6790],
+ [43.4702, 28.3858, 161.9453],
+ [177.5298, 44.2721, 170.3048],
+ [185.6710, 167.6275, 185.5184],
+ [22.0682, 184.1540, 157.4157]]], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['start_points'], expected['start_points'], atol=1e-4, rtol=1e-4)
@@ -142,7 +145,7 @@ class TestRandomPerspectiveGen3D(RandomGeneratorBaseTests):
class TestRandomAffineGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @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('translate', [None, torch.tensor([0.1, 0.1, 0.1])])
@@ -161,35 +164,28 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('depth,height,width,degrees,translate,scale,shear', [
- pytest.param(-100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, -100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, -100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([0, 9]), None, None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]),
- torch.tensor([0.1, 0.2]), None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]),
- torch.tensor([0.1, 0.2]), None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]),
- torch.tensor([0.1]), None, None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]),
- None, torch.tensor([[0.2, 0.2, 0.2]]), None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]),
- None, torch.tensor([0.2]), None, marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]),
- None, None, torch.tensor([[20, 20, 30]]), marks=pytest.mark.xfail),
- pytest.param(100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]),
- None, None, torch.tensor([20]), marks=pytest.mark.xfail),
+ (-100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
+ (100, -100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
+ (100, 100, -100, torch.tensor([[0, 9], [0, 9], [0, 9]]), None, None, None),
+ (100, 100, 100, torch.tensor([0, 9]), None, None, None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1, 0.2]), None, None),
+ (100, 100, 100, torch.tensor([[0, 9], [0, 9], [0, 9]]), torch.tensor([0.1]), None, None),
+ (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])),
])
def test_invalid_param_combinations(
self, depth, height, width, degrees, translate, scale, shear, device, dtype
):
- batch_size = 8
- 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)
+ 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)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -205,19 +201,19 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
shears=shear.to(device=device, dtype=dtype) if shear is not None else None)
expected = dict(
translations=torch.tensor(
- [[13.7008, -4.8987, -16.4756], [14.8200, 4.4975, 8.0473]], device=device, dtype=dtype),
+ [[14.7762, 9.6438, 15.4177], [2.7086, -2.8238, 2.9562]], device=device, dtype=dtype),
center=torch.tensor(
[[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),
scale=torch.tensor(
- [[1.1776, 0.7418, 0.7785], [1.1644, 0.7663, 0.8877]], device=device, dtype=dtype),
+ [[0.8283, 1.1704, 1.1673], [1.0968, 0.7666, 0.9968]], device=device, dtype=dtype),
angles=torch.tensor(
- [[10.5815, 11.2359, 15.2617], [10.6291, 10.5258, 14.7678]], device=device, dtype=dtype),
- sxy=torch.tensor([12.4681, 8.7456], device=device, dtype=dtype),
- sxz=torch.tensor([1.4947, 13.6686], device=device, dtype=dtype),
- syx=torch.tensor([6.2448, 6.1812], device=device, dtype=dtype),
- syz=torch.tensor([0.6268, 0.8073], device=device, dtype=dtype),
- szx=torch.tensor([18.6382, 3.0425], device=device, dtype=dtype),
- szy=torch.tensor([5.3009, 2.6087], device=device, dtype=dtype),
+ [[18.8227, 13.8286, 13.9045], [19.1500, 19.5931, 16.0090]], device=device, dtype=dtype),
+ sxy=torch.tensor([5.3316, 12.5490], device=device, dtype=dtype),
+ sxz=torch.tensor([5.3926, 8.8273], device=device, dtype=dtype),
+ syx=torch.tensor([5.9384, 16.6337], device=device, dtype=dtype),
+ syz=torch.tensor([2.1063, 5.3899], device=device, dtype=dtype),
+ szx=torch.tensor([7.1763, 3.9873], device=device, dtype=dtype),
+ szy=torch.tensor([10.9438, 0.1232], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
@@ -246,19 +242,19 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
same_on_batch=True)
expected = dict(
translations=torch.tensor(
- [[18.2094, 17.1501, -16.6583], [18.2094, 17.1501, -16.6583]], device=device, dtype=dtype),
+ [[-9.7371, 11.7457, 17.6309], [-9.7371, 11.7457, 17.6309]], device=device, dtype=dtype),
center=torch.tensor(
[[99.5000, 99.5000, 99.5000], [99.5000, 99.5000, 99.5000]], device=device, dtype=dtype),
scale=torch.tensor(
- [[0.7263, 0.9631, 0.9384], [0.7263, 0.9631, 0.9384]], device=device, dtype=dtype),
+ [[1.1797, 0.8952, 1.0004], [1.1797, 0.8952, 1.0004]], device=device, dtype=dtype),
angles=torch.tensor(
- [[10.5815, 10.6291, 11.2359], [10.5815, 10.6291, 11.2359]], device=device, dtype=dtype),
- sxy=torch.tensor([2.6528, 2.6528], device=device, dtype=dtype),
- sxz=torch.tensor([3.1411, 3.1411], device=device, dtype=dtype),
- syx=torch.tensor([7.5073, 7.5073], device=device, dtype=dtype),
- syz=torch.tensor([16.8504, 16.8504], device=device, dtype=dtype),
- szx=torch.tensor([17.4100, 17.4100], device=device, dtype=dtype),
- szy=torch.tensor([7.5507, 7.5507], device=device, dtype=dtype),
+ [[18.8227, 19.1500, 13.8286], [18.8227, 19.1500, 13.8286]], device=device, dtype=dtype),
+ sxy=torch.tensor([2.6637, 2.6637], device=device, dtype=dtype),
+ sxz=torch.tensor([18.6920, 18.6920], device=device, dtype=dtype),
+ syx=torch.tensor([11.8716, 11.8716], device=device, dtype=dtype),
+ syz=torch.tensor([17.3881, 17.3881], device=device, dtype=dtype),
+ szx=torch.tensor([11.3543, 11.3543], device=device, dtype=dtype),
+ szy=torch.tensor([14.8219, 14.8219], device=device, dtype=dtype),
)
assert res.keys() == expected.keys()
assert_allclose(res['translations'], expected['translations'], rtol=1e-4, atol=1e-4)
@@ -275,7 +271,7 @@ class TestRandomAffineGen3D(RandomGeneratorBaseTests):
class TestRandomRotationGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
+ @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):
@@ -283,15 +279,15 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=same_on_batch)
@pytest.mark.parametrize('degrees', [
- pytest.param(torch.tensor(10), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([10]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([[0, 30]]), marks=pytest.mark.xfail),
- pytest.param(torch.tensor([[0, 30], [0, 30]]), marks=pytest.mark.xfail),
+ (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):
- batch_size = 8
- random_rotation_generator3d(
- batch_size=batch_size, degrees=degrees.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_rotation_generator3d(
+ batch_size=8, degrees=degrees.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -299,9 +295,9 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
res = random_rotation_generator3d(
batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=False)
expected = dict(
- yaw=torch.tensor([1.7446, 1.8873], device=device, dtype=dtype),
- pitch=torch.tensor([3.7076, 1.5774], device=device, dtype=dtype),
- roll=torch.tensor([15.7852, 14.3035], device=device, dtype=dtype)
+ yaw=torch.tensor([26.4681, 27.4501], device=device, dtype=dtype),
+ pitch=torch.tensor([11.4859, 28.7792], device=device, dtype=dtype),
+ roll=torch.tensor([11.7134, 18.0269], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)
@@ -314,9 +310,9 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
res = random_rotation_generator3d(
batch_size=2, degrees=degrees.to(device=device, dtype=dtype), same_on_batch=True)
expected = dict(
- yaw=torch.tensor([1.7446, 1.7446], device=device, dtype=dtype),
- pitch=torch.tensor([1.8873, 1.8873], device=device, dtype=dtype),
- roll=torch.tensor([3.7076, 3.7076], device=device, dtype=dtype)
+ yaw=torch.tensor([26.4681, 26.4681], device=device, dtype=dtype),
+ pitch=torch.tensor([27.4501, 27.4501], device=device, dtype=dtype),
+ roll=torch.tensor([11.4859, 11.4859], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['yaw'], expected['yaw'], atol=1e-4, rtol=1e-4)
@@ -326,14 +322,16 @@ class TestRandomRotationGen3D(RandomGeneratorBaseTests):
class TestRandomCropGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [2])
+ @pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('input_size', [(200, 200, 200)])
- @pytest.mark.parametrize('size', [(100, 100, 100), torch.tensor([[50, 60, 70], [50, 60, 70]])])
+ @pytest.mark.parametrize('size', [(100, 100, 100), torch.tensor([50, 60, 70])])
@pytest.mark.parametrize('resize_to', [None, (100, 100, 100)])
@pytest.mark.parametrize('same_on_batch', [True, False])
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,
@@ -341,18 +339,17 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('input_size,size,resize_to', [
- pytest.param((-300, 300, 300), (200, 200, 200), (100, 100, 100), marks=pytest.mark.xfail),
- pytest.param((100, 100, 100), (200, 200, 200), (100, 100, 100), marks=pytest.mark.xfail),
- pytest.param((200, 200, 200), torch.tensor([50, 50, 50]), (100, 100, 100), marks=pytest.mark.xfail),
- pytest.param((100, 100, 100), torch.tensor([[50, 60, 70], [50, 60, 70]]),
- (100, 100), marks=pytest.mark.xfail),
+ ((-300, 300, 300), (200, 200, 200), (100, 100, 100)),
+ ((100, 100, 100), (200, 200, 200), (100, 100, 100)),
+ ((200, 200, 200), torch.tensor([50, 50, 50]), (100, 100, 100)),
+ ((100, 100, 100), torch.tensor([[50, 60, 70], [50, 60, 70]]), (100, 100)),
])
def test_invalid_param_combinations(self, input_size, size, resize_to, device, dtype):
- batch_size = 2
- 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)
+ with pytest.raises(Exception):
+ random_crop_generator3d(
+ batch_size=2, input_size=input_size,
+ size=size.to(device=device, dtype=dtype) if isinstance(size, torch.Tensor) else size,
+ resize_to=resize_to)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -361,38 +358,39 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype),
resize_to=(100, 100, 100))
expected = dict(
- src=torch.tensor([[[7., 17., 79.],
- [76., 17., 79.],
- [76., 76., 79.],
- [7., 76., 79.],
- [7., 17., 128.],
- [76., 17., 128.],
- [76., 76., 128.],
- [7., 76., 128.]],
- [[8., 7., 71.],
- [77., 7., 71.],
- [77., 66., 71.],
- [8., 66., 71.],
- [8., 7., 120.],
- [77., 7., 120.],
- [77., 66., 120.],
- [8., 66., 120.]]], device=device, dtype=dtype),
- dst=torch.tensor([[[0., 0., 0.],
- [99., 0., 0.],
- [99., 99., 0.],
- [0., 99., 0.],
- [0., 0., 99.],
- [99., 0., 99.],
- [99., 99., 99.],
- [0., 99., 99.]],
- [[0., 0., 0.],
- [99., 0., 0.],
- [99., 99., 0.],
- [0., 99., 0.],
- [0., 0., 99.],
- [99., 0., 99.],
- [99., 99., 99.],
- [0., 99., 99.]]], device=device, dtype=dtype),
+ src=torch.tensor(
+ [[[115, 53, 58],
+ [184, 53, 58],
+ [184, 112, 58],
+ [115, 112, 58],
+ [115, 53, 107],
+ [184, 53, 107],
+ [184, 112, 107],
+ [115, 112, 107]],
+ [[119, 135, 90],
+ [188, 135, 90],
+ [188, 194, 90],
+ [119, 194, 90],
+ [119, 135, 139],
+ [188, 135, 139],
+ [188, 194, 139],
+ [119, 194, 139]]], device=device, dtype=torch.long),
+ dst=torch.tensor([[[0, 0, 0],
+ [99, 0, 0],
+ [99, 99, 0],
+ [0, 99, 0],
+ [0, 0, 99],
+ [99, 0, 99],
+ [99, 99, 99],
+ [0, 99, 99]],
+ [[0, 0, 0],
+ [99, 0, 0],
+ [99, 99, 0],
+ [0, 99, 0],
+ [0, 0, 99],
+ [99, 0, 99],
+ [99, 99, 99],
+ [0, 99, 99]]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'], expected['src'], atol=1e-4, rtol=1e-4)
@@ -405,47 +403,48 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):
size=torch.tensor([[50, 60, 70], [50, 60, 70]], device=device, dtype=dtype),
resize_to=(100, 100, 100), same_on_batch=True)
expected = dict(
- src=torch.tensor([[[7., 8., 18.],
- [76., 8., 18.],
- [76., 67., 18.],
- [7., 67., 18.],
- [7., 8., 67.],
- [76., 8., 67.],
- [76., 67., 67.],
- [7., 67., 67.]],
- [[7., 8., 18.],
- [76., 8., 18.],
- [76., 67., 18.],
- [7., 67., 18.],
- [7., 8., 67.],
- [76., 8., 67.],
- [76., 67., 67.],
- [7., 67., 67.]]], device=device, dtype=dtype),
- dst=torch.tensor([[[0., 0., 0.],
- [99., 0., 0.],
- [99., 99., 0.],
- [0., 99., 0.],
- [0., 0., 99.],
- [99., 0., 99.],
- [99., 99., 99.],
- [0., 99., 99.]],
- [[0., 0., 0.],
- [99., 0., 0.],
- [99., 99., 0.],
- [0., 99., 0.],
- [0., 0., 99.],
- [99., 0., 99.],
- [99., 99., 99.],
- [0., 99., 99.]]], device=device, dtype=dtype),
+ src=torch.tensor(
+ [[[115, 129, 57],
+ [184, 129, 57],
+ [184, 188, 57],
+ [115, 188, 57],
+ [115, 129, 106],
+ [184, 129, 106],
+ [184, 188, 106],
+ [115, 188, 106]],
+ [[115, 129, 57],
+ [184, 129, 57],
+ [184, 188, 57],
+ [115, 188, 57],
+ [115, 129, 106],
+ [184, 129, 106],
+ [184, 188, 106],
+ [115, 188, 106]]], device=device, dtype=torch.long),
+ dst=torch.tensor([[[0, 0, 0],
+ [99, 0, 0],
+ [99, 99, 0],
+ [0, 99, 0],
+ [0, 0, 99],
+ [99, 0, 99],
+ [99, 99, 99],
+ [0, 99, 99]],
+ [[0, 0, 0],
+ [99, 0, 0],
+ [99, 99, 0],
+ [0, 99, 0],
+ [0, 0, 99],
+ [99, 0, 99],
+ [99, 99, 99],
+ [0, 99, 99]]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
assert_allclose(res['src'], expected['src'], atol=1e-4, rtol=1e-4)
assert_allclose(res['dst'], expected['dst'], atol=1e-4, rtol=1e-4)
-class TestCenterCropGen(RandomGeneratorBaseTests):
+class TestCenterCropGen3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [2])
+ @pytest.mark.parametrize('batch_size', [0, 2])
@pytest.mark.parametrize('depth,height,width', [(200, 200, 200)])
@pytest.mark.parametrize('size', [(100, 100, 100)])
def test_valid_param_combinations(
@@ -454,15 +453,16 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
center_crop_generator3d(batch_size=batch_size, depth=depth, height=height, width=width, size=size)
@pytest.mark.parametrize('depth,height,width,size', [
- pytest.param(200, 200, -200, (100, 100, 100), marks=pytest.mark.xfail),
- pytest.param(200, -200, 200, (100, 100), marks=pytest.mark.xfail),
- pytest.param(200, 100, 100, (300, 120, 100), marks=pytest.mark.xfail),
- pytest.param(200, 150, 100, (120, 180, 100), marks=pytest.mark.xfail),
- pytest.param(200, 100, 150, (120, 80, 200), marks=pytest.mark.xfail),
+ (200, 200, -200, (100, 100, 100)),
+ (200, -200, 200, (100, 100)),
+ (200, 100, 100, (300, 120, 100)),
+ (200, 150, 100, (120, 180, 100)),
+ (200, 100, 150, (120, 80, 200)),
])
def test_invalid_param_combinations(self, depth, height, width, size, device, dtype):
- batch_size = 2
- center_crop_generator3d(batch_size=batch_size, depth=depth, height=height, width=width, size=size)
+ with pytest.raises(Exception):
+ center_crop_generator3d(
+ batch_size=2, depth=depth, height=height, width=width, size=size)
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -488,8 +488,8 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
[0, 149, 119]]], device=device, dtype=torch.long),
)
assert res.keys() == expected.keys()
- assert_allclose(res['src'], expected['src'], atol=1e-4, rtol=1e-4)
- assert_allclose(res['dst'], expected['dst'], atol=1e-4, rtol=1e-4)
+ assert_allclose(res['src'].to(device=device), expected['src'], atol=1e-4, rtol=1e-4)
+ assert_allclose(res['dst'].to(device=device), expected['dst'], atol=1e-4, rtol=1e-4)
def test_same_on_batch(self, device, dtype):
pass
@@ -497,8 +497,8 @@ class TestCenterCropGen(RandomGeneratorBaseTests):
class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
- @pytest.mark.parametrize('batch_size', [1, 8])
- @pytest.mark.parametrize('kernel_size', [1, (3, 5)])
+ @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('same_on_batch', [True, False])
@@ -510,17 +510,17 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
same_on_batch=same_on_batch)
@pytest.mark.parametrize('kernel_size,angle,direction', [
- pytest.param(4, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param(1, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param((1, 2, 3), torch.tensor([(10, 30), (30, 60), (60, 90)]),
- torch.tensor([-1, 1]), marks=pytest.mark.xfail),
- pytest.param(3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-2, 1]), marks=pytest.mark.xfail),
- pytest.param(3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 2]), marks=pytest.mark.xfail),
+ (4, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
+ (1, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
+ ((3, 4, 5), torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 1])),
+ (3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-2, 1])),
+ (3, torch.tensor([(10, 30), (30, 60), (60, 90)]), torch.tensor([-1, 2])),
])
def test_invalid_param_combinations(self, kernel_size, angle, direction, device, dtype):
- random_motion_blur_generator3d(
- batch_size=8, kernel_size=kernel_size, angle=angle.to(device=device, dtype=dtype),
- direction=direction.to(device=device, dtype=dtype))
+ with pytest.raises(Exception):
+ random_motion_blur_generator3d(
+ batch_size=8, kernel_size=kernel_size, angle=angle.to(device=device, dtype=dtype),
+ direction=direction.to(device=device, dtype=dtype))
def test_random_gen(self, device, dtype):
torch.manual_seed(42)
@@ -530,11 +530,11 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype), same_on_batch=False)
expected = dict(
- ksize_factor=torch.tensor([3., 3.], device=device, dtype=torch.int32),
+ ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor([
- [11.1631, 33.7076, 75.7852],
- [11.2582, 31.5774, 74.3035]], device=device, dtype=dtype),
- direction_factor=torch.tensor([0.9105, 0.8575], device=device, dtype=dtype)
+ [27.6454, 41.4859, 71.7134],
+ [28.3001, 58.7792, 78.0269]], device=device, dtype=dtype),
+ direction_factor=torch.tensor([-0.4869, 0.5873], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
@@ -549,11 +549,11 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):
batch_size=2, kernel_size=3, angle=angle.to(device=device, dtype=dtype),
direction=direction.to(device=device, dtype=dtype), same_on_batch=True)
expected = dict(
- ksize_factor=torch.tensor([3., 3.], device=device, dtype=torch.int32),
+ ksize_factor=torch.tensor([3, 3], device=device, dtype=torch.int32),
angle_factor=torch.tensor([
- [11.1631, 31.8873, 63.7076],
- [11.1631, 31.8873, 63.7076]], device=device, dtype=dtype),
- direction_factor=torch.tensor([-0.8948, -0.8948], device=device, dtype=dtype)
+ [27.6454, 57.4501, 71.4859],
+ [27.6454, 57.4501, 71.4859]], device=device, dtype=dtype),
+ direction_factor=torch.tensor([0.9186, 0.9186], device=device, dtype=dtype)
)
assert res.keys() == expected.keys()
assert_allclose(res['ksize_factor'], expected['ksize_factor'], rtol=1e-4, atol=1e-4)
diff --git a/test/geometry/epipolar/test_triangulation.py b/test/geometry/epipolar/test_triangulation.py
index c5729db99..92e5a160d 100644
--- a/test/geometry/epipolar/test_triangulation.py
+++ b/test/geometry/epipolar/test_triangulation.py
@@ -41,7 +41,7 @@ class TestTriangulation:
x_reprojected = kornia.transform_points(scene['P'], X.expand(num_views, -1, -1))
assert_allclose(scene['points3d'], X, rtol=1e-4, atol=1e-4)
- assert_allclose(scene['points2d'], x_reprojected)
+ assert_allclose(scene['points2d'], x_reprojected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device):
points1 = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)