-
Notifications
You must be signed in to change notification settings - Fork 1
/
viewer.py
260 lines (216 loc) · 8.2 KB
/
viewer.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
# Basic OpenCV viewer with sliders for rotation and translation.
# Can be easily customizable to different use cases.
import torch
from gsplat import rasterization
import cv2
import tyro
import numpy as np
import json
from typing import Literal
import pycolmap_scene_manager as pycolmap
device = torch.device("cuda:0")
def get_rpy_matrix(roll, pitch, yaw):
roll_matrix = np.array(
[
[1, 0, 0, 0],
[0, np.cos(roll), -np.sin(roll), 0],
[0, np.sin(roll), np.cos(roll), 0],
[0, 0, 0, 1.0],
])
pitch_matrix = np.array(
[
[np.cos(pitch), 0, np.sin(pitch), 0],
[0, 1, 0, 0],
[-np.sin(pitch), 0, np.cos(pitch), 0],
[0, 0, 0, 1.0],
])
yaw_matrix = np.array(
[
[np.cos(yaw), -np.sin(yaw), 0, 0],
[np.sin(yaw), np.cos(yaw), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1.0],
]
)
return yaw_matrix @ pitch_matrix @ roll_matrix
def _detach_tensors_from_dict(d, inplace=True):
if not inplace:
d = d.copy()
for key in d:
if isinstance(d[key], torch.Tensor):
d[key] = d[key].detach()
return d
def load_checkpoint(checkpoint: str, data_dir: str, rasterizer: Literal["original", "gsplat"]="original", data_factor: int = 1):
colmap_project = pycolmap.SceneManager(f"{data_dir}/sparse/0")
colmap_project.load_cameras()
colmap_project.load_images()
colmap_project.load_points3D()
model = torch.load(checkpoint) # Make sure it is generated by 3DGS original repo
if rasterizer == "original":
model_params, _ = model
splats = {
"active_sh_degree": model_params[0],
"means": model_params[1],
"features_dc": model_params[2],
"features_rest": model_params[3],
"scaling": model_params[4],
"rotation": model_params[5],
"opacity": model_params[6].squeeze(1),
}
elif rasterizer == "gsplat":
model_params = model["splats"]
splats = {
"active_sh_degree": 3,
"means": model_params["means"],
"features_dc": model_params["sh0"],
"features_rest": model_params["shN"],
"scaling": model_params["scales"],
"rotation": model_params["quats"],
"opacity": model_params["opacities"],
}
else:
raise ValueError("Invalid rasterizer")
_detach_tensors_from_dict(splats)
# Assuming only one camera
for camera in colmap_project.cameras.values():
camera_matrix = torch.tensor(
[
[camera.fx, 0, camera.cx],
[0, camera.fy, camera.cy],
[0, 0, 1],
]
)
break
camera_matrix[:2,:3] /= data_factor
splats["camera_matrix"] = camera_matrix
splats["colmap_project"] = colmap_project
splats["colmap_dir"] = data_dir
return splats
def create_checkerboard(width, height, size=64):
checkerboard = np.zeros((height, width, 3), dtype=np.uint8)
for y in range(0, height, size):
for x in range(0, width, size):
if (x // size + y // size) % 2 == 0:
checkerboard[y:y + size, x:x + size] = 255
else:
checkerboard[y:y + size, x:x + size] = 128
return checkerboard
def main(data_dir: str = "./data/chair", # colmap path
checkpoint: str = "./data/chair/checkpoint.pth", # checkpoint path, can generate from original 3DGS repo
rasterizer: Literal["original", "gsplat"] = "original", # Original or GSplat for checkpoints
mask_path: str = "./results/chair/mask3d.pth",
apply_mask: bool = True,
invert: bool = False,
use_checkerboard_backgrounder: bool = True,
data_factor: int = 1):
torch.set_default_device("cuda")
torch.set_grad_enabled(False)
splats = load_checkpoint(checkpoint, data_dir, rasterizer=rasterizer, data_factor=data_factor)
show_anaglyph = False
means = splats["means"].float()
opacities = splats["opacity"]
quats = splats["rotation"]
scales = splats["scaling"].float()
opacities = torch.sigmoid(opacities)
scales = torch.exp(scales)
colors = torch.cat([splats["features_dc"], splats["features_rest"]], 1)
if apply_mask:
mask = torch.load(mask_path)
if invert:
mask = ~mask
means = means[mask]
opacities = opacities[mask]
quats = quats[mask]
scales = scales[mask]
colors = colors[mask]
cv2.namedWindow("Viewer", cv2.WINDOW_NORMAL)
cv2.createTrackbar("Roll", "Viewer", 0, 180, lambda x: None)
cv2.createTrackbar("Pitch", "Viewer", 0, 180, lambda x: None)
cv2.createTrackbar("Yaw", "Viewer", 0, 180, lambda x: None)
cv2.createTrackbar("X", "Viewer", 0, 1000, lambda x: None)
cv2.createTrackbar("Y", "Viewer", 0, 1000, lambda x: None)
cv2.createTrackbar("Z", "Viewer", 0, 1000, lambda x: None)
cv2.createTrackbar("Scaling", "Viewer", 100, 100, lambda x: None)
cv2.setTrackbarMin("Roll", "Viewer", -180)
cv2.setTrackbarMax("Roll", "Viewer", 180)
cv2.setTrackbarMin("Pitch", "Viewer", -180)
cv2.setTrackbarMax("Pitch", "Viewer", 180)
cv2.setTrackbarMin("Yaw", "Viewer", -180)
cv2.setTrackbarMax("Yaw", "Viewer", 180)
cv2.setTrackbarMin("X", "Viewer", -1000)
cv2.setTrackbarMax("X", "Viewer", 1000)
cv2.setTrackbarMin("Y", "Viewer", -1000)
cv2.setTrackbarMax("Y", "Viewer", 1000)
cv2.setTrackbarMin("Z", "Viewer", -1000)
cv2.setTrackbarMax("Z", "Viewer", 1000)
K = splats["camera_matrix"].float()
width = int(K[0, 2] * 2)
height = int(K[1, 2] * 2)
while True:
roll = cv2.getTrackbarPos("Roll", "Viewer")
pitch = cv2.getTrackbarPos("Pitch", "Viewer")
yaw = cv2.getTrackbarPos("Yaw", "Viewer")
roll_rad = np.deg2rad(roll)
pitch_rad = np.deg2rad(pitch)
yaw_rad = np.deg2rad(yaw)
viewmat = (
torch.tensor(get_rpy_matrix(roll_rad, pitch_rad, yaw_rad))
.float()
.to(device)
)
viewmat[0, 3] = cv2.getTrackbarPos("X", "Viewer") / 100.0
viewmat[1, 3] = cv2.getTrackbarPos("Y", "Viewer") / 100.0
viewmat[2, 3] = cv2.getTrackbarPos("Z", "Viewer") / 100.0
output, alphas, meta = rasterization(
means,
quats,
scales * cv2.getTrackbarPos("Scaling", "Viewer") / 100.0,
opacities,
colors,
viewmat[None],
K[None],
width=width,
height=height,
sh_degree=3,
)
output_cv = torch_to_cv(output[0])
if use_checkerboard_backgrounder:
alphas = alphas[0].cpu().numpy()
output_cv = output_cv.astype(float) * alphas + create_checkerboard(width, height).astype(float) * (1 - alphas)
output_cv = np.clip(output_cv, 0, 255).astype(np.uint8)
if show_anaglyph:
left = output_cv.copy()
left[..., :2] = 0
viewmat[:, 3] -= 0.1
output, _, _ = rasterization(
means,
quats,
scales * cv2.getTrackbarPos("Scaling", "Viewer") / 100.0,
opacities,
colors,
viewmat[None],
K[None],
width=width,
height=height,
sh_degree=3,
)
right = torch_to_cv(output[0])
if use_checkerboard_backgrounder:
right = right.astype(float) * alphas + create_checkerboard(width, height).astype(float) * (1 - alphas)
right = np.clip(right, 0, 255).astype(np.uint8)
right[..., -1] = 0
output_cv = left + right
cv2.imshow("Viewer", output_cv)
key = cv2.waitKey(1)
if key == ord("q"):
break
elif key == ord("3"):
show_anaglyph = not show_anaglyph
def torch_to_cv(tensor, permute=False):
if permute:
tensor = torch.clamp(tensor.permute(1, 2, 0), 0, 1).cpu().numpy()
else:
tensor = torch.clamp(tensor, 0, 1).cpu().numpy()
return (tensor * 255).astype(np.uint8)[..., ::-1]
if __name__ == "__main__":
tyro.cli(main)