File size: 5,609 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ad60ce
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch

H, W = 294, 518
Z_TOL, A_TOL = 0.05, 0.1


def unproject(depth, K, c2w, u, v):
    z = depth[..., v, u].double()
    x = (u - K[..., 0, 2, None]) / K[..., 0, 0, None] * z
    y = (v - K[..., 1, 2, None]) / K[..., 1, 1, None] * z
    pc = torch.stack([x, y, z], -1)
    return pc @ c2w[..., :3, :3].transpose(-1, -2) + c2w[..., None, :3, 3]


def project(X, K, c2w):
    w2c = torch.linalg.inv(c2w)
    pc = X @ w2c[..., :3, :3].transpose(-1, -2) + w2c[..., None, :3, 3]
    z = pc[..., 2]
    u = K[..., 0, 0, None] * pc[..., 0] / z + K[..., 0, 2, None]
    v = K[..., 1, 1, None] * pc[..., 1] / z + K[..., 1, 2, None]
    return u, v, z


def inside(u, v, z, h=H, w=W):
    return torch.isfinite(u) & torch.isfinite(v) & (z > 0) & (u >= 0) & (u <= w - 1) & (v >= 0) & (v <= h - 1)


def _pixels(img, u, v):
    return img.flatten(-2).gather(-1, v * img.shape[-1] + u)


def bilinear(img, u, v):
    h, w = img.shape[-2:]
    u0 = u.floor().long().clamp(0, w - 2)
    v0 = v.floor().long().clamp(0, h - 2)
    du, dv = u - u0, v - v0
    a, b = _pixels(img, u0, v0), _pixels(img, u0 + 1, v0)
    c, d = _pixels(img, u0, v0 + 1), _pixels(img, u0 + 1, v0 + 1)
    return (a * (1 - du) + b * du) * (1 - dv) + (c * (1 - du) + d * du) * dv


def nearest(img, u, v):
    h, w = img.shape[-2:]
    return _pixels(img, u.round().long().clamp(0, w - 1), v.round().long().clamp(0, h - 1))


def ext_to_c2w(ext):
    m = torch.eye(4, dtype=torch.float64, device=ext.device).expand(*ext.shape[:-2], 4, 4).clone()
    m[..., :3, :] = ext[..., :3, :].double()
    return torch.linalg.inv(m)


@torch.no_grad()
def visibility(depth, K, c2w, mask, source_indices=None, *, alpha=None, z_tol=Z_TOL, a_tol=A_TOL):
    b, t, h, w = depth.shape
    if h < 2 or w < 2 or mask.shape != depth.shape or K.shape != (b, t, 3, 3) or c2w.shape != (b, t, 4, 4):
        raise ValueError('visibility: depth/mask/camera shape mismatch')
    sources = list(range(t)) if source_indices is None else list(source_indices)
    if not 0 < len(sources) <= 8 or len(set(sources)) != len(sources) or any(j < 0 or j >= t for j in sources):
        raise ValueError('visibility: need 1-8 distinct sources')
    depth, K, c2w = depth.double(), K.double(), c2w.double()
    alpha = mask.double() if alpha is None else alpha.double().expand_as(depth)
    mask = mask.bool()
    valid_depth = torch.isfinite(depth) & (depth > 0)
    counts = mask.flatten(-2).sum(-1)
    n = int(counts.max())
    bits = torch.zeros_like(mask, dtype=torch.uint8)
    if n == 0:
        return {'V': valid_depth, 'bits': bits}
    u = torch.zeros((b, t, n), dtype=torch.long, device=depth.device)
    v = torch.zeros_like(u)
    active = torch.arange(n, device=depth.device)[None, None] < counts[..., None]
    bi, ti, vv, uu = mask.nonzero(as_tuple=True)
    offsets = counts.flatten().cumsum(0) - counts.flatten()
    slot = torch.arange(len(bi), device=depth.device) - offsets[bi * t + ti]
    u[bi, ti, slot], v[bi, ti, slot] = uu, vv
    z = _pixels(depth, u, v)
    x = (u - K[..., 0, 2, None]) / K[..., 0, 0, None] * z
    y = (v - K[..., 1, 2, None]) / K[..., 1, 1, None] * z
    X = torch.stack([x, y, z], -1) @ c2w[..., :3, :3].transpose(-1, -2) + c2w[..., None, :3, 3]
    valid = active & torch.isfinite(z) & (z > 0)
    packed = torch.zeros_like(u, dtype=torch.uint8)
    targets = torch.arange(t, device=depth.device)[None, :, None]
    for bit, j in enumerate(sources):
        uj, vj, zj = project(X, K[:, j:j+1], c2w[:, j:j+1])
        ins = inside(uj, vj, zj, h, w) & valid & (targets != j)
        us, vs = torch.where(ins, uj, 0.), torch.where(ins, vj, 0.)
        a = nearest(alpha[:, j:j+1].expand(b, t, h, w), us, vs)
        d = bilinear(depth[:, j:j+1].expand(b, t, h, w), us, vs)
        rel = (zj - d).abs() / zj
        passed = ins & (a < a_tol) & torch.isfinite(d) & (d > 0) & (rel < z_tol)
        packed |= passed.to(torch.uint8) << bit
    bits[bi, ti, vv, uu] = packed[bi, ti, slot]
    return {'V': ((~mask) | (bits != 0)) & valid_depth, 'bits': bits}


@torch.no_grad()
def visibility_camera(depth, K, c2w, mask, source_indices=None, *, alpha=None, a_tol=A_TOL):
    b, t, h, w = depth.shape
    if mask.shape != depth.shape or K.shape != (b, t, 3, 3) or c2w.shape != (b, t, 4, 4):
        raise ValueError('visibility: depth/mask/camera shape mismatch')
    sources = list(range(t)) if source_indices is None else list(source_indices)
    if not 0 < len(sources) <= 8 or len(set(sources)) != len(sources) or any(j < 0 or j >= t for j in sources):
        raise ValueError('visibility: need 1-8 distinct sources')
    depth, K, c2w = depth.double(), K.double(), c2w.double()
    mask = mask.bool()
    alpha = mask.double() if alpha is None else alpha.double().expand_as(depth)
    u = torch.arange(w, device=depth.device).repeat(h)
    v = torch.arange(h, device=depth.device).repeat_interleave(w)
    X = unproject(depth, K, c2w, u, v)
    valid = torch.isfinite(depth) & (depth > 0)
    active = (valid & mask).flatten(-2)
    bits = torch.zeros((b, t, h * w), dtype=torch.uint8, device=depth.device)
    targets = torch.arange(t, device=depth.device)[None, :, None]
    for bit, j in enumerate(sources):
        uj, vj, zj = project(X, K[:, j:j+1], c2w[:, j:j+1])
        ins = inside(uj, vj, zj, h, w) & active & (targets != j)
        us, vs = torch.where(ins, uj, 0.), torch.where(ins, vj, 0.)
        a = nearest(alpha[:, j:j+1].expand(b, t, h, w), us, vs)
        bits |= (ins & (a < a_tol)).to(torch.uint8) << bit
    bits = bits.reshape(b, t, h, w)
    return {'V': ((~mask) | (bits != 0)) & valid, 'bits': bits}