"""Measure prepared views and lay them out at one real-world scale as a model sheet. Usage: python compose_sheet.py SPEC.json OUT_DIR [--no-render] Reads OUT_DIR/views/.webp (made by prepare_views.py) and writes OUT_DIR/sheet.svg, OUT_DIR/sheet.webp (rendered with headless Chromium when available) and OUT_DIR/measurements.json. Prints every consistency/reference check as PASS or WARN. See references/spec-format.md for the spec. """ import glob import json import math import os import shutil import subprocess import sys import tempfile from html import escape from pathlib import Path import numpy as np from PIL import Image FONT = "font-family=\"'Noto Sans CJK KR','Noto Sans KR','Apple SD Gothic Neo',sans-serif\"" INK, MUTED, GREEN, BLUE, BROWN, RED = '#24343d', '#586873', '#326b60', '#2f6fb0', '#875516', '#9a3830' GRID_STEPS = [(1, 5), (2, 10), (5, 25), (10, 50), (20, 100)] # (minor, major) in cm # ---------------------------------------------------------------- measuring class View: def __init__(self, spec: dict, out: Path): self.spec = spec self.name = spec['name'] image = Image.open(out / 'views' / f'{self.name}.webp').convert('RGBA') data = np.asarray(image) self.rgb = data[..., :3].astype(np.int16) self.solid = data[..., 3] > 127 rows = np.nonzero(self.solid.sum(axis=1) > 2)[0] cols = np.nonzero(self.solid.sum(axis=0) > 2)[0] self.box = (int(cols.min()), int(rows.min()), int(cols.max()) + 1, int(rows.max()) + 1) self.size = image.size self.ppc = None # source pixels per cm, set once scales are known @property def w(self) -> int: return self.box[2] - self.box[0] @property def h(self) -> int: return self.box[3] - self.box[1] def region(self, frac): l, t, r, b = self.box x0, y0, x1, y1 = frac mask = np.zeros_like(self.solid) mask[int(t + y0 * self.h): int(t + y1 * self.h) + 1, int(l + x0 * self.w): int(l + x1 * self.w) + 1] = True return mask & self.solid def detect(self, kind: str): """Coloured feature mask in the upper half of the subject (eyes).""" r, g, b = self.rgb[..., 0], self.rgb[..., 1], self.rgb[..., 2] if kind == 'orange': mask = (r > 170) & (g > 60) & (g < 160) & (b < 70) & (r - g > 60) elif kind == 'yellow': mask = (r > 160) & (g > 140) & (b < 90) & (r - b > 90) elif kind == 'green': mask = (g > 120) & (g > r + 25) & (g > b + 25) else: raise SystemExit(f'unknown detect kind: {kind}') mask &= self.solid mask[self.box[1] + self.h // 2:] = False return mask def text_width(s: str, size: float) -> float: """Rough rendered width: CJK glyphs are about one em, Latin about half.""" return sum(size * (1.0 if ord(ch) > 0x2e80 else 0.58) for ch in s) def centroid(mask): ys, xs = np.nonzero(mask) return (float(xs.mean()), float(ys.mean())) if len(xs) else None def colour_of(view: View, entry: dict): mask = view.detect(entry['detect']) if 'detect' in entry else view.region(entry['box']) px = view.rgb[mask] if len(px) == 0: return None stat = entry.get('stat', 'median') if stat in ('dark', 'light'): lum = px @ np.array([0.299, 0.587, 0.114]) order = np.argsort(lum) n = max(1, len(px) // 5) px = px[order[:n]] if stat == 'dark' else px[order[-n:]] elif stat == 'saturated': sat = px.max(axis=1) - px.min(axis=1) px = px[np.argsort(sat)[-max(1, int(len(px) * 0.3)):]] m = np.median(px, axis=0).astype(int) return '#%02x%02x%02x' % tuple(int(v) for v in m) # ---------------------------------------------------------------- svg helpers class Svg: def __init__(self): self.parts = [] def add(self, s: str): self.parts.append(s) def text(self, x, y, s, size=22, weight=400, fill=INK, anchor='start'): self.add(f'{escape(str(s))}') def line(self, x1, y1, x2, y2, stroke, width=1.5, dash=None, extra=''): d = f' stroke-dasharray="{dash}"' if dash else '' self.add(f'') def grid(self, x0, y0, x1, y1, ox, oy, s, step): minor, major = step for i in range(math.floor((x0 - ox) / (minor * s)), math.ceil((x1 - ox) / (minor * s)) + 1): x = ox + i * minor * s if x0 <= x <= x1: strong = (i * minor) % major == 0 self.line(x, y0, x, y1, '#b9c7c4' if strong else '#e3eaea', 1.4 if strong else 1) for j in range(math.floor((y0 - oy) / (minor * s)), math.ceil((y1 - oy) / (minor * s)) + 1): y = oy + j * minor * s if y0 <= y <= y1: strong = (j * minor) % major == 0 self.line(x0, y, x1, y, '#b9c7c4' if strong else '#e3eaea', 1.4 if strong else 1) def dim_h(self, x1, x2, y, label): self.add(f'' f'' f'') self.text((x1 + x2) / 2, y - 10, label, 20, 700, GREEN, 'middle') def dim_v(self, x, y1, y2, label, side='left'): self.add(f'' f'' f'') self.text(x - 12 if side == 'left' else x + 12, (y1 + y2) / 2 + 7, label, 20, 700, GREEN, 'end' if side == 'left' else 'start') def image(self, href, x, y, w, h): self.add(f'') # ---------------------------------------------------------------- main def main() -> None: spec_path, out = Path(sys.argv[1]), Path(sys.argv[2]) render = '--no-render' not in sys.argv spec = json.loads(spec_path.read_text(encoding='utf-8')) views = {v['name']: View(v, out) for v in spec['views']} # Landmarks are located in pixels first, because the anchor may be one of them. found = [] for lm in spec.get('landmarks', []): v = views[lm['view']] if 'detect' in lm: c = centroid(v.detect(lm['detect'])) if c is None: print(f"WARN landmark {lm['label']} not found in {lm['view']}; give it a 'y' fraction instead") continue y = c[1] else: y = v.box[1] + lm['y'] * v.h found.append((lm, v, y)) anchor = next(v for v in views.values() if 'anchor' in v.spec) a = anchor.spec['anchor'] if 'landmark' in a: # e.g. shoulder height: ground to the landmark is the published size hit = next((y for lm, v, y in found if v is anchor and lm['label'] == a['landmark']), None) if hit is None: raise SystemExit(f"anchor landmark {a['landmark']!r} must be a landmark of the {anchor.name} view") anchor.ppc = (anchor.box[3] - hit) / a['cm'] anchor_dim = 'landmark' else: anchor.ppc = (anchor.w if a['axis'] == 'x' else anchor.h) / a['cm'] anchor_dim = 'length' if a['axis'] == 'x' else 'height' base = {'length': anchor.w / anchor.ppc, 'height': anchor.h / anchor.ppc} for v in views.values(): if v is anchor: continue share = v.spec['share'] # An articulated pose (crouch, T-pose) keeps neither length nor height, so it may # give its own justified size in cm instead. target = share['cm'] if 'cm' in share else base[share['with']] v.ppc = (v.w if share['axis'] == 'x' else v.h) / target dims = {name: {'width': v.w / v.ppc, 'height': v.h / v.ppc} for name, v in views.items()} # Pivot of the anchor view: centre of the feet or of the whole subject. if anchor.spec.get('pivot', 'feet') == 'feet': feet = anchor.solid.copy() feet[: anchor.box[3] - max(2, int(anchor.h * 0.04))] = False pivot_x = centroid(feet)[0] else: pivot_x = (anchor.box[0] + anchor.box[2]) / 2 front_cm = (anchor.box[2] - pivot_x) / anchor.ppc back_cm = (pivot_x - anchor.box[0]) / anchor.ppc # Landmarks: heights above the ground of a standing view. landmarks = [{'label': lm['label'], 'view': lm['view'], 'cm': (v.box[3] - y) / v.ppc} for lm, v, y in found] def value(ref: str) -> float: """'.width' / '.height', or 'landmark: