ToTensor

class paddle.vision.transforms. ToTensor ( data_format='CHW', keys=None ) [source]

Convert a PIL.Image or numpy.ndarray to paddle.Tensor.

Converts a PIL.Image or numpy.ndarray (H x W x C) to a paddle.Tensor of shape (C x H x W).

If input is a grayscale image (H x W), it will be converted to an image of shape (H x W x 1). And the shape of output tensor will be (1 x H x W).

If you want to keep the shape of output tensor as (H x W x C), you can set data_format = HWC .

Converts a PIL.Image or numpy.ndarray in the range [0, 255] to a paddle.Tensor 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.

Parameters
  • data_format (str, optional) – Data format of output tensor, should be ‘HWC’ or ‘CHW’. Default: ‘CHW’.

  • keys (list[str]|tuple[str], optional) – Same as BaseTransform. Default: None.

Shape:
  • img(PIL.Image|np.ndarray): The input image with shape (H x W x C).

  • output(np.ndarray): A tensor with shape (C x H x W) or (H x W x C) according option data_format.

Returns

A callable object of ToTensor.

Examples

import numpy as np
from PIL import Image

import paddle.vision.transforms as T
import paddle.vision.transforms.functional as F

fake_img = Image.fromarray((np.random.rand(4, 5, 3) * 255.).astype(np.uint8))

transform = T.ToTensor()

tensor = transform(fake_img)

print(tensor.shape)
# [3, 4, 5]

print(tensor.dtype)
# paddle.float32

Used in the guide/tutorials