Sampling smooth random fields and binary masks with controllable topology, using tensor products of orthogonal polynomials.
We want a cheap, reproducible supply of smooth random fields on a grid — and, by thresholding, binary masks with controllable topology. Our use case: synthetic perturbations for training a topology-aware segmentation model (see the demo). Orthogonal polynomials make this easy.
Build a 2D field by tensoring two 1D bases, $f(x, y) = \sum_{ij} c_{ij}\, P_i(x)\, P_j(y)$, with random, seeded coefficients. Each basis gives a different texture — a few samples each, expand for more:
Legendre
Chebyshev
Hermite (probabilist’s, $He_n$)
Physicist’s Hermite ($H_n$)
A fresh $300 \times 300$ field takes about 14 ms (≈ 70 per second) on a laptop, so a large batch is cheap.
Threshold a field to get a binary mask. Raising the order folds the level set more, adding more connected components and holes.
import numpy as np
from polysynth import Legendre, TensorPolynomial, random_coefficients
x = np.linspace(-1, 1, 300)
X, Y = np.meshgrid(x, x)
f = TensorPolynomial(Legendre(), random_coefficients((6, 6), normalize="l1", seed=0))
Z = f(X, Y) # smooth random field
mask = f.mask(X, Y, threshold=0.5) # binary topology perturbation
Swap Legendre() for Chebyshev(), Hermite(), or PhysicistsHermite() to change the texture; raise the order for more topology.