_image.py 1.88 KB
Newer Older
1
2
from __future__ import annotations

3
from typing import Any, Optional, Union
Philip Meier's avatar
Philip Meier committed
4

5
import PIL.Image
Philip Meier's avatar
Philip Meier committed
6
7
import torch

8
from ._datapoint import Datapoint
9
10


11
class Image(Datapoint):
Philip Meier's avatar
Philip Meier committed
12
13
14
15
16
17
18
19
20
21
22
23
24
    """[BETA] :class:`torch.Tensor` subclass for images.

    Args:
        data (tensor-like, PIL.Image.Image): Any data that can be turned into a tensor with :func:`torch.as_tensor` as
            well as PIL images.
        dtype (torch.dtype, optional): Desired data type of the bounding box. If omitted, will be inferred from
            ``data``.
        device (torch.device, optional): Desired device of the bounding box. If omitted and ``data`` is a
            :class:`torch.Tensor`, the device is taken from it. Otherwise, the bounding box is constructed on the CPU.
        requires_grad (bool, optional): Whether autograd should record operations on the bounding box. If omitted and
            ``data`` is a :class:`torch.Tensor`, the value is taken from it. Otherwise, defaults to ``False``.
    """

25
26
27
28
    def __new__(
        cls,
        data: Any,
        *,
29
30
        dtype: Optional[torch.dtype] = None,
        device: Optional[Union[torch.device, str, int]] = None,
31
        requires_grad: Optional[bool] = None,
32
    ) -> Image:
33
        if isinstance(data, PIL.Image.Image):
34
            from torchvision.transforms.v2 import functional as F
35
36
37

            data = F.pil_to_tensor(data)

38
39
        tensor = cls._to_tensor(data, dtype=dtype, device=device, requires_grad=requires_grad)
        if tensor.ndim < 2:
40
            raise ValueError
41
42
        elif tensor.ndim == 2:
            tensor = tensor.unsqueeze(0)
43

44
        return tensor.as_subclass(cls)
45

46
    def __repr__(self, *, tensor_contents: Any = None) -> str:  # type: ignore[override]
47
        return self._make_repr()
48

49

Philip Meier's avatar
Philip Meier committed
50
51
52
53
_ImageType = Union[torch.Tensor, PIL.Image.Image, Image]
_ImageTypeJIT = torch.Tensor
_TensorImageType = Union[torch.Tensor, Image]
_TensorImageTypeJIT = torch.Tensor