ExperimentsFable 5.2 Python art (30 images)

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

Several thousand circles are packed so that no two overlap. The picture is
first divided into four invisible regions: night sky, a large moon, a hill and
a sitting cat. A circle may never cross a region border, and its colour comes
only from the region its centre is in. So no outline is ever drawn: the cat
and the moon appear only because the circles change colour and size there.
The packing is greedy: a "free space" map stores, for every pixel, the largest
circle that still fits there, and it is updated after each new circle.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/18-circle-packing.py
"""
import os, time, math
import numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '18-circle-packing.png')
F32 = np.float32
rng = np.random.default_rng(1818)


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 smoothstep(a, b, x):
    t = np.clip((x - a) / (b - a), 0, 1)
    return t * t * (3 - 2 * t)


def noise(sigma, seed):
    r = np.random.default_rng(seed)
    n = ndi.gaussian_filter(r.standard_normal((H // 4, W // 4)).astype(F32), sigma / 4, mode='reflect')
    n = ndi.zoom(n, 4, order=1)
    return (n - n.mean()) / n.std()


yy, xx = np.mgrid[0:H, 0:W].astype(F32)

# ----------------------------------------------------------------------------
# 1. The hidden regions: 0 sky, 1 moon, 2 hill, 3 cat
# ----------------------------------------------------------------------------
MOON = (770.0, 800.0, 575.0)                       # centre x, centre y, radius
moon = np.hypot(xx - MOON[0], yy - MOON[1]) < MOON[2]
hill_y = 1640 + 70 * np.sin((xx - 250) / 520.0) - 0.00016 * (xx - 900) ** 2 + 22 * np.sin(xx / 97.0 + 1.0)
hill = yy > hill_y

# The cat is drawn as a mask (ellipses, triangles and a thick curve for the
# tail), at 2x size, then blurred and cut again so that all joints are round.
S = 2
cm = Image.new('L', (W * S, H * S), 0)
d = ImageDraw.Draw(cm)


CAT_SCALE, AX, AY = 1.24, 880.0, 1700.0             # the cat is enlarged about a point at its base


def tr(x, y):
    return (AX + (x - AX) * CAT_SCALE) * S, (AY + (y - AY) * CAT_SCALE) * S


def ell(cx, cy, rx, ry):
    d.ellipse([*tr(cx - rx, cy - ry), *tr(cx + rx, cy + ry)], fill=255)


def poly(pts):
    d.polygon([tr(x, y) for x, y in pts], fill=255)


CX = 905                                            # the cat sits right of centre, looking up at the moon
ell(CX, 1440, 150, 215)                             # back
ell(CX + 8, 1560, 205, 150)                         # haunches
ell(CX - 12, 1265, 105, 120)                        # shoulders and neck
ell(CX - 30, 1115, 122, 108)                        # head
poly([(CX - 148, 1090), (CX - 138, 930), (CX - 42, 1022)])      # left ear
poly([(CX + 88, 1090), (CX + 80, 932), (CX - 18, 1022)])        # right ear
# Tail: a curve that leaves the body low on the right, sweeps out and curls up.
t = np.linspace(0, 1, 160)
tx = CX + 150 + 235 * np.sin(t * 2.05) + 30 * t
ty = 1655 - 40 * np.sin(t * 3.1) - 330 * t ** 1.9 + 20 * t
tw = 46 - 16 * t
for i in range(len(t)):
    ell(tx[i], ty[i], tw[i], tw[i])
cat = np.asarray(cm, F32) / 255.0
cat = ndi.gaussian_filter(cat, 9 * S)
cat = np.asarray(Image.fromarray((cat * 255).astype(np.uint8)).resize((W, H), Image.LANCZOS), F32) / 255.0 > 0.5

label = np.zeros((H, W), np.int8)
label[moon] = 1
label[hill] = 2
label[cat] = 3
cat_depth = ndi.distance_transform_edt(cat).astype(F32)       # how far inside the cat a pixel is

# Free space: distance from each pixel to the nearest region border or to the
# picture margin. A circle centred there may be at most this large.
MARGIN = 46
free = np.full((H, W), 1e9, F32)
for L in range(4):
    m = label == L
    if m.any():
        free = np.where(m, ndi.distance_transform_edt(m).astype(F32), free)
edge = np.minimum(np.minimum(xx, W - 1 - xx), np.minimum(yy, H - 1 - yy)) - MARGIN
free = np.minimum(free, edge) - 1.5

# ----------------------------------------------------------------------------
# 2. Greedy packing, large circles first
# ----------------------------------------------------------------------------
RMAX = np.array([46, 40, 30, 19], F32)             # largest circle per region
size_var = 0.75 + 0.25 * (noise(160, 5) > 0.2)     # some areas use smaller circles
GAP = 2.6
circles = []                                       # x, y, r, region


def place(px, py, r):
    R = int(r + RMAX.max() + GAP + 3)
    x0, x1 = max(px - R, 0), min(px + R + 1, W)
    y0, y1 = max(py - R, 0), min(py + R + 1, H)
    dd = np.hypot(xx[y0:y1, x0:x1] - px, yy[y0:y1, x0:x1] - py) - r - GAP
    np.minimum(free[y0:y1, x0:x1], dd, out=free[y0:y1, x0:x1])


levels = np.geomspace(46, 3.4, 30)
for li, r_lv in enumerate(levels):
    for attempt in range(40):
        ys, xs = np.nonzero(free >= r_lv)
        if len(ys) == 0:
            break
        pick = rng.permutation(len(ys))[:6000]
        n_new = 0
        for i in pick:
            py, px = int(ys[i]), int(xs[i])
            f = free[py, px]
            if f < r_lv:
                continue
            L = int(label[py, px])
            r = min(f, RMAX[L] * size_var[py, px])
            if r < r_lv * 0.92:
                continue
            # Random shrink for variety on the big levels; small levels fill tightly.
            if r > 12:
                r *= rng.uniform(0.72, 1.0)
            circles.append((px, py, r, L))
            place(px, py, r)
            n_new += 1
        if n_new == 0:
            break
circles = np.array(circles, F32)
print('circles:', len(circles), '%.1fs' % (time.time() - T0))

# ----------------------------------------------------------------------------
# 3. Colour: every circle takes one flat colour from its region
# ----------------------------------------------------------------------------
n_big, n_mid, n_fine = noise(260, 11), noise(90, 12), noise(40, 13)


def ramp(stops, t):
    """Piecewise-linear colour ramp; stops = [(pos, hex), ...]."""
    t = float(np.clip(t, 0, 1))
    for (p0, c0), (p1, c1) in zip(stops[:-1], stops[1:]):
        if t <= p1:
            u = (t - p0) / max(p1 - p0, 1e-6)
            return hexc(c0) * (1 - u) + hexc(c1) * u
    return hexc(stops[-1][1])


SKY = [(0.0, '#141a4a'), (0.35, '#27348a'), (0.62, '#3d5fc0'), (0.82, '#4fa3c9'), (1.0, '#9fd8cf')]
MOONC = [(0.0, '#d98c3a'), (0.30, '#f0b24a'), (0.60, '#f8d67c'), (0.85, '#fdeeb6'), (1.0, '#fffbe6')]
HILL = [(0.0, '#0f2f3a'), (0.4, '#17505a'), (0.75, '#2a7d74'), (1.0, '#69b58c')]
CAT = [(0.0, '#100e1c'), (0.45, '#1d1830'), (0.8, '#30244a'), (1.0, '#4a3466')]

cols = np.zeros((len(circles), 3), F32)
kind = np.zeros(len(circles), np.int8)             # 0 plain, 1 two-tone, 2 ring, 3 star
for i, (px, py, r, L) in enumerate(circles):
    ix, iy = int(px), int(py)
    u = rng.random()
    dm = (math.hypot(px - MOON[0], py - MOON[1]) - MOON[2]) / 900.0      # distance outside the moon
    if L == 0:
        # Sky: brightest in a halo round the moon, darkest in the far corners.
        tsky = 0.95 * math.exp(-dm * 2.6) + 0.10 * n_mid[iy, ix] + 0.10 * (u - 0.5)
        c = ramp(SKY, tsky)
        if r < 6.5 and rng.random() < 0.20:
            c = hexc('#fff3c4'); kind[i] = 3       # small circles become stars
        elif rng.random() < 0.022 and r > 9:
            c = hexc('#e86a8a') * 0.9              # a few rose accents
    elif L == 1:
        # Moon: pale, with darker "seas" from slow noise and a shaded lower-right limb.
        limb = ((px - MOON[0]) * 0.55 + (py - MOON[1]) * 0.83) / MOON[2]
        tm = 0.80 - 0.22 * smoothstep(0.1, 1.0, limb) - 0.30 * smoothstep(0.2, 1.2, n_big[iy, ix] + 0.5 * n_mid[iy, ix]) + 0.22 * (u - 0.5)
        c = ramp(MOONC, tm)
    elif L == 2:
        th = 0.78 - (py - hill_y[iy, ix]) / 330.0 + 0.16 * n_mid[iy, ix] + 0.30 * (u - 0.5)
        c = ramp(HILL, th)
        if r < 10 and rng.random() < 0.10:
            c = hexc('#f2a03d') if rng.random() < 0.6 else hexc('#f4e7b0')   # small flowers in the grass
    else:
        # Cat: dark plum tones; circles close to the outline catch a little warm moonlight.
        rimlight = math.exp(-cat_depth[iy, ix] / 26.0) * (1.0 if py < 1500 else 0.35)
        c = ramp(CAT, 0.40 + 0.75 * (u - 0.5) + 0.15 * n_fine[iy, ix] + 0.35 * rimlight)
        c = c + rimlight * hexc('#c8742a') * 0.30
    cols[i] = c
    if kind[i] == 0 and r > 13:
        q = rng.random()
        kind[i] = 1 if q < 0.30 else (2 if (q < 0.42 and L != 1) else 0)

# ----------------------------------------------------------------------------
# 4. Draw the circles (anti-aliased, with a soft painted look)
# ----------------------------------------------------------------------------
BG = hexc('#0a0b16')
img = np.empty((H, W, 3), F32)
img[:] = BG
img *= (1 + 0.05 * noise(8, 21))[..., None]
shadow = np.zeros((H, W), F32)
order = np.argsort(-circles[:, 2])
for i in order:
    px, py, r, L = circles[i]
    R = int(r + 3)
    x0, x1 = max(int(px) - R, 0), min(int(px) + R + 1, W)
    y0, y1 = max(int(py) - R, 0), min(int(py) + R + 1, H)
    dx, dy = xx[y0:y1, x0:x1] - px, yy[y0:y1, x0:x1] - py
    dist = np.hypot(dx, dy)
    cov = np.clip(r + 0.5 - dist, 0, 1)
    c = cols[i]
    # Light from the upper left, a darker rim, and a small specular touch on big circles.
    shade = 1.0 + 0.16 * (-(dx * 0.6 + dy * 0.8) / max(r, 1.0))
    rim = 1 - 0.20 * smoothstep(r - max(2.0, 0.16 * r), r, dist)
    px_col = c[None, None, :] * (shade * rim)[..., None]
    if kind[i] == 1:                               # two-tone: an inner disc, lighter or darker
        k = 1.28 if rng.random() < 0.6 else 0.72
        inner = np.clip(r * 0.56 + 0.5 - dist, 0, 1)[..., None]
        px_col = px_col * (1 - inner) + np.clip(px_col * k + (0.04 if k > 1 else 0), 0, 1) * inner
    elif kind[i] == 2:                             # ring: the centre shows the background
        hole = np.clip(r * 0.60 + 0.5 - dist, 0, 1)
        cov = cov * (1 - hole)
        dot = np.clip(r * 0.22 + 0.5 - dist, 0, 1)
        cov = np.maximum(cov, dot)
    elif kind[i] == 3:
        px_col = px_col * 1.1
    sl = img[y0:y1, x0:x1]
    sl[:] = sl * (1 - cov[..., None]) + px_col * cov[..., None]

# ----------------------------------------------------------------------------
# 5. Finish: moonlight bloom, paper grain, vignette
# ----------------------------------------------------------------------------
lum = img @ np.array([0.3, 0.55, 0.15], F32)
bright = img * smoothstep(0.55, 0.95, lum)[..., None]
bloom = np.stack([ndi.gaussian_filter(bright[..., c], 46) for c in range(3)], -1)
bloom2 = np.stack([ndi.gaussian_filter(bright[..., c], 12) for c in range(3)], -1)
keep = 1 - 0.75 * ndi.gaussian_filter(cat.astype(F32), 10)   # the cat stays dark: little glow on it
img = img + (0.36 * bloom * np.array([1.0, 0.92, 0.75], F32) + 0.12 * bloom2) * keep[..., None]
grain = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), 0.7)
img *= (1 + 0.035 * grain)[..., None]
vig = 1 - 0.30 * smoothstep(0.55, 1.25, np.hypot((xx - W / 2) / (W / 2), (yy - H / 2) / (H / 2)))
img *= vig[..., None]
img = np.clip(img, 0, 1) ** 0.96
Image.fromarray((img * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))