Image.Tensor#

classmethod Image.Tensor(data: Any, logits: bool = False, colororder: str | None = None, dtype: Any = None) Image[source]#

Create an Image from a PyTorch tensor.

Parameters:
  • data (torch.Tensor or dict) – tensor input, either a torch.Tensor of shape (C, H, W), (H, W), (1, C, H, W) or (1, H, W), or a dictionary containing a tensor (for example model outputs like {"out": tensor})

  • logits (bool, optional) – if True and the tensor is 3D, interpret as class logits and apply argmax over the first axis to create a label image, defaults to False

  • colororder (str, optional) – color plane order, e.g. "RGB" or "BGR", defaults to “RGB” for 3-channel images and None for single-channel images

  • dtype (numpy dtype or None, optional) – data type for the image array, e.g. np.uint8 or np.float32; if None, the dtype of the input tensor is preserved, defaults to same as input tensor dtype

Raises:
  • ImportError – if PyTorch is not installed

  • TypeError – if data is not a tensor or dictionary containing a tensor

  • ValueError – if a 4D tensor has batch size greater than 1

Returns:

image wrapping the tensor data

Return type:

Image

Accepts either a tensor directly or a dictionary containing a tensor as typically returned by torchvision model outputs (for example {"out": tensor}).

Handles: - Moving data from GPU/MPS to CPU - Detaching from the autograd graph - Converting (C, H, W) to (H, W, C) - Handling single-image batches (B, C, H, W) where B=1

For batches where B > 1 use TensorStack which creates an image iterator for the batch.

>>> from machinevisiontoolbox import Image
>>> import torch
!! [RUNBLOCK-ERROR] machinevisiontoolbox/ImageTensor.py:43
    ModuleNotFoundError: No module named 'torch'
>>> tensor = torch.rand(1, 3, 100, 200) # Create a random tensor simulating a model output
!! [RUNBLOCK-ERROR] machinevisiontoolbox/ImageTensor.py:43
    NameError: name 'torch' is not defined
>>> # Convert to Image
>>> img = Image.Tensor(tensor)
!! [RUNBLOCK-ERROR] machinevisiontoolbox/ImageTensor.py:43
    NameError: name 'tensor' is not defined
>>> print(img)
!! [RUNBLOCK-ERROR] machinevisiontoolbox/ImageTensor.py:43
    NameError: name 'img' is not defined

The modern “Machine Vision Toolbox” workflow:

from machinevisiontoolbox import Image
img = Image.Read("monalisa.png")
outputs = model(img.tensor(normalize="imagenet"))  # pass tensor to model
out = Image.Tensor(outputs, logits=True).disp()
Seealso:

tensor TensorStack