File size: 5,525 Bytes
ece131e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
122
123
124
#!/usr/bin/env python3
"""Save a grid of samples: RGB, class mask, and for syn also depth, surface normals and 2D boxes.

Reads only the shards it needs from the Hub (or from a downloaded copy with --data-dir).
A syn sample costs one row group (about 170 MB); real_ours shards are about 250 MB each,
and real_curated shards about 3 GB, so download real_curated first and pass --data-dir.

Examples:
  python tools/explore.py --config syn --classes escalator handrail --num 4 --out syn.png
  python tools/explore.py --config real_ours --split test --num 6 --out real_test.png
"""
from __future__ import annotations

import argparse
import random
import sys
from pathlib import Path

import numpy as np
from PIL import Image, ImageDraw, ImageFont

sys.path.insert(0, str(Path(__file__).resolve().parent))
import navable as nv  # noqa: E402

SYN_COLUMNS = ["image", "mask", "normals", "depth", "bbox", "bbox_class_ids", "object_class", "environment", "asset"]


def font(size: int):
    try:
        return ImageFont.load_default(size=size)
    except TypeError:  # Pillow < 10.1
        return ImageFont.load_default()


def panels(row: dict, config: str) -> list[tuple[str, Image.Image]]:
    image, labels = nv.open_image(row["image"]).convert("RGB"), nv.mask_array(row["mask"])
    out = [("RGB", image), ("class mask", nv.overlay(image, labels, alpha=0.6))]
    if config == "syn":
        out += [("depth (m, log scale)", nv.depth_to_rgb(nv.decode_depth(row["depth"]))),
                ("surface normals", nv.normals_to_rgb(row["normals"])),
                ("2D boxes", nv.draw_boxes(image, row["bbox"], row["bbox_class_ids"]))]
    return out


def caption(row: dict, config: str) -> str:
    if config == "syn":
        return f"{row['object_class']} | {row['environment']} | {row['asset']}"
    if config == "real_ours":
        return f"{row['object_class']} | {row.get('location') or 'location n/a'}"
    return f"{row['source_dataset']} ({row['split_origin']})"


def pick_rows(args) -> list[dict]:
    """Random rows spread over classes (real_curated: over source datasets)."""
    rng = random.Random(args.seed)
    files = nv.parquet_files(args.config, args.split, args.data_dir, args.classes)
    key = "source_dataset" if args.config == "real_curated" else "object_class"
    if args.config == "syn":  # shards are large: look inside `num` random shards only
        files = rng.sample(files, min(args.num, len(files)))
    candidates: dict[str, list[tuple[str, int]]] = {}
    for f in files:
        for i, k in enumerate(nv.read_column(f, key)):
            if not args.classes or k in args.classes:
                candidates.setdefault(k, []).append((f, i))
    picks: list[tuple[str, int]] = []
    pools = {k: rng.sample(v, len(v)) for k, v in sorted(candidates.items())}
    while len(picks) < args.num and any(pools.values()):
        for k in list(pools):  # round-robin over classes
            if pools[k] and len(picks) < args.num:
                picks.append(pools[k].pop())
    columns = SYN_COLUMNS if args.config == "syn" else None
    rows = {}
    for f in dict.fromkeys(f for f, _ in picks):
        idx = [i for g, i in picks if g == f]
        rows.update({(f, i): r for i, r in zip(idx, nv.read_rows(f, idx, columns))})
    return [rows[p] for p in picks]


def grid(rows: list[dict], config: str, width: int) -> Image.Image:
    cells = [panels(r, config) for r in rows]
    titles = [t for t, _ in cells[0]]
    heights = [max(round(width * im.height / im.width) for _, im in c) for c in cells]
    head, cap, pad = 28, 22, 6
    canvas = Image.new("RGB", (len(titles) * (width + pad) + pad, head + sum(h + cap + pad for h in heights)), "white")
    draw = ImageDraw.Draw(canvas)
    for j, t in enumerate(titles):
        draw.text((pad + j * (width + pad) + 4, 6), t, fill=(30, 30, 30), font=font(16))
    y = head
    for row, c, h in zip(rows, cells, heights):
        draw.text((pad + 4, y + 3), caption(row, config), fill=(60, 60, 60), font=font(13))
        for j, (_, im) in enumerate(c):
            canvas.paste(im.resize((width, round(width * im.height / im.width)), Image.BILINEAR),
                         (pad + j * (width + pad), y + cap))
        y += h + cap + pad
    return canvas


def main() -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("--config", choices=list(nv.CONFIGS), default="real_ours")
    p.add_argument("--split", default=None, help="default: test for real_ours, train otherwise")
    p.add_argument("--classes", nargs="+", choices=nv.CLASSES[1:], help="syn / real_ours: only these classes")
    p.add_argument("--num", type=int, default=4)
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--width", type=int, default=360, help="width of each panel in pixels")
    p.add_argument("--data-dir", type=Path, help="downloaded copy of the repo (see tools/download.py)")
    p.add_argument("--out", type=Path, default=Path("navable_samples.png"))
    args = p.parse_args()
    args.split = args.split or ("test" if args.config == "real_ours" else "train")
    if args.split not in nv.CONFIGS[args.config]:
        p.error(f"{args.config} has splits {nv.CONFIGS[args.config]}")

    rows = pick_rows(args)
    if not rows:
        print("no matching rows")
        return 1
    grid(rows, args.config, args.width).save(args.out)
    print(f"saved {len(rows)} samples -> {args.out}")
    return 0


if __name__ == "__main__":
    sys.exit(main())