-
Notifications
You must be signed in to change notification settings - Fork 9
/
run_rotate.py
326 lines (273 loc) · 13 KB
/
run_rotate.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
"""
Open3D-based script to tinker with model predictions interactively.
"""
import argparse
import collections
from pathlib import Path
import cv2
import torch
from open3d import * # watch out, this also contains `Image`
from PIL import Image
from torchvision.transforms import Normalize
from torchvision.transforms import ToTensor
from datasets.dataset_texture import TextureDatasetWithNormal
from datasets.dataset_texture import get_planes
from datasets.dataset_texture import warp_unwarp_planes
from datasets.interop import pascal_idx_to_kpoint
from datasets.interop import pascal_parts_colors
from model.von import G_Resnet
from utils.geometry import intrinsic_matrix
from utils.geometry import pascal_vpoint_to_extrinsics
from utils.geometry import project_points
from utils.normalization import to_image
from utils.open3d import color_mesh_from_obj
def align_view(vis: VisualizerWithKeyCallback,
focal: int, extrinsic: np.ndarray):
""" Implement look-at to the origin """
pinhole_params = vis.get_view_control().convert_to_pinhole_camera_parameters()
# Get view controller intrinsics
intrinsic = pinhole_params.intrinsic
w, h = intrinsic.width, intrinsic.height
cx, cy = intrinsic.get_principal_point()
intrinsic.set_intrinsics(w, h, focal, focal, cx, cy)
# Use current camera extrinsics to update view
pinhole_params.extrinsic = np.concatenate([extrinsic, np.asarray([[0, 0, 0, 1]])])
vis.get_view_control().convert_from_pinhole_camera_parameters(pinhole_params)
vis.update_geometry()
class Geometries(dict):
def __init__(self):
super(Geometries, self).__init__()
def as_list(self):
l = []
for v in self.values():
if isinstance(v, collections.Iterable):
l.extend(v)
else:
l.append(v)
return l
class Callbacks(object):
def __init__(self, key: int):
self.key = key
def __call__(self, vis):
global state
global kpoints_3d
global normal_vertex_colors
global part_vertex_colors
global texture_src
# Do nothing
if self.key == 0:
pass
# Dump current output window
elif self.key == ord('X'):
args.dump_dir.mkdir(exist_ok=True)
el = int(state['angle_y'])
az = int(state['angle_z'])
rad = int(state['radius'])
d_id = state['dump_id']
id_str = f'{d_id:03d}_el_{el:03d}_az_{az:03d}_rad_{rad:03d}'
cv2.imwrite(str(args.dump_dir / f'{id_str}.png'),
state['dump_image'])
state['dump_id'] += 1
# Reset all values
elif self.key == ord('R'):
state['angle_y'] = 0.
state['angle_z'] = 0.
state['radius'] = 0.
# Rotation around Y axis
elif self.key == ord('F'):
state['angle_y'] += 5
elif self.key == ord('D'):
state['angle_y'] -= 5
# Rotation around Z axis
elif self.key == ord('S'):
state['angle_z'] += 5
elif self.key == ord('A'):
state['angle_z'] -= 5
# Distance from origin (+)
elif self.key == ord('H'):
state['radius'] += 0.05
# Distance from origin (-)
elif self.key == ord('G'):
state['radius'] -= 0.05
# Next dataset example
elif self.key == ord(' '):
texture_src = state['dataset'][state['dataset_index']]
state['dataset_index'] += 1
# Next CAD model
elif self.key == ord('N'):
state['cad_idx'] += 1
if state['cad_idx'] == 10:
state['cad_idx'] = 0
# --------------- Update model and Kpoints 3D ----------------------
cad_idx = state['cad_idx']
model_path = args.CAD_root / f'pascal_car_cad_{cad_idx:03d}.ply'
kpoints_3d = state['car_cad_kpoints_3D'][cad_idx].astype(np.float32)
car_mesh = read_triangle_mesh(str(model_path))
# ------------------- Compute normal Colors ----------------------
car_mesh.compute_vertex_normals()
normal_vertex_colors = (np.asarray(car_mesh.vertex_normals) + 1) / 2.
# -------------------- Compute Parts Colors ------------------------
color_dict = pascal_parts_colors['car']
obj_path = model_path.parent / (model_path.stem + '.obj')
color_mesh_from_obj(car_mesh, obj_name=obj_path, mtl_to_color=color_dict,
base_color=color_dict['car'])
part_vertex_colors = np.asarray(car_mesh.vertex_colors).copy()
# Reset colors to normals
car_mesh.vertex_colors = Vector3dVector(normal_vertex_colors)
if 'car_mesh' not in state['geometries']:
state['geometries']['car_mesh'] = car_mesh
else:
state['geometries']['car_mesh'].vertices = car_mesh.vertices
state['geometries']['car_mesh'].vertex_colors = car_mesh.vertex_colors
state['geometries']['car_mesh'].vertex_normals = car_mesh.vertex_normals
state['geometries']['car_mesh'].triangles = car_mesh.triangles
else:
raise NotImplementedError()
# -------------------------- Move Camera ------------------------------
angle_y = np.clip(state['angle_y'], -90, 90)
radius = np.clip(state['radius'], 0, state['radius'])
pascal_az = (state['angle_z'] + 90) % 360
intrinsic = intrinsic_matrix(state['focal'], cx=img_w/2, cy=img_h/2)
print(f'Azimuth:{pascal_az} Elevation:{angle_y} Radius:{radius}')
extrinsic = pascal_vpoint_to_extrinsics(az_deg=pascal_az,
el_deg=90 - angle_y,
radius=radius)
# ---------------------- Start Rendering ------------------------------
if not vis.get_render_option() or not vis.get_view_control():
vis.update_geometry() # we don't have anything, return
return
align_view(vis, focal=state['focal'], extrinsic=extrinsic)
vis.get_render_option().mesh_color_option = MeshColorOption.Color
vis.get_render_option().light_on = False
vis.get_render_option().background_color = (0, 0, 0)
# ---------------------- Normal ---------------------------------------
src_shaded = np.asarray(vis.capture_screen_float_buffer(do_render=True))
src_shaded = (src_shaded * 255).astype(np.uint8)
if args.LAB:
src_shaded = cv2.cvtColor(src_shaded, cv2.COLOR_RGB2LAB)
else:
src_shaded = cv2.cvtColor(src_shaded, cv2.COLOR_RGB2BGR)
# ---------------------- Parts ----------------------------------------
state['geometries']['car_mesh'].vertex_colors = Vector3dVector(part_vertex_colors)
vis.update_geometry()
src_parts = np.asarray(vis.capture_screen_float_buffer(do_render=True))
src_parts = (src_parts * 255).astype(np.uint8)
if args.LAB:
src_parts = cv2.cvtColor(src_parts, cv2.COLOR_RGB2LAB)
else:
src_parts = cv2.cvtColor(src_parts, cv2.COLOR_RGB2BGR)
state['geometries']['car_mesh'].vertex_colors = Vector3dVector(normal_vertex_colors)
vis.update_geometry()
# Project model kpoints in 2D
kpoints_2d_step = project_points(kpoints_3d, intrinsic, extrinsic)
kpoints_2d_step /= (img_w, img_h)
kpoints_2d_step = np.clip(kpoints_2d_step, -1, 1)
kpoints_2d_step_dict = {pascal_idx_to_kpoint['car'][i]: kpoints_2d_step[i]
for i in range(kpoints_2d_step.shape[0])}
meta = {'kpoints_2d': kpoints_2d_step_dict,
'vpoint': [pascal_az]}
_, dst_kpoints_planes, dst_visibilities = get_planes(np.zeros((img_h, img_w, 3)),
meta=meta, pascal_class='car')
src_planes = np.asarray([to_image(i, from_LAB=args.LAB) for i in texture_src['planes']])
src_kpoints_planes = texture_src['src_kpoints_planes']
src_visibilities = texture_src['src_vs']
planes_warped, planes_unwarped = warp_unwarp_planes(src_planes=src_planes,
src_planes_kpoints=src_kpoints_planes,
dst_planes_kpoints=dst_kpoints_planes,
src_visibilities=src_visibilities,
dst_visibilities=dst_visibilities,
pascal_class='car')
planes_warped = TextureDatasetWithNormal.planes_to_torch(planes_warped, to_LAB=args.LAB)
planes_warped = planes_warped.reshape(1, planes_warped.shape[0] * planes_warped.shape[1],
planes_warped.shape[2], planes_warped.shape[3])
src_shaded_input = Normalize(mean=[0.5]*3, std=[0.5]*3)(ToTensor()((Image.fromarray(src_shaded))))
src_parts_input = Normalize(mean=[0.5]*3, std=[0.5]*3)(ToTensor()((Image.fromarray(src_parts))))
src_central = texture_src['src_central']
gen_in_src = torch.cat([src_shaded_input.unsqueeze(0), src_parts_input.unsqueeze(0),
src_central.unsqueeze(0), planes_warped], dim=1)
net_image = to_image(state['net'](gen_in_src.to(args.device))[0], from_LAB=args.LAB)
out_image = np.concatenate([to_image(src_shaded_input, from_LAB=args.LAB),
to_image(src_parts_input, from_LAB=args.LAB),
to_image(src_central, from_LAB=args.LAB),
net_image, to_image(texture_src['src_image'],
from_LAB=args.LAB)], axis=1)
state['dump_image'] = out_image
cv2.imshow('Output', out_image)
cv2.waitKey(20)
vis.update_geometry()
def run(args: argparse.Namespace):
global state
# Initialize state
state = {
'angle_y': 90.,
'angle_z': 0.,
'cad_idx': 0,
'car_cad_kpoints_3D': np.load(args.CAD_root / 'cad_car.npz')['kpoints'],
'dataset_index': 0,
'dump_id': 0,
'focal': 1000,
'geometries': Geometries(),
'radius': 7
}
# Load pre-trained model
net = G_Resnet(input_nc=24).to(args.device)
net.load_state_dict(torch.load(args.model_path))
net.eval()
state['net'] = net
# Load test dataset
dataset = TextureDatasetWithNormal(folder=args.texture_dataset_dir,
resize_factor=0.5,
demo_mode=args.demo,
use_LAB=args.LAB)
dataset.eval()
state['dataset'] = dataset
key_callbacks = {
ord('F'): Callbacks(ord('F')),
ord('D'): Callbacks(ord('D')),
ord('A'): Callbacks(ord('A')),
ord('S'): Callbacks(ord('S')),
ord('H'): Callbacks(ord('H')),
ord('G'): Callbacks(ord('G')),
ord('R'): Callbacks(ord('R')),
ord(' '): Callbacks(ord(' ')),
ord('N'): Callbacks(ord('N')),
ord('O'): Callbacks(ord('O')),
ord('P'): Callbacks(ord('P')),
ord('X'): Callbacks(ord('X')),
}
# Init callbacks
Callbacks(ord('N'))(Visualizer()) # init model
Callbacks(ord(' '))(Visualizer()) # init appearance
Callbacks(0)(Visualizer())
draw_geometries_with_key_callbacks(state['geometries'].as_list(),
key_callbacks,
width=img_w, height=img_h,
left=50, top=1080//4)
cv2.namedWindow('Projection')
if __name__ == '__main__':
img_h = img_w = 128
parser = argparse.ArgumentParser()
parser.add_argument('texture_dataset_dir', type=Path,
help='Texture dataset directory')
parser.add_argument('model_path', type=Path,
help='Path to pre-trained model')
parser.add_argument('CAD_root', type=Path,
help='Directory containing 3D CAD')
parser.add_argument('--dump_dir', type=Path, default=Path('/tmp'),
help='Directory to save output')
parser.add_argument('--device', choices=['cpu', 'cuda'], default='cuda',
help='Device used for model inference')
parser.add_argument('--demo', action='store_true',
help='Load a subset of dataset - faster to load.')
args = parser.parse_args()
args.LAB = True # Expected arg for released model
# Load only the first 100 examples - faster to load. Keep to False to
# iterate over the whole test set.
args.demo = True
# Sanity-checks
if not args.model_path.is_file():
raise OSError('Please provide a valid file for pretrained weights.')
if not args.CAD_root.is_dir():
raise OSError('Please provide a valid CAD root.')
# Start the GUI
run(args)