-
Notifications
You must be signed in to change notification settings - Fork 134
/
Copy pathrender.py
417 lines (342 loc) · 17.6 KB
/
render.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
from mesh import Mesh
import kaolin as kal
from utils import get_camera_from_view2
import matplotlib.pyplot as plt
from utils import device
import torch
import numpy as np
class Renderer():
def __init__(self, mesh='sample.obj',
lights=torch.tensor([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
camera=kal.render.camera.generate_perspective_projection(np.pi / 3).to(device),
dim=(224, 224)):
if camera is None:
camera = kal.render.camera.generate_perspective_projection(np.pi / 3).to(device)
self.lights = lights.unsqueeze(0).to(device)
self.camera_projection = camera
self.dim = dim
def render_y_views(self, mesh, num_views=8, show=False, lighting=True, background=None, mask=False):
faces = mesh.faces
n_faces = faces.shape[0]
azim = torch.linspace(0, 2 * np.pi, num_views + 1)[:-1] # since 0 =360 dont include last element
# elev = torch.cat((torch.linspace(0, np.pi/2, int((num_views+1)/2)), torch.linspace(0, -np.pi/2, int((num_views)/2))))
elev = torch.zeros(len(azim))
images = []
masks = []
rgb_mask = []
if background is not None:
face_attributes = [
mesh.face_attributes,
torch.ones((1, n_faces, 3, 1), device=device)
]
else:
face_attributes = mesh.face_attributes
for i in range(num_views):
camera_transform = get_camera_from_view2(elev[i], azim[i], r=2).to(device)
face_vertices_camera, face_vertices_image, face_normals = kal.render.mesh.prepare_vertices(
mesh.vertices.to(device), mesh.faces.to(device), self.camera_projection,
camera_transform=camera_transform)
image_features, soft_mask, face_idx = kal.render.mesh.dibr_rasterization(
self.dim[1], self.dim[0], face_vertices_camera[:, :, :, -1],
face_vertices_image, face_attributes, face_normals[:, :, -1])
masks.append(soft_mask)
if background is not None:
image_features, mask = image_features
image = torch.clamp(image_features, 0.0, 1.0)
if lighting:
image_normals = face_normals[:, face_idx].squeeze(0)
image_lighting = kal.render.mesh.spherical_harmonic_lighting(image_normals, self.lights).unsqueeze(0)
image = image * image_lighting.repeat(1, 3, 1, 1).permute(0, 2, 3, 1).to(device)
image = torch.clamp(image, 0.0, 1.0)
if background is not None:
background_mask = torch.zeros(image.shape).to(device)
mask = mask.squeeze(-1)
assert torch.all(image[torch.where(mask == 0)] == torch.zeros(3).to(device))
background_mask[torch.where(mask == 0)] = background
image = torch.clamp(image + background_mask, 0., 1.)
images.append(image)
images = torch.cat(images, dim=0).permute(0, 3, 1, 2)
masks = torch.cat(masks, dim=0)
if show:
with torch.no_grad():
fig, axs = plt.subplots(1 + (num_views - 1) // 4, min(4, num_views), figsize=(89.6, 22.4))
for i in range(num_views):
if num_views == 1:
ax = axs
elif num_views <= 4:
ax = axs[i]
else:
ax = axs[i // 4, i % 4]
# ax.imshow(images[i].permute(1,2,0).cpu().numpy())
# ax.imshow(rgb_mask[i].cpu().numpy())
plt.show()
return images
def render_single_view(self, mesh, elev=0, azim=0, show=False, lighting=True, background=None, radius=2,
return_mask=False):
# if mesh is None:
# mesh = self._current_mesh
verts = mesh.vertices
faces = mesh.faces
n_faces = faces.shape[0]
if background is not None:
face_attributes = [
mesh.face_attributes,
torch.ones((1, n_faces, 3, 1), device=device)
]
else:
face_attributes = mesh.face_attributes
camera_transform = get_camera_from_view2(torch.tensor(elev), torch.tensor(azim), r=radius).to(device)
face_vertices_camera, face_vertices_image, face_normals = kal.render.mesh.prepare_vertices(
mesh.vertices.to(device), mesh.faces.to(device), self.camera_projection, camera_transform=camera_transform)
image_features, soft_mask, face_idx = kal.render.mesh.dibr_rasterization(
self.dim[1], self.dim[0], face_vertices_camera[:, :, :, -1],
face_vertices_image, face_attributes, face_normals[:, :, -1])
# Debugging: color where soft mask is 1
# tmp_rgb = torch.ones((224,224,3))
# tmp_rgb[torch.where(soft_mask.squeeze() == 1)] = torch.tensor([1,0,0]).float()
# rgb_mask.append(tmp_rgb)
if background is not None:
image_features, mask = image_features
image = torch.clamp(image_features, 0.0, 1.0)
if lighting:
image_normals = face_normals[:, face_idx].squeeze(0)
image_lighting = kal.render.mesh.spherical_harmonic_lighting(image_normals, self.lights).unsqueeze(0)
image = image * image_lighting.repeat(1, 3, 1, 1).permute(0, 2, 3, 1).to(device)
image = torch.clamp(image, 0.0, 1.0)
if background is not None:
background_mask = torch.zeros(image.shape).to(device)
mask = mask.squeeze(-1)
assert torch.all(image[torch.where(mask == 0)] == torch.zeros(3).to(device))
background_mask[torch.where(mask == 0)] = background
image = torch.clamp(image + background_mask, 0., 1.)
if show:
with torch.no_grad():
fig, axs = plt.subplots(figsize=(89.6, 22.4))
axs.imshow(image[0].cpu().numpy())
# ax.imshow(rgb_mask[i].cpu().numpy())
plt.show()
if return_mask == True:
return image.permute(0, 3, 1, 2), mask
return image.permute(0, 3, 1, 2)
def render_uniform_views(self, mesh, num_views=8, show=False, lighting=True, background=None, mask=False,
center=[0, 0], radius=2.0):
# if mesh is None:
# mesh = self._current_mesh
verts = mesh.vertices
faces = mesh.faces
n_faces = faces.shape[0]
azim = torch.linspace(center[0], 2 * np.pi + center[0], num_views + 1)[
:-1] # since 0 =360 dont include last element
elev = torch.cat((torch.linspace(center[1], np.pi / 2 + center[1], int((num_views + 1) / 2)),
torch.linspace(center[1], -np.pi / 2 + center[1], int((num_views) / 2))))
images = []
masks = []
background_masks = []
if background is not None:
face_attributes = [
mesh.face_attributes,
torch.ones((1, n_faces, 3, 1), device=device)
]
else:
face_attributes = mesh.face_attributes
for i in range(num_views):
camera_transform = get_camera_from_view2(elev[i], azim[i], r=radius).to(device)
face_vertices_camera, face_vertices_image, face_normals = kal.render.mesh.prepare_vertices(
mesh.vertices.to(device), mesh.faces.to(device), self.camera_projection,
camera_transform=camera_transform)
image_features, soft_mask, face_idx = kal.render.mesh.dibr_rasterization(
self.dim[1], self.dim[0], face_vertices_camera[:, :, :, -1],
face_vertices_image, face_attributes, face_normals[:, :, -1])
masks.append(soft_mask)
# Debugging: color where soft mask is 1
# tmp_rgb = torch.ones((224,224,3))
# tmp_rgb[torch.where(soft_mask.squeeze() == 1)] = torch.tensor([1,0,0]).float()
# rgb_mask.append(tmp_rgb)
if background is not None:
image_features, mask = image_features
image = torch.clamp(image_features, 0.0, 1.0)
if lighting:
image_normals = face_normals[:, face_idx].squeeze(0)
image_lighting = kal.render.mesh.spherical_harmonic_lighting(image_normals, self.lights).unsqueeze(0)
image = image * image_lighting.repeat(1, 3, 1, 1).permute(0, 2, 3, 1).to(device)
image = torch.clamp(image, 0.0, 1.0)
if background is not None:
background_mask = torch.zeros(image.shape).to(device)
mask = mask.squeeze(-1)
assert torch.all(image[torch.where(mask == 0)] == torch.zeros(3).to(device))
background_mask[torch.where(mask == 0)] = background
background_masks.append(background_mask)
image = torch.clamp(image + background_mask, 0., 1.)
images.append(image)
images = torch.cat(images, dim=0).permute(0, 3, 1, 2)
masks = torch.cat(masks, dim=0)
if background is not None:
background_masks = torch.cat(background_masks, dim=0).permute(0, 3, 1, 2)
if show:
with torch.no_grad():
fig, axs = plt.subplots(1 + (num_views - 1) // 4, min(4, num_views), figsize=(89.6, 22.4))
for i in range(num_views):
if num_views == 1:
ax = axs
elif num_views <= 4:
ax = axs[i]
else:
ax = axs[i // 4, i % 4]
# ax.imshow(background_masks[i].permute(1,2,0).cpu().numpy())
ax.imshow(images[i].permute(1, 2, 0).cpu().numpy())
# ax.imshow(rgb_mask[i].cpu().numpy())
plt.show()
return images
def render_front_views(self, mesh, num_views=8, std=8, center_elev=0, center_azim=0, show=False, lighting=True,
background=None, mask=False, return_views=False):
# Front view with small perturbations in viewing angle
verts = mesh.vertices
faces = mesh.faces
n_faces = faces.shape[0]
elev = torch.cat((torch.tensor([center_elev]), torch.randn(num_views - 1) * np.pi / std + center_elev))
azim = torch.cat((torch.tensor([center_azim]), torch.randn(num_views - 1) * 2 * np.pi / std + center_azim))
images = []
masks = []
rgb_mask = []
if background is not None:
face_attributes = [
mesh.face_attributes,
torch.ones((1, n_faces, 3, 1), device=device)
]
else:
face_attributes = mesh.face_attributes
for i in range(num_views):
camera_transform = get_camera_from_view2(elev[i], azim[i], r=2).to(device)
face_vertices_camera, face_vertices_image, face_normals = kal.render.mesh.prepare_vertices(
mesh.vertices.to(device), mesh.faces.to(device), self.camera_projection,
camera_transform=camera_transform)
image_features, soft_mask, face_idx = kal.render.mesh.dibr_rasterization(
self.dim[1], self.dim[0], face_vertices_camera[:, :, :, -1],
face_vertices_image, face_attributes, face_normals[:, :, -1])
masks.append(soft_mask)
# Debugging: color where soft mask is 1
# tmp_rgb = torch.ones((224, 224, 3))
# tmp_rgb[torch.where(soft_mask.squeeze() == 1)] = torch.tensor([1, 0, 0]).float()
# rgb_mask.append(tmp_rgb)
if background is not None:
image_features, mask = image_features
image = torch.clamp(image_features, 0.0, 1.0)
if lighting:
image_normals = face_normals[:, face_idx].squeeze(0)
image_lighting = kal.render.mesh.spherical_harmonic_lighting(image_normals, self.lights).unsqueeze(0)
image = image * image_lighting.repeat(1, 3, 1, 1).permute(0, 2, 3, 1).to(device)
image = torch.clamp(image, 0.0, 1.0)
if background is not None:
background_mask = torch.zeros(image.shape).to(device)
mask = mask.squeeze(-1)
assert torch.all(image[torch.where(mask == 0)] == torch.zeros(3).to(device))
background_mask[torch.where(mask == 0)] = background
image = torch.clamp(image + background_mask, 0., 1.)
images.append(image)
images = torch.cat(images, dim=0).permute(0, 3, 1, 2)
masks = torch.cat(masks, dim=0)
# rgb_mask = torch.cat(rgb_mask, dim=0)
if show:
with torch.no_grad():
fig, axs = plt.subplots(1 + (num_views - 1) // 4, min(4, num_views), figsize=(89.6, 22.4))
for i in range(num_views):
if num_views == 1:
ax = axs
elif num_views <= 4:
ax = axs[i]
else:
ax = axs[i // 4, i % 4]
ax.imshow(images[i].permute(1, 2, 0).cpu().numpy())
plt.show()
if return_views == True:
return images, elev, azim
else:
return images
def render_prompt_views(self, mesh, prompt_views, center=[0, 0], background=None, show=False, lighting=True,
mask=False):
# if mesh is None:
# mesh = self._current_mesh
verts = mesh.vertices
faces = mesh.faces
n_faces = faces.shape[0]
num_views = len(prompt_views)
images = []
masks = []
rgb_mask = []
face_attributes = mesh.face_attributes
for i in range(num_views):
view = prompt_views[i]
if view == "front":
elev = 0 + center[1]
azim = 0 + center[0]
if view == "right":
elev = 0 + center[1]
azim = np.pi / 2 + center[0]
if view == "back":
elev = 0 + center[1]
azim = np.pi + center[0]
if view == "left":
elev = 0 + center[1]
azim = 3 * np.pi / 2 + center[0]
if view == "top":
elev = np.pi / 2 + center[1]
azim = 0 + center[0]
if view == "bottom":
elev = -np.pi / 2 + center[1]
azim = 0 + center[0]
if background is not None:
face_attributes = [
mesh.face_attributes,
torch.ones((1, n_faces, 3, 1), device=device)
]
else:
face_attributes = mesh.face_attributes
camera_transform = get_camera_from_view2(torch.tensor(elev), torch.tensor(azim), r=2).to(device)
face_vertices_camera, face_vertices_image, face_normals = kal.render.mesh.prepare_vertices(
mesh.vertices.to(device), mesh.faces.to(device), self.camera_projection,
camera_transform=camera_transform)
image_features, soft_mask, face_idx = kal.render.mesh.dibr_rasterization(
self.dim[1], self.dim[0], face_vertices_camera[:, :, :, -1],
face_vertices_image, face_attributes, face_normals[:, :, -1])
masks.append(soft_mask)
if background is not None:
image_features, mask = image_features
image = torch.clamp(image_features, 0.0, 1.0)
if lighting:
image_normals = face_normals[:, face_idx].squeeze(0)
image_lighting = kal.render.mesh.spherical_harmonic_lighting(image_normals, self.lights).unsqueeze(0)
image = image * image_lighting.repeat(1, 3, 1, 1).permute(0, 2, 3, 1).to(device)
image = torch.clamp(image, 0.0, 1.0)
if background is not None:
background_mask = torch.zeros(image.shape).to(device)
mask = mask.squeeze(-1)
assert torch.all(image[torch.where(mask == 0)] == torch.zeros(3).to(device))
background_mask[torch.where(mask == 0)] = background
image = torch.clamp(image + background_mask, 0., 1.)
images.append(image)
images = torch.cat(images, dim=0).permute(0, 3, 1, 2)
masks = torch.cat(masks, dim=0)
if show:
with torch.no_grad():
fig, axs = plt.subplots(1 + (num_views - 1) // 4, min(4, num_views), figsize=(89.6, 22.4))
for i in range(num_views):
if num_views == 1:
ax = axs
elif num_views <= 4:
ax = axs[i]
else:
ax = axs[i // 4, i % 4]
ax.imshow(images[i].permute(1, 2, 0).cpu().numpy())
# ax.imshow(rgb_mask[i].cpu().numpy())
plt.show()
if not mask:
return images
else:
return images, masks
if __name__ == '__main__':
mesh = Mesh('sample.obj')
mesh.set_image_texture('sample_texture.png')
renderer = Renderer()
# renderer.render_uniform_views(mesh,show=True,texture=True)
mesh = mesh.divide()
renderer.render_uniform_views(mesh, show=True, texture=True)