Fit and render the twelve reference views with adaptive gradient meshes
This commit is contained in:
@@ -0,0 +1,116 @@
|
|||||||
|
"""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")
|
||||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 253 KiB |
@@ -0,0 +1,56 @@
|
|||||||
|
"""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)
|
||||||
Reference in New Issue
Block a user