"""Render fitted ribbon cross-sections. Requires NumPy and Pillow.""" import argparse import json from pathlib import Path import numpy as np from PIL import Image HERE = Path(__file__).resolve().parent def section(section_data, v): knots = np.array(section_data, dtype=float) return np.stack([np.interp(v, knots[:, 0], channel) for channel in knots[:, 1:].T], axis=-1) def render(model, size): """Interpolate geometry first, then interpolate the colours on each face.""" n = model["span"] axis = (np.arange(size) + .5) * n / size - .5 out = np.empty((size, size, 3), dtype=np.uint8) cuts = np.array(model["cuts"]) for row, y in enumerate(axis): i = np.clip(np.searchsorted(cuts, y, side="right")-1, 0, len(cuts)-2) t = np.clip((y-cuts[i])/(cuts[i+1]-cuts[i]), 0, 1) a, b = np.array(model["correspondence"][i]).T middle = (1-t)*a + t*b u = np.interp(axis, middle, a) v = np.interp(axis, middle, b) colors = (1-t)*section(model["sections"][i], u) + t*section(model["sections"][i+1], v) out[row] = np.clip(np.rint(colors), 0, 255) if model["transpose"]: out = np.swapaxes(out, 0, 1) return Image.fromarray(out) def sheet(models, size): gap = size//3 canvas = Image.new("RGB", (4*(size+gap)+gap, 3*(size+gap)+gap), (70, 22, 70)) for i, model in enumerate(models): canvas.paste(render(model, size), (gap+i%4*(size+gap), gap+i//4*(size+gap))) return canvas if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--mark", type=int, choices=range(1, 13)) parser.add_argument("--size", type=int, default=128, help="pixels per mark") parser.add_argument("--output", type=Path) args = parser.parse_args() if args.size < 1: parser.error("--size must be positive") models = json.loads((HERE/"marks.json").read_text()) image = render(models[args.mark-1], args.size) if args.mark else sheet(models, args.size) target = args.output or HERE/(f"mark-{args.mark:02}.png" if args.mark else "preview.png") image.save(target)