hkust-aaron's picture
Whole-video action labels, task graphs and robot-learning exports
3ae204c verified
Raw History Blame Contribute Delete
4.1 kB
"""Automatic click prompts for target-tissue tracking (input to 11_sam31_target_tissue.py).
Usage: python 20_tissue_clicks.py <pack_dir> <out.json> [skip clip ids, e.g. 5,40,43]
For each clip and each tissue target named in layer5_actions/labels/clip_XX.json,
find the action segments that act on it (target text contains "[id]" and the verb
touches tissue). In the middle third of those segments, at frames where the acting
instrument has a computed tip (layer4_tool_kinematics/tool_tips.csv), place points
just ahead of the tip along the shaft direction:
tip + 14 u, tip + 28 u, tip + 14 u + 10 n (u = entry->tip unit vector, n = normal)
A point is kept only if it is inside the image and at least 4 px away from every
instrument or gauze mask in dense_tracks/. The frame with the most valid points
(at least 2) wins, longer segments first. Targets with no valid frame are skipped
and listed in the output under "skipped".
"""
import csv
import json
import re
import sys
from pathlib import Path
import cv2
import numpy as np
pack, out = Path(sys.argv[1]), Path(sys.argv[2])
skip = {int(x) for x in sys.argv[3].split(",")} if len(sys.argv) > 3 else set()
ACT = {"grasp", "hold", "probe", "press", "retract", "peel", "position", "coagulate", "blunt_dissect",
"counter_traction", "open_jaws", "lift_off", "regrasp"}
W, H = 720, 576
tips = {}
with open(pack / "layer4_tool_kinematics" / "tool_tips.csv") as fh:
for r in csv.DictReader(fh):
if r["tip_x"] and r["entry_x"]:
tips[(int(r["frame"]), int(r["track_id"]))] = tuple(float(r[k]) for k in ("tip_x", "tip_y", "entry_x", "entry_y"))
result, skipped = {}, []
kernel = np.ones((9, 9), np.uint8)
for lp in sorted((pack / "layer5_actions" / "labels").glob("clip_*.json")):
lab = json.load(open(lp))
cid = lab["clip_id"]
if cid in skip:
continue
objs = []
for oid, name in lab["tissue_targets"].items():
segs = [dict(zip(["track_id", "start_frame", "end_frame", "verb", "target"], s[:5])) for s in lab["segments"]]
segs = [s for s in segs if f"[{oid}]" in s["target"] and s["verb"] in ACT]
segs.sort(key=lambda s: -(s["end_frame"] - s["start_frame"]))
best = None
for s in segs:
a, b = s["start_frame"], s["end_frame"]
lo, hi = a + (b - a) // 3, b - (b - a) // 3
for f in range(lo, hi + 1, 2):
tp = tips.get((f, s["track_id"]))
if not tp:
continue
tx, ty, ex, ey = tp
u = np.array([tx - ex, ty - ey])
if np.linalg.norm(u) < 1:
continue
u /= np.linalg.norm(u)
nrm = np.array([-u[1], u[0]])
cand = [np.array([tx, ty]) + 14 * u, np.array([tx, ty]) + 28 * u,
np.array([tx, ty]) + 14 * u + 10 * nrm]
inst = cv2.imread(str(pack / "dense_tracks" / "masks" / f"clip_{cid:02d}" / f"{f:05d}.png"), 0)
block = cv2.dilate((inst > 0).astype(np.uint8), kernel)
ok = [[int(round(x)), int(round(y))] for x, y in cand
if 2 <= x < W - 2 and 2 <= y < H - 2 and not block[int(round(y)), int(round(x))]]
if len(ok) >= 2 and (best is None or len(ok) > len(best[1])):
best = (f, ok, s["track_id"], s["verb"])
if len(ok) == 3:
break
if best and len(best[1]) == 3:
break
if best:
objs.append({"id": int(oid), "name": name, "frame": best[0], "clicks": best[1],
"from_segment": {"track_id": best[2], "verb": best[3]}})
else:
skipped.append({"clip_id": cid, "id": int(oid), "name": name})
if objs:
result[str(cid)] = {"keyframe": int(np.median([o["frame"] for o in objs])), "objects": objs}
json.dump({"clips": result, "skipped": skipped}, open(out, "w"), indent=1)
print("clips", len(result), "objects", sum(len(v["objects"]) for v in result.values()), "skipped", len(skipped))