ExperimentsFable 5.2 Python art (30 images)
Image 7 of 30
Underwater kelp forest
The Python script
Open script.py ↗ (opens in a new tab)#!/usr/bin/env python3
"""07 Underwater kelp forest.
Light rays from the surface, three depth layers of kelp built from
curved blade shapes, drifting particles with soft focus, a school of
fish in silhouette and two orange fish.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/07-underwater-kelp-forest.py
"""
import os, sys, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi
# ----------------------------------------------------------------------------
# Shared helper code (copied into every script so that each script runs alone)
# ----------------------------------------------------------------------------
W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
F32 = np.float32
def hexc(s):
s = s.lstrip('#')
return np.array([int(s[i:i + 2], 16) for i in (0, 2, 4)], F32) / 255.0
def c8(c):
return tuple(int(max(0, min(255, round(float(v) * 255)))) for v in c)
def smooth(a, b, x):
t = np.clip((x - a) / (b - a + 1e-12), 0, 1)
return t * t * (3 - 2 * t)
def mix(a, b, t):
return a + (b - a) * t
def ramp(t, stops):
"""Colour gradient. stops = [(position, '#hex'), ...]; t is an array."""
pos = [p for p, _ in stops]
cols = np.array([hexc(c) if isinstance(c, str) else c for _, c in stops])
return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F32)
def vnoise(shape, cell, rng):
"""Smooth value noise in 0..1: a random grid, enlarged with cubic interpolation."""
h, w = shape
cy, cx = (cell, cell) if np.isscalar(cell) else cell
cy, cx = max(1.0, float(cy)), max(1.0, float(cx))
gh, gw = int(h / cy) + 4, int(w / cx) + 4
g = rng.random((gh, gw)).astype(F32)
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)
z = z[oy:oy + h, ox:ox + w]
if z.shape != (h, w):
z = np.pad(z, ((0, h - z.shape[0]), (0, w - z.shape[1])), mode='edge')
return z
def fbm(shape, cell, octaves, rng, gain=0.5, lac=2.0):
"""Fractal noise in about 0..1 (sum of value noise octaves)."""
cy, cx = (cell, cell) if np.isscalar(cell) else cell
out = np.zeros(shape, F32)
amp, tot = 1.0, 0.0
for _ in range(octaves):
out += amp * vnoise(shape, (cy, cx), rng)
tot += amp
amp *= gain
cy /= lac
cx /= lac
return out / tot
def blur(a, s):
"""Gaussian blur for 2D or 3D (h, w, c) arrays; large radii use a small copy."""
if s <= 0:
return a
if s > 10:
k = int(s // 5)
h, w = a.shape[:2]
ph, pw = (-h) % k, (-w) % k
pad = ((0, ph), (0, pw)) + (((0, 0),) if a.ndim == 3 else ())
b = np.pad(a, pad, mode='edge')
hh, ww = b.shape[0] // k, b.shape[1] // k
if a.ndim == 3:
b = b.reshape(hh, k, ww, k, -1).mean((1, 3))
b = ndi.gaussian_filter(b, (s / k, s / k, 0), mode='nearest')
b = ndi.zoom(b, (k, k, 1), order=1)
else:
b = b.reshape(hh, k, ww, k).mean((1, 3))
b = ndi.gaussian_filter(b, s / k, mode='nearest')
b = ndi.zoom(b, (k, k), order=1)
return b[:h, :w].astype(F32)
sig = (s, s, 0) if a.ndim == 3 else s
return ndi.gaussian_filter(a, sig, mode='nearest').astype(F32)
def bloom(a, thresh=0.7, sigmas=(6, 20, 60), gains=(0.35, 0.3, 0.25)):
"""Soft glow around bright areas."""
lum = a.max(-1)
hi = a * smooth(thresh, thresh + 0.25, lum)[..., None]
out = a.copy()
for s, g in zip(sigmas, gains):
out += g * blur(hi, s)
return out
def glow(cx, cy, r, power=2.0):
"""Radial falloff field, 1 at the centre."""
yy, xx = np.mgrid[0:H, 0:W].astype(F32)
d2 = ((xx - cx) ** 2 + (yy - cy) ** 2) / (r * r)
return 1.0 / (1.0 + d2) ** power
def comp(base, rgb, a):
"""Alpha composite. rgb may be one colour or an image; a is an (h, w) mask."""
return base * (1 - a[..., None]) + np.asarray(rgb, F32) * a[..., None]
class Layer:
"""Vector drawing layer (PIL) drawn at 2x size, then averaged down for smooth edges."""
def __init__(self, ss=2):
self.ss = ss
self.im = Image.new('RGBA', (W * ss, H * ss), (0, 0, 0, 0))
self.d = ImageDraw.Draw(self.im)
def _p(self, pts):
s = self.ss
return [(float(x) * s, float(y) * s) for x, y in pts]
def poly(self, pts, col, a=1.0):
self.d.polygon(self._p(pts), fill=c8(col) + (int(a * 255),))
def line(self, pts, col, width=1.0, a=1.0):
wd = max(1, int(round(width * self.ss)))
self.d.line(self._p(pts), fill=c8(col) + (int(a * 255),), width=wd, joint='curve')
def dot(self, x, y, rx, col, a=1.0, ry=None):
s = self.ss
ry = rx if ry is None else ry
self.d.ellipse([(x - rx) * s, (y - ry) * s, (x + rx) * s, (y + ry) * s],
fill=c8(col) + (int(a * 255),))
def arrays(self):
im = self.im.convert('RGBa').reduce(self.ss) # premultiplied alpha
a = np.asarray(im).astype(F32) / 255.0
return a[..., :3], a[..., 3]
def onto(self, base, opacity=1.0, soften=0.0):
rgb, a = self.arrays()
if soften > 0:
rgb, a = blur(rgb, soften), blur(a, soften)
return base * (1 - a[..., None] * opacity) + rgb * opacity
def painterly(ref, rng, sizes=(44, 22, 11, 6), thresh=(0, 0.06, 0.05, 0.04), ss=2,
jitter=0.035, length=5, base_angle=None, edge_follow=1.0, relief=0.3,
density=1.0, tol=0.22, underblur=30, keep=None):
"""Repaint an image with oriented brush strokes, coarse to fine.
Strokes follow the edges of the picture (structure tensor) and a flow field
elsewhere. Finer strokes are added only where the canvas still differs from
the reference. A separate height map of the strokes gives the paint relief.
keep: optional (h, w) probability mask that limits where fine strokes go.
"""
h, w = ref.shape[:2]
lum = ref @ np.array([0.3, 0.59, 0.11], F32)
l2 = ndi.gaussian_filter(lum, 2.0)
gx, gy = ndi.sobel(l2, axis=1), ndi.sobel(l2, axis=0)
jxx, jyy, jxy = blur(gx * gx, 6), blur(gy * gy, 6), blur(gx * gy, 6)
theta = 0.5 * np.arctan2(2 * jxy, jxx - jyy) + np.pi / 2
coh = np.sqrt((jxx - jyy) ** 2 + 4 * jxy ** 2)
cw = smooth(0.0004, 0.01, coh) * edge_follow
if base_angle is None:
base_angle = fbm((h, w), 320, 3, rng) * np.pi * 3
base_angle = np.broadcast_to(np.asarray(base_angle, F32), (h, w))
c2 = cw * np.cos(2 * theta) + (1 - cw) * np.cos(2 * base_angle)
s2 = cw * np.sin(2 * theta) + (1 - cw) * np.sin(2 * base_angle)
ang = 0.5 * np.arctan2(s2, c2)
dxf, dyf = np.cos(ang).astype(F32), np.sin(ang).astype(F32)
start = np.clip(blur(ref, underblur), 0, 1)
canvas = Image.fromarray((start * 255).astype(np.uint8)).resize((w * ss, h * ss), Image.BILINEAR)
hmap = Image.new('L', (w * ss, h * ss), 128)
dr, hd = ImageDraw.Draw(canvas), ImageDraw.Draw(hmap)
for li, s in enumerate(sizes):
sp = max(2.0, s * 0.45 / density)
ny, nx = int(h / sp) + 1, int(w / sp) + 1
gy_, gx_ = np.mgrid[0:ny, 0:nx].astype(F32)
px = (gx_ + rng.random((ny, nx))).ravel() * sp
py = (gy_ + rng.random((ny, nx))).ravel() * sp
ok = (px < w - 1) & (py < h - 1)
px, py = px[ok], py[ok]
xi, yi = px.astype(int), py.astype(int)
sel = np.ones(len(px), bool)
if thresh[li] > 0:
cur = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
diff = blur(np.abs(cur - ref).sum(-1), s * 0.5)
sel &= diff[yi, xi] > thresh[li]
if keep is not None and li >= 1:
sel &= rng.random(len(px)) < keep[yi, xi]
px, py, xi, yi = px[sel], py[sel], xi[sel], yi[sel]
n = len(px)
if n == 0:
continue
col0 = ref[yi, xi]
K = int(length)
step = s * 0.6
pts = np.zeros((n, 2 * K + 1, 2), F32)
pts[:, K, 0], pts[:, K, 1] = px, py
for sgn in (1, -1):
x, y = px.copy(), py.copy()
ddx, ddy = dxf[yi, xi] * sgn, dyf[yi, xi] * sgn
alive = np.ones(n, bool)
for k in range(1, K + 1):
ix = np.clip(x.astype(int), 0, w - 1)
iy = np.clip(y.astype(int), 0, h - 1)
ndx, ndy = dxf[iy, ix], dyf[iy, ix]
flip = np.where(ndx * ddx + ndy * ddy < 0, -1.0, 1.0)
ddx, ddy = ndx * flip, ndy * flip
nx_, ny_ = x + ddx * step, y + ddy * step
jx = np.clip(nx_.astype(int), 0, w - 1)
jy = np.clip(ny_.astype(int), 0, h - 1)
alive &= np.abs(ref[jy, jx] - col0).sum(-1) < tol
x = np.where(alive, nx_, x)
y = np.where(alive, ny_, y)
pts[:, K + sgn * k, 0], pts[:, K + sgn * k, 1] = x, y
colj = col0 * (1 + jitter * rng.standard_normal((n, 1))) + 0.4 * jitter * rng.standard_normal((n, 3))
cols = (np.clip(colj, 0, 1) * 255).astype(np.uint8)
order = rng.permutation(n)
P = (pts[order] * ss).reshape(n, -1).tolist()
Cc = cols[order].tolist()
G = rng.integers(40, 216, n).tolist()
Bo = (rng.standard_normal((n, 3)) * s * ss * 0.28).tolist()
Bl = (1 + 0.07 * rng.standard_normal((n, 3))).tolist()
wd = max(1, int(s * ss))
r = wd / 2.0
for i in range(n):
p = P[i]
c = tuple(Cc[i])
dr.line(p, fill=c, width=wd, joint='curve')
hd.line(p, fill=G[i], width=wd, joint='curve')
for ex, ey in ((p[0], p[1]), (p[-2], p[-1])):
box = [ex - r, ey - r, ex + r, ey + r]
dr.ellipse(box, fill=c)
hd.ellipse(box, fill=G[i])
if s >= 9: # bristle streaks inside the larger strokes
vx, vy = p[-2] - p[0], p[-1] - p[1]
vl = math.hypot(vx, vy) + 1e-6
ox_, oy_ = -vy / vl, vx / vl
for b in range(3):
o = Bo[i][b]
q = [v + (o * ox_ if j % 2 == 0 else o * oy_) for j, v in enumerate(p)]
cb = tuple(int(max(0, min(255, v * Bl[i][b]))) for v in c)
dr.line(q, fill=cb, width=max(1, wd // 5), joint='curve')
hd.line(q, fill=int(max(0, min(255, G[i] + 40 * (Bl[i][b] - 1) * 14))), width=max(1, wd // 5))
out = np.asarray(canvas.reduce(ss)).astype(F32) / 255.0
if relief > 0:
hm = ndi.gaussian_filter(np.asarray(hmap.reduce(ss)).astype(F32), 0.8)
sh = np.clip((-ndi.sobel(hm, axis=1) * 0.5 - ndi.sobel(hm, axis=0) * 0.85) / 255.0, -1, 1)
out = out * (1 + relief * sh[..., None])
return out
def finish(a, name, rng, vignette=0.22, grain=0.012, weave=0.018):
"""Vignette, canvas weave, grain, then save to ../images/<name>.png."""
yy, xx = np.mgrid[0:H, 0:W].astype(F32)
r = np.sqrt(((xx / W - 0.5) * 1.15) ** 2 + (yy / H - 0.5) ** 2)
a = a * (1 - vignette * smooth(0.3, 0.8, r))[..., None]
if weave > 0:
wv = (np.sin(xx * 2.1) * np.sin(yy * 2.1)) * 0.5 + (vnoise((H, W), 2.5, rng) - 0.5)
a = a * (1 + weave * wv)[..., None]
if grain > 0:
a = a + grain * rng.standard_normal((H, W, 1)).astype(F32)
out = os.path.join(HERE, '..', 'images', name + '.png')
os.makedirs(os.path.dirname(out), exist_ok=True)
Image.fromarray((np.clip(a, 0, 1) * 255 + 0.5).astype(np.uint8)).save(out)
print(f'saved {os.path.normpath(out)} ({time.time() - T0:.1f} s)')
# ----------------------------------------------------------------------------
# The picture
# ----------------------------------------------------------------------------
SEED = 707
rng = np.random.default_rng(SEED)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)
SX, SY = 660.0, -260.0 # where the light enters
# ---- water colour -----------------------------------------------------------------
d = np.sqrt((xx - SX) ** 2 * 0.8 + (yy - SY) ** 2) / 2300.0
bg = ramp(np.clip(d, 0, 1), [(0.08, '#d6fbe4'), (0.2, '#9ae6c8'), (0.36, '#4fc4b4'), (0.55, '#1b8a93'), (0.75, '#0c5568'), (1.0, '#052838')])
bg *= (0.93 + 0.14 * fbm((H, W), 260, 3, rng))[..., None]
# ---- rays -------------------------------------------------------------------------
ang = np.arctan2(yy - SY, xx - SX)
rr = np.hypot(xx - SX, yy - SY)
tA = (ang - 0.2) / (np.pi - 0.4) * 4095
n1 = vnoise((1, 4096), (1, 60), rng)[0] * 0.55 + vnoise((1, 4096), (1, 17), rng)[0] * 0.3 + vnoise((1, 4096), (1, 5), rng)[0] * 0.15
ray = np.interp(np.clip(tA, 0, 4095), np.arange(4096), n1)
ray = smooth(0.42, 0.75, ray) * np.exp(-rr / 1500.0) * smooth(1.25, 0.25, d)
RAYC = hexc('#d8ffe6')
img = bg + ray[..., None] * RAYC * 0.42
# ripples of light right under the surface
cn = fbm((H, W), (26, 150), 4, rng)
rowmap = np.clip((yy / 330.0) ** 0.6 * 330, 0, H - 1)
cn = ndi.map_coordinates(cn, np.stack([rowmap * 2.2, xx]), order=1, mode='reflect')
caus = (1 - np.abs(2 * cn - 1)) ** 5 * smooth(330, 0, yy)
img += caus[..., None] * hexc('#f2fff4') * 0.5
def lit_at(x, y):
return float(np.clip(1.15 - math.hypot(x - SX, y - SY) / 1700.0, 0, 1))
# ---- kelp ------------------------------------------------------------------------------
def blade(L, x0, y0, ang_, length, width, col, wav):
n = 12
s = np.linspace(0, 1, n)
ca, sa = math.cos(ang_), math.sin(ang_)
px = x0 + length * s * ca + 0.28 * length * s * s
py = y0 + length * s * sa + 0.10 * length * s * s
wob = np.sin(2 * np.pi * s * 1.4 + wav) * length * 0.05 * s
px, py = px - sa * wob, py + ca * wob
tx, ty = np.gradient(px), np.gradient(py)
tl = np.hypot(tx, ty) + 1e-6
nx_, ny_ = -ty / tl, tx / tl
hw = width * np.sin(np.pi * s ** 0.75) ** 0.7 * (1 + 0.18 * rng.standard_normal(n))
hw[0], hw[-1] = width * 0.12, 0.5
left = list(zip(px + nx_ * hw, py + ny_ * hw))
right = list(zip(px - nx_ * hw, py - ny_ * hw))
L.poly(left + right[::-1], col)
L.line(list(zip(px, py)), col * 0.72, max(1.0, width * 0.1), 0.7) # midrib
L.dot(x0 + ca * width * 0.5, y0 + sa * width * 0.5, width * 0.38, col * 0.9, ry=width * 0.3) # float bulb
def stalk(L, x0, scale, top, dark, gold, sway):
lam = rng.uniform(260, 420) * (0.6 + scale * 0.5)
ph = rng.uniform(0, 6.28)
amp = rng.uniform(26, 70) * scale
fx = lambda y: x0 + amp * math.sin(y / lam + ph) + sway * (H - y) / H
ys = np.arange(H + 60, top, -14.0)
L.line([(fx(y), y) for y in ys], dark * 0.8, max(1.5, 5.5 * scale))
y = H + 20.0
side = 1
while y > top:
x = fx(y)
li = lit_at(x, y) ** 1.5
col = mix(dark, gold, np.clip(li * rng.uniform(0.3, 1.25), 0, 1))
a = (-0.55 + rng.uniform(-0.35, 0.3)) if side > 0 else (np.pi + 0.75 + rng.uniform(-0.3, 0.35))
ln = rng.uniform(130, 250) * scale
blade(L, x, y, a, ln * (0.75 if side < 0 else 1.0), rng.uniform(15, 26) * scale, col, rng.uniform(0, 6.28))
side = -side
y -= rng.uniform(34, 62) * scale
far = Layer()
for x0 in np.linspace(60, W - 60, 11) + rng.uniform(-60, 60, 11):
stalk(far, x0, 0.38, rng.uniform(-60, 500), hexc('#0e4d58'), hexc('#3f8d78'), 60)
img = far.onto(img, opacity=0.6, soften=2.2)
img += ray[..., None] * RAYC * 0.10
# school of small fish, between the far and the middle kelp
def fish(L, x, y, ln, ang_, col, a=1.0):
ca, sa = math.cos(ang_), math.sin(ang_)
T = lambda u, v: (x + (u * ca - v * sa) * ln, y + (u * sa + v * ca) * ln)
body = [T(0.5, 0.0), T(0.3, -0.16), T(0.0, -0.2), T(-0.3, -0.1), T(-0.42, -0.03),
T(-0.42, 0.03), T(-0.3, 0.1), T(0.0, 0.19), T(0.3, 0.14)]
L.poly(body, col, a)
L.poly([T(-0.38, 0.0), T(-0.62, -0.2), T(-0.54, 0.0), T(-0.62, 0.2)], col, a) # tail
L.poly([T(0.1, -0.18), T(-0.12, -0.32), T(-0.2, -0.14)], col, a) # back fin
L.poly([T(0.0, 0.17), T(-0.14, 0.28), T(-0.16, 0.13)], col, a)
sch = Layer()
for _ in range(46):
u = rng.random()
x = 470 + 520 * u + rng.normal(0, 28)
y = 900 - 330 * u + 90 * math.sin(u * 3.0) + rng.normal(0, 40)
fish(sch, x, y, rng.uniform(30, 60), -0.5 + rng.normal(0, 0.12), hexc('#083440'), 0.95)
img = sch.onto(img, opacity=0.9, soften=0.7)
mid = Layer()
for x0 in [130, 400, 1010, 1260, 1480]:
stalk(mid, x0 + rng.uniform(-50, 50), 0.72, rng.uniform(-80, 260), hexc('#0c3324'), hexc('#8a9a34'), 80)
img = mid.onto(img, opacity=0.9, soften=1.0)
img += ray[..., None] * RAYC * 0.10
# ---- reef at the bottom ------------------------------------------------------------------
prof = 1870 - 170 * (vnoise((1, W), (1, 260), rng)[0] * 0.6 + vnoise((1, W), (1, 60), rng)[0] * 0.3 + vnoise((1, W), (1, 16), rng)[0] * 0.1)
prof += 90 * np.exp(-((xx[0] - 800) / 380.0) ** 2)
dr = yy - prof[None, :]
rockm = smooth(-2, 2, dr)
rock = ramp(np.clip(dr / 160.0, 0, 1), [(0, '#2f7c82'), (0.12, '#124450'), (0.5, '#0a2a34'), (1, '#03121a')])
rock *= (0.7 + 0.6 * fbm((H, W), 40, 4, rng))[..., None]
spots = smooth(0.6, 0.78, fbm((H, W), (14, 46), 3, rng)) * np.exp(-np.clip(dr, 0, None) / 50.0)
rock += spots[..., None] * hexc('#5fd0b8') * 0.5
img = comp(img, rock, rockm)
# two orange fish
of = Layer()
for (x, y, ln, a_) in [(560, 1265, 150, 0.12), (835, 1490, 105, -0.1)]:
fish(of, x, y, ln, a_, hexc('#f5741c'))
ca, sa = math.cos(a_), math.sin(a_)
T = lambda u, v: (x + (u * ca - v * sa) * ln, y + (u * sa + v * ca) * ln)
of.poly([T(0.46, 0.02), T(0.3, 0.14), T(0.0, 0.19), T(-0.3, 0.1), T(-0.42, 0.03), T(-0.2, 0.03), T(0.2, 0.05)], hexc('#b8430e'), 0.75)
of.poly([T(0.42, -0.04), T(0.3, -0.15), T(0.0, -0.19), T(-0.25, -0.1), T(0.0, -0.11), T(0.3, -0.08)], hexc('#ffb04a'), 0.8)
ex, ey = T(0.33, -0.03)
of.dot(ex, ey, ln * 0.03, hexc('#1a0d05'))
of.dot(ex + ln * 0.008, ey - ln * 0.008, ln * 0.01, hexc('#ffffff'))
img = of.onto(img)
near = Layer()
for (x0, sc, sw) in [(-10, 1.5, 70), (1330, 1.25, 110), (1620, 1.7, -60)]:
stalk(near, x0, sc, -120, hexc('#06180f'), hexc('#b6a436'), sw)
img = near.onto(img)
# ---- drifting particles and bubbles -------------------------------------------------------
p = np.zeros((H, W), F32)
n = 2600
p[rng.integers(0, H, n), rng.integers(0, W, n)] = rng.random(n) ** 2 + 0.15
soft = blur(p, 0.9) * 6 + blur(p * (rng.random((H, W)) < 0.3), 2.6) * 22
img += (soft * (0.25 + 1.5 * ray + 0.5 * smooth(1.0, 0.2, d)))[..., None] * hexc('#e6fff0') * 0.85
bk = Layer()
for _ in range(60):
x, y = rng.uniform(0, W), rng.uniform(0, H)
r = rng.uniform(5, 17)
bk.dot(x, y, r, hexc('#d8fff0'), rng.uniform(0.04, 0.13))
img = bk.onto(img, soften=1.6)
bb = Layer()
bx = 1130.0
for i in range(26):
y = 1780 - i * rng.uniform(38, 70)
x = bx + 26 * math.sin(i * 0.9) + rng.uniform(-10, 10)
r = rng.uniform(3, 9)
bb.dot(x, y, r, hexc('#c8fff0'), 0.22)
bb.dot(x, y, r * 0.78, hexc('#3fb0a8'), 0.25)
bb.dot(x - r * 0.35, y - r * 0.35, r * 0.28, hexc('#ffffff'), 0.9)
img = bb.onto(img)
# ---- soft brush pass, glow ------------------------------------------------------------------
ref = np.clip(img, 0, 1)
flow = ang + 0.5 * (fbm((H, W), 240, 2, rng) - 0.5)
painted = painterly(ref, rng, sizes=(30, 15, 8, 4), thresh=(0, 0.05, 0.045, 0.04), base_angle=flow, relief=0.16, jitter=0.03, length=6)
img = mix(painted, ref, 0.3)
img = bloom(img, 0.8, (8, 40), (0.16, 0.18))
img = np.clip(img, 0, 1) ** 1.04
finish(img, '07-underwater-kelp-forest', rng, vignette=0.3)

