RipBench / tooling /eval /evaluate_obb.py
Irikos's picture
Add files using upload-large-folder tool
6c30276 verified
Raw History Blame Contribute Delete
7.35 kB
#!/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()