File size: 5,726 Bytes
2f06a53 | 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 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | """Score Mirage (Cactus) on the synthetic poker table dataset.
Modes: "describe" (objects + OCR text lines) and, if the Mirage API supports it,
"forms" scoring over card enums. Reports: card-read accuracy (OCR text that
matches a card glyph set), card-bbox recall via IoU matching to ground truth,
pot-text read rate, and per-image timing.
"""
import argparse
import json
import re
import time
from pathlib import Path
def iou(a, b):
ax0, ay0, ax1, ay1 = a
bx0, by0, bx1, by1 = b
ix = max(0, min(ax1, bx1) - max(ax0, bx0))
iy = max(0, min(ay1, by1) - max(ay0, by0))
inter = ix * iy
if inter <= 0:
return 0.0
return inter / (((ax1 - ax0) * (ay1 - ay0)) + ((bx1 - bx0) * (by1 - by0)) - inter)
def norm_rank(r):
return {"T": "10", "A": "A", "K": "K", "Q": "Q", "J": "J"}.get(r, r)
def card_matches(text, card):
"""Tolerant: rank (3..10,J..A) and suit symbol both present, any order."""
rank, suit = card[:-1], card[-1]
t = text.replace(" ", "").upper()
r_ok = rank.upper() in t if rank != "10" else ("10" in t or "T" in t.upper().replace("10", ""))
s_ok = suit in text or suit in t
return r_ok and s_ok
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--images", default="dataset/images")
ap.add_argument("--labels", default="dataset/labels")
ap.add_argument("--limit", type=int, default=0, help="0 = all")
ap.add_argument("--out", default="results_mirage.json")
ap.add_argument("--scale", type=float, default=1.0,
help="upscale factor for the image before inference; "
"ground-truth bboxes are scaled to match for IoU")
ap.add_argument("--sections", default="objects,text")
args = ap.parse_args()
from cactus import Mirage
model = Mirage()
print("mirage loaded", flush=True)
sections = [s for s in args.sections.split(",") if s]
img_dir, lbl_dir = Path(args.images), Path(args.labels)
names = sorted(p.name for p in img_dir.glob("*.png"))
if args.limit:
names = names[: args.limit]
# ground truth card strings
per_image = []
card_hits = card_true = iou_hits = iou_true = pot_hits = pot_true = 0
reads = []
t_start = time.time()
for i, name in enumerate(names):
lab = json.loads((lbl_dir / name.replace(".png", ".json")).read_text())
from PIL import Image as PILImage
img = PILImage.open(img_dir / name).convert("RGB")
sf = args.scale
if sf != 1.0:
img = img.resize((int(img.width * sf), int(img.height * sf)),
PILImage.LANCZOS)
t0 = time.time()
try:
res = model.describe(img, opts={
"sections": sections, "conf": 0.4, "text_conf": 0.3,
"max_objects": 30, "max_text_lines": 30, "max_tokens": 700,
"nms": True})
except TypeError:
res = model.describe(img, {"sections": sections, "conf": 0.4,
"text_conf": 0.3, "max_objects": 30,
"max_text_lines": 30, "max_tokens": 700,
"nms": True})
dt = time.time() - t0
ocr_lines = [l.get("string", "") for l in (res.get("text") or [])]
obj_names = [o.get("name", "") for o in (res.get("objects") or [])]
obj_boxes = [o.get("bbox") for o in (res.get("objects") or []) if o.get("bbox")]
ocr_boxes = [l.get("bbox") for l in (res.get("text") or []) if l.get("bbox")]
# card read: each GT card matched by some OCR object or text line
gt_cards = [c["card"] for c in lab["card_bboxes"]]
img_hits = 0
img_ious = []
matched = set()
for gt in gt_cards:
hit = any(card_matches(t, gt) for t in ocr_lines) or \
any(card_matches(t, gt) for t in obj_names)
img_hits += hit
# bbox side: best IoU of any detection against any GT card box
best = 0.0
best_j = -1
gt_box = next(c["bbox"] for c in lab["card_bboxes"] if c["card"] == gt)
if sf != 1.0:
gt_box = [v * sf for v in gt_box]
for j, ob in enumerate(obj_boxes + ocr_boxes):
v = iou(gt_box, ob) if ob else 0.0
if v > best:
best, best_j = v, j
img_ious.append(best)
card_hits += img_hits
card_true += len(gt_cards)
iou_hits += sum(1 for v in img_ious if v > 0.4)
iou_true += len(gt_cards)
pot_true += 1
if any(str(lab["pot"]) in t for t in ocr_lines):
pot_hits += 1
per_image.append({"image": name, "cards": len(gt_cards), "hits": img_hits,
"iou": round(sum(img_ious) / len(img_ious), 3) if img_ious else 0,
"sec": round(dt, 1), "ocr": ocr_lines[:8]})
if i < 3:
print(f"[{name}] ocr={ocr_lines[:10]} objs={obj_names[:10]} "
f"({dt:.1f}s)", flush=True)
wall = time.time() - t_start
summary = {
"names": names[:5], "sections": sections, "scale": args.scale,
"card_read_acc": round(card_hits / max(card_true, 1), 3),
"card_bbox_recall_iou40": round(iou_hits / max(iou_true, 1), 3),
"pot_read_acc": round(pot_hits / max(pot_true, 1), 3),
"cards_total": card_true, "sec_per_image": round(wall / len(names), 1),
"wall_min": round(wall / 60, 1),
}
Path(args.out).write_text(json.dumps(
{"summary": summary, "per_image": per_image}, indent=1))
print(json.dumps(summary, indent=2), flush=True)
if __name__ == "__main__":
main()
|