"""Turn raw model outputs into crisp pixel art: hard alpha, limited palette, NN upscale.""" from __future__ import annotations from pathlib import Path import numpy as np import torch from PIL import Image def to_rgba_u8(x: torch.Tensor, max_colors: int = 16) -> list[Image.Image]: """x: [B,4,32,32] in [-1,1] -> list of RGBA PIL images with binary alpha and <= max_colors.""" arr = ((x.permute(0, 2, 3, 1).float().numpy() + 1) * 127.5).clip(0, 255).astype(np.uint8) out = [] for a in arr: alpha = a[..., 3] >= 128 rgb = Image.fromarray(a[..., :3], "RGB") if alpha.any(): # palette from opaque pixels only, so the background never steals palette entries opaque = Image.fromarray(a[..., :3][alpha][None], "RGB") pal = opaque.quantize(colors=max_colors, method=Image.Quantize.MEDIANCUT) rgb = rgb.quantize(palette=pal, dither=Image.Dither.NONE).convert("RGB") rgba = np.dstack([np.asarray(rgb), alpha.astype(np.uint8) * 255]) out.append(Image.fromarray(rgba, "RGBA")) return out def save_grid(x: torch.Tensor, path: Path, cols: int = 8, scale: int = 6, bg=(230, 237, 243, 255)) -> None: imgs = to_rgba_u8(x) rows = (len(imgs) + cols - 1) // cols cell = 34 * scale sheet = Image.new("RGBA", (cols * cell, rows * cell), bg) for i, im in enumerate(imgs): sheet.alpha_composite(im.resize((32 * scale, 32 * scale), Image.NEAREST), ((i % cols) * cell + scale, (i // cols) * cell + scale)) sheet.save(path)