#!/usr/bin/env python3 """Visualize SPARK 2022 dataset labels. Dataset layout: labels/{train,val,test}.csv with rows: filename,class,bbox {train,val,test}/ image folders (.jpg) bbox = [xmin, ymin, xmax, ymax] (x = column, y = row; origin = top-left) Plots images with their bounding box and class label, in grids of up to 6 per figure. Figures are saved as PNG next to this script (headless-safe) and also shown in a window when a display is available. Examples: python3 visualize_labels.py # 6 random from train python3 visualize_labels.py val --num 12 --seed 3 # reproducible sample python3 visualize_labels.py test --filenames img057676.jpg,img058116.jpg python3 visualize_labels.py train --class smart_1 # sample one class python3 visualize_labels.py val --save /tmp/out.png """ import argparse import ast import csv import os import random import sys from pathlib import Path import matplotlib if not os.environ.get("DISPLAY") and sys.platform != "darwin": matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from PIL import Image BOX_COLOR = "#00FF66" # bright green — visible on dark space imagery PER_FIGURE = 6 # images per figure, 3 columns def load_labels(csv_path: Path): """Read the CSV into {filename: (class, [xmin, ymin, xmax, ymax])}.""" rows = {} with open(csv_path, newline="") as f: reader = csv.reader(f) next(reader) # header: filename,class,bbox for row in reader: if len(row) != 3: continue filename, cls, bbox_raw = row try: bbox = list(ast.literal_eval(bbox_raw)) except (ValueError, SyntaxError): bbox = None rows[filename] = (cls, bbox) return rows def plot_batch(batch, rows, img_dir: Path, out_path: Path): """Draw up to PER_FIGURE labeled images on one figure and save it.""" ncols = min(3, len(batch)) nrows = -(-len(batch) // ncols) fig, axes = plt.subplots(nrows, ncols, figsize=(5 * ncols, 5 * nrows), squeeze=False) for ax in axes.flat: ax.set_axis_off() for ax, name in zip(axes.flat, batch): cls, bbox = rows[name] img_path = img_dir / name if not img_path.exists(): ax.set_title(f"{name}\nIMAGE NOT FOUND", fontsize=9, color="red") continue with Image.open(img_path) as im: ax.imshow(im) if bbox is None or len(bbox) != 4: ax.set_title(f"{name} — {cls}\nBAD BBOX", fontsize=9, color="red") continue xmin, ymin, xmax, ymax = bbox ax.add_patch(Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, linewidth=2, edgecolor=BOX_COLOR, facecolor="none")) ax.text(xmin, max(ymin - 6, 0), cls, fontsize=9, color="black", va="bottom", ha="left", bbox=dict(facecolor=BOX_COLOR, edgecolor="none", boxstyle="round,pad=0.2")) ax.set_title(f"{name} — {cls}", fontsize=9) fig.tight_layout() fig.savefig(out_path, dpi=100, bbox_inches="tight") print(f"saved: {out_path}") return fig def main(): ap = argparse.ArgumentParser( description="Plot dataset images with their [xmin, ymin, xmax, ymax] " "bounding boxes.") ap.add_argument("split", nargs="?", default="train", choices=["train", "val", "test"], help="which split to visualize (default: train)") ap.add_argument("--root", type=Path, default=Path(__file__).resolve().parent, help="dataset root (default: this script's folder)") ap.add_argument("--num", type=int, default=6, help="number of random images to plot (default: 6)") ap.add_argument("--filenames", help="comma-separated filenames to plot instead of a " "random sample") ap.add_argument("--class", dest="cls", help="restrict the random sample to one class") ap.add_argument("--seed", type=int, default=None, help="random seed, for a reproducible sample") ap.add_argument("--save", type=Path, default=None, help="output PNG path (default: preview_.png in --root)") args = ap.parse_args() csv_path = args.root / "labels" / f"{args.split}.csv" img_dir = args.root / args.split if not csv_path.is_file(): sys.exit(f"labels file not found: {csv_path}") rows = load_labels(csv_path) if args.filenames: stem_to_name = {Path(n).stem: n for n in rows} picked, missing = [], [] for n in (s.strip() for s in args.filenames.split(",")): resolved = n if n in rows else stem_to_name.get(Path(n).stem) picked.append(resolved) if resolved else missing.append(n) if missing: sys.exit(f"not found in {csv_path.name}: {missing}") else: pool = sorted(n for n, (cls, _) in rows.items() if args.cls is None or cls == args.cls) if not pool: sys.exit(f"no rows for class {args.cls!r} in {csv_path.name}") picked = random.Random(args.seed).sample(pool, min(args.num, len(pool))) base = args.save or (args.root / f"preview_{args.split}.png") figs = [] for i in range(0, len(picked), PER_FIGURE): suffix = f"_{i // PER_FIGURE + 1}" if len(picked) > PER_FIGURE else "" out = base.with_name(f"{base.stem}{suffix}.png") figs.append(plot_batch(picked[i:i + PER_FIGURE], rows, img_dir, out)) if matplotlib.get_backend().lower() != "agg": plt.show() else: plt.close("all") if __name__ == "__main__": main()