Add files using upload-large-folder tool
Browse filesFiles changed (31)
- .gitattributes+6
- source/CLIP_P0010073.movAdded+3
- trajectory_project/intermediate/contact_sheet.jpgAdded
- trajectory_project/intermediate/contact_sheet_full.jpgAdded
- trajectory_project/intermediate/genmo_reference.pdfAdded+3
- trajectory_project/intermediate/genmo_teaser.jpgAdded
- trajectory_project/intermediate/keyframes/t0.jpgAdded
- trajectory_project/intermediate/keyframes/t10.jpgAdded
- trajectory_project/intermediate/keyframes/t20.jpgAdded
- trajectory_project/intermediate/keyframes/t30.jpgAdded
- trajectory_project/intermediate/keyframes/t35.jpgAdded
- trajectory_project/intermediate/keyframes/t40.jpgAdded
- trajectory_project/intermediate/keyframes/t45.jpgAdded
- trajectory_project/intermediate/keyframes/t50.jpgAdded
- trajectory_project/intermediate/keyframes/t55.jpgAdded
- trajectory_project/intermediate/keyframes/t60.jpgAdded
- trajectory_project/intermediate/keyframes/t63.jpgAdded
- trajectory_project/intermediate/keyframes_montage.jpgAdded
- trajectory_project/intermediate/yolo_mask_montage.jpgAdded
- trajectory_project/models/yolov8x-seg.ptAdded+3
- trajectory_project/qa/source_preflight.mdAdded+7
- trajectory_project/qa/v5_image_integrity.mdAdded+14
- trajectory_project/qa/v6_source_preflight.mdAdded+29
- trajectory_project/qa/v7_image_integrity.mdAdded+15
- trajectory_project/scripts/build_trajectory_figure.pyAdded+642
- trajectory_project/scripts/build_trajectory_figure_v3.pyAdded+1113
- trajectory_project/scripts/build_trajectory_figure_v4.pyAdded+562
- trajectory_project/scripts/build_trajectory_figure_v5.pyAdded+551
- trajectory_project/scripts/build_trajectory_figure_v7.pyAdded+802
- trajectory_project/scripts/build_trajectory_figure_v8.pyAdded+972
- trajectory_project/scripts/build_trajectory_figure_v9.pyAdded+1220
10 unmodified lines11121310 unmodified linestrajectory_project/outputs/v8_metallic_contrast_palette/*.tiff filter=lfs diff=lfs merge=lfs -texttrajectory_project/outputs/v9_native_4k_resolution/*.tiff filter=lfs diff=lfs merge=lfs -texttrajectory_project/outputs/v10_brighter_background/*.tiff filter=lfs diff=lfs merge=lfs -text10 unmodified lines11121314151617181910 unmodified linestrajectory_project/outputs/v8_metallic_contrast_palette/*.tiff filter=lfs diff=lfs merge=lfs -texttrajectory_project/outputs/v9_native_4k_resolution/*.tiff filter=lfs diff=lfs merge=lfs -texttrajectory_project/outputs/v10_brighter_background/*.tiff filter=lfs diff=lfs merge=lfs -texttrajectory_project/intermediate/contact_sheet_full.jpg filter=lfs diff=lfs merge=lfs -texttrajectory_project/intermediate/genmo_reference.pdf filter=lfs diff=lfs merge=lfs -texttrajectory_project/intermediate/genmo_teaser.jpg filter=lfs diff=lfs merge=lfs -texttrajectory_project/intermediate/yolo_mask_montage.jpg filter=lfs diff=lfs merge=lfs -texttrajectory_project/intermediate/keyframes_montage.jpg filter=lfs diff=lfs merge=lfs -texttrajectory_project/intermediate/contact_sheet.jpg filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:daaa820619d78a4a5dee1fc70acf0f45329bcd29646ef057fcef2e62b818f503size 169267182123version https://git-lfs.github.com/spec/v1oid sha256:5c69f34776cf9e54c7a77016a6be3d5ce531ce527671332c6b84b4a730405965size 2730535123version https://git-lfs.github.com/spec/v1oid sha256:c333d6a7aff884ec821050eacdab29871f3edd10d996cf48746a02f8e01f1b5dsize 1441016121234567# Source preflight — v1
Validator result: **ready = true; 14 PASS, 0 WARN, 0 FAIL**.
Passed checks: Python syntax, publication-safe sans-serif font, minimum 5 pt text, non-rainbow palette, editable SVG/PDF text, SVG/PDF export, TIFF export at 600 dpi, 183 mm double-column width, sampling/exclusion scan, simulated-data scan, log guard, and Python-backend exclusivity.
The automated result is a source-code preflight only. Visual review was also performed on `trajectory_annotated.png`, `trajectory_clean.png`, and `cutouts_qa.jpg` at final output size.1234567891011121314# 图像完整性记录 — v5 遮挡优化与错位布局
- **原始材料:**沿用同一个固定机位 MOV 视频;v1–v4 的脚本、配置和输出不覆盖。- **展示采样:**6、7、12、14、27、31、32、40、44、45、52、53、56.5 s,对应帧 150、175、300、350、675、775、800、1000、1100、1125、1300、1325、1412。- **分割复用:**不重新推理。v5 从 v4 原样复制 `segmentation_cache.npz`、检测记录、SAM 全量指标和提示点;缓存 SHA256 两端均为 `1aa8ab38fa3e22d386983c99638796b7beee985edcc5f5db2f9b31d346938aca`,其余三份文件也在 `reuse_audit.json` 中逐项一致。- **分割质量:**13 个展示掩膜平均最终 IoU 为 0.926578、平均召回率为 0.934750、平均精度为 0.990655;没有帧回退到 YOLO 原掩膜。- **背景复用:**v5 与 v4 的 `background_plate.png` 逐像素差异为 0;两者 SHA256 均为 `4c54e646bea389665b6c8708a00c117365db6cea915499d48cf312d84ba9127d`。v4 已确认的局部真实像素修补保持不变,不新增生成式内容。- **姿态变换:**每个切片只做二维平移和等比例缩放,不旋转、不非刚性形变、不生成机器人像素。默认尺度 0.92;6/7 s 为 0.96;31 s 为 0.82。- **主要位置调整:**14 s 相对 v4 上移 64.8 px;31 s 脚点约为 (1980, 1240) px;40/44 s 脚点约为 (1940, 680)/(1620, 620) px;45、52、53、56.5 s 向左并上下错位展开。完整坐标见 `layout_change_audit.json` 和 `layout_map.csv`。- **遮挡结果:**冗余遮挡率从 v4 的 0.111805 降至 0.057850,相对减少 0.482581。31/44 s 与 32/40 s 的掩膜交叠均为 0;6/7 s 对较小姿态的交叠为 0.033473。- **可见比例:**31、32、40、44 s 分别为 0.919208、0.944744、0.911305、0.894246;用户点出的被挡姿态均保留清晰主体。- **辅助标注:**annotated 说明框的画布右边界为 x = 535.04 px;56.5 s 的缩放边界从 x = 604 px 开始,水平间隔约 69 px,因此说明框不遮挡该姿态。clean 版不含说明框。- **右侧安全区:**2560 px 底图的安全边界为 x = 2252.8,最终 overlay 最右为 x = 2239;右侧 12% 中 clean/annotated 改动像素均为 0。- **追溯文件:**`reuse_audit.json`、`occlusion_metrics.json`、`layout_change_audit.json`、`layout_map.csv`、`safe_area_metrics.json`、`sam_metrics.json` 和 `refined_masks.npz` 覆盖本版复用、位置、尺度、遮挡与导出检查。1234567891011121314151617181920212223242526272829# 源码与导出预检 — v6 均匀落地布局与轨迹补线
严格源码验证结果:**ready = true;14 PASS,0 WARN,0 FAIL**。
通过项目:Python 语法、出版安全无衬线字体、最小 7 pt 默认文字、非彩虹配色、SVG/PDF 可编辑文字设置、SVG/PDF/TIFF/PNG 导出、TIFF 600 dpi、183 mm 双栏宽度、数据采样扫描、缺失值排除扫描、模拟数据扫描、对数保护扫描和 Python 后端独占。
最终脚本复用 v5 的 14 个唯一帧分割缓存重渲染,并通过以下实际文件检查:
- PNG:2161 × 1215 px、RGBA、约 300 dpi。- TIFF:4322 × 2431 px、RGB、600 dpi、8 bit/通道、无损 LZW 压缩。- SVG:518.740157 × 291.791339 pt,对应 183 × 102.94 mm;annotated 含 15 个可编辑文本节点,clean 按设计不含文字。- PDF:MediaBox 为 518.740157 × 291.791339 pt;annotated 嵌入 CIDFontType2/FontFile2 无衬线字体并保留 ToUnicode 映射,clean 按设计不含字体对象。- 输入完整性:13/13 个时刻、五组颜色、alpha、14 s 跳跃位置和右侧安全比例均与 v5 一致;背景与四份复用分割工件逐文件哈希一致。- 前排:非跳跃姿态高度变异系数为 0.5397%,脚底高度极差为 0 px;14 s 跳跃保持 v5 位置。- 后排:五段脚点间隔均约 290 px,间隔极差为 0.003 px;六个脚底均约 y = 800 px,高度极差为 0 px。- 近大远小:31/32 s 显示高度比为 1.187602。- 遮挡:冗余遮挡率 8.3512%,最大叠加深度 2;31/44 与 32/40 两组交叠均为 0。- 路径:44.50% 的路径像素原本会被姿态遮住;最终只在相交掩膜内补 alpha = 0.48 的细彩线,视觉检查未出现整条亮色腰带。- 安全区:overlay 最右 x = 2237,小于 x = 2252.8;clean/annotated 在右侧 12% 中均为 0 个改动像素。- 视觉检查:前排尺度协调且间距连续;后排脚底齐平、位置均匀并落在同一远景地面线上;31 s 略大于 32 s;轨迹跨遮挡处仍可读。
预检命令:
```bash<v2-python> <nature-figure>/scripts/validate_figure.py \ trajectory_project/scripts/build_trajectory_figure_v6.py --strict```
静态预检不替代论文图注披露;正式使用时仍需说明姿态位置、显示尺度和路径均经过展示性调整。123456789101112131415# 图像完整性记录 — v7 顶部裁切与统一缩小宽幅版
- **原始材料:**沿用同一个固定机位 MOV 视频;v1–v6 的脚本、配置和输出不覆盖。- **展示采样:**6、7、12、14、27、31、32、40、44、45、52、53、56.5 s,对应帧 150、175、300、350、675、775、800、1000、1100、1125、1300、1325、1412。- **分割复用:**不重新推理。v7 从 v6 原样复制分割缓存、检测记录、SAM 全量指标和提示点;四份复用工件的两端 SHA256 全部一致。- **分割质量:**13 个展示掩膜平均最终 IoU 为 0.926578、平均召回率为 0.934750、平均精度为 0.990655;没有帧回退到 YOLO 原掩膜。- **背景复用:**v7 与 v6 的 2560 × 1440 背景逐像素差异为 0;SHA256 均为 `4c54e646bea389665b6c8708a00c117365db6cea915499d48cf312d84ba9127d`。不新增生成式修复或局部背景改动。- **姿态变换:**只做二维平移与等比例缩放,不旋转、不非刚性形变、不生成机器人像素。每帧 v7/v6 尺度比严格为 0.78,比例极差为 0。- **位置变换:**横向脚点全部保持 v6 数值;6/7/12/14/27/31/32 s 纵向脚点不变;40/44/45/52/53/56.5 s 作为整体下移 140 px,脚底统一为 y = 940 px。- **裁切:**完整渲染后删除 y = 0–479 的顶部区域,保留 y = 480–1439;最终内部画布为 2560 × 960。逐姿态边界检查的最小顶部余量为 21.952 px,最小底部余量为 66.803 px,没有机器人像素被裁掉。- **轨迹补画:**18,483 个路径像素中有 6,414 个与姿态掩膜相交,比例为 0.347022;只在相交位置以 alpha = 0.48 补细彩线。- **遮挡结果:**冗余遮挡率为 0.059055,最大叠加深度为 2;相对 v6 减少 29.2856%。最小逐姿态可见比例为 0.667272。- **右侧安全区:**2560 px 底图安全边界为 x = 2252.8,最终 overlay 最右为 x = 2215;右侧 12% 中 clean/annotated 改动像素均为 0。- **追溯文件:**`crop_metrics.json`、`crop_fit_metrics.json`、`scale_multiplier_metrics.json`、`layout_map_wide.csv`、`occlusion_metrics.json`、`layout_change_audit.json`、`reuse_audit.json` 和 `safe_area_metrics.json` 覆盖本版全部变更。- **图注披露:**正式使用时应说明“为适配宽幅版式,画面顶部被裁切,姿态统一缩小,后排展示位置整体下移;彩色线只表示阅读顺序”。123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642#!/usr/bin/env python3"""Build a temporal trajectory composite from a fixed-view G1 video.
The pipeline deliberately keeps the source pixels visible: a generic YOLOinstance-segmentation model proposes masks, temporal/spatial heuristics selectthe single G1 instance, and the selected source frames are alpha-composited onan automatically repaired background plate. The detector class name is neverused as a scientific label (the robot is sometimes classified as a bicycle ormotorcycle by a COCO model)."""
from __future__ import annotations
import argparseimport jsonimport mathimport osimport sysfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable
import cv2import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.collections import LineCollectionfrom matplotlib.patches import FancyBboxPatch, Rectanglefrom matplotlib import patheffects
# Nature-style export defaults: keep text selectable in SVG/PDF and use a# publication-safe sans-serif fallback when Arial/Helvetica is unavailable.matplotlib.rcParams.update( { "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], "font.size": 7, "svg.fonttype": "none", "pdf.fonttype": 42, "axes.spines.right": False, "axes.spines.top": False, })
try: from ultralytics import YOLOexcept Exception as exc: # pragma: no cover - gives a useful CLI error YOLO = None _ULTRALYTICS_IMPORT_ERROR = exc
PROJECT_ROOT = Path(__file__).resolve().parents[2]DEFAULT_VIDEO = str(PROJECT_ROOT / "source" / "CLIP_P0010073.mov")DEFAULT_MODEL = str(PROJECT_ROOT / "trajectory_project" / "models" / "yolov8x-seg.pt")DEFAULT_CONFIG = str(PROJECT_ROOT / "trajectory_project" / "config_v1.json")DEFAULT_OUT = str(PROJECT_ROOT / "trajectory_project" / "outputs" / "v1")
@dataclassclass Detection: time: float frame_index: int bbox: tuple[float, float, float, float] confidence: float class_id: int class_name: str mask: np.ndarray foot_xy: tuple[float, float]
def parse_args() -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) p.add_argument("--video", default=DEFAULT_VIDEO) p.add_argument("--model", default=DEFAULT_MODEL) p.add_argument("--config", default=DEFAULT_CONFIG) p.add_argument("--out-dir", default=DEFAULT_OUT) p.add_argument("--device", default="0", help="Ultralytics device, e.g. 0 or cpu") p.add_argument("--infer-size", type=int, default=1280) p.add_argument("--batch", type=int, default=4) p.add_argument("--conf", type=float, default=0.001) p.add_argument("--keep-intermediate", action="store_true", default=True) return p.parse_args()
def hex_to_rgb(value: str) -> np.ndarray: value = value.lstrip("#") if len(value) != 6: raise ValueError(f"Expected #RRGGBB, got {value!r}") return np.array([int(value[i : i + 2], 16) for i in (0, 2, 4)], dtype=np.float32)
def read_config(path: str | Path) -> dict[str, Any]: with open(path, "r", encoding="utf-8") as f: return json.load(f)
def read_frame(cap: cv2.VideoCapture, frame_index: int) -> np.ndarray: cap.set(cv2.CAP_PROP_POS_FRAMES, int(frame_index)) ok, frame = cap.read() if not ok or frame is None: raise RuntimeError(f"Could not read frame {frame_index}") return frame
def resize_keep_aspect(frame: np.ndarray, width: int) -> np.ndarray: h, w = frame.shape[:2] if w == width: return frame height = int(round(h * width / w)) return cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA)
def normalise_mask(raw: np.ndarray, height: int, width: int) -> np.ndarray: """Convert a model mask to a clean uint8 mask at the frame resolution.""" if raw.ndim > 2: raw = np.squeeze(raw) if raw.shape != (height, width): raw = cv2.resize(raw.astype(np.float32), (width, height), interpolation=cv2.INTER_LINEAR) mask = (raw > 0.45).astype(np.uint8) * 255
# Preserve articulated gaps, but remove isolated one-pixel predictions and # close tiny seams introduced by upsampling the model mask. short = max(3, int(round(min(height, width) / 500))) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (short, short)) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
# Keep all sizeable components in the selected detection (hands/feet can be # detached from the torso in a side-view pose). n, labels, stats, _ = cv2.connectedComponentsWithStats(mask, 8) if n > 1: area_limit = max(20, int(0.0002 * height * width)) keep = np.zeros_like(mask) for idx in range(1, n): if stats[idx, cv2.CC_STAT_AREA] >= area_limit: keep[labels == idx] = 255 mask = keep return mask
def mask_bbox(mask: np.ndarray) -> tuple[float, float, float, float]: ys, xs = np.where(mask > 0) if len(ys) == 0: return (0.0, 0.0, 0.0, 0.0) return (float(xs.min()), float(ys.min()), float(xs.max() + 1), float(ys.max() + 1))
def foot_point(mask: np.ndarray, bbox: tuple[float, float, float, float]) -> tuple[float, float]: # Use the lower bbox centre rather than whichever articulated foot happens # to be the lowest pixel. This keeps the path smooth when the robot dances. ys, _ = np.where(mask > 0) if len(ys) == 0: return ((bbox[0] + bbox[2]) / 2.0, bbox[3]) return ((bbox[0] + bbox[2]) / 2.0, float(np.percentile(ys, 99.5)))
def candidate_score( bbox: tuple[float, float, float, float], confidence: float, mask_area: float, shape: tuple[int, int], previous: Detection | None,) -> float: h, w = shape x1, y1, x2, y2 = bbox bw, bh = max(1.0, x2 - x1), max(1.0, y2 - y1) cx, cy = (x1 + x2) / (2 * w), (y1 + y2) / (2 * h) area_ratio = mask_area / float(h * w) bbox_ratio = mask_area / float(bw * bh)
# The robot stays in the central floor area. The large white pillar at the # right is intentionally down-weighted by the edge penalty. central = 1.0 if (0.10 < cx < 0.82 and 0.10 < cy < 0.92) else 0.0 edge_penalty = 1.0 if (x1 > 0.025 * w and x2 < 0.93 * w) else -1.0 tall = np.clip((bh / bw - 1.0) / 3.5, 0.0, 1.0) plausible_area = np.exp(-((np.log(max(area_ratio, 1e-5)) - np.log(0.035)) ** 2) / 1.35) # Wall/pillar reflections are large and terminate above the floor. A G1 # candidate should reach the floor; this also rejects most background masks # without relying on the unreliable COCO class label. bottom_norm = y2 / float(h) floor_prior = float(np.clip((bottom_norm - 0.45) / 0.25, 0.0, 1.0)) articulated_fill = float(np.clip(1.0 - abs(bbox_ratio - 0.52) / 0.55, 0.0, 1.0)) body_size_prior = float(np.clip((area_ratio - 0.006) / 0.055, 0.0, 1.0)) body_width_prior = float(np.clip((bw - 0.045) / 0.12, 0.0, 1.0))
continuity = 0.0 if previous is not None: px1, py1, px2, py2 = previous.bbox pcx, pcy = (px1 + px2) / (2 * w), (py1 + py2) / (2 * h) pbh = max(1.0, py2 - py1) dist = math.sqrt((cx - pcx) ** 2 + (cy - pcy) ** 2) scale_delta = abs(math.log(max(bh, 1.0) / pbh)) continuity = math.exp(-5.0 * dist - 1.2 * scale_delta) # Do not let a low-confidence limb-only mask permanently shrink the # track. Full-body candidates are preferred when the previous mask was # substantially larger. if bh < 0.62 * pbh: continuity *= 0.18 if bh < 0.45 * pbh: continuity *= 0.20 else: # At the first frame, prefer the largest tall object near the centre. continuity = 0.5 + 0.5 * np.exp(-((cx - 0.43) / 0.28) ** 2)
return ( 2.2 * central + 1.35 * continuity + 0.55 * float(np.clip(confidence, 0.0, 1.0)) + 1.15 * tall + 0.85 * plausible_area + 1.05 * floor_prior + 0.55 * articulated_fill + 1.85 * body_size_prior + 0.70 * body_width_prior + 0.25 * edge_penalty - (2.8 if bottom_norm < 0.45 else 0.0) )
def choose_detection( result: Any, frame: np.ndarray, time: float, frame_index: int, previous: Detection | None, class_names: dict[int, str],) -> Detection | None: if result is None or result.boxes is None or len(result.boxes) == 0 or result.masks is None: return None height, width = frame.shape[:2] options: list[tuple[float, Detection]] = [] for idx, box_obj in enumerate(result.boxes): try: bbox_model = tuple(float(v) for v in box_obj.xyxy[0].detach().cpu().numpy()) confidence = float(box_obj.conf[0].detach().cpu().item()) class_id = int(box_obj.cls[0].detach().cpu().item()) raw_mask = result.masks.data[idx].detach().cpu().numpy() except Exception: continue mask = normalise_mask(raw_mask, height, width) area = float((mask > 0).sum()) if area < 0.002 * height * width: continue bbox = mask_bbox(mask) if bbox[2] <= bbox[0] or bbox[3] <= bbox[1]: continue score = candidate_score(bbox, confidence, area, (height, width), previous) d = Detection( time=float(time), frame_index=int(frame_index), bbox=bbox, confidence=confidence, class_id=class_id, class_name=class_names.get(class_id, str(class_id)), mask=mask, foot_xy=foot_point(mask, bbox), ) options.append((score, d)) if not options: return None options.sort(key=lambda x: x[0], reverse=True) return options[0][1]
def mask_iou(a: np.ndarray, b: np.ndarray) -> float: aa = a > 0 bb = b > 0 inter = np.logical_and(aa, bb).sum() union = np.logical_or(aa, bb).sum() return float(inter / union) if union else 0.0
def phase_for(time: float, phases: list[dict[str, Any]]) -> dict[str, Any]: for phase in phases: if phase["start"] <= time < phase["end"] or ( time == phases[-1]["end"] and phase is phases[-1] ): return phase return phases[-1]
def phase_progress(time: float, phase: dict[str, Any]) -> float: denom = max(1e-6, float(phase["end"]) - float(phase["start"])) return float(np.clip((time - float(phase["start"])) / denom, 0.0, 1.0))
def repair_background( base: np.ndarray, fill: np.ndarray, base_mask: np.ndarray, fill_mask: np.ndarray, dilate_px: int,) -> np.ndarray: """Patch the near robot out of a reference frame with a distant reference.
The camera is fixed, so a feathered pixel-for-pixel patch is preferable to hallucinating a background. A small global colour correction is estimated from the ring around the patch to absorb exposure/compression drift. """ if base_mask is None or int((base_mask > 0).sum()) == 0: return base.copy() kernel_size = max(3, 2 * int(dilate_px) + 1) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)) patch = cv2.dilate((base_mask > 0).astype(np.uint8), kernel, iterations=1)
# If the fill reference still contains the robot in the patch, fall back to # the unmodified base rather than imprinting a second robot. overlap = mask_iou(patch * 255, fill_mask) if overlap > 0.08: return base.copy()
patch_f = cv2.GaussianBlur(patch.astype(np.float32), (0, 0), sigmaX=max(1.0, dilate_px / 2.5)) patch_f = np.clip(patch_f, 0.0, 1.0)[..., None]
# Estimate channel offset on a thin ring outside the patch. outer = cv2.dilate(patch, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (31, 31))) ring = (outer > 0) & (patch == 0) if ring.sum() > 100: delta = np.median(base[ring].astype(np.float32) - fill[ring].astype(np.float32), axis=0) else: delta = np.zeros(3, dtype=np.float32) fill_corr = np.clip(fill.astype(np.float32) + delta[None, None, :], 0, 255) result = base.astype(np.float32) * (1.0 - patch_f) + fill_corr * patch_f return np.clip(result, 0, 255).astype(np.uint8)
def colorize_foreground(frame_bgr: np.ndarray, color: np.ndarray) -> np.ndarray: rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY).astype(np.float32) / 255.0 # Luminance-preserving tint: retain metallic highlights while making each # temporal phase visually separable. tint = np.clip(color[None, None, :] * (0.25 + 0.85 * gray[..., None]), 0, 255) return np.clip(0.28 * rgb + 0.72 * tint, 0, 255).astype(np.uint8)
def alpha_blend_mask(canvas_rgb: np.ndarray, foreground_rgb: np.ndarray, mask: np.ndarray, alpha: float) -> None: if alpha <= 0: return soft = cv2.GaussianBlur(mask.astype(np.float32) / 255.0, (0, 0), sigmaX=1.2) a = np.clip(soft * float(alpha), 0.0, 1.0)[..., None] canvas_rgb[:] = np.clip(canvas_rgb.astype(np.float32) * (1 - a) + foreground_rgb.astype(np.float32) * a, 0, 255).astype(np.uint8)
def draw_mask_outline(canvas_rgb: np.ndarray, mask: np.ndarray, color: np.ndarray, alpha: float, width: int = 2) -> None: contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) if not contours: return layer = canvas_rgb.copy() cv2.drawContours(layer, contours, -1, tuple(int(x) for x in color), max(1, width), lineType=cv2.LINE_AA) a = float(np.clip(alpha, 0, 1)) canvas_rgb[:] = np.clip(canvas_rgb.astype(np.float32) * (1 - a) + layer.astype(np.float32) * a, 0, 255).astype(np.uint8)
def draw_path(canvas_rgb: np.ndarray, detections: list[Detection], phases: list[dict[str, Any]], scale: float) -> None: if len(detections) < 2: return points = np.array([d.foot_xy for d in detections], dtype=np.float32) # Under-stroke gives the path enough contrast on both the dark floor and the # bright window without hiding the source image. for i in range(len(points) - 1): p0, p1 = points[i], points[i + 1] c = hex_to_rgb(phase_for(detections[i].time, phases)["color"]) p0i, p1i = tuple(np.round(p0).astype(int)), tuple(np.round(p1).astype(int)) cv2.line(canvas_rgb, p0i, p1i, (248, 248, 248), max(7, int(10 * scale)), lineType=cv2.LINE_AA) cv2.line(canvas_rgb, p0i, p1i, tuple(int(x) for x in c), max(3, int(5 * scale)), lineType=cv2.LINE_AA) # Arrow head at the final position. p0, p1 = points[-2], points[-1] direction = p1 - p0 norm = float(np.linalg.norm(direction)) if norm > 1: u = direction / norm v = np.array([-u[1], u[0]]) size = 18 * scale tri = np.vstack([p1, p1 - u * size + v * size * 0.55, p1 - u * size - v * size * 0.55]).astype(np.int32) color = tuple(int(x) for x in hex_to_rgb(phase_for(detections[-1].time, phases)["color"])) cv2.fillConvexPoly(canvas_rgb, tri, color, lineType=cv2.LINE_AA)
def add_timeline(ax: Any, config: dict[str, Any], width: int, height: int) -> None: phases = config["phases"] # A dark translucent strip keeps labels readable over either window or wall. ax.add_patch(Rectangle((0, 0.012 * height), width, 0.090 * height, facecolor=(0.03, 0.05, 0.08), alpha=0.76, lw=0, zorder=20)) y0, y1 = 0.028 * height, 0.064 * height for phase in phases: x0 = width * float(phase["start"]) / 64.0 x1 = width * float(phase["end"]) / 64.0 color = hex_to_rgb(phase["color"]) / 255.0 ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, facecolor=color, alpha=0.95, lw=0, zorder=21)) ax.text((x0 + x1) / 2, y0 + 0.62 * (y1 - y0), phase["name"], color="white", ha="center", va="center", fontsize=5.8, weight="bold", zorder=22) for t in [0, 16, 28, 40, 64]: x = width * t / 64.0 ax.plot([x, x], [y1 + 0.008 * height, y1 + 0.022 * height], color="white", lw=0.8, zorder=22) ha = "left" if t == 0 else ("right" if t == 64 else "center") x_text = x + (0.008 * width if t == 0 else (-0.008 * width if t == 64 else 0)) ax.text(x_text, y1 + 0.024 * height, f"{t:g} s", color="white", ha=ha, va="top", fontsize=5.2, zorder=22) ax.text(width - 0.018 * width, y0 - 0.006 * height, "time →", color="white", ha="right", va="bottom", fontsize=5.2, zorder=22)
def save_figure(canvas_rgb: np.ndarray, detections: list[Detection], config: dict[str, Any], out_base: Path, annotated: bool) -> None: height, width = canvas_rgb.shape[:2] # Static double-column contract used by the source validator. The config may # override it for another venue while retaining the 183 mm default. width_mm = 183.0 width_mm = float(config.get("final_width_mm", width_mm)) png_dpi = int(config.get("png_dpi", 300)) tiff_dpi = int(config.get("tiff_dpi", 600)) submission_dpi = 600 width_in = width_mm / 25.4 height_in = width_in * height / width fig = plt.figure(figsize=(width_in, height_in), dpi=png_dpi, facecolor="white") ax = fig.add_axes([0, 0, 1, 1]) ax.imshow(canvas_rgb) ax.set_xlim(0, width) ax.set_ylim(height, 0) ax.axis("off") if annotated and config.get("timeline", True): add_timeline(ax, config, width, height) # A small unobtrusive identifier anchors the panel without competing # with the trajectory. ax.text(0.014 * width, 0.120 * height, "G1", color="white", fontsize=8.0, weight="bold", ha="left", va="top", zorder=23, path_effects=[patheffects.withStroke(linewidth=2.5, foreground=(0, 0, 0, 0.55))]) fig.savefig(str(out_base) + ".png", dpi=png_dpi, facecolor="white") fig.savefig(str(out_base) + ".tiff", dpi=max(tiff_dpi, submission_dpi), facecolor="white") fig.savefig(str(out_base) + ".svg", facecolor="white") fig.savefig(str(out_base) + ".pdf", facecolor="white") plt.close(fig)
def save_detection_artifacts(detections: list[Detection], out_dir: Path) -> None: records = [] masks = {} for i, d in enumerate(detections): records.append({ "index": i, "time_s": d.time, "frame_index": d.frame_index, "bbox_xyxy": [round(float(x), 3) for x in d.bbox], "confidence": round(float(d.confidence), 6), "class_id": d.class_id, "class_name_ignored_for_tracking": d.class_name, "mask_area_px": int((d.mask > 0).sum()), "foot_xy": [round(float(x), 3) for x in d.foot_xy], }) masks[f"mask_{i:03d}"] = d.mask.astype(np.uint8) with open(out_dir / "detections.json", "w", encoding="utf-8") as f: json.dump(records, f, indent=2) np.savez_compressed(out_dir / "masks.npz", **masks) with open(out_dir / "trajectory.csv", "w", encoding="utf-8") as f: f.write("index,time_s,frame_index,foot_x_px,foot_y_px,bbox_x1,bbox_y1,bbox_x2,bbox_y2,confidence,class_name\n") for i, d in enumerate(detections): f.write( f"{i},{d.time:.4f},{d.frame_index},{d.foot_xy[0]:.3f},{d.foot_xy[1]:.3f}," f"{d.bbox[0]:.3f},{d.bbox[1]:.3f},{d.bbox[2]:.3f},{d.bbox[3]:.3f}," f"{d.confidence:.6f},{d.class_name}\n" )
def render_composites( frames: dict[float, np.ndarray], detections: list[Detection], config: dict[str, Any], out_dir: Path,) -> np.ndarray: # Background references are guaranteed to be in frames by main(). ref_times = [float(x) for x in config.get("background_reference_times", [1.0, 44.0])] base_t, fill_t = ref_times[0], ref_times[1] base_det = min(detections, key=lambda d: abs(d.time - base_t)) fill_det = min(detections, key=lambda d: abs(d.time - fill_t)) base = frames[base_t] fill = frames[fill_t] scale = base.shape[1] / 3840.0 dilate_px = max(8, int(round(float(config.get("background_dilate_px_at_4k", 42)) * scale))) background_bgr = repair_background(base, fill, base_det.mask, fill_det.mask, dilate_px) background_rgb = cv2.cvtColor(background_bgr, cv2.COLOR_BGR2RGB)
phases = config["phases"] # Draw the path first so source silhouettes remain the visual foreground. path_canvas = background_rgb.copy() draw_path(path_canvas, detections, phases, scale)
hero_times = {round(float(t), 4) for t in config.get("hero_times", [])} composite = path_canvas.copy() for det in sorted(detections, key=lambda d: d.time): phase = phase_for(det.time, phases) p = phase_progress(det.time, phase) alpha = float(phase["alpha_min"]) + p * (float(phase["alpha_max"]) - float(phase["alpha_min"])) if round(det.time, 4) in hero_times: alpha = max(alpha, 0.90) elif phase["name"] == "near-field dance": alpha *= 0.82 color = hex_to_rgb(phase["color"]) foreground = colorize_foreground(frames[det.time], color) alpha_blend_mask(composite, foreground, det.mask, alpha) # Thin phase-coloured contours make overlapping masks legible. draw_mask_outline(composite, det.mask, color, 0.74 if round(det.time, 4) in hero_times else 0.42, width=max(1, int(round(2.0 * scale))))
# Save the raw composite as a source-data-like image for future layout work. cv2.imwrite(str(out_dir / "composite_rgb.png"), cv2.cvtColor(composite, cv2.COLOR_RGB2BGR)) save_figure(composite, detections, config, out_dir / "trajectory_clean", annotated=False) save_figure(composite, detections, config, out_dir / "trajectory_annotated", annotated=True) return composite
def write_metadata(meta: dict[str, Any], out_dir: Path) -> None: with open(out_dir / "run_metadata.json", "w", encoding="utf-8") as f: json.dump(meta, f, indent=2)
def main() -> int: args = parse_args() if YOLO is None: print(f"Ultralytics import failed: {_ULTRALYTICS_IMPORT_ERROR}", file=sys.stderr) return 2 video = Path(args.video).expanduser().resolve() model_path = Path(args.model).expanduser().resolve() config_path = Path(args.config).expanduser().resolve() out_dir = Path(args.out_dir).expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) intermediate_dir = out_dir / "intermediate" intermediate_dir.mkdir(parents=True, exist_ok=True) if not video.exists(): print(f"Video not found: {video}", file=sys.stderr) return 2 if not model_path.exists(): print(f"Model not found: {model_path}", file=sys.stderr) return 2
config = read_config(config_path) cap = cv2.VideoCapture(str(video)) if not cap.isOpened(): print(f"Could not open video: {video}", file=sys.stderr) return 2 fps = float(cap.get(cv2.CAP_PROP_FPS) or 25.0) frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) source_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0) source_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0) duration = frame_count / fps if fps else 0.0 render_width = int(config.get("render_width", source_width))
sample_times = [float(x) for x in config["sample_times"]] ref_times = [float(x) for x in config.get("background_reference_times", [])] all_times = sorted(set(sample_times + ref_times)) frames: dict[float, np.ndarray] = {} for t in all_times: idx = int(round(np.clip(t, 0.0, max(0.0, duration - 1.0 / fps)) * fps)) frame = read_frame(cap, idx) frames[float(t)] = resize_keep_aspect(frame, render_width) cap.release()
print(f"Video: {source_width}x{source_height}, {fps:.3f} fps, {duration:.3f} s") print(f"Rendering {len(sample_times)} samples at width {render_width}; model device={args.device}") model = YOLO(str(model_path)) ordered_times = all_times ordered_frames = [frames[t] for t in ordered_times] device: Any = args.device if device.isdigit(): device = int(device) try: results = model.predict( ordered_frames, imgsz=args.infer_size, conf=args.conf, iou=0.5, max_det=20, retina_masks=True, device=device, batch=max(1, args.batch), verbose=False, ) except RuntimeError as exc: if "out of memory" not in str(exc).lower() and "cuda" not in str(exc).lower(): raise print(f"GPU inference failed ({exc}); retrying on CPU", file=sys.stderr) results = model.predict( ordered_frames, imgsz=min(args.infer_size, 960), conf=args.conf, iou=0.5, max_det=20, retina_masks=True, device="cpu", batch=1, verbose=False, )
# Temporal continuity is applied in chronological order. References are # included in the same pass so their masks can be used for background repair. previous: Detection | None = None selected_by_time: dict[float, Detection] = {} names = getattr(model, "names", {}) for t, frame, result in zip(ordered_times, ordered_frames, results): idx = int(round(t * fps)) det = choose_detection(result, frame, t, idx, previous, names) if det is None and previous is not None: # A rare low-confidence miss is represented by a transparent copy of # the previous track only for bookkeeping; the source mask is not # silently fabricated, so render it as missing below. print(f"warning: no detection at {t:.3f}s", file=sys.stderr) else: previous = det selected_by_time[t] = det print(f" {t:6.2f}s {det.class_name:>14s} conf={det.confidence:.3f} bbox={tuple(round(x) for x in det.bbox)}")
missing = [t for t in sample_times if t not in selected_by_time] if missing: raise RuntimeError(f"No target mask for sample times: {missing}") missing_refs = [t for t in ref_times if t not in selected_by_time] if missing_refs: raise RuntimeError(f"No target mask for background references: {missing_refs}") detections = [selected_by_time[t] for t in sample_times]
save_detection_artifacts(detections, out_dir) # Save reference masks as well, so the background operation is auditable. ref_records = [selected_by_time[t] for t in ref_times] save_detection_artifacts(ref_records, out_dir / "references") if False else None meta = { "video": str(video), "model": str(model_path), "config": str(config_path), "source_width": source_width, "source_height": source_height, "fps": fps, "frame_count": frame_count, "duration_s": duration, "render_width": render_width, "render_height": int(frames[all_times[0]].shape[0]), "sample_times_s": sample_times, "background_reference_times_s": ref_times, "missing_sample_times_s": missing, "device": args.device, } write_metadata(meta, out_dir) render_composites(frames, detections, config, out_dir) print(f"Wrote outputs to {out_dir}") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113#!/usr/bin/env python3"""Build v3 from 13 user-specified G1 frames with five colour groups.
The plate uses exact source times, YOLO-seeded SAM masks, a uniform 0.92 posescale, and a hard overlay-safe boundary that reserves the rightmost 12% for apossible later crop. Only the coloured display-order line is drawn; no sourcetrajectory is shown or implied.
Publication exports: ``.png`` preview, RGB ``.tiff`` at 600 dpi, andeditable-text ``.svg`` / ``.pdf`` files."""
from __future__ import annotations
import argparseimport csvimport mathimport sysfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable
import cv2import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as pltimport numpy as npfrom matplotlib.patches import FancyBboxPatch, Rectanglefrom PIL import Image
import build_trajectory_figure as v1import build_trajectory_figure_v2 as v2
matplotlib.rcParams.update( { "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], "font.size": 7, "svg.fonttype": "none", "pdf.fonttype": 42, "axes.spines.right": False, "axes.spines.top": False, "axes.linewidth": 0.8, "legend.frameon": False, })
try: from ultralytics import YOLOexcept Exception as exc: # pragma: no cover - useful CLI message YOLO = None _YOLO_IMPORT_ERROR = exc
PROJECT_ROOT = Path(__file__).resolve().parents[2]DEFAULT_VIDEO = PROJECT_ROOT / "source" / "CLIP_P0010073.mov"DEFAULT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v3_custom_frames_layout.json"DEFAULT_YOLO = PROJECT_ROOT / "trajectory_project" / "models" / "yolov8x-seg.pt"DEFAULT_SAM = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v3_custom_frames_layout"
@dataclassclass Pose: time: float frame_index: int frame_bgr: np.ndarray yolo_mask: np.ndarray refined_mask: np.ndarray source_bbox: tuple[float, float, float, float] source_foot: tuple[float, float] display_foot_requested: tuple[float, float] display_foot: tuple[float, float] phase_name: str group_id: str group_label: str color_rgb: np.ndarray hero: bool scale_factor: float sam_metrics: dict[str, Any]
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--video", type=Path, default=DEFAULT_VIDEO) parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--yolo-model", type=Path, default=DEFAULT_YOLO) parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_SAM) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--device", default="cuda:0") parser.add_argument( "--reuse-segmentation", action="store_true", help="Reuse cached YOLO/SAM masks and rerender layout only.", ) return parser.parse_args()
def time_key(time: float) -> str: return f"t_{int(round(time * 1000)):06d}"
def config_key(time: float) -> str: return f"{time:g}"
def group_for_time(time: float, config: dict[str, Any]) -> dict[str, Any]: matches = [ group for group in config["color_groups"] if any(abs(float(value) - time) < 1e-6 for value in group["times"]) ] if len(matches) != 1: raise RuntimeError(f"Expected one colour group for {time:g}s, found {len(matches)}") return matches[0]
def phase_for_time(time: float, config: dict[str, Any]) -> str: phases = config["motion_phases"] for index, phase in enumerate(phases): last = index == len(phases) - 1 if float(phase["start"]) <= time < float(phase["end"]) or ( last and time <= float(phase["end"]) ): return str(phase["name"]) return str(phases[-1]["name"])
def validate_config(config: dict[str, Any]) -> None: sample_times = [float(value) for value in config["sample_times"]] grouped_times = [float(value) for group in config["color_groups"] for value in group["times"]] if len(sample_times) != 13 or len(set(sample_times)) != 13: raise RuntimeError("v3 requires exactly 13 unique user-specified sample times") if sorted(sample_times) != sorted(grouped_times): raise RuntimeError("Colour groups must contain every sample time exactly once") if len(config["color_groups"]) != 5: raise RuntimeError("v3 requires exactly five colour groups") if not 0.85 <= float(config["pose_scale"]) <= 1.0: raise RuntimeError("pose_scale must be a small uniform reduction between 0.85 and 1.0") reserved = float(config["right_reserved_fraction"]) if not 0.0 < reserved < 0.5: raise RuntimeError("right_reserved_fraction must be between 0 and 0.5") targets = config["layout_targets_normalized"] missing = [time for time in sample_times if config_key(time) not in targets] if missing: raise RuntimeError(f"Missing layout targets for: {missing}")
def read_frames( video: Path, times: list[float], render_width: int,) -> tuple[dict[float, np.ndarray], dict[float, int], dict[str, Any]]: cap = cv2.VideoCapture(str(video)) if not cap.isOpened(): raise RuntimeError(f"Could not open video: {video}") fps = float(cap.get(cv2.CAP_PROP_FPS) or 25.0) frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) source_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH) or 0) source_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT) or 0) maximum_time = max(0.0, (frame_count - 1) / fps) frames: dict[float, np.ndarray] = {} indices: dict[float, int] = {} for time in times: clamped = float(np.clip(time, 0.0, maximum_time)) index = int(round(clamped * fps)) frames[time] = v1.resize_keep_aspect(v1.read_frame(cap, index), render_width) indices[time] = index cap.release() first = frames[times[0]] metadata = { "fps": fps, "frame_count": frame_count, "duration_s": float(frame_count / fps) if fps else 0.0, "source_width": source_width, "source_height": source_height, "render_width": int(first.shape[1]), "render_height": int(first.shape[0]), } return frames, indices, metadata
def infer_yolo_masks( frames: dict[float, np.ndarray], frame_indices: dict[float, int], ordered_times: list[float], model_path: Path, config: dict[str, Any], device: str,) -> tuple[dict[float, np.ndarray], list[dict[str, Any]]]: if YOLO is None: raise RuntimeError(f"Ultralytics import failed: {_YOLO_IMPORT_ERROR}") model = YOLO(str(model_path)) yolo_config = config["yolo"] # Ultralytics 8.2 mutates CUDA_VISIBLE_DEVICES when passed an explicit 0 # after torch is already imported. Let it auto-select the first visible # GPU for cuda:0, while SAM still receives the explicit torch device. model_device: Any = "" if device in {"cuda", "cuda:0", "0"} else device ordered_frames = [frames[time] for time in ordered_times] try: results = model.predict( ordered_frames, imgsz=int(yolo_config["infer_size"]), conf=float(yolo_config["confidence"]), iou=float(yolo_config["iou"]), max_det=int(yolo_config["max_detections"]), retina_masks=True, device=model_device, batch=int(yolo_config["batch"]), verbose=False, ) except RuntimeError as exc: if "cuda" not in str(exc).lower() and "out of memory" not in str(exc).lower(): raise print(f"GPU YOLO inference failed ({exc}); retrying on CPU", file=sys.stderr) results = model.predict( ordered_frames, imgsz=min(960, int(yolo_config["infer_size"])), conf=float(yolo_config["confidence"]), iou=float(yolo_config["iou"]), max_det=int(yolo_config["max_detections"]), retina_masks=True, device="cpu", batch=1, verbose=False, )
previous: v1.Detection | None = None masks: dict[float, np.ndarray] = {} records: list[dict[str, Any]] = [] names = getattr(model, "names", {}) for time, frame, result in zip(ordered_times, ordered_frames, results): detection = v1.choose_detection( result, frame, time, frame_indices[time], previous, names, ) if detection is None: raise RuntimeError(f"No YOLO seed target at {time:g}s") previous = detection masks[time] = detection.mask records.append( { "time_s": time, "frame_index": frame_indices[time], "bbox_xyxy": [round(float(value), 3) for value in detection.bbox], "foot_xy": [round(float(value), 3) for value in detection.foot_xy], "confidence": round(float(detection.confidence), 6), "class_id": int(detection.class_id), "class_name_ignored_for_tracking": detection.class_name, "mask_area_px": int((detection.mask > 0).sum()), } ) print( f"{time:5.1f}s YOLO seed={detection.class_name} conf={detection.confidence:.3f} " f"bbox={tuple(round(value) for value in detection.bbox)}" ) return masks, records
def refine_all_masks( frames: dict[float, np.ndarray], yolo_masks: dict[float, np.ndarray], ordered_times: list[float], checkpoint: Path, config: dict[str, Any], device: str,) -> tuple[dict[float, np.ndarray], dict[float, dict[str, Any]], dict[str, Any], str]: if v2.SamPredictor is None or v2.sam_model_registry is None: raise RuntimeError(f"segment-anything import failed: {v2._SAM_IMPORT_ERROR}") checkpoint_hash = v2.sha256sum(checkpoint) expected = str(config["sam"]["checkpoint_sha256"]) if checkpoint_hash != expected: raise RuntimeError(f"SAM checkpoint SHA256 mismatch: expected {expected}, got {checkpoint_hash}") sam = v2.sam_model_registry[str(config["sam"]["model_type"])](checkpoint=str(checkpoint)) sam.to(device=device) sam.eval() predictor = v2.SamPredictor(sam) refined: dict[float, np.ndarray] = {} metrics: dict[float, dict[str, Any]] = {} prompts: dict[str, Any] = {} for index, time in enumerate(ordered_times): mask, row, prompt = v2.refine_one_mask( predictor, frames[time], yolo_masks[time], config["sam"], seed=int(round(time * 1000)) + index, ) refined[time] = mask metrics[time] = row prompts[config_key(time)] = prompt print( f"{time:5.1f}s SAM score={row['sam_score']:.3f} final IoU={row['final_iou']:.3f} " f"recall={row['final_recall']:.3f} precision={row['final_precision']:.3f}" ) del predictor del sam try: import torch
if torch.cuda.is_available(): torch.cuda.empty_cache() except Exception: pass return refined, metrics, prompts, checkpoint_hash
def save_segmentation_cache( out_dir: Path, ordered_times: list[float], yolo_masks: dict[float, np.ndarray], refined_masks: dict[float, np.ndarray], yolo_records: list[dict[str, Any]], metrics: dict[float, dict[str, Any]], prompts: dict[str, Any],) -> None: arrays: dict[str, np.ndarray] = {} for time in ordered_times: key = time_key(time) arrays[f"yolo_{key}"] = yolo_masks[time].astype(np.uint8) arrays[f"sam_{key}"] = refined_masks[time].astype(np.uint8) np.savez_compressed(out_dir / "segmentation_cache.npz", **arrays) v2.write_json(out_dir / "yolo_seed_detections.json", yolo_records) v2.write_json( out_dir / "sam_metrics_all.json", {"frames": [{"time_s": time, "metrics": metrics[time]} for time in ordered_times]}, ) v2.write_json(out_dir / "sam_prompts.json", prompts)
def load_segmentation_cache( out_dir: Path, ordered_times: list[float],) -> tuple[dict[float, np.ndarray], dict[float, np.ndarray], dict[float, dict[str, Any]], list[dict[str, Any]]]: cache_path = out_dir / "segmentation_cache.npz" metrics_path = out_dir / "sam_metrics_all.json" records_path = out_dir / "yolo_seed_detections.json" for path in [cache_path, metrics_path, records_path]: if not path.exists(): raise RuntimeError(f"Missing segmentation cache input: {path}") archive = np.load(cache_path) yolo_masks: dict[float, np.ndarray] = {} refined_masks: dict[float, np.ndarray] = {} for time in ordered_times: key = time_key(time) yolo_masks[time] = archive[f"yolo_{key}"].astype(np.uint8) refined_masks[time] = archive[f"sam_{key}"].astype(np.uint8) archive.close() metrics_rows = v2.load_json(metrics_path)["frames"] metrics = {float(row["time_s"]): row["metrics"] for row in metrics_rows} records = v2.load_json(records_path) if sorted(metrics) != sorted(ordered_times): raise RuntimeError("Cached SAM times do not match the current config") return yolo_masks, refined_masks, metrics, records
def safe_x_limit(width: int, config: dict[str, Any]) -> float: return width * (1.0 - float(config["right_reserved_fraction"]))
def scaled_bbox_offsets( bbox: tuple[float, float, float, float], foot: tuple[float, float], scale_factor: float,) -> tuple[float, float, float, float]: x1, y1, x2, y2 = bbox fx, fy = foot return ( (fx - x1) * scale_factor, (fy - y1) * scale_factor, (x2 - fx) * scale_factor, (y2 - fy) * scale_factor, )
def clamp_display_foot( requested: tuple[float, float], bbox: tuple[float, float, float, float], source_foot: tuple[float, float], scale_factor: float, canvas_shape: tuple[int, int], config: dict[str, Any],) -> tuple[float, float]: height, width = canvas_shape margin = max(8, int(round(float(config["safe_margin_px_at_4k"]) * width / 3840.0))) left, top, right, bottom = scaled_bbox_offsets(bbox, source_foot, scale_factor) maximum_overlay_x = safe_x_limit(width, config) minimum_x = margin + left maximum_x = maximum_overlay_x - margin - right minimum_y = margin + top maximum_y = height - margin - bottom if maximum_x < minimum_x: raise RuntimeError("Pose is too wide for the configured overlay-safe region") return ( float(np.clip(requested[0], minimum_x, maximum_x)), float(np.clip(requested[1], minimum_y, maximum_y)), )
def build_poses( config: dict[str, Any], frames: dict[float, np.ndarray], frame_indices: dict[float, int], yolo_masks: dict[float, np.ndarray], refined_masks: dict[float, np.ndarray], metrics: dict[float, dict[str, Any]],) -> list[Pose]: sample_times = [float(value) for value in config["sample_times"]] height, width = frames[sample_times[0]].shape[:2] scale_factor = float(config["pose_scale"]) heroes = {float(value) for value in config["hero_times"]} poses: list[Pose] = [] for time in sample_times: mask = refined_masks[time] bbox = v1.mask_bbox(mask) foot = v1.foot_point(mask, bbox) target_norm = config["layout_targets_normalized"][config_key(time)] requested = (float(target_norm[0]) * width, float(target_norm[1]) * height) display_foot = clamp_display_foot( requested, bbox, foot, scale_factor, (height, width), config, ) group = group_for_time(time, config) poses.append( Pose( time=time, frame_index=frame_indices[time], frame_bgr=frames[time], yolo_mask=yolo_masks[time], refined_mask=mask, source_bbox=bbox, source_foot=foot, display_foot_requested=requested, display_foot=display_foot, phase_name=phase_for_time(time, config), group_id=str(group["id"]), group_label=str(group["label"]), color_rgb=v1.hex_to_rgb(group["color"]), hero=time in heroes, scale_factor=scale_factor, sam_metrics=metrics[time], ) ) return poses
def scaled_pose_mask(pose: Pose, canvas_shape: tuple[int, int]) -> np.ndarray: height, width = canvas_shape scale = pose.scale_factor transform = np.array( [ [scale, 0.0, pose.display_foot[0] - scale * pose.source_foot[0]], [0.0, scale, pose.display_foot[1] - scale * pose.source_foot[1]], ], dtype=np.float32, ) return cv2.warpAffine( pose.refined_mask, transform, (width, height), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=0, )
def draw_shadows(canvas: np.ndarray, poses: Iterable[Pose], alpha: float) -> None: if alpha <= 0: return height, width = canvas.shape[:2] shadow = np.zeros((height, width), dtype=np.uint8) for pose in poses: bbox_width = (pose.source_bbox[2] - pose.source_bbox[0]) * pose.scale_factor bbox_height = (pose.source_bbox[3] - pose.source_bbox[1]) * pose.scale_factor centre = ( int(round(pose.display_foot[0])), int(round(pose.display_foot[1] + max(2.0, bbox_height * 0.010))), ) axes = ( max(8, int(round(bbox_width * 0.30))), max(3, int(round(bbox_height * 0.016))), ) cv2.ellipse(shadow, centre, axes, 0, 0, 360, 255, -1, lineType=cv2.LINE_AA) sigma = max(2.0, width / 500.0) soft = cv2.GaussianBlur(shadow.astype(np.float32) / 255.0, (0, 0), sigmaX=sigma) canvas[:] = np.clip(canvas.astype(np.float32) * (1.0 - soft[..., None] * alpha), 0, 255).astype(np.uint8)
def blend_scaled_pose(canvas: np.ndarray, pose: Pose, alpha: float) -> None: source_height, source_width = pose.refined_mask.shape x1, y1, x2, y2 = [int(value) for value in v1.mask_bbox(pose.refined_mask)] pad = max(3, int(round(source_width / 3840.0 * 5))) x1, y1 = max(0, x1 - pad), max(0, y1 - pad) x2, y2 = min(source_width, x2 + pad), min(source_height, y2 + pad) mask_crop = pose.refined_mask[y1:y2, x1:x2] frame_crop = pose.frame_bgr[y1:y2, x1:x2] scale = pose.scale_factor scaled_size = ( max(1, int(round(mask_crop.shape[1] * scale))), max(1, int(round(mask_crop.shape[0] * scale))), ) mask_scaled = cv2.resize(mask_crop, scaled_size, interpolation=cv2.INTER_NEAREST) frame_scaled = cv2.resize(frame_crop, scaled_size, interpolation=cv2.INTER_AREA) foot_in_crop = ( (pose.source_foot[0] - x1) * scale, (pose.source_foot[1] - y1) * scale, ) destination_x1 = int(round(pose.display_foot[0] - foot_in_crop[0])) destination_y1 = int(round(pose.display_foot[1] - foot_in_crop[1])) destination_x2 = destination_x1 + mask_scaled.shape[1] destination_y2 = destination_y1 + mask_scaled.shape[0] source_x1 = max(0, -destination_x1) source_y1 = max(0, -destination_y1) source_x2 = mask_scaled.shape[1] - max(0, destination_x2 - canvas.shape[1]) source_y2 = mask_scaled.shape[0] - max(0, destination_y2 - canvas.shape[0]) destination_x1, destination_y1 = max(0, destination_x1), max(0, destination_y1) destination_x2, destination_y2 = min(canvas.shape[1], destination_x2), min(canvas.shape[0], destination_y2) if source_x2 <= source_x1 or source_y2 <= source_y1: return mask = mask_scaled[source_y1:source_y2, source_x1:source_x2] frame = frame_scaled[source_y1:source_y2, source_x1:source_x2] target = canvas[destination_y1:destination_y2, destination_x1:destination_x2]
render_scale = canvas.shape[1] / 3840.0 halo_radius = max(1, int(round(2.5 * render_scale))) halo = cv2.dilate((mask > 0).astype(np.uint8), v2.ellipse_kernel(halo_radius), iterations=1) halo = np.clip(halo.astype(np.float32) - (mask > 0).astype(np.float32), 0.0, 1.0) v2.blend_region(target, np.full_like(target, 247), halo * (0.40 if pose.hero else 0.25))
foreground = v1.colorize_foreground(frame, pose.color_rgb) mask_float = mask.astype(np.float32) / 255.0 soft = cv2.GaussianBlur(mask_float, (0, 0), sigmaX=max(0.6, 1.05 * render_scale)) v2.blend_region(target, foreground, soft * float(alpha)) contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) layer = target.copy() cv2.drawContours( layer, contours, -1, tuple(int(value) for value in pose.color_rgb), max(1, int(round(2.0 * render_scale))), lineType=cv2.LINE_AA, ) contour_alpha = 0.82 if pose.hero else 0.58 target[:] = np.clip( target.astype(np.float32) * (1.0 - contour_alpha) + layer.astype(np.float32) * contour_alpha, 0, 255, ).astype(np.uint8)
def draw_display_path(canvas: np.ndarray, poses: list[Pose]) -> None: render_scale = canvas.shape[1] / 3840.0 points = np.array([pose.display_foot for pose in poses], dtype=np.float32) for pose, p0, p1 in zip(poses[:-1], points[:-1], points[1:]): a = tuple(np.round(p0).astype(int)) b = tuple(np.round(p1).astype(int)) color = tuple(int(value) for value in pose.color_rgb) cv2.line(canvas, a, b, (247, 247, 244), max(5, int(round(9 * render_scale))), lineType=cv2.LINE_AA) cv2.line(canvas, a, b, color, max(2, int(round(4 * render_scale))), lineType=cv2.LINE_AA) v2.arrow_head( canvas, points[-2], points[-1], tuple(int(value) for value in poses[-1].color_rgb), render_scale, )
def render_layout(background: np.ndarray, poses: list[Pose], config: dict[str, Any]) -> np.ndarray: canvas = background.copy() draw_shadows(canvas, poses, float(config["shadow_alpha"])) draw_display_path(canvas, poses) alpha_config = config["alpha"] for pose in sorted(poses, key=lambda item: item.display_foot[1]): alpha = float(alpha_config["hero"] if pose.hero else alpha_config["standard"]) blend_scaled_pose(canvas, pose, alpha) return canvas
def add_timeline(ax: Any, config: dict[str, Any], width: int, height: int) -> None: safe_boundary = safe_x_limit(width, config) content_left = 0.008 * width content_right = safe_boundary - 0.012 * width content_width = content_right - content_left phases = config["motion_phases"] start = float(phases[0]["start"]) end = float(phases[-1]["end"]) ax.add_patch( Rectangle( (0, 0.010 * height), safe_boundary - 0.006 * width, 0.094 * height, facecolor=(0.025, 0.040, 0.055), alpha=0.82, lw=0, zorder=20, ) ) phase_colours = [(0.18, 0.23, 0.27), (0.25, 0.23, 0.19), (0.24, 0.20, 0.25)] y0, y1 = 0.022 * height, 0.051 * height for phase, colour in zip(phases, phase_colours): x0 = content_left + content_width * (float(phase["start"]) - start) / (end - start) x1 = content_left + content_width * (float(phase["end"]) - start) / (end - start) ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0, facecolor=colour, lw=0, zorder=21)) ax.text( (x0 + x1) / 2, y0 + 0.60 * (y1 - y0), phase["name"], color="white", ha="center", va="center", fontsize=5.5, weight="bold", zorder=22, ) marker_y = 0.073 * height ax.plot([content_left, content_right], [marker_y, marker_y], color=(0.80, 0.83, 0.85), lw=0.7, zorder=21) for time in [float(value) for value in config["sample_times"]]: group = group_for_time(time, config) x = content_left + content_width * (time - start) / (end - start) colour = v1.hex_to_rgb(group["color"]) / 255.0 ax.scatter([x], [marker_y], s=10, c=[colour], edgecolors="white", linewidths=0.35, zorder=23) for time in [7, 28, 40, 57]: x = content_left + content_width * (time - start) / (end - start) alignment = "left" if time == 7 else ("right" if time == 57 else "center") offset = 0.006 * content_width if time == 7 else (-0.006 * content_width if time == 57 else 0) ax.text( x + offset, marker_y + 0.018 * height, f"{time:g} s", color="white", ha=alignment, va="top", fontsize=5.1, zorder=22, ) ax.text( content_right, y0 - 0.005 * height, "time →", color="white", fontsize=5.2, ha="right", va="bottom", zorder=22, )
def add_annotation(ax: Any, config: dict[str, Any], width: int, height: int) -> None: safe_width = safe_x_limit(width, config) box_x, box_y = 0.014 * width, 0.118 * height box_w, box_h = 0.330 * width, 0.083 * height ax.add_patch( FancyBboxPatch( (box_x, box_y), box_w, box_h, boxstyle="round,pad=0.012,rounding_size=12", facecolor=(0.02, 0.035, 0.050), edgecolor=(1, 1, 1, 0.34), lw=0.6, alpha=0.76, zorder=24, ) ) ax.text( box_x + 0.015 * width, box_y + 0.029 * height, "13 specified poses • five colour groups", color="white", fontsize=6.4, weight="bold", ha="left", va="center", zorder=25, ) ax.text( box_x + 0.015 * width, box_y + 0.058 * height, "uniform scale ×0.92 • rightmost 12% reserved", color=(0.90, 0.92, 0.94), fontsize=5.2, ha="left", va="center", zorder=25, )
legend_left = 0.370 * width legend_right = safe_width - 0.012 * width slot = (legend_right - legend_left) / len(config["color_groups"]) for index, group in enumerate(config["color_groups"]): x = legend_left + (index + 0.5) * slot colour = v1.hex_to_rgb(group["color"]) / 255.0 ax.scatter([x], [box_y + 0.030 * height], s=18, c=[colour], edgecolors="white", linewidths=0.45, zorder=25) ax.text( x, box_y + 0.059 * height, str(group["label"]), color="white", fontsize=5.0, ha="center", va="center", zorder=25, )
def save_publication_figure( canvas: np.ndarray, out_base: Path, config: dict[str, Any], annotated: bool,) -> None: height, width = canvas.shape[:2] width_mm = 183.0 width_mm = float(config.get("final_width_mm", width_mm)) png_dpi = int(config.get("png_dpi", 300)) tiff_dpi = 600 tiff_dpi = max(tiff_dpi, int(config.get("tiff_dpi", tiff_dpi))) width_in = width_mm / 25.4 height_in = width_in * height / width fig = plt.figure(figsize=(width_in, height_in), dpi=png_dpi, facecolor="white") ax = fig.add_axes([0, 0, 1, 1]) ax.imshow(canvas) ax.set_xlim(0, width) ax.set_ylim(height, 0) ax.axis("off") if annotated: add_timeline(ax, config, width, height) add_annotation(ax, config, width, height) for extension in ["png", "tiff", "svg", "pdf"]: path = out_base.with_suffix(f".{extension}") if extension == "png": fig.savefig(path, dpi=png_dpi, facecolor="white") elif extension == "tiff": fig.savefig(path, dpi=tiff_dpi, facecolor="white") with Image.open(path) as rendered: rendered.convert("RGB").save( path, format="TIFF", compression="tiff_lzw", dpi=(tiff_dpi, tiff_dpi), ) else: fig.savefig(path, facecolor="white") if extension == "svg": lines = path.read_text(encoding="utf-8").splitlines() path.write_text("\n".join(line.rstrip() for line in lines) + "\n", encoding="utf-8") plt.close(fig)
def overlap_statistics(masks: list[np.ndarray]) -> dict[str, Any]: occupancy = np.zeros(masks[0].shape, dtype=np.uint16) for mask in masks: occupancy += (mask > 0).astype(np.uint16) summed = int(occupancy.sum()) union = int((occupancy > 0).sum()) return { "pose_count": len(masks), "summed_pose_area_px": summed, "union_area_px": union, "redundant_overlap_px": summed - union, "redundant_overlap_fraction": round((summed - union) / summed, 6) if summed else 0.0, "pixels_covered_by_two_or_more": int((occupancy > 1).sum()), "maximum_stack_depth": int(occupancy.max()), }
def save_layout_map(poses: list[Pose], config: dict[str, Any], out_dir: Path) -> None: fields = [ "time_s", "phase", "color_group", "color_hex", "hero", "source_foot_x_px", "source_foot_y_px", "requested_display_foot_x_px", "requested_display_foot_y_px", "display_foot_x_px", "display_foot_y_px", "translation_after_scale_dx_px", "translation_after_scale_dy_px", "uniform_scale_factor", "scaled_bbox_x1", "scaled_bbox_y1", "scaled_bbox_x2", "scaled_bbox_y2", "safe_x_limit_px", "alpha", ] colour_by_group = {str(group["id"]): str(group["color"]) for group in config["color_groups"]} with (out_dir / "layout_map.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n") writer.writeheader() for pose in poses: mask = scaled_pose_mask(pose, pose.refined_mask.shape) bbox = v1.mask_bbox(mask) alpha = config["alpha"]["hero" if pose.hero else "standard"] writer.writerow( { "time_s": f"{pose.time:.3f}", "phase": pose.phase_name, "color_group": pose.group_id, "color_hex": colour_by_group[pose.group_id], "hero": int(pose.hero), "source_foot_x_px": f"{pose.source_foot[0]:.3f}", "source_foot_y_px": f"{pose.source_foot[1]:.3f}", "requested_display_foot_x_px": f"{pose.display_foot_requested[0]:.3f}", "requested_display_foot_y_px": f"{pose.display_foot_requested[1]:.3f}", "display_foot_x_px": f"{pose.display_foot[0]:.3f}", "display_foot_y_px": f"{pose.display_foot[1]:.3f}", "translation_after_scale_dx_px": f"{pose.display_foot[0] - pose.scale_factor * pose.source_foot[0]:.3f}", "translation_after_scale_dy_px": f"{pose.display_foot[1] - pose.scale_factor * pose.source_foot[1]:.3f}", "uniform_scale_factor": f"{pose.scale_factor:.3f}", "scaled_bbox_x1": f"{bbox[0]:.3f}", "scaled_bbox_y1": f"{bbox[1]:.3f}", "scaled_bbox_x2": f"{bbox[2]:.3f}", "scaled_bbox_y2": f"{bbox[3]:.3f}", "safe_x_limit_px": f"{safe_x_limit(pose.refined_mask.shape[1], config):.3f}", "alpha": f"{float(alpha):.3f}", } )
def save_colour_map(config: dict[str, Any], out_dir: Path) -> None: with (out_dir / "color_map.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.writer(handle, lineterminator="\n") writer.writerow(["color_group", "color_hex", "times_s"]) for group in config["color_groups"]: writer.writerow([group["id"], group["color"], ",".join(f"{float(t):g}" for t in group["times"])])
def save_refined_records(poses: list[Pose], out_dir: Path) -> None: rows: list[dict[str, Any]] = [] masks: dict[str, np.ndarray] = {} for index, pose in enumerate(poses): rows.append( { "index": index, "time_s": pose.time, "frame_index": pose.frame_index, "phase": pose.phase_name, "color_group": pose.group_id, "source_bbox_xyxy": [round(float(value), 3) for value in pose.source_bbox], "source_foot_xy": [round(float(value), 3) for value in pose.source_foot], "display_foot_xy": [round(float(value), 3) for value in pose.display_foot], "uniform_scale_factor": pose.scale_factor, "sam_metrics": pose.sam_metrics, } ) masks[f"mask_{index:03d}"] = pose.refined_mask.astype(np.uint8) v2.write_json(out_dir / "detections_refined.json", rows) np.savez_compressed(out_dir / "refined_masks.npz", **masks)
def save_requested_keyframes(poses: list[Pose], out_dir: Path) -> None: tile_width, tile_height, header = 480, 305, 34 columns = 5 rows = int(math.ceil(len(poses) / columns)) montage = np.full((rows * tile_height, columns * tile_width, 3), 244, dtype=np.uint8) for index, pose in enumerate(poses): frame_rgb = cv2.cvtColor(pose.frame_bgr, cv2.COLOR_BGR2RGB) body = v2.letterbox(frame_rgb, tile_width, tile_height - header, (235, 235, 235)) tile = np.full((tile_height, tile_width, 3), 244, dtype=np.uint8) tile[header:] = body colour = tuple(int(value) for value in pose.color_rgb) cv2.rectangle(tile, (0, 0), (tile_width - 1, tile_height - 1), colour, 5, lineType=cv2.LINE_AA) label = f"{pose.time:g}s group {pose.group_id} frame {pose.frame_index}" cv2.putText(tile, label, (12, 23), cv2.FONT_HERSHEY_SIMPLEX, 0.53, (32, 38, 44), 1, cv2.LINE_AA) row, column = divmod(index, columns) montage[row * tile_height : (row + 1) * tile_height, column * tile_width : (column + 1) * tile_width] = tile cv2.imwrite( str(out_dir / "requested_keyframes.jpg"), cv2.cvtColor(montage, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 94], )
def save_safe_area_qa( canvas: np.ndarray, background: np.ndarray, config: dict[str, Any], out_dir: Path,) -> dict[str, Any]: height, width = canvas.shape[:2] boundary = safe_x_limit(width, config) boundary_px = int(math.floor(boundary)) difference = np.max(np.abs(canvas.astype(np.int16) - background.astype(np.int16)), axis=2) > 2 yy, xx = np.where(difference) maximum_changed_x = int(xx.max()) if len(xx) else -1 reserved_changed = int(difference[:, int(math.ceil(boundary)) :].sum()) report = { "image_width_px": width, "right_reserved_fraction": float(config["right_reserved_fraction"]), "overlay_safe_x_limit_px": round(boundary, 3), "maximum_changed_overlay_x_px": maximum_changed_x, "changed_pixels_inside_reserved_zone": reserved_changed, "pass": bool(maximum_changed_x < boundary_px and reserved_changed == 0), } clean_png = cv2.imread(str(out_dir / "trajectory_v3_custom_frames_clean.png"), cv2.IMREAD_UNCHANGED) annotated_png = cv2.imread(str(out_dir / "trajectory_v3_custom_frames_annotated.png"), cv2.IMREAD_UNCHANGED) if clean_png is not None and annotated_png is not None and clean_png.shape == annotated_png.shape: png_boundary = int(math.ceil(clean_png.shape[1] * (1.0 - float(config["right_reserved_fraction"])))) annotation_difference = np.max( np.abs(annotated_png.astype(np.int16) - clean_png.astype(np.int16)), axis=2, ) > 2 annotated_reserved_changed = int(annotation_difference[:, png_boundary:].sum()) report["annotated_changed_pixels_inside_reserved_zone"] = annotated_reserved_changed report["pass"] = bool(report["pass"] and annotated_reserved_changed == 0) guide = canvas.copy() red = np.array([213, 70, 66], dtype=np.float32) zone = guide[:, boundary_px:].astype(np.float32) guide[:, boundary_px:] = np.clip(zone * 0.56 + red[None, None, :] * 0.44, 0, 255).astype(np.uint8) cv2.line(guide, (boundary_px, 0), (boundary_px, height - 1), (255, 255, 255), 4, lineType=cv2.LINE_AA) cv2.putText( guide, "12% reserved: no final overlay", (boundary_px + 14, 48), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (255, 255, 255), 2, cv2.LINE_AA, ) cv2.imwrite(str(out_dir / "safe_area_qa.png"), cv2.cvtColor(guide, cv2.COLOR_RGB2BGR)) v2.write_json(out_dir / "safe_area_metrics.json", report) return report
def save_comparison(v2_path: Path, v3_path: Path, safe_path: Path, out_path: Path) -> None: images = [] for path in [v2_path, v3_path, safe_path]: image = cv2.imread(str(path)) if image is None: raise RuntimeError(f"Could not read comparison input: {path}") images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) fig = plt.figure(figsize=(12.0, 7.5), dpi=300, facecolor="#F4F5F4") grid = fig.add_gridspec(2, 2, height_ratios=[1, 1.16], hspace=0.12, wspace=0.04) axes = [fig.add_subplot(grid[0, 0]), fig.add_subplot(grid[0, 1]), fig.add_subplot(grid[1, :])] titles = [ "v2 • 12 selected poses • three colours", "v3 • 13 specified poses • five colours • uniform ×0.92 scale", "v3 crop-safety QA • rightmost 12% contains no final overlay", ] for axis, image, title in zip(axes, images, titles): axis.imshow(image) axis.set_title(title, fontsize=8.4, loc="left", pad=4, weight="bold", color="#28313A") axis.axis("off") fig.savefig(out_path, dpi=300, facecolor=fig.get_facecolor(), bbox_inches="tight", pil_kwargs={"quality": 94}) plt.close(fig)
def metric_summary(poses: list[Pose]) -> dict[str, Any]: fields = ["final_iou", "final_recall", "final_precision", "final_area_ratio", "sam_score"] summary: dict[str, Any] = {"pose_count": len(poses)} for field in fields: values = np.array([float(pose.sam_metrics[field]) for pose in poses], dtype=np.float64) summary[field] = { "mean": round(float(values.mean()), 6), "min": round(float(values.min()), 6), "max": round(float(values.max()), 6), } summary["fallback_count"] = sum(bool(pose.sam_metrics["fallback_to_yolo"]) for pose in poses) return summary
def main() -> int: args = parse_args() video = args.video.expanduser().resolve() config_path = args.config.expanduser().resolve() yolo_path = args.yolo_model.expanduser().resolve() checkpoint = args.sam_checkpoint.expanduser().resolve() out_dir = args.out_dir.expanduser().resolve() for path in [video, config_path, yolo_path]: if not path.exists(): print(f"Required input not found: {path}", file=sys.stderr) return 2 config = v2.load_json(config_path) validate_config(config) out_dir.mkdir(parents=True, exist_ok=True) sample_times = [float(value) for value in config["sample_times"]] reference_times = [float(value) for value in config["background_reference_times"]] ordered_times = sorted(set(sample_times + reference_times)) frames, frame_indices, video_metadata = read_frames( video, ordered_times, int(config["render_width"]), )
prompts: dict[str, Any] = {} if args.reuse_segmentation: yolo_masks, refined_masks, metrics, yolo_records = load_segmentation_cache(out_dir, ordered_times) checkpoint_hash = str(config["sam"]["checkpoint_sha256"]) print(f"Reusing YOLO/SAM masks for {len(ordered_times)} frames from {out_dir}") else: if not checkpoint.exists(): print( "SAM checkpoint not found. Run trajectory_project/scripts/download_sam_checkpoint.py first.", file=sys.stderr, ) return 2 yolo_masks, yolo_records = infer_yolo_masks( frames, frame_indices, ordered_times, yolo_path, config, args.device, ) refined_masks, metrics, prompts, checkpoint_hash = refine_all_masks( frames, yolo_masks, ordered_times, checkpoint, config, args.device, ) save_segmentation_cache( out_dir, ordered_times, yolo_masks, refined_masks, yolo_records, metrics, prompts, )
poses = build_poses( config, frames, frame_indices, yolo_masks, refined_masks, metrics, ) background = v2.make_background(frames, refined_masks, config) layout = render_layout(background, poses, config) cv2.imwrite(str(out_dir / "background_plate.png"), cv2.cvtColor(background, cv2.COLOR_RGB2BGR)) cv2.imwrite(str(out_dir / "composite_layout_rgb.png"), cv2.cvtColor(layout, cv2.COLOR_RGB2BGR)) save_publication_figure( layout, out_dir / "trajectory_v3_custom_frames_clean", config, annotated=False, ) save_publication_figure( layout, out_dir / "trajectory_v3_custom_frames_annotated", config, annotated=True, )
save_requested_keyframes(poses, out_dir) v2.save_sam_qa(poses, out_dir) save_layout_map(poses, config, out_dir) save_colour_map(config, out_dir) save_refined_records(poses, out_dir) scaled_masks = [scaled_pose_mask(pose, layout.shape[:2]) for pose in poses] overlap_report = overlap_statistics(scaled_masks) v2.write_json(out_dir / "overlap_metrics.json", overlap_report) safe_report = save_safe_area_qa(layout, background, config, out_dir) v2_path = PROJECT_ROOT / "trajectory_project" / "outputs" / "v2_sam_layout" / "trajectory_v2_layout_expanded_annotated.png" save_comparison( v2_path, out_dir / "trajectory_v3_custom_frames_annotated.png", out_dir / "safe_area_qa.png", out_dir / "comparison_v2_v3.jpg", ) sam_summary = metric_summary(poses) v2.write_json( out_dir / "sam_metrics.json", {"summary": sam_summary, "frames": [{"time_s": pose.time, "metrics": pose.sam_metrics} for pose in poses]}, ) metadata = { "version": config["version"], "video": v2.display_path(video), "config": v2.display_path(config_path), "yolo_model": yolo_path.name, "sam_checkpoint": checkpoint.name, "sam_checkpoint_sha256": checkpoint_hash, "device": args.device, "sample_times_s": sample_times, "color_groups": config["color_groups"], "uniform_pose_scale": float(config["pose_scale"]), "right_reserved_fraction": float(config["right_reserved_fraction"]), "trajectory_overlay": "none; coloured line encodes display order only", "video_metadata": video_metadata, "sam_summary": sam_summary, "layout_overlap": overlap_report, "safe_area": safe_report, } v2.write_json(out_dir / "run_metadata.json", metadata) if prompts: v2.write_json(out_dir / "sam_prompts.json", prompts) print(f"Wrote v3 outputs to {out_dir}") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562#!/usr/bin/env python3"""Build the timing-adjusted v4 G1 trajectory figure.
This is a deliberately thin adapter around the locked v3 renderer. It changesonly the requested source times, raises the 14 s display anchor slightly, andremoves the 44 s donor-frame robot residual from the background with pixelsfrom a clean 31 s frame of the same fixed-camera video.
Publication exports: ``.png`` preview, RGB ``.tiff`` at 600 dpi, andeditable-text ``.svg`` / ``.pdf`` files at 183 mm width."""
from __future__ import annotations
import argparseimport csvfrom pathlib import Pathfrom typing import Any
import cv2import numpy as np
import build_trajectory_figure_v3 as v3
v3.matplotlib.rcParams.update( { "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], "font.size": 7, "svg.fonttype": "none", "pdf.fonttype": 42, })
PROJECT_ROOT = Path(__file__).resolve().parents[2]DEFAULT_VIDEO = PROJECT_ROOT / "source" / "CLIP_P0010073.mov"DEFAULT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v4_frame_timing_background_fix.json"DEFAULT_YOLO = PROJECT_ROOT / "trajectory_project" / "models" / "yolov8x-seg.pt"DEFAULT_SAM = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v4_frame_timing_background_fix"V3_REFERENCE = ( PROJECT_ROOT / "trajectory_project" / "outputs" / "v3_custom_frames_layout" / "trajectory_v3_custom_frames_annotated.png")V3_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v3_custom_frames_layout.json"OUTPUT_STEM = "trajectory_v4_timing_background"
_BACKGROUND_AUDIT: dict[str, Any] = {}_BACKGROUND_BEFORE_RGB: np.ndarray | None = None_BACKGROUND_AFTER_RGB: np.ndarray | None = None
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--video", type=Path, default=DEFAULT_VIDEO) parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--yolo-model", type=Path, default=DEFAULT_YOLO) parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_SAM) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--device", default="cuda:0") parser.add_argument( "--reuse-segmentation", action="store_true", help="Reuse the v4 YOLO/SAM cache and rerender only.", ) return parser.parse_args()
def mask_bbox(mask: np.ndarray) -> list[int] | None: yy, xx = np.where(mask > 0) if len(xx) == 0: return None return [int(xx.min()), int(yy.min()), int(xx.max()), int(yy.max())]
def apply_background_tone(image_bgr: np.ndarray, config: dict[str, Any]) -> np.ndarray: rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY).astype(np.float32)[..., None] desaturate = float(np.clip(config.get("background_desaturate", 0.0), 0.0, 1.0)) brightness = float(np.clip(config.get("background_brightness", 1.0), 0.0, 2.0)) rgb = (1.0 - desaturate) * rgb + desaturate * gray rgb *= brightness return np.clip(rgb, 0, 255).astype(np.uint8)
def make_background_v4( frames: dict[float, np.ndarray], masks: dict[float, np.ndarray], config: dict[str, Any],) -> np.ndarray: """Reproduce v3 background repair, then remove only its donor residual.""" global _BACKGROUND_AUDIT, _BACKGROUND_BEFORE_RGB, _BACKGROUND_AFTER_RGB
reference_times = [float(value) for value in config["background_reference_times"]] if len(reference_times) != 3: raise RuntimeError("v4 background repair requires base, fill, and cleanup reference times") base_time, fill_time, cleanup_time = reference_times base = frames[base_time] fill = frames[fill_time] cleanup = frames[cleanup_time] base_mask = masks[base_time] fill_mask = masks[fill_time] cleanup_mask = masks[cleanup_time]
scale = base.shape[1] / 3840.0 first_dilate = max(8, int(round(float(config["background_dilate_px_at_4k"]) * scale))) repaired_before_cleanup = v3.v1.repair_background( base, fill, base_mask, fill_mask, first_dilate, )
kernel_size = max(3, 2 * first_dilate + 1) base_patch = cv2.dilate( (base_mask > 0).astype(np.uint8), cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size)), iterations=1, ) residual_core = ((fill_mask > 0) & (base_patch > 0)).astype(np.uint8) if int(residual_core.sum()) == 0: raise RuntimeError("Expected a donor-frame residual but found no overlap to repair")
cleanup_dilate = max( 4, int(round(float(config["background_residual_dilate_px_at_4k"]) * scale)), ) cleanup_kernel_size = max(3, 2 * cleanup_dilate + 1) cleanup_patch = cv2.dilate( residual_core, cv2.getStructuringElement( cv2.MORPH_ELLIPSE, (cleanup_kernel_size, cleanup_kernel_size), ), iterations=1, ) cleanup_overlap_pixels = int(((cleanup_mask > 0) & (cleanup_patch > 0)).sum()) if cleanup_overlap_pixels: raise RuntimeError( "The cleanup frame contains robot pixels inside the residual repair patch" )
repaired_after_cleanup = v3.v1.repair_background( repaired_before_cleanup, cleanup, residual_core * 255, cleanup_mask, cleanup_dilate, ) before_rgb = apply_background_tone(repaired_before_cleanup, config) after_rgb = apply_background_tone(repaired_after_cleanup, config) difference = np.max( np.abs(after_rgb.astype(np.int16) - before_rgb.astype(np.int16)), axis=2, ) changed = difference > 2 if int(changed.sum()) == 0: raise RuntimeError("Residual repair did not change the background")
_BACKGROUND_BEFORE_RGB = before_rgb _BACKGROUND_AFTER_RGB = after_rgb _BACKGROUND_AUDIT = { "method": "fixed-camera source-pixel patch with colour matching and feathering", "base_time_s": base_time, "first_fill_time_s": fill_time, "cleanup_time_s": cleanup_time, "generative_fill": False, "residual_core_pixels": int(residual_core.sum()), "residual_core_bbox_xyxy": mask_bbox(residual_core), "cleanup_patch_pixels": int(cleanup_patch.sum()), "cleanup_patch_bbox_xyxy": mask_bbox(cleanup_patch), "cleanup_robot_overlap_pixels": cleanup_overlap_pixels, "changed_pixels_over_2": int(changed.sum()), "changed_bbox_xyxy": mask_bbox(changed.astype(np.uint8)), "maximum_absolute_channel_change": int(difference.max()), } return after_rgb
def save_v3_v4_comparison( _v2_path: Path, v4_path: Path, safe_path: Path, _v2_v3_out_path: Path,) -> None: paths = [V3_REFERENCE, v4_path, safe_path] images = [] for path in paths: image = cv2.imread(str(path)) if image is None: raise RuntimeError(f"Could not read comparison input: {path}") images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) figure = v3.plt.figure(figsize=(12.0, 7.5), dpi=300, facecolor="#F4F5F4") grid = figure.add_gridspec(2, 2, height_ratios=[1, 1.16], hspace=0.12, wspace=0.04) axes = [ figure.add_subplot(grid[0, 0]), figure.add_subplot(grid[0, 1]), figure.add_subplot(grid[1, :]), ] titles = [ "v3 • locked layout", "v4 • requested frame timing + local background fix", "v4 crop-safety QA • rightmost 12% contains no final overlay", ] for axis, image, title in zip(axes, images, titles): axis.imshow(image) axis.set_title(title, fontsize=8.4, loc="left", pad=4, weight="bold", color="#28313A") axis.axis("off") figure.savefig( v4_path.parent / "comparison_v3_v4.jpg", dpi=300, facecolor=figure.get_facecolor(), bbox_inches="tight", pil_kwargs={"quality": 94}, ) v3.plt.close(figure)
def add_timeline_v4(ax: Any, config: dict[str, Any], width: int, height: int) -> None: """Use the locked v3 timeline styling with v4's actual endpoints.""" safe_boundary = v3.safe_x_limit(width, config) content_left = 0.008 * width content_right = safe_boundary - 0.012 * width content_width = content_right - content_left phases = config["motion_phases"] start = float(phases[0]["start"]) end = float(phases[-1]["end"]) ax.add_patch( v3.Rectangle( (0, 0.010 * height), safe_boundary - 0.006 * width, 0.094 * height, facecolor=(0.025, 0.040, 0.055), alpha=0.82, lw=0, zorder=20, ) ) phase_colours = [(0.18, 0.23, 0.27), (0.25, 0.23, 0.19), (0.24, 0.20, 0.25)] y0, y1 = 0.022 * height, 0.051 * height for phase, colour in zip(phases, phase_colours): x0 = content_left + content_width * (float(phase["start"]) - start) / (end - start) x1 = content_left + content_width * (float(phase["end"]) - start) / (end - start) ax.add_patch( v3.Rectangle((x0, y0), x1 - x0, y1 - y0, facecolor=colour, lw=0, zorder=21) ) ax.text( (x0 + x1) / 2, y0 + 0.60 * (y1 - y0), phase["name"], color="white", ha="center", va="center", fontsize=5.5, weight="bold", zorder=22, ) marker_y = 0.073 * height ax.plot( [content_left, content_right], [marker_y, marker_y], color=(0.80, 0.83, 0.85), lw=0.7, zorder=21, ) for time in [float(value) for value in config["sample_times"]]: group = v3.group_for_time(time, config) x = content_left + content_width * (time - start) / (end - start) colour = v3.v1.hex_to_rgb(group["color"]) / 255.0 ax.scatter( [x], [marker_y], s=10, c=[colour], edgecolors="white", linewidths=0.35, zorder=23, ) label_times = [start] + [float(phase["end"]) for phase in phases] for index, time in enumerate(label_times): x = content_left + content_width * (time - start) / (end - start) first = index == 0 last = index == len(label_times) - 1 alignment = "left" if first else ("right" if last else "center") offset = 0.006 * content_width if first else (-0.006 * content_width if last else 0) ax.text( x + offset, marker_y + 0.018 * height, f"{time:g} s", color="white", ha=alignment, va="top", fontsize=5.1, zorder=22, ) ax.text( content_right, y0 - 0.005 * height, "time →", color="white", fontsize=5.2, ha="right", va="bottom", zorder=22, )
def save_publication_figure_v4( canvas: np.ndarray, out_base: Path, config: dict[str, Any], annotated: bool,) -> None: """Export the final v4 bundle explicitly for standalone source auditing.""" height, width = canvas.shape[:2] width_mm = 183.0 width_mm = float(config.get("final_width_mm", width_mm)) png_dpi = int(config.get("png_dpi", 300)) tiff_dpi = 600 tiff_dpi = max(tiff_dpi, int(config.get("tiff_dpi", tiff_dpi))) width_in = width_mm / 25.4 height_in = width_in * height / width figure = v3.plt.figure(figsize=(width_in, height_in), dpi=png_dpi, facecolor="white") axis = figure.add_axes([0, 0, 1, 1]) axis.imshow(canvas) axis.set_xlim(0, width) axis.set_ylim(height, 0) axis.axis("off") if annotated: add_timeline_v4(axis, config, width, height) v3.add_annotation(axis, config, width, height) for extension in ["png", "tiff", "svg", "pdf"]: path = out_base.with_suffix(f".{extension}") if extension == "png": figure.savefig(path, dpi=png_dpi, facecolor="white") elif extension == "tiff": figure.savefig(path, dpi=tiff_dpi, facecolor="white") with v3.Image.open(path) as rendered: rendered.convert("RGB").save( path, format="TIFF", compression="tiff_lzw", dpi=(tiff_dpi, tiff_dpi), ) else: figure.savefig(path, facecolor="white") if extension == "svg": lines = path.read_text(encoding="utf-8").splitlines() path.write_text("\n".join(line.rstrip() for line in lines) + "\n", encoding="utf-8") v3.plt.close(figure)
def export_final_publication_outputs(out_dir: Path, config: dict[str, Any]) -> None: layout_bgr = cv2.imread(str(out_dir / "composite_layout_rgb.png")) if layout_bgr is None: raise RuntimeError("Missing v4 composite layout for final export") layout_rgb = cv2.cvtColor(layout_bgr, cv2.COLOR_BGR2RGB) save_publication_figure_v4( layout_rgb, out_dir / f"{OUTPUT_STEM}_clean", config, annotated=False, ) save_publication_figure_v4( layout_rgb, out_dir / f"{OUTPUT_STEM}_annotated", config, annotated=True, ) for variant in ["clean", "annotated"]: for extension in ["png", "tiff", "svg", "pdf"]: intermediate = out_dir / f"trajectory_v3_custom_frames_{variant}.{extension}" if intermediate.exists(): intermediate.unlink()
def save_background_fix_qa(out_dir: Path) -> None: if _BACKGROUND_BEFORE_RGB is None or _BACKGROUND_AFTER_RGB is None: raise RuntimeError("Background QA buffers were not populated") bbox = _BACKGROUND_AUDIT.get("changed_bbox_xyxy") if not bbox: raise RuntimeError("Missing changed background bounding box") height, width = _BACKGROUND_AFTER_RGB.shape[:2] x1, y1, x2, y2 = [int(value) for value in bbox] margin = int(round(0.035 * width)) x1 = max(0, x1 - margin) y1 = max(0, y1 - margin) x2 = min(width - 1, x2 + margin) y2 = min(height - 1, y2 + margin) before = _BACKGROUND_BEFORE_RGB[y1 : y2 + 1, x1 : x2 + 1] after = _BACKGROUND_AFTER_RGB[y1 : y2 + 1, x1 : x2 + 1] difference = np.abs(after.astype(np.int16) - before.astype(np.int16)).max(axis=2)
figure, axes = v3.plt.subplots(1, 3, figsize=(9.0, 3.2), dpi=300, facecolor="#F4F5F4") panels = [before, after, difference] titles = ["v3 donor residual", "v4 local source-pixel repair", "absolute difference"] for axis, panel, title in zip(axes, panels, titles): if panel.ndim == 2: axis.imshow(panel, cmap="magma", vmin=0, vmax=max(24, int(difference.max()))) else: axis.imshow(panel) axis.set_title(title, fontsize=8, loc="left", weight="bold") axis.axis("off") figure.tight_layout(pad=0.8) figure.savefig( out_dir / "background_fix_qa.jpg", dpi=300, facecolor=figure.get_facecolor(), pil_kwargs={"quality": 95}, ) v3.plt.close(figure) v3.v2.write_json(out_dir / "background_fix_metrics.json", _BACKGROUND_AUDIT)
def save_layout_change_audit(config: dict[str, Any], out_dir: Path) -> dict[str, Any]: parent = v3.v2.load_json(V3_CONFIG) slot_mapping = [ (7.0, 6.0), (8.0, 7.0), (12.0, 12.0), (14.0, 14.0), (27.0, 27.0), (32.0, 31.0), (33.0, 32.0), (40.0, 40.0), (45.0, 44.0), (50.0, 45.0), (52.0, 52.0), (53.0, 53.0), (57.0, 56.5), ] rows = [] unexpected_changes = [] for old_time, new_time in slot_mapping: old_target = parent["layout_targets_normalized"][v3.config_key(old_time)] new_target = config["layout_targets_normalized"][v3.config_key(new_time)] delta = [round(float(new_target[i]) - float(old_target[i]), 6) for i in range(2)] expected = [0.0, -0.019] if old_time == 14.0 else [0.0, 0.0] if delta != expected: unexpected_changes.append( {"v3_time_s": old_time, "v4_time_s": new_time, "delta_xy": delta} ) rows.append( { "v3_time_s": old_time, "v4_time_s": new_time, "v3_target_xy": old_target, "v4_target_xy": new_target, "delta_xy": delta, } ) with (PROJECT_ROOT / "trajectory_project" / "outputs" / "v3_custom_frames_layout" / "layout_map.csv").open( newline="" ) as handle: v3_layout = {float(row["time_s"]): row for row in csv.DictReader(handle)} with (out_dir / "layout_map.csv").open(newline="") as handle: v4_layout = {float(row["time_s"]): row for row in csv.DictReader(handle)} final_rows = [] unexpected_final_changes = [] for old_time, new_time in slot_mapping: old_row = v3_layout[old_time] new_row = v4_layout[new_time] old_foot = [float(old_row["display_foot_x_px"]), float(old_row["display_foot_y_px"])] new_foot = [float(new_row["display_foot_x_px"]), float(new_row["display_foot_y_px"])] delta = [round(new_foot[i] - old_foot[i], 3) for i in range(2)] if old_time == 7.0: expected = [62.98, 0.0] reason = "v3 in-frame constraint retained the full 6 s outstretched left hand" elif old_time == 14.0: expected = [0.0, -27.36] reason = "user-requested slight upward adjustment" else: expected = [0.0, 0.0] reason = "locked v3 slot" if any(abs(delta[i] - expected[i]) > 1e-3 for i in range(2)): unexpected_final_changes.append( {"v3_time_s": old_time, "v4_time_s": new_time, "delta_xy_px": delta} ) final_rows.append( { "v3_time_s": old_time, "v4_time_s": new_time, "v3_display_foot_xy_px": old_foot, "v4_display_foot_xy_px": new_foot, "delta_xy_px": delta, "reason": reason, } ) report = { "pass": not unexpected_changes and not unexpected_final_changes, "rule": "all display anchors unchanged except 14 s raised by 0.019 image height", "unexpected_changes": unexpected_changes, "unexpected_final_anchor_changes": unexpected_final_changes, "requested_target_slots": rows, "final_display_anchors": final_rows, } if unexpected_changes or unexpected_final_changes: raise RuntimeError( f"Unexpected v4 layout changes: {unexpected_changes + unexpected_final_changes}" ) v3.v2.write_json(out_dir / "layout_change_audit.json", report) return report
def update_run_metadata( config: dict[str, Any], out_dir: Path, layout_audit: dict[str, Any],) -> None: path = out_dir / "run_metadata.json" metadata = v3.v2.load_json(path) metadata.update( { "parent_version": "v3-custom-frames-layout", "frame_replacements_s": [ {"from": 7.0, "to": 6.0}, {"from": 8.0, "to": 7.0}, {"from": 32.0, "to": 31.0}, {"from": 33.0, "to": 32.0}, {"from": 45.0, "to": 44.0}, {"from": 50.0, "to": 45.0}, {"from": 57.0, "to": 56.5}, ], "layout_change_audit": layout_audit, "background_residual_repair": _BACKGROUND_AUDIT, "publication_output_stem": OUTPUT_STEM, } ) v3.v2.write_json(path, metadata)
def main() -> int: # Reuse the locked v3 renderer verbatim; override only the v4 input/output # adapter, the local background cleanup, and the version comparison panel. v3.parse_args = parse_args v3.v2.make_background = make_background_v4 v3.save_comparison = save_v3_v4_comparison v3.add_timeline = add_timeline_v4 return_code = v3.main() if return_code: return return_code
args = parse_args() out_dir = args.out_dir.expanduser().resolve() config = v3.v2.load_json(args.config.expanduser().resolve()) export_final_publication_outputs(out_dir, config) save_background_fix_qa(out_dir) layout_audit = save_layout_change_audit(config, out_dir) update_run_metadata(config, out_dir, layout_audit) print(f"Wrote v4 outputs to {out_dir}") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551#!/usr/bin/env python3"""Build v5 by tuning only scale and layout to reduce pose occlusion.
The exact v4 source frames, SAM masks, five colours, alpha values, repairedbackground, and rightmost 12% reserve are retained. V5 enlarges 6/7 s tobalance the near-field row, reduces 31 s, raises 14 s, and staggers 40–56.5 sto keep 40 s and 44 s visible.
Publication exports: ``.png`` preview, RGB ``.tiff`` at 600 dpi, andeditable-text ``.svg`` / ``.pdf`` files at 183 mm width."""
from __future__ import annotations
import argparseimport csvimport hashlibimport shutilfrom dataclasses import replacefrom pathlib import Pathfrom typing import Any
import cv2import numpy as np
import build_trajectory_figure_v3 as v3import build_trajectory_figure_v4 as v4
v3.matplotlib.rcParams.update( { "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], "font.size": 7, "svg.fonttype": "none", "pdf.fonttype": 42, })
PROJECT_ROOT = Path(__file__).resolve().parents[2]DEFAULT_VIDEO = PROJECT_ROOT / "source" / "CLIP_P0010073.mov"DEFAULT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v5_occlusion_layout_tuning.json"DEFAULT_YOLO = PROJECT_ROOT / "trajectory_project" / "models" / "yolov8x-seg.pt"DEFAULT_SAM = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v5_occlusion_layout_tuning"DEFAULT_SEGMENTATION_SOURCE = ( PROJECT_ROOT / "trajectory_project" / "outputs" / "v4_frame_timing_background_fix")V4_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v4_frame_timing_background_fix.json"V4_ANNOTATED = DEFAULT_SEGMENTATION_SOURCE / "trajectory_v4_timing_background_annotated.png"OUTPUT_STEM = "trajectory_v5_occlusion_tuned"REUSED_SEGMENTATION_ARTIFACTS = ( "segmentation_cache.npz", "yolo_seed_detections.json", "sam_metrics_all.json", "sam_prompts.json",)
_ORIGINAL_BUILD_POSES = v3.build_poses_ORIGINAL_LOAD_CACHE = v3.load_segmentation_cache_POSES_V5: list[v3.Pose] = []_FRAMES: dict[float, np.ndarray] = {}_FRAME_INDICES: dict[float, int] = {}_YOLO_MASKS: dict[float, np.ndarray] = {}_REFINED_MASKS: dict[float, np.ndarray] = {}_METRICS: dict[float, dict[str, Any]] = {}
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--video", type=Path, default=DEFAULT_VIDEO) parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--yolo-model", type=Path, default=DEFAULT_YOLO) parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_SAM) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--segmentation-source", type=Path, default=DEFAULT_SEGMENTATION_SOURCE) parser.add_argument("--device", default="cuda:0") args = parser.parse_args() args.reuse_segmentation = True return args
def load_v4_segmentation_cache( _out_dir: Path, ordered_times: list[float],) -> tuple[ dict[float, np.ndarray], dict[float, np.ndarray], dict[float, dict[str, Any]], list[dict[str, Any]],]: source = Path(load_v4_segmentation_cache.source_dir) return _ORIGINAL_LOAD_CACHE(source, ordered_times)
load_v4_segmentation_cache.source_dir = str(DEFAULT_SEGMENTATION_SOURCE)
def build_poses_v5( config: dict[str, Any], frames: dict[float, np.ndarray], frame_indices: dict[float, int], yolo_masks: dict[float, np.ndarray], refined_masks: dict[float, np.ndarray], metrics: dict[float, dict[str, Any]],) -> list[v3.Pose]: global _POSES_V5, _FRAMES, _FRAME_INDICES, _YOLO_MASKS, _REFINED_MASKS, _METRICS poses = _ORIGINAL_BUILD_POSES( config, frames, frame_indices, yolo_masks, refined_masks, metrics, ) height, width = frames[float(config["sample_times"][0])].shape[:2] overrides = { str(key): float(value) for key, value in config.get("pose_scale_overrides", {}).items() } adjusted: list[v3.Pose] = [] for pose in poses: scale = overrides.get(v3.config_key(pose.time), float(config["pose_scale"])) target = config["layout_targets_normalized"][v3.config_key(pose.time)] requested = (float(target[0]) * width, float(target[1]) * height) display_foot = v3.clamp_display_foot( requested, pose.source_bbox, pose.source_foot, scale, (height, width), config, ) adjusted.append( replace( pose, scale_factor=scale, display_foot_requested=requested, display_foot=display_foot, ) ) _POSES_V5 = adjusted _FRAMES = frames _FRAME_INDICES = frame_indices _YOLO_MASKS = yolo_masks _REFINED_MASKS = refined_masks _METRICS = metrics return adjusted
def add_annotation_v5(ax: Any, config: dict[str, Any], width: int, height: int) -> None: safe_width = v3.safe_x_limit(width, config) box_x, box_y = 0.014 * width, 0.118 * height # Keep the auxiliary note fully left of the elevated 56.5 s pose. box_w, box_h = 0.195 * width, 0.083 * height ax.add_patch( v3.FancyBboxPatch( (box_x, box_y), box_w, box_h, boxstyle="round,pad=0.012,rounding_size=12", facecolor=(0.02, 0.035, 0.050), edgecolor=(1, 1, 1, 0.34), lw=0.6, alpha=0.76, zorder=24, ) ) ax.text( box_x + 0.015 * width, box_y + 0.029 * height, "13 poses • five colour groups", color="white", fontsize=5.7, weight="bold", ha="left", va="center", zorder=25, ) scale_values = [float(config["pose_scale"])] + [ float(value) for value in config.get("pose_scale_overrides", {}).values() ] ax.text( box_x + 0.015 * width, box_y + 0.058 * height, f"scale ×{min(scale_values):.2f}–{max(scale_values):.2f} • 12% right reserve", color=(0.90, 0.92, 0.94), fontsize=5.0, ha="left", va="center", zorder=25, ) legend_left = 0.370 * width legend_right = safe_width - 0.012 * width slot = (legend_right - legend_left) / len(config["color_groups"]) for index, group in enumerate(config["color_groups"]): x = legend_left + (index + 0.5) * slot colour = v3.v1.hex_to_rgb(group["color"]) / 255.0 ax.scatter( [x], [box_y + 0.030 * height], s=18, c=[colour], edgecolors="white", linewidths=0.45, zorder=25, ) ax.text( x, box_y + 0.059 * height, str(group["label"]), color="white", fontsize=5.0, ha="center", va="center", zorder=25, )
def save_v4_v5_comparison( _v2_path: Path, v5_path: Path, safe_path: Path, _v2_v3_out_path: Path,) -> None: paths = [V4_ANNOTATED, v5_path, safe_path] images = [] for path in paths: image = cv2.imread(str(path)) if image is None: raise RuntimeError(f"Could not read comparison input: {path}") images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) figure = v3.plt.figure(figsize=(12.0, 7.5), dpi=300, facecolor="#F4F5F4") grid = figure.add_gridspec(2, 2, height_ratios=[1, 1.16], hspace=0.12, wspace=0.04) axes = [ figure.add_subplot(grid[0, 0]), figure.add_subplot(grid[0, 1]), figure.add_subplot(grid[1, :]), ] titles = [ "v4 • timing and background fixed", "v5 • scale-balanced staggered layout", "v5 crop-safety QA • rightmost 12% contains no final overlay", ] for axis, image, title in zip(axes, images, titles): axis.imshow(image) axis.set_title(title, fontsize=8.4, loc="left", pad=4, weight="bold", color="#28313A") axis.axis("off") figure.savefig( v5_path.parent / "comparison_v4_v5.jpg", dpi=300, facecolor=figure.get_facecolor(), bbox_inches="tight", pil_kwargs={"quality": 94}, ) v3.plt.close(figure)
def save_publication_figure_v5( canvas: np.ndarray, out_base: Path, config: dict[str, Any], annotated: bool,) -> None: height, width = canvas.shape[:2] width_mm = 183.0 width_mm = float(config.get("final_width_mm", width_mm)) png_dpi = int(config.get("png_dpi", 300)) tiff_dpi = 600 tiff_dpi = max(tiff_dpi, int(config.get("tiff_dpi", tiff_dpi))) width_in = width_mm / 25.4 height_in = width_in * height / width figure = v3.plt.figure(figsize=(width_in, height_in), dpi=png_dpi, facecolor="white") axis = figure.add_axes([0, 0, 1, 1]) axis.imshow(canvas) axis.set_xlim(0, width) axis.set_ylim(height, 0) axis.axis("off") if annotated: v4.add_timeline_v4(axis, config, width, height) add_annotation_v5(axis, config, width, height) for extension in ["png", "tiff", "svg", "pdf"]: path = out_base.with_suffix(f".{extension}") if extension == "png": figure.savefig(path, dpi=png_dpi, facecolor="white") elif extension == "tiff": figure.savefig(path, dpi=tiff_dpi, facecolor="white") with v3.Image.open(path) as rendered: rendered.convert("RGB").save( path, format="TIFF", compression="tiff_lzw", dpi=(tiff_dpi, tiff_dpi), ) else: figure.savefig(path, facecolor="white") if extension == "svg": lines = path.read_text(encoding="utf-8").splitlines() path.write_text("\n".join(line.rstrip() for line in lines) + "\n", encoding="utf-8") v3.plt.close(figure)
def export_final_publication_outputs(out_dir: Path, config: dict[str, Any]) -> None: layout_bgr = cv2.imread(str(out_dir / "composite_layout_rgb.png")) if layout_bgr is None: raise RuntimeError("Missing v5 composite layout for final export") layout_rgb = cv2.cvtColor(layout_bgr, cv2.COLOR_BGR2RGB) save_publication_figure_v5( layout_rgb, out_dir / f"{OUTPUT_STEM}_clean", config, annotated=False, ) save_publication_figure_v5( layout_rgb, out_dir / f"{OUTPUT_STEM}_annotated", config, annotated=True, ) for variant in ["clean", "annotated"]: for extension in ["png", "tiff", "svg", "pdf"]: intermediate = out_dir / f"trajectory_v3_custom_frames_{variant}.{extension}" if intermediate.exists(): intermediate.unlink()
def pose_visibility_metrics(poses: list[v3.Pose]) -> dict[str, Any]: if not poses: raise RuntimeError("No poses available for occlusion analysis") shape = poses[0].refined_mask.shape masks = {pose.time: v3.scaled_pose_mask(pose, shape) > 0 for pose in poses} occupancy = np.zeros(shape, dtype=np.uint16) for mask in masks.values(): occupancy += mask.astype(np.uint16) summed = int(occupancy.sum()) union = int((occupancy > 0).sum()) ordered = sorted(poses, key=lambda pose: pose.display_foot[1]) visibility: dict[str, float] = {} for index, pose in enumerate(ordered): later = np.zeros(shape, dtype=bool) for other in ordered[index + 1 :]: later |= masks[other.time] area = int(masks[pose.time].sum()) visible = int((masks[pose.time] & ~later).sum()) visibility[v3.config_key(pose.time)] = round(visible / area, 6) if area else 0.0 pair_rows = {} for first, second in [(6.0, 7.0), (31.0, 44.0), (32.0, 40.0)]: intersection = int((masks[first] & masks[second]).sum()) denominator = min(int(masks[first].sum()), int(masks[second].sum())) pair_rows[f"{first:g}-{second:g}"] = { "intersection_px": intersection, "intersection_over_smaller_pose": round(intersection / denominator, 6) if denominator else 0.0, } return { "redundant_overlap_fraction": round((summed - union) / summed, 6) if summed else 0.0, "maximum_stack_depth": int(occupancy.max()), "per_pose_visible_fraction": visibility, "target_pair_overlap": pair_rows, }
def save_occlusion_audit(config: dict[str, Any], out_dir: Path) -> dict[str, Any]: v4_config = v3.v2.load_json(V4_CONFIG) v4_poses = _ORIGINAL_BUILD_POSES( v4_config, _FRAMES, _FRAME_INDICES, _YOLO_MASKS, _REFINED_MASKS, _METRICS, ) before = pose_visibility_metrics(v4_poses) after = pose_visibility_metrics(_POSES_V5) before_overlap = float(before["redundant_overlap_fraction"]) after_overlap = float(after["redundant_overlap_fraction"]) report = { "pass": ( after_overlap < before_overlap and float(after["per_pose_visible_fraction"]["40"]) > 0.85 and float(after["per_pose_visible_fraction"]["44"]) > 0.85 ), "v4": before, "v5": after, "relative_redundant_overlap_reduction": round( (before_overlap - after_overlap) / before_overlap, 6, ), } if not report["pass"]: raise RuntimeError("V5 occlusion audit failed") v3.v2.write_json(out_dir / "occlusion_metrics.json", report) return report
def save_layout_change_audit(config: dict[str, Any], out_dir: Path) -> dict[str, Any]: parent = v3.v2.load_json(V4_CONFIG) rows = [] for time in [float(value) for value in config["sample_times"]]: key = v3.config_key(time) old_target = [float(value) for value in parent["layout_targets_normalized"][key]] new_target = [float(value) for value in config["layout_targets_normalized"][key]] old_scale = float(parent["pose_scale"]) new_scale = float(config.get("pose_scale_overrides", {}).get(key, config["pose_scale"])) rows.append( { "time_s": time, "v4_target_xy": old_target, "v5_target_xy": new_target, "delta_xy_px_at_2560x1440": [ round((new_target[0] - old_target[0]) * 2560.0, 3), round((new_target[1] - old_target[1]) * 1440.0, 3), ], "v4_scale": old_scale, "v5_scale": new_scale, } ) report = { "source_frames_unchanged": True, "colours_unchanged": [group["color"] for group in config["color_groups"]] == [group["color"] for group in parent["color_groups"]], "alpha_unchanged": config["alpha"] == parent["alpha"], "right_reserved_fraction_unchanged": config["right_reserved_fraction"] == parent["right_reserved_fraction"], "changes": rows, } v3.v2.write_json(out_dir / "layout_change_audit.json", report) return report
def repair_output_field_names(out_dir: Path) -> None: layout_path = out_dir / "layout_map.csv" text = layout_path.read_text(encoding="utf-8") layout_path.write_text( text.replace("uniform_scale_factor", "scale_factor", 1), encoding="utf-8", ) detections_path = out_dir / "detections_refined.json" detections = v3.v2.load_json(detections_path) for row in detections: row["scale_factor"] = row.pop("uniform_scale_factor") v3.v2.write_json(detections_path, detections)
def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def copy_reused_segmentation_artifacts(args: argparse.Namespace, out_dir: Path) -> None: source = args.segmentation_source.expanduser().resolve() for name in REUSED_SEGMENTATION_ARTIFACTS: source_path = source / name if not source_path.exists(): raise RuntimeError(f"Missing reused segmentation artifact: {source_path}") shutil.copy2(source_path, out_dir / name)
def save_reuse_audit(args: argparse.Namespace, out_dir: Path) -> dict[str, Any]: source = args.segmentation_source.expanduser().resolve() v4_background = cv2.imread(str(source / "background_plate.png")) v5_background = cv2.imread(str(out_dir / "background_plate.png")) if v4_background is None or v5_background is None or v4_background.shape != v5_background.shape: raise RuntimeError("Could not compare v4/v5 backgrounds") changed = int(np.any(v4_background != v5_background, axis=2).sum()) artifact_rows = {} for name in REUSED_SEGMENTATION_ARTIFACTS: source_hash = sha256(source / name) copied_hash = sha256(out_dir / name) artifact_rows[name] = { "source_sha256": source_hash, "copied_sha256": copied_hash, "identical": source_hash == copied_hash, } report = { "segmentation_source": v3.v2.display_path(source), "source_frame_times_unchanged": True, "segmentation_artifacts_identical": all( bool(row["identical"]) for row in artifact_rows.values() ), "segmentation_artifacts": artifact_rows, "background_changed_pixels": changed, "background_identical": changed == 0, "v4_background_sha256": sha256(source / "background_plate.png"), "v5_background_sha256": sha256(out_dir / "background_plate.png"), } if not report["background_identical"] or not report["segmentation_artifacts_identical"]: raise RuntimeError("V5 unexpectedly changed a reused v4 artifact") v3.v2.write_json(out_dir / "reuse_audit.json", report) return report
def update_run_metadata( config: dict[str, Any], out_dir: Path, occlusion: dict[str, Any], layout: dict[str, Any], reuse: dict[str, Any],) -> None: path = out_dir / "run_metadata.json" metadata = v3.v2.load_json(path) metadata.pop("uniform_pose_scale", None) metadata.update( { "parent_version": "v4-frame-timing-background-fix", "default_pose_scale": float(config["pose_scale"]), "pose_scale_overrides": config["pose_scale_overrides"], "pose_scale_range": [0.82, 0.96], "layout_change_audit": layout, "occlusion_audit": occlusion, "reuse_audit": reuse, "publication_output_stem": OUTPUT_STEM, } ) v3.v2.write_json(path, metadata)
def main() -> int: args = parse_args() load_v4_segmentation_cache.source_dir = str(args.segmentation_source.expanduser().resolve()) v3.parse_args = lambda: args v3.load_segmentation_cache = load_v4_segmentation_cache v3.build_poses = build_poses_v5 v3.v2.make_background = v4.make_background_v4 v3.add_timeline = v4.add_timeline_v4 v3.add_annotation = add_annotation_v5 v3.save_comparison = save_v4_v5_comparison return_code = v3.main() if return_code: return return_code
out_dir = args.out_dir.expanduser().resolve() config = v3.v2.load_json(args.config.expanduser().resolve()) export_final_publication_outputs(out_dir, config) copy_reused_segmentation_artifacts(args, out_dir) repair_output_field_names(out_dir) occlusion = save_occlusion_audit(config, out_dir) layout = save_layout_change_audit(config, out_dir) reuse = save_reuse_audit(args, out_dir) update_run_metadata(config, out_dir, occlusion, layout, reuse) print(f"Wrote v5 outputs to {out_dir}") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802#!/usr/bin/env python3"""Build the wide v7 figure by cropping v6 and uniformly shrinking every pose.
V7 keeps all v6 source frames, SAM masks, colours, alpha values, display order,near/far scale relationships, repaired background, and the rightmost 12%reserve. Every v6 pose scale is multiplied by one shared factor, while thefar-field row is moved down as a unit so that a strict top-third crop does notclip any robot. The final 2560 x 960 composition is exported at 183 mm width."""
from __future__ import annotations
import argparseimport csvimport hashlibimport mathimport shutilfrom pathlib import Pathfrom typing import Any
import cv2import numpy as np
import build_trajectory_figure_v3 as v3import build_trajectory_figure_v5 as v5import build_trajectory_figure_v6 as v6
PROJECT_ROOT = Path(__file__).resolve().parents[2]DEFAULT_VIDEO = PROJECT_ROOT / "source" / "CLIP_P0010073.mov"DEFAULT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v7_wide_crop_uniform_scale.json"DEFAULT_YOLO = PROJECT_ROOT / "trajectory_project" / "models" / "yolov8x-seg.pt"DEFAULT_SAM = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v7_wide_crop_uniform_scale"PARENT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v6_grounded_uniform_layout.json"PARENT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v6_grounded_uniform_layout"PARENT_CLEAN = PARENT_OUT / "trajectory_v6_grounded_uniform_clean.png"PARENT_ANNOTATED = PARENT_OUT / "trajectory_v6_grounded_uniform_annotated.png"OUTPUT_STEM = "trajectory_v7_wide_crop"FINAL_WIDTH_MM = 183.0PNG_DPI = 300TIFF_DPI = 600PUBLICATION_SUFFIXES = (".png", ".tiff", ".svg", ".pdf")_ORIGINAL_V6_RENDER = v6.render_layout_v6_ORIGINAL_VALIDATE_CONFIG = v3.validate_config
v3.matplotlib.rcParams.update( { "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], "font.size": 7, "svg.fonttype": "none", "pdf.fonttype": 42, })
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--video", type=Path, default=DEFAULT_VIDEO) parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--yolo-model", type=Path, default=DEFAULT_YOLO) parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_SAM) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--segmentation-source", type=Path, default=PARENT_OUT) parser.add_argument("--device", default="cuda:0") args = parser.parse_args() args.reuse_segmentation = True return args
def config_scale(config: dict[str, Any], time: float) -> float: key = v3.config_key(time) return float(config.get("pose_scale_overrides", {}).get(key, config["pose_scale"]))
def crop_top_px(config: dict[str, Any], full_height: int) -> int: fraction = float(config["crop_top_fraction"]) if not 0.0 < fraction < 1.0: raise ValueError("crop_top_fraction must be between zero and one") return int(round(full_height * fraction))
def render_layout_v7( background: np.ndarray, poses: list[v3.Pose], config: dict[str, Any],) -> np.ndarray: """Render the complete source canvas; the publication crop is applied once later.""" return _ORIGINAL_V6_RENDER(background, poses, config)
def validate_config_v7(config: dict[str, Any]) -> None: """Retain the v3 semantic checks while allowing the deliberate v7 reduction.""" proxy = dict(config) proxy["pose_scale"] = 0.92 _ORIGINAL_VALIDATE_CONFIG(proxy) scales = [ config_scale(config, float(time)) for time in config["sample_times"] ] if not all(0.50 <= value <= 1.0 for value in scales): raise RuntimeError("V7 pose scales must remain between 0.50 and 1.0") if not 0.5 <= float(config["parent_pose_scale_multiplier"]) <= 1.0: raise RuntimeError("parent_pose_scale_multiplier must be between 0.5 and 1.0") crop_top_px(config, 1440)
def defer_comparison( _parent_path: Path, _current_path: Path, _safe_path: Path, _unused_path: Path,) -> None: """The aspect-ratio-aware v6/v7 comparison is generated after the wide export."""
def bbox_for_pose(pose: v3.Pose) -> tuple[float, float, float, float]: left, top, right, bottom = v3.scaled_bbox_offsets( pose.source_bbox, pose.source_foot, pose.scale_factor, ) return ( pose.display_foot[0] - left, pose.display_foot[1] - top, pose.display_foot[0] + right, pose.display_foot[1] + bottom, )
def scale_multiplier_audit( parent_config: dict[str, Any], config: dict[str, Any],) -> dict[str, Any]: expected = float(config["parent_pose_scale_multiplier"]) rows = [] for time in [float(value) for value in config["sample_times"]]: parent_scale = config_scale(parent_config, time) current_scale = config_scale(config, time) ratio = current_scale / parent_scale rows.append( { "time_s": time, "v6_scale": parent_scale, "v7_scale": current_scale, "v7_over_v6": round(ratio, 8), "matches_shared_multiplier": abs(ratio - expected) <= 1e-8, } ) ratios = [float(row["v7_over_v6"]) for row in rows] return { "expected_shared_multiplier": expected, "observed_min_multiplier": min(ratios), "observed_max_multiplier": max(ratios), "multiplier_range": round(max(ratios) - min(ratios), 10), "poses": rows, "pass": all(bool(row["matches_shared_multiplier"]) for row in rows), }
def crop_fit_audit( poses: list[v3.Pose], config: dict[str, Any],) -> dict[str, Any]: full_height, full_width = poses[0].refined_mask.shape crop_y = crop_top_px(config, full_height) rows = [] for pose in poses: left, top, right, bottom = bbox_for_pose(pose) rows.append( { "time_s": pose.time, "full_bbox_xyxy": [ round(left, 3), round(top, 3), round(right, 3), round(bottom, 3), ], "wide_bbox_xyxy": [ round(left, 3), round(top - crop_y, 3), round(right, 3), round(bottom - crop_y, 3), ], "top_margin_inside_crop_px": round(top - crop_y, 3), "bottom_margin_inside_crop_px": round(full_height - bottom, 3), } ) minimum_top_margin = min(float(row["top_margin_inside_crop_px"]) for row in rows) minimum_bottom_margin = min(float(row["bottom_margin_inside_crop_px"]) for row in rows) return { "full_canvas_width_px": full_width, "full_canvas_height_px": full_height, "crop_top_y_px": crop_y, "crop_top_fraction": float(config["crop_top_fraction"]), "wide_canvas_width_px": full_width, "wide_canvas_height_px": full_height - crop_y, "minimum_pose_top_margin_px": round(minimum_top_margin, 3), "minimum_pose_bottom_margin_px": round(minimum_bottom_margin, 3), "poses": rows, "pass": minimum_top_margin >= 4.0 and minimum_bottom_margin >= 0.0, }
def save_occlusion_audit(config: dict[str, Any], out_dir: Path) -> dict[str, Any]: parent_config = v3.v2.load_json(PARENT_CONFIG) current_poses = list(v5._POSES_V5) try: parent_poses = v5.build_poses_v5( parent_config, v5._FRAMES, v5._FRAME_INDICES, v5._YOLO_MASKS, v5._REFINED_MASKS, v5._METRICS, ) finally: v5._POSES_V5 = current_poses before = v5.pose_visibility_metrics(parent_poses) after = v5.pose_visibility_metrics(current_poses) row_layout = v6.row_layout_metrics(current_poses, config) path_overlay = v6.path_overlay_metrics(current_poses, config) scale_audit = scale_multiplier_audit(parent_config, config) crop_audit = crop_fit_audit(current_poses, config) before_overlap = float(before["redundant_overlap_fraction"]) after_overlap = float(after["redundant_overlap_fraction"]) minimum_visible = min(float(value) for value in after["per_pose_visible_fraction"].values()) report = { "pass": ( row_layout["pass"] and scale_audit["pass"] and crop_audit["pass"] and after_overlap <= before_overlap and int(after["maximum_stack_depth"]) <= 2 and minimum_visible >= 0.62 and bool(path_overlay["foreground_redraw_enabled"]) ), "v6": before, "v7": after, "minimum_v7_visible_fraction": round(minimum_visible, 6), "row_layout": row_layout, "scale_multiplier": scale_audit, "crop_fit": crop_audit, "path_overlay": path_overlay, "relative_redundant_overlap_reduction_vs_v6": round( (before_overlap - after_overlap) / before_overlap, 6, ) if before_overlap else 0.0, } if not report["pass"]: raise RuntimeError("V7 wide-layout audit failed") v3.v2.write_json(out_dir / "occlusion_metrics.json", report) v3.v2.write_json(out_dir / "row_layout_metrics.json", row_layout) v3.v2.write_json(out_dir / "scale_multiplier_metrics.json", scale_audit) v3.v2.write_json(out_dir / "crop_fit_metrics.json", crop_audit) v3.v2.write_json(out_dir / "path_overlay_metrics.json", path_overlay) return report
def save_layout_change_audit(config: dict[str, Any], out_dir: Path) -> dict[str, Any]: parent = v3.v2.load_json(PARENT_CONFIG) scale_audit = scale_multiplier_audit(parent, config) rows = [] for time in [float(value) for value in config["sample_times"]]: key = v3.config_key(time) old_target = [float(value) for value in parent["layout_targets_normalized"][key]] new_target = [float(value) for value in config["layout_targets_normalized"][key]] rows.append( { "time_s": time, "v6_target_xy": old_target, "v7_target_xy": new_target, "delta_xy_px_at_2560x1440": [ round((new_target[0] - old_target[0]) * 2560.0, 3), round((new_target[1] - old_target[1]) * 1440.0, 3), ], "v6_scale": config_scale(parent, time), "v7_scale": config_scale(config, time), "v7_over_v6_scale": round( config_scale(config, time) / config_scale(parent, time), 8, ), } ) changed_position_times = [ row["time_s"] for row in rows if any(abs(float(value)) > 0.01 for value in row["delta_xy_px_at_2560x1440"]) ] report = { "source_frames_unchanged": config["sample_times"] == parent["sample_times"], "colours_unchanged": [group["color"] for group in config["color_groups"]] == [group["color"] for group in parent["color_groups"]], "alpha_unchanged": config["alpha"] == parent["alpha"], "right_reserved_fraction_unchanged": config["right_reserved_fraction"] == parent["right_reserved_fraction"], "x_targets_unchanged": all( abs(float(row["delta_xy_px_at_2560x1440"][0])) <= 0.01 for row in rows ), "changed_position_times_s": changed_position_times, "shared_pose_scale_multiplier": float(config["parent_pose_scale_multiplier"]), "all_scales_share_one_multiplier": bool(scale_audit["pass"]), "changes": rows, } v3.v2.write_json(out_dir / "layout_change_audit.json", report) return report
def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest()
def save_reuse_audit(args: argparse.Namespace, out_dir: Path) -> dict[str, Any]: source = args.segmentation_source.expanduser().resolve() parent_background = cv2.imread(str(source / "background_plate.png")) current_background = cv2.imread(str(out_dir / "background_plate.png")) if ( parent_background is None or current_background is None or parent_background.shape != current_background.shape ): raise RuntimeError("Could not compare v6/v7 backgrounds") changed = int(np.any(parent_background != current_background, axis=2).sum()) artifacts = {} for name in v5.REUSED_SEGMENTATION_ARTIFACTS: source_hash = sha256(source / name) copied_hash = sha256(out_dir / name) artifacts[name] = { "source_sha256": source_hash, "copied_sha256": copied_hash, "identical": source_hash == copied_hash, } report = { "parent_version": "v6-grounded-uniform-layout", "segmentation_source": v3.v2.display_path(source), "source_frame_times_unchanged": True, "segmentation_artifacts_identical": all(row["identical"] for row in artifacts.values()), "segmentation_artifacts": artifacts, "background_changed_pixels": changed, "background_identical": changed == 0, "parent_background_sha256": sha256(source / "background_plate.png"), "v7_background_sha256": sha256(out_dir / "background_plate.png"), } if not report["background_identical"] or not report["segmentation_artifacts_identical"]: raise RuntimeError("V7 unexpectedly changed a reused v6 artifact") v3.v2.write_json(out_dir / "reuse_audit.json", report) return report
def update_run_metadata( config: dict[str, Any], out_dir: Path, occlusion: dict[str, Any], layout: dict[str, Any], reuse: dict[str, Any],) -> None: path = out_dir / "run_metadata.json" metadata = v3.v2.load_json(path) metadata.pop("uniform_pose_scale", None) scales = [config_scale(config, float(time)) for time in config["sample_times"]] metadata.update( { "parent_version": "v6-grounded-uniform-layout", "default_pose_scale": float(config["pose_scale"]), "pose_scale_overrides": config["pose_scale_overrides"], "pose_scale_range": [min(scales), max(scales)], "parent_pose_scale_multiplier": float(config["parent_pose_scale_multiplier"]), "crop_top_fraction": float(config["crop_top_fraction"]), "layout_change_audit": layout, "occlusion_audit": occlusion, "reuse_audit": reuse, "publication_output_stem": OUTPUT_STEM, "publication_export_suffixes": list(PUBLICATION_SUFFIXES), "final_width_mm": FINAL_WIDTH_MM, "png_dpi": PNG_DPI, "tiff_dpi": TIFF_DPI, } ) v3.v2.write_json(path, metadata)
def save_publication_figure( canvas_rgb: np.ndarray, out_base: Path, config: dict[str, Any], annotated: bool,) -> None: height, width = canvas_rgb.shape[:2] width_mm = float(config.get("final_width_mm", FINAL_WIDTH_MM)) png_dpi = int(config.get("png_dpi", PNG_DPI)) tiff_dpi = max(TIFF_DPI, int(config.get("tiff_dpi", TIFF_DPI))) width_in = width_mm / 25.4 height_in = width_in * height / width figure = v3.plt.figure(figsize=(width_in, height_in), dpi=png_dpi, facecolor="white") axis = figure.add_axes([0, 0, 1, 1]) axis.imshow(canvas_rgb) axis.set_xlim(0, width) axis.set_ylim(height, 0) axis.axis("off") if annotated: v5.v4.add_timeline_v4(axis, config, width, height) v5.add_annotation_v5(axis, config, width, height) for extension in ["png", "tiff", "svg", "pdf"]: path = out_base.with_suffix(f".{extension}") if extension == "png": figure.savefig(path, dpi=png_dpi, facecolor="white") elif extension == "tiff": figure.savefig(path, dpi=tiff_dpi, facecolor="white") with v3.Image.open(path) as rendered: rendered.convert("RGB").save( path, format="TIFF", compression="tiff_lzw", dpi=(tiff_dpi, tiff_dpi), ) else: figure.savefig(path, facecolor="white") if extension == "svg": lines = path.read_text(encoding="utf-8").splitlines() path.write_text( "\n".join(line.rstrip() for line in lines) + "\n", encoding="utf-8", ) v3.plt.close(figure)
def save_wide_layout_map(out_dir: Path, crop_y: int) -> None: source = out_dir / "layout_map.csv" with source.open("r", encoding="utf-8", newline="") as handle: rows = list(csv.DictReader(handle)) if not rows: raise RuntimeError("layout_map.csv is empty") fields = list(rows[0]) additions = [ "crop_top_y_px", "display_foot_y_wide_px", "scaled_bbox_y1_wide", "scaled_bbox_y2_wide", ] with (out_dir / "layout_map_wide.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fields + additions, lineterminator="\n") writer.writeheader() for row in rows: row.update( { "crop_top_y_px": f"{crop_y:d}", "display_foot_y_wide_px": f"{float(row['display_foot_y_px']) - crop_y:.3f}", "scaled_bbox_y1_wide": f"{float(row['scaled_bbox_y1']) - crop_y:.3f}", "scaled_bbox_y2_wide": f"{float(row['scaled_bbox_y2']) - crop_y:.3f}", } ) writer.writerow(row)
def save_wide_safe_area_qa( canvas_rgb: np.ndarray, background_rgb: np.ndarray, config: dict[str, Any], out_dir: Path,) -> dict[str, Any]: height, width = canvas_rgb.shape[:2] boundary = v3.safe_x_limit(width, config) boundary_floor = int(math.floor(boundary)) difference = np.max( np.abs(canvas_rgb.astype(np.int16) - background_rgb.astype(np.int16)), axis=2, ) > 2 yy, xx = np.where(difference) maximum_changed_x = int(xx.max()) if len(xx) else -1 reserved_changed = int(difference[:, int(math.ceil(boundary)) :].sum())
clean = cv2.imread(str(out_dir / f"{OUTPUT_STEM}_clean.png"), cv2.IMREAD_UNCHANGED) annotated = cv2.imread(str(out_dir / f"{OUTPUT_STEM}_annotated.png"), cv2.IMREAD_UNCHANGED) if clean is None or annotated is None or clean.shape != annotated.shape: raise RuntimeError("Could not compare final v7 clean/annotated PNG files") png_boundary = int( math.ceil(clean.shape[1] * (1.0 - float(config["right_reserved_fraction"]))) ) annotation_difference = np.max( np.abs(annotated.astype(np.int16) - clean.astype(np.int16)), axis=2, ) > 2 annotated_reserved_changed = int(annotation_difference[:, png_boundary:].sum()) report = { "image_width_px": width, "image_height_px": height, "right_reserved_fraction": float(config["right_reserved_fraction"]), "overlay_safe_x_limit_px": round(boundary, 3), "maximum_changed_overlay_x_px": maximum_changed_x, "changed_pixels_inside_reserved_zone": reserved_changed, "annotated_changed_pixels_inside_reserved_zone": annotated_reserved_changed, "pass": bool( maximum_changed_x < boundary_floor and reserved_changed == 0 and annotated_reserved_changed == 0 ), } guide = canvas_rgb.copy() red = np.array([213, 70, 66], dtype=np.float32) zone = guide[:, boundary_floor:].astype(np.float32) guide[:, boundary_floor:] = np.clip( zone * 0.56 + red[None, None, :] * 0.44, 0, 255, ).astype(np.uint8) cv2.line( guide, (boundary_floor, 0), (boundary_floor, height - 1), (255, 255, 255), 4, lineType=cv2.LINE_AA, ) cv2.putText( guide, "12% reserved: no final overlay", (boundary_floor + 14, 42), cv2.FONT_HERSHEY_SIMPLEX, 0.56, (255, 255, 255), 2, cv2.LINE_AA, ) cv2.imwrite(str(out_dir / "safe_area_qa.png"), cv2.cvtColor(guide, cv2.COLOR_RGB2BGR)) v3.v2.write_json(out_dir / "safe_area_metrics.json", report) if not report["pass"]: raise RuntimeError("V7 wide safe-area audit failed") return report
def save_crop_window_preview(parent_rgb: np.ndarray, crop_y: int, out_dir: Path) -> Path: preview = parent_rgb.copy() overlay = preview.copy() overlay[:crop_y] = np.array([196, 76, 70], dtype=np.uint8) preview[:crop_y] = np.clip( preview[:crop_y].astype(np.float32) * 0.42 + overlay[:crop_y].astype(np.float32) * 0.58, 0, 255, ).astype(np.uint8) cv2.line(preview, (0, crop_y), (preview.shape[1] - 1, crop_y), (255, 255, 255), 5) cv2.putText( preview, "top one-third removed", (30, max(42, crop_y - 24)), cv2.FONT_HERSHEY_SIMPLEX, 0.82, (255, 255, 255), 2, cv2.LINE_AA, ) path = out_dir / "crop_window_on_full_canvas.png" cv2.imwrite(str(path), cv2.cvtColor(preview, cv2.COLOR_RGB2BGR)) return path
def save_v6_v7_comparison( crop_preview_path: Path, current_path: Path, out_dir: Path,) -> None: paths = [PARENT_CLEAN, crop_preview_path, current_path] images = [] for path in paths: image = cv2.imread(str(path)) if image is None: raise RuntimeError(f"Could not read comparison input: {path}") images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) figure = v3.plt.figure(figsize=(12.0, 8.4), dpi=300, facecolor="#F4F5F4") grid = figure.add_gridspec(3, 1, height_ratios=[1.0, 1.0, 0.72], hspace=0.16) axes = [figure.add_subplot(grid[index, 0]) for index in range(3)] titles = [ "v6 • 16:9 grounded layout", "v7 crop window • exact top one-third removed", "v7 • 8:3 wide layout + shared ×0.78 pose multiplier", ] for axis, image, title in zip(axes, images, titles): axis.imshow(image) axis.set_title( title, fontsize=8.4, loc="left", pad=4, weight="bold", color="#28313A", ) axis.axis("off") figure.savefig( out_dir / "comparison_v6_v7.jpg", dpi=300, facecolor=figure.get_facecolor(), bbox_inches="tight", pil_kwargs={"quality": 94}, ) v3.plt.close(figure)
def publication_artifact_audit( out_dir: Path, config: dict[str, Any], crop_y: int,) -> dict[str, Any]: variants = {} for variant in ["clean", "annotated"]: rows = {} for extension in PUBLICATION_SUFFIXES: path = out_dir / f"{OUTPUT_STEM}_{variant}{extension}" if not path.exists() or path.stat().st_size == 0: raise RuntimeError(f"Missing publication artifact: {path}") rows[extension.lstrip(".")] = { "bytes": path.stat().st_size, "sha256": sha256(path), } with v3.Image.open(out_dir / f"{OUTPUT_STEM}_{variant}.png") as image: rows["png"].update( { "width_px": image.width, "height_px": image.height, "mode": image.mode, "dpi": [round(float(value), 3) for value in image.info.get("dpi", (0, 0))], } ) with v3.Image.open(out_dir / f"{OUTPUT_STEM}_{variant}.tiff") as image: rows["tiff"].update( { "width_px": image.width, "height_px": image.height, "mode": image.mode, "compression": image.info.get("compression"), "dpi": [round(float(value), 3) for value in image.info.get("dpi", (0, 0))], } ) variants[variant] = rows width_in = float(config["final_width_mm"]) / 25.4 aspect = (1440 - crop_y) / 2560 expected_png_width = int(width_in * int(config["png_dpi"])) expected_png_height = int(width_in * aspect * int(config["png_dpi"])) expected_tiff_width = int(width_in * int(config["tiff_dpi"])) expected_tiff_height = int(width_in * aspect * int(config["tiff_dpi"])) clean_png = variants["clean"]["png"] clean_tiff = variants["clean"]["tiff"] report = { "expected_png_size_px": [expected_png_width, expected_png_height], "variants": variants, "pass": bool( clean_png["width_px"] == expected_png_width and clean_png["height_px"] == expected_png_height and clean_tiff["width_px"] == expected_tiff_width and clean_tiff["height_px"] == expected_tiff_height and clean_tiff["mode"] == "RGB" and clean_tiff["compression"] == "tiff_lzw" ), } if not report["pass"]: raise RuntimeError("V7 publication artifact audit failed") v3.v2.write_json(out_dir / "publication_artifact_metrics.json", report) return report
def postprocess_wide_outputs( out_dir: Path, config: dict[str, Any], occlusion: dict[str, Any],) -> None: full_layout_bgr = cv2.imread(str(out_dir / "composite_layout_rgb.png")) full_background_bgr = cv2.imread(str(out_dir / "background_plate.png")) if full_layout_bgr is None or full_background_bgr is None: raise RuntimeError("Missing full-canvas v7 render") if full_layout_bgr.shape != full_background_bgr.shape: raise RuntimeError("Full layout and background dimensions do not match") full_layout_rgb = cv2.cvtColor(full_layout_bgr, cv2.COLOR_BGR2RGB) full_background_rgb = cv2.cvtColor(full_background_bgr, cv2.COLOR_BGR2RGB) crop_y = crop_top_px(config, full_layout_rgb.shape[0]) wide_layout_rgb = full_layout_rgb[crop_y:].copy() wide_background_rgb = full_background_rgb[crop_y:].copy()
shutil.copy2( out_dir / "composite_layout_rgb.png", out_dir / "composite_layout_full_rgb.png", ) cv2.imwrite( str(out_dir / "composite_layout_wide_rgb.png"), cv2.cvtColor(wide_layout_rgb, cv2.COLOR_RGB2BGR), ) cv2.imwrite( str(out_dir / "background_plate_wide.png"), cv2.cvtColor(wide_background_rgb, cv2.COLOR_RGB2BGR), )
save_publication_figure( wide_layout_rgb, out_dir / f"{OUTPUT_STEM}_clean", config, annotated=False, ) save_publication_figure( wide_layout_rgb, out_dir / f"{OUTPUT_STEM}_annotated", config, annotated=True, ) save_wide_layout_map(out_dir, crop_y)
full_safe_path = out_dir / "safe_area_qa.png" full_safe_metrics_path = out_dir / "safe_area_metrics.json" if full_safe_path.exists(): full_safe_path.replace(out_dir / "safe_area_full_qa.png") if full_safe_metrics_path.exists(): full_safe_metrics_path.replace(out_dir / "safe_area_full_metrics.json") safe_report = save_wide_safe_area_qa( wide_layout_rgb, wide_background_rgb, config, out_dir, ) crop_preview = save_crop_window_preview(full_layout_rgb, crop_y, out_dir) save_v6_v7_comparison( crop_preview, out_dir / f"{OUTPUT_STEM}_clean.png", out_dir, ) artifact_report = publication_artifact_audit(out_dir, config, crop_y)
crop_report = { "full_canvas_size_px": [full_layout_rgb.shape[1], full_layout_rgb.shape[0]], "crop_top_y_px": crop_y, "requested_crop_top_fraction": float(config["crop_top_fraction"]), "actual_removed_fraction": round(crop_y / full_layout_rgb.shape[0], 8), "wide_canvas_size_px": [wide_layout_rgb.shape[1], wide_layout_rgb.shape[0]], "aspect_ratio": round(wide_layout_rgb.shape[1] / wide_layout_rgb.shape[0], 6), "height_reduction_fraction": round( 1.0 - wide_layout_rgb.shape[0] / full_layout_rgb.shape[0], 8, ), "pose_crop_fit": occlusion["crop_fit"], "safe_area": safe_report, "publication_artifacts": artifact_report, "pass": bool( occlusion["crop_fit"]["pass"] and safe_report["pass"] and artifact_report["pass"] and wide_layout_rgb.shape[:2] == (960, 2560) ), } if not crop_report["pass"]: raise RuntimeError("V7 crop/export audit failed") v3.v2.write_json(out_dir / "crop_metrics.json", crop_report)
metadata_path = out_dir / "run_metadata.json" metadata = v3.v2.load_json(metadata_path) metadata.update( { "full_render_size_px": [full_layout_rgb.shape[1], full_layout_rgb.shape[0]], "crop_top_y_px": crop_y, "wide_render_size_px": [wide_layout_rgb.shape[1], wide_layout_rgb.shape[0]], "wide_aspect_ratio": crop_report["aspect_ratio"], "crop_audit": crop_report, } ) v3.v2.write_json(metadata_path, metadata)
def install_v7_hooks() -> None: v3.validate_config = validate_config_v7 v6.DEFAULT_CONFIG = DEFAULT_CONFIG v6.DEFAULT_OUT = DEFAULT_OUT v6.PARENT_CONFIG = PARENT_CONFIG v6.PARENT_OUT = PARENT_OUT v6.PARENT_ANNOTATED = PARENT_ANNOTATED v6.OUTPUT_STEM = OUTPUT_STEM v6.parse_args = parse_args v6.render_layout_v6 = render_layout_v7 v6.save_v5_v6_comparison = defer_comparison v6.save_occlusion_audit = save_occlusion_audit v6.save_layout_change_audit = save_layout_change_audit v6.save_reuse_audit = save_reuse_audit v6.update_run_metadata = update_run_metadata
def main() -> int: args = parse_args() install_v7_hooks() return_code = v6.main() if return_code: return return_code out_dir = args.out_dir.expanduser().resolve() config = v3.v2.load_json(args.config.expanduser().resolve()) occlusion = v3.v2.load_json(out_dir / "occlusion_metrics.json") postprocess_wide_outputs(out_dir, config, occlusion) print(f"Wrote v7 wide outputs to {out_dir}") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972#!/usr/bin/env python3"""Build v8 with a contrastive metallic colour grade on the locked v7 layout.
V8 changes only the five group colours and the foreground colour-transferfunction. The transfer preserves the source-frame L* structure and more thanhalf of the source chroma/detail contribution, so the G1 remains metallicinstead of becoming a pale flat silhouette. Source frames, SAM masks, crop,pose positions, scales, opacity, z-order, paths, shadows, background, and therightmost 12% reserve remain identical to v7."""
from __future__ import annotations
import argparseimport copyimport hashlibimport mathfrom pathlib import Pathfrom typing import Any, Callable
import cv2import numpy as npfrom matplotlib.patches import Rectangle
import build_trajectory_figure_v7 as v7
v3 = v7.v3v5 = v7.v5v6 = v7.v6
PROJECT_ROOT = Path(__file__).resolve().parents[2]DEFAULT_VIDEO = PROJECT_ROOT / "source" / "CLIP_P0010073.mov"DEFAULT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v8_metallic_contrast_palette.json"DEFAULT_YOLO = PROJECT_ROOT / "trajectory_project" / "models" / "yolov8x-seg.pt"DEFAULT_SAM = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v8_metallic_contrast_palette"PARENT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v7_wide_crop_uniform_scale.json"PARENT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v7_wide_crop_uniform_scale"PARENT_CLEAN = PARENT_OUT / "trajectory_v7_wide_crop_clean.png"PARENT_ANNOTATED = PARENT_OUT / "trajectory_v7_wide_crop_annotated.png"OUTPUT_STEM = "trajectory_v8_metallic_contrast"FINAL_WIDTH_MM = 183.0PNG_DPI = 300TIFF_DPI = 600PUBLICATION_SUFFIXES = (".png", ".tiff", ".svg", ".pdf")_ORIGINAL_COLORIZE: Callable[[np.ndarray, np.ndarray], np.ndarray] = ( v3.v1.colorize_foreground)_ORIGINAL_V6_RENDER = v7._ORIGINAL_V6_RENDER_COLOR_STYLE: dict[str, float | str] = { "name": "metallic-lab-chroma", "source_chroma_weight": 0.45, "group_chroma_weight": 0.55, "lightness_lift_lstar": 1.5, "source_rgb_detail_weight": 0.15,}
v3.matplotlib.rcParams.update( { "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], "font.size": 7, "svg.fonttype": "none", "pdf.fonttype": 42, })
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--video", type=Path, default=DEFAULT_VIDEO) parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--yolo-model", type=Path, default=DEFAULT_YOLO) parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_SAM) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--segmentation-source", type=Path, default=PARENT_OUT) parser.add_argument("--device", default="cuda:0") args = parser.parse_args() args.reuse_segmentation = True return args
def configure_colour_style(config: dict[str, Any]) -> None: global _COLOR_STYLE _COLOR_STYLE = dict(config["foreground_color_style"])
def metallic_colorize_foreground( frame_bgr: np.ndarray, color: np.ndarray,) -> np.ndarray: """Shift chroma in CIELAB while preserving the source metallic lightness.""" rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB).astype(np.float32) source_lab = cv2.cvtColor(rgb / 255.0, cv2.COLOR_RGB2LAB) target_rgb = color.astype(np.float32).reshape(1, 1, 3) / 255.0 target_lab = cv2.cvtColor(target_rgb, cv2.COLOR_RGB2LAB)[0, 0] source_chroma_weight = float(_COLOR_STYLE["source_chroma_weight"]) group_chroma_weight = float(_COLOR_STYLE["group_chroma_weight"]) lightness_lift = float(_COLOR_STYLE["lightness_lift_lstar"]) detail_weight = float(_COLOR_STYLE["source_rgb_detail_weight"]) graded_lab = source_lab.copy() graded_lab[..., 0] = np.clip(source_lab[..., 0] + lightness_lift, 0.0, 100.0) graded_lab[..., 1] = ( source_chroma_weight * source_lab[..., 1] + group_chroma_weight * target_lab[1] ) graded_lab[..., 2] = ( source_chroma_weight * source_lab[..., 2] + group_chroma_weight * target_lab[2] ) graded_rgb = np.clip( cv2.cvtColor(graded_lab, cv2.COLOR_LAB2RGB) * 255.0, 0, 255, ) return np.clip( detail_weight * rgb + (1.0 - detail_weight) * graded_rgb, 0, 255, ).astype(np.uint8)
def render_layout_v8( background: np.ndarray, poses: list[v3.Pose], config: dict[str, Any],) -> np.ndarray: """Use the unchanged v6/v7 geometry renderer with the v8 tint function.""" return _ORIGINAL_V6_RENDER(background, poses, config)
def validate_config_v8(config: dict[str, Any]) -> None: v7.validate_config_v7(config) style = config.get("foreground_color_style", {}) required = { "name", "source_chroma_weight", "group_chroma_weight", "lightness_lift_lstar", "source_rgb_detail_weight", } if set(style) != required: raise RuntimeError("V8 foreground_color_style fields are incomplete") source_chroma = float(style["source_chroma_weight"]) group_chroma = float(style["group_chroma_weight"]) if not 0.35 <= source_chroma <= 0.70: raise RuntimeError("source_chroma_weight must be between 0.35 and 0.70") if not 0.30 <= group_chroma <= 0.65: raise RuntimeError("group_chroma_weight must be between 0.30 and 0.65") if abs(source_chroma + group_chroma - 1.0) > 1e-8: raise RuntimeError("source and group chroma weights must sum to one") if not -3.0 <= float(style["lightness_lift_lstar"]) <= 3.0: raise RuntimeError("lightness_lift_lstar must be between -3 and 3") if not 0.0 <= float(style["source_rgb_detail_weight"]) <= 0.35: raise RuntimeError("source_rgb_detail_weight must be between 0 and 0.35") colours = [str(group["color"]).upper() for group in config["color_groups"]] if len(colours) != len(set(colours)): raise RuntimeError("V8 colour groups must use five distinct colours")
def _parent_poses(parent_config: dict[str, Any]) -> list[v3.Pose]: current_poses = list(v5._POSES_V5) try: return v5.build_poses_v5( parent_config, v5._FRAMES, v5._FRAME_INDICES, v5._YOLO_MASKS, v5._REFINED_MASKS, v5._METRICS, ) finally: v5._POSES_V5 = current_poses
def _non_colour_config(config: dict[str, Any]) -> dict[str, Any]: payload = copy.deepcopy(config) payload.pop("version", None) payload.pop("foreground_color_style", None) for group in payload["color_groups"]: group["color"] = "__COLOUR_LOCK_IGNORED__" return payload
def _array_sha256(array: np.ndarray) -> str: return hashlib.sha256(np.ascontiguousarray(array).view(np.uint8)).hexdigest()
def _pose_geometry(pose: v3.Pose) -> dict[str, Any]: return { "time_s": pose.time, "frame_index": pose.frame_index, "source_bbox": [float(value) for value in pose.source_bbox], "source_foot": [float(value) for value in pose.source_foot], "display_foot_requested": [ float(value) for value in pose.display_foot_requested ], "display_foot": [float(value) for value in pose.display_foot], "scale_factor": float(pose.scale_factor), "hero": bool(pose.hero), "mask_sha256": _array_sha256(pose.refined_mask), }
def geometry_lock_audit( parent_config: dict[str, Any], config: dict[str, Any], parent_poses: list[v3.Pose], current_poses: list[v3.Pose],) -> dict[str, Any]: parent_by_time = {pose.time: pose for pose in parent_poses} current_by_time = {pose.time: pose for pose in current_poses} rows = [] for time in [float(value) for value in config["sample_times"]]: old = _pose_geometry(parent_by_time[time]) new = _pose_geometry(current_by_time[time]) rows.append( { "time_s": time, "v7_display_foot": old["display_foot"], "v8_display_foot": new["display_foot"], "v7_scale": old["scale_factor"], "v8_scale": new["scale_factor"], "position_delta_px": [ round( float(new["display_foot"][axis]) - float(old["display_foot"][axis]), 10, ) for axis in range(2) ], "scale_delta": round( float(new["scale_factor"]) - float(old["scale_factor"]), 12, ), "source_and_geometry_identical": old == new, } ) parent_group_structure = [ { "id": group["id"], "times": group["times"], "label": group["label"], } for group in parent_config["color_groups"] ] current_group_structure = [ { "id": group["id"], "times": group["times"], "label": group["label"], } for group in config["color_groups"] ] report = { "parent_version": parent_config["version"], "current_version": config["version"], "all_non_colour_config_identical": _non_colour_config(parent_config) == _non_colour_config(config), "group_membership_identical": parent_group_structure == current_group_structure, "pose_count_identical": len(parent_poses) == len(current_poses), "all_pose_geometry_identical": all( bool(row["source_and_geometry_identical"]) for row in rows ), "maximum_absolute_position_delta_px": max( abs(float(delta)) for row in rows for delta in row["position_delta_px"] ), "maximum_absolute_scale_delta": max( abs(float(row["scale_delta"])) for row in rows ), "poses": rows, } report["pass"] = bool( report["all_non_colour_config_identical"] and report["group_membership_identical"] and report["pose_count_identical"] and report["all_pose_geometry_identical"] and report["maximum_absolute_position_delta_px"] == 0.0 and report["maximum_absolute_scale_delta"] == 0.0 ) return report
def _hex_rgb(value: str) -> np.ndarray: return np.asarray( [int(value[index : index + 2], 16) for index in (1, 3, 5)], dtype=np.uint8, )
def _rgb_to_lab(rgb: np.ndarray) -> np.ndarray: original_shape = rgb.shape[:-1] flat = rgb.reshape(-1, 1, 3).astype(np.float32) / 255.0 lab = cv2.cvtColor(flat, cv2.COLOR_RGB2LAB).reshape(-1, 3) return lab.reshape(*original_shape, 3).astype(np.float64)
def _ciede2000(first: np.ndarray, second: np.ndarray) -> float: l1, a1, b1 = [float(value) for value in first] l2, a2, b2 = [float(value) for value in second] c1 = math.hypot(a1, b1) c2 = math.hypot(a2, b2) c_bar = (c1 + c2) / 2.0 g = 0.5 * ( 1.0 - math.sqrt((c_bar**7) / (c_bar**7 + 25.0**7)) ) a1_prime = (1.0 + g) * a1 a2_prime = (1.0 + g) * a2 c1_prime = math.hypot(a1_prime, b1) c2_prime = math.hypot(a2_prime, b2) h1_prime = math.degrees(math.atan2(b1, a1_prime)) % 360.0 h2_prime = math.degrees(math.atan2(b2, a2_prime)) % 360.0 delta_l = l2 - l1 delta_c = c2_prime - c1_prime if c1_prime * c2_prime == 0.0: delta_h_degrees = 0.0 else: delta_h_degrees = h2_prime - h1_prime if delta_h_degrees > 180.0: delta_h_degrees -= 360.0 elif delta_h_degrees < -180.0: delta_h_degrees += 360.0 delta_h = 2.0 * math.sqrt(c1_prime * c2_prime) * math.sin( math.radians(delta_h_degrees / 2.0) ) l_bar = (l1 + l2) / 2.0 c_prime_bar = (c1_prime + c2_prime) / 2.0 if c1_prime * c2_prime == 0.0: h_prime_bar = h1_prime + h2_prime elif abs(h1_prime - h2_prime) <= 180.0: h_prime_bar = (h1_prime + h2_prime) / 2.0 elif h1_prime + h2_prime < 360.0: h_prime_bar = (h1_prime + h2_prime + 360.0) / 2.0 else: h_prime_bar = (h1_prime + h2_prime - 360.0) / 2.0 t = ( 1.0 - 0.17 * math.cos(math.radians(h_prime_bar - 30.0)) + 0.24 * math.cos(math.radians(2.0 * h_prime_bar)) + 0.32 * math.cos(math.radians(3.0 * h_prime_bar + 6.0)) - 0.20 * math.cos(math.radians(4.0 * h_prime_bar - 63.0)) ) delta_theta = 30.0 * math.exp( -(((h_prime_bar - 275.0) / 25.0) ** 2) ) r_c = 2.0 * math.sqrt( (c_prime_bar**7) / (c_prime_bar**7 + 25.0**7) ) s_l = 1.0 + ( 0.015 * ((l_bar - 50.0) ** 2) / math.sqrt(20.0 + ((l_bar - 50.0) ** 2)) ) s_c = 1.0 + 0.045 * c_prime_bar s_h = 1.0 + 0.015 * c_prime_bar * t r_t = -math.sin(math.radians(2.0 * delta_theta)) * r_c l_term = delta_l / s_l c_term = delta_c / s_c h_term = delta_h / s_h return math.sqrt( l_term**2 + c_term**2 + h_term**2 + r_t * c_term * h_term )
def _masked_lightness_values(rgb: np.ndarray, mask: np.ndarray) -> np.ndarray: pixels = rgb[mask > 0] if len(pixels) == 0: raise RuntimeError("Cannot measure lightness on an empty mask") if len(pixels) > 180_000: indices = np.linspace(0, len(pixels) - 1, 180_000).astype(np.int64) pixels = pixels[indices] return _rgb_to_lab(pixels).reshape(-1, 3)[:, 0]
def _pairwise_palette_metrics( config: dict[str, Any],) -> tuple[list[dict[str, Any]], float]: groups = config["color_groups"] rgb = np.stack([_hex_rgb(str(group["color"])) for group in groups]) lab = _rgb_to_lab(rgb) rows = [] for first_index, first in enumerate(groups): for second_index in range(first_index + 1, len(groups)): second = groups[second_index] rows.append( { "groups": f"{first['id']}-{second['id']}", "colours": [first["color"], second["color"]], "ciede2000": round( _ciede2000(lab[first_index], lab[second_index]), 4, ), } ) return rows, min(float(row["ciede2000"]) for row in rows)
def palette_audit( parent_config: dict[str, Any], config: dict[str, Any], parent_poses: list[v3.Pose], current_poses: list[v3.Pose],) -> dict[str, Any]: old_groups = {str(group["id"]): group for group in parent_config["color_groups"]} new_groups = {str(group["id"]): group for group in config["color_groups"]} pairwise, minimum_delta = _pairwise_palette_metrics(config) new_base_rgb = np.stack( [_hex_rgb(str(group["color"])) for group in config["color_groups"]] ) new_base_lab = _rgb_to_lab(new_base_rgb) parent_by_time = {pose.time: pose for pose in parent_poses} current_by_time = {pose.time: pose for pose in current_poses} time_to_group = { float(time): str(group["id"]) for group in config["color_groups"] for time in group["times"] } pose_rows = [] for time in [float(value) for value in config["sample_times"]]: old_pose = parent_by_time[time] new_pose = current_by_time[time] source_rgb = cv2.cvtColor(new_pose.frame_bgr, cv2.COLOR_BGR2RGB) old_rgb = _ORIGINAL_COLORIZE(old_pose.frame_bgr, old_pose.color_rgb) new_rgb = metallic_colorize_foreground( new_pose.frame_bgr, new_pose.color_rgb, ) source_l = _masked_lightness_values(source_rgb, new_pose.refined_mask) old_l = _masked_lightness_values(old_rgb, old_pose.refined_mask) new_l = _masked_lightness_values(new_rgb, new_pose.refined_mask) source_std = float(source_l.std()) new_std = float(new_l.std()) old_std = float(old_l.std()) pose_rows.append( { "time_s": time, "group": time_to_group[time], "source_mean_l_star": round(float(source_l.mean()), 4), "v7_mean_l_star": round(float(old_l.mean()), 4), "v8_mean_l_star": round(float(new_l.mean()), 4), "v8_mean_lightness_shift_from_source": round( float(new_l.mean() - source_l.mean()), 4, ), "v7_lightness_correlation_to_source": round( float(np.corrcoef(source_l, old_l)[0, 1]), 6, ), "v8_lightness_correlation_to_source": round( float(np.corrcoef(source_l, new_l)[0, 1]), 6, ), "v7_local_contrast_retention": round( old_std / source_std, 6, ), "v8_local_contrast_retention": round( new_std / source_std, 6, ), } ) style = config["foreground_color_style"] detail_weight = float(style["source_rgb_detail_weight"]) source_chroma_weight = float(style["source_chroma_weight"]) effective_source_contribution = detail_weight + ( 1.0 - detail_weight ) * source_chroma_weight effective_group_contribution = ( 1.0 - detail_weight ) * float(style["group_chroma_weight"]) group_rows = [] for group_index, group in enumerate(config["color_groups"]): group_id = str(group["id"]) group_pose_rows = [row for row in pose_rows if row["group"] == group_id] mean_correlation = float( np.mean( [ float(row["v8_lightness_correlation_to_source"]) for row in group_pose_rows ] ) ) mean_contrast_retention = float( np.mean( [ float(row["v8_local_contrast_retention"]) for row in group_pose_rows ] ) ) old_colour = str(old_groups[group_id]["color"]).upper() new_colour = str(new_groups[group_id]["color"]).upper() group_rows.append( { "group": group_id, "times_s": [float(value) for value in group["times"]], "v7_colour": old_colour, "v8_colour": new_colour, "v8_base_l_star": round(float(new_base_lab[group_index, 0]), 4), "mean_v8_lightness_correlation_to_source": round( mean_correlation, 6, ), "mean_v8_local_contrast_retention": round( mean_contrast_retention, 6, ), "same_colour_within_group": all( np.array_equal( current_by_time[float(time)].color_rgb, _hex_rgb(new_colour), ) for time in group["times"] ), } ) minimum_correlation = min( float(row["v8_lightness_correlation_to_source"]) for row in pose_rows ) contrast_values = [ float(row["v8_local_contrast_retention"]) for row in pose_rows ] v7_contrast_values = [ float(row["v7_local_contrast_retention"]) for row in pose_rows ] contrast_improvements = [ current - previous for current, previous in zip(contrast_values, v7_contrast_values) ] maximum_absolute_lightness_shift = max( abs(float(row["v8_mean_lightness_shift_from_source"])) for row in pose_rows ) minimum_base_l = min(float(row["v8_base_l_star"]) for row in group_rows) maximum_base_l = max(float(row["v8_base_l_star"]) for row in group_rows) report = { "style": style, "group_count": len(group_rows), "all_group_colours_unique": len( {str(group["color"]).upper() for group in config["color_groups"]} ) == len(config["color_groups"]), "all_within_group_mappings_preserved": all( bool(row["same_colour_within_group"]) for row in group_rows ), "minimum_pairwise_ciede2000": round(minimum_delta, 4), "minimum_required_pairwise_ciede2000": 20.0, "base_l_star_range": [ round(minimum_base_l, 4), round(maximum_base_l, 4), ], "effective_source_colour_and_detail_contribution": round( effective_source_contribution, 6, ), "effective_group_colour_contribution": round( effective_group_contribution, 6, ), "minimum_v8_lightness_correlation_to_source": round( minimum_correlation, 6, ), "v8_local_contrast_retention_range": [ round(min(contrast_values), 6), round(max(contrast_values), 6), ], "v7_local_contrast_retention_range": [ round(min(v7_contrast_values), 6), round(max(v7_contrast_values), 6), ], "minimum_local_contrast_retention_improvement_vs_v7": round( min(contrast_improvements), 6, ), "maximum_absolute_mean_lightness_shift_from_source": round( maximum_absolute_lightness_shift, 4, ), "groups": group_rows, "pairwise_colour_difference": pairwise, "poses": pose_rows, } report["pass"] = bool( report["all_group_colours_unique"] and report["all_within_group_mappings_preserved"] and report["minimum_pairwise_ciede2000"] >= report["minimum_required_pairwise_ciede2000"] and minimum_base_l >= 42.0 and maximum_base_l <= 74.0 and effective_source_contribution >= 0.50 and minimum_correlation >= 0.985 and min(contrast_values) >= 0.85 and max(contrast_values) <= 1.15 and min(contrast_improvements) >= 0.25 and maximum_absolute_lightness_shift <= 4.5 ) return report
def save_occlusion_audit(config: dict[str, Any], out_dir: Path) -> dict[str, Any]: parent_config = v3.v2.load_json(PARENT_CONFIG) current_poses = list(v5._POSES_V5) parent_poses = _parent_poses(parent_config) before = v5.pose_visibility_metrics(parent_poses) after = v5.pose_visibility_metrics(current_poses) geometry = geometry_lock_audit( parent_config, config, parent_poses, current_poses, ) palette = palette_audit( parent_config, config, parent_poses, current_poses, ) row_layout = v6.row_layout_metrics(current_poses, config) path_overlay = v6.path_overlay_metrics(current_poses, config) crop_fit = v7.crop_fit_audit(current_poses, config) report = { "pass": bool( geometry["pass"] and palette["pass"] and before == after and row_layout["pass"] and crop_fit["pass"] and bool(path_overlay["foreground_redraw_enabled"]) ), "v7": before, "v8": after, "visibility_metrics_identical": before == after, "geometry_lock": geometry, "palette": palette, "row_layout": row_layout, "crop_fit": crop_fit, "path_overlay": path_overlay, } if not report["pass"]: raise RuntimeError("V8 colour-only, palette, or layout audit failed") v3.v2.write_json(out_dir / "occlusion_metrics.json", report) v3.v2.write_json(out_dir / "geometry_lock_metrics.json", geometry) v3.v2.write_json(out_dir / "palette_metrics.json", palette) v3.v2.write_json(out_dir / "row_layout_metrics.json", row_layout) v3.v2.write_json(out_dir / "crop_fit_metrics.json", crop_fit) v3.v2.write_json(out_dir / "path_overlay_metrics.json", path_overlay) return report
def save_layout_change_audit( config: dict[str, Any], out_dir: Path,) -> dict[str, Any]: parent = v3.v2.load_json(PARENT_CONFIG) rows = [] old_groups = {str(group["id"]): group for group in parent["color_groups"]} for group in config["color_groups"]: old = old_groups[str(group["id"])] rows.append( { "group": group["id"], "times_s": group["times"], "v7_colour": str(old["color"]).upper(), "v8_colour": str(group["color"]).upper(), "colour_changed": str(old["color"]).upper() != str(group["color"]).upper(), } ) report = { "source_frames_unchanged": config["sample_times"] == parent["sample_times"], "positions_unchanged": config["layout_targets_normalized"] == parent["layout_targets_normalized"], "scales_unchanged": ( config["pose_scale"] == parent["pose_scale"] and config["pose_scale_overrides"] == parent["pose_scale_overrides"] ), "alpha_unchanged": config["alpha"] == parent["alpha"], "crop_unchanged": config["crop_top_fraction"] == parent["crop_top_fraction"], "right_reserved_fraction_unchanged": config["right_reserved_fraction"] == parent["right_reserved_fraction"], "non_colour_config_unchanged": _non_colour_config(config) == _non_colour_config(parent), "changed_scope": [ "color_groups[*].color", "foreground_color_style", ], "colour_changes": rows, } report["pass"] = bool( report["source_frames_unchanged"] and report["positions_unchanged"] and report["scales_unchanged"] and report["alpha_unchanged"] and report["crop_unchanged"] and report["right_reserved_fraction_unchanged"] and report["non_colour_config_unchanged"] and all(bool(row["colour_changed"]) for row in rows) ) if not report["pass"]: raise RuntimeError("V8 change-scope audit failed") v3.v2.write_json(out_dir / "layout_change_audit.json", report) return report
def save_reuse_audit( args: argparse.Namespace, out_dir: Path,) -> dict[str, Any]: source = args.segmentation_source.expanduser().resolve() parent_background = cv2.imread(str(source / "background_plate.png")) current_background = cv2.imread(str(out_dir / "background_plate.png")) if ( parent_background is None or current_background is None or parent_background.shape != current_background.shape ): raise RuntimeError("Could not compare v7/v8 backgrounds") changed = int(np.any(parent_background != current_background, axis=2).sum()) artifacts = {} for name in v5.REUSED_SEGMENTATION_ARTIFACTS: source_hash = v7.sha256(source / name) copied_hash = v7.sha256(out_dir / name) artifacts[name] = { "source_sha256": source_hash, "copied_sha256": copied_hash, "identical": source_hash == copied_hash, } report = { "parent_version": "v7-wide-crop-uniform-scale", "segmentation_source": v3.v2.display_path(source), "source_frame_times_unchanged": True, "segmentation_artifacts_identical": all( row["identical"] for row in artifacts.values() ), "segmentation_artifacts": artifacts, "background_changed_pixels": changed, "background_identical": changed == 0, "parent_background_sha256": v7.sha256(source / "background_plate.png"), "v8_background_sha256": v7.sha256(out_dir / "background_plate.png"), } report["pass"] = bool( report["background_identical"] and report["segmentation_artifacts_identical"] ) if not report["pass"]: raise RuntimeError("V8 unexpectedly changed a reused v7 artifact") v3.v2.write_json(out_dir / "reuse_audit.json", report) return report
def update_run_metadata( config: dict[str, Any], out_dir: Path, occlusion: dict[str, Any], layout: dict[str, Any], reuse: dict[str, Any],) -> None: path = out_dir / "run_metadata.json" metadata = v3.v2.load_json(path) scales = [ v7.config_scale(config, float(time)) for time in config["sample_times"] ] metadata.update( { "parent_version": "v7-wide-crop-uniform-scale", "default_pose_scale": float(config["pose_scale"]), "pose_scale_overrides": config["pose_scale_overrides"], "pose_scale_range": [min(scales), max(scales)], "crop_top_fraction": float(config["crop_top_fraction"]), "foreground_color_style": config["foreground_color_style"], "palette_audit": occlusion["palette"], "geometry_lock_audit": occlusion["geometry_lock"], "layout_change_audit": layout, "occlusion_audit": occlusion, "reuse_audit": reuse, "publication_output_stem": OUTPUT_STEM, "publication_export_suffixes": list(PUBLICATION_SUFFIXES), "final_width_mm": float(config["final_width_mm"]), "png_dpi": int(config["png_dpi"]), "tiff_dpi": int(config["tiff_dpi"]), } ) v3.v2.write_json(path, metadata)
def _swatch_text_colour(colour: str) -> str: rgb = _hex_rgb(colour).astype(np.float64) luminance = float(rgb @ np.asarray([0.2126, 0.7152, 0.0722])) return "#FFFFFF" if luminance < 145.0 else "#26313A"
def save_palette_swatch(config: dict[str, Any], out_dir: Path) -> Path: figure = v3.plt.figure(figsize=(8.2, 2.05), dpi=300, facecolor="#F6F7F5") axis = figure.add_axes([0.025, 0.10, 0.95, 0.82]) axis.set_xlim(0, len(config["color_groups"])) axis.set_ylim(0, 1) axis.axis("off") for index, group in enumerate(config["color_groups"]): colour = str(group["color"]).upper() axis.add_patch( Rectangle( (index + 0.04, 0.28), 0.92, 0.48, facecolor=colour, edgecolor="#FFFFFF", linewidth=1.8, ) ) axis.text( index + 0.5, 0.52, f"{group['id']} {colour}", ha="center", va="center", fontsize=9.0, color=_swatch_text_colour(colour), weight="bold", ) axis.text( index + 0.5, 0.16, str(group["label"]), ha="center", va="center", fontsize=7.2, color="#46525A", ) axis.text( 0.0, 0.93, "v8 contrastive metallic palette", ha="left", va="center", fontsize=9.5, color="#24313A", weight="bold", ) path = out_dir / "palette_swatch.png" figure.savefig(path, dpi=300, facecolor=figure.get_facecolor()) v3.plt.close(figure) return path
def save_v7_v8_comparison( _crop_preview_path: Path, current_path: Path, out_dir: Path,) -> None: config = v3.v2.load_json(DEFAULT_CONFIG) paths = [PARENT_CLEAN, current_path] images = [] for path in paths: image = cv2.imread(str(path)) if image is None: raise RuntimeError(f"Could not read comparison input: {path}") images.append(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) figure = v3.plt.figure(figsize=(12.0, 5.15), dpi=300, facecolor="#F4F5F4") grid = figure.add_gridspec( 3, 1, height_ratios=[1.0, 1.0, 0.35], hspace=0.17, ) titles = [ "v7 • original medium-depth palette", "v8 • contrastive metallic colour grade, identical geometry", ] for index, (image, title) in enumerate(zip(images, titles)): axis = figure.add_subplot(grid[index, 0]) axis.imshow(image) axis.set_title( title, fontsize=8.4, loc="left", pad=4, weight="bold", color="#28313A", ) axis.axis("off") swatch_axis = figure.add_subplot(grid[2, 0]) swatch_axis.set_xlim(0, len(config["color_groups"])) swatch_axis.set_ylim(0, 1) swatch_axis.axis("off") for index, group in enumerate(config["color_groups"]): colour = str(group["color"]).upper() swatch_axis.add_patch( Rectangle( (index + 0.03, 0.18), 0.94, 0.64, facecolor=colour, edgecolor="#FFFFFF", linewidth=1.1, ) ) swatch_axis.text( index + 0.5, 0.50, f"{group['id']} {colour}", ha="center", va="center", fontsize=7.2, color=_swatch_text_colour(colour), weight="bold", ) figure.savefig( out_dir / "comparison_v7_v8.jpg", dpi=300, facecolor=figure.get_facecolor(), bbox_inches="tight", pil_kwargs={"quality": 94}, ) v3.plt.close(figure) save_palette_swatch(config, out_dir)
def install_v8_hooks() -> None: v3.validate_config = validate_config_v8 v3.v1.colorize_foreground = metallic_colorize_foreground v6.DEFAULT_CONFIG = DEFAULT_CONFIG v6.DEFAULT_OUT = DEFAULT_OUT v6.PARENT_CONFIG = PARENT_CONFIG v6.PARENT_OUT = PARENT_OUT v6.PARENT_ANNOTATED = PARENT_ANNOTATED v6.OUTPUT_STEM = OUTPUT_STEM v6.parse_args = parse_args v6.render_layout_v6 = render_layout_v8 v6.save_v5_v6_comparison = v7.defer_comparison v6.save_occlusion_audit = save_occlusion_audit v6.save_layout_change_audit = save_layout_change_audit v6.save_reuse_audit = save_reuse_audit v6.update_run_metadata = update_run_metadata v7.DEFAULT_CONFIG = DEFAULT_CONFIG v7.DEFAULT_OUT = DEFAULT_OUT v7.PARENT_CONFIG = PARENT_CONFIG v7.PARENT_OUT = PARENT_OUT v7.PARENT_CLEAN = PARENT_CLEAN v7.PARENT_ANNOTATED = PARENT_ANNOTATED v7.OUTPUT_STEM = OUTPUT_STEM v7.save_v6_v7_comparison = save_v7_v8_comparison
def main() -> int: args = parse_args() config = v3.v2.load_json(args.config.expanduser().resolve()) configure_colour_style(config) install_v8_hooks() return_code = v6.main() if return_code: return return_code out_dir = args.out_dir.expanduser().resolve() occlusion = v3.v2.load_json(out_dir / "occlusion_metrics.json") v7.postprocess_wide_outputs(out_dir, config, occlusion) print(f"Wrote v8 metallic-contrast outputs to {out_dir}") return 0
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220#!/usr/bin/env python3"""Build v9 at the native 3840 x 2160 source-video resolution.
V9 is a resolution-only successor to v8. It keeps the locked source times,layout targets, pose scales, colours, alpha values, z-order, crop, paths,background recipe, and rightmost 12% reserve. The original 2560 x 1440 SAMmasks are mapped to the native 3840 x 2160 grid with nearest-neighboursampling, while robot texture and background pixels are decoded directly fromthe 4K video. The final crop is 3840 x 1440. A pixel-native PNG is retainedalongside 183 mm, 600 dpi PNG/TIFF/SVG/PDF publication exports."""
from __future__ import annotations
import argparseimport copyimport csvimport hashlibimport mathimport shutilfrom pathlib import Pathfrom typing import Any
import cv2import numpy as np
import build_trajectory_figure_v8 as v8
v3 = v8.v3v5 = v8.v5v6 = v8.v6v7 = v8.v7
PROJECT_ROOT = Path(__file__).resolve().parents[2]DEFAULT_VIDEO = PROJECT_ROOT / "source" / "CLIP_P0010073.mov"DEFAULT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v9_native_4k_resolution.json"DEFAULT_YOLO = PROJECT_ROOT / "trajectory_project" / "models" / "yolov8x-seg.pt"DEFAULT_SAM = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v9_native_4k_resolution"PARENT_CONFIG = PROJECT_ROOT / "trajectory_project" / "config_v8_metallic_contrast_palette.json"PARENT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v8_metallic_contrast_palette"PARENT_CLEAN = PARENT_OUT / "trajectory_v8_metallic_contrast_clean.png"PARENT_ANNOTATED = PARENT_OUT / "trajectory_v8_metallic_contrast_annotated.png"PARENT_WIDE = PARENT_OUT / "composite_layout_wide_rgb.png"OUTPUT_STEM = "trajectory_v9_native_4k"NATIVE_CLEAN_NAME = f"{OUTPUT_STEM}_clean_native.png"FINAL_WIDTH_MM = 183.0PNG_DPI = 600TIFF_DPI = 600TARGET_WIDTH = 3840TARGET_HEIGHT = 2160PARENT_WIDTH = 2560PARENT_HEIGHT = 1440GRID_SCALE = TARGET_WIDTH / PARENT_WIDTHPUBLICATION_SUFFIXES = (".png", ".tiff", ".svg", ".pdf")_ORDERED_TIMES: list[float] = []
v3.matplotlib.rcParams.update( { "font.family": "sans-serif", "font.sans-serif": ["Arial", "Helvetica", "DejaVu Sans", "sans-serif"], "font.size": 7, "svg.fonttype": "none", "pdf.fonttype": 42, })
def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--video", type=Path, default=DEFAULT_VIDEO) parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG) parser.add_argument("--yolo-model", type=Path, default=DEFAULT_YOLO) parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_SAM) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument("--segmentation-source", type=Path, default=PARENT_OUT) parser.add_argument("--device", default="cuda:0") args = parser.parse_args() args.reuse_segmentation = True return args
def _locked_visual_config(config: dict[str, Any]) -> dict[str, Any]: payload = copy.deepcopy(config) for key in ["version", "render_width", "png_dpi"]: payload.pop(key, None) return payload
def validate_config_v9(config: dict[str, Any]) -> None: v8.validate_config_v8(config) parent = v3.v2.load_json(PARENT_CONFIG) if int(config["render_width"]) != TARGET_WIDTH: raise RuntimeError("V9 must render at the native 3840 px video width") if int(config["png_dpi"]) != PNG_DPI or int(config["tiff_dpi"]) != TIFF_DPI: raise RuntimeError("V9 publication PNG and TIFF must both be 600 dpi") if _locked_visual_config(config) != _locked_visual_config(parent): raise RuntimeError("V9 may change only version, render_width, and PNG export dpi")
def _resize_mask_native(mask: np.ndarray) -> np.ndarray: if mask.shape == (TARGET_HEIGHT, TARGET_WIDTH): return mask.astype(np.uint8) if mask.shape != (PARENT_HEIGHT, PARENT_WIDTH): raise RuntimeError(f"Unexpected parent mask shape: {mask.shape}") return cv2.resize( mask.astype(np.uint8), (TARGET_WIDTH, TARGET_HEIGHT), interpolation=cv2.INTER_NEAREST, )
def load_native_segmentation_cache( _out_dir: Path, ordered_times: list[float],) -> tuple[ dict[float, np.ndarray], dict[float, np.ndarray], dict[float, dict[str, Any]], list[dict[str, Any]],]: global _ORDERED_TIMES source = Path(load_native_segmentation_cache.source_dir) yolo, refined, metrics, records = v5._ORIGINAL_LOAD_CACHE(source, ordered_times) _ORDERED_TIMES = list(ordered_times) return ( {time: _resize_mask_native(mask) for time, mask in yolo.items()}, {time: _resize_mask_native(mask) for time, mask in refined.items()}, metrics, records, )
load_native_segmentation_cache.source_dir = str(PARENT_OUT)
def _scale_xy(values: list[float]) -> list[float]: return [round(float(value) * GRID_SCALE, 4) for value in values]
def copy_scaled_segmentation_artifacts( args: argparse.Namespace, out_dir: Path,) -> None: source = args.segmentation_source.expanduser().resolve() arrays: dict[str, np.ndarray] = {} for time in _ORDERED_TIMES: key = v3.time_key(time) arrays[f"yolo_{key}"] = v5._YOLO_MASKS[time].astype(np.uint8) arrays[f"sam_{key}"] = v5._REFINED_MASKS[time].astype(np.uint8) np.savez_compressed(out_dir / "segmentation_cache.npz", **arrays)
shutil.copy2(source / "sam_metrics_all.json", out_dir / "sam_metrics_all.json")
records = copy.deepcopy(v3.v2.load_json(source / "yolo_seed_detections.json")) for row in records: row["bbox_xyxy"] = _scale_xy(row["bbox_xyxy"]) row["foot_xy"] = _scale_xy(row["foot_xy"]) row["mask_area_px"] = int(round(float(row["mask_area_px"]) * GRID_SCALE**2)) row["coordinate_grid"] = [TARGET_WIDTH, TARGET_HEIGHT] row["coordinate_scale_from_v8"] = GRID_SCALE v3.v2.write_json(out_dir / "yolo_seed_detections.json", records)
prompts = copy.deepcopy(v3.v2.load_json(source / "sam_prompts.json")) for prompt in prompts.values(): prompt["bbox_xyxy"] = _scale_xy(prompt["bbox_xyxy"]) prompt["point_coords_xy"] = [ _scale_xy(point) for point in prompt["point_coords_xy"] ] prompt["coordinate_grid"] = [TARGET_WIDTH, TARGET_HEIGHT] prompt["coordinate_scale_from_v8"] = GRID_SCALE v3.v2.write_json(out_dir / "sam_prompts.json", prompts)
def defer_intermediate_publication( *_args: Any, **_kwargs: Any,) -> None: """V9 writes publication files once, after applying the locked wide crop."""
def _array_sha256(array: np.ndarray) -> str: return hashlib.sha256(np.ascontiguousarray(array).view(np.uint8)).hexdigest()
def _mask_iou(first: np.ndarray, second: np.ndarray) -> float: first_bool = first > 0 second_bool = second > 0 union = int((first_bool | second_bool).sum()) return float((first_bool & second_bool).sum() / union) if union else 1.0
def _read_parent_layout() -> dict[float, dict[str, str]]: with (PARENT_OUT / "layout_map.csv").open( "r", encoding="utf-8", newline="", ) as handle: return { float(row["time_s"]): row for row in csv.DictReader(handle) }
def geometry_lock_audit( config: dict[str, Any], current_poses: list[v3.Pose],) -> dict[str, Any]: parent_config = v3.v2.load_json(PARENT_CONFIG) parent_layout = _read_parent_layout() parent_archive = np.load(PARENT_OUT / "segmentation_cache.npz") rows = [] try: for pose in current_poses: old = parent_layout[pose.time] old_display = np.asarray( [ float(old["display_foot_x_px"]), float(old["display_foot_y_px"]), ], dtype=np.float64, ) expected_display = old_display * GRID_SCALE current_display = np.asarray(pose.display_foot, dtype=np.float64) current_bbox = np.asarray(v7.bbox_for_pose(pose), dtype=np.float64) old_bbox = np.asarray( [ float(old["scaled_bbox_x1"]), float(old["scaled_bbox_y1"]), float(old["scaled_bbox_x2"]), float(old["scaled_bbox_y2"]), ], dtype=np.float64, ) expected_bbox = old_bbox * GRID_SCALE parent_mask = parent_archive[f"sam_{v3.time_key(pose.time)}"] expected_mask = _resize_mask_native(parent_mask) parent_scale = v7.config_scale(parent_config, pose.time) rows.append( { "time_s": pose.time, "frame_index": pose.frame_index, "v8_display_foot_px": old_display.tolist(), "expected_v9_display_foot_px": expected_display.tolist(), "v9_display_foot_px": current_display.tolist(), "display_foot_delta_from_exact_1_5x_px": ( current_display - expected_display ).round(4).tolist(), "display_foot_normalized": ( current_display / np.asarray([TARGET_WIDTH, TARGET_HEIGHT]) ).round(8).tolist(), "v8_scale_factor": parent_scale, "v9_scale_factor": float(pose.scale_factor), "scale_delta": round( float(pose.scale_factor) - parent_scale, 12, ), "bbox_delta_from_exact_1_5x_px": ( current_bbox - expected_bbox ).round(4).tolist(), "native_mask_matches_nearest_mapped_v8_mask": bool( np.array_equal(pose.refined_mask, expected_mask) ), "native_mask_sha256": _array_sha256(pose.refined_mask), } ) finally: parent_archive.close() maximum_position_delta = max( abs(float(value)) for row in rows for value in row["display_foot_delta_from_exact_1_5x_px"] ) maximum_bbox_delta = max( abs(float(value)) for row in rows for value in row["bbox_delta_from_exact_1_5x_px"] ) maximum_scale_delta = max(abs(float(row["scale_delta"])) for row in rows) report = { "parent_version": parent_config["version"], "current_version": config["version"], "render_grid_change": [PARENT_WIDTH, PARENT_HEIGHT, TARGET_WIDTH, TARGET_HEIGHT], "expected_linear_grid_scale": GRID_SCALE, "all_locked_visual_config_identical": ( _locked_visual_config(config) == _locked_visual_config(parent_config) ), "all_masks_equal_nearest_mapped_parent": all( bool(row["native_mask_matches_nearest_mapped_v8_mask"]) for row in rows ), "maximum_absolute_display_foot_delta_from_exact_1_5x_px": round( maximum_position_delta, 4, ), "maximum_absolute_bbox_delta_from_exact_1_5x_px": round( maximum_bbox_delta, 4, ), "maximum_absolute_scale_delta": round(maximum_scale_delta, 12), "poses": rows, } report["pass"] = bool( report["all_locked_visual_config_identical"] and report["all_masks_equal_nearest_mapped_parent"] and maximum_position_delta <= 1.0 and maximum_bbox_delta <= 2.0 and maximum_scale_delta <= 1e-12 ) return report
def _scaled_row_layout_metrics( poses: list[v3.Pose], config: dict[str, Any],) -> dict[str, Any]: report = v6.row_layout_metrics(poses, config) report["pixel_scale_vs_v8"] = GRID_SCALE report["foreground_gap_range_in_v8_equivalent_px"] = round( float(report["foreground_gap_range_px"]) / GRID_SCALE, 4, ) report["foreground_ground_y_span_in_v8_equivalent_px"] = round( float(report["foreground_ground_y_span_px"]) / GRID_SCALE, 4, ) report["far_field_gap_range_in_v8_equivalent_px"] = round( float(report["far_field_gap_range_px"]) / GRID_SCALE, 4, ) report["far_field_y_span_in_v8_equivalent_px"] = round( float(report["far_field_y_span_px"]) / GRID_SCALE, 4, ) report["pass"] = bool( float(report["foreground_height_cv"]) < 0.02 and float(report["foreground_gap_range_in_v8_equivalent_px"]) <= 60.0 and float(report["foreground_ground_y_span_in_v8_equivalent_px"]) <= 2.0 and float(report["far_field_gap_range_in_v8_equivalent_px"]) <= 2.0 and float(report["far_field_y_span_in_v8_equivalent_px"]) <= 2.0 and 1.05 <= float(report["retreat_31_to_32_apparent_height_ratio"]) <= 1.25 ) return report
def _visibility_delta( parent: dict[str, Any], current: dict[str, Any],) -> dict[str, Any]: pose_deltas = { key: round( float(current["per_pose_visible_fraction"][key]) - float(parent["per_pose_visible_fraction"][key]), 6, ) for key in parent["per_pose_visible_fraction"] } return { "redundant_overlap_fraction_delta": round( float(current["redundant_overlap_fraction"]) - float(parent["redundant_overlap_fraction"]), 6, ), "maximum_stack_depth_unchanged": ( int(current["maximum_stack_depth"]) == int(parent["maximum_stack_depth"]) ), "maximum_absolute_per_pose_visible_fraction_delta": round( max(abs(float(value)) for value in pose_deltas.values()), 6, ), "per_pose_visible_fraction_delta": pose_deltas, }
def save_occlusion_audit( config: dict[str, Any], out_dir: Path,) -> dict[str, Any]: current_poses = list(v5._POSES_V5) current_visibility = v5.pose_visibility_metrics(current_poses) parent_report = v3.v2.load_json(PARENT_OUT / "occlusion_metrics.json") parent_visibility = parent_report["v8"] visibility_delta = _visibility_delta(parent_visibility, current_visibility) geometry = geometry_lock_audit(config, current_poses) row_layout = _scaled_row_layout_metrics(current_poses, config) path_overlay = v6.path_overlay_metrics(current_poses, config) crop_fit = v7.crop_fit_audit(current_poses, config)
v7_config = v3.v2.load_json(v8.PARENT_CONFIG) parent_colour_poses = v8._parent_poses(v7_config) palette = v8.palette_audit( v7_config, config, parent_colour_poses, current_poses, ) palette["evaluated_render_grid_px"] = [TARGET_WIDTH, TARGET_HEIGHT]
report = { "pass": bool( geometry["pass"] and palette["pass"] and row_layout["pass"] and crop_fit["pass"] and bool(path_overlay["foreground_redraw_enabled"]) and abs(float(visibility_delta["redundant_overlap_fraction_delta"])) <= 0.001 and bool(visibility_delta["maximum_stack_depth_unchanged"]) and float( visibility_delta[ "maximum_absolute_per_pose_visible_fraction_delta" ] ) <= 0.01 ), "v8": parent_visibility, "v9": current_visibility, "visibility_delta_from_mask_grid_mapping": visibility_delta, "geometry_lock": geometry, "palette": palette, "row_layout": row_layout, "crop_fit": crop_fit, "path_overlay": path_overlay, } if not report["pass"]: raise RuntimeError("V9 resolution-only geometry or visibility audit failed") v3.v2.write_json(out_dir / "occlusion_metrics.json", report) v3.v2.write_json(out_dir / "geometry_lock_metrics.json", geometry) v3.v2.write_json(out_dir / "palette_metrics.json", palette) v3.v2.write_json(out_dir / "row_layout_metrics.json", row_layout) v3.v2.write_json(out_dir / "crop_fit_metrics.json", crop_fit) v3.v2.write_json(out_dir / "path_overlay_metrics.json", path_overlay) return report
def save_layout_change_audit( config: dict[str, Any], out_dir: Path,) -> dict[str, Any]: parent = v3.v2.load_json(PARENT_CONFIG) report = { "parent_version": parent["version"], "current_version": config["version"], "source_frames_unchanged": config["sample_times"] == parent["sample_times"], "positions_unchanged": ( config["layout_targets_normalized"] == parent["layout_targets_normalized"] ), "scales_unchanged": ( config["pose_scale"] == parent["pose_scale"] and config["pose_scale_overrides"] == parent["pose_scale_overrides"] ), "colours_unchanged": config["color_groups"] == parent["color_groups"], "colour_transfer_unchanged": ( config["foreground_color_style"] == parent["foreground_color_style"] ), "alpha_unchanged": config["alpha"] == parent["alpha"], "crop_unchanged": ( config["crop_top_fraction"] == parent["crop_top_fraction"] ), "right_reserved_fraction_unchanged": ( config["right_reserved_fraction"] == parent["right_reserved_fraction"] ), "locked_visual_config_unchanged": ( _locked_visual_config(config) == _locked_visual_config(parent) ), "changed_scope": [ "render_width: 2560 -> 3840", "png_dpi: 300 -> 600", "version/output names", "SAM mask coordinate grid: nearest-neighbour 1.5x mapping", ], } report["pass"] = bool( report["source_frames_unchanged"] and report["positions_unchanged"] and report["scales_unchanged"] and report["colours_unchanged"] and report["colour_transfer_unchanged"] and report["alpha_unchanged"] and report["crop_unchanged"] and report["right_reserved_fraction_unchanged"] and report["locked_visual_config_unchanged"] ) if not report["pass"]: raise RuntimeError("V9 change-scope audit failed") v3.v2.write_json(out_dir / "layout_change_audit.json", report) return report
def _psnr(first: np.ndarray, second: np.ndarray) -> float: error = float( np.mean( ( first.astype(np.float32) - second.astype(np.float32) ) ** 2 ) ) return float("inf") if error == 0.0 else 10.0 * math.log10(255.0**2 / error)
def save_reuse_audit( args: argparse.Namespace, out_dir: Path,) -> dict[str, Any]: source = args.segmentation_source.expanduser().resolve() parent_archive = np.load(source / "segmentation_cache.npz") current_archive = np.load(out_dir / "segmentation_cache.npz") mask_rows = [] try: for key in parent_archive.files: parent_mask = parent_archive[key] current_mask = current_archive[key] expected = _resize_mask_native(parent_mask) downsampled = cv2.resize( current_mask, (PARENT_WIDTH, PARENT_HEIGHT), interpolation=cv2.INTER_NEAREST, ) parent_area = int((parent_mask > 0).sum()) current_area = int((current_mask > 0).sum()) mask_rows.append( { "key": key, "parent_shape": list(parent_mask.shape[::-1]), "native_shape": list(current_mask.shape[::-1]), "native_equals_expected_nearest_mapping": bool( np.array_equal(current_mask, expected) ), "foreground_area_scale": round( current_area / parent_area, 6, ) if parent_area else 1.0, "roundtrip_downsample_iou": round( _mask_iou(parent_mask, downsampled), 6, ), } ) finally: parent_archive.close() current_archive.close()
parent_background = cv2.imread(str(source / "background_plate.png")) current_background = cv2.imread(str(out_dir / "background_plate.png")) if parent_background is None or current_background is None: raise RuntimeError("Could not read v8/v9 background plates") current_down = cv2.resize( current_background, (PARENT_WIDTH, PARENT_HEIGHT), interpolation=cv2.INTER_AREA, ) background_mae = float( np.mean( np.abs( parent_background.astype(np.float32) - current_down.astype(np.float32) ) ) ) background_psnr = _psnr(parent_background, current_down) minimum_roundtrip_iou = min( float(row["roundtrip_downsample_iou"]) for row in mask_rows ) maximum_area_scale_error = max( abs(float(row["foreground_area_scale"]) - GRID_SCALE**2) for row in mask_rows ) metrics_identical = ( v7.sha256(source / "sam_metrics_all.json") == v7.sha256(out_dir / "sam_metrics_all.json") ) report = { "parent_version": "v8-metallic-contrast-palette", "segmentation_source": v3.v2.display_path(source), "source_frame_times_unchanged": True, "mask_mapping_method": "nearest-neighbour from locked 2560x1440 masks", "linear_grid_scale": GRID_SCALE, "expected_area_scale": GRID_SCALE**2, "all_native_masks_equal_expected_mapping": all( bool(row["native_equals_expected_nearest_mapping"]) for row in mask_rows ), "minimum_roundtrip_downsample_iou": round(minimum_roundtrip_iou, 6), "maximum_foreground_area_scale_error": round( maximum_area_scale_error, 6, ), "sam_metrics_identical": metrics_identical, "background_parent_size_px": list(parent_background.shape[1::-1]), "background_native_size_px": list(current_background.shape[1::-1]), "background_downsample_mae": round(background_mae, 6), "background_downsample_psnr_db": ( "inf" if math.isinf(background_psnr) else round(background_psnr, 4) ), "masks": mask_rows, } report["pass"] = bool( report["all_native_masks_equal_expected_mapping"] and minimum_roundtrip_iou >= 0.97 and maximum_area_scale_error <= 0.01 and metrics_identical and current_background.shape[:2] == (TARGET_HEIGHT, TARGET_WIDTH) and background_mae <= 5.0 and background_psnr >= 30.0 ) if not report["pass"]: raise RuntimeError("V9 native-grid reuse audit failed") v3.v2.write_json(out_dir / "reuse_audit.json", report) v3.v2.write_json( out_dir / "mask_scaling_metrics.json", { key: report[key] for key in [ "mask_mapping_method", "linear_grid_scale", "expected_area_scale", "all_native_masks_equal_expected_mapping", "minimum_roundtrip_downsample_iou", "maximum_foreground_area_scale_error", "masks", "pass", ] }, ) return report
def update_run_metadata( config: dict[str, Any], out_dir: Path, occlusion: dict[str, Any], layout: dict[str, Any], reuse: dict[str, Any],) -> None: path = out_dir / "run_metadata.json" metadata = v3.v2.load_json(path) metadata.pop("uniform_pose_scale", None) scales = [ v7.config_scale(config, float(time)) for time in config["sample_times"] ] metadata.update( { "parent_version": "v8-metallic-contrast-palette", "change_scope": "native-resolution rerender only", "default_pose_scale": float(config["pose_scale"]), "pose_scale_overrides": config["pose_scale_overrides"], "pose_scale_range": [min(scales), max(scales)], "crop_top_fraction": float(config["crop_top_fraction"]), "foreground_color_style": config["foreground_color_style"], "layout_change_audit": layout, "occlusion_audit": occlusion, "reuse_audit": reuse, "native_source_grid_px": [TARGET_WIDTH, TARGET_HEIGHT], "mask_grid_mapping": "nearest-neighbour 1.5x from locked v8 SAM masks", "publication_output_stem": OUTPUT_STEM, "publication_export_suffixes": list(PUBLICATION_SUFFIXES), "final_width_mm": float(config["final_width_mm"]), "png_dpi": int(config["png_dpi"]), "tiff_dpi": int(config["tiff_dpi"]), "generative_super_resolution_used": False, "artificial_sharpening_used": False, } ) v3.v2.write_json(path, metadata)
def publication_artifact_audit( out_dir: Path, config: dict[str, Any], crop_y: int,) -> dict[str, Any]: variants: dict[str, Any] = {} for variant in ["clean", "annotated"]: rows: dict[str, Any] = {} for extension in PUBLICATION_SUFFIXES: path = out_dir / f"{OUTPUT_STEM}_{variant}{extension}" if not path.exists() or path.stat().st_size == 0: raise RuntimeError(f"Missing publication artifact: {path}") rows[extension.lstrip(".")] = { "bytes": path.stat().st_size, "sha256": v7.sha256(path), } with v3.Image.open(out_dir / f"{OUTPUT_STEM}_{variant}.png") as image: rows["png"].update( { "width_px": image.width, "height_px": image.height, "mode": image.mode, "dpi": [ round(float(value), 3) for value in image.info.get("dpi", (0, 0)) ], } ) with v3.Image.open(out_dir / f"{OUTPUT_STEM}_{variant}.tiff") as image: rows["tiff"].update( { "width_px": image.width, "height_px": image.height, "mode": image.mode, "compression": image.info.get("compression"), "dpi": [ round(float(value), 3) for value in image.info.get("dpi", (0, 0)) ], } ) variants[variant] = rows
width_in = float(config["final_width_mm"]) / 25.4 aspect = (TARGET_HEIGHT - crop_y) / TARGET_WIDTH expected_png = [ int(width_in * int(config["png_dpi"])), int(width_in * aspect * int(config["png_dpi"])), ] expected_tiff = [ int(width_in * int(config["tiff_dpi"])), int(width_in * aspect * int(config["tiff_dpi"])), ] native_path = out_dir / NATIVE_CLEAN_NAME with v3.Image.open(native_path) as native: native_row = { "path": native_path.name, "width_px": native.width, "height_px": native.height, "mode": native.mode, "bytes": native_path.stat().st_size, "sha256": v7.sha256(native_path), } report = { "expected_png_size_px": expected_png, "expected_tiff_size_px": expected_tiff, "native_clean": native_row, "variants": variants, } report["pass"] = bool( native_row["width_px"] == TARGET_WIDTH and native_row["height_px"] == TARGET_HEIGHT - crop_y and all( row["png"]["width_px"] == expected_png[0] and row["png"]["height_px"] == expected_png[1] and abs(float(row["png"]["dpi"][0]) - PNG_DPI) <= 0.1 and row["tiff"]["width_px"] == expected_tiff[0] and row["tiff"]["height_px"] == expected_tiff[1] and row["tiff"]["mode"] == "RGB" and row["tiff"]["compression"] == "tiff_lzw" for row in variants.values() ) ) if not report["pass"]: raise RuntimeError("V9 publication artifact audit failed") v3.v2.write_json(out_dir / "publication_artifact_metrics.json", report) return report
def _crop_square( image: np.ndarray, centre_x: float, centre_y: float, size: int,) -> np.ndarray: half = size // 2 x1 = int(round(centre_x)) - half y1 = int(round(centre_y)) - half x1 = max(0, min(x1, image.shape[1] - size)) y1 = max(0, min(y1, image.shape[0] - size)) return image[y1 : y1 + size, x1 : x1 + size].copy()
def save_resolution_comparisons( _crop_preview_path: Path, _current_path: Path, out_dir: Path,) -> None: parent_bgr = cv2.imread(str(PARENT_WIDE)) current_bgr = cv2.imread(str(out_dir / "composite_layout_wide_rgb.png")) if parent_bgr is None or current_bgr is None: raise RuntimeError("Could not read v8/v9 comparison inputs") parent_rgb = cv2.cvtColor(parent_bgr, cv2.COLOR_BGR2RGB) current_rgb = cv2.cvtColor(current_bgr, cv2.COLOR_BGR2RGB)
figure = v3.plt.figure(figsize=(12.0, 5.15), dpi=300, facecolor="#F4F5F4") grid = figure.add_gridspec(2, 1, hspace=0.16) panels = [ (parent_rgb, "v8 • 2560 × 960 internal render"), (current_rgb, "v9 • native 3840 × 1440 render, identical visual layout"), ] for index, (image, title) in enumerate(panels): axis = figure.add_subplot(grid[index, 0]) axis.imshow(image) axis.set_title( title, fontsize=8.4, loc="left", pad=4, weight="bold", color="#28313A", ) axis.axis("off") figure.savefig( out_dir / "comparison_v8_v9_resolution.jpg", dpi=300, facecolor=figure.get_facecolor(), bbox_inches="tight", pil_kwargs={"quality": 95}, ) v3.plt.close(figure)
parent_layout = _read_parent_layout() crop_y_parent = int(round(PARENT_HEIGHT / 3.0)) crop_y_native = int(round(TARGET_HEIGHT / 3.0)) detail_times = [6.0, 14.0, 40.0] old_size = 320 native_size = int(round(old_size * GRID_SCALE)) header = 42 gutter = 12 sheet = np.full( ( len(detail_times) * (native_size + header + gutter) - gutter, native_size * 2 + gutter, 3, ), 246, dtype=np.uint8, ) for row_index, time in enumerate(detail_times): row = parent_layout[time] x = float(row["display_foot_x_px"]) bbox_top = float(row["scaled_bbox_y1"]) bbox_bottom = float(row["scaled_bbox_y2"]) centre_y = bbox_top + 0.43 * (bbox_bottom - bbox_top) - crop_y_parent old_crop = _crop_square(parent_rgb, x, centre_y, old_size) old_upscaled = cv2.resize( old_crop, (native_size, native_size), interpolation=cv2.INTER_LANCZOS4, ) native_crop = _crop_square( current_rgb, x * GRID_SCALE, (centre_y + crop_y_parent) * GRID_SCALE - crop_y_native, native_size, ) y0 = row_index * (native_size + header + gutter) sheet[y0 + header : y0 + header + native_size, :native_size] = old_upscaled sheet[ y0 + header : y0 + header + native_size, native_size + gutter :, ] = native_crop cv2.putText( sheet, f"{time:g} s v8 enlarged from 2560", (12, y0 + 28), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (40, 48, 55), 1, cv2.LINE_AA, ) cv2.putText( sheet, f"{time:g} s v9 native 4K pixels", (native_size + gutter + 12, y0 + 28), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (40, 48, 55), 1, cv2.LINE_AA, ) cv2.imwrite( str(out_dir / "detail_crops_v8_v9.png"), cv2.cvtColor(sheet, cv2.COLOR_RGB2BGR), )
def postprocess_wide_outputs( out_dir: Path, config: dict[str, Any], occlusion: dict[str, Any],) -> None: full_layout_bgr = cv2.imread(str(out_dir / "composite_layout_rgb.png")) full_background_bgr = cv2.imread(str(out_dir / "background_plate.png")) if full_layout_bgr is None or full_background_bgr is None: raise RuntimeError("Missing full-canvas v9 render") if full_layout_bgr.shape != full_background_bgr.shape: raise RuntimeError("Full layout and background dimensions do not match") full_layout_rgb = cv2.cvtColor(full_layout_bgr, cv2.COLOR_BGR2RGB) full_background_rgb = cv2.cvtColor(full_background_bgr, cv2.COLOR_BGR2RGB) crop_y = v7.crop_top_px(config, full_layout_rgb.shape[0]) wide_layout_rgb = full_layout_rgb[crop_y:].copy() wide_background_rgb = full_background_rgb[crop_y:].copy()
shutil.copy2( out_dir / "composite_layout_rgb.png", out_dir / "composite_layout_full_rgb.png", ) cv2.imwrite( str(out_dir / "composite_layout_wide_rgb.png"), cv2.cvtColor(wide_layout_rgb, cv2.COLOR_RGB2BGR), ) cv2.imwrite( str(out_dir / "background_plate_wide.png"), cv2.cvtColor(wide_background_rgb, cv2.COLOR_RGB2BGR), ) shutil.copy2( out_dir / "composite_layout_wide_rgb.png", out_dir / NATIVE_CLEAN_NAME, )
v7.save_publication_figure( wide_layout_rgb, out_dir / f"{OUTPUT_STEM}_clean", config, annotated=False, ) v7.save_publication_figure( wide_layout_rgb, out_dir / f"{OUTPUT_STEM}_annotated", config, annotated=True, ) v7.save_wide_layout_map(out_dir, crop_y)
full_safe_path = out_dir / "safe_area_qa.png" full_safe_metrics_path = out_dir / "safe_area_metrics.json" if full_safe_path.exists(): full_safe_path.replace(out_dir / "safe_area_full_qa.png") if full_safe_metrics_path.exists(): full_safe_metrics_path.replace(out_dir / "safe_area_full_metrics.json") safe_report = v7.save_wide_safe_area_qa( wide_layout_rgb, wide_background_rgb, config, out_dir, ) crop_preview = v7.save_crop_window_preview( full_layout_rgb, crop_y, out_dir, ) save_resolution_comparisons( crop_preview, out_dir / f"{OUTPUT_STEM}_clean.png", out_dir, ) artifact_report = publication_artifact_audit(out_dir, config, crop_y)
crop_report = { "full_canvas_size_px": [ full_layout_rgb.shape[1], full_layout_rgb.shape[0], ], "crop_top_y_px": crop_y, "requested_crop_top_fraction": float(config["crop_top_fraction"]), "actual_removed_fraction": round(crop_y / full_layout_rgb.shape[0], 8), "wide_canvas_size_px": [ wide_layout_rgb.shape[1], wide_layout_rgb.shape[0], ], "aspect_ratio": round( wide_layout_rgb.shape[1] / wide_layout_rgb.shape[0], 6, ), "height_reduction_fraction": round( 1.0 - wide_layout_rgb.shape[0] / full_layout_rgb.shape[0], 8, ), "pose_crop_fit": occlusion["crop_fit"], "safe_area": safe_report, "publication_artifacts": artifact_report, } crop_report["pass"] = bool( occlusion["crop_fit"]["pass"] and safe_report["pass"] and artifact_report["pass"] and wide_layout_rgb.shape[:2] == (TARGET_HEIGHT - crop_y, TARGET_WIDTH) ) if not crop_report["pass"]: raise RuntimeError("V9 crop/export audit failed") v3.v2.write_json(out_dir / "crop_metrics.json", crop_report)
metadata_path = out_dir / "run_metadata.json" metadata = v3.v2.load_json(metadata_path) metadata.update( { "full_render_size_px": [ full_layout_rgb.shape[1], full_layout_rgb.shape[0], ], "crop_top_y_px": crop_y, "wide_render_size_px": [ wide_layout_rgb.shape[1], wide_layout_rgb.shape[0], ], "wide_aspect_ratio": crop_report["aspect_ratio"], "native_clean_file": NATIVE_CLEAN_NAME, "crop_audit": crop_report, } ) v3.v2.write_json(metadata_path, metadata)
def _masked_detail_metrics( frame_bgr: np.ndarray, mask: np.ndarray,) -> tuple[float, float, float, float]: low = cv2.resize( frame_bgr, (PARENT_WIDTH, PARENT_HEIGHT), interpolation=cv2.INTER_AREA, ) baseline = cv2.resize( low, (TARGET_WIDTH, TARGET_HEIGHT), interpolation=cv2.INTER_LANCZOS4, ) native_gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY).astype(np.float32) baseline_gray = cv2.cvtColor(baseline, cv2.COLOR_BGR2GRAY).astype(np.float32) core = cv2.erode( (mask > 0).astype(np.uint8), np.ones((7, 7), dtype=np.uint8), iterations=1, ) > 0 if int(core.sum()) < 500: core = mask > 0 native_laplacian = cv2.Laplacian(native_gray, cv2.CV_32F) baseline_laplacian = cv2.Laplacian(baseline_gray, cv2.CV_32F) native_high = native_gray - cv2.GaussianBlur(native_gray, (0, 0), 1.2) baseline_high = baseline_gray - cv2.GaussianBlur(baseline_gray, (0, 0), 1.2) native_laplacian_variance = float(native_laplacian[core].var()) baseline_laplacian_variance = float(baseline_laplacian[core].var()) native_high_rms = float(np.sqrt(np.mean(native_high[core] ** 2))) baseline_high_rms = float(np.sqrt(np.mean(baseline_high[core] ** 2))) return ( native_laplacian_variance, baseline_laplacian_variance, native_high_rms, baseline_high_rms, )
def save_resolution_audit( out_dir: Path, config: dict[str, Any],) -> dict[str, Any]: native = cv2.imread(str(out_dir / NATIVE_CLEAN_NAME)) parent = cv2.imread(str(PARENT_WIDE)) publication = cv2.imread(str(out_dir / f"{OUTPUT_STEM}_clean.png")) if native is None or parent is None or publication is None: raise RuntimeError("Missing v8/v9 raster for resolution audit") native_down = cv2.resize( native, (PARENT_WIDTH, PARENT_HEIGHT - PARENT_HEIGHT // 3), interpolation=cv2.INTER_AREA, ) full_composite_mae = float( np.mean(np.abs(native_down.astype(np.float32) - parent.astype(np.float32))) ) full_composite_psnr = _psnr(native_down, parent)
detail_rows = [] for pose in v5._POSES_V5: native_lap, baseline_lap, native_high, baseline_high = _masked_detail_metrics( pose.frame_bgr, pose.refined_mask, ) detail_rows.append( { "time_s": pose.time, "native_laplacian_variance": round(native_lap, 6), "v8_grid_baseline_laplacian_variance": round(baseline_lap, 6), "laplacian_variance_ratio": round( native_lap / baseline_lap, 6, ) if baseline_lap else 1.0, "native_high_frequency_rms": round(native_high, 6), "v8_grid_baseline_high_frequency_rms": round( baseline_high, 6, ), "high_frequency_rms_ratio": round( native_high / baseline_high, 6, ) if baseline_high else 1.0, } ) high_ratios = [ float(row["high_frequency_rms_ratio"]) for row in detail_rows ] laplacian_ratios = [ float(row["laplacian_variance_ratio"]) for row in detail_rows ] metadata = v3.v2.load_json(out_dir / "run_metadata.json") video_metadata = metadata["video_metadata"] report = { "source_video_codec_note": "H.264 8-bit source; no method can recover detail absent from the source", "source_video_size_px": [ int(video_metadata["source_width"]), int(video_metadata["source_height"]), ], "v8_full_render_size_px": [PARENT_WIDTH, PARENT_HEIGHT], "v9_full_render_size_px": [TARGET_WIDTH, TARGET_HEIGHT], "v8_wide_native_size_px": list(parent.shape[1::-1]), "v9_wide_native_size_px": list(native.shape[1::-1]), "v9_publication_png_size_px": list(publication.shape[1::-1]), "linear_resolution_gain": GRID_SCALE, "pixel_count_gain": GRID_SCALE**2, "publication_png_dpi": int(config["png_dpi"]), "native_clean_file": NATIVE_CLEAN_NAME, "generative_super_resolution_used": False, "artificial_sharpening_used": False, "v9_downsampled_vs_v8_composite_mae": round(full_composite_mae, 6), "v9_downsampled_vs_v8_composite_psnr_db": round( full_composite_psnr, 4, ), "median_native_high_frequency_gain": round( float(np.median(high_ratios)), 6, ), "minimum_native_high_frequency_gain": round( min(high_ratios), 6, ), "median_native_laplacian_variance_gain": round( float(np.median(laplacian_ratios)), 6, ), "per_pose_source_detail": detail_rows, } report["pass"] = bool( report["source_video_size_px"] == [TARGET_WIDTH, TARGET_HEIGHT] and report["v9_full_render_size_px"] == [TARGET_WIDTH, TARGET_HEIGHT] and report["v9_wide_native_size_px"] == [ TARGET_WIDTH, TARGET_HEIGHT - TARGET_HEIGHT // 3, ] and report["linear_resolution_gain"] == 1.5 and report["pixel_count_gain"] == 2.25 and float(report["median_native_high_frequency_gain"]) >= 1.05 and not report["generative_super_resolution_used"] and not report["artificial_sharpening_used"] ) if not report["pass"]: raise RuntimeError("V9 native-resolution detail audit failed") v3.v2.write_json(out_dir / "resolution_metrics.json", report) metadata["resolution_audit"] = report v3.v2.write_json(out_dir / "run_metadata.json", metadata) return report
def install_v9_hooks() -> None: v8.install_v8_hooks() v3.validate_config = validate_config_v9 v3.save_publication_figure = defer_intermediate_publication v5.load_v4_segmentation_cache = load_native_segmentation_cache v5.copy_reused_segmentation_artifacts = copy_scaled_segmentation_artifacts v5.export_final_publication_outputs = defer_intermediate_publication
v6.DEFAULT_CONFIG = DEFAULT_CONFIG v6.DEFAULT_OUT = DEFAULT_OUT v6.PARENT_CONFIG = PARENT_CONFIG v6.PARENT_OUT = PARENT_OUT v6.PARENT_ANNOTATED = PARENT_ANNOTATED v6.OUTPUT_STEM = OUTPUT_STEM v6.parse_args = parse_args v6.render_layout_v6 = v8.render_layout_v8 v6.save_v5_v6_comparison = v7.defer_comparison v6.save_occlusion_audit = save_occlusion_audit v6.save_layout_change_audit = save_layout_change_audit v6.save_reuse_audit = save_reuse_audit v6.update_run_metadata = update_run_metadata
v7.DEFAULT_CONFIG = DEFAULT_CONFIG v7.DEFAULT_OUT = DEFAULT_OUT v7.PARENT_CONFIG = PARENT_CONFIG v7.PARENT_OUT = PARENT_OUT v7.PARENT_CLEAN = PARENT_CLEAN v7.PARENT_ANNOTATED = PARENT_ANNOTATED v7.OUTPUT_STEM = OUTPUT_STEM v7.FINAL_WIDTH_MM = FINAL_WIDTH_MM v7.PNG_DPI = PNG_DPI v7.TIFF_DPI = TIFF_DPI
def main() -> int: args = parse_args() config = v3.v2.load_json(args.config.expanduser().resolve()) v8.configure_colour_style(config) install_v9_hooks() return_code = v6.main() if return_code: return return_code out_dir = args.out_dir.expanduser().resolve() occlusion = v3.v2.load_json(out_dir / "occlusion_metrics.json") postprocess_wide_outputs(out_dir, config, occlusion) resolution = save_resolution_audit(out_dir, config) print( "Wrote v9 native-4K outputs to " f"{out_dir} (detail gain median {resolution['median_native_high_frequency_gain']}x)" ) return 0
if __name__ == "__main__": raise SystemExit(main()).gitattributes+6
source/CLIP_P0010073.movAdded+3
trajectory_project/intermediate/contact_sheet.jpgAdded

Large File Pointer Details
- SHA256: d68e8c9fcb0e8e911935a651b764326cd0199ef4c3f3c9a0e53752af1198c6c9
- Pointer size: 131 Bytes
- Size of remote file: 154 kB
trajectory_project/intermediate/contact_sheet_full.jpgAdded

Large File Pointer Details
- SHA256: 7015bf0ed740a415ee38f95cc13df35e982b5babe07ab86ddae787bbb9b285d5
- Pointer size: 131 Bytes
- Size of remote file: 147 kB
trajectory_project/intermediate/genmo_reference.pdfAdded+3
trajectory_project/intermediate/genmo_teaser.jpgAdded

Large File Pointer Details
- SHA256: 1e402e454af403e1b1755570feefc22fd5d9a13c4a7d8d9d086ec8b437cdccbe
- Pointer size: 132 Bytes
- Size of remote file: 3.4 MB
trajectory_project/intermediate/keyframes/t0.jpgAdded

trajectory_project/intermediate/keyframes/t10.jpgAdded

trajectory_project/intermediate/keyframes/t20.jpgAdded

trajectory_project/intermediate/keyframes/t30.jpgAdded

trajectory_project/intermediate/keyframes/t35.jpgAdded

trajectory_project/intermediate/keyframes/t40.jpgAdded

trajectory_project/intermediate/keyframes/t45.jpgAdded

trajectory_project/intermediate/keyframes/t50.jpgAdded

trajectory_project/intermediate/keyframes/t55.jpgAdded

trajectory_project/intermediate/keyframes/t60.jpgAdded

trajectory_project/intermediate/keyframes/t63.jpgAdded

trajectory_project/intermediate/keyframes_montage.jpgAdded

Large File Pointer Details
- SHA256: f80f446aa66ebe94be50b135debd732ec537e08f09f1ea8545f43b1999678c6f
- Pointer size: 131 Bytes
- Size of remote file: 353 kB
trajectory_project/intermediate/yolo_mask_montage.jpgAdded

Large File Pointer Details
- SHA256: f56f10f0533b52b6444bd578daeef6199d75eabcde2d06f49ed2631abde9e966
- Pointer size: 131 Bytes
- Size of remote file: 371 kB
trajectory_project/models/yolov8x-seg.ptAdded+3
trajectory_project/qa/source_preflight.mdAdded+7
trajectory_project/qa/v5_image_integrity.mdAdded+14
trajectory_project/qa/v6_source_preflight.mdAdded+29
trajectory_project/qa/v7_image_integrity.mdAdded+15
trajectory_project/scripts/build_trajectory_figure.pyAdded+642
trajectory_project/scripts/build_trajectory_figure_v3.pyAdded+1113
trajectory_project/scripts/build_trajectory_figure_v4.pyAdded+562
trajectory_project/scripts/build_trajectory_figure_v5.pyAdded+551
trajectory_project/scripts/build_trajectory_figure_v7.pyAdded+802
trajectory_project/scripts/build_trajectory_figure_v8.pyAdded+972
trajectory_project/scripts/build_trajectory_figure_v9.pyAdded+1220