File size: 2,495 Bytes
07f5340
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Layer 1: per-second usability timeline from the per-frame metrics.

Usage: python 03_quality_timeline.py <frame_metrics.csv> <out_csv> <out_summary_json>

scene_state boundaries come from frame-by-frame visual review of source frames
17350-17398 (camera starts leaving the field at frame 17374, last tissue seen
at 17382, trocar/room from 17384). Flags are simple thresholds on the metrics:
  blur          median sharpness of the second < 150 (about the 5th percentile)
  glare         mean saturated-pixel fraction > 0.03
  low_red       mean red_ratio < 0.43 (haze, smoke or a near-lens grey object)
usable = intracorporeal and not blur.
"""
import csv
import json
import sys
from statistics import mean, median

WITHDRAW_START, EXTRA_START, FPS = 17374, 17384, 25

rows = list(csv.DictReader(open(sys.argv[1])))
out, summary = [], {"seconds_total": 0, "intracorporeal": 0, "usable": 0, "blur": 0, "glare": 0, "low_red": 0}
for s in range(0, len(rows), FPS):
    chunk = rows[s:s + FPS]
    first, last = int(chunk[0]["frame_index"]), int(chunk[-1]["frame_index"])
    if last < WITHDRAW_START:
        state = "intracorporeal"
    elif first >= EXTRA_START:
        state = "extracorporeal"
    else:
        state = "camera_withdrawal"
    sharp = median(float(r["sharpness"]) for r in chunk)
    sat = mean(float(r["saturated"]) for r in chunk)
    red = mean(float(r["red_ratio"]) for r in chunk)
    motion = mean(float(r["motion"]) for r in chunk)
    blur, glare, low_red = sharp < 150, sat > 0.03, red < 0.43
    usable = state == "intracorporeal" and not blur
    out.append([s // FPS, first, last, state, round(sharp, 1), round(red, 3), round(sat, 4), round(motion, 2),
                int(blur), int(glare), int(low_red), int(usable)])
    summary["seconds_total"] += 1
    if state == "intracorporeal":
        summary["intracorporeal"] += 1
        summary["usable"] += usable
        summary["blur"] += blur
        summary["glare"] += glare
        summary["low_red"] += low_red

with open(sys.argv[2], "w", newline="") as f:
    w = csv.writer(f)
    w.writerow(["second", "first_frame", "last_frame", "scene_state", "median_sharpness", "mean_red_ratio",
                "mean_saturated", "mean_motion", "blur", "glare", "low_red", "usable"])
    w.writerows(out)
summary = {k: int(v) for k, v in summary.items()}
summary["note"] = "blur/glare/low_red/usable are counted over intracorporeal seconds only"
json.dump(summary, open(sys.argv[3], "w"), indent=1)
print(summary)