Spaces:
Running on Zero

File size: 2,830 Bytes
a863b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Geometry utilities. `geotrf` and `Rt_to_T` are adapted from DUSt3R
# (https://github.com/naver/dust3r, Copyright (C) 2024-present Naver Corporation, CC BY-NC-SA 4.0).

import torch
import torch.nn.functional as F


def Rt_to_T(R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
    """(..., 3, 3), (..., 3) -> (..., 4, 4) homogeneous transform."""
    T = torch.cat((R, t.unsqueeze(-1)), dim=-1)
    T = F.pad(T, (0, 0, 0, 1), value=0)
    T[..., -1, -1] = 1
    return T


def geotrf(T: torch.Tensor, pts: torch.Tensor) -> torch.Tensor:
    """Applies (..., 4, 4) transforms to points (..., *, 3) with matching leading dims."""
    Tt = T.swapaxes(-1, -2)
    p = pts.reshape(*T.shape[:-2], -1, 3)
    return (p @ Tt[..., :3, :3] + Tt[..., 3:, :3]).reshape(pts.shape)


def solve_transfm(p: torch.Tensor, q: torch.Tensor, w: torch.Tensor = None) -> torch.Tensor:
    """Weighted rigid (Kabsch) alignment: the (..., 4, 4) transform T minimizing
    sum_n w_n |T p_n - q_n|^2, for points p, q of shape (..., N, 3) and weights w (..., N)."""
    N = p.shape[-2]
    if w is None:
        w = torch.ones_like(p[..., :1]) / N
    elif w.ndim == p.ndim - 1:
        w = w.unsqueeze(-1)

    mean_p = torch.sum(w * p, dim=-2, keepdim=True)
    mean_q = torch.sum(w * q, dim=-2, keepdim=True)
    H = torch.einsum("...ni,...nj->...ij", w * (p - mean_p), q - mean_q)
    U, _, Vt = torch.linalg.svd(H)
    R = torch.matmul(Vt.transpose(-2, -1), U.transpose(-2, -1))

    # ensure a proper rotation (det(R) = 1)
    mask = torch.det(R) < 0
    mask_lastrow = mask[..., None, None].repeat(mask.ndim * [1] + [3, 3])
    mask_lastrow[..., :-1, :] = False
    Vt_new = Vt.clone()
    Vt_new[mask_lastrow] *= -1
    R[mask] = torch.matmul(Vt_new[mask].transpose(-2, -1), U[mask].transpose(-2, -1))

    t = (mean_q - torch.matmul(R, mean_p.transpose(-2, -1)).transpose(-2, -1)).squeeze(-2)
    return Rt_to_T(R, t)


def focal_length_from_pointmap(pts3d: torch.Tensor, conf: torch.Tensor = None) -> torch.Tensor:
    """Least-squares focal length (principal point at the image center) of (..., H, W, 3)
    pointmaps in camera coordinates. Returns (...,); NaN where it cannot be estimated."""
    H, W = pts3d.shape[-3:-1]
    yy, xx = torch.meshgrid(torch.arange(H, device=pts3d.device), torch.arange(W, device=pts3d.device), indexing="ij")
    du = (xx - W / 2.0).reshape(1, -1)
    dv = (yy - H / 2.0).reshape(1, -1)

    X, Y, Z = (pts3d[..., i].reshape(*pts3d.shape[:-3], -1) for i in range(3))
    valid = Z > 1e-6
    Xn = torch.where(valid, X / Z, torch.zeros_like(X))
    Yn = torch.where(valid, Y / Z, torch.zeros_like(Y))
    w = valid.float() if conf is None else conf.reshape(*pts3d.shape[:-3], -1) * valid

    f = (w * (du * Xn + dv * Yn)).sum(dim=-1) / (w * (Xn**2 + Yn**2)).sum(dim=-1)
    f[f <= 0] = torch.nan
    return f