ExperimentsFable 5.2 Python art (30 images)
Image 11 of 30
Flow-field ink
The Python script
Open script.py ↗ (opens in a new tab)#!/usr/bin/env python3
"""11 Flow-field ink.
About 150,000 particles follow a swirling, divergence-free flow field (the curl
of a smooth noise "stream function" plus a few vortices). Every particle leaves
a thin trail. The trails are added up per ink colour and the paper is darkened
with a subtractive (light-absorbing) ink model, so that overlapping trails
build up like real ink in water.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/11-flow-field-ink.py
"""
import os, time
import numpy as np
from PIL import Image
from scipy import ndimage as ndi
W, H = 1600, 2000
SS = 2 # trails are accumulated at 2x and scaled down
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '11-flow-field-ink.png')
F32 = np.float32
rng = np.random.default_rng(1111)
# ----------------------------------------------------------------------------
# 1. Flow field: velocity = curl of a stream function psi (no sources or sinks)
# ----------------------------------------------------------------------------
GW, GH = W // 2, H // 2 # field grid (800 x 1000)
def smooth_noise(sigma):
n = ndi.gaussian_filter(rng.standard_normal((GH, GW)).astype(F32), sigma, mode='wrap')
return n / n.std()
psi = 1.00 * smooth_noise(105) + 0.30 * smooth_noise(44) + 0.03 * smooth_noise(17)
gy, gx = np.mgrid[0:GH, 0:GW].astype(F32)
def vortex(cx, cy, s, a):
r2 = (gx - cx * GW) ** 2 + (gy - cy * GH) ** 2
return a * np.exp(-r2 / (2 * (s * GW) ** 2))
# Vortices set the composition: one large eye left of centre, a counter-eddy
# lower right and a small one near the top.
psi += vortex(0.40, 0.40, 0.23, 3.1)
psi += vortex(0.72, 0.74, 0.15, -2.2)
psi += vortex(0.74, 0.14, 0.10, 1.3)
psi += vortex(0.16, 0.86, 0.11, 1.2)
dpy, dpx = np.gradient(psi)
SPIRAL = 0.11 # small pull toward the eyes: closed loops become spirals
VX, VY = dpy + SPIRAL * dpx, -dpx + SPIRAL * dpy
speed = np.hypot(VX, VY) + 1e-6
SPN = (speed / np.percentile(speed, 95)).astype(F32)
def sample(field, x, y):
"""Bilinear lookup; x, y in full-resolution pixel units."""
return ndi.map_coordinates(field, [y / 2.0, x / 2.0], order=1, mode='nearest')
# ----------------------------------------------------------------------------
# 2. Ink drops: where the particles start, and which ink they carry
# ----------------------------------------------------------------------------
# (x, y, radius, number of particles, ink index) ink: 0 indigo, 1 vermilion, 2 black-green
DROPS = [
(0.40, 0.40, 0.050, 9000, 1),
(0.31, 0.30, 0.085, 17000, 0),
(0.53, 0.47, 0.075, 15000, 0),
(0.36, 0.56, 0.060, 11000, 0),
(0.47, 0.27, 0.040, 6000, 1),
(0.20, 0.47, 0.060, 8000, 2),
(0.63, 0.31, 0.060, 9000, 0),
(0.72, 0.74, 0.050, 9000, 1),
(0.66, 0.66, 0.075, 13000, 0),
(0.81, 0.83, 0.060, 9000, 2),
(0.56, 0.84, 0.055, 7000, 0),
(0.74, 0.14, 0.050, 6500, 0),
(0.80, 0.21, 0.030, 3000, 1),
(0.16, 0.86, 0.050, 5500, 0),
(0.24, 0.80, 0.030, 2500, 2),
(0.88, 0.50, 0.050, 5000, 0),
(0.12, 0.17, 0.050, 4500, 0),
(0.50, 0.66, 0.045, 5000, 2),
]
px, py, ink = [], [], []
for cx, cy, r, n, k in DROPS:
n = int(n * 0.5)
# Each drop is a soft blob with a few tighter clots inside it.
nclot = 5
ccx = cx * W + rng.normal(0, r * W * 0.7, nclot)
ccy = cy * H + rng.normal(0, r * W * 0.7, nclot)
which = rng.integers(0, nclot, n)
spread = r * W * rng.choice([0.25, 0.5, 1.0], n, p=[0.35, 0.4, 0.25])
px.append(ccx[which] + rng.normal(0, 1, n) * spread)
py.append(ccy[which] + rng.normal(0, 1, n) * spread)
ink.append(np.full(n, k))
# A thin veil of stray particles so the empty paper still shows the flow.
NS = 9000
px.append(rng.uniform(0, W, NS)); py.append(rng.uniform(0, H, NS))
ink.append(rng.choice([0, 0, 0, 2], NS))
px = np.concatenate(px).astype(F32); py = np.concatenate(py).astype(F32)
ink = np.concatenate(ink)
N = px.size
life = rng.integers(260, 1100, N) # steps a particle lives
life[-NS:] = rng.integers(150, 500, NS)
weight = np.clip(rng.lognormal(-0.45, 0.65, N), 0.15, 4.0).astype(F32) # a few heavy strands
weight[-NS:] *= 0.5
direction = rng.choice([-1.0, 1.0], N).astype(F32)
# ----------------------------------------------------------------------------
# 3. Move the particles and add up their trails
# ----------------------------------------------------------------------------
AW, AH = W * SS, H * SS
dens = np.zeros((3, AH * AW), F32)
STEP = 1.25 # pixels per step (full resolution)
MAXSTEP = int(life.max())
buf_i = [[], [], []]
buf_w = [[], [], []]
def flush():
for k in range(3):
if buf_i[k]:
ii = np.concatenate(buf_i[k]); ww = np.concatenate(buf_w[k])
dens[k] += np.bincount(ii, weights=ww, minlength=AH * AW).astype(F32)
buf_i[k].clear(); buf_w[k].clear()
for s in range(MAXSTEP):
alive = s < life
if not alive.any():
break
idx = np.nonzero(alive)[0]
x = px[idx]; y = py[idx]
vx = sample(VX, x, y); vy = sample(VY, x, y)
sp = np.hypot(vx, vy) + 1e-6
# Constant-length steps along the flow, with a little diffusion.
jit = 0.16
x = x + direction[idx] * vx / sp * STEP + rng.normal(0, jit, idx.size).astype(F32)
y = y + direction[idx] * vy / sp * STEP + rng.normal(0, jit, idx.size).astype(F32)
px[idx] = x; py[idx] = y
t = s / life[idx]
taper = np.sin(np.pi * t) ** 0.6 # trails fade in and out
spn = sample(SPN, x, y)
fast = (0.55 + 0.45 * np.clip(spn, 0, 1.3)) * np.clip((spn - 0.10) * 5.0, 0, 1) # no ink piles in dead water
w = weight[idx] * taper * fast
xi = np.round(x * SS).astype(np.int64); yi = np.round(y * SS).astype(np.int64)
ok = (xi >= 0) & (xi < AW) & (yi >= 0) & (yi < AH)
flat = yi[ok] * AW + xi[ok]
kk = ink[idx][ok]; w = w[ok]
for k in range(3):
m = kk == k
buf_i[k].append(flat[m]); buf_w[k].append(w[m])
if s % 24 == 23:
flush()
flush()
print('particles done %.1fs' % (time.time() - T0))
# ----------------------------------------------------------------------------
# 4. Turn trail density into ink on paper
# ----------------------------------------------------------------------------
layers = []
for k in range(3):
d = dens[k].reshape(AH, AW)
d = ndi.gaussian_filter(d, 0.8)
d = np.asarray(Image.fromarray(d).resize((W, H), Image.BOX), F32) * (SS * SS)
layers.append(d)
dens = None
yy, xx = np.mgrid[0:H, 0:W].astype(F32)
# Paper: warm white with soft mottling and fine grain.
paper = np.array([0.962, 0.945, 0.912], F32)
mott = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), 90)
mott /= mott.std()
fib = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), (0.6, 2.2))
fib /= fib.std()
img = paper[None, None, :] * (1 + 0.012 * mott[..., None] + 0.010 * fib[..., None])
vig = 1 - 0.10 * (((xx - W / 2) / (W * 0.75)) ** 2 + ((yy - H / 2) / (H * 0.75)) ** 2)
img *= vig[..., None]
# Absorption per colour channel (how strongly each ink removes R, G, B).
ABSORB = np.array([
[2.70, 1.85, 0.55], # indigo
[0.10, 1.55, 2.20], # vermilion
[2.10, 1.70, 1.45], # black-green
], F32)
GAIN = [0.040, 0.056, 0.046]
for k in range(3):
d = layers[k]
wash = ndi.gaussian_filter(d, 6) * 0.30 + ndi.gaussian_filter(d, 30) * 0.22 # diluted halo
od = GAIN[k] * (d ** 0.82) + GAIN[k] * 0.9 * wash
# Ink soaks unevenly into the paper grain.
od *= 1 + 0.10 * fib
img *= np.exp(-od[..., None] * ABSORB[k][None, None, :])
# Small lift of the darkest ink so it stays coloured, not flat black.
img = np.clip(img, 0, 1)
img = 0.02 + 0.98 * img
grain = rng.standard_normal((H, W)).astype(F32) * 0.008
img = np.clip(img + grain[..., None], 0, 1)
Image.fromarray((img ** (1 / 1.0) * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))

