File size: 21,735 Bytes
b004d6f | 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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 | import csv
import json
import math
import os
import imageio
import lpips
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.io as sio
import torch
import tqdm
from nerfacc import OccGridEstimator
from skimage.metrics import structural_similarity
from misc.dataset_utils import read_h5
from misc.eval_utils import load_eval_args, read_json
from misc.transient_volrend import torch_laser_kernel
from radiance_fields.ngp import NGPRadianceField
from utils import render_transient
def _to_numpy(x):
if isinstance(x, np.ndarray):
return x
if isinstance(x, torch.Tensor):
return x.detach().cpu().numpy()
return np.asarray(x)
def get_gt_depth(frame, camtoworld, data_root_fp):
depth_folder = os.path.join(data_root_fp, "test")
number = int(frame["file_path"].split("_")[-1])
ax_flip = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]])
try:
fname = os.path.join(depth_folder, f"test_{number:03d}_depth_gt.npy")
pos3d = np.load(fname)
except Exception:
fname = os.path.join(depth_folder, f"test_{number:03d}_depth_gt.h5")
pos3d = read_h5(fname)
cam_pos = (ax_flip @ camtoworld)[:3, -1]
depth = np.sqrt(((pos3d - cam_pos[None, None, :]) ** 2).sum(-1))
return depth.astype(np.float32)
def _safe_psnr(gt, pred, mask=None):
gt = np.asarray(gt, dtype=np.float64)
pred = np.asarray(pred, dtype=np.float64)
if mask is not None:
mask = np.asarray(mask, dtype=bool)
if gt.ndim == 3:
if not np.any(mask):
return float("nan")
gt_eval = gt[mask]
pred_eval = pred[mask]
else:
if not np.any(mask):
return float("nan")
gt_eval = gt[mask]
pred_eval = pred[mask]
else:
gt_eval = gt.reshape(-1)
pred_eval = pred.reshape(-1)
if gt_eval.size == 0:
return float("nan")
mse = np.mean((gt_eval - pred_eval) ** 2)
max_val = max(float(np.max(gt_eval)), float(np.max(pred_eval)), 1e-8)
return float(20.0 * np.log10(max_val / np.sqrt(mse + 1e-12)))
def _save_metrics_csv(path, rows):
if not rows:
return
fieldnames = list(rows[0].keys())
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def _to_lpips_input(img_01):
img_rgb = np.repeat(img_01[..., None], 3, axis=2).astype(np.float32)
ten = torch.from_numpy(img_rgb).permute(2, 0, 1).unsqueeze(0)
ten = ten * 2.0 - 1.0
return ten
def _frame_token(frame_dict):
raw = str(frame_dict.get("file_path", frame_dict.get("filepath", "")))
return os.path.splitext(os.path.basename(raw))[0]
def _normalize_for_vis(img: np.ndarray, mask: np.ndarray = None, q_low: float = 1.0, q_high: float = 99.5):
arr = np.asarray(img, dtype=np.float32)
if mask is not None:
m = np.asarray(mask, dtype=bool)
vals = arr[m]
else:
vals = arr.reshape(-1)
vals = vals[np.isfinite(vals)]
if vals.size == 0:
return np.zeros_like(arr, dtype=np.float32)
lo = float(np.percentile(vals, q_low))
hi = float(np.percentile(vals, q_high))
if not np.isfinite(lo) or not np.isfinite(hi) or hi <= lo:
hi = lo + 1e-6
out = (arr - lo) / (hi - lo)
return np.clip(out, 0.0, 1.0)
def _extract_intensity_from_hist(hist: np.ndarray) -> np.ndarray:
hist = np.asarray(hist, dtype=np.float32)
if hist.ndim != 4:
raise ValueError(f"Expected histogram with shape [H, W, n_bins, C], got {hist.shape}")
# Use peak intensity over time bins instead of temporal sum.
peak_rgb = hist.max(axis=-2)
return peak_rgb[..., 0].astype(np.float32)
def _to_gamma_domain(img_01: np.ndarray, gamma: float = 2.2) -> np.ndarray:
img_01 = np.asarray(img_01, dtype=np.float32)
return np.clip(img_01, 0.0, 1.0) ** (1.0 / gamma)
def _load_irf_series(path: str, column: str) -> np.ndarray:
ext = os.path.splitext(path)[1].lower()
if ext == ".csv":
df = pd.read_csv(path, sep=",")
if column in df.columns:
arr = df[column].to_numpy(dtype=np.float64)
else:
numeric_cols = [c for c in df.columns if np.issubdtype(df[c].dtype, np.number)]
if not numeric_cols:
raise ValueError(f"No numeric columns found in IRF CSV: {path}")
arr = df[numeric_cols[0]].to_numpy(dtype=np.float64)
return arr.squeeze()
if ext == ".npy":
return np.load(path).astype(np.float64).squeeze()
if ext == ".mat":
mat = sio.loadmat(path)
if "out" in mat:
return _to_numpy(mat["out"]).astype(np.float64).squeeze()
for value in mat.values():
if isinstance(value, np.ndarray) and value.ndim >= 1 and value.size > 1:
return _to_numpy(value).astype(np.float64).squeeze()
raise ValueError(f"Cannot find valid IRF series in mat file: {path}")
if ext == ".pt":
return _to_numpy(torch.load(path, map_location="cpu")).astype(np.float64).squeeze()
raise ValueError(f"Unsupported IRF extension: {ext}")
def build_irf_kernel(args, device):
irf_path = getattr(args, "irf_path", "") or args.pulse_path
if not irf_path:
raise ValueError("IRF path is empty. Set --irf_path or --pulse_path.")
irf_column = getattr(args, "irf_column", "irf")
irf_half_window = int(getattr(args, "irf_half_window", 50))
no_irf_reverse = bool(getattr(args, "no_irf_reverse", False))
irf = _load_irf_series(irf_path, irf_column)
if irf.ndim != 1:
irf = irf.reshape(-1)
if irf.size == 0:
raise ValueError(f"Loaded empty IRF from: {irf_path}")
peak_idx = int(np.argmax(irf))
if irf_half_window > 0:
lo = max(0, peak_idx - irf_half_window)
hi = min(len(irf), peak_idx + irf_half_window + 1)
irf = irf[lo:hi]
irf = irf / (irf.sum() + 1e-8)
if not no_irf_reverse:
irf = irf[::-1].copy()
laser = torch.tensor(irf, dtype=torch.float32, device=device)
return torch_laser_kernel(laser, device=device)
@torch.no_grad()
def eval():
args = load_eval_args()
print("version =", args.version)
device = args.device
scale_int = float(args.scale_int)
if scale_int <= 0:
raise ValueError(f"scale_int must be > 0, got {scale_int}")
print(f"Using fixed intensity scale from config: {scale_int}")
ckpt_dir = args.checkpoint_dir
outpath = os.path.join(args.checkpoint_dir, "results_revise")
os.makedirs(outpath, exist_ok=True)
transforms_path = os.path.join(args.test_folder_path, f"transforms_{args.split}.json")
positions = read_json(transforms_path)
frames = positions.get("frames", [])
print(f"Using transforms: {transforms_path} (split={args.split}, frames={len(frames)})")
if args.split == "test":
train_tf_path = os.path.join(args.test_folder_path, "transforms_train.json")
if os.path.isfile(train_tf_path):
train_positions = read_json(train_tf_path)
train_frames = train_positions.get("frames", [])
test_ids = {_frame_token(f) for f in frames}
train_ids = {_frame_token(f) for f in train_frames}
overlap = sorted(test_ids.intersection(train_ids))
if overlap:
print(
f"[WARN] test/train overlap detected: {len(overlap)} shared frame ids. "
f"Examples: {overlap[:10]}"
)
else:
print("Train/test overlap check: no shared frame ids.")
else:
print(f"Train overlap check skipped: not found {train_tf_path}")
used_views = []
for idx, f in enumerate(frames):
raw = str(f.get("file_path", f.get("filepath", "")))
used_views.append(
{
"index": idx,
"frame_file_path": raw,
"frame_name": os.path.basename(raw),
"frame_stem": _frame_token(f),
}
)
used_views_json_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_used_views.json")
used_views_csv_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_used_views.csv")
used_views_txt_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_used_views.txt")
with open(used_views_json_path, "w", encoding="utf-8") as f:
json.dump(
{
"split": args.split,
"transforms_path": transforms_path,
"num_frames": len(used_views),
"views": used_views,
},
f,
indent=2,
)
_save_metrics_csv(used_views_csv_path, used_views)
with open(used_views_txt_path, "w", encoding="utf-8") as f:
for v in used_views:
f.write(f"{v['index']}\t{v['frame_file_path']}\n")
print(f"Saved used-view list: {used_views_json_path}")
ckpt_path_rf = os.path.join(ckpt_dir, f"radiance_field_{args.step:04d}.pth")
ckpt_path_oc = os.path.join(ckpt_dir, f"occupancy_grid_{args.step:04d}.pth")
aabb = torch.tensor(args.aabb, dtype=torch.float32, device=device)
img_h = int(getattr(args, "img_height_test", None) or args.img_shape_test)
img_w = int(getattr(args, "img_width_test", None) or args.img_shape_test)
img_shape = (img_h, img_w)
if args.version == "simulated":
from loaders.loader_synthetic import SubjectLoaderTransient as SubjectLoader
test_dataset_kwargs = {
"img_shape": img_shape,
"have_images": True,
"n_bins": args.n_bins,
"color_bkgd_aug": "black",
"rfilter_sigma": args.rfilter_sigma,
}
else:
from loaders.loader_captured_ours import LearnRays, SubjectLoaderTransientRealOurs as SubjectLoader
params = np.load(args.intrinsics, allow_pickle=True)[()]
shift = _to_numpy(params["shift"])
rays = _to_numpy(params["rays"])
source_img_shape = (int(rays.shape[0]), int(rays.shape[1]))
args.laser_kernel = build_irf_kernel(args, device=device)
measurement_root = getattr(args, "measurement_root", "").strip() or None
invalid_mask_path = getattr(args, "invalid_mask_path", "").strip() or None
data_exts = tuple(
e.strip()
for e in getattr(args, "data_exts", ".npz,.txt,.pt,.h5,.hdf5").split(",")
if e.strip()
)
if getattr(args, "bin_width_s_loader", None) is not None:
bin_width_s_loader = float(args.bin_width_s_loader)
else:
bin_width_s_loader = float(args.exposure_time) / 299792458.0
test_dataset_kwargs = {
"img_shape": img_shape,
"have_images": True,
"n_bins": args.n_bins,
"color_bkgd_aug": "black",
"rfilter_sigma": args.rfilter_sigma,
"shift": shift,
"measurement_root": measurement_root,
"data_exts": data_exts,
"bin_width_s": bin_width_s_loader,
"source_img_shape": source_img_shape,
"invalid_mask_path": invalid_mask_path,
"invalid_mask_invalid_gt": float(getattr(args, "invalid_mask_invalid_gt", 10.0)),
}
render_step_size = (((aabb[3:] - aabb[:3]).max() * math.sqrt(3)) / args.render_n_samples).item()
occupancy_grid = OccGridEstimator(
roi_aabb=aabb,
resolution=args.grid_resolution,
levels=args.grid_nlvl,
).to(device)
radiance_field = NGPRadianceField(
use_viewdirs=True,
aabb=aabb,
unbounded=False,
radiance_activation=torch.exp,
args=args,
).to(device)
ckpt = torch.load(ckpt_path_rf, map_location=device)
radiance_field.load_state_dict(ckpt)
ckpt = torch.load(ckpt_path_oc, map_location=device)
occupancy_grid.load_state_dict(ckpt)
radiance_field.eval()
occupancy_grid.eval()
test_dataset = SubjectLoader(
subject_id=f"{args.scene}",
root_fp=args.test_folder_path,
split=args.split,
num_rays=None,
**test_dataset_kwargs,
testing=True,
sample_as_per_distribution=args.sample_as_per_distribution,
)
if args.version == "captured":
test_dataset.K = LearnRays(rays, device=device, img_shape=img_shape).to(device)
test_dataset.rep = 1
test_dataset.camtoworlds = test_dataset.camtoworlds.to(device)
test_dataset.K = test_dataset.K.to(device)
if args.version == "captured":
eval_dataset_scale = float(_to_numpy(test_dataset.max).reshape(-1)[0])
if eval_dataset_scale <= 0:
eval_dataset_scale = 1.0
else:
eval_dataset_scale = 1.0
lpips_model = lpips.LPIPS(net="vgg").eval().cpu()
per_image_metrics = []
for i in range(len(test_dataset)):
frame_info = positions["frames"][i]
frame_key = frame_info.get("file_path", frame_info.get("filepath", str(i)))
frame_file_path = str(frame_key)
frame_name = os.path.basename(frame_file_path)
try:
ind = int(str(frame_key).split("_")[-1])
except Exception:
ind = i
print(f"test image {ind} | file={frame_file_path}")
pred_hist = np.zeros((img_h, img_w, args.n_bins, 3), dtype=np.float32)
pred_depth = np.zeros((img_h, img_w), dtype=np.float32)
pred_depth_viz = np.zeros((img_h, img_w), dtype=np.float32)
weights_sum = np.zeros((img_h, img_w), dtype=np.float32)
gt_hist = None
valid_mask = None
for _ in tqdm.tqdm(range(args.rep_number)):
data = test_dataset[i]
pixels = data["pixels"].detach().cpu().numpy().reshape(img_h, img_w, args.n_bins, 3)
if gt_hist is None:
gt_hist = pixels.astype(np.float32)
if "valid_mask" in data:
valid_mask = data["valid_mask"].detach().cpu().numpy().reshape(img_h, img_w).astype(bool)
rays = data["rays"]
sample_weights = data["weights"].detach().cpu().numpy().reshape(img_h, img_w)
out = render_transient(
radiance_field,
occupancy_grid,
rays,
near_plane=args.near_plane,
far_plane=args.far_plane,
render_step_size=render_step_size,
cone_angle=args.cone_angle,
alpha_thre=args.alpha_thre,
use_normals=False,
args=args,
)
pred_depth += (
out["depths"] * data["weights"][:, None]
).reshape(img_h, img_w).detach().cpu().numpy()
pred_depth_viz += (
out["depths"] * data["weights"][:, None] * (out["opacities"] > 0)
).reshape(img_h, img_w).detach().cpu().numpy()
pred_hist += (
out["colors"] * data["weights"][:, None]
).reshape(img_h, img_w, args.n_bins, 3).detach().cpu().numpy()
weights_sum += sample_weights
del out
weights_sum = np.clip(weights_sum, 1e-8, None)
pred_hist /= weights_sum[..., None, None]
pred_depth /= weights_sum
pred_depth_viz /= weights_sum
if valid_mask is None:
valid_mask = np.ones((img_h, img_w), dtype=bool)
gt_hist_1 = gt_hist[..., 0].astype(np.float32)
pred_hist_1 = pred_hist[..., 0].astype(np.float32)
gt_intensity = _extract_intensity_from_hist(gt_hist)
pred_intensity = _extract_intensity_from_hist(pred_hist)
if args.version == "simulated":
gt_depth = get_gt_depth(frame_info, test_dataset.camtoworlds[i].cpu().numpy(), args.test_folder_path)
else:
gt_depth = np.argmax(gt_hist_1, axis=-1).astype(np.float32) * float(args.exposure_time) / 2.0
# Keep captured depth definition consistent with histogram peak depth.
pred_depth = np.argmax(pred_hist_1, axis=-1).astype(np.float32) * float(args.exposure_time) / 2.0
signal_mask = gt_intensity > 0
if args.version == "captured" and float(getattr(args, "meas_peak_min", 100.0)) > 0:
peak_thre_norm = float(args.meas_peak_min) / float(eval_dataset_scale)
meas_peak_mask = np.max(gt_hist_1, axis=-1) >= peak_thre_norm
else:
meas_peak_mask = np.ones_like(signal_mask, dtype=bool)
metric_mask = valid_mask & signal_mask & meas_peak_mask
print(
f"mask ratio: valid={valid_mask.mean():.4f}, "
f"peak={meas_peak_mask.mean():.4f}, metric={metric_mask.mean():.4f}"
)
depth_mask = metric_mask & np.isfinite(gt_depth) & np.isfinite(pred_depth)
if np.any(depth_mask):
depth_l1 = float(np.mean(np.abs(gt_depth[depth_mask] - pred_depth[depth_mask])))
else:
depth_l1 = float("nan")
gt_intensity_01 = np.clip(gt_intensity / scale_int, 0.0, 1.0)
pred_intensity_01 = np.clip(pred_intensity / scale_int, 0.0, 1.0)
gt_hist_01 = np.clip(gt_hist_1 / scale_int, 0.0, 1.0)
pred_hist_01 = np.clip(pred_hist_1 / scale_int, 0.0, 1.0)
gt_intensity_gamma = _to_gamma_domain(gt_intensity_01)
pred_intensity_gamma = _to_gamma_domain(pred_intensity_01)
gt_intensity_eval = gt_intensity_gamma.copy()
pred_intensity_eval = pred_intensity_gamma.copy()
gt_intensity_eval[~metric_mask] = 0.0
pred_intensity_eval[~metric_mask] = 0.0
intensity_ssim = float(
structural_similarity(gt_intensity_eval, pred_intensity_eval, data_range=1.0)
)
gt_lpips = _to_lpips_input(gt_intensity_eval)
pred_lpips = _to_lpips_input(pred_intensity_eval)
intensity_lpips = float(lpips_model(gt_lpips, pred_lpips).detach().cpu().item())
waveform_psnr = _safe_psnr(gt_hist_01, pred_hist_01, mask=metric_mask)
prefix = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_test{ind}")
np.save(prefix + "_hist_gt.npy", gt_hist_1.astype(np.float32))
np.save(prefix + "_hist_pred.npy", pred_hist_1.astype(np.float32))
np.save(prefix + "_depth_gt.npy", gt_depth.astype(np.float32))
np.save(prefix + "_depth_pred.npy", pred_depth.astype(np.float32))
np.save(prefix + "_intensity_gt.npy", gt_intensity.astype(np.float32))
np.save(prefix + "_intensity_pred.npy", pred_intensity.astype(np.float32))
np.save(prefix + "_valid_mask.npy", metric_mask.astype(np.uint8))
np.save(prefix + "_meas_peak_mask.npy", meas_peak_mask.astype(np.uint8))
torch.save(torch.from_numpy(pred_hist_1.astype(np.float32)), prefix + "_conv_pred.pt")
gt_intensity_vis = _normalize_for_vis(gt_intensity, metric_mask) ** (1.0 / 2.2)
pred_intensity_vis = _normalize_for_vis(pred_intensity, metric_mask) ** (1.0 / 2.2)
imageio.imwrite(prefix + "_intensity_gt.png", (gt_intensity_vis * 255.0).astype(np.uint8))
imageio.imwrite(prefix + "_intensity_pred.png", (pred_intensity_vis * 255.0).astype(np.uint8))
depth_for_viz = gt_depth[depth_mask] if np.any(depth_mask) else gt_depth[np.isfinite(gt_depth)]
if depth_for_viz.size > 0:
vmin = float(np.percentile(depth_for_viz, 1.0))
vmax = float(np.percentile(depth_for_viz, 99.0))
if vmax <= vmin:
vmax = vmin + 1e-6
else:
vmin, vmax = 0.0, 1.0
plt.imsave(prefix + "_depth_gt.png", gt_depth, cmap="inferno", vmin=vmin, vmax=vmax)
plt.imsave(prefix + "_depth_pred.png", pred_depth, cmap="inferno", vmin=vmin, vmax=vmax)
plt.imsave(prefix + "_depth_pred_viz.png", pred_depth_viz, cmap="inferno", vmin=vmin, vmax=vmax)
metrics_row = {
"index": i,
"frame_id": ind,
"frame_file_path": frame_file_path,
"frame_name": frame_name,
"intensity_ssim": intensity_ssim,
"intensity_lpips": intensity_lpips,
"depth_l1": depth_l1,
"waveform_psnr": waveform_psnr,
}
per_image_metrics.append(metrics_row)
print(
f"SSIM={intensity_ssim:.6f} LPIPS={intensity_lpips:.6f} "
f"DepthL1={depth_l1:.6f} WavePSNR={waveform_psnr:.4f}"
)
print("-----")
def _nanmean(key):
values = np.array([row[key] for row in per_image_metrics], dtype=np.float64)
return float(np.nanmean(values))
summary = {
"scene": args.scene,
"num_views": int(args.num_views),
"step": int(args.step),
"num_images": len(per_image_metrics),
"avg_intensity_ssim": _nanmean("intensity_ssim"),
"avg_intensity_lpips": _nanmean("intensity_lpips"),
"avg_depth_l1": _nanmean("depth_l1"),
"avg_waveform_psnr": _nanmean("waveform_psnr"),
}
print(json.dumps(summary, indent=2))
csv_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_metrics_per_image.csv")
json_rows_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_metrics_per_image.json")
json_summary_path = os.path.join(outpath, f"{args.scene}_{args.num_views}_{args.step}_metrics_summary.json")
_save_metrics_csv(csv_path, per_image_metrics)
with open(json_rows_path, "w", encoding="utf-8") as f:
json.dump(per_image_metrics, f, indent=2)
with open(json_summary_path, "w", encoding="utf-8") as f:
json.dump(summary, f, indent=2)
if __name__ == "__main__":
eval()
|