Datasets:
File size: 5,251 Bytes
74f7b5f | 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 | #!/usr/bin/env python3
"""Create side-by-side visual QA overlays for held-out images."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import cv2
import numpy as np
from ultralytics import YOLO
from dataset_utils import label_for_image, split_images
PRED_COLORS = {0: (80, 220, 255), 1: (255, 120, 80), 2: (80, 80, 255)}
GT_COLOR = (80, 255, 80)
def draw_ground_truth(image: np.ndarray, label_path: Path, names: dict[int, str]) -> None:
height, width = image.shape[:2]
if not label_path.is_file():
return
for line in label_path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
class_text, cx_text, cy_text, w_text, h_text = line.split()
class_id = int(class_text)
cx, cy, box_w, box_h = map(float, (cx_text, cy_text, w_text, h_text))
x1 = int((cx - box_w / 2) * width)
y1 = int((cy - box_h / 2) * height)
x2 = int((cx + box_w / 2) * width)
y2 = int((cy + box_h / 2) * height)
cv2.rectangle(image, (x1, y1), (x2, y2), GT_COLOR, 2)
cv2.putText(image, f"GT {names[class_id]}", (x1, max(18, y1 - 5)), cv2.FONT_HERSHEY_SIMPLEX, 0.55, GT_COLOR, 2)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model", type=Path, required=True)
parser.add_argument("--data", type=Path, required=True)
parser.add_argument("--output-dir", type=Path, required=True)
parser.add_argument("--quality-gate", type=Path, help="evaluate.py quality_gate.json")
parser.add_argument("--split", default="val", choices=("train", "val", "test"))
parser.add_argument("--count", type=int, default=30)
parser.add_argument("--device", default="0")
parser.add_argument("--imgsz", type=int, default=960)
parser.add_argument("--fallback-conf", type=float, default=0.25)
parser.add_argument("--columns", type=int, default=3)
args = parser.parse_args()
images, root, names = split_images(args.data, args.split)
if not images:
raise SystemExit(f"no {args.split} images")
count = min(args.count, len(images))
indices = np.linspace(0, len(images) - 1, count, dtype=int)
selected = [images[index] for index in indices]
thresholds = {name: args.fallback_conf for name in names.values()}
if args.quality_gate:
gate = json.loads(args.quality_gate.read_text(encoding="utf-8"))
thresholds.update(gate["recommended_confidence_by_class"])
minimum_conf = min(thresholds.values())
args.output_dir.mkdir(parents=True, exist_ok=True)
model = YOLO(str(args.model.resolve()))
results = model.predict(
source=[str(path) for path in selected], imgsz=args.imgsz,
conf=minimum_conf, iou=0.7, max_det=100, device=args.device,
stream=True, verbose=False,
)
tiles = []
index_rows = []
for sequence, (path, result) in enumerate(zip(selected, results, strict=True)):
image = cv2.imread(str(path))
draw_ground_truth(image, label_for_image(path, root, args.split), names)
kept = 0
if result.boxes is not None:
for box, confidence, class_id in zip(
result.boxes.xyxy.cpu().numpy(),
result.boxes.conf.cpu().numpy(),
result.boxes.cls.cpu().numpy().astype(int),
strict=True,
):
name = names[int(class_id)]
if confidence < thresholds[name]:
continue
x1, y1, x2, y2 = map(int, box)
color = PRED_COLORS[int(class_id)]
cv2.rectangle(image, (x1, y1), (x2, y2), color, 3)
cv2.putText(
image, f"P {name} {confidence:.2f}", (x1, min(image.shape[0] - 8, y2 + 18)),
cv2.FONT_HERSHEY_SIMPLEX, 0.55, color, 2,
)
kept += 1
cv2.putText(image, "green=GT; colored=PRED", (12, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 3)
cv2.putText(image, "green=GT; colored=PRED", (12, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (20, 20, 20), 1)
output = args.output_dir / f"{sequence:03d}_{path.name}"
cv2.imwrite(str(output), image)
tile_width = 480
tile_height = round(image.shape[0] * tile_width / image.shape[1])
tiles.append(cv2.resize(image, (tile_width, tile_height)))
index_rows.append({"source": str(path), "preview": output.name, "predictions": kept})
tile_height = max(tile.shape[0] for tile in tiles)
rows = (len(tiles) + args.columns - 1) // args.columns
sheet = np.full((rows * tile_height, args.columns * 480, 3), 32, dtype=np.uint8)
for index, tile in enumerate(tiles):
row, column = divmod(index, args.columns)
sheet[row * tile_height : row * tile_height + tile.shape[0], column * 480 : (column + 1) * 480] = tile
cv2.imwrite(str(args.output_dir / "contact_sheet.jpg"), sheet)
(args.output_dir / "index.jsonl").write_text(
"".join(json.dumps(row, ensure_ascii=False) + "\n" for row in index_rows), encoding="utf-8"
)
print((args.output_dir / "contact_sheet.jpg").resolve())
if __name__ == "__main__":
main()
|