File size: 7,348 Bytes
6c30276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
#!/usr/bin/env python3
"""Benchmark-grade OBB evaluator (rotated IoU) for RipBench.

Consumes prediction dumps from eval/predict_obb.py + the DOTA GT in
labels/obb/dota/. Same protocol as evaluate_detection.py: sweep the
confidence threshold on VAL, select best F2 @ rotated-IoU 0.50 (ties
broken by recall, then precision, then the higher threshold), FREEZE it,
apply to TEST. Appends one row per model x split to
eval/results/obb_eval.tsv.

No CLI args - edit CONFIG below and run (needs shapely; the yoloV26 env
has it).

Matching is COCO-style greedy in descending score order with rotated
(polygon) IoU. Because greedy matching in score order is stable under
threshold truncation, each image is matched ONCE at the confidence
floor and every threshold in the sweep is evaluated by truncating the
scored match list - O(1) per threshold.
"""

import json
import os
_RIPBENCH_ROOT = os.environ.get("RIPBENCH_ROOT", os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")))  # release root (env RIPBENCH_ROOT overrides)
from datetime import datetime

from shapely.geometry import Polygon

# --- configuration -----------------------------------------------------------
DATASET_ROOT = _RIPBENCH_ROOT
PRED_DIR = os.path.join(DATASET_ROOT, "models", "obb", "best_models", "predictions")
PRED_GLOB = "*_preds_"  # stems are discovered from files matching <stem>_preds_val.json
IOU_THR = 0.50
CONF_GRID = [round(0.01 * i, 2) for i in range(1, 10)] + [round(0.05 * i, 2) for i in range(2, 19)]
USE_VAL_SELECTION = True  # False = use FIXED_CONF_THRESHOLD on TEST only
FIXED_CONF_THRESHOLD = None
SPLITS = ("val", "test")
OUT_TSV = os.path.join(os.path.dirname(os.path.abspath(__file__)), "results", "obb_eval.tsv")
# ------------------------------------------------------------------------------

DOTA_DIR = os.path.join(DATASET_ROOT, "labels", "obb", "dota")

TSV_COLS = ["timestamp", "model", "task", "split", "selected_conf", "selected_on",
            "n_images", "n_gt", "AP50", "P50", "R50", "F1_50", "F2_50",
            "TP50", "FP50", "FN50"]


def gt_polys(split):
    """{image basename: [Polygon, ...]} for every image in the split manifest
    (images without a label file are negatives with an empty list)."""
    out = {}
    manifest = os.path.join(DOTA_DIR, f"{split}.txt")
    for line in open(manifest).read().splitlines():
        if not line:
            continue
        rel = line[2:] if line.startswith("./") else line
        stem = os.path.splitext(os.path.basename(rel))[0]
        # ./images/<source>/<class>/<name>.jpg -> labels/<source>/<class>/<name>.txt
        parts = rel.split("/")
        lbl = os.path.join(DOTA_DIR, "labels", *parts[1:-1], stem + ".txt")
        polys = []
        if os.path.isfile(lbl):
            for row in open(lbl).read().splitlines():
                vals = row.split()
                if len(vals) < 9:
                    continue
                pts = [(float(vals[i]), float(vals[i + 1])) for i in range(0, 8, 2)]
                g = Polygon(pts)
                if not g.is_valid:
                    g = g.buffer(0)
                if not g.is_empty:
                    polys.append(g)
        out[stem] = polys
    return out


def riou(a, b):
    try:
        inter = a.intersection(b).area
        union = a.union(b).area
        return inter / union if union > 0 else 0.0
    except Exception:
        return 0.0


def match_split(preds_file, gts):
    """One greedy pass per image at the conf floor. Returns (scored, n_gt)
    where scored = [(score, matched_bool), ...] sorted by descending score
    across the whole split; thresholding = truncation."""
    per_img = {}
    for p in json.load(open(preds_file)):
        per_img.setdefault(p["image"], []).append(p)
    scored = []
    n_gt = 0
    for stem, polys in gts.items():
        n_gt += len(polys)
        used = set()
        for p in sorted(per_img.get(stem, []), key=lambda x: -x["score"]):
            pts = p["poly"]
            g = Polygon([(pts[i], pts[i + 1]) for i in range(0, 8, 2)])
            if not g.is_valid:
                g = g.buffer(0)
            best, bi = -1.0, -1
            for j, o in enumerate(polys):
                if j in used:
                    continue
                v = riou(g, o)
                if v > best:
                    best, bi = v, j
            ok = best >= IOU_THR
            if ok:
                used.add(bi)
            scored.append((p["score"], ok))
    scored.sort(key=lambda x: -x[0])
    return scored, n_gt


def counts_at(scored, n_gt, thr):
    tp = fp = 0
    for s, ok in scored:
        if s < thr:
            break
        if ok:
            tp += 1
        else:
            fp += 1
    return tp, fp, n_gt - tp


def prf2(tp, fp, fn):
    p = tp / (tp + fp + 1e-9)
    r = tp / (tp + fn + 1e-9)
    f1 = 2 * p * r / (p + r + 1e-9)
    f2 = 5 * p * r / (4 * p + r + 1e-9)
    return p, r, f1, f2


def ap50(scored, n_gt):
    """All-point interpolated AP at the rotated-IoU threshold."""
    prec, rec = [], []
    tp = fp = 0
    for s, ok in scored:
        if ok:
            tp += 1
        else:
            fp += 1
        prec.append(tp / (tp + fp))
        rec.append(tp / (n_gt + 1e-9))
    if not prec:
        return 0.0
    for i in range(len(prec) - 2, -1, -1):  # precision envelope
        prec[i] = max(prec[i], prec[i + 1])
    ap, prev_r = 0.0, 0.0
    for p, r in zip(prec, rec):
        ap += p * (r - prev_r)
        prev_r = r
    return ap


def main():
    os.makedirs(os.path.dirname(OUT_TSV), exist_ok=True)
    if not os.path.isfile(OUT_TSV):
        with open(OUT_TSV, "w") as f:
            f.write("\t".join(TSV_COLS) + "\n")
    gts = {s: gt_polys(s) for s in SPLITS}
    stems = sorted({f.split("_preds_")[0] for f in os.listdir(PRED_DIR)
                    if "_preds_" in f and f.endswith(".json")})
    for stem in stems:
        matched = {}
        for s in SPLITS:
            pf = os.path.join(PRED_DIR, f"{stem}_preds_{s}.json")
            if not os.path.isfile(pf):
                print(f"SKIP {stem}: missing {s} predictions")
                matched = None
                break
            matched[s] = match_split(pf, gts[s])
        if matched is None:
            continue
        if USE_VAL_SELECTION:
            sv, nv = matched["val"]
            best = max(CONF_GRID, key=lambda t: (
                prf2(*counts_at(sv, nv, t))[3],  # F2
                prf2(*counts_at(sv, nv, t))[1],  # R
                prf2(*counts_at(sv, nv, t))[0],  # P
                t))
            sel_on = "val"
        else:
            best, sel_on = FIXED_CONF_THRESHOLD, "fixed"
        for s in SPLITS:
            sc, ng = matched[s]
            tp, fp, fn = counts_at(sc, ng, best)
            p, r, f1, f2 = prf2(tp, fp, fn)
            row = [datetime.now().strftime("%Y-%m-%d %H:%M"), stem, "obb", s,
                   f"{best:.2f}", sel_on, str(len(gts[s])), str(ng),
                   f"{ap50(sc, ng):.6f}", f"{p:.6f}", f"{r:.6f}",
                   f"{f1:.6f}", f"{f2:.6f}", str(tp), str(fp), str(fn)]
            with open(OUT_TSV, "a") as f:
                f.write("\t".join(row) + "\n")
            print(f"{stem} [{s}] conf {best:.2f}: AP50 {ap50(sc, ng):.3f} "
                  f"F2 {f2:.3f} (P {p:.3f} R {r:.3f})")


if __name__ == "__main__":
    main()