Implementation:Kornia Kornia Tensor To Image
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Vision, IO |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
Concrete tool for converting PyTorch tensors to numpy image arrays provided by Kornia.
Description
The tensor_to_image function converts torch.Tensor images from (C, H, W) or (B, C, H, W) format to numpy.ndarray in (H, W, C) or (H, W) format suitable for matplotlib or PIL display.
Key features:
- Automatic channel permutation from CHW to HWC format
- CPU transfer handled internally (works with GPU tensors)
- Grayscale handling -- single-channel tensors produce (H, W) arrays
- Optional contiguous memory layout via
force_contiguousfor compatibility with libraries requiring contiguous arrays - Batch dimension handling via
keepdimparameter
Usage
Import when you need to visualize tensor outputs using matplotlib, PIL, or save to disk. This is the standard way to move from Kornia's tensor format back to the numpy/image ecosystem.
Code Reference
Source Location
- Repository: kornia
- File: kornia/image/utils.py
- Lines: L167-225
Signature
def tensor_to_image(
tensor: torch.Tensor,
keepdim: bool = False,
force_contiguous: bool = False,
) -> np.ndarray
Import
from kornia.utils import tensor_to_image
# or
from kornia import tensor_to_image
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| tensor | torch.Tensor | Yes | Image tensor in (C, H, W) or (B, C, H, W) format |
| keepdim | bool | No | Preserve batch dimension in output; default False |
| force_contiguous | bool | No | Ensure output array has contiguous memory layout; default False |
Outputs
| Name | Type | Description |
|---|---|---|
| return | numpy.ndarray | Image array in (H, W, C) format for color images, (H, W) for grayscale |
Usage Examples
Basic Conversion for Matplotlib Display
import torch
import matplotlib.pyplot as plt
from kornia.utils import tensor_to_image
# Assume img_tensor is a (3, H, W) float32 tensor from a Kornia pipeline
img_tensor = torch.randn(3, 256, 256).clamp(0, 1)
# Convert to numpy for matplotlib
img_np = tensor_to_image(img_tensor)
print(img_np.shape) # (256, 256, 3)
plt.imshow(img_np)
plt.title("Converted Image")
plt.show()
Batch Tensor Conversion
import torch
from kornia.utils import tensor_to_image
# Batch of 4 images
batch_tensor = torch.randn(4, 3, 128, 128).clamp(0, 1)
# Convert each image in the batch
for i in range(batch_tensor.shape[0]):
img_np = tensor_to_image(batch_tensor[i])
print(f"Image {i} shape: {img_np.shape}") # (128, 128, 3)
Grayscale Conversion
import torch
from kornia.utils import tensor_to_image
# Single-channel grayscale tensor
gray_tensor = torch.randn(1, 256, 256).clamp(0, 1)
img_np = tensor_to_image(gray_tensor)
print(img_np.shape) # (256, 256) -- channel dimension is squeezed
Related Pages
Implements Principle
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment