#!/usr/bin/env python3 """ Bake print / retro effects into photos so the site gets a grungy, hand-made look without running heavy filters on visitors' phones. python3 tools/fx.py # regenerate everything in RECIPES python3 tools/fx.py motorcycle # only recipes whose source matches Sources: src/assets/photos/.jpg|png Output: src/assets/fx/-.webp Needs: pip install pillow numpy """ import sys from pathlib import Path import numpy as np from PIL import Image, ImageChops, ImageEnhance, ImageFilter, ImageOps ROOT = Path(__file__).resolve().parent.parent SRC = ROOT / 'src/assets/photos' OUT = ROOT / 'src/assets/fx' RNG = np.random.default_rng(7) # 24-colour palette for pixel art: site palette + CTA line colours + naturals. PALETTE = np.array([ (20, 20, 18), (58, 52, 44), (108, 75, 52), (163, 150, 122), (210, 205, 190), (243, 236, 217), (255, 255, 255), (198, 12, 48), (249, 70, 28), (255, 150, 60), (249, 227, 0), (200, 224, 52), (140, 198, 63), (76, 154, 42), (0, 155, 58), (15, 93, 61), (30, 60, 40), (120, 190, 230), (0, 161, 222), (29, 63, 216), (20, 30, 80), (82, 35, 152), (226, 126, 166), (130, 40, 60), ], dtype=np.float32) BAYER4 = (np.array([[0, 8, 2, 10], [12, 4, 14, 6], [3, 11, 1, 9], [15, 7, 13, 5]], dtype=np.float32) + 0.5) / 16 - 0.5 def load(name: str) -> Image.Image: for ext in ('.jpg', '.png'): p = SRC / f'{name}{ext}' if p.exists(): return Image.open(p).convert('RGB') raise FileNotFoundError(name) def fit(img: Image.Image, width: int) -> Image.Image: if img.width <= width: return img return img.resize((width, round(img.height * width / img.width)), Image.LANCZOS) # ---------- grunge layers ---------- def grain(img: Image.Image, amount=18) -> Image.Image: a = np.asarray(img, dtype=np.float32) n = RNG.normal(0, amount, a.shape[:2])[..., None] return Image.fromarray(np.clip(a + n, 0, 255).astype(np.uint8)) def dust(img: Image.Image, specks=900, scratches=14) -> Image.Image: a = np.asarray(img, dtype=np.float32).copy() h, w = a.shape[:2] ys, xs = RNG.integers(0, h, specks), RNG.integers(0, w, specks) vals = RNG.choice([235.0, 18.0], specks, p=[0.6, 0.4]) for y, x, v in zip(ys, xs, vals): r = int(RNG.integers(0, 2)) a[max(0, y - r):y + r + 1, max(0, x - r):x + r + 1] = v for _ in range(scratches): x = int(RNG.integers(0, w)) y0 = int(RNG.integers(0, h // 2)) length = int(RNG.integers(h // 6, h)) drift = RNG.normal(0, 0.15) for i in range(length): yy, xx = y0 + i, int(x + drift * i) if 0 <= yy < h and 0 <= xx < w: a[yy, xx] = a[yy, xx] * 0.4 + 235 * 0.6 return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)) def vignette(img: Image.Image, strength=0.55) -> Image.Image: w, h = img.size y, x = np.ogrid[-1:1:h * 1j, -1:1:w * 1j] mask = 1 - strength * np.clip(np.sqrt(x * x + y * y) - 0.35, 0, 1) ** 1.4 a = np.asarray(img, dtype=np.float32) * mask[..., None] return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)) def paper(img: Image.Image, tint=(243, 236, 217), mix=0.12) -> Image.Image: tex = Image.open(SRC / 'paper-crumpled.jpg').convert('L').resize(img.size) tex = ImageOps.autocontrast(tex).convert('RGB') out = ImageChops.multiply(img, tex) return Image.blend(out, Image.new('RGB', img.size, tint), mix) # ---------- looks ---------- def toon(img, levels=6, ink=2): """Cel shading: flatten colours, then trace dark ink outlines.""" base = img.filter(ImageFilter.MedianFilter(5)).filter(ImageFilter.MedianFilter(5)) base = ImageEnhance.Color(base).enhance(1.45) flat = base.quantize(colors=levels * 3, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE).convert('RGB') g = img.convert('L').filter(ImageFilter.GaussianBlur(1.4)) edges = g.filter(ImageFilter.FIND_EDGES) edges = edges.point(lambda v: 255 if v > 18 else 0) if ink > 1: edges = edges.filter(ImageFilter.MaxFilter(ink * 2 - 1)) inkc = Image.new('RGB', img.size, (20, 18, 22)) out = Image.composite(inkc, flat, edges) return grain(out, 10) def pixel(img, width=128, scale=1, spread=36): """Pixel art: shrink and ordered-dither to the palette. Saved at true size; the site scales it up with image-rendering: pixelated (any img named *-pixel).""" small = img.resize((width, round(img.height * width / img.width)), Image.BOX) small = ImageEnhance.Color(small).enhance(1.3) a = np.asarray(small, dtype=np.float32) h, w = a.shape[:2] t = np.tile(BAYER4, (h // 4 + 1, w // 4 + 1))[:h, :w][..., None] a = a + t * spread d = ((a[:, :, None, :] - PALETTE[None, None]) ** 2).sum(-1) q = PALETTE[d.argmin(-1)].astype(np.uint8) out = Image.fromarray(q).resize((w * scale, h * scale), Image.NEAREST) return out def xerox(img): """Photocopy: crushed contrast, toner speckle, paper texture.""" g = ImageOps.autocontrast(img.convert('L'), cutoff=4) g = ImageEnhance.Contrast(g).enhance(2.2) a = np.asarray(g, dtype=np.float32) a = a + RNG.normal(0, 28, a.shape) a = np.where(a > 128, 238, 22).astype(np.uint8) out = Image.fromarray(a).filter(ImageFilter.MedianFilter(3)).convert('RGB') out = dust(out, specks=1600, scratches=6) return paper(out, mix=0.08) def riso(img, ink_a=(226, 60, 120), ink_b=(29, 63, 216), offset=(7, 4)): """Two-colour risograph with misregistration and grain.""" g = ImageOps.autocontrast(img.convert('L'), cutoff=2) inv = ImageOps.invert(g) a = np.asarray(inv, dtype=np.float32) / 255 paper_c = np.array((246, 239, 222), dtype=np.float32) def layer(dens, ink): ink = np.array(ink, dtype=np.float32) return paper_c * (1 - dens[..., None]) + ink * dens[..., None] dens_a = np.clip(a * 1.15 - 0.05, 0, 1) dens_b = np.clip((a - 0.45) * 1.8, 0, 1) la = layer(dens_a, ink_a) lb = layer(np.roll(np.roll(dens_b, offset[1], 0), offset[0], 1), ink_b) out = (la / 255) * (lb / 255) * 255 out = Image.fromarray(np.clip(out, 0, 255).astype(np.uint8)) return dust(grain(out, 14), specks=500, scratches=0) def vintage(img): """Faded 90s print: lifted blacks, warm cast, light leak, vignette, dust.""" a = np.asarray(ImageEnhance.Color(img).enhance(0.8), dtype=np.float32) a = a * 0.82 + 30 a[..., 0] *= 1.06 a[..., 2] *= 0.88 h, w = a.shape[:2] y, x = np.ogrid[0:h, 0:w] leak = np.exp(-(((x - w * 0.95) / (w * 0.35)) ** 2 + ((y - h * 0.1) / (h * 0.5)) ** 2)) a = a + leak[..., None] * np.array([110, 45, 0]) out = Image.fromarray(np.clip(a, 0, 255).astype(np.uint8)) return dust(vignette(grain(out, 16), 0.6), specks=700, scratches=10) LOOKS = {'toon': toon, 'pixel': pixel, 'xerox': xerox, 'riso': riso, 'vintage': vintage} # (source, look, width, kwargs) RECIPES = [ ('motorcycle', 'toon', 1200, {}), ('motorcycle', 'pixel', 1200, {'width': 150}), ('cassette', 'vintage', 900, {}), ('guitar-strat', 'riso', 900, {}), ('guitar-hollow', 'toon', 900, {}), ('computers-pile', 'pixel', 900, {'width': 120}), ('computers-room', 'xerox', 900, {}), ('tv', 'vintage', 800, {}), ('synth', 'vintage', 900, {}), ('daisies', 'toon', 1200, {'levels': 7}), ('daisies', 'pixel', 1200, {'width': 160}), ('grass-top', 'pixel', 700, {'width': 96}), ('server-rack', 'toon', 800, {}), ('botanical', 'riso', 700, {'ink_a': (240, 90, 40), 'ink_b': (0, 155, 58)}), ('lily', 'pixel', 800, {'width': 110}), ('hibiscus', 'toon', 1000, {}), ('cta-sign', 'vintage', 1400, {}), ('pedalboard', 'riso', 1000, {'ink_a': (226, 126, 166), 'ink_b': (20, 20, 18)}), ('cloud', 'xerox', 700, {}), ] def main(): OUT.mkdir(parents=True, exist_ok=True) only = sys.argv[1:] for src, look, width, kw in RECIPES: if only and src not in only: continue img = fit(load(src), width) out = LOOKS[look](img, **kw) path = OUT / f'{src}-{look}.webp' if look == 'pixel': out.save(path, 'WEBP', lossless=True) else: out.save(path, 'WEBP', quality=84, method=6) print(f'{path.relative_to(ROOT)} {out.size[0]}x{out.size[1]} {path.stat().st_size // 1024} KB') if __name__ == '__main__': main()