_deprecated.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import warnings
  2. from typing import Any, Dict, Union
  3. import numpy as np
  4. import PIL.Image
  5. import torch
  6. from torchvision.transforms import functional as _F
  7. from torchvision.transforms.v2 import Transform
  8. class ToTensor(Transform):
  9. """[DEPRECATED] Use ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`` instead.
  10. Convert a PIL Image or ndarray to tensor and scale the values accordingly.
  11. .. warning::
  12. :class:`v2.ToTensor` is deprecated and will be removed in a future release.
  13. Please use instead ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])``.
  14. This transform does not support torchscript.
  15. Converts a PIL Image or numpy.ndarray (H x W x C) in the range
  16. [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
  17. if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)
  18. or if the numpy.ndarray has dtype = np.uint8
  19. In the other cases, tensors are returned without scaling.
  20. .. note::
  21. Because the input image is scaled to [0.0, 1.0], this transformation should not be used when
  22. transforming target image masks. See the `references`_ for implementing the transforms for image masks.
  23. .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation
  24. """
  25. _transformed_types = (PIL.Image.Image, np.ndarray)
  26. def __init__(self) -> None:
  27. warnings.warn(
  28. "The transform `ToTensor()` is deprecated and will be removed in a future release. "
  29. "Instead, please use `v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`."
  30. )
  31. super().__init__()
  32. def _transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: Dict[str, Any]) -> torch.Tensor:
  33. return _F.to_tensor(inpt)