File size: 5,103 Bytes
a54e6a7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Camera and world geometry in the BOSSV2V convention.

World: UE centimetres, X forward, Y right, Z up. A camera is (quaternion xyzw, position cm, horizontal FOV deg); the
columns of rotation(q) are the camera's forward, right and up axes, with up = forward x right and right = up x forward
(zero roll in all recordings). Images are 1280x720 unless stated otherwise.
"""
from dataclasses import dataclass
import numpy as np

UP = np.array([0.0, 0.0, 1.0])


def rotation(q):
    """Quaternion (x, y, z, w) -> 3x3 matrix; same formula as the dataset exporter."""
    q = np.asarray(q, dtype=float)
    x, y, z, w = q / np.linalg.norm(q)
    return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
                     [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
                     [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])


def quat_from_matrix(R):
    w = np.sqrt(max(0.0, 1 + R[0, 0] + R[1, 1] + R[2, 2])) / 2
    x = np.copysign(np.sqrt(max(0.0, 1 + R[0, 0] - R[1, 1] - R[2, 2])) / 2, R[2, 1] - R[1, 2])
    y = np.copysign(np.sqrt(max(0.0, 1 - R[0, 0] + R[1, 1] - R[2, 2])) / 2, R[0, 2] - R[2, 0])
    z = np.copysign(np.sqrt(max(0.0, 1 - R[0, 0] - R[1, 1] + R[2, 2])) / 2, R[1, 0] - R[0, 1])
    q = np.array([x, y, z, w])
    return q / np.linalg.norm(q)


def look_rotation(forward):
    """Zero-roll camera rotation looking along `forward`."""
    f = np.asarray(forward, float); f = f / np.linalg.norm(f)
    r = np.cross(UP, f); r /= np.linalg.norm(r)
    return np.stack([f, r, np.cross(f, r)], axis=1)


def rot_z(angle):
    c, s = np.cos(angle), np.sin(angle)
    return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])


def rot_axis(axis, angle):
    """Rodrigues rotation matrix about an arbitrary axis."""
    a = np.asarray(axis, float); a = a / np.linalg.norm(a)
    K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])
    return np.eye(3) + np.sin(angle) * K + (1 - np.cos(angle)) * K @ K


@dataclass
class Camera:
    position: np.ndarray          # cm
    quat: np.ndarray              # xyzw
    fov: float = 70.0             # horizontal degrees
    width: int = 1280
    height: int = 720

    @staticmethod
    def look_at(position, target, fov=70.0, width=1280, height=720):
        position = np.asarray(position, float)
        return Camera(position, quat_from_matrix(look_rotation(np.asarray(target, float) - position)), fov, width, height)

    @staticmethod
    def from_horizon(v_horizon, camera_height_cm=220.0, fov=70.0, yaw=0.0, xy=(0.0, 0.0), width=1280, height=720):
        """Camera guessed from a single image: the horizon's image row fixes the pitch (row above the centre = camera
        looks down), plus an assumed height above the ground (z = 0), FOV and facing yaw (rad about +Z)."""
        f = width / 2 / np.tan(np.radians(fov) / 2)
        pitch = np.arctan((height / 2 - v_horizon) / f)             # > 0: horizon above centre -> camera pitched down
        fwd = np.array([np.cos(yaw) * np.cos(-pitch), np.sin(yaw) * np.cos(-pitch), np.sin(-pitch)])
        pos = np.array([xy[0], xy[1], camera_height_cm], float)
        return Camera(pos, quat_from_matrix(look_rotation(fwd)), fov, width, height)

    @property
    def R(self):
        return rotation(self.quat)

    @property
    def focal(self):
        return self.width / 2 / np.tan(np.radians(self.fov) / 2)

    def transform(self):
        """10-vector as stored in states.npz camera_transforms: quat xyzw, position, 3 unused."""
        return np.concatenate([self.quat, self.position, np.zeros(3)])

    def project(self, pts):
        """World points (...,3) -> pixel (u, v) and camera-forward depth (cm)."""
        rel = np.asarray(pts, float) - self.position
        R = self.R
        x, y, z = rel @ R[:, 0], rel @ R[:, 1], rel @ R[:, 2]
        xs = np.maximum(x, 1e-6)
        return np.stack([self.width / 2 + self.focal * y / xs, self.height / 2 - self.focal * z / xs], -1), x

    def ray(self, u, v):
        R = self.R
        d = R[:, 0] + R[:, 1] * (u - self.width / 2) / self.focal - R[:, 2] * (v - self.height / 2) / self.focal
        return d / np.linalg.norm(d)

    def ground_point(self, u, v, ground_z=0.0):
        """Intersect the pixel ray with the plane z = ground_z (e.g. the pixel under a character's feet)."""
        d = self.ray(u, v)
        assert d[2] < -1e-6, "pixel is above the horizon; cannot place it on the ground"
        t = (ground_z - self.position[2]) / d[2]
        return self.position + t * d

    def height_at(self, world_point, v_top):
        """World height (cm) of a vertical extent standing at world_point whose top projects to image row v_top."""
        _, depth = self.project(world_point)
        uv, _ = self.project(world_point)
        return float((uv[1] - v_top) * depth / self.focal)

    def in_view(self, pts, margin=0):
        uv, d = self.project(pts)
        return (d > 10) & (uv[..., 0] >= -margin) & (uv[..., 0] < self.width + margin) & (uv[..., 1] >= -margin) & (uv[..., 1] < self.height + margin)