"""Turn an image into Galaga tile mosaic: every 8x8 cell becomes the tile character and colour code (of the board's 128 x 64) that looks closest. The candidates come from target/glyphs.bin, rendered by the board's own video code (cargo run --release --bin galaga-glyphs), so the preview is exactly what a cabinet shows. Usage: python3 tools/mosaic.py IMAGE --cols 28 --rows 5 --out target/mosaic/NAME writes NAME.png (preview, 3x), NAME.target.png (the image as fitted), NAME.cells (row col code colour per line, for the board) and prints the byte cost. galaga-mosaic-show NAME.cells TOP ROWS OUT.ppm shows the cells on the real title screen. --mode solid (the solid block in the best colour per cell) gives the cleanest result for a bold logo; hybrid adds shaped characters on clean edges; glyph uses any character and is noisy. """ import argparse import numpy as np from PIL import Image ap = argparse.ArgumentParser() ap.add_argument("image") ap.add_argument("--cols", type=int, default=28) ap.add_argument("--rows", type=int, default=5) ap.add_argument("--out", required=True) ap.add_argument("--top", type=int, default=2, help="screen row of the mosaic's first row") ap.add_argument("--mode", choices=["glyph", "solid", "hybrid"], default="hybrid", help="glyph: any character; solid: the solid block (0x25) or blank only; " "hybrid: a shaped character only where it beats the best solid block clearly") ap.add_argument("--key-background", action="store_true", help="treat the image's border colour (a flat background) as black/transparent") ap.add_argument("--key-tolerance", type=float, default=70.0) ap.add_argument("--edge", type=float, default=0.6, help="hybrid: a shaped character must have at most this fraction of the best solid error") args = ap.parse_args() atlas = np.fromfile("target/glyphs.bin", dtype=np.uint8).reshape(64, 128, 8, 8, 3).astype(np.float32) cand = atlas.reshape(64 * 128, 64, 3) # Drop duplicate looks so ties resolve to the first (lowest colour, code). _, keep = np.unique(cand.reshape(len(cand), -1), axis=0, return_index=True) keep = np.sort(keep) cand_k = cand[keep] # Candidates that are the solid block (0x25) in some colour, or blank. SOLID, BLANK = 0x25, 0x24 solid_idx = np.array([i for i, k in enumerate(keep) if k % 128 in (SOLID, BLANK)]) w, h = args.cols * 8, args.rows * 8 src = Image.open(args.image).convert("RGB") if args.key_background: a = np.asarray(src, dtype=np.float32) border = np.concatenate([a[0], a[-1], a[:, 0], a[:, -1]]) key = np.median(border, axis=0) far = np.sqrt(((a - key) ** 2).sum(axis=2)) > args.key_tolerance a[~far] = 0 src = Image.fromarray(a.astype(np.uint8)) # Fit the image into the area keeping its aspect, centred on black. scale = min(w / src.width, h / src.height) fitted = src.resize((max(1, round(src.width * scale)), max(1, round(src.height * scale))), Image.LANCZOS) canvas = Image.new("RGB", (w, h)) canvas.paste(fitted, ((w - fitted.width) // 2, (h - fitted.height) // 2)) target = np.asarray(canvas, dtype=np.float32) out = np.zeros((h, w, 3), np.uint8) cells = [] blank = 0 for r in range(args.rows): for c in range(args.cols): block = target[r * 8:(r + 1) * 8, c * 8:(c + 1) * 8].reshape(64, 3) err = ((cand_k - block) ** 2).sum(axis=(1, 2)) best = keep[int(err.argmin())] if args.mode != "glyph": solid_err = err[solid_idx] best_solid = keep[solid_idx[int(solid_err.argmin())]] if args.mode == "solid" or err.min() > args.edge * solid_err.min(): best = best_solid colour, code = divmod(int(best), 128) out[r * 8:(r + 1) * 8, c * 8:(c + 1) * 8] = atlas[colour, code].astype(np.uint8) if atlas[colour, code].max() == 0: blank += 1 else: cells.append((args.top + r, c, code, colour)) Image.fromarray(out).resize((w * 3, h * 3), Image.NEAREST).save(args.out + ".png") canvas.resize((w * 3, h * 3), Image.NEAREST).save(args.out + ".target.png") with open(args.out + ".cells", "w") as f: for row, col, code, colour in cells: f.write(f"{row} {col} {code} {colour}\n") err = ((out.astype(np.float32) - target) ** 2).mean() ** 0.5 codes = sorted({c[2] for c in cells}) print(f"{args.cols}x{args.rows} cells: {len(cells)} drawn, {blank} blank; " f"{2 * len(cells)} bytes as (code, colour) pairs before compression; " f"{len(codes)} distinct characters; RMS error {err:.1f}")