File size: 8,568 Bytes
90bec74 | 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | #!/usr/bin/env python3
"""Encode an image to ASCII (or CP437) with a trained PatchToGlyph checkpoint; emit text + PNG."""
from __future__ import annotations
import argparse
from pathlib import Path
import numpy as np
import torch
from PIL import Image
from .preprocess import to_luma01, tone_stretch
from .glyph_bank import (
BORDER,
CELL_H,
CELL_W,
WIN_H,
WIN_W,
GlyphBank,
)
from .model import PatchToGlyph
def _target_hw(h: int, w: int, width_cells: int | None) -> tuple[int, int]:
if width_cells is not None:
target_w = max(CELL_W, width_cells * CELL_W)
else:
# Default: ~120 cells wide, or native if smaller
target_w = min(w, 120 * CELL_W)
target_w = max(CELL_W * 8, (target_w // CELL_W) * CELL_W)
nh = max(CELL_H, int(round(h * (target_w / w))))
nh = (nh // CELL_H) * CELL_H
return nh, target_w
def prepare_luma(path: Path, width_cells: int | None) -> np.ndarray:
img = Image.open(path).convert("RGB")
y = tone_stretch(to_luma01(img))
h, w = y.shape
nh, target_w = _target_hw(h, w, width_cells)
pil = Image.fromarray((y * 255).clip(0, 255).astype(np.uint8), mode="L")
pil = pil.resize((target_w, nh), Image.Resampling.LANCZOS)
return np.asarray(pil, dtype=np.float32) / 255.0
def prepare_luma_rgb(
img: Image.Image,
width_cells: int,
) -> tuple[np.ndarray, np.ndarray]:
"""Tone-stretched luma for the model + RGB resized to the same cell grid."""
rgb_img = img.convert("RGB")
y = tone_stretch(to_luma01(rgb_img))
h, w = y.shape
nh, target_w = _target_hw(h, w, width_cells)
luma = Image.fromarray((y * 255).clip(0, 255).astype(np.uint8), mode="L")
luma = luma.resize((target_w, nh), Image.Resampling.LANCZOS)
rgb = rgb_img.resize((target_w, nh), Image.Resampling.LANCZOS)
y_arr = np.asarray(luma, dtype=np.float32) / 255.0
rgb_arr = np.asarray(rgb, dtype=np.float32) / 255.0
return y_arr, rgb_arr
def cell_mean_colors(
rgb: np.ndarray,
sat_boost: float = 1.35,
sat_lift: float = 0.04,
) -> np.ndarray:
"""Per-cell mean RGB with mild HSV saturation boost (reads better on black).
Returns [rows, cols, 3] float32 in [0, 1].
"""
H, W, _ = rgb.shape
rows, cols = H // CELL_H, W // CELL_W
# reshape → mean over pixels in each cell
tiles = rgb.reshape(rows, CELL_H, cols, CELL_W, 3).mean(axis=(1, 3))
# saturation boost in HSV
hsv = np.asarray(
Image.fromarray((tiles * 255).clip(0, 255).astype(np.uint8), mode="RGB").convert(
"HSV"
),
dtype=np.float32,
)
h_ch, s_ch, v_ch = hsv[..., 0], hsv[..., 1], hsv[..., 2]
s_ch = np.clip(s_ch * sat_boost + sat_lift * 255.0, 0, 255)
hsv_boost = np.stack([h_ch, s_ch, v_ch], axis=-1).astype(np.uint8)
out = np.asarray(Image.fromarray(hsv_boost, mode="HSV").convert("RGB"), dtype=np.float32)
return out / 255.0
def windows_from_image(y: np.ndarray) -> tuple[torch.Tensor, torch.Tensor, int, int]:
"""Pad 4px, extract every cell window. Returns [N,2,24,16], rows, cols."""
H, W = y.shape
assert H % CELL_H == 0 and W % CELL_W == 0
rows, cols = H // CELL_H, W // CELL_W
gray = np.pad(y, ((BORDER, BORDER), (BORDER, BORDER)), mode="constant")
mask = np.zeros_like(gray, dtype=np.float32)
mask[BORDER : BORDER + H, BORDER : BORDER + W] = 1.0
wins = []
for ry in range(rows):
for cx in range(cols):
y0 = ry * CELL_H
x0 = cx * CELL_W
g = gray[y0 : y0 + WIN_H, x0 : x0 + WIN_W]
m = mask[y0 : y0 + WIN_H, x0 : x0 + WIN_W]
wins.append(np.stack([g * m, m], axis=0))
x = torch.from_numpy(np.stack(wins, axis=0).astype(np.float32))
return x, rows, cols
@torch.no_grad()
def encode(
model: PatchToGlyph,
bank: GlyphBank,
y: np.ndarray,
device: torch.device,
batch: int = 2048,
) -> tuple[list[str], torch.Tensor]:
model.eval()
windows, rows, cols = windows_from_image(y)
logits_all = []
for i in range(0, windows.shape[0], batch):
chunk = windows[i : i + batch].to(device)
logits_all.append(model(chunk).float().cpu())
logits = torch.cat(logits_all, dim=0)
idx = logits.argmax(dim=-1)
chars = bank.decode_indices(idx)
lines = [
"".join(chars[r * cols : (r + 1) * cols]) for r in range(rows)
]
return lines, idx.view(rows, cols)
def render_ascii_png(
indices: torch.Tensor,
bank: GlyphBank,
out_path: Path,
scale: int = 1,
colors: np.ndarray | None = None,
) -> None:
"""Blit VGA bitmaps for each cell → greyscale or color PNG (light on dark).
If `colors` is provided as [rows, cols, 3] in [0,1], each glyph is tinted by
that cell's color: out = glyph * color.
"""
rows, cols = indices.shape
bitmaps = bank.bitmaps.cpu().numpy()
if colors is None:
canvas = np.zeros((rows * CELL_H, cols * CELL_W), dtype=np.float32)
for r in range(rows):
for c in range(cols):
g = bitmaps[int(indices[r, c])]
canvas[
r * CELL_H : (r + 1) * CELL_H,
c * CELL_W : (c + 1) * CELL_W,
] = g
img = Image.fromarray((canvas * 255).clip(0, 255).astype(np.uint8), mode="L")
else:
assert colors.shape[:2] == (rows, cols), colors.shape
canvas = np.zeros((rows * CELL_H, cols * CELL_W, 3), dtype=np.float32)
for r in range(rows):
for c in range(cols):
g = bitmaps[int(indices[r, c])]
canvas[
r * CELL_H : (r + 1) * CELL_H,
c * CELL_W : (c + 1) * CELL_W,
:,
] = g[..., None] * colors[r, c][None, None, :]
img = Image.fromarray((canvas * 255).clip(0, 255).astype(np.uint8), mode="RGB")
if scale > 1:
img = img.resize(
(img.width * scale, img.height * scale), Image.Resampling.NEAREST
)
out_path.parent.mkdir(parents=True, exist_ok=True)
img.save(out_path)
def parse_args():
p = argparse.ArgumentParser(description="asc-eye image → ASCII PNG")
p.add_argument("--image", type=str, required=True)
p.add_argument("--ckpt", type=str, required=True)
p.add_argument("--font", type=str, default="./assets/VGA8.F16")
p.add_argument("--charset", type=str, default="ascii", choices=("ascii", "cp437"))
p.add_argument("--width_cells", type=int, default=120)
p.add_argument("--out_txt", type=str, default="")
p.add_argument("--out_png", type=str, required=True)
p.add_argument("--scale", type=int, default=2, help="nearest-neighbor upscale for PNG")
p.add_argument("--color", action="store_true", help="tint glyphs by per-cell mean RGB")
p.add_argument("--device", type=str, default="cuda")
return p.parse_args()
def main():
args = parse_args()
device = torch.device(
args.device if args.device != "cuda" or torch.cuda.is_available() else "cpu"
)
bank = GlyphBank(args.font, charset=args.charset).to(device)
ckpt = torch.load(args.ckpt, map_location=device, weights_only=False)
meta = ckpt.get("meta") or {}
# Prefer checkpoint's recorded charset/K if present
ck_args = meta.get("args") or {}
charset = ck_args.get("charset", args.charset)
if charset != args.charset:
print(f"[encode] ckpt charset={charset} (overriding CLI {args.charset})")
bank = GlyphBank(args.font, charset=charset).to(device)
model = PatchToGlyph(bank.K).to(device)
model.load_state_dict(ckpt["model"])
step = ckpt.get("step", "?")
print(f"[encode] loaded step={step} K={bank.K} charset={bank.charset} device={device}")
img = Image.open(args.image)
if args.color:
y, rgb = prepare_luma_rgb(img, args.width_cells)
colors = cell_mean_colors(rgb)
else:
y = prepare_luma(Path(args.image), args.width_cells)
colors = None
print(f"[encode] luma grid {y.shape[1]//CELL_W}×{y.shape[0]//CELL_H} cells ({y.shape[1]}×{y.shape[0]} px)")
lines, indices = encode(model, bank, y, device)
txt = "\n".join(lines) + "\n"
out_txt = Path(args.out_txt) if args.out_txt else Path(args.out_png).with_suffix(".txt")
out_txt.write_text(txt, encoding="utf-8")
render_ascii_png(indices, bank, Path(args.out_png), scale=args.scale, colors=colors)
print(f"[encode] wrote {out_txt} ({len(lines)} lines)")
print(f"[encode] wrote {args.out_png}")
if __name__ == "__main__":
main()
|