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.Tensorof 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
Trueand the tensor is 3D, interpret as class logits and applyargmaxover the first axis to create a label image, defaults toFalsecolororder (str, optional) – color plane order, e.g.
"RGB"or"BGR", defaults to “RGB” for 3-channel images and None for single-channel imagesdtype (numpy dtype or None, optional) – data type for the image array, e.g.
np.uint8ornp.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
datais not a tensor or dictionary containing a tensorValueError – if a 4D tensor has batch size greater than 1
- Returns:
image wrapping the tensor data
- Return type:
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)whereB=1For batches where
B > 1useTensorStackwhich 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:
tensorTensorStack