"""Build the instance-mask subset: 12 hand-picked frames (polygons below) plus one mid-clip frame per 10 s clip (polygons in keyframe_polygons.json). Usage: python 02_gold_subset.py [keyframe_polygons.json] A frame listed with no objects was checked and contains no instrument or gauze. The mid-clip frame of clip 66 (source frame 16625) is left out: it shows only ambiguous fragments at the image edge. Each object starts as a hand-placed polygon (drawn by Claude on a 60 px coordinate grid over the original frame). Instrument polygons are then snapped to image edges with OpenCV GrabCut: the eroded polygon is fixed foreground, everything outside a dilated polygon is fixed background, the band in between is decided by colour. The refined mask is kept only if it still agrees with the hand polygon (IoU >= 0.6); otherwise the polygon itself is used. Gauze polygons are not refined (woven texture defeats colour models); instrument masks are subtracted from them so instances never overlap. Appearance classes (not device identification): white_insulated_jawed jawed instrument with cream/white insulation dark_rod dark cylindrical rod, no visible jaws fenestrated_grasper jawed instrument with an open-window jaw gauze woven gauze-like material """ import json import sys from pathlib import Path import cv2 import numpy as np img_dir, out_dir = Path(sys.argv[1]), Path(sys.argv[2]) (out_dir / "masks").mkdir(parents=True, exist_ok=True) (out_dir / "overlays").mkdir(parents=True, exist_ok=True) W, H, FPS = 720, 576, 25 # frame -> list of (class, confidence, tip or None, polygon) POLYS = { 900: [ ("fenestrated_grasper", "high", (452, 255), [(428, 256), (372, 300), (315, 360), (272, 420), (212, 480), (160, 540), (135, 576), (300, 576), (292, 540), (322, 480), (358, 420), (398, 360), (455, 300), (480, 265), (462, 250)]), ("dark_rod", "medium", (498, 325), [(480, 325), (520, 322), (540, 360), (555, 420), (565, 480), (578, 576), (520, 576), (508, 480), (495, 420), (480, 360)]), ("gauze", "high", None, [(0, 495), (40, 490), (110, 540), (130, 576), (0, 576)]), ], 1800: [ ("white_insulated_jawed", "high", (405, 205), [(0, 435), (120, 330), (240, 245), (310, 205), (375, 168), (402, 165), (415, 195), (412, 240), (390, 255), (330, 285), (278, 320), (258, 420), (215, 500), (185, 576), (0, 576)]), ("dark_rod", "medium", None, [(422, 250), (470, 215), (492, 300), (500, 420), (508, 576), (428, 576), (424, 420)]), ("gauze", "medium", None, [(150, 440), (280, 370), (340, 400), (360, 500), (390, 576), (185, 576), (215, 500)]), ], 2400: [ ("white_insulated_jawed", "high", (390, 268), [(20, 576), (25, 555), (175, 425), (300, 300), (365, 262), (392, 258), (396, 285), (372, 320), (255, 440), (220, 500), (145, 576)]), ("dark_rod", "medium", (510, 288), [(485, 292), (538, 285), (552, 360), (568, 440), (600, 576), (520, 576), (500, 440), (490, 360)]), ], 3900: [ ("white_insulated_jawed", "high", (438, 325), [(425, 318), (447, 325), (445, 360), (400, 400), (330, 470), (290, 530), (250, 576), (140, 576), (230, 490), (300, 420), (360, 370), (400, 335)]), ("dark_rod", "low", None, [(478, 312), (510, 315), (545, 400), (575, 480), (605, 576), (555, 576), (530, 490), (500, 400)]), ("gauze", "high", None, [(0, 10), (90, 5), (150, 60), (180, 110), (290, 125), (300, 200), (230, 240), (40, 230), (0, 200)]), ], 4800: [ ("white_insulated_jawed", "high", (355, 242), [(0, 335), (110, 300), (240, 255), (300, 235), (355, 230), (360, 255), (300, 285), (265, 310), (150, 370), (40, 430), (0, 445)]), ("dark_rod", "low", None, [(290, 425), (335, 420), (345, 480), (340, 535), (300, 535), (285, 480)]), ("gauze", "high", None, [(0, 20), (60, 10), (120, 60), (230, 90), (270, 140), (240, 200), (180, 250), (60, 310), (0, 330)]), ], 6900: [ ("white_insulated_jawed", "high", (265, 200), [(0, 320), (90, 270), (170, 230), (215, 195), (265, 188), (272, 215), (235, 245), (195, 290), (100, 360), (20, 420), (0, 420)]), ("dark_rod", "high", (325, 216), [(298, 218), (352, 215), (372, 300), (385, 400), (400, 576), (312, 576), (302, 400), (296, 300)]), ("gauze", "medium", None, [(425, 440), (480, 415), (520, 470), (540, 540), (470, 560), (430, 520)]), ], 8100: [ ("white_insulated_jawed", "high", (218, 125), [(0, 95), (120, 92), (205, 98), (222, 120), (215, 150), (180, 175), (90, 230), (0, 290)]), ("dark_rod", "high", (345, 118), [(310, 122), (378, 116), (385, 300), (388, 576), (285, 576), (300, 300)]), ("gauze", "medium", None, [(185, 190), (240, 200), (290, 250), (285, 330), (230, 340), (200, 280)]), ], 9300: [ ("white_insulated_jawed", "high", (372, 335), [(345, 335), (380, 328), (385, 360), (340, 430), (300, 490), (320, 576), (180, 576), (215, 480), (270, 420), (310, 370)]), ("dark_rod", "medium", (415, 347), [(392, 350), (440, 345), (455, 400), (470, 480), (480, 576), (405, 576), (395, 480)]), ("gauze", "low", None, [(70, 320), (120, 315), (140, 380), (170, 440), (190, 520), (120, 560), (90, 470), (70, 390)]), ], 10800: [ ("dark_rod", "medium", None, [(300, 60), (395, 70), (410, 300), (425, 576), (325, 576), (312, 300)]), ("white_insulated_jawed", "low", None, [(0, 45), (100, 20), (165, 15), (200, 40), (150, 80), (80, 130), (0, 185)]), ], 12600: [ ("white_insulated_jawed", "high", (448, 55), [(0, 245), (150, 150), (330, 85), (430, 40), (455, 50), (450, 90), (350, 150), (330, 220), (250, 330), (120, 430), (0, 470)]), ("dark_rod", "low", None, [(592, 395), (615, 392), (650, 520), (620, 530)]), ("gauze", "medium", None, [(120, 430), (250, 400), (400, 380), (520, 410), (560, 500), (420, 540), (300, 576), (200, 576), (130, 480)]), ], 13500: [ ("white_insulated_jawed", "medium", (135, 165), [(0, 165), (60, 150), (110, 140), (140, 150), (138, 200), (130, 255), (60, 335), (0, 375)]), ("dark_rod", "medium", (462, 270), [(440, 275), (490, 265), (520, 330), (540, 420), (560, 576), (480, 576), (455, 420), (435, 330)]), ("gauze", "medium", None, [(140, 310), (300, 330), (420, 300), (440, 400), (430, 576), (280, 576), (190, 420), (130, 360)]), ], 15900: [ ("white_insulated_jawed", "medium", (398, 215), [(385, 210), (410, 220), (400, 260), (350, 330), (330, 420), (290, 576), (130, 576), (190, 470), (270, 380), (320, 300), (360, 240)]), ("dark_rod", "low", None, [(405, 312), (440, 302), (470, 400), (500, 576), (420, 576), (410, 420)]), ], } if len(sys.argv) > 3: for k, objs in json.load(open(sys.argv[3])).items(): POLYS[int(k)] = [(c, conf, tuple(t) if t else None, [tuple(p) for p in poly]) for c, conf, t, poly in objs] POLYS = dict(sorted(POLYS.items())) COLORS = {"white_insulated_jawed": (255, 200, 0), "dark_rod": (0, 165, 255), "fenestrated_grasper": (0, 255, 0), "gauze": (255, 0, 255)} CAT_ID = {"white_insulated_jawed": 1, "dark_rod": 2, "fenestrated_grasper": 3, "gauze": 4} def poly_mask(poly): m = np.zeros((H, W), np.uint8) cv2.fillPoly(m, [np.array(poly, np.int32)], 1) return m def refine(img, pm): k_in = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (15, 15)) k_out = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (41, 41)) core, halo = cv2.erode(pm, k_in), cv2.dilate(pm, k_out) gc = np.full((H, W), cv2.GC_BGD, np.uint8) gc[halo == 1] = cv2.GC_PR_BGD gc[pm == 1] = cv2.GC_PR_FGD gc[core == 1] = cv2.GC_FGD if core.sum() < 50: return pm, 1.0, "polygon" cv2.grabCut(img, gc, None, np.zeros((1, 65)), np.zeros((1, 65)), 5, cv2.GC_INIT_WITH_MASK) out = ((gc == cv2.GC_FGD) | (gc == cv2.GC_PR_FGD)).astype(np.uint8) out = cv2.morphologyEx(out, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))) n, lab, stats, _ = cv2.connectedComponentsWithStats(out) if n > 1: # keep the largest component only out = (lab == 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA]))).astype(np.uint8) iou = float((out & pm).sum() / max(1, (out | pm).sum())) return (out, iou, "grabcut") if iou >= 0.6 else (pm, iou, "polygon") coco = {"info": {"description": "instance-mask subset; AI-drafted polygons snapped with GrabCut, reviewed and approved by the contributing physician on 2026-11-17"}, "images": [], "annotations": [], "categories": [{"id": v, "name": k} for k, v in CAT_ID.items()]} ann_id = 1 for fi, objs in POLYS.items(): img = cv2.imread(str(img_dir / f"f{fi:05d}.png")) assert img is not None and img.shape[:2] == (H, W) coco["images"].append({"id": fi, "file_name": f"images/f{fi:05d}.png", "width": W, "height": H, "source_frame_index": fi, "timestamp_seconds": fi / FPS}) vis = img.copy() inst = np.zeros((H, W), np.uint8) instruments = np.zeros((H, W), np.uint8) for k, (cls, conf, tip, poly) in enumerate(objs, 1): pm = poly_mask(poly) if cls == "gauze": # instruments lie in front of gauze: cut them out of the gauze polygon mask, iou, method = pm & (1 - instruments), 1.0, "polygon" else: mask, iou, method = refine(img, pm) instruments |= mask inst[mask == 1] = k if mask.sum() == 0: continue cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnt = max(cnts, key=cv2.contourArea) seg = cv2.approxPolyDP(cnt, 1.5, True).reshape(-1).tolist() x, y, w, h = cv2.boundingRect(cnt) coco["annotations"].append({ "id": ann_id, "image_id": fi, "category_id": CAT_ID[cls], "iscrowd": 0, "bbox": [x, y, w, h], "area": int(mask.sum()), "segmentation": [seg], "tip": list(tip) if tip else None, "confidence": conf, "mask_method": method, "polygon_vs_refined_iou": round(iou, 3), "instance_index_in_mask_png": k}) ann_id += 1 col = COLORS[cls] vis[mask == 1] = (0.55 * vis[mask == 1] + 0.45 * np.array(col)).astype(np.uint8) cv2.drawContours(vis, [cnt], -1, col, 2) cv2.putText(vis, f"{cls} [{conf}/{method}]", (x + 3, max(12, y + 14)), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 255, 255), 1) if tip: cv2.drawMarker(vis, tip, (0, 0, 255), cv2.MARKER_CROSS, 14, 2) cv2.imwrite(str(out_dir / "masks" / f"f{fi:05d}_instances.png"), inst) cv2.imwrite(str(out_dir / "overlays" / f"f{fi:05d}_overlay.jpg"), vis, [cv2.IMWRITE_JPEG_QUALITY, 90]) json.dump(coco, open(out_dir / "instances_coco.json", "w"), indent=1) print("images", len(coco["images"]), "annotations", len(coco["annotations"])) for a in coco["annotations"]: print(a["image_id"], a["category_id"], a["mask_method"], a["polygon_vs_refined_iou"], a["bbox"])