File size: 3,664 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
"""Relative monocular depth for every frame (Depth Anything V2 Small), sampled at tool tips (CUDA machine).

Usage: python 16_depth.py <video> <model_dir> <tool_tips.csv> <dense_masks_dir> <out_dir> <clips e.g. 5,40,43>

Depth Anything V2 predicts relative inverse depth (larger = closer) up to an
unknown scale and shift per frame; it is not metric. To make values comparable
over time each frame is normalised by the median of its background pixels
(instrument masks excluded): rel_inv_depth = prediction / background median.
  > 1 closer to the lens than the typical tissue, < 1 farther away.
Per instrument-frame the tip value is the median in a 7x7 window at the tip and
the shaft value the median over the mask.
For the listed clips the full maps are also saved every 5th frame as 16-bit PNG
(360x288, value = rel_inv_depth x 10000).

Writes tool_depth.csv and depth_maps/clip_XX/<frame>.png.
"""
import csv
import sys
from pathlib import Path

import cv2
import numpy as np
import torch
from transformers import AutoImageProcessor, AutoModelForDepthEstimation

video, model_dir, tips_csv, masks_dir, out = sys.argv[1], sys.argv[2], sys.argv[3], Path(sys.argv[4]), Path(sys.argv[5])
save_clips = {int(x) for x in sys.argv[6].split(",")}
out.mkdir(parents=True, exist_ok=True)
proc = AutoImageProcessor.from_pretrained(model_dir)
model = AutoModelForDepthEstimation.from_pretrained(model_dir).cuda().eval().half()

tips = {}
with open(tips_csv) as fh:
    for r in csv.DictReader(fh):
        tips.setdefault(int(r["frame"]), []).append(r)

cap = cv2.VideoCapture(video)
rows, f, BATCH = [], 0, 16
buf = []


def flush(buf):
    imgs = [b[1][..., ::-1] for b in buf]
    inp = proc(images=imgs, return_tensors="pt").to("cuda")
    with torch.no_grad():
        pred = model(pixel_values=inp["pixel_values"].half()).predicted_depth.float()
    pred = torch.nn.functional.interpolate(pred[:, None], size=(576, 720), mode="bicubic", align_corners=False)[:, 0]
    for (fi, _), d in zip(buf, pred.cpu().numpy()):
        inst = cv2.imread(str(masks_dir / f"clip_{fi // 250:02d}" / f"{fi:05d}.png"), 0)
        bgm = np.median(d[inst == 0]) if (inst == 0).any() else np.median(d)
        rel = d / max(bgm, 1e-6)
        for r in tips.get(fi, []):
            tid = int(r["track_id"])
            m = inst == tid
            row = {"frame": fi, "clip_id": r["clip_id"], "track_id": tid, "category": r["category"],
                   "shaft_rel_inv_depth": round(float(np.median(rel[m])), 4) if m.any() else "",
                   "tip_rel_inv_depth": ""}
            if r["tip_x"]:
                x, y = int(round(float(r["tip_x"]))), int(round(float(r["tip_y"])))
                win = rel[max(0, y - 3):y + 4, max(0, x - 3):x + 4]
                row["tip_rel_inv_depth"] = round(float(np.median(win)), 4)
            rows.append(row)
        c = fi // 250
        if c in save_clips and fi % 5 == 0:
            (out / "depth_maps" / f"clip_{c:02d}").mkdir(parents=True, exist_ok=True)
            small = cv2.resize(rel, (360, 288), interpolation=cv2.INTER_AREA)
            cv2.imwrite(str(out / "depth_maps" / f"clip_{c:02d}" / f"{fi:05d}.png"),
                        np.clip(small * 10000, 0, 65535).astype(np.uint16))


while True:
    ok, img = cap.read()
    if not ok:
        break
    buf.append((f, img))
    f += 1
    if len(buf) == BATCH:
        flush(buf)
        buf = []
    if f % 2000 == 0:
        print("frames", f, flush=True)
if buf:
    flush(buf)
with open(out / "tool_depth.csv", "w", newline="") as fh:
    w = csv.DictWriter(fh, list(rows[0]))
    w.writeheader()
    w.writerows(rows)
print("done frames", f, "rows", len(rows))