"""Read coco/train/labels.json, print counts per class and save one box overlay (overlay.jpg). Run from the dataset root: python scripts/load_example.py (needs Pillow)""" import collections, json from pathlib import Path from PIL import Image, ImageDraw root = Path(__file__).resolve().parent.parent d = json.loads((root / "coco/train/labels.json").read_text()) names = {c["id"]: c["name"] for c in d["categories"]} count = collections.Counter(names[a["category_id"]] for a in d["annotations"]) print(len(d["images"]), "tiles,", len(d["annotations"]), "boxes") for n in names.values(): print(f" {n:13s} {count[n]:6d} boxes") by_img = collections.defaultdict(list) for a in d["annotations"]: by_img[a["image_id"]].append(a) img = max(d["images"], key=lambda i: len(by_img[i["id"]])) # tile with the most boxes im = Image.open(root / "coco/train/images" / img["file_name"]).convert("RGB") dr = ImageDraw.Draw(im) for a in by_img[img["id"]]: x, y, w, h = a["bbox"] dr.rectangle([x, y, x + w, y + h], outline=(255, 0, 0), width=3) im.save(root / "overlay.jpg", quality=90) print("saved overlay.jpg for", img["file_name"], "with", len(by_img[img["id"]]), "boxes")