staging-tester / ocean-landing-serve / scripts/ ascii-portrait.py

# Usage: uv run --with pillow --with numpy python -I scripts/ascii-portrait.py static/team/fenil-sonani-portrait.webp 120 0.12 1.2
# Draws a portrait in ink on a light ground over the whole photo (no trimming, so it registers with the photo).
# The flat wall is blanked by hue so the person stands alone; darker means a denser glyph and a deeper blue. Every
# pixel of the person gets at least the floor of ink so lit skin keeps its outline, a gamma spreads the face across
# the ramp, and edges get a lift. A second block after --- holds one shade digit per glyph (0 darkest to 4 lightest).
import sys, colorsys
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter

src, cols = sys.argv[1], int(sys.argv[2])
floor = float(sys.argv[3]) if len(sys.argv) > 3 else 0.12
gamma = float(sys.argv[4]) if len(sys.argv) > 4 else 1.0

# Cells run about 1.9 times taller than wide, matching type-portrait in layout.css.
cw, ch = 12, 23
ramp = '.:-=+*#%@'

im = Image.open(src).convert('RGB')
w, h = im.size
rows = round(cols * (h / w) * (cw / ch))
small = ImageEnhance.Contrast(im.filter(ImageFilter.UnsharpMask(3, 120, 2))).enhance(1.25).resize((cols, rows), Image.LANCZOS)
rgb = np.asarray(small, dtype=np.float64) / 255
hue, sat, val = np.vectorize(colorsys.rgb_to_hsv)(rgb[..., 0], rgb[..., 1], rgb[..., 2])
deg = hue * 360
wall = (sat > 0.22) & ((deg > 330) | (deg < 2)) & (val > 0.35)
lum = rgb @ np.array([0.299, 0.587, 0.114])
edge = np.asarray(small.convert('L').filter(ImageFilter.FIND_EDGES), dtype=np.float64)

person = np.sort(lum[~wall])
rank = np.searchsorted(person, lum) / max(1, person.size - 1)
ink = floor + np.clip(1 - rank, 0, 1) ** gamma * (1 - floor)
ink = np.where(edge >= np.quantile(edge[~wall], 0.85), np.minimum(1.0, ink + 0.1), ink)

out, shade = [], []
for y in range(rows):
    line, tone = '', ''
    for x in range(cols):
        if wall[y, x]:
            line += ' '; tone += ' '
            continue
        q = ink[y, x]
        line += ramp[min(len(ramp) - 1, int(q * len(ramp)))]
        tone += str(4 - min(4, int(q * 5)))
    out.append(line); shade.append(tone)
print('rows', len(out), 'cols', cols, file=sys.stderr)
print('\n'.join(out))
print('---')
print('\n'.join(shade))