File size: 4,253 Bytes
f8fe8a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Shared utilities: NeRF-synthetic (Blender) loading, camera conventions, metrics.

All camera handling converts the Blender/OpenGL camera-to-world convention used in
the synthetic NeRF dataset into the OpenCV world-to-camera convention expected by
gsplat (x right, y down, z forward).
"""
import json
import math
import os
from typing import Tuple

import numpy as np
import torch
import torch.nn.functional as F
import imageio.v2 as imageio


# Blender (OpenGL) -> OpenCV camera-axis flip (negate y and z columns).
_GL2CV = torch.tensor(
    [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, 1]], dtype=torch.float32
)


def load_blender(scene_dir: str, split: str, downscale: int, device: str,
                 max_views: int = -1) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int, int]:
    """Return (images[N,H,W,3] in [0,1] white-composited, viewmats[N,4,4] w2c OpenCV,
    Ks[N,3,3], W, H)."""
    with open(os.path.join(scene_dir, f"transforms_{split}.json")) as f:
        meta = json.load(f)
    angle_x = float(meta["camera_angle_x"])
    frames = meta["frames"]
    # de-duplicate frames that may carry the same base path (some mirrors add extra maps)
    seen = set()
    sel = []
    for fr in frames:
        fp = fr["file_path"]
        if fp in seen:
            continue
        seen.add(fp)
        sel.append(fr)
    frames = sel
    if max_views > 0:
        frames = frames[:max_views]

    imgs, viewmats = [], []
    W = H = None
    for fr in frames:
        fp = fr["file_path"]
        path = os.path.join(scene_dir, fp)
        if not path.endswith(".png"):
            path = path + ".png"
        img = imageio.imread(path).astype(np.float32) / 255.0  # H,W,4 (RGBA) or H,W,3
        if img.shape[-1] == 4:
            rgb, a = img[..., :3], img[..., 3:4]
            img = rgb * a + (1.0 - a)  # composite over white
        H0, W0 = img.shape[:2]
        t = torch.from_numpy(img).permute(2, 0, 1)[None]  # 1,3,H,W
        if downscale > 1:
            t = F.interpolate(t, scale_factor=1.0 / downscale, mode="area")
        t = t[0].permute(1, 2, 0).contiguous()  # H,W,3
        H, W = t.shape[0], t.shape[1]
        imgs.append(t)
        c2w_gl = torch.tensor(fr["transform_matrix"], dtype=torch.float32)
        c2w_cv = c2w_gl @ _GL2CV
        w2c = torch.inverse(c2w_cv)
        viewmats.append(w2c)

    focal = 0.5 * W / math.tan(0.5 * angle_x)
    K = torch.tensor([[focal, 0, W / 2.0], [0, focal, H / 2.0], [0, 0, 1.0]], dtype=torch.float32)
    images = torch.stack(imgs, 0).to(device)
    viewmats = torch.stack(viewmats, 0).to(device)
    Ks = K[None].repeat(len(frames), 1, 1).to(device)
    return images, viewmats, Ks, W, H


def psnr(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
    """PSNR between two images in [0,1] (any shape)."""
    mse = torch.mean((a - b) ** 2)
    mse = torch.clamp(mse, min=1e-12)
    return -10.0 * torch.log10(mse)


def _gaussian_window(window_size: int, sigma: float, device) -> torch.Tensor:
    coords = torch.arange(window_size, dtype=torch.float32, device=device) - window_size // 2
    g = torch.exp(-(coords ** 2) / (2 * sigma ** 2))
    g = g / g.sum()
    return g


def ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int = 11) -> torch.Tensor:
    """SSIM for NCHW tensors in [0,1]."""
    device = img1.device
    channel = img1.shape[1]
    _1d = _gaussian_window(window_size, 1.5, device)
    _2d = (_1d[:, None] @ _1d[None, :])
    window = _2d.expand(channel, 1, window_size, window_size).contiguous()
    pad = window_size // 2
    mu1 = F.conv2d(img1, window, padding=pad, groups=channel)
    mu2 = F.conv2d(img2, window, padding=pad, groups=channel)
    mu1_sq, mu2_sq, mu1_mu2 = mu1 * mu1, mu2 * mu2, mu1 * mu2
    sigma1_sq = F.conv2d(img1 * img1, window, padding=pad, groups=channel) - mu1_sq
    sigma2_sq = F.conv2d(img2 * img2, window, padding=pad, groups=channel) - mu2_sq
    sigma12 = F.conv2d(img1 * img2, window, padding=pad, groups=channel) - mu1_mu2
    C1, C2 = 0.01 ** 2, 0.03 ** 2
    ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / (
        (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))
    return ssim_map.mean()


def inverse_sigmoid(x: float) -> float:
    return math.log(x / (1.0 - x))