#!/usr/bin/env python3 """Colourise the label masks of this dataset so you can look at them. The label PNGs store the class id directly in the pixel value (0..N-1), which is the standard convention (Cityscapes *_labelTrainIds.png, ADE20K, COCO-Stuff). Because the ids are small numbers the files look almost entirely black in an image viewer - that is expected, not corruption. This script maps them to the colours in classes.json. python visualize_labels.py # grid of random samples python visualize_labels.py val_001889 # one sample: image | mask | overlay python visualize_labels.py val_001889 --mode overlay python visualize_labels.py --contact-sheet 8 Needs only numpy and Pillow. Run it from anywhere; it finds the dataset next to itself. """ from __future__ import annotations import argparse import glob as _glob import json import os import random import sys HERE = os.path.dirname(os.path.abspath(__file__)) try: import numpy as np from PIL import Image except ImportError as exc: # pragma: no cover - dependency guidance sys.exit(f"error: this script needs numpy and Pillow ({exc}).\n" f" install them with: pip install numpy pillow") # ----------------------------------------------------------------- dataset --- def load_palette(root): cfg_path = os.path.join(root, "classes.json") if not os.path.exists(cfg_path): sys.exit(f"error: {cfg_path} not found.\n" f" pass the dataset folder with --root /path/to/dataset") cfg = json.load(open(cfg_path)) n = cfg["num_classes"] pal = np.zeros((max(n, 256), 3), np.uint8) names = [] for c in cfg["classes"]: pal[c["id"]] = c["color"] names.append(c["name"]) return pal, names def _split_dirs(root, split): """Return (images_dir, labels_dir) for either supported layout.""" a = (os.path.join(root, "images", split), os.path.join(root, "labels", split)) b = (os.path.join(root, split, "images"), os.path.join(root, split, "labels")) return a if os.path.isdir(a[0]) else b def known_splits(root): return [s for s in ("train", "val", "test") if os.path.isdir(_split_dirs(root, s)[0])] def normalise_stem(value, root): """Accept a bare stem, a filename, or a path to an image/label file.""" stem = os.path.basename(str(value)) for ext in (".png", ".jpg", ".jpeg"): if stem.lower().endswith(ext): stem = stem[: -len(ext)] break return stem def resolve(root, stem): """Find (image_path, label_path) for a stem, or exit with a helpful message.""" for split in known_splits(root): img_dir, lbl_dir = _split_dirs(root, split) for ext in (".png", ".jpg", ".jpeg"): img = os.path.join(img_dir, stem + ext) lbl = os.path.join(lbl_dir, stem + ".png") if os.path.exists(img) and os.path.exists(lbl): return img, lbl, split # Not found - be useful about it. hint = "" for split in known_splits(root): img_dir, _ = _split_dirs(root, split) near = sorted(os.path.basename(p) for p in _glob.glob(os.path.join(img_dir, stem[:9] + "*")))[:3] if near: hint = ("\n did you mean: " + ", ".join(os.path.splitext(n)[0] for n in near)) break examples = [] for split in known_splits(root): f = os.path.join(root, "splits", f"{split}.txt") if os.path.exists(f): with open(f) as fh: first = fh.readline().strip() if first: examples.append(first) sys.exit(f"error: no image/label pair named '{stem}' in {root}{hint}\n" f" valid names look like: {', '.join(examples) or 'train_000002'}\n" f" full list: {os.path.join(root, 'splits', 'val.txt')}") def load_pair(root, stem): img_p, lbl_p, split = resolve(root, stem) return (np.array(Image.open(img_p).convert("RGB")), np.array(Image.open(lbl_p)), split) # ------------------------------------------------------------------ render --- def colorize(label, pal): return pal[label] def _legend_font(size): from PIL import ImageFont for name in ("DejaVuSans-Bold.ttf", "DejaVuSans.ttf"): try: return ImageFont.truetype(name, size) except OSError: pass try: # matplotlib bundles DejaVu, if it happens to be installed import matplotlib hits = _glob.glob(os.path.join(os.path.dirname(matplotlib.__file__), "mpl-data", "fonts", "ttf", "DejaVuSans*.ttf")) if hits: return ImageFont.truetype(sorted(hits)[0], size) except Exception: # noqa: BLE001 pass try: # Pillow >= 10.1 can scale its built-in font return ImageFont.load_default(size=size) except TypeError: return ImageFont.load_default() def legend_bar(pal, names, width, height=None): from PIL import ImageDraw n = len(names) if height is None: height = max(44, width // 20) font = _legend_font(int(height * 0.55)) seg = width // n bar = np.full((height, width, 3), 255, np.uint8) for i in range(n): bar[:, i * seg:(i + 1) * seg] = pal[i] im = Image.fromarray(bar) draw = ImageDraw.Draw(im) for i, name in enumerate(names): r, g, b = (int(x) for x in pal[i]) fg = (255, 255, 255) if (0.299 * r + 0.587 * g + 0.114 * b) < 128 else (0, 0, 0) box = draw.textbbox((0, 0), name, font=font) tw, th = box[2] - box[0], box[3] - box[1] draw.text((i * seg + (seg - tw) / 2, (height - th) / 2 - box[1]), name, fill=fg, font=font) return np.array(im) def render(root, stem, pal, mode, alpha): img, lbl, _ = load_pair(root, stem) col = colorize(lbl, pal) if mode == "mask": return col ov = (img * (1 - alpha) + col * alpha).astype(np.uint8) if mode == "overlay": return ov return np.concatenate([img, col, ov], axis=1) def sample_stems(root, k, seed=0): for split in ("val", "train"): f = os.path.join(root, "splits", f"{split}.txt") if os.path.exists(f): stems = [l.strip() for l in open(f) if l.strip()] break else: split = known_splits(root)[0] img_dir, _ = _split_dirs(root, split) stems = [os.path.splitext(f)[0] for f in os.listdir(img_dir)] rng = random.Random(seed) return rng.sample(stems, min(k, len(stems))) # -------------------------------------------------------------------- main --- def main(): ap = argparse.ArgumentParser( description="Colourise this dataset's label masks.", epilog="with no arguments, writes a grid of random samples") ap.add_argument("sample", nargs="?", help="name of a sample, e.g. val_001889 (extension optional)") ap.add_argument("--stem", help="same as the positional argument") ap.add_argument("--root", default=HERE, help="dataset folder (default: the folder this script is in)") ap.add_argument("--mode", choices=["triptych", "mask", "overlay"], default="triptych", help="triptych = image | mask | overlay (default)") ap.add_argument("--alpha", type=float, default=0.55, help="mask opacity in the overlay (default 0.55)") ap.add_argument("--contact-sheet", type=int, default=0, help="render N random samples as a grid") ap.add_argument("--out", help="output PNG (default: chosen automatically)") ap.add_argument("--scale", type=float, default=0.5, help="output scale factor (default 0.5)") args = ap.parse_args() root = os.path.abspath(args.root) pal, names = load_palette(root) stem = args.sample or args.stem if stem: stem = normalise_stem(stem, root) # No sample given and no explicit grid requested -> useful default. n_grid = args.contact_sheet or (0 if stem else 6) if n_grid: out = args.out or "contact_sheet.png" tiles = [] for s in sample_stems(root, n_grid): im = Image.fromarray(render(root, s, pal, args.mode, args.alpha)) im = im.resize((max(1, int(im.width * args.scale)), max(1, int(im.height * args.scale)))) tiles.append(np.array(im)) grid = np.concatenate(tiles, axis=0) grid = np.concatenate([grid, legend_bar(pal, names, grid.shape[1])], axis=0) Image.fromarray(grid).save(out) print(f"wrote {os.path.abspath(out)} ({n_grid} random samples: " f"image | mask | overlay)") print(f"classes: {', '.join(names)}") return out = args.out or f"{stem}_{args.mode}.png" im = Image.fromarray(render(root, stem, pal, args.mode, args.alpha)) if args.scale != 1.0: im = im.resize((max(1, int(im.width * args.scale)), max(1, int(im.height * args.scale)))) im.save(out) print(f"wrote {os.path.abspath(out)}") print(f"classes: {', '.join(names)}") if __name__ == "__main__": main()