-
Notifications
You must be signed in to change notification settings - Fork 1
/
cam_utils.py
402 lines (339 loc) · 13.8 KB
/
cam_utils.py
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
import numpy as np
from scipy.spatial.transform import Rotation
from typing import Literal
from utils import safe_normalize
# convert between different world coordinate systems
def convert(
pose,
target: Literal['unity', 'blender', 'opencv', 'colmap', 'opengl'] = 'unity',
original: Literal['unity', 'blender', 'opencv', 'colmap', 'opengl'] = 'opengl',
):
"""A method to convert between different world coordinate systems.
Args:
pose (np.ndarray): camera pose, float [4, 4].
target (Literal['unity', 'blender', 'opencv', 'colmap', 'opengl'], optional): from convention. Defaults to 'unity'.
original (Literal['unity', 'blender', 'opencv', 'colmap', 'opengl'], optional): to convention. Defaults to 'opengl'.
Returns:
np.ndarray: converted camera pose, float [4, 4].
"""
if original == 'opengl':
if target == 'unity':
pose[2] *= -1
elif target == 'blender':
pose[2] *= -1
pose[[1, 2]] = pose[[2, 1]]
elif target in ['opencv', 'colmap']:
pose[1:3] *= -1
elif original == 'unity':
if target == 'opengl':
pose[2] *= -1
elif target == 'blender':
pose[[1, 2]] = pose[[2, 1]]
elif target in ['opencv', 'colmap']:
pose[1] *= -1
elif original == 'blender':
if target == 'opengl':
pose[1] *= -1
pose[[1, 2]] = pose[[2, 1]]
elif target == 'unity':
pose[[1, 2]] = pose[[2, 1]]
elif target in ['opencv', 'colmap']:
pose[2] *= -1
pose[[1, 2]] = pose[[2, 1]]
elif original in ['opencv', 'colmap']:
if target == 'opengl':
pose[1:3] *= -1
elif target == 'unity':
pose[1] *= -1
elif target == 'blender':
pose[1] *= -1
pose[[1, 2]] = pose[[2, 1]]
return pose
def look_at(campos, target, opengl=True):
"""construct pose rotation matrix by look-at.
Args:
campos (np.ndarray): camera position, float [3]
target (np.ndarray): look at target, float [3]
opengl (bool, optional): whether use opengl camera convention (forward direction is target --> camera). Defaults to True.
Returns:
np.ndarray: the camera pose rotation matrix, float [3, 3], normalized.
"""
if not opengl:
# camera forward aligns with -z, camera --> target
forward_vector = safe_normalize(target - campos)
up_vector = np.array([0, 1, 0], dtype=np.float32)
right_vector = safe_normalize(np.cross(forward_vector, up_vector))
up_vector = safe_normalize(np.cross(right_vector, forward_vector))
else:
# camera forward aligns with +z, target --> camera
forward_vector = safe_normalize(campos - target)
up_vector = np.array([0, 1, 0], dtype=np.float32)
right_vector = safe_normalize(np.cross(up_vector, forward_vector))
up_vector = safe_normalize(np.cross(forward_vector, right_vector))
R = np.stack([right_vector, up_vector, forward_vector], axis=1)
return R
# elevation & azimuth to pose (cam2world) matrix
def orbit_camera(elevation, azimuth, radius=1, is_degree=True, target=None, opengl=True, customize_pos=False):
"""construct a camera pose matrix orbiting a target with elevation & azimuth angle.
Args:
elevation (float): elevation in (-90, 90), from +y to -y is (-90, 90)
azimuth (float): azimuth in (-180, 180), from +z to +x is (0, 90)
radius (int, optional): camera radius. Defaults to 1.
is_degree (bool, optional): if the angles are in degree. Defaults to True.
target (np.ndarray, optional): look at target position. Defaults to None.
opengl (bool, optional): whether to use OpenGL camera convention. Defaults to True.
Returns:
np.ndarray: the camera pose matrix, float [4, 4]
"""
if is_degree:
elevation = np.deg2rad(elevation)
azimuth = np.deg2rad(azimuth)
x = radius * np.cos(elevation) * np.sin(azimuth)
y = - radius * np.sin(elevation)
z = radius * np.cos(elevation) * np.cos(azimuth)
if target is None:
target = np.zeros([3], dtype=np.float32)
if not customize_pos:
campos = np.array([x, y, z]) + target # [3] original implementation, shift the camera pose together with the target
else:
campos = np.array([x, y, z]) # customized for tactile camera, keep the predefined camera pose
T = np.eye(4, dtype=np.float32)
T[:3, :3] = look_at(campos, target, opengl)
T[:3, 3] = campos
return T
def undo_orbit_camera(T, is_degree=True):
""" undo an orbital camera pose matrix to elevation & azimuth
Args:
T (np.ndarray): camera pose matrix, float [4, 4], must be an orbital camera targeting at (0, 0, 0)!
is_degree (bool, optional): whether to return angles in degree. Defaults to True.
Returns:
Tuple[float]: elevation, azimuth, and radius.
"""
campos = T[:3, 3]
radius = np.linalg.norm(campos)
elevation = np.arcsin(-campos[1] / radius)
azimuth = np.arctan2(campos[0], campos[2])
if is_degree:
elevation = np.rad2deg(elevation)
azimuth = np.rad2deg(azimuth)
return elevation, azimuth, radius
# perspective matrix
def get_perspective(fovy, aspect=1, near=0.01, far=1000):
"""construct a perspective matrix from fovy.
Args:
fovy (float): field of view in degree along y-axis.
aspect (int, optional): aspect ratio. Defaults to 1.
near (float, optional): near clip plane. Defaults to 0.01.
far (int, optional): far clip plane. Defaults to 1000.
Returns:
np.ndarray: perspective matrix, float [4, 4]
"""
# fovy: field of view in degree.
y = np.tan(np.deg2rad(fovy) / 2)
return np.array(
[
[1 / (y * aspect), 0, 0, 0],
[0, -1 / y, 0, 0],
[
0,
0,
-(far + near) / (far - near),
-(2 * far * near) / (far - near),
],
[0, 0, -1, 0],
],
dtype=np.float32,
)
def get_rays(pose, h, w, fovy, opengl=True, normalize_dir=True):
""" construct rays origin and direction from a camera pose.
Args:
pose (np.ndarray): camera pose, float [4, 4]
h (int): image height
w (int): image width
fovy (float): field of view in degree along y-axis.
opengl (bool, optional): whether to use the OpenGL camera convention. Defaults to True.
normalize_dir (bool, optional): whether to normalize the ray directions. Defaults to True.
Returns:
Tuple[np.ndarray]: rays_o and rays_d, both are float [h, w, 3]
"""
# pose: [4, 4]
# fov: in degree
# opengl: camera front view convention
x, y = np.meshgrid(np.arange(w), np.arange(h), indexing="xy")
x = x.reshape(-1)
y = y.reshape(-1)
cx = w * 0.5
cy = h * 0.5
# objaverse rendering has fixed focal of 560 at resolution 512 --> fov = 49.1 degree
focal = h * 0.5 / np.tan(0.5 * np.deg2rad(fovy))
camera_dirs = np.stack([
(x - cx + 0.5) / focal,
(y - cy + 0.5) / focal * (-1.0 if opengl else 1.0),
np.ones_like(x) * (-1.0 if opengl else 1.0),
], axis=-1) # [hw, 3]
rays_d = camera_dirs @ pose[:3, :3].transpose(0, 1) # [hw, 3]
rays_o = np.expand_dims(pose[:3, 3], 0).repeat(rays_d.shape[0], 0) # [hw, 3]
if normalize_dir:
rays_d = safe_normalize(rays_d)
rays_o = rays_o.reshape(h, w, 3)
rays_d = rays_d.reshape(h, w, 3)
return rays_o, rays_d
class OrbitCamera:
""" An orbital camera class.
"""
def __init__(self, W, H, r=2, fovy=60, near=0.01, far=100, proj_mode="perspective", view_volume_size=None):
"""init function
Args:
W (int): image width
H (int): image height
r (int, optional): camera radius. Defaults to 2.
fovy (int, optional): camera field of view in degree along y-axis. Defaults to 60.
near (float, optional): near clip plane. Defaults to 0.01.
far (int, optional): far clip plane. Defaults to 100.
"""
self.W = W
self.H = H
self.radius = r # camera distance from center
self.fovy = np.deg2rad(fovy) # deg 2 rad
self.near = near
self.far = far
self.center = np.array([0, 0, 0], dtype=np.float32) # look at this point
self.rot = Rotation.from_matrix(np.eye(3))
self.up = np.array([0, 1, 0], dtype=np.float32) # need to be normalized!
self.proj_mode = proj_mode
if self.proj_mode == "orthographic":
assert view_volume_size is not None
self.view_volume_size = view_volume_size
@property
def fovx(self):
"""get the field of view in radians along x-axis
Returns:
float: field of view in radians along x-axis
"""
return 2 * np.arctan(np.tan(self.fovy / 2) * self.W / self.H)
@property
def campos(self):
return self.pose[:3, 3]
# pose (c2w)
@property
def pose(self):
"""get the camera pose matrix (cam2world)
Returns:
np.ndarray: camera pose, float [4, 4]
"""
# first move camera to radius
res = np.eye(4, dtype=np.float32)
res[2, 3] = self.radius # opengl convention...
# rotate
rot = np.eye(4, dtype=np.float32)
rot[:3, :3] = self.rot.as_matrix()
res = rot @ res
# translate
res[:3, 3] -= self.center
return res
# view (w2c)
@property
def view(self):
"""get the camera view matrix (world2cam, inverse of cam2world)
Returns:
np.ndarray: camera view, float [4, 4]
"""
return np.linalg.inv(self.pose)
# projection (perspective)
@property
def perspective(self):
"""get the perspective matrix
Returns:
np.ndarray: camera perspective, float [4, 4]
"""
# Enable different modes for prospective projection and orthographic projection
if self.proj_mode == "perspective":
y = np.tan(self.fovy / 2)
aspect = self.W / self.H
return np.array(
[
[1 / (y * aspect), 0, 0, 0],
[0, -1 / y, 0, 0],
[
0,
0,
-(self.far + self.near) / (self.far - self.near),
-(2 * self.far * self.near) / (self.far - self.near),
],
[0, 0, -1, 0],
],
dtype=np.float32,
)
elif self.proj_mode == "orthographic":
t = self.view_volume_size / 2 # top boundary of the view volume
b = -t # bottom boundary of the view volume
r = t * self.W / self.H # right boundary of the view volume
l = -r # left boundary of the view volume
return np.array(
[
[2 / (r - l), 0, 0, -(r + l) / (r - l)],
[0, 2 / (t - b), 0, -(t + b) / (t - b)],
[0, 0, -2 / (self.far - self.near), -(self.far + self.near) / (self.far - self.near)],
[0, 0, 0, 1],
],
dtype=np.float32,
)
else:
raise ValueError(f"Unknown projection mode {self.proj_mode}!")
# intrinsics
@property
def intrinsics(self):
"""get the camera intrinsics
Returns:
np.ndarray: intrinsics (fx, fy, cx, cy), float [4]
"""
focal = self.H / (2 * np.tan(self.fovy / 2))
return np.array([focal, focal, self.W // 2, self.H // 2], dtype=np.float32)
@property
def mvp(self):
"""get the MVP (model-view-perspective) matrix.
Returns:
np.ndarray: camera MVP, float [4, 4]
"""
return self.perspective @ np.linalg.inv(self.pose) # [4, 4]
def orbit(self, dx, dy):
""" rotate along camera up/side axis!
Args:
dx (float): delta step along x (up).
dy (float): delta step along y (side).
"""
side = self.rot.as_matrix()[:3, 0]
rotvec_x = self.up * np.radians(-0.05 * dx)
rotvec_y = side * np.radians(-0.05 * dy)
self.rot = Rotation.from_rotvec(rotvec_x) * Rotation.from_rotvec(rotvec_y) * self.rot
def scale(self, delta):
"""scale the camera.
Args:
delta (float): delta step.
"""
self.radius *= 1.1 ** (-delta)
def pan(self, dx, dy, dz=0):
"""pan the camera.
Args:
dx (float): delta step along x.
dy (float): delta step along y.
dz (float, optional): delta step along x. Defaults to 0.
"""
# pan in camera coordinate system (careful on the sensitivity!)
self.center += 0.0005 * self.rot.as_matrix()[:3, :3] @ np.array([dx, -dy, dz])
def from_angle(self, elevation, azimuth, is_degree=True):
"""set the camera pose from elevation & azimuth angle.
Args:
elevation (float): elevation in (-90, 90), from +y to -y is (-90, 90)
azimuth (float): azimuth in (-180, 180), from +z to +x is (0, 90)
is_degree (bool, optional): whether the angles are in degree. Defaults to True.
"""
if is_degree:
elevation = np.deg2rad(elevation)
azimuth = np.deg2rad(azimuth)
x = self.radius * np.cos(elevation) * np.sin(azimuth)
y = - self.radius * np.sin(elevation)
z = self.radius * np.cos(elevation) * np.cos(azimuth)
campos = np.array([x, y, z]) # [N, 3]
rot_mat = look_at(campos, np.zeros([3], dtype=np.float32))
self.rot = Rotation.from_matrix(rot_mat)