ExperimentsFable 5.2 Python art (30 images)

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

The poster is built like an old colour print. Every shape (circle, bar,
triangle, ring, arc) is a distance formula, which gives clean anti-aliased
edges. The shapes are sorted onto four "printing plates": yellow, red, blue
and black. The plates are printed one over the other with a light-absorbing
ink model, so red over yellow turns orange and red over blue turns deep
maroon, as real inks do. Each plate is shifted by a pixel or two, the ink is a
little uneven and the paper has fibres, so the result looks printed, not
computer-flat.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/19-bauhaus-poster.py
"""
import os, time, math
import numpy as np
from PIL import Image
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', '19-bauhaus-poster.png')
F32 = np.float32
rng = np.random.default_rng(1919)
yy, xx = np.mgrid[0:H, 0:W].astype(F32)


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, stretch=(1, 1)):
    n = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), (sigma * stretch[0], sigma * stretch[1]))
    return (n - n.mean()) / n.std()


# ----------------------------------------------------------------------------
# 1. Shapes as signed distances (negative inside). cov() turns one into 0..1.
# ----------------------------------------------------------------------------
def circle(cx, cy, r):
    return np.hypot(xx - cx, yy - cy) - r


def box(cx, cy, hw, hh, deg=0.0):
    a = math.radians(deg)
    dx, dy = xx - cx, yy - cy
    u = dx * math.cos(a) + dy * math.sin(a)
    v = -dx * math.sin(a) + dy * math.cos(a)
    qx, qy = np.abs(u) - hw, np.abs(v) - hh
    return np.hypot(np.maximum(qx, 0), np.maximum(qy, 0)) + np.minimum(np.maximum(qx, qy), 0)


def rect(x0, y0, x1, y1):
    return box((x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0) / 2, (y1 - y0) / 2)


def halfplane(px, py, deg):
    """Negative on the side that the direction 'deg' points away from."""
    a = math.radians(deg)
    return (xx - px) * math.cos(a) + (yy - py) * math.sin(a)


def convex(pts):
    """Convex polygon, points in clockwise screen order."""
    dmax = np.full((H, W), -1e9, F32)
    n = len(pts)
    for i in range(n):
        (x0, y0), (x1, y1) = pts[i], pts[(i + 1) % n]
        ex, ey = x1 - x0, y1 - y0
        L = math.hypot(ex, ey)
        dmax = np.maximum(dmax, ((xx - x0) * ey - (yy - y0) * ex) / L)
    return dmax


def ring(cx, cy, r, w):
    return np.abs(np.hypot(xx - cx, yy - cy) - r) - w / 2


def cov(sd):
    return np.clip(0.5 - sd, 0, 1)


def both(a, b):          # intersection
    return np.maximum(a, b)


def minus(a, b):         # a without b
    return np.maximum(a, -b)


# ----------------------------------------------------------------------------
# 2. The composition, sorted by printing plate
# ----------------------------------------------------------------------------
M = 96                                    # paper margin
plates = {k: np.zeros((H, W), F32) for k in ('yellow', 'red', 'blue', 'black')}
knock = np.zeros((H, W), F32)             # places where all ink is left out (bare paper)


def ink(name, sd):
    plates[name] = np.maximum(plates[name], cov(sd))


DIAG = -37.0                              # the main diagonal of the poster, in degrees

# Colour blocks.
ink('yellow', rect(M, M, 760, 620))                               # yellow field, upper left
ink('blue', rect(1040, 1150, W - M, H - M - 150))                 # blue field, lower right
# The large red disc sits on both fields and overprints them.
RC = (880.0, 930.0, 455.0)
ink('red', circle(*RC))
# A blue half disc, cut along the diagonal, lower left.
ink('blue', both(circle(520, 1480, 300), halfplane(520, 1480, DIAG + 90)))
# A yellow quarter disc tucked against the half disc on the other side of the cut.
ink('yellow', both(both(circle(520, 1480, 300), -halfplane(520, 1480, DIAG + 90) + 26), halfplane(520, 1480, DIAG) + 0))
# Red triangle, upper right, pointing at the disc.
ink('red', convex([(1180, M), (W - M, M), (W - M, 520)]))
# Small solid shapes.
ink('yellow', circle(1340, 1330, 132))                            # yellow disc on the blue field
ink('red', rect(M, 1010, M + 150, 1160))                          # red square on the left edge
ink('blue', circle(330, 360, 150))                                # blue disc on the yellow field -> green

# Black: the long diagonal beam and its thin companions.
ink('black', box(800, 1000, 1060, 34, DIAG))
ink('black', box(872, 1096, 720, 7, DIAG))
ink('black', box(908, 1144, 520, 3, DIAG))
# Black: concentric arcs round the red disc (upper right half only).
for k, rr in enumerate((500, 540, 580)):
    ink('black', both(ring(RC[0], RC[1], rr, 9 - 2 * k), -halfplane(RC[0], RC[1], DIAG + 90) + 40))
# Black disc with a ring, upper right.
ink('black', circle(1210, 700, 78))
ink('black', ring(1210, 700, 112, 8))
# Black bars: a rhythm of five, lower left.
for k in range(6):
    ink('black', rect(M + k * 58, 1806, M + k * 58 + 14 + 5 * k, H - M))
# Black base rule and the three small squares, like a maker's mark.
ink('black', rect(1040, H - M - 22, W - M, H - M))
ink('red', rect(1040, H - M - 118, 1112, H - M - 46))
ink('yellow', rect(1132, H - M - 118, 1204, H - M - 46))
ink('blue', rect(1224, H - M - 118, 1296, H - M - 46))
# A short stack of bars of falling length fills the quiet space at the top.
for k in range(5):
    ink('black', rect(860, 110 + k * 40, 1110 - k * 48, 124 + k * 40))
# A small black triangle answers the large red one from the left edge.
ink('black', convex([(M, 1240), (M + 150, 1315), (M, 1390)]))
# Thin black frame lines.
ink('black', rect(M, 660, 760, 668))
ink('black', rect(W - M - 8, 560, W - M, 1110))

# Knock-outs (bare paper): a dot grid in the blue field and a small disc in the black one.
for j in range(6):
    for i in range(6):
        knock = np.maximum(knock, cov(circle(1112 + i * 46, 1500 + j * 46, 9.5 - 1.1 * j)))
knock = np.maximum(knock, cov(circle(1210, 700, 22)))
# A paper-coloured ring cut out of the red disc.
knock_red = cov(ring(RC[0] - 150, RC[1] - 120, 150, 16))
# Yellow and blue never mix here (that would give a muddy green): where one
# sits on the other's field, the lower plate is left out.
knock_blue = cov(circle(1340, 1330, 132))
knock_yellow = cov(circle(330, 360, 150))

# ----------------------------------------------------------------------------
# 3. Printing: paper, uneven ink, plate shifts, overprint by absorption
# ----------------------------------------------------------------------------
fib = noise(1.0, (0.6, 5.0)) * 0.5 + noise(1.0, (4.0, 0.6)) * 0.3 + noise(0.7) * 0.35
blot = noise(120)
paper = hexc('#ece2cb')[None, None, :] * (1 + 0.022 * fib + 0.006 * blot)[..., None]
paper = paper * np.array([1.0, 1 - 0.006 * 1, 1 - 0.02], F32)

INK = {'yellow': hexc('#f2b90f'), 'red': hexc('#d4301f'), 'blue': hexc('#1f4aa0'), 'black': hexc('#16130f')}
SHIFT = {'yellow': (1.6, -1.2), 'red': (-1.0, 1.4), 'blue': (1.2, 1.8), 'black': (0.0, 0.0)}
STRENGTH = {'yellow': 0.97, 'red': 0.95, 'blue': 0.95, 'black': 0.985}

img = paper.copy()
for name in ('yellow', 'red', 'blue', 'black'):
    c = plates[name] * (1 - knock)
    if name == 'red':
        c = c * (1 - knock_red)
    if name == 'blue':
        c = c * (1 - knock_blue)
    if name == 'yellow':
        c = c * (1 - knock_yellow)
    c = ndi.shift(c, SHIFT[name], order=1, mode='constant')
    # Uneven ink: slow mottling, fine grain that follows the paper, and tiny voids.
    mott = noise(26)
    grain = noise(0.8)
    lay = STRENGTH[name] * (1 + 0.035 * mott + 0.05 * grain - 0.05 * np.clip(fib, 0, 3))
    voids = smoothstep(2.35, 2.9, noise(1.3))
    lay = np.clip(lay, 0, 1) * (1 - 0.8 * voids)
    # Ink squeezes to the edge of a letterpress shape: a slightly darker rim.
    inner = ndi.gaussian_filter(c, 3.0)
    rim = c * (1 - inner) * 2.0
    a = np.clip(c * lay + 0.10 * rim, 0, 1)
    # Absorption: the ink removes its complementary light from what is below.
    img = img * (1 - a[..., None] * (1 - INK[name][None, None, :]))

# ----------------------------------------------------------------------------
# 4. Finish: soft age toning toward the edges, fine grain
# ----------------------------------------------------------------------------
e = np.minimum(np.minimum(xx, W - 1 - xx), np.minimum(yy, H - 1 - yy))
tone = 1 - 0.07 * (1 - smoothstep(0, 200, e))
img = img * tone[..., None] * np.array([1.0, 0.99, 0.965], F32)
img += rng.standard_normal((H, W, 1)).astype(F32) * 0.008
Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))