eval_our / _loader.py
nosmall's picture
Upload panorama depth benchmark (initial)
d3c7b2f verified
Raw History Blame Contribute Delete
7.46 kB
"""Minimal PyTorch Dataset for the panorama depth benchmark.
Usage:
from _loader import PanoDepthDataset
ds = PanoDepthDataset(root="/path/to/benchmark", name="stanford2d3d")
sample = ds[0]
# sample.keys() == {"rgb", "depth", "valid", "stem"}
Depth is **radial distance in meters** (not planar / Z depth) for every
subset; a 360° depth model that outputs planar depth needs to convert
internally before comparison.
"""
from __future__ import annotations
import io
import os
from pathlib import Path
from typing import Callable, Any
import numpy as np
# Needed for Holo360D's EXR files
os.environ.setdefault("OPENCV_IO_ENABLE_OPENEXR", "1")
def _read_dpt(path) -> np.ndarray:
"""Sintel .dpt depth file: magic 'PIEH' + int32 width + int32 height + float32 raster."""
import struct
with open(path, "rb") as fp:
if fp.read(4) != b"PIEH":
raise RuntimeError(f"not a .dpt file: {path}")
w = struct.unpack("<i", fp.read(4))[0]
h = struct.unpack("<i", fp.read(4))[0]
buf = fp.read(w * h * 4)
return np.frombuffer(buf, dtype=np.float32).reshape(h, w).copy()
def _read_npy(path) -> np.ndarray:
"""Depth stored as a raw .npy array (PanoInfinigen). Already metric meters."""
return np.load(path, allow_pickle=False).astype(np.float32)
# ----------------------------------------------------------------------
# Per-dataset config: how to decode depth bytes, min/max metric range,
# whether a mask file is present.
# ----------------------------------------------------------------------
def _d_stanford2d3d(arr): return arr.astype(np.float32) / 512.0
def _d_matterport3d(arr): return arr.astype(np.float32) / 4000.0
def _d_structured3d(arr): return arr.astype(np.float32) / 1000.0
def _d_metropolis(arr): return arr.astype(np.float32) / 512.0
def _d_panosuncg(arr):
if arr.ndim == 3:
arr = arr[..., 0]
return arr.astype(np.float32) * 10.0 / 255.0
CONFIG: dict[str, dict] = {
"stanford2d3d": dict(decode=_d_stanford2d3d, min=0.001, max=5.0, depth_fmt="png_u16"),
"matterport3d": dict(decode=_d_matterport3d, min=0.001, max=5.0, depth_fmt="png_u16"),
"panosuncg": dict(decode=_d_panosuncg, min=0.001, max=5.0, depth_fmt="png_u8_rgb"),
"structured3d": dict(decode=_d_structured3d, min=0.001, max=5.0, depth_fmt="png_u16"),
"metropolis": dict(decode=_d_metropolis, min=0.2, max=128.0, depth_fmt="png_u16"),
"holo360d_indoor": dict(decode=None, min=0.01, max=10.0, depth_fmt="exr"),
"holo360d_outdoor":dict(decode=None, min=0.01, max=75.0, depth_fmt="exr"),
"replica360_2k": dict(decode=None, min=0.001, max=10.0, depth_fmt="dpt"),
"panoinfinigen_indoor": dict(decode=None, min=0.001, max=10.0, depth_fmt="npy"),
"panoinfinigen_nature": dict(decode=None, min=0.001, max=100.0, depth_fmt="npy"),
"panoinfinigen_urban": dict(decode=None, min=0.001, max=500.0, depth_fmt="npy"),
"zuripano": dict(decode=None, min=0.01, max=75.0, depth_fmt="parquet"),
}
# ----------------------------------------------------------------------
class PanoDepthDataset:
"""Lightweight sequential-access dataset.
Returns dicts with uint8 RGB [H, W, 3], float32 depth [H, W] in meters,
bool valid mask [H, W], and the sample stem.
"""
def __init__(self, root: str | os.PathLike, name: str):
if name not in CONFIG:
raise ValueError(f"unknown dataset {name!r}; available: {sorted(CONFIG)}")
self.name = name
self.cfg = CONFIG[name]
self.root = Path(root) / name
if self.cfg["depth_fmt"] == "parquet":
self._init_parquet()
else:
self._init_file()
# -------- native file layout ------------------------------------
def _init_file(self):
split_file = self.root / "test.txt"
if not split_file.is_file():
raise FileNotFoundError(split_file)
self.entries = []
for ln in split_file.read_text().strip().splitlines():
parts = ln.split()
if len(parts) < 2:
continue
rgb_rel, dep_rel = parts[0], parts[1]
mask_rel = parts[2] if len(parts) >= 3 and parts[2] else None
self.entries.append((rgb_rel, dep_rel, mask_rel))
# -------- zuripano parquet layout -------------------------------
def _init_parquet(self):
import pyarrow.parquet as pq
shard_paths = sorted((self.root / "data").glob("test-*.parquet"))
self._shard_tables = [pq.read_table(str(p)) for p in shard_paths]
self._shard_offsets = []
total = 0
for t in self._shard_tables:
self._shard_offsets.append(total)
total += t.num_rows
self._total = total
# ----------------------------------------------------------------
def __len__(self) -> int:
return self._total if self.cfg["depth_fmt"] == "parquet" else len(self.entries)
def __getitem__(self, i: int) -> dict[str, Any]:
if self.cfg["depth_fmt"] == "parquet":
return self._getitem_parquet(i)
return self._getitem_file(i)
# ----------------------------------------------------------------
def _getitem_file(self, i: int) -> dict[str, Any]:
from PIL import Image
rgb_rel, dep_rel, mask_rel = self.entries[i]
rgb = np.asarray(Image.open(self.root / rgb_rel).convert("RGB"), dtype=np.uint8)
fmt = self.cfg["depth_fmt"]
if fmt == "exr":
import cv2
d = cv2.imread(str(self.root / dep_rel), cv2.IMREAD_UNCHANGED)
if d is None:
raise RuntimeError(f"cv2 could not read EXR: {dep_rel}")
if d.ndim == 3:
d = d[..., 0]
depth = d.astype(np.float32)
elif fmt == "dpt":
depth = _read_dpt(self.root / dep_rel)
elif fmt == "npy":
depth = _read_npy(self.root / dep_rel)
else:
d = np.asarray(Image.open(self.root / dep_rel))
depth = self.cfg["decode"](d)
valid = np.isfinite(depth) & (depth > self.cfg["min"]) & (depth <= self.cfg["max"])
if mask_rel:
m = np.asarray(Image.open(self.root / mask_rel).convert("L"))
valid = valid & (m > 127)
stem = Path(rgb_rel).stem
return {"rgb": rgb, "depth": depth, "valid": valid, "stem": stem}
def _getitem_parquet(self, i: int) -> dict[str, Any]:
from PIL import Image
shard, local = 0, i
for s, off in enumerate(self._shard_offsets):
if i >= off:
shard, local = s, i - off
t = self._shard_tables[shard]
row = {col: t.column(col)[local].as_py() for col in t.column_names}
rgb = np.asarray(Image.open(io.BytesIO(row["rgb"]["bytes"])).convert("RGB"), dtype=np.uint8)
d_u16 = np.asarray(Image.open(io.BytesIO(row["depth"]["bytes"])))
depth = d_u16.astype(np.float32) * (200.0 / 65535.0)
mask = np.asarray(Image.open(io.BytesIO(row["mask"]["bytes"])).convert("L"))
valid = (mask > 127) & np.isfinite(depth) & \
(depth > self.cfg["min"]) & (depth <= self.cfg["max"])
return {"rgb": rgb, "depth": depth, "valid": valid, "stem": row.get("id", f"idx_{i}")}
def available_datasets() -> list[str]:
return sorted(CONFIG.keys())