File size: 5,791 Bytes
bfa2869
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
"""Score the YOLO11n playing-card detector (MIT, shrimantasatpati) on the
synthetic poker table dataset. Per-card class accuracy at IoU>=0.5 + timing."""
import argparse
import json
import time
from pathlib import Path

from huggingface_hub import hf_hub_download

WEIGHTS = "detect/yolo11_playing_cards/weights/best.pt"


def resolve_weights():
    try:
        return hf_hub_download("shrimantasatpati/yolov11_playing_cards_detection",
                               "detect/yolo11n_playing_cards/weights/best.pt")
    except Exception as e:
        print(f"weights download failed ({e}); trying resolve URL", flush=True)
        import urllib.request
        url = ("https://huggingface.co/shrimantasatpati/yolov11_playing_cards_detection"
               "/resolve/main/detect/yolo11n_playing_cards/weights/best.pt")
        dst = "yolo_cards.pt"
        urllib.request.urlretrieve(url, dst)
        return dst


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 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("--conf", type=float, default=0.1)
    ap.add_argument("--imgsz", type=int, default=1280)
    ap.add_argument("--out", default="results_yolo.json")
    args = ap.parse_args()

    from ultralytics import YOLO
    wpath = resolve_weights()
    model = YOLO(wpath)
    print("classes:", model.names, flush=True)

    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]

    correct = total = detected = 0
    correct_full = correct_glyph = det_full = det_glyph = 0
    per_image = []
    t_start = time.time()
    for name in names:
        lab = json.loads((lbl_dir / name.replace(".png", ".json")).read_text())
        t0 = time.time()
        r = model.predict(str(img_dir / name), conf=args.conf, imgsz=args.imgsz,
                          verbose=False)[0]
        dt = time.time() - t0
        dets = []
        for b, c in zip(r.boxes.xyxy.tolist(), r.boxes.cls.tolist()):
            dets.append((model.names[int(c)], b))
        img_correct = 0
        img_iou_only = 0
        img_det_full = img_det_glyph = 0
        img_correct_full = img_correct_glyph = 0
        gt_cards = lab["card_bboxes"]
        for gc in gt_cards:
            gt = gc["card"]
            # YOLO detects the corner rank/suit glyph patch, not the full card;
            # score against both the full card box and the glyph region.
            x0, y0, x1, y1 = gc["bbox"]
            glyph = [x0, y0, x0 + 0.65 * (x1 - x0), y0 + 0.45 * (y1 - y0)]
            best_cls, best_iou, best_glyph, best_bbox = None, 0.0, 0.0, None
            for cls, bb in dets:
                v = iou(gc["bbox"], bb)
                g = iou(glyph, bb)
                if g > best_glyph or (g == best_glyph and v > best_iou):
                    best_iou, best_glyph, best_cls, best_bbox = v, g, cls, bb
            hit = best_glyph >= 0.4 or best_iou >= 0.4
            cls_ok = hit and best_cls and class_matches(best_cls, gt)
            if best_iou >= 0.4:
                img_det_full += 1
                if cls_ok:
                    img_correct_full += 1
            if best_glyph >= 0.4:
                img_det_glyph += 1
                if cls_ok:
                    img_correct_glyph += 1
            if hit:
                detected += 1
                img_iou_only += 1
            if cls_ok:
                img_correct += 1
        correct += img_correct
        correct_full += img_correct_full
        correct_glyph += img_correct_glyph
        det_full += img_det_full
        det_glyph += img_det_glyph
        total += len(gt_cards)
        per_image.append({"image": name, "cards": len(gt_cards),
                          "correct": img_correct, "located": img_iou_only,
                          "sec": round(dt, 2)})
        if len(per_image) <= 3:
            print(f"[{name}] dets={[(c, [round(x) for x in b]) for c, b in dets][:5]} "
                  f"({dt:.2f}s)", flush=True)
    wall = time.time() - t_start
    summary = {
        "class_acc_iou40": round(correct / max(total, 1), 3),
        "class_acc_full_box": round(correct_full / max(total, 1), 3),
        "class_acc_glyph": round(correct_glyph / max(total, 1), 3),
        "detected_iou40": round(detected / max(total, 1), 3),
        "detected_full_box": round(det_full / max(total, 1), 3),
        "detected_glyph": round(det_glyph / max(total, 1), 3),
        "cards_total": total,
        "sec_per_image": round(wall / len(names), 2),
        "conf": args.conf,
    }
    Path(args.out).write_text(json.dumps(
        {"summary": summary, "per_image": per_image}, indent=1))
    print(json.dumps(summary, indent=2), flush=True)


def class_matches(cls, gt):
    """Map YOLO class name (e.g. 'AS', '10D') to our 'A♠' style.

    Model classes are rank+suit-letter: {0:'10C' ... 39:'AS' ... 51:'QS'}.
    """
    rank, suit = gt[:-1], gt[-1]
    suit_letter = {"♠": "S", "♥": "H", "♦": "D", "♣": "C"}[suit]
    c = cls.strip().upper()
    if len(c) < 2:
        return False
    mrank, msuit = c[:-1], c[-1]
    if msuit not in ("S", "H", "D", "C"):
        return False
    rank_ok = (mrank == rank) or (rank == "10" and mrank in ("10", "T"))
    return rank_ok and msuit == suit_letter


if __name__ == "__main__":
    main()