FrameXlabs commited on
Commit
7bb45a7
·
verified ·
1 Parent(s): f3b08bd

Add trout/viz.py

Browse files
Files changed (1) hide show
  1. trout/viz.py +54 -0
trout/viz.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Turning palette tokens into images and grids."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List, Optional, Sequence, Tuple
6
+
7
+ import numpy as np
8
+ import torch
9
+ from PIL import Image
10
+
11
+ from .palette import Palette
12
+
13
+
14
+ def tokens_to_images(tokens, palette: Palette, grid: int = 16) -> List[Image.Image]:
15
+ if isinstance(tokens, torch.Tensor):
16
+ tokens = tokens.detach().cpu().numpy()
17
+ tokens = np.asarray(tokens).reshape(-1, grid, grid)
18
+ rgba = palette.tokens_to_rgba(tokens)
19
+ return [Image.fromarray(a, "RGBA") for a in rgba]
20
+
21
+
22
+ def checkerboard(size: int, cell: int = 4, c1=(70, 70, 70), c2=(56, 56, 56)) -> Image.Image:
23
+ yy, xx = np.mgrid[0:size, 0:size]
24
+ board = ((yy // cell + xx // cell) % 2 == 0)[..., None]
25
+ arr = np.where(board, np.array(c1, np.uint8), np.array(c2, np.uint8)).astype(np.uint8)
26
+ return Image.fromarray(arr, "RGB").convert("RGBA")
27
+
28
+
29
+ def upscale(img: Image.Image, scale: int = 8, background: Optional[Tuple[int, int, int]] = None,
30
+ checker: bool = False) -> Image.Image:
31
+ big = img.convert("RGBA").resize((img.width * scale, img.height * scale), Image.NEAREST)
32
+ if checker:
33
+ bg = checkerboard(big.width, cell=max(2, scale))
34
+ elif background is not None:
35
+ bg = Image.new("RGBA", big.size, tuple(background) + (255,))
36
+ else:
37
+ return big
38
+ bg.alpha_composite(big)
39
+ return bg
40
+
41
+
42
+ def make_grid(images: Sequence[Image.Image], ncols: int = 8, scale: int = 6, pad: int = 4,
43
+ background=(32, 32, 34), checker: bool = True) -> Image.Image:
44
+ if not images:
45
+ return Image.new("RGB", (1, 1))
46
+ w = images[0].width * scale
47
+ h = images[0].height * scale
48
+ nrows = (len(images) + ncols - 1) // ncols
49
+ canvas = Image.new("RGBA", (ncols * (w + pad) + pad, nrows * (h + pad) + pad), tuple(background) + (255,))
50
+ for i, im in enumerate(images):
51
+ r, c = divmod(i, ncols)
52
+ canvas.alpha_composite(upscale(im, scale, checker=checker, background=None if checker else background),
53
+ (pad + c * (w + pad), pad + r * (h + pad)))
54
+ return canvas.convert("RGB")