""" Extract gold bounding boxes from an annotated screenshot of the cellar floor plan. Detects colored rectangles (red/pink, green, blue, cyan, orange) drawn by the user, maps their positions to the full PDF image coordinate space, and saves them to JSON. Usage: python extract_screenshot_gold.py --screenshot cellar_annotated_ref.png The PDF page at 300 DPI is 14400 x 10800 px. The script auto-fits the drawing bounds inside the screenshot so no manual calibration is needed. """ from __future__ import annotations import argparse import json from pathlib import Path import numpy as np from PIL import Image OUT_DIR = Path(__file__).resolve().parent / "output_floor_iter" / "model_compare_acp" # PDF page size at 300 DPI (page 2 of the Mechanical CD set) PDF_W, PDF_H = 14400, 10800 # ── color bands ────────────────────────────────────────────────────────────── # Each entry: (label_for_json, r_min, r_max, g_min, g_max, b_min, b_max) COLOR_BANDS = [ # large pink / magenta / red boxes drawn by the user ("unit_red", 160, 255, 0, 120, 0, 160), ("unit_pink", 200, 255, 50, 160, 80, 200), # green ("unit_green", 0, 120, 150, 255, 0, 120), # blue ("unit_blue", 0, 100, 0, 120, 150, 255), # cyan ("unit_cyan", 0, 120, 150, 255, 150, 255), # orange / yellow ("unit_orange", 200, 255, 100, 200, 0, 80), ] MIN_BOX_PX = 20 # minimum side length in screenshot pixels to be counted MIN_AREA_PX = 600 # minimum area def detect_color_mask(arr: np.ndarray, r0, r1, g0, g1, b0, b1) -> np.ndarray: r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2] return ( (r >= r0) & (r <= r1) & (g >= g0) & (g <= g1) & (b >= b0) & (b <= b1) ) def bounding_boxes_from_mask(mask: np.ndarray, min_side: int, min_area: int) -> list[tuple[int,int,int,int]]: """Return (x1,y1,x2,y2) boxes for connected colored regions using a simple flood-fill free approach.""" from scipy import ndimage # type: ignore labeled, n = ndimage.label(mask) boxes = [] for i in range(1, n + 1): ys, xs = np.where(labeled == i) if len(xs) < min_area: continue x1, x2 = int(xs.min()), int(xs.max()) y1, y2 = int(ys.min()), int(ys.max()) w, h = x2 - x1, y2 - y1 if w < min_side or h < min_side: continue boxes.append((x1, y1, x2, y2)) return boxes def find_drawing_bounds(arr: np.ndarray) -> tuple[int, int, int, int]: """ Estimate the rectangle that contains the actual drawing by finding where the image is NOT white/near-white. Returns (left, top, right, bottom). """ gray = arr.mean(axis=2) non_white = gray < 240 cols = non_white.any(axis=0) rows = non_white.any(axis=1) left = int(np.argmax(cols)) right = int(len(cols) - np.argmax(cols[::-1]) - 1) top = int(np.argmax(rows)) bottom = int(len(rows) - np.argmax(rows[::-1]) - 1) return left, top, right, bottom def screenshot_to_pdf(sx, sy, left, top, draw_w, draw_h) -> tuple[float, float]: """Map screenshot (sx,sy) within drawing bounds to PDF pixel coords.""" px = (sx - left) / draw_w * PDF_W py = (sy - top) / draw_h * PDF_H return px, py def main(): parser = argparse.ArgumentParser() parser.add_argument("--screenshot", type=Path, default=Path(__file__).resolve().parent / "cellar_annotated_ref.png") parser.add_argument("--out", type=Path, default=None) args = parser.parse_args() img = Image.open(args.screenshot).convert("RGB") arr = np.array(img) sh, sw = arr.shape[:2] print(f"Screenshot: {sw}x{sh}") left, top, right, bottom = find_drawing_bounds(arr) draw_w = right - left draw_h = bottom - top print(f"Drawing bounds in screenshot: ({left},{top}) -> ({right},{bottom}) size={draw_w}x{draw_h}") print(f"Scale to PDF: x×{PDF_W/draw_w:.2f} y×{PDF_H/draw_h:.2f}") all_boxes: list[dict] = [] for label, r0, r1, g0, g1, b0, b1 in COLOR_BANDS: mask = detect_color_mask(arr, r0, r1, g0, g1, b0, b1) boxes = bounding_boxes_from_mask(mask, MIN_BOX_PX, MIN_AREA_PX) print(f" {label}: {len(boxes)} box(es)") for x1, y1, x2, y2 in boxes: px1, py1 = screenshot_to_pdf(x1, y1, left, top, draw_w, draw_h) px2, py2 = screenshot_to_pdf(x2, y2, left, top, draw_w, draw_h) all_boxes.append({ "color": label, "tag": "unit", "x": int(px1), "y": int(py1), "w": int(px2 - px1), "h": int(py2 - py1), "screen": [x1, y1, x2, y2], }) out_path = args.out or (OUT_DIR / "gold_allunits.json") out_path.parent.mkdir(parents=True, exist_ok=True) out_path.write_text(json.dumps(all_boxes, indent=2), encoding="utf-8") print(f"\n{len(all_boxes)} total boxes saved to {out_path}") # Visual check: draw detected boxes on a thumbnail of the screenshot from PIL import ImageDraw thumb = img.copy() draw = ImageDraw.Draw(thumb) COLORS = { "unit_red": (255, 0, 0), "unit_pink": (255, 100, 150), "unit_green": (0, 200, 0), "unit_blue": (0, 0, 255), "unit_cyan": (0, 200, 200), "unit_orange": (255, 150, 0), } for b in all_boxes: x1, y1, x2, y2 = b["screen"] c = COLORS.get(b["color"], (200, 200, 200)) draw.rectangle([x1, y1, x2, y2], outline=c, width=3) check_path = out_path.parent / "gold_allunits_check.png" thumb.save(check_path) print(f"Visual check saved to {check_path}") if __name__ == "__main__": main()