Datasets:
Download annotated/scripts/10_tool_tips.py from hkust-aaron/laparoscopic-robotic-vision-sample: direct link, hf CLI and curl.
- Browser
- Download file 7.02 kB
-
https://huggingface.co/datasets/hkust-aaron/laparoscopic-robotic-vision-sample/resolve/main/annotated/scripts/10_tool_tips.py
- Command line
-
hf download hf://datasets/hkust-aaron/laparoscopic-robotic-vision-sample/annotated/scripts/10_tool_tips.py
-
curl -L -o 10_tool_tips.py https://huggingface.co/datasets/hkust-aaron/laparoscopic-robotic-vision-sample/resolve/main/annotated/scripts/10_tool_tips.py
7.02 kB
| """2D tool kinematics from the dense SAM 3.1 tracks: tip, shaft entry and shaft angle per frame. | |
| Usage: python 10_tool_tips.py <pack_dir> | |
| For every instrument track (gauze is skipped) in every frame: | |
| mask = largest connected piece of the track's mask (stray fragments ignored) | |
| entry = centroid of the mask pixels closest to the image border (where the shaft | |
| comes into view); masks often stop a few pixels short of the edge | |
| tip = mean of the mask pixels farthest from the entry (top 0.5 % by distance) | |
| angle = direction entry -> tip, degrees, 0 = pointing right, 90 = pointing down | |
| A mask that comes no closer than NEAR px to the border has no defined entry; tip is | |
| left empty and flagged. Tips are then median-filtered over 5 frames within a track, and speed is | |
| the frame-to-frame displacement of the smoothed tip in px/s (25 fps). | |
| Validation: on the 69 keyframes the computed tip is compared with the hand-placed | |
| tip in gold_subset/instances_coco_v2.json for the same instance. | |
| Writes layer4_tool_kinematics/tool_tips.csv, track_summary.csv, validation.json. | |
| """ | |
| import csv | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| pack = Path(sys.argv[1]) | |
| dense, out = pack / "dense_tracks", pack / "layer4_tool_kinematics" | |
| out.mkdir(exist_ok=True) | |
| H, W, FPS, EDGE, NEAR = 576, 720, 25, 3, 25 | |
| yy, xx = np.mgrid[0:H, 0:W] | |
| border_dist = np.minimum.reduce([xx, yy, W - 1 - xx, H - 1 - yy]) | |
| rows = [] | |
| for tp in sorted((dense / "tracks").glob("clip_*.json")): | |
| meta = json.load(open(tp)) | |
| c = meta["clip_id"] | |
| tools = {int(k): v for k, v in meta["tracks"].items() if v["category"] != "gauze"} | |
| for f in range(meta["start_frame"], meta["start_frame"] + meta["num_frames"]): | |
| inst = cv2.imread(str(dense / "masks" / f"clip_{c:02d}" / f"{f:05d}.png"), 0) | |
| for tid in np.unique(inst)[1:]: | |
| tid = int(tid) | |
| if tid not in tools: | |
| continue | |
| m = inst == tid | |
| r = {"frame": f, "time_s": round(f / FPS, 2), "clip_id": c, "track_id": tid, | |
| "source": tools[tid]["source"], "category": tools[tid]["category"], "area": int(m.sum())} | |
| # largest connected piece only, so stray fragments cannot become the tip | |
| n_cc, lab, stats, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8), connectivity=8) | |
| m = lab == 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) | |
| ys, xs = np.nonzero(m) | |
| # entry: mask pixels closest to the image border, if that is within NEAR px | |
| bd = border_dist[ys, xs] | |
| sel = bd <= bd.min() + EDGE | |
| bx, by = (xs[sel], ys[sel]) if bd.min() <= NEAR else (np.array([]), np.array([])) | |
| if len(bx) == 0: | |
| r.update(tip_x=None, tip_y=None, entry_x=None, entry_y=None, shaft_angle_deg=None, | |
| flag="no_border_contact") | |
| else: | |
| ex, ey = bx.mean(), by.mean() | |
| d = np.hypot(xs - ex, ys - ey) | |
| far = d >= np.quantile(d, 0.995) | |
| tx, ty = xs[far].mean(), ys[far].mean() | |
| r.update(tip_x=round(float(tx), 1), tip_y=round(float(ty), 1), entry_x=round(float(ex), 1), | |
| entry_y=round(float(ey), 1), | |
| shaft_angle_deg=round(float(np.degrees(np.arctan2(ty - ey, tx - ex))), 1), | |
| flag="tip_on_border" if (tx < EDGE + 2 or tx > W - EDGE - 3 or ty < EDGE + 2 or | |
| ty > H - EDGE - 3) else "") | |
| rows.append(r) | |
| # smoothing and speed, per (clip, track) | |
| rows.sort(key=lambda r: (r["clip_id"], r["track_id"], r["frame"])) | |
| groups = {} | |
| for r in rows: | |
| groups.setdefault((r["clip_id"], r["track_id"]), []).append(r) | |
| for g in groups.values(): | |
| for i, r in enumerate(g): | |
| win = [q for q in g[max(0, i - 2):i + 3] if q["tip_x"] is not None and abs(q["frame"] - r["frame"]) <= 2] | |
| if r["tip_x"] is None or len(win) < 3: | |
| r["tip_x_smooth"] = r["tip_y_smooth"] = None | |
| else: | |
| r["tip_x_smooth"] = round(float(np.median([q["tip_x"] for q in win])), 1) | |
| r["tip_y_smooth"] = round(float(np.median([q["tip_y"] for q in win])), 1) | |
| p = g[i - 1] if i else None | |
| if p and p["frame"] == r["frame"] - 1 and p.get("tip_x_smooth") is not None and r["tip_x_smooth"] is not None: | |
| r["speed_px_s"] = round(float(np.hypot(r["tip_x_smooth"] - p["tip_x_smooth"], | |
| r["tip_y_smooth"] - p["tip_y_smooth"]) * FPS), 1) | |
| else: | |
| r["speed_px_s"] = None | |
| cols = ["frame", "time_s", "clip_id", "track_id", "source", "category", "tip_x", "tip_y", "tip_x_smooth", | |
| "tip_y_smooth", "entry_x", "entry_y", "shaft_angle_deg", "speed_px_s", "area", "flag"] | |
| rows.sort(key=lambda r: (r["frame"], r["track_id"])) | |
| with open(out / "tool_tips.csv", "w", newline="") as fh: | |
| w = csv.DictWriter(fh, cols) | |
| w.writeheader() | |
| w.writerows(rows) | |
| with open(out / "track_summary.csv", "w", newline="") as fh: | |
| w = csv.writer(fh) | |
| w.writerow(["clip_id", "track_id", "source", "category", "first_frame", "last_frame", "frames", | |
| "frames_with_tip", "path_length_px", "median_speed_px_s", "max_speed_px_s"]) | |
| for (c, t), g in sorted(groups.items()): | |
| sp = [r["speed_px_s"] for r in g if r["speed_px_s"] is not None] | |
| w.writerow([c, t, g[0]["source"], g[0]["category"], g[0]["frame"], g[-1]["frame"], len(g), | |
| sum(r["tip_x"] is not None for r in g), round(sum(sp) / FPS, 1), | |
| round(float(np.median(sp)), 1) if sp else "", round(max(sp), 1) if sp else ""]) | |
| # validation against hand-placed keyframe tips | |
| coco = json.load(open(pack / "gold_subset" / "instances_coco_v2.json")) | |
| cat = {c["id"]: c["name"] for c in coco["categories"]} | |
| idx = {(r["frame"], r["track_id"]): r for r in rows} | |
| errs, n_ref, no_tip = [], 0, 0 | |
| for a in coco["annotations"]: | |
| if not a["tip"] or cat[a["category_id"]] == "gauze": | |
| continue | |
| r = idx.get((a["image_id"], 100 + a["instance_index_in_mask_png"])) | |
| if r is None: | |
| continue | |
| n_ref += 1 | |
| if r["tip_x"] is None: | |
| no_tip += 1 | |
| continue | |
| errs.append(float(np.hypot(r["tip_x"] - a["tip"][0], r["tip_y"] - a["tip"][1]))) | |
| e = np.array(errs) | |
| val = {"reference": "hand-placed tips on keyframes (instances_coco_v2.json), click tracks only", | |
| "instances_compared": n_ref, "no_computed_tip": no_tip, | |
| "median_error_px": round(float(np.median(e)), 1), "p90_error_px": round(float(np.quantile(e, 0.9)), 1), | |
| "within_20px": round(float((e <= 20).mean()), 3), "within_40px": round(float((e <= 40).mean()), 3), | |
| "errors_px": [round(x, 1) for x in errs]} | |
| json.dump(val, open(out / "validation.json", "w"), indent=1) | |
| print("rows", len(rows), "tracks", len(groups), "with tip", sum(r["tip_x"] is not None for r in rows)) | |
| print({k: v for k, v in val.items() if k != "errors_px"}) | |