_misc.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. import warnings
  2. from typing import Any, Callable, cast, Dict, List, Optional, Sequence, Type, Union
  3. import PIL.Image
  4. import torch
  5. from torch.utils._pytree import tree_flatten, tree_unflatten
  6. from torchvision import transforms as _transforms, tv_tensors
  7. from torchvision.transforms.v2 import functional as F, Transform
  8. from ._utils import _parse_labels_getter, _setup_number_or_seq, _setup_size, get_bounding_boxes, has_any, is_pure_tensor
  9. # TODO: do we want/need to expose this?
  10. class Identity(Transform):
  11. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  12. return inpt
  13. class Lambda(Transform):
  14. """Apply a user-defined function as a transform.
  15. This transform does not support torchscript.
  16. Args:
  17. lambd (function): Lambda/function to be used for transform.
  18. """
  19. _transformed_types = (object,)
  20. def __init__(self, lambd: Callable[[Any], Any], *types: Type):
  21. super().__init__()
  22. self.lambd = lambd
  23. self.types = types or self._transformed_types
  24. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  25. if isinstance(inpt, self.types):
  26. return self.lambd(inpt)
  27. else:
  28. return inpt
  29. def extra_repr(self) -> str:
  30. extras = []
  31. name = getattr(self.lambd, "__name__", None)
  32. if name:
  33. extras.append(name)
  34. extras.append(f"types={[type.__name__ for type in self.types]}")
  35. return ", ".join(extras)
  36. class LinearTransformation(Transform):
  37. """Transform a tensor image or video with a square transformation matrix and a mean_vector computed offline.
  38. This transform does not support PIL Image.
  39. Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and
  40. subtract mean_vector from it which is then followed by computing the dot
  41. product with the transformation matrix and then reshaping the tensor to its
  42. original shape.
  43. Applications:
  44. whitening transformation: Suppose X is a column vector zero-centered data.
  45. Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X),
  46. perform SVD on this matrix and pass it as transformation_matrix.
  47. Args:
  48. transformation_matrix (Tensor): tensor [D x D], D = C x H x W
  49. mean_vector (Tensor): tensor [D], D = C x H x W
  50. """
  51. _v1_transform_cls = _transforms.LinearTransformation
  52. _transformed_types = (is_pure_tensor, tv_tensors.Image, tv_tensors.Video)
  53. def __init__(self, transformation_matrix: torch.Tensor, mean_vector: torch.Tensor):
  54. super().__init__()
  55. if transformation_matrix.size(0) != transformation_matrix.size(1):
  56. raise ValueError(
  57. "transformation_matrix should be square. Got "
  58. f"{tuple(transformation_matrix.size())} rectangular matrix."
  59. )
  60. if mean_vector.size(0) != transformation_matrix.size(0):
  61. raise ValueError(
  62. f"mean_vector should have the same length {mean_vector.size(0)}"
  63. f" as any one of the dimensions of the transformation_matrix [{tuple(transformation_matrix.size())}]"
  64. )
  65. if transformation_matrix.device != mean_vector.device:
  66. raise ValueError(
  67. f"Input tensors should be on the same device. Got {transformation_matrix.device} and {mean_vector.device}"
  68. )
  69. if transformation_matrix.dtype != mean_vector.dtype:
  70. raise ValueError(
  71. f"Input tensors should have the same dtype. Got {transformation_matrix.dtype} and {mean_vector.dtype}"
  72. )
  73. self.transformation_matrix = transformation_matrix
  74. self.mean_vector = mean_vector
  75. def _check_inputs(self, sample: Any) -> Any:
  76. if has_any(sample, PIL.Image.Image):
  77. raise TypeError(f"{type(self).__name__}() does not support PIL images.")
  78. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  79. shape = inpt.shape
  80. n = shape[-3] * shape[-2] * shape[-1]
  81. if n != self.transformation_matrix.shape[0]:
  82. raise ValueError(
  83. "Input tensor and transformation matrix have incompatible shape."
  84. + f"[{shape[-3]} x {shape[-2]} x {shape[-1]}] != "
  85. + f"{self.transformation_matrix.shape[0]}"
  86. )
  87. if inpt.device.type != self.mean_vector.device.type:
  88. raise ValueError(
  89. "Input tensor should be on the same device as transformation matrix and mean vector. "
  90. f"Got {inpt.device} vs {self.mean_vector.device}"
  91. )
  92. flat_inpt = inpt.reshape(-1, n) - self.mean_vector
  93. transformation_matrix = self.transformation_matrix.to(flat_inpt.dtype)
  94. output = torch.mm(flat_inpt, transformation_matrix)
  95. output = output.reshape(shape)
  96. if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)):
  97. output = tv_tensors.wrap(output, like=inpt)
  98. return output
  99. class Normalize(Transform):
  100. """Normalize a tensor image or video with mean and standard deviation.
  101. This transform does not support PIL Image.
  102. Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``
  103. channels, this transform will normalize each channel of the input
  104. ``torch.*Tensor`` i.e.,
  105. ``output[channel] = (input[channel] - mean[channel]) / std[channel]``
  106. .. note::
  107. This transform acts out of place, i.e., it does not mutate the input tensor.
  108. Args:
  109. mean (sequence): Sequence of means for each channel.
  110. std (sequence): Sequence of standard deviations for each channel.
  111. inplace(bool,optional): Bool to make this operation in-place.
  112. """
  113. _v1_transform_cls = _transforms.Normalize
  114. def __init__(self, mean: Sequence[float], std: Sequence[float], inplace: bool = False):
  115. super().__init__()
  116. self.mean = list(mean)
  117. self.std = list(std)
  118. self.inplace = inplace
  119. def _check_inputs(self, sample: Any) -> Any:
  120. if has_any(sample, PIL.Image.Image):
  121. raise TypeError(f"{type(self).__name__}() does not support PIL images.")
  122. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  123. return self._call_kernel(F.normalize, inpt, mean=self.mean, std=self.std, inplace=self.inplace)
  124. class GaussianBlur(Transform):
  125. """Blurs image with randomly chosen Gaussian blur.
  126. If the input is a Tensor, it is expected
  127. to have [..., C, H, W] shape, where ... means an arbitrary number of leading dimensions.
  128. Args:
  129. kernel_size (int or sequence): Size of the Gaussian kernel.
  130. sigma (float or tuple of float (min, max)): Standard deviation to be used for
  131. creating kernel to perform blurring. If float, sigma is fixed. If it is tuple
  132. of float (min, max), sigma is chosen uniformly at random to lie in the
  133. given range.
  134. """
  135. _v1_transform_cls = _transforms.GaussianBlur
  136. def __init__(
  137. self, kernel_size: Union[int, Sequence[int]], sigma: Union[int, float, Sequence[float]] = (0.1, 2.0)
  138. ) -> None:
  139. super().__init__()
  140. self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers")
  141. for ks in self.kernel_size:
  142. if ks <= 0 or ks % 2 == 0:
  143. raise ValueError("Kernel size value should be an odd and positive number.")
  144. self.sigma = _setup_number_or_seq(sigma, "sigma")
  145. if not 0.0 < self.sigma[0] <= self.sigma[1]:
  146. raise ValueError(f"sigma values should be positive and of the form (min, max). Got {self.sigma}")
  147. def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
  148. sigma = torch.empty(1).uniform_(self.sigma[0], self.sigma[1]).item()
  149. return dict(sigma=[sigma, sigma])
  150. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  151. return self._call_kernel(F.gaussian_blur, inpt, self.kernel_size, **params)
  152. class ToDtype(Transform):
  153. """Converts the input to a specific dtype, optionally scaling the values for images or videos.
  154. .. note::
  155. ``ToDtype(dtype, scale=True)`` is the recommended replacement for ``ConvertImageDtype(dtype)``.
  156. Args:
  157. dtype (``torch.dtype`` or dict of ``TVTensor`` -> ``torch.dtype``): The dtype to convert to.
  158. If a ``torch.dtype`` is passed, e.g. ``torch.float32``, only images and videos will be converted
  159. to that dtype: this is for compatibility with :class:`~torchvision.transforms.v2.ConvertImageDtype`.
  160. A dict can be passed to specify per-tv_tensor conversions, e.g.
  161. ``dtype={tv_tensors.Image: torch.float32, tv_tensors.Mask: torch.int64, "others":None}``. The "others"
  162. key can be used as a catch-all for any other tv_tensor type, and ``None`` means no conversion.
  163. scale (bool, optional): Whether to scale the values for images or videos. See :ref:`range_and_dtype`.
  164. Default: ``False``.
  165. """
  166. _transformed_types = (torch.Tensor,)
  167. def __init__(
  168. self, dtype: Union[torch.dtype, Dict[Union[Type, str], Optional[torch.dtype]]], scale: bool = False
  169. ) -> None:
  170. super().__init__()
  171. if not isinstance(dtype, (dict, torch.dtype)):
  172. raise ValueError(f"dtype must be a dict or a torch.dtype, got {type(dtype)} instead")
  173. if (
  174. isinstance(dtype, dict)
  175. and torch.Tensor in dtype
  176. and any(cls in dtype for cls in [tv_tensors.Image, tv_tensors.Video])
  177. ):
  178. warnings.warn(
  179. "Got `dtype` values for `torch.Tensor` and either `tv_tensors.Image` or `tv_tensors.Video`. "
  180. "Note that a plain `torch.Tensor` will *not* be transformed by this (or any other transformation) "
  181. "in case a `tv_tensors.Image` or `tv_tensors.Video` is present in the input."
  182. )
  183. self.dtype = dtype
  184. self.scale = scale
  185. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  186. if isinstance(self.dtype, torch.dtype):
  187. # For consistency / BC with ConvertImageDtype, we only care about images or videos when dtype
  188. # is a simple torch.dtype
  189. if not is_pure_tensor(inpt) and not isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)):
  190. return inpt
  191. dtype: Optional[torch.dtype] = self.dtype
  192. elif type(inpt) in self.dtype:
  193. dtype = self.dtype[type(inpt)]
  194. elif "others" in self.dtype:
  195. dtype = self.dtype["others"]
  196. else:
  197. raise ValueError(
  198. f"No dtype was specified for type {type(inpt)}. "
  199. "If you only need to convert the dtype of images or videos, you can just pass e.g. dtype=torch.float32. "
  200. "If you're passing a dict as dtype, "
  201. 'you can use "others" as a catch-all key '
  202. 'e.g. dtype={tv_tensors.Mask: torch.int64, "others": None} to pass-through the rest of the inputs.'
  203. )
  204. supports_scaling = is_pure_tensor(inpt) or isinstance(inpt, (tv_tensors.Image, tv_tensors.Video))
  205. if dtype is None:
  206. if self.scale and supports_scaling:
  207. warnings.warn(
  208. "scale was set to True but no dtype was specified for images or videos: no scaling will be done."
  209. )
  210. return inpt
  211. return self._call_kernel(F.to_dtype, inpt, dtype=dtype, scale=self.scale)
  212. class ConvertImageDtype(Transform):
  213. """[DEPRECATED] Use ``v2.ToDtype(dtype, scale=True)`` instead.
  214. Convert input image to the given ``dtype`` and scale the values accordingly.
  215. .. warning::
  216. Consider using ``ToDtype(dtype, scale=True)`` instead. See :class:`~torchvision.transforms.v2.ToDtype`.
  217. This function does not support PIL Image.
  218. Args:
  219. dtype (torch.dtype): Desired data type of the output
  220. .. note::
  221. When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
  222. If converted back and forth, this mismatch has no effect.
  223. Raises:
  224. RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as
  225. well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to
  226. overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
  227. of the integer ``dtype``.
  228. """
  229. _v1_transform_cls = _transforms.ConvertImageDtype
  230. def __init__(self, dtype: torch.dtype = torch.float32) -> None:
  231. super().__init__()
  232. self.dtype = dtype
  233. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  234. return self._call_kernel(F.to_dtype, inpt, dtype=self.dtype, scale=True)
  235. class SanitizeBoundingBoxes(Transform):
  236. """Remove degenerate/invalid bounding boxes and their corresponding labels and masks.
  237. This transform removes bounding boxes and their associated labels/masks that:
  238. - are below a given ``min_size``: by default this also removes degenerate boxes that have e.g. X2 <= X1.
  239. - have any coordinate outside of their corresponding image. You may want to
  240. call :class:`~torchvision.transforms.v2.ClampBoundingBoxes` first to avoid undesired removals.
  241. It is recommended to call it at the end of a pipeline, before passing the
  242. input to the models. It is critical to call this transform if
  243. :class:`~torchvision.transforms.v2.RandomIoUCrop` was called.
  244. If you want to be extra careful, you may call it after all transforms that
  245. may modify bounding boxes but once at the end should be enough in most
  246. cases.
  247. Args:
  248. min_size (float, optional) The size below which bounding boxes are removed. Default is 1.
  249. labels_getter (callable or str or None, optional): indicates how to identify the labels in the input.
  250. By default, this will try to find a "labels" key in the input (case-insensitive), if
  251. the input is a dict or it is a tuple whose second element is a dict.
  252. This heuristic should work well with a lot of datasets, including the built-in torchvision datasets.
  253. It can also be a callable that takes the same input
  254. as the transform, and returns the labels.
  255. """
  256. def __init__(
  257. self,
  258. min_size: float = 1.0,
  259. labels_getter: Union[Callable[[Any], Optional[torch.Tensor]], str, None] = "default",
  260. ) -> None:
  261. super().__init__()
  262. if min_size < 1:
  263. raise ValueError(f"min_size must be >= 1, got {min_size}.")
  264. self.min_size = min_size
  265. self.labels_getter = labels_getter
  266. self._labels_getter = _parse_labels_getter(labels_getter)
  267. def forward(self, *inputs: Any) -> Any:
  268. inputs = inputs if len(inputs) > 1 else inputs[0]
  269. labels = self._labels_getter(inputs)
  270. if labels is not None and not isinstance(labels, torch.Tensor):
  271. raise ValueError(
  272. f"The labels in the input to forward() must be a tensor or None, got {type(labels)} instead."
  273. )
  274. flat_inputs, spec = tree_flatten(inputs)
  275. boxes = get_bounding_boxes(flat_inputs)
  276. if labels is not None and boxes.shape[0] != labels.shape[0]:
  277. raise ValueError(
  278. f"Number of boxes (shape={boxes.shape}) and number of labels (shape={labels.shape}) do not match."
  279. )
  280. boxes = cast(
  281. tv_tensors.BoundingBoxes,
  282. F.convert_bounding_box_format(
  283. boxes,
  284. new_format=tv_tensors.BoundingBoxFormat.XYXY,
  285. ),
  286. )
  287. ws, hs = boxes[:, 2] - boxes[:, 0], boxes[:, 3] - boxes[:, 1]
  288. valid = (ws >= self.min_size) & (hs >= self.min_size) & (boxes >= 0).all(dim=-1)
  289. # TODO: Do we really need to check for out of bounds here? All
  290. # transforms should be clamping anyway, so this should never happen?
  291. image_h, image_w = boxes.canvas_size
  292. valid &= (boxes[:, 0] <= image_w) & (boxes[:, 2] <= image_w)
  293. valid &= (boxes[:, 1] <= image_h) & (boxes[:, 3] <= image_h)
  294. params = dict(valid=valid.as_subclass(torch.Tensor), labels=labels)
  295. flat_outputs = [
  296. # Even-though it may look like we're transforming all inputs, we don't:
  297. # _transform() will only care about BoundingBoxeses and the labels
  298. self._transform(inpt, params)
  299. for inpt in flat_inputs
  300. ]
  301. return tree_unflatten(flat_outputs, spec)
  302. def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
  303. is_label = inpt is not None and inpt is params["labels"]
  304. is_bounding_boxes_or_mask = isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.Mask))
  305. if not (is_label or is_bounding_boxes_or_mask):
  306. return inpt
  307. output = inpt[params["valid"]]
  308. if is_label:
  309. return output
  310. return tv_tensors.wrap(output, like=inpt)