File size: 968 Bytes
c388140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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)