File size: 18,186 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 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | """Minimal loader for the ICLR mono-depth zero-shot benchmark.
Mirrors the preprocessing of `iclr/zero-shot3/eval/datasets.py` (which in turn
follows ZoeDepth / TR2M / RSA official protocols) but reads only from THIS
folder, so the benchmark is self-contained after upload.
Layout expected here (produced by `_collect.py`):
iclr_benchmark/
├── datasets/<name>/... # same relative paths as zero-shot3/datasets/<name>
└── text/<name>/... # Gemini text JSONs
The 8 datasets are all **perspective** (mono) depth, not panoramas:
`iBims-1`, `SUN`, `DDAD`, `DIML`, `DIODE_indoor`, `DIODE_outdoor`,
`hypersim`, `vkitti`.
Usage:
from _loader import MonoDepthDataset, ALL_DATASETS, DATASET_META
ds = MonoDepthDataset(root="/path/to/iclr_benchmark", name="iBims-1")
s = ds[0]
# s: {"image": float32 [3,H,W] in [0,1], "depth": float32 [1,H,W] meters,
# "valid": bool [1,H,W], "text": str, "rgb_path": str, "dataset": str}
Depth conventions (meters unless noted):
iBims-1 uint16 * 50/65535 valid = mask_invalid & mask_transp & (d>0)
SUN uint16 / 10000 (0.1mm) d > 8 invalid
DDAD uint16 / 256
DIML uint16 / 1000 (mm)
DIODE_indoor float32 .npy (already meters) + _depth_mask.npy
DIODE_outdoor same
hypersim uint16 / 1000 (planar depth)
vkitti uint16 / 100 (cm) d > 80 invalid
"""
from __future__ import annotations
import glob
import json
import os
from pathlib import Path
from typing import Any, Optional
import numpy as np
from PIL import Image
# ----------------------------------------------------------------------
# Eval protocol metadata (mirrors zero-shot3/eval/datasets.py DATASET_META)
# ----------------------------------------------------------------------
DATASET_META: dict[str, dict] = {
"iBims-1": dict(min_depth=0.0, max_depth=10.0, crop="eigen"),
"SUN": dict(min_depth=0.001, max_depth=8.0, crop="eigen"),
"DIODE_indoor": dict(min_depth=0.001, max_depth=10.0, crop="eigen"),
"hypersim": dict(min_depth=0.001, max_depth=80.0, crop="eigen"),
"DDAD": dict(min_depth=0.001, max_depth=80.0, crop="garg"),
"DIML": dict(min_depth=2.0, max_depth=80.0, crop="garg"),
"DIODE_outdoor": dict(min_depth=0.001, max_depth=80.0, crop="garg"),
"vkitti": dict(min_depth=0.001, max_depth=80.0, crop="garg"),
# RSA sanity-check pair: no eigen/garg crop (NYU has none in RSA's eval;
# KITTI is already KB-cropped at load time).
"NYU": dict(min_depth=0.001, max_depth=10.0, crop=None),
"KITTI": dict(min_depth=0.001, max_depth=80.0, crop=None),
}
ALL_DATASETS = list(DATASET_META.keys())
# Datasets that use the RSA layout (split .txt at the dataset root, separate
# rgb / gt trees) rather than the zero-shot3 layout.
RSA_DATASETS = ("NYU", "KITTI")
# split file → (column → sub-tree the reference loader resolves it under).
# NYU keeps rgb and depth in the same tree; KITTI splits rgb from ground truth.
RSA_LAYOUT = {
"NYU": dict(split="nyudepthv2_test_files_with_gt.txt",
cols=[("rgb", 0), ("rgb", 1)]),
"KITTI": dict(split="eigen_test_files_with_gt.txt",
cols=[("rgb", 0), ("gt", 1)]),
}
KITTI_KB_H, KITTI_KB_W = 352, 1216
# Data-dir name on disk (DIODE_indoor's data folder is plural upstream).
DATA_DIRNAME = {"DIODE_indoor": "DIODE_indoors"}
# Eval-time resize, matching the zero-shot3 loaders. None = keep native.
RESIZE = {
"SUN": (480, 640), # H, W (then eigen crop)
"DIODE_indoor": None, # short side 480, GT native
"DIODE_outdoor": None,
"hypersim": (480, 640),
"DDAD": (352, 1216),
"vkitti": None, # KB crop disabled upstream
}
DIODE_SHORT_SIDE = 480
# Eigen crop in 480x640 image space, Garg crop in 352x1216 space.
EIGEN_CROP = (45, 471, 41, 601) # top, bottom, left, right
GARG_CROP = (0, 352, 0, 1216)
# ----------------------------------------------------------------------
def _load_rgb(path: Path, size: Optional[tuple[int, int]] = None,
antialias: bool = False) -> np.ndarray:
"""RGB -> float32 [3, H, W] in [0, 1] (no ImageNet normalisation).
``size`` is (H, W). The resize op is chosen to match the reference
evaluator exactly, because PIL bilinear, torch bilinear without
antialiasing and ``torchvision.transforms.Resize(antialias=True)`` all
disagree by up to ~0.3 on a [0,1] scale:
* ``antialias=False`` → ``F.interpolate(mode="bilinear",
align_corners=True)`` — what the SUN loader uses.
* ``antialias=True`` → ``T.Resize(size, antialias=True)`` — what the
DDAD / hypersim / DIODE loaders use.
"""
img = Image.open(path).convert("RGB")
native_hw = (img.size[1], img.size[0])
if size is None or native_hw == size:
arr = np.asarray(img, dtype=np.float32) / 255.0
return np.ascontiguousarray(arr.transpose(2, 0, 1))
try:
import torch
import torch.nn.functional as F
t = torch.from_numpy(np.asarray(img, dtype=np.float32) / 255.0
).permute(2, 0, 1).contiguous()
if antialias:
from torchvision import transforms as _T
out = _T.Resize(size, antialias=True)(t)
else:
out = F.interpolate(t[None], size, mode="bilinear",
align_corners=True)[0]
return out.numpy()
except ImportError:
img = img.resize((size[1], size[0]), Image.BILINEAR)
arr = np.asarray(img, dtype=np.float32) / 255.0
return np.ascontiguousarray(arr.transpose(2, 0, 1))
def _resize_nearest(depth: np.ndarray, size: tuple[int, int]) -> np.ndarray:
"""Resize a depth map with exact nearest-neighbour indexing.
Uses ``torch.nn.functional.interpolate`` when torch is importable, because
that is what the reference evaluator uses and its index arithmetic is not
reproducible by PIL or a naive float formula (they disagree on ~2% of
pixels for non-integer scale factors). Falls back to PIL otherwise.
"""
h, w = size
if depth.shape[:2] == (h, w):
return depth
try:
import torch
import torch.nn.functional as F
t = torch.from_numpy(np.ascontiguousarray(depth, dtype=np.float32))
return F.interpolate(t[None, None], (h, w), mode="nearest")[0, 0].numpy()
except ImportError:
img = Image.fromarray(depth.astype(np.float32), mode="F")
return np.asarray(img.resize((w, h), Image.NEAREST), dtype=np.float32)
def _load_text(path: Path) -> str:
"""Global description from a Gemini JSON, "objects. description"."""
try:
with open(path) as fp:
data = json.load(fp)
g = data.get("Global", {}) or {}
objs = g.get("objects", []) or []
obj_str = ", ".join(objs) if isinstance(objs, list) and objs else ""
desc = (g.get("description", "") or "").strip()
if obj_str and desc:
return f"{obj_str}. {desc}"
return desc or obj_str or "a scene"
except Exception:
return "a scene"
def _read_text_first_line(path: Path) -> str:
"""First line of an RSA-style caption file (its eval uses line 0)."""
try:
with open(path) as fp:
first = fp.readline().strip()
return first or "a scene"
except Exception:
return "a scene"
# ----------------------------------------------------------------------
class MonoDepthDataset:
"""Sequential-access dataset over one of the 8 ICLR mono-depth test sets."""
def __init__(self, root: str | os.PathLike, name: str,
apply_crop: bool = False):
if name not in DATASET_META:
raise ValueError(f"unknown dataset {name!r}; choose from {ALL_DATASETS}")
self.name = name
self.meta = DATASET_META[name]
self.root = Path(root)
self.data = self.root / "datasets" / DATA_DIRNAME.get(name, name)
self.text = self.root / "text" / name
self.apply_crop = apply_crop
self.entries: list[tuple[Path, Path, Optional[Path]]] = []
getattr(self, f"_init_{name.replace('-', '_').replace('.', '_')}")()
# ---- per-dataset indexing ------------------------------------------
def _init_iBims_1(self):
basenames = [l.strip() for l in (self.data / "imagelist.txt").read_text().splitlines() if l.strip()]
for b in basenames:
self.entries.append((self.data / "rgb" / f"{b}.png",
self.data / "depth" / f"{b}.png",
self.data / "mask_invalid" / f"{b}.png"))
def _init_SUN(self):
for rel in (self.data / "test_images.txt").read_text().split():
stem = Path(rel).stem
self.entries.append((self.data / rel, self.data / "depth" / f"{stem}.png", None))
def _init_DDAD(self):
imgs = (self.data / "test_images.txt").read_text().split()
deps = (self.data / "test_depths.txt").read_text().split()
for i, d in zip(imgs, deps):
self.entries.append((self.data / i, self.data / d, None))
def _init_DIML(self):
for p in sorted(glob.glob(str(self.data / "HR" / "outleft" / "*.png"))):
dep = Path(p.replace("outleft", "depthmap"))
self.entries.append((Path(p), dep, None))
def _init_DIODE_indoor(self):
self._init_diode("DIODE_indoor")
def _init_DIODE_outdoor(self):
self._init_diode("DIODE_outdoor")
def _init_diode(self, split: str):
for p in sorted(self.data.rglob("*.png")):
dep = p.parent / f"{p.stem}_depth.npy"
mask = p.parent / f"{p.stem}_depth_mask.npy"
if dep.is_file():
self.entries.append((p, dep, mask if mask.is_file() else None))
def _init_hypersim(self):
for scene in sorted(os.listdir(self.data)):
sd = self.data / scene
if not sd.is_dir():
continue
for fn in sorted(os.listdir(sd)):
if fn.startswith("rgb_cam_") and fn.endswith(".png"):
base = fn[:-4]
cam_frame = base.replace("rgb_cam_", "")
self.entries.append((sd / fn, sd / f"depth_plane_cam_{cam_frame}.png", None))
def _init_vkitti(self):
imgs = (self.data / "test_images.txt").read_text().split()
dep_txt = self.data / "test_depths.txt"
deps = dep_txt.read_text().split() if dep_txt.is_file() else None
for k, i in enumerate(imgs):
if deps is not None:
dep = self.data / deps[k]
else:
r = i.replace("rgb/", "depth/", 1).replace("/rgb/", "/depth/") \
.replace("rgb_", "depth_").replace(".jpg", ".png")
dep = self.data / r
self.entries.append((self.data / i, dep, None))
# --------------------------------------------------------------------
def __len__(self) -> int:
return len(self.entries)
def __getitem__(self, idx: int) -> dict[str, Any]:
rgb_p, dep_p, mask_p = self.entries[idx]
if self.name.startswith("DIODE"):
return self._get_diode(rgb_p, dep_p, mask_p)
if self.name in RSA_DATASETS:
return getattr(self, f"_get_{self.name}")(rgb_p, dep_p, mask_p)
method = f"_get_{self.name.replace('-', '_').replace('.', '_')}"
return getattr(self, method)(rgb_p, dep_p, mask_p)
def _init_NYU(self):
self._init_rsa("NYU")
def _init_KITTI(self):
self._init_rsa("KITTI")
def _init_rsa(self, name: str):
layout = RSA_LAYOUT[name]
lines = [l.split() for l in (self.data / layout["split"]).read_text().splitlines()
if l.strip()]
for parts in lines:
cols = []
for tree, col in layout["cols"]:
cols.append(self.data / tree / parts[col] if len(parts) > col else None)
self.entries.append((cols[0], cols[1], None))
# ---- per-dataset readers -------------------------------------------
def _get_NYU(self, rgb_p, dep_p, mask_p):
"""NYU Depth v2 test (Eigen split). Native 480x640, no crop."""
rgb = _load_rgb(rgb_p)
d = np.asarray(Image.open(dep_p), dtype=np.uint16).astype(np.float32) / 1000.0
valid = d > 0
return self._pack(rgb, np.where(valid, d, 0.0), valid, rgb_p,
rel_override=rgb_p.relative_to(self.data / "rgb"))
def _get_KITTI(self, rgb_p, dep_p, mask_p):
"""KITTI Eigen test. RGB and GT are both KB-cropped to 352x1216."""
rgb = _load_rgb(rgb_p)
d = np.asarray(Image.open(dep_p), dtype=np.float32) / 256.0
h, w = rgb.shape[1:]
top = int(h - KITTI_KB_H)
left = int((w - KITTI_KB_W) / 2)
rgb = rgb[:, top:top + KITTI_KB_H, left:left + KITTI_KB_W]
d = d[top:top + KITTI_KB_H, left:left + KITTI_KB_W]
valid = d > 0
return self._pack(rgb, np.where(valid, d, 0.0), valid, rgb_p,
rel_override=rgb_p.relative_to(self.data / "rgb"))
def _get_iBims_1(self, rgb_p, dep_p, mask_p):
rgb = _load_rgb(rgb_p)
d = np.asarray(Image.open(dep_p), dtype=np.uint16).astype(np.float32) * 50.0 / 65535
m_inv = np.asarray(Image.open(mask_p)).astype(bool)
m_transp = np.asarray(Image.open(mask_p.parent.parent / "mask_transp" / mask_p.name)).astype(bool)
valid = m_inv & m_transp & (d > 0)
# Match the reference loader: invalid pixels carry -1, not 0.
depth = np.where(valid, d, -1.0).astype(np.float32)
return self._pack(rgb, depth, valid, rgb_p)
def _get_SUN(self, rgb_p, dep_p, mask_p):
size = RESIZE["SUN"]
rgb = _load_rgb(rgb_p, size)
d = np.asarray(Image.open(dep_p), dtype=np.uint16).astype(np.float32) / 10000.0
# Resize FIRST, then threshold — matches the reference, which defines
# the 8 m cutoff in the 480x640 frame rather than at native resolution.
d = _resize_nearest(d, size)
valid = (d > 0) & (d <= 8.0)
d = np.where(d > 8.0, -1.0, d) # reference marks >8m as -1 first
return self._pack(rgb, np.where(valid, d, 0.0), valid, rgb_p)
def _get_DDAD(self, rgb_p, dep_p, mask_p):
size = RESIZE["DDAD"]
rgb = _load_rgb(rgb_p, size, antialias=True) # image resized (T.Resize semantics)
d = np.asarray(Image.open(dep_p), dtype=np.uint16).astype(np.float32) / 256.0
valid = d > 0 # GT stays native
return self._pack(rgb, np.where(valid, d, 0.0), valid, rgb_p)
def _get_DIML(self, rgb_p, dep_p, mask_p):
rgb = _load_rgb(rgb_p)
d = np.asarray(Image.open(dep_p), dtype=np.uint16).astype(np.float32) / 1000.0
valid = d > 0
return self._pack(rgb, np.where(valid, d, 0.0), valid, rgb_p)
def _get_DIODE_indoor(self, rgb_p, dep_p, mask_p):
return self._get_diode(rgb_p, dep_p, mask_p)
def _get_DIODE_outdoor(self, rgb_p, dep_p, mask_p):
return self._get_diode(rgb_p, dep_p, mask_p)
def _get_diode(self, rgb_p, dep_p, mask_p):
rgb = _load_rgb(rgb_p)
h, w = rgb.shape[1:]
if min(h, w) != DIODE_SHORT_SIDE:
scale = DIODE_SHORT_SIDE / min(h, w)
rgb = _load_rgb(rgb_p, (round(h * scale), round(w * scale)),
antialias=True)
d = np.load(dep_p).astype(np.float32)
if d.ndim == 3:
d = d.squeeze(-1)
valid = np.load(mask_p).astype(bool) if mask_p is not None else d > 0
# Reference keeps the raw GT values (including the ones the mask
# excludes); only `valid` gates them.
return self._pack(rgb, d, valid, rgb_p)
def _get_hypersim(self, rgb_p, dep_p, mask_p):
size = RESIZE["hypersim"]
rgb = _load_rgb(rgb_p, size, antialias=True)
d = np.asarray(Image.open(dep_p), dtype=np.uint16).astype(np.float32) / 1000.0
valid = d > 0
return self._pack(rgb, np.where(valid, d, 0.0), valid, rgb_p)
def _get_vkitti(self, rgb_p, dep_p, mask_p):
rgb = _load_rgb(rgb_p)
d = np.asarray(Image.open(dep_p)).astype(np.float32) / 100.0
valid = (d > 0) & (d <= 80.0)
return self._pack(rgb, np.where(valid, d, 0.0), valid, rgb_p)
# --------------------------------------------------------------------
def _pack(self, rgb, depth, valid, rgb_p, rel_override=None) -> dict[str, Any]:
if self.apply_crop:
t, b, l, r = EIGEN_CROP if self.meta["crop"] == "eigen" else GARG_CROP
h, w = depth.shape
if b <= h and r <= w:
rgb = rgb[:, t:b, l:r]
depth = depth[t:b, l:r]
valid = valid[t:b, l:r]
rel = rel_override if rel_override is not None else rgb_p.relative_to(self.data)
return {
"image": rgb,
"depth": depth[None].astype(np.float32),
"valid": valid[None],
"text": self._text_for(rel),
"rgb_path": str(rel),
"dataset": self.name,
}
def _text_for(self, rel: Path) -> str:
if self.name in RSA_DATASETS:
# RSA ships one .txt per image; the reference uses the FIRST line
# (its eval runs with random_number=0), not the whole file.
return _read_text_first_line(self.text / rel.parent / f"{rel.stem}.txt")
if self.name.startswith("DIODE"):
split = "DIODE_indoor" if self.name == "DIODE_indoor" else "DIODE_outdoor"
return _load_text(self.root / "text" / split / rel.parent / f"{rel.stem}.json")
if self.name == "SUN":
return _load_text(self.text / "image" / f"{rel.stem}.json")
if self.name == "iBims-1":
return _load_text(self.text / f"{rel.stem}.json")
return _load_text(self.text / rel.parent / f"{rel.stem}.json")
def available_datasets() -> list[str]:
return ALL_DATASETS
|