212 lines
9.2 KiB
Python
212 lines
9.2 KiB
Python
#!/usr/bin/env python3
|
|
"""logo16 - turn logo images into LED-matrix-ready 16x16 assets.
|
|
|
|
Put source images in an input folder named by ICAO airline code
|
|
(DAL.png, AAL.svg, SWA.jpg, ...). The file stem (uppercased) becomes the
|
|
lookup key, so your flight code can do: key = callsign[:3].
|
|
|
|
Outputs (in --out):
|
|
png/<CODE>.png 16x16 RGB PNG (black background = LEDs off)
|
|
atlas.bin all logos as raw RGB888, one file to load at startup
|
|
manifest.json code -> png path / atlas index
|
|
logos.h (optional, --c-header) C arrays for C++ builds
|
|
preview.png contact sheet, nearest-neighbour upscaled, for eyeballing
|
|
|
|
Requires Pillow. SVG input additionally needs `pip install cairosvg`.
|
|
"""
|
|
import argparse
|
|
import json
|
|
import struct
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from PIL import Image, ImageChops, ImageDraw, ImageEnhance, ImageFilter, ImageFont
|
|
|
|
EXTS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"}
|
|
|
|
|
|
def load_rgba(path: Path) -> Image.Image:
|
|
if path.suffix.lower() == ".svg":
|
|
try:
|
|
import cairosvg # type: ignore
|
|
except ImportError:
|
|
sys.exit("SVG input needs cairosvg: pip install cairosvg (or convert to PNG first)")
|
|
import io
|
|
png = cairosvg.svg2png(url=str(path), output_width=512)
|
|
return Image.open(io.BytesIO(png)).convert("RGBA")
|
|
return Image.open(path).convert("RGBA")
|
|
|
|
|
|
def knock_out_background(img: Image.Image, tol: int) -> Image.Image:
|
|
"""If the image is opaque and its four corners share one colour, treat that
|
|
colour as background and make it transparent (soft edge for antialiasing)."""
|
|
if img.getchannel("A").getextrema()[0] < 250:
|
|
return img # already has real transparency
|
|
w, h = img.size
|
|
corners = [img.getpixel(p)[:3] for p in ((0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1))]
|
|
ref = corners[0]
|
|
if any(max(abs(a - b) for a, b in zip(c, ref)) > 12 for c in corners):
|
|
return img # busy background; leave it alone
|
|
diff = ImageChops.difference(img.convert("RGB"), Image.new("RGB", img.size, ref)).convert("L")
|
|
lo, hi = tol, tol * 3
|
|
mask = diff.point(lambda v: 0 if v <= lo else 255 if v >= hi else (v - lo) * 255 // (hi - lo))
|
|
out = img.copy()
|
|
out.putalpha(mask)
|
|
return out
|
|
|
|
|
|
def to_matrix_image(img: Image.Image, a: argparse.Namespace) -> Image.Image:
|
|
S = a.size
|
|
if a.bg_knockout:
|
|
img = knock_out_background(img, a.bg_tol)
|
|
|
|
if a.trim: # crop to visible content so the mark fills the 16px box
|
|
bbox = img.getchannel("A").point(lambda v: 255 if v > 8 else 0).getbbox()
|
|
if bbox:
|
|
img = img.crop(bbox)
|
|
|
|
# Composite on black at high resolution BEFORE shrinking. Black is "off" on
|
|
# an LED panel, and doing it here avoids dark/light fringes from alpha.
|
|
flat = Image.new("RGB", img.size, (0, 0, 0))
|
|
flat.paste(img, mask=img.getchannel("A"))
|
|
|
|
inner = S - 2 * a.margin
|
|
w, h = flat.size
|
|
if a.fit == "cover":
|
|
scale = max(inner / w, inner / h)
|
|
else:
|
|
scale = min(inner / w, inner / h)
|
|
nw, nh = max(1, round(w * scale)), max(1, round(h * scale))
|
|
small = flat.resize((nw, nh), Image.LANCZOS)
|
|
|
|
if a.fit == "cover":
|
|
l, t = (nw - inner) // 2, (nh - inner) // 2
|
|
small = small.crop((l, t, l + inner, t + inner))
|
|
nw = nh = inner
|
|
|
|
canvas = Image.new("RGB", (S, S), (0, 0, 0))
|
|
canvas.paste(small, ((S - nw) // 2, (S - nh) // 2))
|
|
|
|
# Tiny logos need help: punch up saturation/contrast, optional sharpen.
|
|
if a.sharpen > 0:
|
|
canvas = canvas.filter(ImageFilter.UnsharpMask(radius=0.6, percent=int(a.sharpen * 100), threshold=0))
|
|
if a.saturation != 1:
|
|
canvas = ImageEnhance.Color(canvas).enhance(a.saturation)
|
|
if a.contrast != 1:
|
|
canvas = ImageEnhance.Contrast(canvas).enhance(a.contrast)
|
|
if a.gamma != 1:
|
|
lut = [round(255 * (i / 255) ** a.gamma) for i in range(256)] * 3
|
|
canvas = canvas.point(lut)
|
|
if a.min_value: # dark navy/maroon marks vanish on LEDs: lift any lit pixel to a minimum brightness
|
|
h, sat, v = canvas.convert("HSV").split()
|
|
v = v.point(lambda x: x if x < 24 else max(x, a.min_value))
|
|
canvas = Image.merge("HSV", (h, sat, v)).convert("RGB")
|
|
if a.colors: # flat palettes read cleaner on LEDs than gradients
|
|
q = canvas.quantize(colors=a.colors, method=Image.MEDIANCUT, dither=Image.NONE)
|
|
canvas = q.convert("RGB")
|
|
return canvas
|
|
|
|
|
|
def write_c_header(path: Path, items, S):
|
|
lines = ["// generated by logo16.py - RGB888, row-major", f"#define LOGO_SIZE {S}",
|
|
"#include <stdint.h>", ""]
|
|
for code, im in items:
|
|
data = ", ".join(str(b) for b in im.tobytes())
|
|
lines.append(f"static const uint8_t LOGO_{code}[{S*S*3}] = {{{data}}};")
|
|
lines += ["", "struct LogoEntry { const char *code; const uint8_t *rgb; };",
|
|
"static const LogoEntry LOGOS[] = {"]
|
|
lines += [f' {{"{c}", LOGO_{c}}},' for c, _ in items]
|
|
lines += ["};", f"static const int LOGO_COUNT = {len(items)};", ""]
|
|
path.write_text("\n".join(lines))
|
|
|
|
|
|
def preview_sheet(items, S, scale, cols=8) -> Image.Image:
|
|
cell = S * scale
|
|
pad, label_h = 8, 14
|
|
rows = (len(items) + cols - 1) // cols
|
|
W = cols * (cell + pad) + pad
|
|
H = rows * (cell + pad + label_h) + pad
|
|
sheet = Image.new("RGB", (W, H), (24, 24, 24))
|
|
d = ImageDraw.Draw(sheet)
|
|
font = ImageFont.load_default()
|
|
for i, (code, im) in enumerate(items):
|
|
x = pad + (i % cols) * (cell + pad)
|
|
y = pad + (i // cols) * (cell + pad + label_h)
|
|
sheet.paste(im.resize((cell, cell), Image.NEAREST), (x, y))
|
|
d.text((x, y + cell + 2), code, fill=(200, 200, 200), font=font)
|
|
return sheet
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
p.add_argument("input_dir", type=Path)
|
|
p.add_argument("--out", type=Path, default=Path("out"))
|
|
p.add_argument("--size", type=int, default=16)
|
|
p.add_argument("--margin", type=int, default=0, help="px of black border inside the box (default 0)")
|
|
p.add_argument("--fit", choices=["contain", "cover"], default="contain")
|
|
p.add_argument("--no-trim", dest="trim", action="store_false", help="don't crop to visible content")
|
|
p.add_argument("--no-bg-knockout", dest="bg_knockout", action="store_false",
|
|
help="don't auto-remove a flat opaque background")
|
|
p.add_argument("--bg-tol", type=int, default=24)
|
|
p.add_argument("--saturation", type=float, default=1.35)
|
|
p.add_argument("--contrast", type=float, default=1.1)
|
|
p.add_argument("--sharpen", type=float, default=1.0, help="0 disables")
|
|
p.add_argument("--gamma", type=float, default=1.0,
|
|
help="pre-gamma; leave at 1.0, rpi-rgb-led-matrix already applies luminance correction")
|
|
p.add_argument("--min-value", type=int, default=150,
|
|
help="brightness floor (0-255) for non-black pixels so dark logos stay visible; 0 disables")
|
|
p.add_argument("--colors", type=int, default=0, help="quantize to N colours (0 = off); try 6-8")
|
|
p.add_argument("--c-header", action="store_true", help="also write logos.h")
|
|
p.add_argument("--native", type=Path,
|
|
help="folder of finished 16x16 pixel art (e.g. UFO.png, GA.png) copied in unchanged, no processing")
|
|
p.add_argument("--only", nargs="*", help="only these codes")
|
|
a = p.parse_args()
|
|
|
|
files = sorted(f for f in a.input_dir.iterdir() if f.suffix.lower() in EXTS)
|
|
if a.only:
|
|
want = {c.upper() for c in a.only}
|
|
files = [f for f in files if f.stem.upper() in want]
|
|
if not files:
|
|
sys.exit(f"no images found in {a.input_dir}")
|
|
|
|
(a.out / "png").mkdir(parents=True, exist_ok=True)
|
|
items = []
|
|
for f in files:
|
|
code = f.stem.upper()
|
|
try:
|
|
im = to_matrix_image(load_rgba(f), a)
|
|
except Exception as e: # keep going on one bad file
|
|
print(f"skip {f.name}: {e}", file=sys.stderr)
|
|
continue
|
|
im.save(a.out / "png" / f"{code}.png")
|
|
items.append((code, im))
|
|
print(f"ok {code}")
|
|
|
|
if a.native:
|
|
for f in sorted(x for x in a.native.iterdir() if x.suffix.lower() == ".png"):
|
|
im = Image.open(f).convert("RGB")
|
|
if im.size != (a.size, a.size):
|
|
sys.exit(f"{f.name}: native art must be exactly {a.size}x{a.size}, got {im.size}")
|
|
code = f.stem.upper()
|
|
items = [(c, i) for c, i in items if c != code] + [(code, im)]
|
|
im.save(a.out / "png" / f"{code}.png")
|
|
print(f"ok {code} (native)")
|
|
|
|
S = a.size
|
|
# atlas: magic, size(u8), count(u16), then per entry: 4-byte code + RGB888
|
|
with open(a.out / "atlas.bin", "wb") as fh:
|
|
fh.write(b"LG16" + struct.pack("<BH", S, len(items)))
|
|
for code, im in items:
|
|
fh.write(code.encode("ascii")[:4].ljust(4, b"\0") + im.tobytes())
|
|
(a.out / "manifest.json").write_text(json.dumps(
|
|
{"size": S, "logos": {c: {"png": f"png/{c}.png", "index": i} for i, (c, _) in enumerate(items)}},
|
|
indent=2))
|
|
if a.c_header:
|
|
write_c_header(a.out / "logos.h", items, S)
|
|
preview_sheet(items, S, 12).save(a.out / "preview.png")
|
|
print(f"\n{len(items)} logos -> {a.out}/ (see preview.png)")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|