_deprecated.py 1.9 KB
Newer Older
1
import warnings
2
from typing import Any, Dict, Union
3

4
5
import numpy as np
import PIL.Image
6
import torch
7
from torchvision.transforms import functional as _F
8

9
10
from torchvision.transforms.v2 import Transform

11

12
class ToTensor(Transform):
13
    """[DEPRECATED] Use ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`` instead.
Nicolas Hug's avatar
Nicolas Hug committed
14
15

    Convert a PIL Image or ndarray to tensor and scale the values accordingly.
16
17
18

    .. warning::
        :class:`v2.ToTensor` is deprecated and will be removed in a future release.
Nicolas Hug's avatar
Nicolas Hug committed
19
        Please use instead ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])``.
20
        Output is equivalent up to float precision.
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

    This transform does not support torchscript.


    Converts a PIL Image or numpy.ndarray (H x W x C) in the range
    [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
    if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)
    or if the numpy.ndarray has dtype = np.uint8

    In the other cases, tensors are returned without scaling.

    .. note::
        Because the input image is scaled to [0.0, 1.0], this transformation should not be used when
        transforming target image masks. See the `references`_ for implementing the transforms for image masks.

    .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation
    """

39
    _transformed_types = (PIL.Image.Image, np.ndarray)
40

41
42
43
    def __init__(self) -> None:
        warnings.warn(
            "The transform `ToTensor()` is deprecated and will be removed in a future release. "
Nicolas Hug's avatar
Nicolas Hug committed
44
            "Instead, please use `v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`."
45
            "Output is equivalent up to float precision."
46
47
48
        )
        super().__init__()

49
    def _transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: Dict[str, Any]) -> torch.Tensor:
50
        return _F.to_tensor(inpt)