ExperimentsFable 5.2 Python art (30 images)

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

A fern drawn as a vintage botanical plate: watercolour over fine ink lines on aged paper.
Fable 5.2 Python art experiment: every pixel comes from the code below.
The fronds grow from an L-system: a short set of rewriting rules ("a stem piece
becomes a stem piece plus two side branches plus a new tip") that is applied again
and again, then drawn by a "turtle" that walks and turns. The leaflets are painted
as transparent washes that darken where they overlap and at their edges, as real
watercolour does. The numerals are built from strokes; no font is used.
Run: .venv/bin/python scripts/27-botanical-fern.py
"""
import os, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

W, H = 1600, 2000
SS = 2
SEED = 27
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '27-botanical-fern.png')
F = np.float32
rng = np.random.default_rng(SEED)


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
    g = r.random((int(h / cell) + 4, int(w / cell) + 4)).astype(F)
    z = ndi.zoom(g, cell, order=3 if cell >= 3 else 1)
    o = int(cell * 1.5)
    return z[o:o + h, o:o + w]


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


# ----------------------------------------------------------------------------
# L-system
# ----------------------------------------------------------------------------
def rewrite(mods, rules, max_iter=200):
    """Apply the rules to every symbol until nothing changes."""
    for _ in range(max_iter):
        out = []
        changed = False
        for m in mods:
            fn = rules.get(m[0])
            if fn is None:
                out.append(m)
            else:
                out.extend(fn(*m[1:]))
                changed = True
        mods = out
        if not changed:
            break
    return mods


def frond_rules(N, seg0, pinna_max, curve, r, droop=0.0):
    """Rules for one frond. A = growing tip of the main stem, P = side branch (pinna),
    B = growing tip of a side branch, L = leaflet, F/f = stem pieces, + = turn, [ ] = branch."""
    def A(i):
        if i >= N:
            return [('L', seg0 * 1.2, seg0 * 0.45, 0.0, 1.0)]
        t = i / N
        seg = seg0 * (1 - 0.55 * t)
        s = pinna_max * 1.75 * (t + 0.04) ** 0.42 * (1 - t) ** 1.05
        ang = math.radians(74 - 26 * t)
        turn = math.radians(curve / N * (0.4 + 1.6 * t) + droop / N * 3 * t * t + r.normal(0, 0.6))
        return [('F', seg, 1 - t), ('[',), ('+', -ang + r.normal(0, 0.04)), ('P', s * r.uniform(0.92, 1.05), -1, t), (']',),
                ('F', seg * 0.5, 1 - t),
                ('[',), ('+', ang + r.normal(0, 0.04)), ('P', s * r.uniform(0.92, 1.05), 1, t), (']',), ('+', turn), ('A', i + 1)]

    def P(s, side, t):
        n = max(2, int(s / 11.0))
        return [('B', s, side, 0, n, t)]

    def B(s, side, j, n, t):
        u = j / n
        if j >= n:
            return [('L', s * 0.10 + 4, s * 0.035 + 2, 0.0, t)]
        step = s / n * (1.12 - 0.24 * u)
        ll = (s * 0.19 + 5) * (1 - u) ** 0.75 * (0.55 + 0.45 * smooth(0, 0.12, u + 0.02))
        lw = ll * 0.40 + 1.5
        a = math.radians(62 - 14 * u)
        out = [('f', step, 1 - u)]
        out += [('[',), ('+', -a + r.normal(0, 0.05)), ('L', ll * (1.0 if side > 0 else 0.92), lw, 0.25, t), (']',)]
        out += [('[',), ('+', a + r.normal(0, 0.05)), ('L', ll * (0.92 if side > 0 else 1.0), lw, -0.25, t), (']',)]
        out += [('+', math.radians(side * -1.4 + r.normal(0, 0.5))), ('B', s, side, j + 1, n, t)]
        return out

    return {'A': A, 'P': P, 'B': B}


class Turtle:
    def __init__(self):
        self.stems = []      # (x0, y0, x1, y1, width, kind)
        self.leaves = []     # (polygon, midrib, t along frond, layer)

    def run(self, mods, x, y, heading, stem_w, layer, r):
        stack = []
        pin = 0
        for m in mods:
            c = m[0]
            if c in ('F', 'f'):
                L = m[1]
                nx, ny = x + L * math.cos(heading), y + L * math.sin(heading)
                wd = stem_w * (0.25 + 0.75 * m[2]) if c == 'F' else 1.3 * (0.4 + 0.6 * m[2])
                self.stems.append((x, y, nx, ny, wd, c))
                x, y = nx, ny
            elif c == '+':
                heading += m[1]
            elif c == '[':
                stack.append((x, y, heading)); pin += 1
            elif c == ']':
                x, y, heading = stack.pop()
            elif c == 'L':
                self.leaves.append(leaflet(x, y, heading, m[1], m[2], m[3], r) + (m[4], (pin // 3 + layer) % 2))
        return x, y, heading


def leaflet(x, y, heading, L, Wd, falc, r):
    n = 9 if L < 22 else 15
    t = np.linspace(0, 1, n)
    half = Wd / 2 * np.sin(math.pi * t ** 0.72) ** 0.65
    if L >= 22:
        half *= 1 + 0.16 * np.sin(t * math.pi * (5 + L / 14)) ** 2 * (1 - t)       # scalloped edge on big leaflets
    hd = heading + falc * t
    dx = np.cumsum(np.r_[0, np.cos(hd[1:]) * L / (n - 1)])
    dy = np.cumsum(np.r_[0, np.sin(hd[1:]) * L / (n - 1)])
    ax = x + dx; ay = y + dy
    nxv, nyv = -np.sin(hd), np.cos(hd)
    left = np.stack([ax + nxv * half, ay + nyv * half], 1)
    right = np.stack([ax - nxv * half * 0.88, ay - nyv * half * 0.88], 1)
    return (np.vstack([left, right[::-1]]), np.stack([ax, ay], 1))


def main():
    yy, xx = np.mgrid[0:H, 0:W].astype(F)
    # ------------------------------------------------------------ grow the plant
    tur = Turtle()
    base = (770.0, 1560.0)
    fronds = [  # start offset, heading (deg, -90 is up), stipe pieces, N, piece, pinna size, curve, stem width, layer
        ((14, -6), -94, 8, 46, 24.0, 228, 60, 10.5, 0, 34),
        ((-18, -4), -109, 6, 38, 20.0, 180, -60, 9.0, 1, -38),
        ((36, 4), -48, 5, 27, 19.0, 130, 36, 6.5, 0, 34),
    ]
    tips = []
    for (off, hd, nst, N, seg, pm, curve, sw, layer, droop) in fronds:
        frng = np.random.default_rng(100 + N)
        mods = [('F', seg * 1.5, 1.0), ('+', math.radians(curve / (N + nst) * 0.3))] * nst + [('A', 0)]
        mods = rewrite(mods, frond_rules(N, seg, pm, curve, frng, droop))
        tips.append(tur.run(mods, base[0] + off[0], base[1] + off[1], math.radians(hd), sw, layer, frng))
    print('L-system: %d leaflets, %d stem pieces  %.1fs' % (len(tur.leaves), len(tur.stems), time.time() - T0))

    # ------------------------------------------------------------ draw washes and ink at double size
    wash = [Image.new('RGB', (W * SS, H * SS), (255, 255, 255)) for _ in range(3)]
    wd_ = [ImageDraw.Draw(w) for w in wash]
    ink = Image.new('L', (W * SS, H * SS), 0)
    di = ImageDraw.Draw(ink)

    def S(pts):
        return [(float(px) * SS, float(py) * SS) for px, py in pts]

    def col8(c):
        return tuple(int(max(0, min(255, v * 255))) for v in c)

    def ribbon(pts, widths):
        p = np.asarray(pts, float)
        tg = np.gradient(p, axis=0)
        tg /= np.hypot(tg[:, 0], tg[:, 1])[:, None] + 1e-9
        nr = np.stack([-tg[:, 1], tg[:, 0]], 1)
        wv = np.asarray(widths, float)[:, None]
        return np.vstack([p + nr * wv, (p - nr * wv)[::-1]])

    YOUNG = np.array([0.60, 0.70, 0.30]); MATURE = np.array([0.33, 0.52, 0.24]); DEEP = np.array([0.20, 0.38, 0.22])
    BROWN = np.array([0.62, 0.48, 0.24])
    cn = fbm((H // 4, W // 4), 40, 3, np.random.default_rng(5))
    lrng = np.random.default_rng(6)
    for (poly, mid, t, layer) in tur.leaves:
        cx, cy = mid[len(mid) // 2]
        k = cn[int(np.clip(cy / 4, 0, H // 4 - 1)), int(np.clip(cx / 4, 0, W // 4 - 1))]
        g = np.clip(k * 1.5 - 0.25 + lrng.normal(0, 0.10), 0, 1)
        c = MATURE * (1 - g) + DEEP * g
        c = c * (1 - 0.55 * t ** 2.2) + YOUNG * 0.55 * t ** 2.2            # young growth at the frond tip
        if lrng.random() < 0.035:
            c = c * 0.5 + BROWN * 0.5                                    # a few leaflets have begun to turn
        c = c + lrng.normal(0, 0.018, 3)
        wd_[layer].polygon(S(poly), fill=col8(c))
        di.line(S(np.vstack([poly, poly[:1]])), fill=120, width=2)
        di.line(S(mid[: max(2, int(len(mid) * 0.8))]), fill=150, width=2)
    # stems: brown-green wash plus ink edges
    for (x0, y0, x1, y1, wdt, kind) in tur.stems:
        if kind == 'F':
            poly = ribbon([(x0, y0), (x1, y1)], [wdt / 2 + 0.6, wdt / 2 + 0.6])
            wd_[2].polygon(S(poly), fill=col8((0.50, 0.40, 0.20)))
            wd_[2].ellipse([(x1 - wdt / 2) * SS, (y1 - wdt / 2) * SS, (x1 + wdt / 2) * SS, (y1 + wdt / 2) * SS], fill=col8((0.50, 0.40, 0.20)))
            nx_, ny_ = -(y1 - y0), (x1 - x0)
            nl = math.hypot(nx_, ny_) + 1e-9
            nx_, ny_ = nx_ / nl * wdt / 2, ny_ / nl * wdt / 2
            di.line(S([(x0 + nx_, y0 + ny_), (x1 + nx_, y1 + ny_)]), fill=215, width=2)
            di.line(S([(x0 - nx_, y0 - ny_), (x1 - nx_, y1 - ny_)]), fill=170, width=2)
        else:
            di.line(S([(x0, y0), (x1, y1)]), fill=205, width=max(2, int(wdt * SS)))
    # thin brown scales on the lower stems
    srng = np.random.default_rng(8)
    for (x0, y0, x1, y1, wdt, kind) in tur.stems:
        if kind == 'F' and wdt > 6.0 and y0 > 1050:
            for _ in range(3):
                a = srng.uniform(0, 1)
                px, py = x0 + (x1 - x0) * a, y0 + (y1 - y0) * a
                ang = math.atan2(y1 - y0, x1 - x0) + srng.choice([-1, 1]) * srng.uniform(0.5, 1.2)
                L = srng.uniform(5, 12)
                di.line(S([(px, py), (px + L * math.cos(ang), py + L * math.sin(ang))]), fill=170, width=2)

    # ------------------------------------------------------------ fiddlehead (a young, coiled frond)
    fpts = []
    x, y, hd = base[0] - 50, base[1] + 2, math.radians(-163)
    for i in range(36):
        hd += math.radians(0.55)
        x += 7.4 * math.cos(hd); y += 7.4 * math.sin(hd)
        fpts.append((x, y))
    turn = 3.4
    for i in range(112):
        hd += math.radians(turn)
        turn *= 1.0150
        step = max(1.2, 6.4 * 0.987 ** i)
        x += step * math.cos(hd); y += step * math.sin(hd)
        fpts.append((x, y))
    fpts = np.array(fpts)
    fw = np.linspace(7.5, 2.4, len(fpts))
    wd_[2].polygon(S(ribbon(fpts, fw)), fill=col8((0.52, 0.56, 0.26)))
    rb = ribbon(fpts, fw)
    di.line(S(rb[:len(fpts)]), fill=215, width=2)
    di.line(S(rb[len(fpts):]), fill=170, width=2)
    tgf = np.gradient(fpts, axis=0)
    for i in range(40, len(fpts) - 6, 3):                                   # tiny folded leaflets inside the coil and hairs outside
        ang = math.atan2(tgf[i][1], tgf[i][0])
        sz = 21 * (1 - (i - 38) / 112) + 4
        poly, mid = leaflet(fpts[i][0], fpts[i][1], ang + 1.25, sz, sz * 0.5, 0.9, srng)
        wd_[0].polygon(S(poly), fill=col8((0.50, 0.63, 0.28)))
        di.line(S(np.vstack([poly, poly[:1]])), fill=120, width=2)
    for i in range(0, 120, 2):
        ang = math.atan2(tgf[i][1], tgf[i][0]) - srng.uniform(0.6, 1.3)
        L = srng.uniform(5, 13)
        px, py = fpts[i] + np.array([math.cos(ang - 0.3), math.sin(ang - 0.3)]) * fw[i]
        di.line(S([(px, py), (px + L * math.cos(ang), py + L * math.sin(ang))]), fill=165, width=2)

    # ------------------------------------------------------------ rhizome and roots
    rrng = np.random.default_rng(9)
    for k in range(26):
        cx_ = base[0] + rrng.normal(0, 46); cy_ = base[1] + 14 + rrng.normal(0, 13)
        rx, ry = rrng.uniform(16, 34), rrng.uniform(11, 20)
        c = np.array([0.42, 0.28, 0.15]) * rrng.uniform(0.8, 1.25)
        wd_[k % 2].ellipse([(cx_ - rx) * SS, (cy_ - ry) * SS, (cx_ + rx) * SS, (cy_ + ry) * SS], fill=col8(c))
        pts = [(cx_ + rx * math.cos(a), cy_ + ry * math.sin(a)) for a in np.linspace(0.3, 2.6, 12) + rrng.uniform(0, 6)]
        di.line(S(pts), fill=200, width=2)
        for _ in range(4):
            a = rrng.uniform(0, 6.28); L = rrng.uniform(4, 10)
            di.line(S([(cx_ + rx * 0.5 * math.cos(a), cy_ + ry * 0.5 * math.sin(a)),
                       (cx_ + rx * 0.5 * math.cos(a) + L, cy_ + ry * 0.5 * math.sin(a) + L * 0.6)]), fill=150, width=2)

    def root(x, y, hd, L, wdt, depth):
        pts = [(x, y)]
        n = int(L / 7)
        for i in range(n):
            hd += rrng.normal(0, 0.16) + 0.02 * math.copysign(1, math.cos(hd)) * 0 + 0.03 * (math.pi / 2 - hd)
            x += 7 * math.cos(hd); y += 7 * math.sin(hd)
            pts.append((x, y))
            if depth > 0 and rrng.random() < 0.13:
                root(x, y, hd + rrng.choice([-1, 1]) * rrng.uniform(0.4, 1.0), L * rrng.uniform(0.25, 0.5), wdt * 0.6, depth - 1)
        for i in range(len(pts) - 1):
            wv = max(1.0, wdt * (1 - i / len(pts)))
            di.line(S(pts[i:i + 2]), fill=int(150 + 60 * (1 - i / len(pts))), width=max(1, int(round(wv * SS))))

    for k in range(30):
        root(base[0] + rrng.normal(0, 44), base[1] + 22 + rrng.uniform(0, 8), math.pi / 2 + rrng.normal(0, 0.75),
             rrng.uniform(90, 250), rrng.uniform(1.4, 2.6), 2)

    # ------------------------------------------------------------ detail figures
    # II: a leaflet from below, enlarged, with its two rows of spore dots (sori)
    c2 = (300.0, 1690.0); R2 = 158.0
    for rr, wv in ((R2, 3), (R2 - 9, 1)):
        di.ellipse([(c2[0] - rr) * SS, (c2[1] - rr) * SS, (c2[0] + rr) * SS, (c2[1] + rr) * SS], outline=215, width=wv * SS)
    poly, mid = leaflet(c2[0] - 112, c2[1] + 62, math.radians(-30), 262, 122, 0.18, srng)
    # make the big leaflet lobed
    wd_[0].polygon(S(poly), fill=col8((0.62, 0.72, 0.42)))
    di.line(S(np.vstack([poly, poly[:1]])), fill=215, width=3)
    di.line(S(mid[:-1]), fill=215, width=4)
    nl = len(mid)
    for j in range(2, nl - 2):
        tgx, tgy = mid[j + 1] - mid[j - 1]
        tl = math.hypot(tgx, tgy); tgx /= tl; tgy /= tl
        for side in (-1, 1):
            edge = poly[j] if side > 0 else poly[len(poly) - 1 - j]
            vx, vy = edge - mid[j]
            vl = math.hypot(vx, vy)
            if vl < 12:
                continue
            e2 = mid[j] + np.array([vx, vy]) * 0.88 + np.array([tgx, tgy]) * vl * 0.45
            di.line(S([mid[j], mid[j] + (e2 - mid[j]) * 0.5 + np.array([tgx, tgy]) * 2, e2]), fill=130, width=2)
            if vl > 22:
                sc = mid[j] + np.array([vx, vy]) * 0.52 + np.array([tgx, tgy]) * vl * 0.10
                rs = min(10.5, vl * 0.20)
                wd_[1].ellipse([(sc[0] - rs) * SS, (sc[1] - rs) * SS, (sc[0] + rs) * SS, (sc[1] + rs) * SS], fill=col8((0.62, 0.36, 0.14)))
                wd_[2].ellipse([(sc[0] - rs * 0.45) * SS, (sc[1] - rs * 0.45) * SS, (sc[0] + rs * 0.45) * SS, (sc[1] + rs * 0.45) * SS], fill=col8((0.50, 0.26, 0.10)))
                di.ellipse([(sc[0] - rs) * SS, (sc[1] - rs) * SS, (sc[0] + rs) * SS, (sc[1] + rs) * SS], outline=190, width=2)
    # dashed leader from the circle to a real leaflet on the left frond
    tx, ty = 430.0, 1010.0
    a0 = math.atan2(ty - c2[1], tx - c2[0])
    sx_, sy_ = c2[0] + R2 * math.cos(a0), c2[1] + R2 * math.sin(a0)
    for k in range(0, 40, 2):
        p0 = (sx_ + (tx - sx_) * k / 40, sy_ + (ty - sy_) * k / 40)
        p1 = (sx_ + (tx - sx_) * (k + 1) / 40, sy_ + (ty - sy_) * (k + 1) / 40)
        di.line(S([p0, p1]), fill=150, width=2)
    di.ellipse([(tx - 17) * SS, (ty - 17) * SS, (tx + 17) * SS, (ty + 17) * SS], outline=170, width=2)

    # III: a spore case (sporangium) on its stalk, with the ring of thick cells and loose spores
    c3 = (1290.0, 1700.0)
    stalk = [(c3[0] - 60 + 14 * math.sin(k / 4), c3[1] + 150 - k * 9) for k in range(12)]
    wd_[2].polygon(S(ribbon(stalk, np.linspace(7, 5, 12))), fill=col8((0.80, 0.70, 0.42)))
    rbs = ribbon(stalk, np.linspace(7, 5, 12))
    di.line(S(rbs[:12]), fill=210, width=2); di.line(S(rbs[12:]), fill=210, width=2)
    for k in range(1, 11, 2):
        di.line(S([rbs[k], rbs[23 - k]]), fill=120, width=2)
    cc = (c3[0] + 8, c3[1] - 12)
    ex, ey = 86, 72
    wd_[0].ellipse([(cc[0] - ex) * SS, (cc[1] - ey) * SS, (cc[0] + ex) * SS, (cc[1] + ey) * SS], fill=col8((0.90, 0.80, 0.50)))
    di.ellipse([(cc[0] - ex) * SS, (cc[1] - ey) * SS, (cc[0] + ex) * SS, (cc[1] + ey) * SS], outline=215, width=3)
    angs = np.linspace(math.radians(120), math.radians(400), 22)
    for i in range(len(angs) - 1):
        a0_, a1_ = angs[i], angs[i + 1]
        quad = [(cc[0] + ex * math.cos(a0_), cc[1] + ey * math.sin(a0_)), (cc[0] + ex * math.cos(a1_), cc[1] + ey * math.sin(a1_)),
                (cc[0] + (ex + 20) * math.cos(a1_), cc[1] + (ey + 20) * math.sin(a1_)), (cc[0] + (ex + 20) * math.cos(a0_), cc[1] + (ey + 20) * math.sin(a0_))]
        wd_[1].polygon(S(quad), fill=col8((0.70, 0.46, 0.20)))
        di.line(S(quad + quad[:1]), fill=215, width=2)
    for _ in range(46):                                                     # spores inside the case
        a = srng.uniform(0, 6.28); rr = math.sqrt(srng.uniform(0, 0.78))
        px, py = cc[0] + ex * rr * math.cos(a), cc[1] + ey * rr * math.sin(a)
        wd_[2].ellipse([(px - 7) * SS, (py - 7) * SS, (px + 7) * SS, (py + 7) * SS], fill=col8((0.58, 0.38, 0.16)))
        di.ellipse([(px - 7) * SS, (py - 7) * SS, (px + 7) * SS, (py + 7) * SS], outline=150, width=2)
    for _ in range(16):                                                     # and a few that escape
        px, py = cc[0] + srng.uniform(60, 190), cc[1] - srng.uniform(70, 190)
        wd_[2].ellipse([(px - 5) * SS, (py - 5) * SS, (px + 5) * SS, (py + 5) * SS], fill=col8((0.58, 0.38, 0.16)))
        di.ellipse([(px - 5) * SS, (py - 5) * SS, (px + 5) * SS, (py + 5) * SS], outline=150, width=2)

    # Roman numerals for the three figures and a scale bar, from strokes
    def numeral(x, y, n, h=26):
        for k in range(n):
            px = x + k * 12
            di.line(S([(px, y), (px, y + h)]), fill=215, width=5)
        di.line(S([(x - 6, y), (x + (n - 1) * 12 + 6, y)]), fill=215, width=3)
        di.line(S([(x - 6, y + h), (x + (n - 1) * 12 + 6, y + h)]), fill=215, width=3)
        px = x + (n - 1) * 12 + 13
        di.ellipse([(px - 2.5) * SS, (y + h - 3) * SS, (px + 2.5) * SS, (y + h + 2) * SS], fill=215)

    numeral(905, 1590, 1)
    numeral(120, 1500, 2)
    numeral(1130, 1560, 3)
    di.line(S([(650, 1880), (950, 1880)]), fill=215, width=3)
    for k in range(7):
        px = 650 + k * 50
        di.line(S([(px, 1880 - (12 if k % 2 == 0 else 7)), (px, 1880)]), fill=215, width=3)
    # plate border: a thin double line
    for m_, wv in ((70, 3), (82, 1)):
        di.rectangle([m_ * SS, m_ * SS, (W - m_) * SS, (H - m_) * SS], outline=190, width=wv * SS)
    print('drawn %.1fs' % (time.time() - T0))

    # ------------------------------------------------------------ paper
    prng = np.random.default_rng(15)
    paper = np.array([0.930, 0.880, 0.760], F)[None, None, :] * np.ones((H, W, 1), F)
    big = fbm((H, W), 420, 4, prng)
    paper *= (0.93 + 0.13 * big)[..., None]
    grainp = fbm((H, W), 3, 2, prng)
    paper *= (0.975 + 0.05 * grainp)[..., None]
    fib = Image.new('L', (W, H), 128)
    fd = ImageDraw.Draw(fib)
    for _ in range(4200):
        x, y = prng.uniform(0, W), prng.uniform(0, H)
        a = prng.uniform(0, math.pi); L = prng.uniform(6, 30)
        fd.line([(x, y), (x + L * math.cos(a), y + L * math.sin(a))], fill=int(128 + prng.choice([-1, 1]) * prng.uniform(10, 34)), width=1)
    paper *= (1 + 0.45 * ndi.gaussian_filter((np.asarray(fib, F) - 128) / 255, 0.6))[..., None]
    # foxing: small rusty age spots, and one old water stain with a darker rim
    fox = np.zeros((H, W), F)
    for _ in range(170):
        x, y = prng.uniform(0, W), prng.uniform(0, H)
        r_ = prng.uniform(1.5, 9) * (1 + 2.0 * (prng.random() < 0.08))
        ys, xs = slice(max(0, int(y - 40)), int(y + 40)), slice(max(0, int(x - 40)), int(x + 40))
        fox[ys, xs] += np.exp(-((xx[ys, xs] - x) ** 2 + (yy[ys, xs] - y) ** 2) / (r_ * r_)) * prng.uniform(0.15, 0.6)
    paper *= 1 - np.clip(fox, 0, 0.8)[..., None] * np.array([0.22, 0.36, 0.55], F)
    ds = np.hypot((xx - 1500) / 1.0, (yy - 190) / 0.8) + 90 * (fbm((H, W), 120, 3, prng) - 0.5)
    stain = smooth(330, 290, ds) * 0.05 + np.exp(-((ds - 310) / 9.0) ** 2) * 0.10
    paper *= 1 - stain[..., None] * np.array([0.5, 0.75, 1.0], F)
    ed = np.minimum(np.minimum(xx, W - 1 - xx), np.minimum(yy, H - 1 - yy))
    paper *= (0.80 + 0.20 * smooth(0, 190, ed + 90 * (big - 0.5)))[..., None] ** np.array([0.8, 1.0, 1.3], F)
    fold = np.exp(-((yy - 1004 - 3 * np.sin(xx / 90)) / 1.6) ** 2)
    paper *= (1 - 0.06 * fold)[..., None]
    paper += (np.exp(-((yy - 1008 - 3 * np.sin(xx / 90)) / 2.5) ** 2) * 0.02)[..., None]

    # ------------------------------------------------------------ watercolour
    M = np.ones((H, W, 3), F)
    cov = np.zeros((H, W), F)
    blot = fbm((H, W), 60, 4, prng)
    for wimg in wash:
        a = np.asarray(wimg.resize((W, H), Image.BOX), F) / 255.0
        c = (a.min(-1) < 0.985).astype(F)
        c = ndi.gaussian_filter(c, 0.7)
        # pigment gathers at the rim of every wash and is uneven inside it
        rim = np.clip(c - ndi.gaussian_filter(c, 2.6), 0, 1)
        dens = (0.72 + 0.50 * blot + 0.9 * rim) * (0.9 + 0.25 * grainp)
        a = ndi.gaussian_filter(a, (0.6, 0.6, 0))
        M *= np.clip(1 - (1 - a) * dens[..., None], 0, 1)
        cov = np.maximum(cov, c)
    img = paper * (0.10 + 0.90 * M)
    inkm = np.asarray(ink.resize((W, H), Image.BOX), F) / 255.0
    inkm = inkm * (0.80 + 0.35 * vnoise((H, W), 3, prng))                     # the pen line is not perfectly even
    sepia = np.array([0.23, 0.15, 0.08], F)
    a = np.clip(inkm, 0, 1)[..., None] * 0.86
    img = img * (1 - a) + sepia * paper * a * 1.1
    img = np.clip(img, 0, 1)
    Image.fromarray((img * 255 + 0.5).astype(np.uint8)).save(OUT)
    print('saved %s  %.1fs' % (os.path.abspath(OUT), time.time() - T0))


if __name__ == '__main__':
    main()