Mirror to Gitea / mirror (push) Skipped
Turn the home cover into a two-tone street poster: stacked-letter title band, manga panels, graffiti and drip lettering, speech bubbles and fold creases. Add a live ASCII canvas, Tag and PosterBand components, graffiti fonts, and jsr / popart / ascii presets to tools/fx.py.
345 lines
14 KiB
Python
345 lines
14 KiB
Python
#!/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/<name>.jpg|png Output: src/assets/fx/<name>-<effect>.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)
|
|
|
|
|
|
|
|
# ---------- poster / comic / terminal looks ----------
|
|
def _halftone_mask(density, cell=7, angle=45):
|
|
"""Return a boolean ink mask: round dots whose size follows density (0..1)."""
|
|
h, w = density.shape
|
|
y, x = np.mgrid[0:h, 0:w].astype(np.float32)
|
|
a = np.deg2rad(angle)
|
|
u = x * np.cos(a) + y * np.sin(a)
|
|
v = -x * np.sin(a) + y * np.cos(a)
|
|
fu = (u / cell) % 1 - 0.5
|
|
fv = (v / cell) % 1 - 0.5
|
|
dist = np.sqrt(fu * fu + fv * fv)
|
|
radius = np.sqrt(np.clip(density, 0, 1)) * 0.62
|
|
return dist < radius
|
|
|
|
|
|
def _ink_edges(img, thresh=22, thick=3):
|
|
g = img.convert('L').filter(ImageFilter.GaussianBlur(1.2))
|
|
e = g.filter(ImageFilter.FIND_EDGES).point(lambda v: 255 if v > thresh else 0)
|
|
if thick > 1:
|
|
e = e.filter(ImageFilter.MaxFilter(thick | 1))
|
|
return np.asarray(e) > 0
|
|
|
|
|
|
def creases(img, folds=((0.5, 'v'), (0.33, 'h'), (0.66, 'h')), strength=0.18):
|
|
"""Paper fold lines: a bright ridge next to a dark valley."""
|
|
a = np.asarray(img, dtype=np.float32).copy()
|
|
h, w = a.shape[:2]
|
|
for pos, d in folds:
|
|
if d == 'v':
|
|
c = int(w * pos)
|
|
for off, k in ((-2, 1 + strength), (-1, 1 + strength * 0.6), (1, 1 - strength), (2, 1 - strength * 0.6)):
|
|
if 0 <= c + off < w:
|
|
a[:, c + off] *= k
|
|
else:
|
|
c = int(h * pos)
|
|
for off, k in ((-2, 1 + strength), (-1, 1 + strength * 0.6), (1, 1 - strength), (2, 1 - strength * 0.6)):
|
|
if 0 <= c + off < h:
|
|
a[c + off, :] *= k
|
|
return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
|
|
|
|
|
|
def jsr(img, ink=(46, 92, 44), paper=(226, 233, 150), cell=6, outline=True):
|
|
"""Two-tone street poster: one ink on coloured stock, halftone mid-tones,
|
|
solid shadows, ink outlines, fold creases, speckle and wear."""
|
|
g = ImageOps.autocontrast(img.convert('L'), cutoff=2)
|
|
g = ImageEnhance.Contrast(g).enhance(1.25)
|
|
g = ImageEnhance.Brightness(g).enhance(1.12)
|
|
d = 1 - np.asarray(g, dtype=np.float32) / 255
|
|
ink_mask = _halftone_mask(np.clip((d - 0.28) / 0.55, 0, 1) ** 1.2, cell=cell)
|
|
ink_mask |= d > 0.84
|
|
if outline:
|
|
ink_mask |= _ink_edges(img, thresh=26, thick=3)
|
|
# speckle: lost ink and stray ink, like a worn print
|
|
noise = RNG.random(d.shape)
|
|
ink_mask = (ink_mask & (noise > 0.035)) | (noise < 0.004)
|
|
paper_c, ink_c = np.array(paper, np.float32), np.array(ink, np.float32)
|
|
out = np.where(ink_mask[..., None], ink_c, paper_c)
|
|
out = Image.fromarray(out.astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.35))
|
|
out = paper_tex(out, 0.5)
|
|
out = creases(out)
|
|
return grain(out, 9)
|
|
|
|
|
|
def paper_tex(img, amount=0.5):
|
|
tex = Image.open(SRC / 'paper-crumpled.jpg').convert('L').resize(img.size)
|
|
tex = ImageOps.autocontrast(tex)
|
|
t = np.asarray(tex, dtype=np.float32) / 255
|
|
t = 1 - (1 - t) * amount
|
|
a = np.asarray(img, dtype=np.float32) * t[..., None]
|
|
return Image.fromarray(np.clip(a, 0, 255).astype(np.uint8))
|
|
|
|
|
|
def popart(img, colors=((230, 40, 45), (255, 214, 0), (0, 160, 220), (250, 245, 230)), cell=8):
|
|
"""Comic pop-art: flat colour zones, Ben-Day dots, heavy black outlines."""
|
|
base = img.filter(ImageFilter.MedianFilter(5))
|
|
base = ImageEnhance.Color(base).enhance(1.6)
|
|
pal = np.array(colors, dtype=np.float32)
|
|
a = np.asarray(base, dtype=np.float32)
|
|
idx = ((a[:, :, None, :] - pal[None, None]) ** 2).sum(-1).argmin(-1)
|
|
flat = pal[idx]
|
|
lum = np.asarray(img.convert('L'), dtype=np.float32) / 255
|
|
dots = _halftone_mask(np.clip((0.75 - lum) * 1.4, 0, 1), cell=cell, angle=15)
|
|
flat = np.where(dots[..., None], flat * 0.55, flat)
|
|
flat = np.where((lum < 0.16)[..., None], 20, flat)
|
|
edges = _ink_edges(img, thresh=20, thick=5)
|
|
flat = np.where(edges[..., None], 18, flat)
|
|
return grain(Image.fromarray(np.clip(flat, 0, 255).astype(np.uint8)), 6)
|
|
|
|
|
|
ASCII_RAMP = ' .:-=+*#%@'
|
|
|
|
|
|
def ascii_art(img, cols=72, fg=(120, 255, 160), bg=(6, 14, 9), font_px=14, ramp=ASCII_RAMP, color=False):
|
|
"""Redraw the photo as monospaced characters (terminal style)."""
|
|
from PIL import ImageDraw, ImageFont
|
|
font = None
|
|
for f in ('/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf',
|
|
'/Library/Fonts/Menlo.ttc', '/System/Library/Fonts/Menlo.ttc', 'C:/Windows/Fonts/consolab.ttf'):
|
|
if Path(f).exists():
|
|
font = ImageFont.truetype(f, font_px)
|
|
break
|
|
font = font or ImageFont.load_default(size=font_px)
|
|
cw = font.getbbox('M')[2]
|
|
ch = int(font_px * 1.15)
|
|
rows = max(1, int(cols * img.height / img.width * cw / ch))
|
|
small = ImageOps.autocontrast(img.resize((cols, rows), Image.BOX), cutoff=2)
|
|
small = ImageEnhance.Contrast(small).enhance(1.4)
|
|
lum = np.asarray(small.convert('L'), dtype=np.float32) / 255
|
|
rgb = np.asarray(small, dtype=np.uint8)
|
|
out = Image.new('RGB', (cols * cw, rows * ch), bg)
|
|
draw = ImageDraw.Draw(out)
|
|
n = len(ramp) - 1
|
|
if sum(bg) > 382: # light paper: dark ink should mark the dark areas
|
|
lum = 1 - lum
|
|
for r in range(rows):
|
|
for c in range(cols):
|
|
v = lum[r, c]
|
|
char = ramp[int(v * n)]
|
|
if char != ' ':
|
|
col = tuple(int(x) for x in rgb[r, c]) if color else fg
|
|
draw.text((c * cw, r * ch), char, font=font, fill=col)
|
|
return out
|
|
|
|
|
|
LOOKS = {'toon': toon, 'pixel': pixel, 'xerox': xerox, 'riso': riso, 'vintage': vintage,
|
|
'jsr': jsr, 'popart': popart, 'ascii': ascii_art}
|
|
|
|
# (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, {}),
|
|
# street-poster set (stand-ins until the new stock photos are sourced)
|
|
('motorcycle', 'jsr', 1100, {}),
|
|
('guitar-strat', 'jsr', 900, {'ink': (30, 60, 140), 'paper': (240, 228, 200)}),
|
|
('cta-sign', 'popart', 900, {}),
|
|
('guitar-strat', 'popart', 900, {}),
|
|
('synth', 'jsr', 900, {'ink': (150, 30, 40), 'paper': (245, 222, 180)}),
|
|
('cassette', 'ascii', 900, {}),
|
|
('tv', 'ascii', 800, {'fg': (46, 92, 44), 'bg': (226, 233, 150)}),
|
|
]
|
|
|
|
|
|
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()
|