ExperimentsFable 5.2 Python art (30 images)

Hot air balloons, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""28 Hot air balloons.

Colourful balloons rise over a misty valley at sunrise.
Fable 5.2 Python art experiment: every pixel comes from the code below.
The valley is built far to near from noise ridgelines with bands of mist
between them. Every balloon is a true surface of revolution: for each pixel
the script works out the point on the curved envelope, its panel (gore) and
its angle to the sun, so that the stripes bend round the form and the sunny
side glows. A brush-stroke pass then repaints the picture.
Run: .venv/bin/python scripts/28-hot-air-balloons.py
"""
import os, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

W, H = 1600, 2000
SEED = 28
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '28-hot-air-balloons.png')
F = np.float32
rng = np.random.default_rng(SEED)
SUNX, SUNY = 1010.0, 1066.0


def smooth(a, b, x):
    t = np.clip((x - a) / (b - a + 1e-9), 0, 1)
    return t * t * (3 - 2 * t)


def vnoise(shape, cell, r):
    h, w = shape
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    g = r.random((int(h / cy) + 4, int(w / cx) + 4)).astype(F)
    z = ndi.zoom(g, (cy, cx), order=3 if min(cy, cx) >= 3 else 1)
    oy, ox = int(cy * 1.5), int(cx * 1.5)
    return z[oy:oy + h, ox:ox + w]


def fbm(shape, cell, octaves, r):
    cy, cx = cell if isinstance(cell, tuple) else (cell, cell)
    out = np.zeros(shape, F)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        out += amp * vnoise(shape, (max(1.0, cy), max(1.0, cx)), r)
        tot += amp
        amp *= 0.5
        cy /= 2; cx /= 2
    return out / tot


def fbm1(n, cell, octaves, r):
    out = np.zeros(n, F)
    amp, tot = 1.0, 0.0
    for _ in range(octaves):
        g = r.random(int(n / cell) + 5).astype(F)
        z = ndi.zoom(g, cell, order=3 if cell >= 3 else 1)
        out += amp * z[int(cell * 1.5):int(cell * 1.5) + n]
        tot += amp
        amp *= 0.5
        cell = max(1.0, cell / 2)
    return out / tot


def ramp(t, stops):
    pos = [p for p, _ in stops]
    cols = np.array([c for _, c in stops], F)
    return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F)


YY, XX = np.mgrid[0:H, 0:W].astype(F)
PAL = {
    'rainbow': [(0.86, 0.16, 0.14), (0.96, 0.50, 0.10), (0.98, 0.80, 0.16), (0.36, 0.66, 0.26), (0.10, 0.56, 0.62), (0.16, 0.30, 0.66), (0.48, 0.22, 0.60)],
    'fire': [(0.82, 0.12, 0.12), (0.97, 0.90, 0.78), (0.10, 0.18, 0.40), (0.97, 0.90, 0.78)],
    'sea': [(0.05, 0.50, 0.55), (0.98, 0.80, 0.25), (0.95, 0.42, 0.15), (0.96, 0.92, 0.82)],
    'royal': [(0.42, 0.16, 0.55), (0.96, 0.76, 0.22)],
    'candy': [(0.88, 0.16, 0.22), (0.97, 0.93, 0.86)],
    'sun': [(0.97, 0.55, 0.10), (0.99, 0.82, 0.25), (0.80, 0.20, 0.12)],
    'mint': [(0.20, 0.62, 0.50), (0.96, 0.93, 0.80), (0.92, 0.36, 0.32)],
    'sky': [(0.20, 0.42, 0.78), (0.97, 0.93, 0.86), (0.95, 0.70, 0.20)],
}
SUN_DIR = np.array([0.80, 0.26, 0.42], F)
SUN_DIR /= np.linalg.norm(SUN_DIR)


def balloon(img, cx, cy, R, design, pal, rot=0.0, gores=18, burner=False, haze=0.0, hazecol=(0.9, 0.8, 0.75)):
    """Draw one balloon. The envelope is a surface of revolution with a rounded top and a tapering skirt."""
    top, bot = cy - 1.06 * R, cy + 1.32 * R
    Ht = bot - top
    x0, x1 = max(0, int(cx - R - 4)), min(W, int(cx + R + 4))
    y0, y1 = max(0, int(top - 4)), min(H, int(bot + R * 0.75))
    X = XX[y0:y1, x0:x1] - cx
    Y = YY[y0:y1, x0:x1]
    s = np.clip((Y - top) / Ht, 0, 1)
    sm = 0.44
    up = np.sqrt(np.clip(1 - (1 - s / sm) ** 2, 0, 1))
    lo = 0.20 + 0.80 * np.clip(np.cos(np.clip((s - sm) / (1 - sm), 0, 1) * math.pi / 2), 0, 1) ** 0.85
    rr = R * np.where(s < sm, up, lo)
    drdy = np.gradient(rr, axis=0)
    inside = (np.abs(X) < rr) & (Y >= top) & (Y <= bot)
    edge = np.clip((rr - np.abs(X)) * 1.0 + 0.5, 0, 1) * np.clip((Y - top) + 0.5, 0, 1) * np.clip((bot - Y) + 0.5, 0, 1)
    xn = np.clip(X / np.maximum(rr, 1e-3), -1, 1)
    nz = np.sqrt(1 - xn * xn)
    phi = np.arctan2(xn, nz) + rot
    g = phi / (2 * math.pi) * gores
    gi = np.floor(g).astype(int)
    gf = g - gi
    palc = np.array(pal, F)
    n = len(pal)
    if design == 'gores':
        idx = gi % n
    elif design == 'spiral':
        idx = np.floor(g + s * gores * 0.55).astype(int) % n
    elif design == 'zigzag':
        tri = np.abs(gf - 0.5) * 2
        idx = np.floor(s * 9 + tri * 0.9).astype(int) % n
    elif design == 'checker':
        idx = (gi + np.floor(s * gores * 0.62).astype(int)) % n
    elif design == 'bands':
        idx = np.floor(s * 7.0).astype(int) % n
    else:                                     # 'sunburst': gores at the top, a broad band, then gores again
        band = (s > 0.36) & (s < 0.52)
        idx = np.where(band, n - 1, gi % (n - 1))
    col = palc[idx]
    crown = s < 0.045
    col = np.where(crown[..., None], palc[0][None, None, :] * 0.8, col)
    # each panel bulges a little between its seams
    bulge = 0.90 + 0.10 * np.clip(np.sin(gf * math.pi), 0, 1) ** 0.6
    seam = 1 - 0.20 * np.exp(-(np.minimum(gf, 1 - gf) * 2 * math.pi * rr / gores / 1.6) ** 2)
    nrm = np.stack([xn + 0.35 * np.cos(gf * math.pi) * nz / gores * 6, -drdy, nz], -1)
    nrm /= np.linalg.norm(nrm, axis=-1, keepdims=True)
    ndl = nrm @ SUN_DIR
    lit = np.clip(ndl, 0, 1)
    wrap = np.clip((ndl + 0.55) / 1.55, 0, 1)
    sunc = np.array([1.25, 0.98, 0.70], F)
    shadec = np.array([0.27, 0.25, 0.47], F)
    light = shadec[None, None, :] * (0.75 + 0.25 * np.clip(-nrm[..., 1], 0, 1))[..., None] + sunc[None, None, :] * (0.16 * wrap + 0.98 * lit ** 1.25)[..., None]
    c = col * light * (bulge * seam)[..., None]
    # thin cloth: light shines through on the side away from the viewer's sun
    c += col * (np.clip(xn * 0.8 + 0.2, 0, 1) ** 2 * 0.22 * nz)[..., None] * sunc
    c += (lit ** 6 * 0.20 * nz)[..., None] * np.array([1.0, 0.95, 0.8], F)
    if burner:
        glow = np.exp(-(1 - s) * 5.0) * 0.9
        c += col * glow[..., None] * np.array([1.6, 0.95, 0.35], F) + glow[..., None] * np.array([0.35, 0.16, 0.02], F)
    a = edge * inside
    # mouth of the balloon: a dark opening seen from below
    my = bot
    mr = R * 0.20
    mouth = np.clip(1.2 - np.hypot(X / mr, (Y - my) / (mr * 0.30)), 0, 1) * (np.abs(X) < mr)
    mcol = np.array([0.20, 0.10, 0.08], F) if not burner else np.array([1.0, 0.72, 0.25], F)
    c = c * (1 - mouth[..., None]) + mcol * mouth[..., None]
    a = np.maximum(a, np.clip(mouth * 3, 0, 1) * (Y >= bot - 1))
    # basket and ropes
    by = bot + R * 0.42
    bw, bh = R * 0.115, R * 0.15
    bask = np.clip(bw - np.abs(X) + 0.5, 0, 1) * np.clip(Y - by + 0.5, 0, 1) * np.clip(by + bh - Y + 0.5, 0, 1)
    weave = 0.85 + 0.15 * np.sin(Y * (3.5 if R > 80 else 0) + X * 0.0)
    bcol = np.array([0.42, 0.26, 0.13], F)[None, None, :] * (0.55 + 0.75 * np.clip(xn * 0 + X / max(bw, 1) * 0.5 + 0.5, 0, 1))[..., None] * weave[..., None]
    rim = np.clip(bw * 1.12 - np.abs(X) + 0.5, 0, 1) * np.clip(Y - by + 1.5, 0, 1) * np.clip(by + max(1.5, bh * 0.16) - Y + 0.5, 0, 1)
    for sgn in (-1.0, -0.35, 0.35, 1.0):
        tt = np.clip((Y - bot) / (by - bot), 0, 1)
        lx = sgn * (mr * (1 - tt) + bw * tt)
        rope = np.clip(max(0.7, R * 0.008) - np.abs(X - lx) + 0.5, 0, 1) * (Y > bot) * (Y < by)
        c = c * (1 - rope[..., None]) + np.array([0.16, 0.10, 0.08], F) * rope[..., None]
        a = np.maximum(a, rope * 0.9)
    c = c * (1 - bask[..., None]) + bcol * bask[..., None]
    c = c * (1 - rim[..., None]) + np.array([0.24, 0.14, 0.08], F) * rim[..., None]
    a = np.maximum(a, np.maximum(bask, rim))
    if R > 60:                                 # two tiny passengers
        for px in (-bw * 0.4, bw * 0.35):
            head = np.clip(R * 0.028 - np.hypot(X - px, Y - (by - R * 0.03)) + 0.5, 0, 1)
            c = c * (1 - head[..., None]) + np.array([0.12, 0.09, 0.10], F) * head[..., None]
            a = np.maximum(a, head)
    hz = np.array(hazecol, F)
    c = c * (1 - haze) + hz * haze
    img[y0:y1, x0:x1] = img[y0:y1, x0:x1] * (1 - a[..., None]) + c * a[..., None]
    return (x0, x1, y0, y1, a)


def pine(d, x, base, h, w, col, ss=2):
    """A conifer made of stacked, slightly irregular triangles."""
    tiers = max(4, int(h / 26))
    d.rectangle([(x - w * 0.05) * ss, (base - h * 0.12) * ss, (x + w * 0.05) * ss, base * ss], fill=col)
    for i in range(tiers):
        t = i / tiers
        yb = base - h * 0.08 - (h * 0.92) * t
        yt = yb - h * 0.92 / tiers * 1.9
        ww = w * (1 - t) ** 0.9 * 0.5 + 2
        jit = rng.uniform(-0.12, 0.12) * ww
        d.polygon([((x - ww + jit) * ss, yb * ss), ((x + ww + jit) * ss, yb * ss), (x * ss, max(base - h, yt) * ss)], fill=col)


def scene():
    # ---------------------------------------------------------------- sky
    t = YY / 1250.0
    sky = ramp(t, [(0.0, (0.10, 0.17, 0.42)), (0.25, (0.22, 0.30, 0.58)), (0.48, (0.52, 0.44, 0.66)), (0.66, (0.92, 0.55, 0.50)),
                   (0.82, (1.00, 0.68, 0.36)), (0.93, (1.00, 0.84, 0.50)), (1.3, (1.0, 0.90, 0.62))])
    ds = np.hypot(XX - SUNX, (YY - SUNY) * 1.15)
    sky += (np.exp(-ds / 520.0) * 0.30)[..., None] * np.array([1.0, 0.70, 0.35], F)
    sky += (np.exp(-ds / 150.0) * 0.75)[..., None] * np.array([1.0, 0.85, 0.50], F)
    sky += (np.exp(-ds / 60.0) * 0.9)[..., None] * np.array([1.0, 0.92, 0.65], F)
    # long thin clouds, lit from below
    crng = np.random.default_rng(3)
    cn = fbm((H, W), (60, 520), 5, crng)
    cn2 = fbm((H, W), (26, 200), 4, crng)
    band = np.exp(-((YY - 330) / 260) ** 2) * 0.9 + np.exp(-((YY - 840) / 150) ** 2) * 0.75
    cl = smooth(0.56, 0.70, cn * 0.75 + cn2 * 0.25 + 0.16 * band - 0.08) * smooth(1120, 900, YY)
    under = np.clip(ndi.sobel(ndi.gaussian_filter(cl, 6), 0) * 4.0, -1, 1)
    ccol = ramp(np.clip(YY / 1150, 0, 1), [(0, (0.62, 0.58, 0.80)), (0.5, (0.96, 0.66, 0.66)), (1.0, (1.0, 0.86, 0.60))])
    ccol = ccol * (1.0 + 0.28 * under[..., None]) + np.clip(under, 0, 1)[..., None] * np.array([0.25, 0.14, 0.02], F)
    sky = sky * (1 - 0.70 * cl[..., None]) + ccol * 0.70 * cl[..., None]
    # sun disc
    sd = np.hypot(XX - SUNX, YY - SUNY)
    sky = sky * (1 - smooth(50, 44, sd)[..., None]) + np.array([3.0, 2.8, 2.2], F) * smooth(50, 44, sd)[..., None]
    # soft rays that fan out from the sun
    ang = np.arctan2(YY - SUNY, XX - SUNX)
    rayn = fbm1(4000, 34, 3, crng)
    rays = rayn[np.clip(((ang + math.pi) / (2 * math.pi) * 3999).astype(int), 0, 3999)]
    sky += (smooth(0.52, 0.8, rays) * np.exp(-ds / 600.0) * 0.16)[..., None] * np.array([1.0, 0.85, 0.55], F)
    img = sky.copy()

    # ---------------------------------------------------------------- ridges and mist, far to near
    rr_ = np.random.default_rng(7)
    xs = np.arange(W, dtype=F)
    specs = [  # baseline, noise height, extra rise at left, at right, colour at the top, colour at the base, tree teeth
        (1175, 120, 60, 40, (0.56, 0.44, 0.66), (0.86, 0.62, 0.60), 0),
        (1235, 150, 210, 0, (0.38, 0.36, 0.60), (0.70, 0.54, 0.62), 0),
        (1300, 140, 0, 260, (0.24, 0.30, 0.50), (0.52, 0.46, 0.58), 2),
        (1400, 130, 300, 0, (0.13, 0.24, 0.38), (0.34, 0.38, 0.50), 4),
        (1525, 120, 0, 330, (0.06, 0.16, 0.24), (0.18, 0.28, 0.36), 7),
    ]
    behind = []                                        # balloons that float between the ridges
    mist_n = fbm((H, W), (70, 300), 4, rr_)
    ridges = []
    for i, (base, amp, rl, rright, ctop, cbot, teeth) in enumerate(specs):
        prof = fbm1(W, 300 - 30 * i, 5, rr_)
        ytop = base - amp * (prof - 0.35) - rl * smooth(1000, 0, xs) ** 1.4 - rright * smooth(600, 1600, xs) ** 1.4
        if teeth:
            tn = rr_.random(W // 3 + 2).astype(F)
            ytop = ytop - teeth * 2.2 * np.interp(xs, np.arange(len(tn)) * 3, tn) - teeth * np.abs(np.sin(xs * 0.45 + 3 * prof))
        ridges.append(ytop)
        m = smooth(-1.0, 1.0, YY - ytop[None, :])
        dep = np.clip((YY - ytop[None, :]) / 240.0, 0, 1)
        col = np.array(ctop, F)[None, None, :] * (1 - dep[..., None]) + np.array(cbot, F)[None, None, :] * dep[..., None]
        # the slopes that face the sun catch warm light
        slope = np.gradient(ndi.gaussian_filter1d(ytop, 14))
        facing = np.clip(-slope * np.sign(SUNX - xs) * 1.2, -0.5, 1.0)
        tex = fbm((H, W), (22, 34), 3, rr_)
        warm = np.clip(facing[None, :] * 0.5 + 0.25, 0, 1) * np.exp(-dep * 3.5) * (0.6 + 0.8 * tex)
        col = col * (0.88 + 0.24 * tex[..., None]) + warm[..., None] * np.array([0.60, 0.32, 0.12], F) * (0.5 + 0.12 * i)
        near_sun = np.exp(-((XX - SUNX) / 420.0) ** 2)
        col = col + (np.exp(-np.clip(YY - ytop[None, :], 0, None) / 5.0) * 0.30 * near_sun)[..., None] * np.array([1.0, 0.75, 0.4], F)
        img = img * (1 - m[..., None]) + col * m[..., None]
        if i == 99:
            ry = np.clip((YY - 1440) / 170.0, 0, 1)
            rcx = 830 + 130 * np.sin((YY - 1440) / 58.0) * (0.3 + 0.7 * ry) + 60 * ry
            rw = 5 + 48 * ry ** 1.5
            river = smooth(rw + 3, rw - 3, np.abs(XX - rcx)) * (YY > 1440) * (YY < 1640)
            rcol = np.array([1.0, 0.86, 0.60], F)[None, None, :] * (0.85 + 0.25 * np.sin(YY * 0.9 + XX * 0.05))[..., None]
            img = img * (1 - river[..., None]) + rcol * river[..., None]
        if i == 2:
            behind.append(balloon(img, 585, 1262, 46, 'gores', PAL['sun'], 0.3, 14, haze=0.30))
        # mist that pools behind the next ridge
        yc = base + 95 + 40 * i
        fog = smooth(yc - 120, yc + 40, YY + 130 * (mist_n - 0.5) * (1 + 0.2 * i)) * (0.72 + 0.04 * i)
        fog *= smooth(-30, 60, YY - ytop[None, :]) * 0.7 + 0.3
        fcol = np.array([1.05, 0.80, 0.52], F)[None, None, :] * near_sun[..., None] + np.array([0.72, 0.64, 0.80], F)[None, None, :] * (1 - near_sun[..., None])
        fcol = fcol * (0.92 + 0.16 * mist_n[..., None])
        img = img * (1 - fog[..., None]) + fcol * fog[..., None]
        if i == 3:                                     # the river on the valley floor catches the sky
            ry = np.clip((YY - 1450) / 150.0, 0, 1)
            rcx = 800 + 120 * np.sin((YY - 1450) / 52.0) * (0.3 + 0.7 * ry) + 90 * ry
            rw = 4 + 44 * ry ** 1.4
            river = smooth(rw + 3, rw - 3, np.abs(XX - rcx)) * (YY > 1450) * (YY < 1640) * smooth(0, 30, YY - ytop[None, :])
            rcol = np.array([1.25, 0.95, 0.60], F)[None, None, :] * (0.85 + 0.25 * np.sin(YY * 0.9 + XX * 0.05))[..., None]
            img = img * (1 - 0.9 * river[..., None]) + rcol * 0.9 * river[..., None]

    # ---------------------------------------------------------------- balloons in the open sky (far ones first)
    img_bg = img.copy()
    marks = []
    sky_b = [
        (1262, 1090, 21, 'bands', 'candy', 0.0, 12, False, 0.55),
        (1085, 965, 25, 'gores', 'sky', 0.4, 12, False, 0.50),
        (150, 800, 33, 'spiral', 'mint', 0.0, 12, False, 0.42),
        (700, 1095, 37, 'zigzag', 'royal', 0.2, 12, False, 0.38),
        (770, 400, 44, 'sunburst', 'sun', 0.1, 14, False, 0.33),
        (1420, 860, 58, 'bands', 'candy', 0.0, 16, False, 0.25),
        (262, 1075, 68, 'checker', 'royal', 0.25, 16, True, 0.18),
        (880, 800, 96, 'zigzag', 'sea', 0.1, 18, False, 0.10),
        (1200, 400, 140, 'spiral', 'fire', 0.15, 20, False, 0.04),
        (455, 560, 222, 'gores', 'rainbow', 0.09, 22, True, 0.0),
    ]
    for (cx, cy, R, design, pal, rot, gores, burner, haze) in sky_b:
        hz = img[int(min(H - 1, cy)), int(cx)] * 0.5 + np.array([0.95, 0.80, 0.72], F) * 0.5
        marks.append(balloon(img, cx, cy, R, design, PAL[pal], rot, gores, burner, haze, hz))

    # ---------------------------------------------------------------- foreground hills with pines
    ss = 2
    fg = Image.new('L', (W * ss, H * ss), 0)
    d = ImageDraw.Draw(fg)
    hl = 1760 - 250 * smooth(900, 0, xs) ** 1.3 + 30 * fbm1(W, 160, 3, rr_) + 10
    hr = 1905 - 170 * smooth(900, 1600, xs) ** 1.5 + 24 * fbm1(W, 140, 3, rr_)
    hill = np.minimum(hl, hr)
    d.polygon([(float(x) * ss, float(hill[int(x)]) * ss) for x in range(0, W, 4)] + [(W * ss, H * ss), (0, H * ss)], fill=255)
    prng = np.random.default_rng(41)
    trees = []
    for _ in range(64):
        x = prng.uniform(-20, W + 20)
        if 560 < x < 1180 and prng.random() < 0.85:
            continue
        xi = int(np.clip(x, 0, W - 1))
        edge_k = abs(x - 800) / 800
        h = prng.uniform(120, 300) * (0.45 + 0.75 * edge_k)
        trees.append((hill[xi] + prng.uniform(10, 120), x, h))
    for base_, x, h in sorted(trees):
        pine(d, x, base_, h, h * 0.42, 255, ss)
    fgm = np.asarray(fg.resize((W, H), Image.BOX), F) / 255.0
    ftex = fbm((H, W), (14, 9), 3, rr_)
    fcol = np.array([0.020, 0.060, 0.070], F)[None, None, :] * (0.6 + 0.9 * ftex[..., None])
    # warm rim light on the edges that face the sun
    gx = ndi.sobel(ndi.gaussian_filter(fgm, 1.5), 1)
    gy = ndi.sobel(ndi.gaussian_filter(fgm, 1.5), 0)
    tosun = np.stack([SUNX - XX, SUNY - YY], -1)
    tosun /= np.linalg.norm(tosun, axis=-1, keepdims=True) + 1e-6
    rimk = np.clip(-(gx * tosun[..., 0] + gy * tosun[..., 1]) * 0.9, 0, 1) * (0.5 + 0.9 * ftex)
    fcol = fcol + rimk[..., None] * np.array([0.95, 0.50, 0.16], F) * 0.7
    # sunlit grass on the open slope
    grass = smooth(0.50, 0.75, fbm((H, W), (5, 26), 3, rr_)) * np.exp(-((XX - SUNX) / 600.0) ** 2) * smooth(1650, 1800, YY)
    fcol = fcol + grass[..., None] * np.array([0.13, 0.085, 0.025], F)
    # a last thin veil of low mist in front of the nearest trees
    fog = smooth(1560, 1700, YY + 120 * (mist_n - 0.5)) * smooth(2000, 1760, YY) * 0.13
    out2 = []
    for im in (img_bg, img):
        im = im * (1 - fgm[..., None]) + fcol * fgm[..., None]
        out2.append(im * (1 - fog[..., None]) + np.array([0.90, 0.70, 0.60], F) * fog[..., None])
    img_bg, img = out2

    # ---------------------------------------------------------------- birds
    bl = Image.new('L', (W * ss, H * ss), 0)
    bd = ImageDraw.Draw(bl)
    for (bx, by, sc) in ((930, 560, 1.0), (985, 590, 0.8), (1035, 545, 0.7), (890, 610, 0.6), (1075, 600, 0.55), (1500, 1010, 0.5), (1460, 1035, 0.4)):
        for sgn in (-1, 1):
            pts = [((bx + sgn * 18 * sc * tt) * ss, (by - 9 * sc * math.sin(tt * 2.6) + 4 * sc * tt) * ss) for tt in np.linspace(0, 1, 8)]
            bd.line(pts, fill=255, width=int(max(2, 2.6 * sc * ss)))
    bm = np.asarray(bl.resize((W, H), Image.BOX), F) / 255.0
    img = img * (1 - 0.85 * bm[..., None]) + np.array([0.12, 0.10, 0.16], F) * 0.85 * bm[..., None]
    img_bg = img_bg * (1 - 0.85 * bm[..., None]) + np.array([0.12, 0.10, 0.16], F) * 0.85 * bm[..., None]

    detail = np.zeros((H, W), F)
    for (x0, x1, y0, y1, a) in marks + behind:
        detail[y0:y1, x0:x1] = np.maximum(detail[y0:y1, x0:x1], a)
    bdetail = np.clip(ndi.gaussian_filter(detail, 2.5) * 1.5, 0, 1)
    gdetail = 0.7 * ndi.gaussian_filter(fgm, 3) * (YY < 1800) + 0.5 * bm
    return img_bg, img, gdetail, bdetail


# ----------------------------------------------------------------------------
# Brush engine
# ----------------------------------------------------------------------------
def make_sprite(length, width, ang, r):
    S = int(length + 6) | 1
    yy, xx = np.mgrid[0:S, 0:S].astype(F) - S // 2
    ca, sa = math.cos(ang), math.sin(ang)
    u = xx * ca + yy * sa
    v = -xx * sa + yy * ca
    un = u / (length / 2)
    vn = v / (width / 2)
    nb = max(4, int(width * 1.2))
    bn = ndi.gaussian_filter1d(r.random(nb + 8).astype(F), 1.0)
    bn = (bn - bn.min()) / (bn.max() - bn.min() + 1e-6)
    bi = np.clip(((vn * 0.5 + 0.5) * nb + 4).astype(int), 0, nb + 7)
    bristle = bn[bi]
    endk = 1 - smooth(0.55, 1.0, np.abs(un) + 0.25 * (bristle - 0.5))
    a = endk * (1 - smooth(0.7, 1.0, np.abs(vn)))
    dry = smooth(0.1, 1.0, un) * smooth(0.45, 0.8, bristle)
    a = a * (1 - 0.75 * dry)
    hgt = a * (0.55 + 0.45 * bristle) + 0.35 * a * smooth(0.5, 0.9, np.abs(vn))
    return a.astype(F), hgt.astype(F)


def paint(under, r, layers, detail=None, flow=None, init=None, dw=(0.5, 0.5, 0.4, 0.2, 0.06, 0.03)):
    """Repaint `under` (h, w, 3) with brush strokes. Returns the picture and a paint height map."""
    h, w = under.shape[:2]
    M = 80
    canvas = np.zeros((h + 2 * M, w + 2 * M, 3), F)
    canvas[M:-M, M:-M] = ndi.gaussian_filter(under, (30, 30, 0)) * 0.9
    hmap = np.zeros((h + 2 * M, w + 2 * M), F)
    if init is not None:                      # continue on a canvas that is already painted
        canvas[M:-M, M:-M] = init[0]
        hmap[M:-M, M:-M] = init[1]
    lum = under @ np.array([0.3, 0.5, 0.2], F)
    ls = ndi.gaussian_filter(lum, 5)
    gx = ndi.sobel(ls, 1)
    gy = ndi.sobel(ls, 0)
    # structure tensor: smooth the edge direction over a neighbourhood
    jxx = ndi.gaussian_filter(gx * gx, 10)
    jyy = ndi.gaussian_filter(gy * gy, 10)
    jxy = ndi.gaussian_filter(gx * gy, 10)
    theta = 0.5 * np.arctan2(2 * jxy, jxx - jyy) + math.pi / 2     # along the edge
    cohere = np.sqrt((jxx - jyy) ** 2 + 4 * jxy ** 2)
    cohere = smooth(0.0, np.percentile(cohere, 80), cohere)
    if flow is None:
        flow = (fbm((h, w), 260, 3, r) - 0.5) * 5.0
    theta = np.where(cohere > 0.12, theta, flow)
    NA = 24
    for li, (length, width, count, opac, sig) in enumerate(layers):
        ref = ndi.gaussian_filter(under, (sig, sig, 0))
        sprites = [[make_sprite(length * s, width * s, math.pi * k / NA, r) for k in range(NA)] for s in (0.8, 1.0, 1.25)]
        if li == 0 and init is None:
            n = count
            xs = r.uniform(0, w, n)
            ys = r.uniform(0, h, n)
        else:
            err = np.abs(canvas[M:-M, M:-M] - under).sum(-1)
            err = ndi.gaussian_filter(err, width * 0.6) + 0.004
            if detail is not None:
                err = err * (dw[li] + detail)
            pr = (err ** 1.5).ravel().astype(np.float64)
            pr /= pr.sum()
            idx = r.choice(h * w, size=count, p=pr)
            ys, xs = np.divmod(idx, w)
            xs = xs + r.uniform(-0.5, 0.5, count)
            ys = ys + r.uniform(-0.5, 0.5, count)
            n = count
        xi = np.clip(xs.astype(int), 0, w - 1)
        yi = np.clip(ys.astype(int), 0, h - 1)
        jit = 0.022 if li < 2 else 0.04
        cols = ref[yi, xi] * (1 + r.normal(0, jit, (n, 1))) + r.normal(0, jit * 0.25, (n, 3))
        cols = np.clip(cols, 0, 1.2).astype(F)
        angs = theta[yi, xi] + r.normal(0, 0.22, n)
        ak = np.round(angs / (math.pi / NA)).astype(int) % NA
        sk = r.integers(0, 3, n)
        for i in range(n):
            a, hg = sprites[sk[i]][ak[i]]
            S = a.shape[0]
            y0 = int(ys[i]) + M - S // 2
            x0 = int(xs[i]) + M - S // 2
            if y0 < 0 or x0 < 0 or y0 + S > h + 2 * M or x0 + S > w + 2 * M:
                continue
            ao = a * opac
            cv = canvas[y0:y0 + S, x0:x0 + S]
            cv += (cols[i] - cv) * ao[..., None]
            hv = hmap[y0:y0 + S, x0:x0 + S]
            hv += (hg * (0.6 + 0.4 * width / layers[0][1]) + 0.15 * hv - hv) * ao
        print('  layer %d (%d strokes) %.1fs' % (li, n, time.time() - T0))
    return canvas[M:-M, M:-M], hmap[M:-M, M:-M]


def relief(img, hmap, r, strength=1.0):
    hs = ndi.gaussian_filter(hmap, 0.8)
    gx = ndi.sobel(hs, 1)
    gy = ndi.sobel(hs, 0)
    shade = np.clip(-(gx * -0.7 + gy * -0.7) * 0.22 * strength, -0.22, 0.30)
    h, w = hmap.shape
    yy, xx = np.mgrid[0:h, 0:w].astype(F)
    weave = 0.5 * np.sin(xx * 1.9) * np.sin(yy * 1.9) + (r.random((h, w)).astype(F) - 0.5)
    out = img * (1 + shade[..., None]) + np.clip(shade, 0, 1)[..., None] * 0.05
    return out * (1 + 0.018 * weave[..., None])


def grade(img):
    """Tone curve and richer colour for the underpainting."""
    img = 1 - np.exp(-img * 1.75)
    img = np.clip(img, 0, 1) ** 1.12
    g = img.mean(-1, keepdims=True)
    return np.clip(g + (img - g) * 1.28, 0, 1).astype(F)


def main():
    img_bg, img, gdetail, bdetail = scene()
    print('scene %.1fs' % (time.time() - T0))
    under_bg, under = grade(img_bg), grade(img)
    flow = (fbm((H, W), 300, 2, rng) - 0.5) * 0.7            # sky strokes run nearly level
    # pass 1: the landscape and the sky, with large to small strokes
    layers = [  # length, width, count, opacity, colour blur
        (210, 70, 2600, 0.95, 12),
        (130, 42, 5600, 0.93, 7),
        (76, 25, 12000, 0.92, 4),
        (42, 14, 24000, 0.9, 2.2),
        (22, 8, 30000, 0.9, 1.2),
        (12, 4.5, 16000, 0.86, 0.7),
    ]
    canvas, hmap = paint(under_bg, rng, layers, detail=gdetail, flow=flow)
    # pass 2: the balloons, painted on top with fine strokes only
    layers2 = [
        (46, 17, 2600, 0.94, 2.2),
        (24, 9, 16000, 0.92, 1.1),
        (13, 5, 30000, 0.9, 0.7),
        (8, 3.2, 26000, 0.88, 0.5),
    ]
    canvas, hmap = paint(under, rng, layers2, detail=bdetail, flow=flow, init=(canvas, hmap), dw=(0.004, 0.004, 0.004, 0.004))
    out = relief(canvas, hmap, rng, 0.7)
    yy, xx = np.mgrid[0:H, 0:W].astype(F)
    vig = 1 - 0.22 * smooth(0.55, 1.25, np.hypot((xx - W * 0.5) / W, (yy - H * 0.5) / H) * 1.6)
    out = np.clip(out * vig[..., None], 0, 1)
    Image.fromarray((out * 255 + 0.5).astype(np.uint8)).save(OUT)
    print('saved %s  %.1fs' % (os.path.abspath(OUT), time.time() - T0))


if __name__ == '__main__':
    main()