wkea's picture
Deploy Space
c388140 verified
Raw History Blame Contribute Delete
968 Bytes
from __future__ import annotations
import os
from typing import Optional
import torch
from PIL import Image
from torchvision.utils import make_grid
def save_tensor_grid(
x: torch.Tensor,
path: str,
nrow: int,
padding: int = 1,
) -> None:
"""
保存图片网格,支持 RGB(3) / RGBA(4)。
约定:
- x: (B,C,H,W) 且值域在 [0,1]
- path: 输出文件路径(推荐 .png)
"""
if x.ndim != 4:
raise ValueError("x 必须是 (B,C,H,W)")
if x.shape[1] not in (3, 4):
raise ValueError("仅支持 3(RGB) 或 4(RGBA) 通道")
os.makedirs(os.path.dirname(path), exist_ok=True)
grid = make_grid(x, nrow=nrow, padding=padding) # (C,H,W)
grid = grid.clamp(0.0, 1.0)
arr = (grid.permute(1, 2, 0) * 255.0).to(torch.uint8).cpu().numpy()
mode = "RGBA" if arr.shape[2] == 4 else "RGB"
im = Image.fromarray(arr, mode=mode)
im.save(path)