_augment.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import math
  2. import numbers
  3. import warnings
  4. from typing import Any, Callable, Dict, List, Tuple
  5. import PIL.Image
  6. import torch
  7. from torch.nn.functional import one_hot
  8. from torch.utils._pytree import tree_flatten, tree_unflatten
  9. from torchvision import transforms as _transforms, tv_tensors
  10. from torchvision.transforms.v2 import functional as F
  11. from ._transform import _RandomApplyTransform, Transform
  12. from ._utils import _parse_labels_getter, has_any, is_pure_tensor, query_chw, query_size
  13. class RandomErasing(_RandomApplyTransform):
  14. """Randomly select a rectangle region in the input image or video and erase its pixels.
  15. This transform does not support PIL Image.
  16. 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896
  17. Args:
  18. p (float, optional): probability that the random erasing operation will be performed.
  19. scale (tuple of float, optional): range of proportion of erased area against input image.
  20. ratio (tuple of float, optional): range of aspect ratio of erased area.
  21. value (number or tuple of numbers): erasing value. Default is 0. If a single int, it is used to
  22. erase all pixels. If a tuple of length 3, it is used to erase
  23. R, G, B channels respectively.
  24. If a str of 'random', erasing each pixel with random values.
  25. inplace (bool, optional): boolean to make this transform inplace. Default set to False.
  26. Returns:
  27. Erased input.
  28. Example:
  29. >>> from torchvision.transforms import v2 as transforms
  30. >>>
  31. >>> transform = transforms.Compose([
  32. >>> transforms.RandomHorizontalFlip(),
  33. >>> transforms.PILToTensor(),
  34. >>> transforms.ConvertImageDtype(torch.float),
  35. >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
  36. >>> transforms.RandomErasing(),
  37. >>> ])
  38. """
  39. _v1_transform_cls = _transforms.RandomErasing
  40. def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
  41. return dict(
  42. super()._extract_params_for_v1_transform(),
  43. value="random" if self.value is None else self.value,
  44. )
  45. def __init__(
  46. self,
  47. p: float = 0.5,
  48. scale: Tuple[float, float] = (0.02, 0.33),
  49. ratio: Tuple[float, float] = (0.3, 3.3),
  50. value: float = 0.0,
  51. inplace: bool = False,
  52. ):
  53. super().__init__(p=p)
  54. if not isinstance(value, (numbers.Number, str, tuple, list)):
  55. raise TypeError("Argument value should be either a number or str or a sequence")
  56. if isinstance(value, str) and value != "random":
  57. raise ValueError("If value is str, it should be 'random'")
  58. if not isinstance(scale, (tuple, list)):
  59. raise TypeError("Scale should be a sequence")
  60. if not isinstance(ratio, (tuple, list)):
  61. raise TypeError("Ratio should be a sequence")
  62. if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
  63. warnings.warn("Scale and ratio should be of kind (min, max)")
  64. if scale[0] < 0 or scale[1] > 1:
  65. raise ValueError("Scale should be between 0 and 1")
  66. self.scale = scale
  67. self.ratio = ratio
  68. if isinstance(value, (int, float)):
  69. self.value = [float(value)]
  70. elif isinstance(value, str):
  71. self.value = None
  72. elif isinstance(value, (list, tuple)):
  73. self.value = [float(v) for v in value]
  74. else:
  75. self.value = value
  76. self.inplace = inplace
  77. self._log_ratio = torch.log(torch.tensor(self.ratio))
  78. def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any:
  79. if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.Mask)):
  80. warnings.warn(
  81. f"{type(self).__name__}() is currently passing through inputs of type "
  82. f"tv_tensors.{type(inpt).__name__}. This will likely change in the future."
  83. )
  84. return super()._call_kernel(functional, inpt, *args, **kwargs)
  85. def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
  86. img_c, img_h, img_w = query_chw(flat_inputs)
  87. if self.value is not None and not (len(self.value) in (1, img_c)):
  88. raise ValueError(
  89. f"If value is a sequence, it should have either a single value or {img_c} (number of inpt channels)"
  90. )
  91. area = img_h * img_w
  92. log_ratio = self._log_ratio
  93. for _ in range(10):
  94. erase_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()
  95. aspect_ratio = torch.exp(
  96. torch.empty(1).uniform_(
  97. log_ratio[0], # type: ignore[arg-type]
  98. log_ratio[1], # type: ignore[arg-type]
  99. )
  100. ).item()
  101. h = int(round(math.sqrt(erase_area * aspect_ratio)))
  102. w = int(round(math.sqrt(erase_area / aspect_ratio)))
  103. if not (h < img_h and w < img_w):
  104. continue
  105. if self.value is None:
  106. v = torch.empty([img_c, h, w], dtype=torch.float32).normal_()
  107. else:
  108. v = torch.tensor(self.value)[:, None, None]
  109. i = torch.randint(0, img_h - h + 1, size=(1,)).item()
  110. j = torch.randint(0, img_w - w + 1, size=(1,)).item()
  111. break
  112. else:
  113. i, j, h, w, v = 0, 0, img_h, img_w, None
  114. return dict(i=i, j=j, h=h, w=w, v=v)
  115. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  116. if params["v"] is not None:
  117. inpt = self._call_kernel(F.erase, inpt, **params, inplace=self.inplace)
  118. return inpt
  119. class _BaseMixUpCutMix(Transform):
  120. def __init__(self, *, alpha: float = 1.0, num_classes: int, labels_getter="default") -> None:
  121. super().__init__()
  122. self.alpha = float(alpha)
  123. self._dist = torch.distributions.Beta(torch.tensor([alpha]), torch.tensor([alpha]))
  124. self.num_classes = num_classes
  125. self._labels_getter = _parse_labels_getter(labels_getter)
  126. def forward(self, *inputs):
  127. inputs = inputs if len(inputs) > 1 else inputs[0]
  128. flat_inputs, spec = tree_flatten(inputs)
  129. needs_transform_list = self._needs_transform_list(flat_inputs)
  130. if has_any(flat_inputs, PIL.Image.Image, tv_tensors.BoundingBoxes, tv_tensors.Mask):
  131. raise ValueError(f"{type(self).__name__}() does not support PIL images, bounding boxes and masks.")
  132. labels = self._labels_getter(inputs)
  133. if not isinstance(labels, torch.Tensor):
  134. raise ValueError(f"The labels must be a tensor, but got {type(labels)} instead.")
  135. elif labels.ndim != 1:
  136. raise ValueError(
  137. f"labels tensor should be of shape (batch_size,) " f"but got shape {labels.shape} instead."
  138. )
  139. params = {
  140. "labels": labels,
  141. "batch_size": labels.shape[0],
  142. **self._get_params(
  143. [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform]
  144. ),
  145. }
  146. # By default, the labels will be False inside needs_transform_list, since they are a torch.Tensor coming
  147. # after an image or video. However, we need to handle them in _transform, so we make sure to set them to True
  148. needs_transform_list[next(idx for idx, inpt in enumerate(flat_inputs) if inpt is labels)] = True
  149. flat_outputs = [
  150. self._transform(inpt, params) if needs_transform else inpt
  151. for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list)
  152. ]
  153. return tree_unflatten(flat_outputs, spec)
  154. def _check_image_or_video(self, inpt: torch.Tensor, *, batch_size: int):
  155. expected_num_dims = 5 if isinstance(inpt, tv_tensors.Video) else 4
  156. if inpt.ndim != expected_num_dims:
  157. raise ValueError(
  158. f"Expected a batched input with {expected_num_dims} dims, but got {inpt.ndim} dimensions instead."
  159. )
  160. if inpt.shape[0] != batch_size:
  161. raise ValueError(
  162. f"The batch size of the image or video does not match the batch size of the labels: "
  163. f"{inpt.shape[0]} != {batch_size}."
  164. )
  165. def _mixup_label(self, label: torch.Tensor, *, lam: float) -> torch.Tensor:
  166. label = one_hot(label, num_classes=self.num_classes)
  167. if not label.dtype.is_floating_point:
  168. label = label.float()
  169. return label.roll(1, 0).mul_(1.0 - lam).add_(label.mul(lam))
  170. class MixUp(_BaseMixUpCutMix):
  171. """Apply MixUp to the provided batch of images and labels.
  172. Paper: `mixup: Beyond Empirical Risk Minimization <https://arxiv.org/abs/1710.09412>`_.
  173. .. note::
  174. This transform is meant to be used on **batches** of samples, not
  175. individual images. See
  176. :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage
  177. examples.
  178. The sample pairing is deterministic and done by matching consecutive
  179. samples in the batch, so the batch needs to be shuffled (this is an
  180. implementation detail, not a guaranteed convention.)
  181. In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed
  182. into a tensor of shape ``(batch_size, num_classes)``.
  183. Args:
  184. alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1.
  185. num_classes (int): number of classes in the batch. Used for one-hot-encoding.
  186. labels_getter (callable or "default", optional): indicates how to identify the labels in the input.
  187. By default, this will pick the second parameter as the labels if it's a tensor. This covers the most
  188. common scenario where this transform is called as ``MixUp()(imgs_batch, labels_batch)``.
  189. It can also be a callable that takes the same input as the transform, and returns the labels.
  190. """
  191. def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
  192. return dict(lam=float(self._dist.sample(()))) # type: ignore[arg-type]
  193. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  194. lam = params["lam"]
  195. if inpt is params["labels"]:
  196. return self._mixup_label(inpt, lam=lam)
  197. elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt):
  198. self._check_image_or_video(inpt, batch_size=params["batch_size"])
  199. output = inpt.roll(1, 0).mul_(1.0 - lam).add_(inpt.mul(lam))
  200. if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)):
  201. output = tv_tensors.wrap(output, like=inpt)
  202. return output
  203. else:
  204. return inpt
  205. class CutMix(_BaseMixUpCutMix):
  206. """Apply CutMix to the provided batch of images and labels.
  207. Paper: `CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features
  208. <https://arxiv.org/abs/1905.04899>`_.
  209. .. note::
  210. This transform is meant to be used on **batches** of samples, not
  211. individual images. See
  212. :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage
  213. examples.
  214. The sample pairing is deterministic and done by matching consecutive
  215. samples in the batch, so the batch needs to be shuffled (this is an
  216. implementation detail, not a guaranteed convention.)
  217. In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed
  218. into a tensor of shape ``(batch_size, num_classes)``.
  219. Args:
  220. alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1.
  221. num_classes (int): number of classes in the batch. Used for one-hot-encoding.
  222. labels_getter (callable or "default", optional): indicates how to identify the labels in the input.
  223. By default, this will pick the second parameter as the labels if it's a tensor. This covers the most
  224. common scenario where this transform is called as ``CutMix()(imgs_batch, labels_batch)``.
  225. It can also be a callable that takes the same input as the transform, and returns the labels.
  226. """
  227. def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
  228. lam = float(self._dist.sample(())) # type: ignore[arg-type]
  229. H, W = query_size(flat_inputs)
  230. r_x = torch.randint(W, size=(1,))
  231. r_y = torch.randint(H, size=(1,))
  232. r = 0.5 * math.sqrt(1.0 - lam)
  233. r_w_half = int(r * W)
  234. r_h_half = int(r * H)
  235. x1 = int(torch.clamp(r_x - r_w_half, min=0))
  236. y1 = int(torch.clamp(r_y - r_h_half, min=0))
  237. x2 = int(torch.clamp(r_x + r_w_half, max=W))
  238. y2 = int(torch.clamp(r_y + r_h_half, max=H))
  239. box = (x1, y1, x2, y2)
  240. lam_adjusted = float(1.0 - (x2 - x1) * (y2 - y1) / (W * H))
  241. return dict(box=box, lam_adjusted=lam_adjusted)
  242. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  243. if inpt is params["labels"]:
  244. return self._mixup_label(inpt, lam=params["lam_adjusted"])
  245. elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt):
  246. self._check_image_or_video(inpt, batch_size=params["batch_size"])
  247. x1, y1, x2, y2 = params["box"]
  248. rolled = inpt.roll(1, 0)
  249. output = inpt.clone()
  250. output[..., y1:y2, x1:x2] = rolled[..., y1:y2, x1:x2]
  251. if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)):
  252. output = tv_tensors.wrap(output, like=inpt)
  253. return output
  254. else:
  255. return inpt