TensorStack#

class TensorStack(tensor: torch.Tensor, colororder: str | None = None, logits: bool = False, dtype: DTypeLike | None = None)[source]#

Lazy image source from a PyTorch batch tensor.

Each frame is a zero-copy view into the batch tensor, providing memory-efficient iteration over model outputs or other batch-processed tensors.

Parameters:
  • tensor (torch.Tensor) – tensor of shape (B, C, H, W) or (B, H, W)

  • colororder (str, optional) – colour plane order for multi-channel tensors, e.g. "RGB" or "BGR", defaults to None

  • logits (bool, optional) – if True, take argmax over the channel dimension to convert per-class logits to a class label image, defaults to False

  • dtype (numpy dtype or None, optional) – data type for output image arrays, e.g. np.uint8 or np.float32; if None, dtype is inferred from the tensor data, defaults to None

Example:


>>> from machinevisiontoolbox import TensorStack
>>> import torch
>>> batch = torch.randn(10, 3, 64, 64)  # 10 RGB images
>>> source = TensorStack(batch, colororder="RGB")
>>> len(source)
10
>>> img = source[7]  # Returns Image wrapping tensor[7] (zero-copy view)
>>> for img in source:
...     features = extract(img)  # Process each image lazily
Seealso:

Image.Tensor

Initialize TensorStack from a batch tensor.

Parameters:
  • tensor – batch tensor of shape (B, C, H, W) or (B, H, W)

  • colororder – colour plane order for display/export

  • logits – if True, argmax the channel dimension for segmentation masks

  • dtype – output array dtype passed to Image constructor

Methods

disp

Display images from the source interactively.

tensor

Convert all images from this source into a single 4D PyTorch tensor.