File size: 5,072 Bytes
f20e058
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Camera (laparoscope) motion between consecutive frames, and tool motion with it removed.

Usage: python 15_camera_motion.py <pack_dir>

The image motion of a tool tip mixes two things: the tool moving and the camera
moving. For learning what the instrument did, the camera part has to come out.
For each frame pair:
  - corner features on the background only (instrument and gauze masks from
    dense_tracks/, dilated by 15 px, are excluded)
  - pyramidal Lucas-Kanade flow, then a RANSAC similarity transform
    (translation, rotation, uniform scale = zoom) from frame t-1 to t
  - inlier_ratio says how well one rigid transform explains the background;
    tissue moves and deforms, so values well under 1 are normal
Then for each instrument tip: compensated displacement = tip_t - T(tip_{t-1}),
i.e. what the tip did relative to the tissue around it.

Writes layer4_tool_kinematics/camera_motion.csv (per frame) and
tool_motion_compensated.csv (per instrument-frame).
"""
import csv
import json
import sys
from pathlib import Path

import cv2
import numpy as np

pack = Path(sys.argv[1])
L4 = pack / "layer4_tool_kinematics"
FPS = 25
cap = cv2.VideoCapture(str(pack / "video" / "laparoscopic_sample_001_intracorporeal.mp4"))
kernel = np.ones((31, 31), np.uint8)

cam, prev, prev_mask = [], None, None
f = 0
while True:
    ok, img = cap.read()
    if not ok:
        break
    g = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    inst = cv2.imread(str(pack / "dense_tracks" / "masks" / f"clip_{f // 250:02d}" / f"{f:05d}.png"), 0)
    bg = (cv2.dilate((inst > 0).astype(np.uint8), kernel) == 0).astype(np.uint8) * 255
    row = {"frame": f, "time_s": round(f / FPS, 2), "tx": "", "ty": "", "rot_deg": "", "scale": "", "n_tracked": 0,
           "inlier_ratio": "", "M": None}
    if prev is not None:
        pts = cv2.goodFeaturesToTrack(prev, 400, 0.01, 8, mask=prev_mask)
        if pts is not None and len(pts) >= 12:
            nxt, st, _ = cv2.calcOpticalFlowPyrLK(prev, g, pts, None, winSize=(21, 21), maxLevel=3)
            p0, p1 = pts[st[:, 0] == 1], nxt[st[:, 0] == 1]
            row["n_tracked"] = int(len(p0))
            if len(p0) >= 12:
                M, inl = cv2.estimateAffinePartial2D(p0, p1, method=cv2.RANSAC, ransacReprojThreshold=2.0)
                if M is not None:
                    s = float(np.hypot(M[0, 0], M[1, 0]))
                    row.update(tx=round(float(M[0, 2]), 2), ty=round(float(M[1, 2]), 2),
                               rot_deg=round(float(np.degrees(np.arctan2(M[1, 0], M[0, 0]))), 3),
                               scale=round(s, 4), inlier_ratio=round(float(inl.mean()), 3), M=M)
    cam.append(row)
    prev, prev_mask, f = g, bg, f + 1

with open(L4 / "camera_motion.csv", "w", newline="") as fh:
    cols = ["frame", "time_s", "tx", "ty", "rot_deg", "scale", "n_tracked", "inlier_ratio"]
    w = csv.DictWriter(fh, cols, extrasaction="ignore")
    w.writeheader()
    w.writerows(cam)

tips = {}
with open(L4 / "tool_tips.csv") as fh:
    for r in csv.DictReader(fh):
        if r["tip_x_smooth"]:
            tips[(int(r["frame"]), int(r["track_id"]))] = (float(r["tip_x_smooth"]), float(r["tip_y_smooth"]), r)
rows = []
for (f, t), (x, y, r) in sorted(tips.items()):
    p = tips.get((f - 1, t))
    M = cam[f]["M"] if f < len(cam) else None
    if not p or p[2]["clip_id"] != r["clip_id"]:
        continue
    dx_img, dy_img = x - p[0], y - p[1]
    if M is not None:
        px, py = M @ np.array([p[0], p[1], 1.0])
        dx, dy = x - px, y - py
    else:
        dx = dy = None
    rows.append({"frame": f, "clip_id": r["clip_id"], "track_id": t, "category": r["category"],
                 "dx_image": round(dx_img, 2), "dy_image": round(dy_img, 2),
                 "dx_camera_removed": "" if dx is None else round(float(dx), 2),
                 "dy_camera_removed": "" if dy is None else round(float(dy), 2),
                 "speed_camera_removed_px_s": "" if dx is None else round(float(np.hypot(dx, dy)) * FPS, 1),
                 "camera_inlier_ratio": cam[f]["inlier_ratio"]})
with open(L4 / "tool_motion_compensated.csv", "w", newline="") as fh:
    w = csv.DictWriter(fh, list(rows[0]))
    w.writeheader()
    w.writerows(rows)

ok = [c for c in cam if c["M"] is not None]
inl = np.array([c["inlier_ratio"] for c in ok])
sp = np.array([np.hypot(c["tx"], c["ty"]) for c in ok])
summary = {"frames": len(cam), "frames_with_estimate": len(ok), "median_inlier_ratio": round(float(np.median(inl)), 3),
           "frames_inlier_ratio_ge_0.5": int((inl >= 0.5).sum()),
           "median_camera_translation_px_per_frame": round(float(np.median(sp)), 2),
           "tool_rows": len(rows),
           "median_tip_speed_image_px_s": round(float(np.median([np.hypot(r["dx_image"], r["dy_image"]) * FPS for r in rows])), 1),
           "median_tip_speed_camera_removed_px_s": round(float(np.median(
               [r["speed_camera_removed_px_s"] for r in rows if r["speed_camera_removed_px_s"] != ""])), 1)}
json.dump(summary, open(L4 / "camera_motion_summary.json", "w"), indent=1)
print(summary)