"""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"