File size: 5,524 Bytes
20cfecb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
批量可视化 contact / force 并拼成 combined 三联视频。

对 --root 下每个含 modalities/ 的 episode:
  1) 渲染 contact_vis.mp4 / force_vis.mp4 (黑底, 对齐原视频)
  2) 横向拼接 original + contact + force -> combined_vis.mp4

一遍 pass 同时写出三个 vis 文件 + combined, 不重复解码。
多进程并行, 已有 combined 默认跳过, 单 episode 失败不中断整批。

用法:
  python batch_visualize.py --root .../all_episodes
  python batch_visualize.py --root .../all_episodes --workers 8 --overwrite
  python batch_visualize.py --root .../all_episodes --glob "00*"   # 只跑匹配的
"""
import os
import json
import argparse
import traceback
import numpy as np
import cv2
from pathlib import Path
from concurrent.futures import ProcessPoolExecutor, as_completed

LABELS = ["original", "contact", "force"]


def load_norm(modalities_dir):
    with open(modalities_dir / "norm_params.json") as f:
        n = json.load(f)
    return n["max_contact"], n["max_force"]


def render_contact(contact, max_contact):
    """黑底白斑: 亮度 = 归一化接触强度"""
    c = np.clip(contact / max_contact, 0, 1)
    gray = (c * 255).astype(np.uint8)
    return cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)


def render_force(force, max_force):
    """黑底彩斑: 亮度 = |force|, 色相 = xyz 方向"""
    mag = np.sqrt((force ** 2).sum(-1))
    brightness = np.clip(mag / max_force, 0, 1)
    norm = mag.copy()
    norm[norm < 1e-8] = 1.0
    direction = force / norm[..., None]          # 单位向量 [-1,1]
    color = (direction + 1.0) / 2.0              # -> [0,1] 当 RGB
    rgb = color * brightness[..., None]
    bgr = (rgb[..., ::-1] * 255).astype(np.uint8)
    return bgr


def _fit(img, W, H):
    """模态分辨率万一和原视频不一致, resize 回去避免 hstack 崩"""
    if img.shape[1] != W or img.shape[0] != H:
        img = cv2.resize(img, (W, H), interpolation=cv2.INTER_NEAREST)
    return img


def process_episode(ep, video_name, overwrite):
    ep = Path(ep)
    mod = ep / "modalities"
    combined_path = ep / "combined_vis.mp4"

    if not mod.is_dir():
        return ep.name, "skip (no modalities/)"
    if combined_path.exists() and not overwrite:
        return ep.name, "skip (exists)"

    max_contact, max_force = load_norm(mod)

    cap = cv2.VideoCapture(str(ep / video_name))
    if not cap.isOpened():
        cap.release()
        return ep.name, f"skip (cannot open {video_name})"
    fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
    W = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    H = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    c_out = cv2.VideoWriter(str(mod / "contact" / "contact_vis.mp4"), fourcc, fps, (W, H))
    f_out = cv2.VideoWriter(str(mod / "force" / "force_vis.mp4"), fourcc, fps, (W, H))
    comb = cv2.VideoWriter(str(combined_path), fourcc, fps, (W * 3, H))

    frame_idx = 0
    while True:
        ret, orig = cap.read()
        if not ret:
            break

        cp = mod / "contact" / f"{frame_idx:06d}.npy"
        c_vis = render_contact(np.load(cp), max_contact) if cp.exists() \
            else np.zeros((H, W, 3), np.uint8)
        c_vis = _fit(c_vis, W, H)

        fp = mod / "force" / f"{frame_idx:06d}.npy"
        f_vis = render_force(np.load(fp), max_force) if fp.exists() \
            else np.zeros((H, W, 3), np.uint8)
        f_vis = _fit(f_vis, W, H)

        c_out.write(c_vis)
        f_out.write(f_vis)

        trio = [orig.copy(), c_vis.copy(), f_vis.copy()]
        for img, label in zip(trio, LABELS):
            cv2.putText(img, label, (10, 25),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)
        comb.write(np.hstack(trio))
        frame_idx += 1

    cap.release()
    c_out.release()
    f_out.release()
    comb.release()
    return ep.name, f"ok ({frame_idx} frames)"


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=str, required=True,
                        help="包含多个 episode 子目录的父目录")
    parser.add_argument("--glob", type=str, default="*",
                        help="episode 目录名匹配模式 (相对 root)")
    parser.add_argument("--video_name", type=str, default="camera2.mp4")
    parser.add_argument("--workers", type=int,
                        default=min(8, os.cpu_count() or 1))
    parser.add_argument("--overwrite", action="store_true",
                        help="重新生成已存在的 combined_vis.mp4")
    args = parser.parse_args()

    root = Path(args.root)
    ep_dirs = [p for p in sorted(root.glob(args.glob))
               if (p / "modalities").is_dir()]
    print(f"Found {len(ep_dirs)} episodes under {root}  (workers={args.workers})")

    ok = skip = fail = 0
    with ProcessPoolExecutor(max_workers=args.workers) as ex:
        futs = {ex.submit(process_episode, str(ep), args.video_name, args.overwrite): ep
                for ep in ep_dirs}
        for fut in as_completed(futs):
            ep = futs[fut]
            try:
                name, status = fut.result()
                print(f"[{name}] {status}")
                if status.startswith("ok"):
                    ok += 1
                else:
                    skip += 1
            except Exception:
                fail += 1
                print(f"[{ep.name}] FAILED\n{traceback.format_exc()}")

    print(f"\nDone. ok={ok}  skip={skip}  fail={fail}")


if __name__ == "__main__":
    main()