File size: 8,542 Bytes
a099b24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""HuggingFace `datasets` loading script for the ICLR mono-depth benchmark.

Eight zero-shot perspective-depth test sets, mirrored from
`code/iclr/zero-shot3`. Data lives in sibling folders of this script.

Usage:
    from datasets import load_dataset
    ds = load_dataset("/path/to/iclr_benchmark", "iBims-1", split="test")
    row = ds[0]
    # row["image"]  -> {"path": ..., "bytes": PNG/JPG}
    # row["depth"]  -> {"path": ..., "bytes": ...}            (PNG) or raw bytes (.npy)
    # row["text"]   -> str   Gemini Global description
    # row["depth_scale"] -> str  recipe hint

Note that these are **perspective** (pinhole) images, not equirectangular
panoramas — no spherical handling is needed.
"""
from __future__ import annotations
import fnmatch
from pathlib import Path

import datasets as hfds

_CITATION = """
Please cite the original paper of each dataset you use (iBims-1, SUN RGB-D,
DDAD, DIML, DIODE, Hypersim, Virtual KITTI 2), plus ZoeDepth / TR2M for the
evaluation protocol these splits follow.
"""

# name -> (data dir, depth relative path recipe, depth format, scale, min, max)
_CONFIGS = {
    "iBims-1":       dict(fmt="png_u16", scale="v * 50 / 65535",        min=0.0,   max=10.0, layout="zs"),
    "SUN":           dict(fmt="png_u16", scale="v / 10000 (0.1mm)",     min=0.001, max=8.0,  layout="zs"),
    "DDAD":          dict(fmt="png_u16", scale="v / 256",               min=0.001, max=80.0, layout="zs"),
    "DIML":          dict(fmt="png_u16", scale="v / 1000 (mm)",         min=2.0,   max=80.0, layout="zs"),
    "DIODE_indoor":  dict(fmt="npy_f32", scale="already meters",        min=0.001, max=10.0, layout="zs"),
    "DIODE_outdoor": dict(fmt="npy_f32", scale="already meters",        min=0.001, max=80.0, layout="zs"),
    "hypersim":      dict(fmt="png_u16", scale="v / 1000 (planar)",     min=0.001, max=80.0, layout="zs"),
    "vkitti":        dict(fmt="png_u16", scale="v / 100 (cm)",          min=0.001, max=80.0, layout="zs"),
    # RSA sanity-check pair — split .txt at the dataset root, separate trees
    "NYU":           dict(fmt="png_u16", scale="v / 1000 (mm)",         min=0.001, max=10.0, layout="rsa"),
    "KITTI":         dict(fmt="png_u16", scale="v / 256",               min=0.001, max=80.0, layout="rsa"),
}

_DATA_DIRNAME = {"DIODE_indoor": "DIODE_indoors"}

# RSA layout: split file name at the dataset root, and which sub-tree each
# split column resolves under.
_RSA_LAYOUT = {
    "NYU":   dict(split="nyudepthv2_test_files_with_gt.txt",
                  cols=[("rgb", 0), ("rgb", 1)], text_suffix=".txt"),
    "KITTI": dict(split="eigen_test_files_with_gt.txt",
                  cols=[("rgb", 0), ("gt", 1)], text_suffix=".txt"),
}


def _pair_split_file(root: Path, images_txt: Path, depths_txt: Path):
    imgs = [l.strip() for l in images_txt.read_text().split() if l.strip()]
    if not depths_txt.is_file():
        return [(i, None) for i in imgs]
    deps = [l.strip() for l in depths_txt.read_text().split() if l.strip()]
    return list(zip(imgs, deps))


class ICLRDepthConfig(hfds.BuilderConfig):
    def __init__(self, **kw):
        super().__init__(**kw)


class ICLRDepthBenchmark(hfds.GeneratorBasedBuilder):
    BUILDER_CONFIGS = [
        ICLRDepthConfig(name=k, version=hfds.Version("1.0.0"), description=f"{k} test split")
        for k in _CONFIGS
    ]

    def _info(self):
        cfg = _CONFIGS[self.config.name]
        depth_type = hfds.Value("binary") if cfg["fmt"] == "npy_f32" \
                     else hfds.Image(decode=False)
        return hfds.DatasetInfo(
            description="ICLR zero-shot mono-depth benchmark (8 perspective test sets).",
            features=hfds.Features({
                "image":       hfds.Image(decode=False),
                "depth":       depth_type,
                "valid":       depth_type,
                "text":        hfds.Value("string"),
                "rel_path":    hfds.Value("string"),
                "depth_scale": hfds.Value("string"),
                "min_depth":   hfds.Value("float32"),
                "max_depth":   hfds.Value("float32"),
            }),
            citation=_CITATION,
        )

    def _split_generators(self, dl_manager):
        return [hfds.SplitGenerator(name=hfds.Split.TEST,
                                    gen_kwargs={"root": str(Path(self.base_path or "."))})]

    def _generate_examples(self, root):
        root = Path(root)
        name = self.config.name
        cfg = _CONFIGS[name]
        data = root / "datasets" / _DATA_DIRNAME.get(name, name)
        text_root = root / "text"

        for idx, (rgb_rel, dep_rel, mask_rel) in enumerate(self._enumerate(data, name)):
            def rb(rel):
                with open(data / rel, "rb") as fp:
                    return {"path": str(data / rel), "bytes": fp.read()}

            row = {
                "image":       rb(rgb_rel),
                "depth":       rb(dep_rel),
                "valid":       rb(mask_rel) if mask_rel else rb(dep_rel),
                "text":        self._text(text_root, name, Path(rgb_rel)),
                "rel_path":    rgb_rel,
                "depth_scale": cfg["scale"],
                "min_depth":   float(cfg["min"]),
                "max_depth":   float(cfg["max"]),
            }
            yield idx, row

    @staticmethod
    def _enumerate(data: Path, name: str):
        if name in _RSA_LAYOUT:
            layout = _RSA_LAYOUT[name]
            lines = [l.split() for l in (data / layout["split"]).read_text().splitlines()
                     if l.strip()]
            for parts in lines:
                rgb_rel = f"{layout['cols'][0][0]}/{parts[layout['cols'][0][1]]}"
                dep_rel = f"{layout['cols'][1][0]}/{parts[layout['cols'][1][1]]}"
                yield (rgb_rel, dep_rel, None)
            return
        if name == "iBims-1":
            for b in (data / "imagelist.txt").read_text().split():
                yield (f"rgb/{b}.png", f"depth/{b}.png", f"mask_invalid/{b}.png")
        elif name == "SUN":
            for rel in (data / "test_images.txt").read_text().split():
                yield (rel, f"depth/{Path(rel).stem}.png", None)
        elif name in ("DDAD", "vkitti"):
            for i, d in _pair_split_file(data, data / "test_images.txt", data / "test_depths.txt"):
                yield (i, d, None)
        elif name == "DIML":
            for p in sorted((data / "HR" / "outleft").glob("*.png")):
                yield (f"HR/outleft/{p.name}", f"HR/depthmap/{p.name}", None)
        elif name.startswith("DIODE"):
            for p in sorted(data.rglob("*.png")):
                dep = p.parent / f"{p.stem}_depth.npy"
                if dep.is_file():
                    yield (str(p.relative_to(data)), str(dep.relative_to(data)),
                           str((p.parent / f"{p.stem}_depth_mask.npy").relative_to(data)))
        elif name == "hypersim":
            for scene in sorted(p for p in data.iterdir() if p.is_dir()):
                for p in sorted(scene.glob("rgb_cam_*.png")):
                    yield (f"{scene.name}/{p.name}",
                           f"{scene.name}/{p.name.replace('rgb_cam_', 'depth_plane_cam_')}", None)

    @staticmethod
    def _text(text_root: Path, name: str, rgb_rel: Path) -> str:
        import json
        if name in _RSA_LAYOUT:
            # RSA ships one .txt per image; the reference uses the first line.
            try:
                with open(text_root / name / rgb_rel.parent / f"{rgb_rel.stem}.txt") as fp:
                    first = fp.readline().strip()
                return first or "a scene"
            except Exception:
                return "a scene"
        if name.startswith("DIODE"):
            split = "DIODE_indoor" if name == "DIODE_indoor" else "DIODE_outdoor"
            p = text_root / split / rgb_rel.parent / f"{rgb_rel.stem}.json"
        elif name == "SUN":
            p = text_root / "SUN" / "image" / f"{rgb_rel.stem}.json"
        elif name == "iBims-1":
            p = text_root / "iBims-1" / f"{rgb_rel.stem}.json"
        else:
            p = text_root / name / rgb_rel.parent / f"{rgb_rel.stem}.json"
        try:
            g = (json.load(open(p)) or {}).get("Global", {}) or {}
            objs = g.get("objects", []) or []
            desc = (g.get("description", "") or "").strip()
            o = ", ".join(objs) if isinstance(objs, list) and objs else ""
            return f"{o}. {desc}" if o and desc else (desc or o or "a scene")
        except Exception:
            return "a scene"