Files
Open_Vocabulary_Object_Dete…/evaluate_models.py
T
2026-11-26 16:53:02 +05:30

344 lines
13 KiB
Python

#!/usr/bin/env python3
"""
Ground-truth annotation + evaluation for Grounding DINO and YOLO-World.
Run from the Open_Vocabulary project directory:
source venv/bin/activate
python evaluate_models.py
The script opens each original image and asks you to draw one ground-truth
box per listed target. Press ENTER/SPACE to accept each box. Press C to cancel
and retry. The script then runs both models and writes evaluation CSV files.
"""
import csv
import json
import time
from pathlib import Path
import cv2
import numpy as np
import torch
from PIL import Image
from transformers import AutoProcessor, AutoModelForZeroShotObjectDetection
from ultralytics import YOLOWorld
ROOT = Path(__file__).resolve().parent
IMAGE_DIR = ROOT / "sample_images" / "Original_Images"
ANNOTATION_FILE = ROOT / "reports" / "ground_truth_annotations.json"
RESULTS_DIR = ROOT / "reports" / "evaluation"
DINO_ID = "IDEA-Research/grounding-dino-tiny"
YOLO_WEIGHTS = ROOT / "yolov8s-world.pt"
CLASSES_BY_IMAGE = {
"sample_1.png": ["person", "safety helmet"],
"sample_2.png": ["safety helmet"],
"sample_3.png": ["mobile phone"],
"sample_4.png": ["laptop"],
"sample_5.png": ["traffic cone"],
"sample_6.png": ["caliper"],
"sample_7.png": ["pipe wrench"],
"sample_8.png": ["soldering iron"],
}
CLASSES = sorted({c for labels in CLASSES_BY_IMAGE.values() for c in labels})
EVAL_CONFIDENCE = 0.25
IOU_THRESHOLDS = [round(x, 2) for x in np.arange(0.50, 0.96, 0.05)]
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
def annotate_ground_truth():
"""Create boxes using OpenCV's interactive ROI selector."""
annotations = {}
print("\nGROUND-TRUTH ANNOTATION")
print("For each displayed target, drag a tight rectangle around the object.")
print("Press ENTER/SPACE to accept the box; C cancels the current selection.\n")
for filename, labels in CLASSES_BY_IMAGE.items():
path = IMAGE_DIR / filename
if not path.exists():
raise FileNotFoundError(f"Missing image: {path}")
image = cv2.imread(str(path))
if image is None:
raise RuntimeError(f"Could not read image: {path}")
h, w = image.shape[:2]
image_annotations = []
for label in labels:
display = image.copy()
cv2.putText(
display, f"{filename}: select the {label}",
(5, 18), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 1,
cv2.LINE_AA
)
print(f"{filename}: draw a box around '{label}' ({w}x{h})")
while True:
x, y, bw, bh = cv2.selectROI(
"Ground Truth Annotation", display,
showCrosshair=True, fromCenter=False
)
if bw > 0 and bh > 0:
break
print("No box selected. Please select the object.")
x1, y1 = int(x), int(y)
x2, y2 = int(x + bw), int(y + bh)
image_annotations.append({
"class": label,
"bbox_xyxy": [x1, y1, x2, y2]
})
cv2.rectangle(display, (x1, y1), (x2, y2), (0, 255, 0), 2)
annotations[filename] = {
"width": w, "height": h, "objects": image_annotations
}
print(f" Saved {len(image_annotations)} box(es) for {filename}")
cv2.destroyAllWindows()
ANNOTATION_FILE.parent.mkdir(parents=True, exist_ok=True)
ANNOTATION_FILE.write_text(json.dumps(annotations, indent=2))
print(f"\nGround truth saved to: {ANNOTATION_FILE}")
return annotations
def load_annotations():
if ANNOTATION_FILE.exists():
answer = input(
f"Existing annotations found at {ANNOTATION_FILE}.\n"
"Reuse them? [Y/n]: "
).strip().lower()
if answer in ("", "y", "yes"):
return json.loads(ANNOTATION_FILE.read_text())
return annotate_ground_truth()
def normalize_label(label):
return " ".join(str(label).lower().replace("_", " ").replace("-", " ").split())
def run_dino(image, labels, processor, model):
prompt = ". ".join(labels) + "."
inputs = processor(images=image, text=prompt, return_tensors="pt").to(DEVICE)
if DEVICE == "cuda":
torch.cuda.synchronize()
start = time.perf_counter()
with torch.inference_mode():
outputs = model(**inputs)
if DEVICE == "cuda":
torch.cuda.synchronize()
elapsed_ms = (time.perf_counter() - start) * 1000
result = processor.post_process_grounded_object_detection(
outputs, inputs.input_ids,
threshold=0.001,
text_threshold=0.25,
target_sizes=[(image.height, image.width)]
)[0]
labels_out = result.get("text_labels", result.get("labels", []))
detections = []
for box, score, label in zip(result["boxes"], result["scores"], labels_out):
detections.append({
"class": normalize_label(label),
"confidence": float(score),
"bbox_xyxy": [float(v) for v in box.tolist()]
})
return detections, elapsed_ms
def run_yolo(image, labels, model):
model.set_classes(labels)
if DEVICE == "cuda":
torch.cuda.synchronize()
start = time.perf_counter()
results = model.predict(
source=image, device=0 if DEVICE == "cuda" else "cpu",
conf=0.001, imgsz=640, verbose=False
)
if DEVICE == "cuda":
torch.cuda.synchronize()
elapsed_ms = (time.perf_counter() - start) * 1000
result = results[0]
detections = []
if result.boxes is not None:
for box in result.boxes:
class_id = int(box.cls[0])
detections.append({
"class": normalize_label(result.names[class_id]),
"confidence": float(box.conf[0]),
"bbox_xyxy": [float(v) for v in box.xyxy[0].tolist()]
})
return detections, elapsed_ms
def iou_xyxy(a, b):
x1 = max(a[0], b[0])
y1 = max(a[1], b[1])
x2 = min(a[2], b[2])
y2 = min(a[3], b[3])
inter = max(0.0, x2 - x1) * max(0.0, y2 - y1)
area_a = max(0.0, a[2] - a[0]) * max(0.0, a[3] - a[1])
area_b = max(0.0, b[2] - b[0]) * max(0.0, b[3] - b[1])
union = area_a + area_b - inter
return inter / union if union > 0 else 0.0
def evaluate_at_iou(predictions, annotations, class_name, iou_threshold):
gt_by_image = {}
total_gt = 0
for filename, data in annotations.items():
boxes = [
obj["bbox_xyxy"] for obj in data["objects"]
if normalize_label(obj["class"]) == class_name
]
gt_by_image[filename] = boxes
total_gt += len(boxes)
preds = []
for filename, detections in predictions.items():
for det in detections:
if normalize_label(det["class"]) == class_name and det["confidence"] >= EVAL_CONFIDENCE:
preds.append((det["confidence"], filename, det["bbox_xyxy"]))
preds.sort(key=lambda x: x[0], reverse=True)
matched = {filename: set() for filename in gt_by_image}
tp_flags, fp_flags = [], []
tp = 0
for confidence, filename, box in preds:
candidates = gt_by_image.get(filename, [])
best_iou, best_idx = 0.0, -1
for idx, gt_box in enumerate(candidates):
if idx in matched[filename]:
continue
overlap = iou_xyxy(box, gt_box)
if overlap > best_iou:
best_iou, best_idx = overlap, idx
if best_idx >= 0 and best_iou >= iou_threshold:
matched[filename].add(best_idx)
tp += 1
tp_flags.append(1)
fp_flags.append(0)
else:
tp_flags.append(0)
fp_flags.append(1)
fp = len(preds) - tp
fn = total_gt - tp
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / total_gt if total_gt else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
# 101-point interpolated AP; no-GT classes are excluded from mAP.
ap = None
if total_gt:
if preds:
tp_cum = np.cumsum(tp_flags)
fp_cum = np.cumsum(fp_flags)
recalls = tp_cum / total_gt
precisions = tp_cum / np.maximum(tp_cum + fp_cum, 1)
interpolated = []
for recall_level in np.linspace(0, 1, 101):
valid = precisions[recalls >= recall_level]
interpolated.append(float(valid.max()) if len(valid) else 0.0)
ap = float(np.mean(interpolated))
else:
ap = 0.0
return {
"TP": tp, "FP": fp, "FN": fn,
"Precision": precision, "Recall": recall, "F1": f1, "AP": ap
}
def main():
if not IMAGE_DIR.exists():
raise FileNotFoundError(f"Image folder not found: {IMAGE_DIR}")
annotations = load_annotations()
print(f"\nDevice: {DEVICE}")
if DEVICE == "cuda":
print(f"GPU: {torch.cuda.get_device_name(0)}")
print("Loading Grounding DINO...")
processor = AutoProcessor.from_pretrained(DINO_ID)
dino = AutoModelForZeroShotObjectDetection.from_pretrained(DINO_ID).to(DEVICE)
dino.eval()
print("Loading YOLO-World...")
yolo = YOLOWorld(str(YOLO_WEIGHTS) if YOLO_WEIGHTS.exists() else "yolov8s-world.pt")
all_predictions = {"Grounding DINO": {}, "YOLO-World": {}}
timing_rows = []
labels = CLASSES
for filename in CLASSES_BY_IMAGE:
image = Image.open(IMAGE_DIR / filename).convert("RGB")
print(f"\nEvaluating {filename}...")
dino_preds, dino_ms = run_dino(image, labels, processor, dino)
yolo_preds, yolo_ms = run_yolo(image, labels, yolo)
all_predictions["Grounding DINO"][filename] = dino_preds
all_predictions["YOLO-World"][filename] = yolo_preds
timing_rows.extend([
{"Image": filename, "Model": "Grounding DINO",
"Inference_Time_ms": round(dino_ms, 2),
"Predictions_at_0.25": sum(p["confidence"] >= EVAL_CONFIDENCE for p in dino_preds)},
{"Image": filename, "Model": "YOLO-World",
"Inference_Time_ms": round(yolo_ms, 2),
"Predictions_at_0.25": sum(p["confidence"] >= EVAL_CONFIDENCE for p in yolo_preds)}
])
print(f" Grounding DINO: {len(dino_preds)} raw predictions; {dino_ms:.1f} ms")
print(f" YOLO-World: {len(yolo_preds)} raw predictions; {yolo_ms:.1f} ms")
RESULTS_DIR.mkdir(parents=True, exist_ok=True)
with (RESULTS_DIR / "inference_timings.csv").open("w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=timing_rows[0].keys())
writer.writeheader()
writer.writerows(timing_rows)
summary_rows = []
ap_rows = []
for model_name, predictions in all_predictions.items():
for class_name in CLASSES:
base = evaluate_at_iou(predictions, annotations, class_name, 0.50)
summary_rows.append({
"Model": model_name, "Class": class_name,
"IoU_Threshold": 0.50,
**{k: round(v, 4) if isinstance(v, float) else v
for k, v in base.items() if k != "AP"}
})
for threshold in IOU_THRESHOLDS:
result = evaluate_at_iou(predictions, annotations, class_name, threshold)
ap_rows.append({
"Model": model_name, "Class": class_name,
"IoU_Threshold": threshold,
"AP": round(result["AP"], 4) if result["AP"] is not None else ""
})
with (RESULTS_DIR / "metrics_by_class.csv").open("w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=summary_rows[0].keys())
writer.writeheader()
writer.writerows(summary_rows)
with (RESULTS_DIR / "average_precision.csv").open("w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=ap_rows[0].keys())
writer.writeheader()
writer.writerows(ap_rows)
print("\nEVALUATION SUMMARY (confidence >= 0.25, IoU >= 0.50)")
print(f"{'Model':<18} {'Precision':>11} {'Recall':>9} {'F1':>9}")
for model_name in all_predictions:
rows = [r for r in summary_rows if r["Model"] == model_name]
tp = sum(r["TP"] for r in rows)
fp = sum(r["FP"] for r in rows)
fn = sum(r["FN"] for r in rows)
p = tp / (tp + fp) if tp + fp else 0.0
r = tp / (tp + fn) if tp + fn else 0.0
f1 = 2*p*r/(p+r) if p+r else 0.0
aps50 = [x["AP"] for x in ap_rows if x["Model"] == model_name and x["IoU_Threshold"] == 0.50 and x["AP"] != ""]
all_aps = [x["AP"] for x in ap_rows if x["Model"] == model_name and x["AP"] != ""]
map50 = float(np.mean(aps50)) if aps50 else 0.0
map5095 = float(np.mean(all_aps)) if all_aps else 0.0
print(f"{model_name:<18} {p:>11.4f} {r:>9.4f} {f1:>9.4f}")
print(f" mAP@50={map50:.4f} | mAP@50:95={map5095:.4f}")
print("\nFiles saved in:", RESULTS_DIR)
print(" ground_truth_annotations.json")
print(" inference_timings.csv")
print(" metrics_by_class.csv")
print(" average_precision.csv")
print("\nImportant: results are for this small 8-image dataset only.")
if __name__ == "__main__":
main()