Image.tensor#

Image.tensor(device: str = 'cpu', normalize: str | tuple[Any, Any] | None = None, dtype: Any = None) torch.Tensor[source]#

Convert image to a PyTorch tensor.

The returned tensor has shape (1, C, H, W) for multi-plane images and (1, 1, H, W) for single-plane images, with pixel values preserved in their original dtype.

Parameters:
  • device (str, optional) – target device for the tensor (e.g. “cpu”, “cuda” or “mps”), defaults to “cpu”

  • normalize (str or tuple or None, optional) – normalization to apply to pixel values, either “imagenet” for standard ImageNet scaling or a tuple of (mean, std) lists for custom scaling; if None, no scaling is applied and pixel values are preserved in their original range, defaults to None

  • dtype (torch.dtype or None, optional) – output tensor dtype, for example torch.float32; if None, dtype is inferred from the Image array dtype, defaults to None

Raises:

ImportError – if PyTorch is not installed

Returns:

image as a PyTorch tensor

Return type:

torch.Tensor

Note

Pixel values are not normalised by default; set normalize="imagenet" or provide custom mean/std to scale to zero mean and unit variance if required for model input.

The returned tensor has shape (C, H, W) for multi-plane images and (1, H, W) for single-plane images, with pixel values preserved in their original dtype.

Raises:

ImportError – if PyTorch is not installed

Returns:

image as a PyTorch tensor

Return type:

torch.Tensor

Note

Pixel values are not normalised; scale to [0, 1] manually if required for model input.

Convert to tensor and apply normalization. ‘normalize’ can be: - None: stays 0.0-1.0 or 0-255 - “imagenet”: applies standard ImageNet mean/std - (mean, std): a tuple of lists/arrays, one per channel, for custom scaling