Files
Bedrock/brand/ribbon-study/gradient-mesh/fit.py
T

117 lines
4.2 KiB
Python

"""Fit a gradient mesh to the 750 x 1500 reference sheet. Requires NumPy and Pillow."""
import argparse
import json
from pathlib import Path
import numpy as np
from PIL import Image
from render import HERE, render
# Centre, half-width of square, transpose to cut across vertical ribbons.
CROPS = [(459,255,40,1), (300,1108,40,1), (451,1108,41,0), (609,128,40,1),
(148,1245,42,1), (459,128,41,1), (221,256,122,0), (604,1245,41,1),
(148,1383,41,1), (609,382,41,0), (459,382,41,1), (609,255,41,1)]
def simplify(values, tolerance):
"""Indices of knots in a piecewise linear approximation with bounded error."""
keep = [0, len(values)-1]
pending = [(0, len(values)-1)]
while pending:
a, b = pending.pop()
if b-a < 2:
continue
t = np.arange(1, b-a)[:, None]/(b-a)
error = np.max(np.abs(values[a+1:b] - (values[a]+t*(values[b]-values[a]))), axis=1)
split = int(np.argmax(error))
if error[split] > tolerance:
mid = a+1+split
keep.append(mid)
pending.extend([(a,mid), (mid,b)])
return sorted(keep)
def align(a, b, spacing):
"""Monotone matching along two cross-sections, penalising stretch and drift."""
n = len(a)
pos = np.arange(n)
displacement = np.abs(pos[:, None]-pos)
cost = (np.mean(np.abs(a[:, None]-b), axis=2) + .5*displacement
+ 5*np.maximum(displacement-2*spacing, 0))
total = np.full((n+1, n+1), np.inf)
total[0,0] = 0
# All entries on one antidiagonal can be updated together.
for k in range(2, 2*n+1):
x = np.arange(max(1,k-n), min(n,k-1)+1)
y = k-x
total[x,y] = cost[x-1,y-1]+np.minimum(total[x-1,y-1],
1.8+np.minimum(total[x-1,y],total[x,y-1]))
x = y = n
path = []
while x and y:
path.append((x-1,y-1))
step = np.argmin([total[x-1,y-1], total[x-1,y]+1.8, total[x,y-1]+1.8])
x -= int(step != 2)
y -= int(step != 1)
points = np.array(path[::-1])
return points[simplify(points, .8)].tolist()
def fit(rgb, transpose):
data = (rgb.swapaxes(0,1) if transpose else rgb).astype(float)
n = len(data)
sample = np.arange(n)
sections, matches = {}, {}
def profile(y):
if y not in sections:
knots = simplify(data[y], 5)
sections[y] = np.column_stack((sample[knots], data[y,knots])).astype(int).tolist()
return sections[y]
def match(a,b):
if (a,b) not in matches:
matches[a,b] = align(data[a],data[b],b-a)
return matches[a,b]
def build(cuts):
return dict(span=n, transpose=bool(transpose), cuts=cuts, sections=[profile(y) for y in cuts],
correspondence=[match(a,b) for a,b in zip(cuts,cuts[1:])])
cuts = sorted({0,n-1,*range(0,n,max(6,n//10))})
for _ in range(5):
model = build(cuts)
view = np.asarray(render(model, n))
if transpose:
view = view.swapaxes(0,1)
delta = np.mean(np.abs(view-data),axis=2)
# Include a high percentile so a narrow tip cannot disappear in the mean.
errors = delta.mean(axis=1) + .35*np.percentile(delta,95,axis=1)
additions = []
for a,b in zip(cuts,cuts[1:]):
if b-a<2:
continue
y = a+1+int(np.argmax(errors[a+1:b]))
if errors[y] > (10 if b-a <= 3 else 5):
additions.append(y)
if not additions:
break
cuts = sorted(cuts+additions)
return build(cuts)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("reference", type=Path)
args = parser.parse_args()
photo = Image.open(args.reference).convert("RGB")
if photo.size != (750,1500):
parser.error("Expected the original 750 x 1500 reference sheet")
models = []
for cx,cy,r,transpose in CROPS:
crop = np.asarray(photo.crop((cx-r,cy-r,cx+r,cy+r)))
models.append(fit(crop, transpose))
(HERE/"marks.json").write_text("[\n"+",\n".join(json.dumps(model,separators=(",",":"))
for model in models)+"\n]\n")