File size: 11,383 Bytes
bdd9ed1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | #!/usr/bin/env python3
"""Render deterministic complete-sequence ReInterHand full-output reviews."""
from __future__ import annotations
import argparse
import html
import json
import random
import subprocess
from pathlib import Path
import preprocess_reinterhand as pilot
def atomic_json(path: Path, value: object) -> None:
pilot.atomic_json(path, value)
def decode(ffmpeg: str, path: Path, width: int, height: int, pixel_format: str, channels: int):
process = subprocess.Popen(
[ffmpeg, "-v", "error", "-threads", "1", "-i", str(path), "-f", "rawvideo", "-pix_fmt", pixel_format, "-"],
stdout=subprocess.PIPE,
)
assert process.stdout is not None
size = width * height * channels
while True:
block = process.stdout.read(size)
if not block:
break
if len(block) != size:
raise RuntimeError(f"short decoded frame: {path}")
yield block
if process.wait() != 0:
raise RuntimeError(f"decode failed: {path}")
def mask_intensity_panel(mask, np, Image):
"""Render the native non-binary mask itself, without hiding it in RGB."""
gray = Image.fromarray(mask.astype(np.uint8), "L").convert("RGB")
from PIL import ImageDraw
draw = ImageDraw.Draw(gray)
width, height = gray.size
bar_width = min(280, max(120, width // 3))
x0, y0 = 12, max(34, height - 42)
gradient = np.tile(np.arange(256, dtype=np.uint8), (14, 1))
gradient = Image.fromarray(gradient, "L").resize((bar_width, 14)).convert("RGB")
gray.paste(gradient, (x0, y0))
draw.rectangle((x0 - 1, y0 - 1, x0 + bar_width, y0 + 14), outline=(255, 70, 70), width=2)
draw.text((x0, y0 - 17), "mask intensity: 0 black -> 255 white", fill=(255, 70, 70))
draw.text((x0, y0 + 17), f"frame min={int(mask.min())}, max={int(mask.max())}", fill=(255, 70, 70))
return gray
def mano_legend(image, Image):
"""Put an in-frame color legend next to the actual MANO overlay."""
from PIL import ImageDraw
result = image.copy()
draw = ImageDraw.Draw(result)
x0, y0 = 12, max(34, result.height - 54)
draw.rectangle((x0 - 6, y0 - 6, x0 + 238, y0 + 40), fill=(0, 0, 0))
draw.rectangle((x0, y0, x0 + 20, y0 + 14), fill=(0, 255, 255))
draw.text((x0 + 28, y0), "LEFT hand", fill=(255, 255, 255))
draw.rectangle((x0 + 116, y0, x0 + 136, y0 + 14), fill=(255, 140, 0))
draw.text((x0 + 144, y0), "RIGHT hand", fill=(255, 255, 255))
return result
def render_view(view: Path, output: Path, runtime: Path, models, faces, ffmpeg: str, modules) -> dict:
np, torch, cv2, Image, _ = modules
metadata = json.loads((view / "metainfo.json").read_text(encoding="utf-8"))
width, height = metadata["camera"]["image_size"]
total = int(metadata["num_frames"])
intrinsic = torch.load(view / "camera/intrinsic.pt", map_location="cpu", weights_only=True).numpy()
distortion_path = view / "camera/distortion.pt"
distortion = torch.load(distortion_path, map_location="cpu", weights_only=True).numpy() if distortion_path.exists() else None
motion = torch.load(view / "annotation/mano/motion.pt", map_location="cpu", weights_only=True).numpy()
valid = torch.load(view / "annotation/mano/motion_valid.pt", map_location="cpu", weights_only=True).numpy().astype(bool)
meshes = {}
for index, side in enumerate(("left", "right")):
meshes[side], _ = models[index].geometry(motion[:, index, :48], motion[:, index, 48:58], motion[:, index, 58:])
rgb_frames = decode(ffmpeg, view / "observation/rgb.mkv", width, height, "rgb24", 3)
# The lossless shared mask container is gray16le, while the preserved
# native samples occupy the uint8 range 0..255. Asking FFmpeg for 8-bit
# ``gray`` rescales 0..65535 to 0..255 and therefore collapses native
# values 0..255 to almost all black. Decode the stored words verbatim and
# only then display their native intensity.
mask_frames = decode(ffmpeg, view / "annotation/segment/mask.mkv", width, height, "gray16le", 2)
frame_rows = [json.loads(line) for line in (view / "camera/frames.jsonl").read_text(encoding="utf-8").splitlines()]
relative = Path("media") / f"{metadata['sequence_id']}__{metadata['camera_id']}.mp4"
def panels():
count = 0
for index, (rgb_bytes, mask_bytes) in enumerate(zip(rgb_frames, mask_frames)):
rgb = np.frombuffer(rgb_bytes, dtype=np.uint8).reshape(height, width, 3)
mask16 = np.frombuffer(mask_bytes, dtype="<u2").reshape(height, width)
if int(mask16.max()) > 255:
raise RuntimeError(f"native mask exceeds declared uint8 range: {view} frame {index}")
mask = mask16.astype(np.uint8)
original = Image.fromarray(rgb, "RGB")
points = {}
for hand_index, side in enumerate(("left", "right")):
if valid[index, hand_index]:
uv, _ = pilot.project_vertices(meshes[side][index], intrinsic[index], None if distortion is None else distortion[index], np, cv2)
points[side] = uv
mano = mano_legend(pilot.draw_mano_meshes(original, points, faces, Image), Image)
masked = mask_intensity_panel(mask, np, Image)
source_id = frame_rows[index].get("source_frame_id")
canvas = Image.new("RGB", (width * 3, height))
canvas.paste(pilot.label_panel(original, f"RGB | source frame {source_id}", Image), (0, 0))
canvas.paste(pilot.label_panel(mano, "shared MANO | cyan left, orange right", Image), (width, 0))
canvas.paste(pilot.label_panel(masked, "native non-binary mask | grayscale intensity", Image), (width * 2, 0))
count += 1
yield canvas
if count != total:
raise RuntimeError(f"decoded {count}/{total}: {view}")
rendered = pilot.render_review_video(panels(), output / relative, (width, height), panels=3)
return {
"camera_id": metadata["camera_id"], "view_type": metadata["view_type"],
"frames": rendered, "video": relative.as_posix(),
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--release", required=True)
parser.add_argument("--runtime", required=True)
parser.add_argument("--output", required=True)
parser.add_argument("--host-label", required=True)
parser.add_argument("--samples-per-render", type=int, default=1)
parser.add_argument("--seed", type=int, default=20260927)
parser.add_argument("--ffmpeg", default="ffmpeg")
args = parser.parse_args()
release, runtime, output = Path(args.release).resolve(), Path(args.runtime).resolve(), Path(args.output).resolve()
output.mkdir(parents=True, exist_ok=True)
modules = pilot.runtime_imports(runtime)
np, torch, _, _, smplx = modules
models = [pilot.ManoModel("left", runtime / "models", np, torch, smplx), pilot.ManoModel("right", runtime / "models", np, torch, smplx)]
with torch.no_grad():
models[0].data["shapedirs"][:, 0] *= -1
models[0].layer.shapedirs[:, 0] *= -1
faces = np.asarray(models[0].data["f"], dtype=np.int64)
groups = {"envmap_per_frame": [], "envmap_per_segment": []}
for path in sorted((release / "data").iterdir()):
if path.is_dir():
kind = "envmap_per_frame" if "__envmap_per_frame__" in path.name else "envmap_per_segment"
groups[kind].append(path.name)
rng = random.Random(f"{args.seed}:{args.host_label}")
selected = [name for kind in sorted(groups) for name in rng.sample(groups[kind], min(args.samples_per_render, len(groups[kind])))]
status = {
"schema": "reinterhand-full-random-status/v1", "stage": "rendering", "seed": args.seed,
"host_label": args.host_label, "selected": selected, "completed": [],
"sampling": "uniform complete-sequence sampling within render-type stratum on the fixed server partition",
}
atomic_json(output / "status.json", status)
cards = []
for sequence in selected:
sequence_root = release / "data" / sequence
rows = [render_view(view, output, runtime, models, faces, args.ffmpeg, modules)
for view in sorted(sequence_root.iterdir()) if (view / "metainfo.json").is_file()]
atomic_json(output / f"{sequence}.json", {"sequence": sequence, "views": rows})
status["completed"].append(sequence)
atomic_json(output / "status.json", status)
videos = "".join(
f"<details><summary>{html.escape(row['camera_id'])} · {row['view_type']} · {row['frames']} frames</summary>"
f"<video controls preload='metadata' src='{html.escape(row['video'])}' style='width:100%'></video></details>"
for row in rows
)
semantics = "独立图片集合;MKV 仅为无损批容器,播放顺序不是时间。" if "__envmap_per_frame__" in sequence else "真实时序视频序列。"
cards.append(f"<section><h2>{html.escape(sequence)}</h2><p>{semantics}</p>{videos}</section>")
atomic_json(output / "sampling.json", {
"schema": "hand-warehouse-full-random-sampling/v1", "dataset_id": "ReInterHand",
"seed": args.seed, "host_partition": args.host_label,
"method": status["sampling"], "population": {key: len(value) for key, value in groups.items()},
"selected_sequences": selected, "all_cameras": True, "all_frames": True,
})
atomic_json(output / "human-review.json", {
"dataset_id": "ReInterHand", "stage": "full_random", "status": "pending",
"reviewed_report": "index.html", "confirmed_at": None, "confirmed_by": None,
"notes": "Content fingerprints and automatic checks do not constitute human approval.",
})
page = f"""<!doctype html><html lang='zh-CN'><meta charset='utf-8'><meta name='viewport' content='width=device-width'>
<title>ReInterHand full random {html.escape(args.host_label)}</title><style>body{{font:16px/1.6 system-ui;max-width:1600px;margin:auto;padding:24px;background:#f5f6f8}}header,section{{background:#fff;padding:20px;margin:16px 0;border-radius:12px}}details{{margin:12px 0}}.pending{{color:#9a5b00;font-weight:bold}}</style>
<header><h1>ReInterHand 全量随机抽查 · {html.escape(args.host_label)}</h1><p class='pending'>人工审核:待确认</p>
<p>固定随机种子 {args.seed};按渲染类型分层抽取完整短序列,展示抽中序列的全部相机和全部帧。每个视频依次显示 RGB、MANO 网格投影、原生非二值 mask 强度图。</p>
<p><strong>MANO 图例:</strong><span style='display:inline-block;width:1em;height:1em;background:#00ffff;border:1px solid #333'></span> 青色=左手;<span style='display:inline-block;width:1em;height:1em;background:#ff8c00;border:1px solid #333'></span> 橙色=右手。<strong>Mask 图例:</strong>黑色=0,白色=255;这是连续强度,不是左右手类别。</p>
<p><code>envmap_per_frame</code> 是每帧独立更换背景的图片集合;<code>envmap_per_segment</code> 才具有视频时间关系。SHA256 只固定当前字节,不证明源一致性、语义或视觉质量。</p></header>{''.join(cards)}</html>"""
(output / "index.html").write_text(page, encoding="utf-8")
status["stage"] = "complete"
atomic_json(output / "status.json", status)
if __name__ == "__main__":
main()
|