_deprecated.py 1.8 KB

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