ExperimentsFable 5.2 Python art (30 images)
Image 24 of 30
Great wave woodblock
The Python script
Open script.py ↗ (opens in a new tab)#!/usr/bin/env python3
"""24 Great wave woodblock.
A wave in the style of a Japanese woodblock print: flat colours, foam claws,
a red sun and paper texture. Inspired by Hokusai, but a new composition.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Every shape is a polygon built from smooth curves. The shapes are sorted onto
"printing blocks" (one per colour plus a dark line block). Each block is
printed onto textured paper with wood grain, small gaps and a tiny shift,
as in a real hand-pulled print.
Run: .venv/bin/python scripts/24-great-wave-woodblock.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 = 24
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '24-great-wave-woodblock.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
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 spline(pts, n=24):
"""Smooth curve through points (Catmull-Rom)."""
p = np.asarray(pts, float)
p = np.vstack([2 * p[0] - p[1], p, 2 * p[-1] - p[-2]])
out = []
t = np.linspace(0, 1, n, endpoint=False)[:, None]
for i in range(1, len(p) - 2):
a, b, c, d = p[i - 1], p[i], p[i + 1], p[i + 2]
out.append(0.5 * ((2 * b) + (-a + c) * t + (2 * a - 5 * b + 4 * c - d) * t ** 2 + (-a + 3 * b - 3 * c + d) * t ** 3))
out.append(p[-2][None, :])
return np.vstack(out)
def resample(poly, n):
d = np.r_[0, np.cumsum(np.hypot(*np.diff(poly, axis=0).T))]
s = np.linspace(0, d[-1], n)
return np.stack([np.interp(s, d, poly[:, 0]), np.interp(s, d, poly[:, 1])], 1)
class Mask:
"""One shape layer, drawn at double size and averaged down for smooth edges."""
def __init__(self):
self.im = Image.new('L', (W * SS, H * SS), 0)
self.d = ImageDraw.Draw(self.im)
def poly(self, pts, v=255):
self.d.polygon([(float(x) * SS, float(y) * SS) for x, y in pts], fill=v)
def circle(self, x, y, r, v=255):
self.d.ellipse([(x - r) * SS, (y - r) * SS, (x + r) * SS, (y + r) * SS], fill=v)
def line(self, pts, w, v=255):
self.d.line([(float(x) * SS, float(y) * SS) for x, y in pts], fill=v, width=max(1, int(round(w * SS))), joint='curve')
def ribbon(self, pts, widths, v=255):
"""A stroke with changing width (a list of half-widths along the points)."""
p = np.asarray(pts, float)
t = np.gradient(p, axis=0)
t /= np.hypot(t[:, 0], t[:, 1])[:, None] + 1e-9
nrm = np.stack([-t[:, 1], t[:, 0]], 1)
wd = np.asarray(widths, float)[:, None]
self.poly(np.vstack([p + nrm * wd, (p - nrm * wd)[::-1]]), v)
def get(self):
return np.asarray(self.im.resize((W, H), Image.BOX), F) / 255.0
def finger(m, p, ang, length, w0, curl, depth, r):
"""A foam claw: a tapering, curling finger with a round tip and smaller fingers."""
n = 14
pts = [np.array(p, float)]
a = ang
for i in range(n):
a += curl / n
pts.append(pts[-1] + (length / n) * np.array([math.cos(a), math.sin(a)]))
pts = np.array(pts)
wd = w0 * (1 - 0.62 * np.linspace(0, 1, n + 1) ** 0.8)
m.ribbon(pts, wd)
m.circle(pts[-1][0], pts[-1][1], wd[-1] * 1.25)
m.circle(pts[0][0], pts[0][1], w0)
if depth > 0:
for k in range(r.integers(1, 3)):
i = int(n * r.uniform(0.45, 0.8))
side = 1 if (k % 2 == 0) == (curl > 0) else -1
finger(m, pts[i], a - curl * 0.3 + side * r.uniform(0.5, 1.0), length * r.uniform(0.35, 0.5), wd[i] * 0.8,
curl * r.uniform(0.6, 1.2) * (1 if side > 0 else -0.6), depth - 1, r)
def edge_line(mask, r_noise, w0=2.0, w1=3.6):
"""Carved outline along the border of a shape, a little thicker in some places."""
a = ndi.gaussian_filter(mask, w0)
b = ndi.gaussian_filter(mask, w1)
la = np.clip(1.25 - np.abs(a - 0.5) * 2 * 1.9, 0, 1)
lb = np.clip(1.25 - np.abs(b - 0.5) * 2 * 1.9, 0, 1)
return np.clip(la * (1 - r_noise) + lb * r_noise, 0, 1)
def main():
yy, xx = np.mgrid[0:H, 0:W].astype(F)
wnoise = fbm((H, W), 220, 2, rng) # where the outline gets thicker
PRUSS = np.array([0.075, 0.150, 0.300], F)
MID = np.array([0.215, 0.385, 0.560], F)
LIGHT = np.array([0.520, 0.680, 0.740], F)
FOAM = np.array([0.950, 0.925, 0.830], F)
SHADE = np.array([0.700, 0.790, 0.790], F)
SUN = np.array([0.800, 0.225, 0.130], F)
KEY = np.array([0.060, 0.085, 0.170], F)
HILL = np.array([0.420, 0.520, 0.560], F)
plates = {} # colour name -> [colour, coverage map]
key = np.zeros((H, W), F)
def add(name, colour, mask, outline=True, lw=(2.0, 3.6)):
nonlocal key
for k in plates:
plates[k][1] *= (1 - mask)
if name not in plates:
plates[name] = [colour, np.zeros((H, W), F)]
plates[name][1] += mask
key *= (1 - mask)
if outline:
key = np.maximum(key, edge_line(mask, wnoise, *lw))
# ---------------- sun, far hills, mist bands, far sea ----------------
m = Mask(); m.circle(585, 860, 215)
add('sun', SUN, m.get(), lw=(1.6, 2.4))
m = Mask()
hill = spline([(-20, 1215), (60, 1190), (150, 1150), (230, 1168), (330, 1120), (410, 1150), (520, 1180), (640, 1200), (760, 1215)], 20)
m.poly(np.vstack([hill, [(760, 1300), (-20, 1300)]]))
add('hill', HILL, m.get(), lw=(1.5, 2.2))
m = Mask()
far = spline([(-20, 1212), (120, 1202), (260, 1215), (420, 1200), (560, 1214), (700, 1204), (860, 1216), (1000, 1206), (1200, 1215), (1400, 1205), (1640, 1212)], 16)
m.poly(np.vstack([far, [(1640, 2040), (-20, 2040)]]))
farm = m.get()
add('light', LIGHT, farm, lw=(1.5, 2.2))
m = Mask()
for k in range(9):
y0 = 1232 + k * 26 + rng.uniform(-4, 4)
x0 = rng.uniform(-100, 200)
while x0 < W:
L = rng.uniform(120, 420)
xs = np.linspace(x0, x0 + L, 30)
ys = y0 + 5 * np.sin(xs * 0.02 + k) + 3 * np.sin(xs * 0.05 + k * 2)
m.ribbon(np.stack([xs, ys], 1), 4.5 * np.sin(np.linspace(0, math.pi, 30)) ** 0.6 + 0.5)
x0 += L + rng.uniform(40, 160)
add('mid', MID, m.get() * farm, outline=False)
# ---------------- the great wave ----------------
O = resample(spline([(1660, 1560), (1615, 1180), (1520, 850), (1350, 585), (1110, 420), (850, 362), (620, 400),
(450, 505), (350, 650), (318, 790), (352, 880)], 40), 500)
I = resample(spline([(-60, 1585), (240, 1620), (520, 1585), (740, 1470), (885, 1280), (940, 1070), (915, 880),
(820, 745), (680, 680), (540, 690), (440, 760), (384, 850), (352, 880)], 40), 500)
m = Mask()
m.poly(np.vstack([O, I[::-1], [(-60, 2040), (1660, 2040)]]))
body = m.get()
add('pruss', PRUSS, body)
def C(w):
return I * (1 - w) + O * w
# stripes that follow the flow of the water up the face of the wave
for colour_name, colour, ws in (('mid', MID, (0.10, 0.25, 0.40, 0.55, 0.70)), ('light', LIGHT, (0.18, 0.33, 0.48, 0.63))):
m = Mask()
for w in ws:
s0 = rng.uniform(0.02, 0.12) + 0.25 * (w > 0.5) * 0
s1 = rng.uniform(0.80, 0.9)
i0, i1 = int(s0 * 499), int(s1 * 499)
a = C(w)[i0:i1]
th = 0.030 if colour_name == 'mid' else 0.013
b = C(w + th)[i0:i1]
tp = np.sin(np.linspace(0, math.pi, len(a))) ** 0.5
bb = a + (b - a) * tp[:, None]
m.poly(np.vstack([a, bb[::-1]]))
add(colour_name, colour, m.get() * body, outline=False)
# foam along the crest and round the lip, with a lumpy inner border
foam = Mask()
s = np.linspace(0, 1, 500)
th = 0.36 * smooth(0.30, 0.50, s) * (0.8 + 0.2 * np.sin(s * 55)) + 0.75 * smooth(0.70, 0.90, s)
th = np.clip(th, 0, 1)
inner = I + (O - I) * (1 - th)[:, None]
i0 = 150
foam.poly(np.vstack([O[i0:], inner[i0:][::-1]]))
frng = np.random.default_rng(3)
for i in range(i0 + 6, 500, 9): # lumps on the inner border and on the top edge
foam.circle(inner[i][0], inner[i][1], frng.uniform(13, 30))
for i in range(i0 - 20, 440, 7):
k = smooth(i0 - 20, i0 + 60, i)
foam.circle(O[i][0], O[i][1], frng.uniform(10, 26) * k + 3)
# claws that reach out of the lip into the hollow of the wave
tan = np.gradient(I, axis=0)
tan /= np.hypot(tan[:, 0], tan[:, 1])[:, None]
i = int(0.585 * 499)
while i < 497:
sfrac = i / 499
nrm = np.array([-tan[i][1], tan[i][0]])
if nrm @ (O[i] - I[i]) > 0:
nrm = -nrm
d = nrm * 0.55 + np.array([-0.5, 0.72])
ang = math.atan2(d[1], d[0]) + frng.uniform(-0.25, 0.25)
k = math.sin(math.pi * min(1.0, (sfrac - 0.56) / 0.44)) ** 0.6
length = (80 + 170 * k) * frng.uniform(0.6, 1.1)
base = I[i] - nrm * 22
finger(foam, base, ang, length, frng.uniform(19, 28) * (0.7 + 0.5 * k), frng.uniform(0.9, 1.9), 2, frng)
i += int(frng.uniform(12, 22))
# a few claws on the outside of the falling lip
tanO = np.gradient(O, axis=0)
for i in range(405, 500, 16):
nrm = np.array([-tanO[i][1], tanO[i][0]]); nrm /= np.hypot(*nrm)
if nrm @ (I[i] - O[i]) > 0:
nrm = -nrm
d = nrm * 0.7 + np.array([-0.3, 0.6])
finger(foam, O[i] - nrm * 10, math.atan2(d[1], d[0]), frng.uniform(60, 120), frng.uniform(15, 22), -frng.uniform(0.8, 1.6), 2, frng)
foamm = foam.get()
add('foam', FOAM, foamm)
# pale blue shading inside the foam
m = Mask()
for i in range(i0 + 30, 470, 34):
j = min(499, i + int(frng.uniform(14, 26)))
w = 1 - th[i:j] * frng.uniform(0.35, 0.6)
seg = I[i:j] + (O[i:j] - I[i:j]) * w[:, None]
if len(seg) > 3:
m.ribbon(seg, 7 * np.sin(np.linspace(0, math.pi, len(seg))) + 1)
add('shade', SHADE, m.get() * (ndi.gaussian_filter(foamm, 6) > 0.93), outline=False)
# ---------------- spray: round drops flying off the crest ----------------
m = Mask()
for _ in range(230):
i = frng.integers(250, 499)
base = O[i] if frng.random() < 0.5 else I[min(499, i + 60)]
off = np.array([-abs(frng.normal(0, 150)) - 20, frng.normal(60, 150)])
p = base + off
if 90 < p[0] < W - 90 and 90 < p[1] < 1180:
m.circle(p[0], p[1], frng.uniform(3.5, 10))
spray = m.get() * (1 - smooth(0.02, 0.2, ndi.gaussian_filter(foamm + body, 5)))
add('foam', FOAM, spray, lw=(1.3, 1.8))
# ---------------- middle wave (left), a pointed peak with its own foam ----------------
top = resample(spline([(-60, 1700), (90, 1630), (230, 1530), (340, 1420), (420, 1330), (475, 1290), (505, 1345),
(560, 1470), (690, 1580), (880, 1650), (1100, 1690), (1300, 1680), (1480, 1640), (1680, 1610)], 30), 400)
m = Mask(); m.poly(np.vstack([top, [(1680, 2040), (-60, 2040)]]))
midm = m.get()
add('mid', MID, midm)
m = Mask()
for k in range(1, 12):
off = k * 30 + frng.uniform(-5, 5)
a = top + np.array([10.0 * k, off])
j0, j1 = sorted(frng.integers(0, 400, 2))
if j1 - j0 < 90:
j0, j1 = max(0, j0 - 80), min(400, j1 + 80)
seg = a[j0:j1]
m.ribbon(seg, 7.5 * np.sin(np.linspace(0, math.pi, len(seg))) ** 0.6 + 0.5)
add('pruss', PRUSS, m.get() * midm, outline=False)
def cap(mk, seg, thick, lump):
"""A foam cap that sits on a crest: flat on top, lumpy below."""
prof = np.sin(np.linspace(0, math.pi, len(seg))) ** 0.6
low = seg + np.stack([np.zeros(len(seg)), thick * prof], 1)
mk.poly(np.vstack([seg + np.array([0, -3.0]), low[::-1]]))
step = max(2, int(lump * 1.1 / (np.hypot(*(seg[1] - seg[0])) + 1e-6)))
for j in range(step, len(seg) - step, step):
mk.circle(low[j][0], low[j][1], lump * frng.uniform(0.7, 1.25) * (0.45 + 0.55 * prof[j]))
mk.circle(seg[j][0], seg[j][1] - 1, lump * 0.55 * frng.uniform(0.5, 1.0) * prof[j])
foam2 = Mask()
cap(foam2, top[70:215], 128, 27)
for i in range(150, 212, 10):
finger(foam2, top[i] + np.array([0, 40.0]), frng.uniform(0.9, 1.5), frng.uniform(45, 90), frng.uniform(12, 17), -frng.uniform(0.8, 1.6), 1, frng)
for i in range(80, 140, 14):
finger(foam2, top[i] + np.array([0, 36.0]), math.pi - frng.uniform(0.7, 1.2), frng.uniform(35, 65), frng.uniform(10, 14), frng.uniform(0.8, 1.4), 1, frng)
f2 = foam2.get()
add('foam', FOAM, f2)
m = Mask()
for (j0, j1) in ((90, 118), (125, 150), (160, 190)):
seg = top[j0:j1] + np.array([0, 30.0])
m.ribbon(seg, 6 * np.sin(np.linspace(0, math.pi, len(seg))) + 1)
add('shade', SHADE, m.get() * (ndi.gaussian_filter(f2, 5) > 0.9), outline=False)
# ---------------- front swell along the bottom ----------------
top2 = resample(spline([(-60, 1900), (150, 1850), (380, 1790), (600, 1800), (800, 1860), (1000, 1890), (1180, 1840),
(1330, 1770), (1450, 1745), (1540, 1790), (1680, 1850)], 30), 400)
m = Mask(); m.poly(np.vstack([top2, [(1680, 2040), (-60, 2040)]]))
fm = m.get()
add('pruss', PRUSS, fm)
m = Mask()
for k in range(1, 7):
a = top2 + np.array([0, k * 24.0 + 6])
j0 = frng.integers(0, 200); j1 = j0 + frng.integers(120, 200)
seg = a[j0:j1]
m.ribbon(seg, 5.5 * np.sin(np.linspace(0, math.pi, len(seg))) ** 0.6 + 0.5)
add('light', LIGHT, m.get() * fm, outline=False)
foam3 = Mask()
for (a0, a1) in ((30, 150), (265, 360)):
cap(foam3, top2[a0:a1], 46, 17)
for i in range(a0 + 14, a1 - 10, 17):
finger(foam3, top2[i] + np.array([0, 24.0]), frng.uniform(0.8, 1.4) if a0 > 200 else math.pi - frng.uniform(0.8, 1.4),
frng.uniform(28, 50), frng.uniform(8, 11), frng.uniform(-1.5, 1.5), 1, frng)
add('foam', FOAM, foam3.get())
# ---------------- birds in the sky ----------------
m = Mask()
for (bx, by, sc, tilt) in ((250, 330, 1.0, -0.2), (360, 265, 0.8, 0.1), (190, 455, 0.7, -0.35), (470, 350, 0.6, 0.0), (120, 250, 0.55, 0.2)):
for sgn in (-1, 1):
t = np.linspace(0, 1, 12)
wx = bx + sgn * 46 * sc * t
wy = by - 26 * sc * np.sin(t * 2.4) + 10 * sc * t + tilt * sgn * 20 * t
m.ribbon(np.stack([wx, wy], 1), 5.5 * sc * (1 - t) ** 0.8 + 0.6)
m.circle(bx, by + 2 * sc, 6 * sc)
birds = m.get()
print('shapes done %.1fs' % (time.time() - T0))
# ---------------- paper ----------------
prng = np.random.default_rng(5)
paper = np.array([0.925, 0.875, 0.755], F)[None, None, :] * np.ones((H, W, 1), F)
paper *= (0.955 + 0.09 * fbm((H, W), 300, 4, prng))[..., None]
paper *= (0.985 + 0.03 * fbm((H, W), 4, 2, prng))[..., None]
fib = Image.new('L', (W, H), 128)
fd = ImageDraw.Draw(fib)
for _ in range(5200):
x, y = prng.uniform(0, W), prng.uniform(0, H)
a = prng.uniform(0, math.pi); L = prng.uniform(8, 42)
c = prng.uniform(-0.3, 0.3)
pts = [(x + math.cos(a + c * t) * L * t, y + math.sin(a + c * t) * L * t) for t in np.linspace(0, 1, 6)]
fd.line(pts, fill=int(128 + prng.choice([-1, 1]) * prng.uniform(14, 44)), width=1)
fibn = (np.asarray(fib, F) - 128) / 255.0
paper *= (1 + 0.5 * ndi.gaussian_filter(fibn, 0.6))[..., None]
paper *= (1 - 0.012 * (np.sin(yy * 2 * math.pi / 5.0) > 0.92))[..., None] # laid lines of the paper mould
stain = fbm((H, W), 500, 3, prng)
paper *= (1 - 0.10 * smooth(0.55, 0.8, stain))[..., None] * np.array([1.0, 0.985, 0.95], F)
ed = np.minimum(np.minimum(xx, W - 1 - xx), np.minimum(yy, H - 1 - yy))
paper *= (0.86 + 0.14 * smooth(0, 150, ed + 60 * (stain - 0.5)))[..., None]
# ---------------- printing ----------------
MAR = 74
inside = ((xx > MAR) & (xx < W - MAR) & (yy > MAR) & (yy < H - MAR)).astype(F)
frame_wob = ndi.gaussian_filter(inside, 1.2)
grain = fbm((H, W), (9, 900), 3, prng) # wood grain of the printing blocks
gy = np.clip(yy + 60 * fbm((H, W), (400, 500), 2, prng) + 14 * np.sin(xx / 260.0), 0, H - 1)
grain = ndi.map_coordinates(grain, [gy, xx], order=1) # the grain lines wander a little
grain2 = fbm((H, W), (3, 60), 2, prng)
img = paper.copy()
def printp(colour, cov, shift, strength=1.0, grainy=0.16, seed=0):
nonlocal img
r = np.random.default_rng(seed)
cov = ndi.shift(cov, shift, order=1, mode='nearest') * frame_wob
g = 1 - grainy * smooth(0.45, 0.8, grain) - 0.05 * grain2
holes = vnoise((H, W), 2.2, r) > 0.93
blot = 0.93 + 0.07 * fbm((H, W), 90, 3, r)
a = np.clip(cov * strength * g * blot * (1 - 0.5 * holes), 0, 1)[..., None]
ink = colour[None, None, :] * (0.55 + 0.45 * paper / paper.max())
img = img * (1 - a) + ink * a
# sky colours fade smoothly ("bokashi"): the printer wipes the block before printing
sky_dark = smooth(640, 74, yy) ** 1.4 * 0.86
sky_warm = np.exp(-((yy - 1150) / 230) ** 2) * 0.55
printp(np.array([0.90, 0.60, 0.42], F), sky_warm, (0, 0), grainy=0.10, seed=1)
printp(np.array([0.13, 0.19, 0.31], F), sky_dark, (0, 0), grainy=0.07, seed=2)
shifts = {'sun': (1.5, -1.0), 'hill': (-1, 1), 'light': (1.2, 1.4), 'mid': (-1.4, 0.8), 'pruss': (0.6, -1.2), 'foam': (0, 0), 'shade': (1, 1)}
for i, name in enumerate(('foam', 'sun', 'hill', 'light', 'shade', 'mid', 'pruss')):
colour, cov = plates[name]
printp(colour, cov, shifts[name], strength=0.97 if name != 'foam' else 0.85, grainy=0.03 if name == 'foam' else 0.06, seed=10 + i)
key = np.maximum(key, birds)
printp(KEY, np.clip(key, 0, 1), (0, 0), strength=0.95, grainy=0.08, seed=30)
# thin border line and a red seal
bl = ((np.abs(xx - MAR) < 2.2) | (np.abs(xx - (W - MAR)) < 2.2) | (np.abs(yy - MAR) < 2.2) | (np.abs(yy - (H - MAR)) < 2.2)) \
& (xx > MAR - 3) & (xx < W - MAR + 3) & (yy > MAR - 3) & (yy < H - MAR + 3)
printp(KEY, bl.astype(F) / np.maximum(frame_wob, 1e-3) * 0 + bl.astype(F), (0, 0), 0.9, 0.1, 31)
seal = Mask()
sx, sy, sz = 1385, 150, 82
seal.d.rounded_rectangle([sx * SS, sy * SS, (sx + sz) * SS, (sy + sz * 1.5) * SS], radius=10 * SS, fill=255)
for k in range(3): # an abstract wave mark, not writing
t = np.linspace(0, 1, 30)
px = sx + 14 + (sz - 28) * t
py = sy + 28 + k * 34 + 9 * np.sin(t * 2 * math.pi * 1.5 + k)
seal.line(np.stack([px, py], 1), 6.5, 0)
seal.circle(sx + sz / 2, sy + sz * 1.5 - 20, 0)
img_before = img
cov = seal.get()
frame_wob_backup = frame_wob
printp(np.array([0.78, 0.16, 0.10], F), cov, (0, 0), 0.9, 0.25, 32)
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()

