Download trajectory_project/scripts/build_trajectory_figure_v2.py from Tinghong-Ye22/code-paper: direct link, hf CLI and curl.
- Browser
- Download file 51.3 kB
-
https://huggingface.co/Tinghong-Ye22/code-paper/resolve/main/trajectory_project/scripts/build_trajectory_figure_v2.py
- Command line
-
hf download hf://Tinghong-Ye22/code-paper/trajectory_project/scripts/build_trajectory_figure_v2.py
-
curl -L -o build_trajectory_figure_v2.py https://huggingface.co/Tinghong-Ye22/code-paper/resolve/main/trajectory_project/scripts/build_trajectory_figure_v2.py
51.3 kB
#!/usr/bin/env python3
"""Build the v2 G1 trajectory plate with SAM-refined masks and layout expansion.
The v2 pipeline deliberately separates two meanings:
1. ``true-position`` keeps every selected pose at its source image coordinate.
2. ``layout-expanded`` translates the same source-scale cut-outs to documented
display coordinates so overlapping poses can be read in a paper teaser.
The grey dashed line in the layout-expanded plate is the source image-plane
trajectory. The coloured line links display positions and is not presented as
a physical path. No pose is rescaled, rotated, generated, or deformed.
Publication exports: ``.png`` preview, ``.tiff`` at 600 dpi, and editable-text
``.svg`` / ``.pdf`` files.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import math
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable
import cv2
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patheffects
from matplotlib.lines import Line2D
from matplotlib.patches import FancyBboxPatch, Rectangle
from PIL import Image
import build_trajectory_figure as v1
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 segment_anything import SamPredictor, sam_model_registry
except Exception as exc: # pragma: no cover - useful command-line failure
SamPredictor = None
sam_model_registry = None
_SAM_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_v2_sam_layout.json"
DEFAULT_SEED_DIR = PROJECT_ROOT / "trajectory_project" / "outputs" / "v1"
DEFAULT_CHECKPOINT = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"
DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v2_sam_layout"
@dataclass
class 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
color_rgb: np.ndarray
hero: bool
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("--seed-dir", type=Path, default=DEFAULT_SEED_DIR)
parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_CHECKPOINT)
parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT)
parser.add_argument("--device", default="cuda:0", help="SAM device, e.g. cuda:0 or cpu")
parser.add_argument(
"--reuse-refined",
action="store_true",
help="Reuse refined_masks.npz in the output directory and only rerender layout.",
)
return parser.parse_args()
def load_json(path: Path) -> Any:
with path.open("r", encoding="utf-8") as handle:
return json.load(handle)
def write_json(path: Path, value: Any) -> None:
with path.open("w", encoding="utf-8") as handle:
json.dump(value, handle, ensure_ascii=False, indent=2)
def sha256sum(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 display_path(path: Path) -> str:
try:
return str(path.resolve().relative_to(PROJECT_ROOT.resolve()))
except ValueError:
return path.name
def ellipse_kernel(radius: int) -> np.ndarray:
radius = max(1, int(radius))
return cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (2 * radius + 1, 2 * radius + 1))
def binary_mask(mask: np.ndarray) -> np.ndarray:
return (mask > 0).astype(np.uint8)
def mask_similarity(reference: np.ndarray, candidate: np.ndarray) -> dict[str, float]:
ref = reference > 0
cand = candidate > 0
intersection = int(np.logical_and(ref, cand).sum())
union = int(np.logical_or(ref, cand).sum())
ref_area = int(ref.sum())
cand_area = int(cand.sum())
return {
"iou": float(intersection / union) if union else 0.0,
"recall": float(intersection / ref_area) if ref_area else 0.0,
"precision": float(intersection / cand_area) if cand_area else 0.0,
"area_ratio": float(cand_area / ref_area) if ref_area else 0.0,
"reference_area_px": ref_area,
"candidate_area_px": cand_area,
}
def expanded_bbox(mask: np.ndarray, padding_fraction: float) -> np.ndarray:
height, width = mask.shape
x1, y1, x2, y2 = v1.mask_bbox(mask)
bw, bh = max(1.0, x2 - x1), max(1.0, y2 - y1)
px = max(8.0, bw * float(padding_fraction))
py = max(8.0, bh * float(padding_fraction))
return np.array(
[
np.clip(x1 - px, 0, width - 1),
np.clip(y1 - py, 0, height - 1),
np.clip(x2 + px, 1, width),
np.clip(y2 + py, 1, height),
],
dtype=np.float32,
)
def farthest_points(region: np.ndarray, count: int, seed: int) -> np.ndarray:
"""Choose deterministic, spatially distributed points from a binary region."""
yy, xx = np.where(region > 0)
if len(xx) == 0 or count <= 0:
return np.empty((0, 2), dtype=np.float32)
coordinates = np.column_stack([xx, yy]).astype(np.float32)
if len(coordinates) > 8000:
# Deterministic coverage sampling keeps prompt generation reproducible;
# it is an implementation detail, not observation/data sampling.
offset = int(seed % max(1, len(coordinates) // 8000))
chosen = np.linspace(offset, len(coordinates) - 1, num=8000, dtype=np.int64)
coordinates = coordinates[chosen]
mins = coordinates.min(axis=0)
spans = np.maximum(coordinates.max(axis=0) - mins, 1.0)
normalised = (coordinates - mins) / spans
centre = np.array([0.5, 0.5], dtype=np.float32)
first = int(np.argmin(np.sum((normalised - centre) ** 2, axis=1)))
selected = [first]
min_distance = np.sum((normalised - normalised[first]) ** 2, axis=1)
while len(selected) < min(count, len(coordinates)):
nxt = int(np.argmax(min_distance))
selected.append(nxt)
distance = np.sum((normalised - normalised[nxt]) ** 2, axis=1)
min_distance = np.minimum(min_distance, distance)
return coordinates[selected]
def prompt_points(mask: np.ndarray, positive_count: int, negative_count: int, seed: int) -> tuple[np.ndarray, np.ndarray]:
fg = binary_mask(mask)
height, width = fg.shape
bbox = v1.mask_bbox(fg)
bw, bh = max(1.0, bbox[2] - bbox[0]), max(1.0, bbox[3] - bbox[1])
inner_radius = max(2, int(round(min(bw, bh) * 0.008)))
positive_region = cv2.erode(fg, ellipse_kernel(inner_radius), iterations=1)
if int(positive_region.sum()) < positive_count:
positive_region = fg
outer_radius = max(12, int(round(min(bw, bh) * 0.12)))
guard_radius = max(4, int(round(min(bw, bh) * 0.025)))
outer = cv2.dilate(fg, ellipse_kernel(outer_radius), iterations=1)
guard = cv2.dilate(fg, ellipse_kernel(guard_radius), iterations=1)
negative_region = ((outer > 0) & (guard == 0)).astype(np.uint8)
x1, y1, x2, y2 = expanded_bbox(mask, 0.18).astype(int)
crop_guard = np.zeros_like(negative_region)
crop_guard[y1:y2, x1:x2] = 1
negative_region &= crop_guard
positive = farthest_points(positive_region, positive_count, seed)
negative = farthest_points(negative_region, negative_count, seed + 1009)
points = np.vstack([positive, negative]).astype(np.float32)
labels = np.concatenate(
[np.ones(len(positive), dtype=np.int32), np.zeros(len(negative), dtype=np.int32)]
)
return points, labels
def select_sam_candidate(
masks: np.ndarray,
scores: np.ndarray,
yolo_mask: np.ndarray,
) -> tuple[np.ndarray, int, dict[str, float]]:
candidates: list[tuple[float, int, np.ndarray, dict[str, float]]] = []
for index, (mask, sam_score) in enumerate(zip(masks, scores)):
stats = mask_similarity(yolo_mask, mask)
ratio = max(stats["area_ratio"], 1e-6)
rank = (
2.30 * stats["iou"]
+ 0.70 * stats["recall"]
+ 0.70 * stats["precision"]
+ 0.30 * float(sam_score)
- 0.35 * abs(math.log(ratio))
)
candidates.append((rank, index, mask, {**stats, "sam_score": float(sam_score)}))
candidates.sort(key=lambda item: item[0], reverse=True)
_, index, mask, stats = candidates[0]
return mask.astype(np.uint8), int(index), stats
def refine_one_mask(
predictor: Any,
frame_bgr: np.ndarray,
yolo_mask: np.ndarray,
sam_config: dict[str, Any],
seed: int,
) -> tuple[np.ndarray, dict[str, Any], dict[str, Any]]:
height, width = yolo_mask.shape
predictor.set_image(cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB))
points, labels = prompt_points(
yolo_mask,
int(sam_config["positive_points"]),
int(sam_config["negative_points"]),
seed,
)
box = expanded_bbox(yolo_mask, float(sam_config["bbox_padding_fraction"]))
masks, scores, _ = predictor.predict(
point_coords=points,
point_labels=labels,
box=box,
multimask_output=True,
return_logits=False,
)
raw, selected_index, raw_stats = select_sam_candidate(masks, scores, yolo_mask)
scale = width / 3840.0
clip_radius = max(2, int(round(float(sam_config["clip_dilation_px_at_4k"]) * scale)))
core_radius = max(1, int(round(float(sam_config["core_erosion_px_at_4k"]) * scale)))
yolo = binary_mask(yolo_mask)
allowed = cv2.dilate(yolo, ellipse_kernel(clip_radius), iterations=1)
core = cv2.erode(yolo, ellipse_kernel(core_radius), iterations=1)
refined = (((raw > 0) & (allowed > 0)) | (core > 0)).astype(np.uint8)
refined = cv2.morphologyEx(refined, cv2.MORPH_CLOSE, ellipse_kernel(1))
# Keep only components that overlap the seed target; this blocks unrelated
# objects while retaining detached articulated hands or feet.
count, component_map, stats, _ = cv2.connectedComponentsWithStats(refined, 8)
kept = np.zeros_like(refined)
for component in range(1, count):
component_pixels = component_map == component
overlap = int(np.logical_and(component_pixels, yolo > 0).sum())
if overlap >= 8 and int(stats[component, cv2.CC_STAT_AREA]) >= 12:
kept[component_pixels] = 1
refined = kept
final_stats = mask_similarity(yolo, refined)
fallback = final_stats["precision"] < 0.85 or final_stats["recall"] < 0.78
if fallback:
refined = yolo
final_stats = mask_similarity(yolo, refined)
metrics: dict[str, Any] = {
"selected_sam_candidate": selected_index,
"sam_score": round(float(raw_stats["sam_score"]), 6),
"raw_iou": round(float(raw_stats["iou"]), 6),
"raw_recall": round(float(raw_stats["recall"]), 6),
"raw_precision": round(float(raw_stats["precision"]), 6),
"raw_area_ratio": round(float(raw_stats["area_ratio"]), 6),
"final_iou": round(float(final_stats["iou"]), 6),
"final_recall": round(float(final_stats["recall"]), 6),
"final_precision": round(float(final_stats["precision"]), 6),
"final_area_ratio": round(float(final_stats["area_ratio"]), 6),
"fallback_to_yolo": bool(fallback),
}
prompt_record = {
"bbox_xyxy": [round(float(value), 3) for value in box],
"point_coords_xy": [[round(float(x), 3), round(float(y), 3)] for x, y in points],
"point_labels": [int(value) for value in labels],
}
return (refined * 255).astype(np.uint8), metrics, prompt_record
def load_seed_masks(seed_dir: Path) -> tuple[list[dict[str, Any]], dict[float, np.ndarray]]:
records = load_json(seed_dir / "detections.json")
archive = np.load(seed_dir / "masks.npz")
masks: dict[float, np.ndarray] = {}
for row in records:
index = int(row["index"])
masks[float(row["time_s"])] = archive[f"mask_{index:03d}"].astype(np.uint8)
archive.close()
return records, masks
def record_for_time(records: list[dict[str, Any]], time: float) -> dict[str, Any]:
matches = [row for row in records if abs(float(row["time_s"]) - time) < 1e-5]
if len(matches) != 1:
raise RuntimeError(f"Expected exactly one v1 seed record for {time:g}s, found {len(matches)}")
return matches[0]
def read_source_frames(
video: Path,
records: list[dict[str, Any]],
sample_times: list[float],
render_width: int,
) -> tuple[dict[float, np.ndarray], dict[str, Any]]:
cap = cv2.VideoCapture(str(video))
if not cap.isOpened():
raise RuntimeError(f"Could not open source 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)
frames: dict[float, np.ndarray] = {}
for time in sample_times:
row = record_for_time(records, time)
frame = v1.read_frame(cap, int(row["frame_index"]))
frames[time] = v1.resize_keep_aspect(frame, render_width)
cap.release()
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": render_width,
"render_height": int(next(iter(frames.values())).shape[0]),
}
return frames, metadata
def make_background(
frames: dict[float, np.ndarray],
masks: dict[float, np.ndarray],
config: dict[str, Any],
) -> np.ndarray:
base_time, fill_time = [float(value) for value in config["background_reference_times"]]
base = frames[base_time]
fill = frames[fill_time]
scale = base.shape[1] / 3840.0
dilate_px = max(8, int(round(float(config["background_dilate_px_at_4k"]) * scale)))
repaired = v1.repair_background(base, fill, masks[base_time], masks[fill_time], dilate_px)
rgb = cv2.cvtColor(repaired, cv2.COLOR_BGR2RGB).astype(np.float32)
gray = cv2.cvtColor(repaired, 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 config_key(time: float) -> str:
return f"{time:g}"
def clamp_display_foot(
requested: tuple[float, float],
bbox: tuple[float, float, float, float],
source_foot: tuple[float, float],
canvas_shape: tuple[int, int],
margin: int,
) -> tuple[float, float]:
height, width = canvas_shape
x1, y1, x2, y2 = bbox
fx, fy = source_foot
minimum_x = margin + (fx - x1)
maximum_x = width - margin - (x2 - fx)
minimum_y = margin + (fy - y1)
maximum_y = height - margin - (y2 - fy)
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],
records: list[dict[str, Any]],
frames: dict[float, np.ndarray],
seed_masks: dict[float, np.ndarray],
refined_masks: dict[float, np.ndarray],
metrics_by_time: dict[float, dict[str, Any]],
) -> list[Pose]:
sample_times = [float(value) for value in config["sample_times"]]
height, width = next(iter(frames.values())).shape[:2]
scale = width / 3840.0
margin = max(8, int(round(float(config["layout_margin_px_at_4k"]) * scale)))
hero_times = {float(value) for value in config["hero_times"]}
poses: list[Pose] = []
for time in sample_times:
row = record_for_time(records, time)
mask = refined_masks[time]
bbox = v1.mask_bbox(mask)
source_foot = v1.foot_point(mask, bbox)
normalised = config["layout_targets_normalized"][config_key(time)]
requested = (float(normalised[0]) * width, float(normalised[1]) * height)
display_foot = clamp_display_foot(requested, bbox, source_foot, (height, width), margin)
phase = v1.phase_for(time, config["phases"])
poses.append(
Pose(
time=time,
frame_index=int(row["frame_index"]),
frame_bgr=frames[time],
yolo_mask=seed_masks[time],
refined_mask=mask,
source_bbox=bbox,
source_foot=source_foot,
display_foot_requested=requested,
display_foot=display_foot,
phase_name=str(phase["name"]),
color_rgb=v1.hex_to_rgb(phase["color"]),
hero=time in hero_times,
sam_metrics=metrics_by_time[time],
)
)
return poses
def blend_region(canvas: np.ndarray, foreground: np.ndarray, opacity: np.ndarray) -> None:
alpha = np.clip(opacity.astype(np.float32), 0.0, 1.0)[..., None]
canvas[:] = np.clip(
canvas.astype(np.float32) * (1.0 - alpha) + foreground.astype(np.float32) * alpha,
0,
255,
).astype(np.uint8)
def shifted_mask(mask: np.ndarray, target_foot: tuple[float, float], source_foot: tuple[float, float]) -> np.ndarray:
height, width = mask.shape
dx = int(round(target_foot[0] - source_foot[0]))
dy = int(round(target_foot[1] - source_foot[1]))
transform = np.array([[1.0, 0.0, dx], [0.0, 1.0, dy]], dtype=np.float32)
return cv2.warpAffine(
mask,
transform,
(width, height),
flags=cv2.INTER_NEAREST,
borderMode=cv2.BORDER_CONSTANT,
borderValue=0,
)
def draw_shadows(canvas: np.ndarray, poses: Iterable[Pose], use_layout: bool, 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 = max(1.0, pose.source_bbox[2] - pose.source_bbox[0])
bbox_height = max(1.0, pose.source_bbox[3] - pose.source_bbox[1])
foot = pose.display_foot if use_layout else pose.source_foot
centre = (int(round(foot[0])), int(round(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)
shadow_f = cv2.GaussianBlur(shadow.astype(np.float32) / 255.0, (0, 0), sigmaX=sigma)
canvas[:] = np.clip(canvas.astype(np.float32) * (1.0 - shadow_f[..., None] * alpha), 0, 255).astype(np.uint8)
def draw_dashed_segment(
image: np.ndarray,
p0: np.ndarray,
p1: np.ndarray,
color: tuple[int, int, int],
width: int,
dash: float,
gap: float,
) -> None:
vector = p1 - p0
length = float(np.linalg.norm(vector))
if length < 1.0:
return
direction = vector / length
cursor = 0.0
while cursor < length:
end = min(length, cursor + dash)
a = tuple(np.round(p0 + direction * cursor).astype(int))
b = tuple(np.round(p0 + direction * end).astype(int))
cv2.line(image, a, b, color, width, lineType=cv2.LINE_AA)
cursor += dash + gap
def draw_source_path(canvas: np.ndarray, points: np.ndarray, scale: float) -> None:
layer = canvas.copy()
for p0, p1 in zip(points[:-1], points[1:]):
draw_dashed_segment(layer, p0, p1, (20, 24, 30), max(4, int(round(7 * scale))), 17 * scale, 12 * scale)
draw_dashed_segment(layer, p0, p1, (226, 230, 232), max(2, int(round(3 * scale))), 17 * scale, 12 * scale)
for point in points:
cv2.circle(layer, tuple(np.round(point).astype(int)), max(2, int(round(4 * scale))), (232, 234, 235), -1, lineType=cv2.LINE_AA)
cv2.circle(layer, tuple(np.round(point).astype(int)), max(1, int(round(2 * scale))), (76, 82, 88), -1, lineType=cv2.LINE_AA)
canvas[:] = np.clip(0.42 * layer.astype(np.float32) + 0.58 * canvas.astype(np.float32), 0, 255).astype(np.uint8)
def arrow_head(canvas: np.ndarray, p0: np.ndarray, p1: np.ndarray, color: tuple[int, int, int], scale: float) -> None:
direction = p1 - p0
norm = float(np.linalg.norm(direction))
if norm < 2.0:
return
unit = direction / norm
normal = np.array([-unit[1], unit[0]])
size = max(8.0, 18.0 * scale)
triangle = np.vstack(
[p1, p1 - unit * size + normal * size * 0.55, p1 - unit * size - normal * size * 0.55]
).astype(np.int32)
cv2.fillConvexPoly(canvas, triangle, color, lineType=cv2.LINE_AA)
def draw_display_path(canvas: np.ndarray, poses: list[Pose], config: dict[str, Any], scale: float) -> None:
points = np.array([pose.display_foot for pose in poses], dtype=np.float32)
for index, (p0, p1) in enumerate(zip(points[:-1], points[1:])):
phase = v1.phase_for(poses[index].time, config["phases"])
color = tuple(int(value) for value in v1.hex_to_rgb(phase["color"]))
cv2.line(canvas, tuple(np.round(p0).astype(int)), tuple(np.round(p1).astype(int)), (247, 247, 244), max(5, int(round(9 * scale))), lineType=cv2.LINE_AA)
cv2.line(canvas, tuple(np.round(p0).astype(int)), tuple(np.round(p1).astype(int)), color, max(2, int(round(4 * scale))), lineType=cv2.LINE_AA)
final_color = tuple(int(value) for value in poses[-1].color_rgb)
arrow_head(canvas, points[-2], points[-1], final_color, scale)
def blend_pose(canvas: np.ndarray, pose: Pose, target_foot: tuple[float, float], alpha: float, scale: float) -> None:
x1, y1, x2, y2 = [int(value) for value in v1.mask_bbox(pose.refined_mask)]
pad = max(3, int(round(5 * scale)))
x1 = max(0, x1 - pad)
y1 = max(0, y1 - pad)
x2 = min(pose.refined_mask.shape[1], x2 + pad)
y2 = min(pose.refined_mask.shape[0], y2 + pad)
crop_mask = pose.refined_mask[y1:y2, x1:x2]
crop_frame = pose.frame_bgr[y1:y2, x1:x2]
if crop_mask.size == 0:
return
dx = int(round(target_foot[0] - pose.source_foot[0]))
dy = int(round(target_foot[1] - pose.source_foot[1]))
destination_x1, destination_y1 = x1 + dx, y1 + dy
destination_x2, destination_y2 = x2 + dx, y2 + dy
source_x1 = max(0, -destination_x1)
source_y1 = max(0, -destination_y1)
source_x2 = crop_mask.shape[1] - max(0, destination_x2 - canvas.shape[1])
source_y2 = crop_mask.shape[0] - max(0, destination_y2 - canvas.shape[0])
destination_x1 = max(0, destination_x1)
destination_y1 = max(0, destination_y1)
destination_x2 = min(canvas.shape[1], destination_x2)
destination_y2 = min(canvas.shape[0], destination_y2)
if source_x2 <= source_x1 or source_y2 <= source_y1:
return
mask = crop_mask[source_y1:source_y2, source_x1:source_x2]
frame = crop_frame[source_y1:source_y2, source_x1:source_x2]
target = canvas[destination_y1:destination_y2, destination_x1:destination_x2]
mask_float = mask.astype(np.float32) / 255.0
# A thin neutral halo separates neighbouring silhouettes without changing
# their source geometry.
halo_radius = max(1, int(round(2.5 * scale)))
halo = cv2.dilate((mask > 0).astype(np.uint8), ellipse_kernel(halo_radius), iterations=1)
halo = np.clip(halo.astype(np.float32) - (mask > 0).astype(np.float32), 0.0, 1.0)
blend_region(target, np.full_like(target, 247), halo * (0.42 if pose.hero else 0.27))
foreground = v1.colorize_foreground(frame, pose.color_rgb)
soft = cv2.GaussianBlur(mask_float, (0, 0), sigmaX=max(0.6, 1.05 * scale))
blend_region(target, foreground, soft * float(alpha))
contour_layer = target.copy()
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
outline = tuple(int(value) for value in pose.color_rgb)
cv2.drawContours(
contour_layer,
contours,
-1,
outline,
max(1, int(round(2.0 * 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)
+ contour_layer.astype(np.float32) * contour_alpha,
0,
255,
).astype(np.uint8)
def render_composite(
background: np.ndarray,
poses: list[Pose],
source_path: np.ndarray,
config: dict[str, Any],
mode: str,
) -> np.ndarray:
canvas = background.copy()
scale = canvas.shape[1] / 3840.0
alpha_config = config["alpha"]
if mode == "true_position":
draw_source_path(canvas, source_path, scale)
draw_shadows(canvas, poses, use_layout=False, alpha=float(config["shadow_alpha"]) * 0.45)
draw_order = sorted(poses, key=lambda pose: pose.source_foot[1])
for pose in draw_order:
alpha = float(
alpha_config["true_position_hero"] if pose.hero else alpha_config["true_position_standard"]
)
blend_pose(canvas, pose, pose.source_foot, alpha, scale)
elif mode == "layout_expanded":
draw_source_path(canvas, source_path, scale)
draw_shadows(canvas, poses, use_layout=True, alpha=float(config["shadow_alpha"]))
draw_display_path(canvas, poses, config, scale)
draw_order = sorted(poses, key=lambda pose: pose.display_foot[1])
for pose in draw_order:
alpha = float(alpha_config["layout_hero"] if pose.hero else alpha_config["layout_standard"])
blend_pose(canvas, pose, pose.display_foot, alpha, scale)
else:
raise ValueError(f"Unknown render mode: {mode}")
return canvas
def add_timeline(ax: Any, config: dict[str, Any], width: int, height: int) -> None:
phases = config["phases"]
maximum_time = float(phases[-1]["end"])
ax.add_patch(
Rectangle(
(0, 0.010 * height),
width,
0.090 * height,
facecolor=(0.025, 0.040, 0.055),
alpha=0.80,
lw=0,
zorder=20,
)
)
y0, y1 = 0.026 * height, 0.062 * height
for phase in phases:
x0 = width * float(phase["start"]) / maximum_time
x1 = width * float(phase["end"]) / maximum_time
color = v1.hex_to_rgb(phase["color"]) / 255.0
ax.add_patch(
Rectangle((x0, y0), x1 - x0, y1 - y0, facecolor=color, alpha=0.96, lw=0, zorder=21)
)
ax.text(
(x0 + x1) / 2,
y0 + 0.61 * (y1 - y0),
phase["name"],
color="white",
ha="center",
va="center",
fontsize=5.9,
weight="bold",
zorder=22,
)
for time in [0, 16, 28, 40, 64]:
x = width * time / maximum_time
ax.plot([x, x], [y1 + 0.006 * height, y1 + 0.020 * height], color="white", lw=0.75, zorder=22)
alignment = "left" if time == 0 else ("right" if time == 64 else "center")
offset = 0.008 * width if time == 0 else (-0.008 * width if time == 64 else 0)
ax.text(
x + offset,
y1 + 0.022 * height,
f"{time:g} s",
color="white",
ha=alignment,
va="top",
fontsize=5.2,
zorder=22,
)
ax.text(
width - 0.015 * width,
y0 - 0.006 * height,
"time →",
color="white",
ha="right",
va="bottom",
fontsize=5.3,
zorder=22,
)
def add_annotation_card(ax: Any, width: int, height: int, mode: str) -> None:
if mode == "layout_expanded":
box_x, box_y = 0.014 * width, 0.116 * height
box_w, box_h = 0.315 * width, 0.092 * 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.36),
lw=0.6,
alpha=0.78,
zorder=24,
)
)
ax.text(
box_x + 0.018 * width,
box_y + 0.030 * height,
"Layout-expanded poses",
color="white",
fontsize=7.0,
weight="bold",
ha="left",
va="center",
zorder=25,
)
ax.text(
box_x + 0.018 * width,
box_y + 0.062 * height,
"positions expanded for visibility; source scale retained",
color=(0.90, 0.92, 0.94),
fontsize=5.2,
ha="left",
va="center",
zorder=25,
)
handles = [
Line2D([0], [0], color="#DDE1E3", lw=1.2, ls=(0, (3, 2)), label="source image-plane trajectory"),
Line2D([0], [0], color="#31AEBE", lw=1.8, label="display sequence"),
]
legend = ax.legend(
handles=handles,
loc="upper right",
bbox_to_anchor=(0.985, 0.875),
fontsize=5.2,
labelcolor="white",
handlelength=2.3,
borderaxespad=0,
frameon=True,
facecolor=(0.02, 0.035, 0.050),
edgecolor="none",
framealpha=0.62,
)
legend.set_zorder(25)
else:
ax.text(
0.015 * width,
0.126 * height,
"SAM-refined • 12 representative poses • source image-plane positions",
color="white",
fontsize=6.0,
weight="bold",
ha="left",
va="top",
zorder=24,
path_effects=[patheffects.withStroke(linewidth=2.6, foreground=(0, 0, 0, 0.62))],
)
def save_publication_figure(
canvas: np.ndarray,
out_base: Path,
config: dict[str, Any],
mode: str,
annotated: bool,
formats: tuple[str, ...],
) -> None:
height, width = canvas.shape[:2]
# Static double-column contract is kept explicit for source preflight.
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:
if config.get("timeline", True):
add_timeline(ax, config, width, height)
add_annotation_card(ax, width, height, mode)
for extension in formats:
path = out_base.with_suffix(f".{extension}")
if extension == "png":
fig.savefig(path, dpi=png_dpi, facecolor="white")
elif extension in {"tif", "tiff"}:
fig.savefig(path, dpi=tiff_dpi, facecolor="white")
# Submission TIFF is stored as lossless LZW RGB rather than a large
# uncompressed RGBA canvas; pixel values and physical DPI are kept.
with Image.open(path) as rendered:
rendered.convert("RGB").save(
path,
format="TIFF",
compression="tiff_lzw",
dpi=(tiff_dpi, tiff_dpi),
)
elif extension in {"svg", "pdf"}:
fig.savefig(path, facecolor="white")
if extension == "svg":
# Matplotlib emits harmless trailing spaces in multi-line path
# commands; normalise them so repository diffs stay clean.
lines = path.read_text(encoding="utf-8").splitlines()
path.write_text("\n".join(line.rstrip() for line in lines) + "\n", encoding="utf-8")
else:
raise ValueError(f"Unsupported output format: {extension}")
plt.close(fig)
def overlap_statistics(masks: list[np.ndarray]) -> dict[str, Any]:
if not masks:
return {}
occupancy = np.zeros(masks[0].shape, dtype=np.uint16)
for mask in masks:
occupancy += (mask > 0).astype(np.uint16)
summed_area = int(occupancy.sum())
union_area = int((occupancy > 0).sum())
multiply_covered = int((occupancy > 1).sum())
pair_count = 0
maximum_pair_iou = 0.0
for left in range(len(masks)):
for right in range(left + 1, len(masks)):
a = masks[left] > 0
b = masks[right] > 0
intersection = int(np.logical_and(a, b).sum())
if intersection:
pair_count += 1
union = int(np.logical_or(a, b).sum())
maximum_pair_iou = max(maximum_pair_iou, intersection / union)
return {
"pose_count": len(masks),
"summed_pose_area_px": summed_area,
"union_area_px": union_area,
"redundant_overlap_px": summed_area - union_area,
"redundant_overlap_fraction": round((summed_area - union_area) / summed_area, 6) if summed_area else 0.0,
"pixels_covered_by_two_or_more": multiply_covered,
"overlapping_pose_pairs": pair_count,
"maximum_stack_depth": int(occupancy.max()),
"maximum_pair_iou": round(maximum_pair_iou, 6),
}
def compute_overlap_report(poses: list[Pose]) -> dict[str, Any]:
source_masks = [pose.refined_mask for pose in poses]
layout_masks = [shifted_mask(pose.refined_mask, pose.display_foot, pose.source_foot) for pose in poses]
near_indices = [index for index, pose in enumerate(poses) if pose.time < 28.0]
report = {
"definition": "redundant_overlap_fraction = (sum of pose-mask areas - union area) / sum of pose-mask areas",
"true_position": {
"all_poses": overlap_statistics(source_masks),
"near_field": overlap_statistics([source_masks[index] for index in near_indices]),
},
"layout_expanded": {
"all_poses": overlap_statistics(layout_masks),
"near_field": overlap_statistics([layout_masks[index] for index in near_indices]),
},
}
for scope in ["all_poses", "near_field"]:
before = report["true_position"][scope]["redundant_overlap_fraction"]
after = report["layout_expanded"][scope]["redundant_overlap_fraction"]
report.setdefault("relative_reduction", {})[scope] = round((before - after) / before, 6) if before else 0.0
return report
def save_layout_map(poses: list[Pose], config: dict[str, Any], out_dir: Path) -> None:
alpha_config = config["alpha"]
fields = [
"time_s",
"phase",
"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_dx_px",
"translation_dy_px",
"scale_factor",
"layout_alpha",
]
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:
alpha = alpha_config["layout_hero"] if pose.hero else alpha_config["layout_standard"]
writer.writerow(
{
"time_s": f"{pose.time:.3f}",
"phase": pose.phase_name,
"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_dx_px": f"{pose.display_foot[0] - pose.source_foot[0]:.3f}",
"translation_dy_px": f"{pose.display_foot[1] - pose.source_foot[1]:.3f}",
"scale_factor": "1.000",
"layout_alpha": f"{float(alpha):.3f}",
}
)
def save_refined_records(poses: list[Pose], out_dir: Path) -> None:
records: list[dict[str, Any]] = []
masks: dict[str, np.ndarray] = {}
for index, pose in enumerate(poses):
records.append(
{
"index": index,
"time_s": pose.time,
"frame_index": pose.frame_index,
"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],
"phase": pose.phase_name,
"hero": pose.hero,
"sam_metrics": pose.sam_metrics,
}
)
masks[f"mask_{index:03d}"] = pose.refined_mask.astype(np.uint8)
write_json(out_dir / "detections_refined.json", records)
np.savez_compressed(out_dir / "refined_masks.npz", **masks)
def letterbox(image: np.ndarray, width: int, height: int, color: tuple[int, int, int]) -> np.ndarray:
scale = min(width / image.shape[1], height / image.shape[0])
resized = cv2.resize(
image,
(max(1, int(round(image.shape[1] * scale))), max(1, int(round(image.shape[0] * scale)))),
interpolation=cv2.INTER_AREA if scale < 1 else cv2.INTER_LINEAR,
)
canvas = np.full((height, width, 3), color, dtype=np.uint8)
x = (width - resized.shape[1]) // 2
y = (height - resized.shape[0]) // 2
canvas[y : y + resized.shape[0], x : x + resized.shape[1]] = resized
return canvas
def save_sam_qa(poses: list[Pose], out_dir: Path) -> None:
tile_width, tile_height, header = 500, 360, 42
columns = 4
rows = int(math.ceil(len(poses) / columns))
legend_height = 34
montage = np.full((legend_height + rows * tile_height, columns * tile_width, 3), 24, dtype=np.uint8)
for index, pose in enumerate(poses):
union = ((pose.yolo_mask > 0) | (pose.refined_mask > 0)).astype(np.uint8) * 255
x1, y1, x2, y2 = v1.mask_bbox(union)
bw, bh = max(1.0, x2 - x1), max(1.0, y2 - y1)
padding = 0.18
x1 = max(0, int(round(x1 - bw * padding)))
x2 = min(union.shape[1], int(round(x2 + bw * padding)))
y1 = max(0, int(round(y1 - bh * padding)))
y2 = min(union.shape[0], int(round(y2 + bh * padding)))
crop = cv2.cvtColor(pose.frame_bgr[y1:y2, x1:x2], cv2.COLOR_BGR2RGB)
yolo_crop = pose.yolo_mask[y1:y2, x1:x2]
sam_crop = pose.refined_mask[y1:y2, x1:x2]
yolo_contours, _ = cv2.findContours(yolo_crop, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
sam_contours, _ = cv2.findContours(sam_crop, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(crop, yolo_contours, -1, (232, 76, 92), 3, lineType=cv2.LINE_AA)
cv2.drawContours(crop, sam_contours, -1, (52, 204, 132), 2, lineType=cv2.LINE_AA)
body = letterbox(crop, tile_width, tile_height - header, (18, 18, 18))
tile = np.full((tile_height, tile_width, 3), 24, dtype=np.uint8)
tile[header:] = body
metrics = pose.sam_metrics
label = (
f"{pose.time:g}s final IoU={metrics['final_iou']:.3f} "
f"rec={metrics['final_recall']:.3f} prec={metrics['final_precision']:.3f}"
)
cv2.putText(tile, label, (10, 27), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (238, 238, 238), 1, cv2.LINE_AA)
row, column = divmod(index, columns)
y0 = legend_height + row * tile_height
montage[y0 : y0 + tile_height, column * tile_width : (column + 1) * tile_width] = tile
cv2.putText(montage, "Boundary QA", (12, 23), cv2.FONT_HERSHEY_SIMPLEX, 0.52, (238, 238, 238), 1, cv2.LINE_AA)
cv2.putText(montage, "red: YOLO seed", (140, 23), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (232, 76, 92), 1, cv2.LINE_AA)
cv2.putText(montage, "green: SAM-refined", (285, 23), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (52, 204, 132), 1, cv2.LINE_AA)
cv2.imwrite(str(out_dir / "sam_refinement_qa.jpg"), cv2.cvtColor(montage, cv2.COLOR_RGB2BGR), [cv2.IMWRITE_JPEG_QUALITY, 94])
def save_sam_metrics_csv(poses: list[Pose], out_dir: Path) -> None:
fields = [
"time_s",
"sam_score",
"raw_iou",
"raw_recall",
"raw_precision",
"raw_area_ratio",
"final_iou",
"final_recall",
"final_precision",
"final_area_ratio",
"fallback_to_yolo",
]
with (out_dir / "sam_metrics.csv").open("w", encoding="utf-8", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fields, lineterminator="\n")
writer.writeheader()
for pose in poses:
writer.writerow({"time_s": f"{pose.time:.3f}", **{field: pose.sam_metrics[field] for field in fields[1:]}})
def save_comparison(
v1_image_path: Path,
true_image_path: Path,
layout_image_path: Path,
overlap_report: dict[str, Any],
out_path: Path,
) -> None:
images = [
cv2.cvtColor(cv2.imread(str(v1_image_path)), cv2.COLOR_BGR2RGB),
cv2.cvtColor(cv2.imread(str(true_image_path)), cv2.COLOR_BGR2RGB),
cv2.cvtColor(cv2.imread(str(layout_image_path)), cv2.COLOR_BGR2RGB),
]
if any(image is None for image in images):
raise RuntimeError("Could not read one of the comparison inputs")
reduction = 100.0 * float(overlap_report["relative_reduction"]["near_field"])
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 = [
"v1 baseline • 20 poses • YOLO masks",
"v2 control • 12 poses • SAM • source positions",
f"v2 proposed • layout expanded • near-pose overlap reduced {reduction:.1f}%",
]
for axis, image, title in zip(axes, images, titles):
axis.imshow(image)
axis.set_title(title, fontsize=8.5, 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 aggregate_sam_metrics(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()
seed_dir = args.seed_dir.expanduser().resolve()
checkpoint = args.sam_checkpoint.expanduser().resolve()
out_dir = args.out_dir.expanduser().resolve()
for required in [video, config_path, seed_dir / "detections.json", seed_dir / "masks.npz"]:
if not required.exists():
print(f"Required input not found: {required}", file=sys.stderr)
return 2
out_dir.mkdir(parents=True, exist_ok=True)
config = load_json(config_path)
sample_times = [float(value) for value in config["sample_times"]]
seed_records, seed_masks_all = load_seed_masks(seed_dir)
missing = [time for time in sample_times if time not in seed_masks_all]
if missing:
raise RuntimeError(f"v2 sample times missing from v1 seed masks: {missing}")
frames, video_metadata = read_source_frames(
video,
seed_records,
sample_times,
int(config["render_width"]),
)
seed_masks = {time: seed_masks_all[time] for time in sample_times}
for time in sample_times:
if seed_masks[time].shape != frames[time].shape[:2]:
seed_masks[time] = cv2.resize(
seed_masks[time],
(frames[time].shape[1], frames[time].shape[0]),
interpolation=cv2.INTER_NEAREST,
)
metrics_by_time: dict[float, dict[str, Any]] = {}
prompts_by_time: dict[str, Any] = {}
refined_masks: dict[float, np.ndarray] = {}
cache_path = out_dir / "refined_masks.npz"
metrics_path = out_dir / "sam_metrics.json"
if args.reuse_refined:
if not cache_path.exists() or not metrics_path.exists():
raise RuntimeError("--reuse-refined requested, but refined mask cache or metrics are missing")
archive = np.load(cache_path)
for index, time in enumerate(sample_times):
refined_masks[time] = archive[f"mask_{index:03d}"].astype(np.uint8)
archive.close()
cached_metrics = load_json(metrics_path)
metrics_by_time = {float(row["time_s"]): row["metrics"] for row in cached_metrics["frames"]}
print(f"Reusing {len(refined_masks)} SAM-refined masks from {out_dir}")
checkpoint_hash = str(config["sam"]["checkpoint_sha256"])
else:
if SamPredictor is None or sam_model_registry is None:
print(f"segment-anything import failed: {_SAM_IMPORT_ERROR}", file=sys.stderr)
return 2
if not checkpoint.exists():
print(
"SAM checkpoint not found. Run trajectory_project/scripts/download_sam_checkpoint.py first.",
file=sys.stderr,
)
return 2
checkpoint_hash = sha256sum(checkpoint)
expected_hash = str(config["sam"]["checkpoint_sha256"])
if checkpoint_hash != expected_hash:
raise RuntimeError(f"SAM checkpoint SHA256 mismatch: expected {expected_hash}, got {checkpoint_hash}")
model_type = str(config["sam"]["model_type"])
sam = sam_model_registry[model_type](checkpoint=str(checkpoint))
sam.to(device=args.device)
sam.eval()
predictor = SamPredictor(sam)
for index, time in enumerate(sample_times):
refined, metrics, prompts = refine_one_mask(
predictor,
frames[time],
seed_masks[time],
config["sam"],
seed=int(round(time * 1000)) + index,
)
refined_masks[time] = refined
metrics_by_time[time] = metrics
prompts_by_time[config_key(time)] = prompts
print(
f"{time:5.1f}s SAM score={metrics['sam_score']:.3f} "
f"final IoU={metrics['final_iou']:.3f} recall={metrics['final_recall']:.3f} "
f"precision={metrics['final_precision']:.3f}"
)
del predictor
del sam
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
except Exception:
pass
poses = build_poses(
config,
seed_records,
frames,
seed_masks,
refined_masks,
metrics_by_time,
)
refined_by_time = {pose.time: pose.refined_mask for pose in poses}
background = make_background(frames, refined_by_time, config)
source_path = np.array([row["foot_xy"] for row in seed_records], dtype=np.float32)
true_canvas = render_composite(background, poses, source_path, config, "true_position")
layout_canvas = render_composite(background, poses, source_path, config, "layout_expanded")
cv2.imwrite(str(out_dir / "background_plate.png"), cv2.cvtColor(background, cv2.COLOR_RGB2BGR))
cv2.imwrite(str(out_dir / "composite_true_position_rgb.png"), cv2.cvtColor(true_canvas, cv2.COLOR_RGB2BGR))
cv2.imwrite(str(out_dir / "composite_layout_expanded_rgb.png"), cv2.cvtColor(layout_canvas, cv2.COLOR_RGB2BGR))
save_publication_figure(
true_canvas,
out_dir / "trajectory_v2_true_position",
config,
"true_position",
annotated=True,
formats=("png",),
)
save_publication_figure(
layout_canvas,
out_dir / "trajectory_v2_layout_expanded_clean",
config,
"layout_expanded",
annotated=False,
formats=("png", "tiff", "svg", "pdf"),
)
save_publication_figure(
layout_canvas,
out_dir / "trajectory_v2_layout_expanded_annotated",
config,
"layout_expanded",
annotated=True,
formats=("png", "tiff", "svg", "pdf"),
)
save_refined_records(poses, out_dir)
save_layout_map(poses, config, out_dir)
save_sam_metrics_csv(poses, out_dir)
save_sam_qa(poses, out_dir)
overlap_report = compute_overlap_report(poses)
write_json(out_dir / "overlap_metrics.json", overlap_report)
sam_frames = [{"time_s": pose.time, "metrics": pose.sam_metrics} for pose in poses]
sam_report = {"summary": aggregate_sam_metrics(poses), "frames": sam_frames}
write_json(metrics_path, sam_report)
if prompts_by_time:
write_json(out_dir / "sam_prompts.json", prompts_by_time)
save_comparison(
seed_dir / "trajectory_annotated.png",
out_dir / "trajectory_v2_true_position.png",
out_dir / "trajectory_v2_layout_expanded_annotated.png",
overlap_report,
out_dir / "comparison_v1_v2.jpg",
)
metadata = {
"version": config["version"],
"video": display_path(video),
"config": display_path(config_path),
"seed_directory": display_path(seed_dir),
"output_directory": display_path(out_dir),
"sam_checkpoint_filename": checkpoint.name,
"sam_checkpoint_sha256": checkpoint_hash,
"sam_device": args.device,
"sample_times_s": sample_times,
"selection_note": config["selection_note"],
"pose_transform": "translation only; source scale_factor = 1.0; no rotation or deformation",
"video_metadata": video_metadata,
"sam_summary": sam_report["summary"],
"overlap_summary": overlap_report,
}
write_json(out_dir / "run_metadata.json", metadata)
print(f"Wrote v2 outputs to {out_dir}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
#!/usr/bin/env python3
"""Build the v2 G1 trajectory plate with SAM-refined masks and layout expansion.
The v2 pipeline deliberately separates two meanings:
1. ``true-position`` keeps every selected pose at its source image coordinate.
2. ``layout-expanded`` translates the same source-scale cut-outs to documented
display coordinates so overlapping poses can be read in a paper teaser.
The grey dashed line in the layout-expanded plate is the source image-plane
trajectory. The coloured line links display positions and is not presented as
a physical path. No pose is rescaled, rotated, generated, or deformed.
Publication exports: ``.png`` preview, ``.tiff`` at 600 dpi, and editable-text
``.svg`` / ``.pdf`` files.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import json
import math
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable
import cv2
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patheffects
from matplotlib.lines import Line2D
from matplotlib.patches import FancyBboxPatch, Rectangle
from PIL import Image
import build_trajectory_figure as v1
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 segment_anything import SamPredictor, sam_model_registry
except Exception as exc: # pragma: no cover - useful command-line failure
SamPredictor = None
sam_model_registry = None
_SAM_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_v2_sam_layout.json"
DEFAULT_SEED_DIR = PROJECT_ROOT / "trajectory_project" / "outputs" / "v1"
DEFAULT_CHECKPOINT = PROJECT_ROOT / "trajectory_project" / "models" / "sam_vit_b_01ec64.pth"
DEFAULT_OUT = PROJECT_ROOT / "trajectory_project" / "outputs" / "v2_sam_layout"
class 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
color_rgb: np.ndarray
hero: bool
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("--seed-dir", type=Path, default=DEFAULT_SEED_DIR)
parser.add_argument("--sam-checkpoint", type=Path, default=DEFAULT_CHECKPOINT)
parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT)
parser.add_argument("--device", default="cuda:0", help="SAM device, e.g. cuda:0 or cpu")
parser.add_argument(