-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
1848 lines (1546 loc) · 85.5 KB
/
main.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import random
import time
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
from neural_scene_graph_helper import *
from data_loader.load_vkitti import load_vkitti_data
from data_loader.load_kitti import load_kitti_data, plot_kitti_poses, tracking2txt
from prepare_input_helper import *
from neural_scene_graph_manipulation import *
import numpy as np
# import tensorflow as tf
import matplotlib.pyplot as plt
import imageio
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def scatter_nd(indices: torch.Tensor, updates: torch.Tensor,
shape: torch.Tensor) -> torch.Tensor:
ret = torch.zeros(*shape, dtype=updates.dtype).to(device)
ndim = indices.shape[-1]
output_shape = list(indices.shape[:-1]) + shape[indices.shape[-1]:]
flatted_indices = indices.view(-1, ndim)
slices = [flatted_indices[:, i] for i in range(ndim)]
slices += [Ellipsis]
ret[slices] = updates.view(*output_shape)
return ret
def scatter_nd_my(indices, updates, shape):
# Ensure indices are long tensor for indexing
indices = indices.long()
# Create a zero tensor of the specified shape
result = torch.zeros(shape, dtype=updates.dtype).to(device)
# Unpack the dimensions for scattering
dim_length = indices.shape[-1]
idx_expanded = tuple(indices[..., i] for i in range(dim_length))
# Scatter the updates to the result tensor
result[idx_expanded] = updates
return result
def batchify(fn, chunk):
"""Constructs a version of 'fn' that applies to smaller batches."""
if chunk is None:
return fn
def ret(inputs):
inputs = inputs.to(device)
return torch.cat([fn(inputs[i:i+chunk]) for i in range(0, inputs.shape[0], chunk)], 0)
return ret
def run_network(inputs, viewdirs, fn, embed_fn, embeddirs_fn, embedobj_fn, netchunk=1024*64):
"""Prepares inputs and applies network 'fn'."""
inputs_flat = torch.reshape(inputs[..., :3], [-1, 3])
embedded = embed_fn(inputs_flat)
if inputs.shape[-1] > 3:
if inputs.shape[-1] == 4:
# NeRF + T w/o embedding
time_st = torch.reshape(inputs[..., 3], [inputs_flat.shape[0], -1])
embedded = torch.cat([embedded, time_st], -1)
else:
# NeRF + Latent Code
inputs_latent = torch.reshape(inputs[..., 3:], [inputs_flat.shape[0], -1])
embedded = torch.cat([embedded, inputs_latent], -1)
if viewdirs is not None:
input_dirs = torch.expand_copy(viewdirs[:, None, :3], inputs[..., :3].shape)
input_dirs_flat = torch.reshape(input_dirs, [-1, input_dirs.shape[-1]])
embedded_dirs = embeddirs_fn(input_dirs_flat)
embedded = torch.cat([embedded, embedded_dirs], -1)
if viewdirs.shape[-1] > 3:
# Use global locations of objects
input_obj_pose = torch.expand_copy(viewdirs[:, None, 3:],
size=[inputs[..., :3].shape[0], inputs[..., :3].shape[1], 3])
input_obj_pose_flat = torch.reshape(input_obj_pose, [-1, input_obj_pose.shape[-1]])
embedded_obj = embedobj_fn(input_obj_pose_flat)
embedded = torch.cat([embedded, embedded_obj], -1)
embedded = embedded.float()
outputs_flat = batchify(fn, netchunk)(embedded)
outputs = torch.reshape(outputs_flat, list(
inputs.shape[:-1]) + [outputs_flat.shape[-1]])
return outputs
def render_rays(ray_batch,
network_fn,
network_query_fn,
N_samples,
N_samples_obj,
retraw=False,
perturb=1.,
N_importance=0,
network_fine=None,
object_network_fn_dict=None,
latent_vector_dict=None,
N_obj=None,
obj_only=False,
obj_transparency=True,
white_bkgd=False,
raw_noise_std=0.,
sampling_method=None,
use_time=False,
plane_bds=None,
plane_normal=None,
delta=0.,
id_planes=0,
verbose=False,
obj_location=True):
"""Volumetric rendering.
Args:
ray_batch: array of shape [batch_size, ...]. All information necessary
for sampling along a ray, including: ray origin, ray direction, min
dist, max dist, and unit-magnitude viewing direction.
network_fn: function. Model for predicting RGB and density at each point
in space.
network_query_fn: function used for passing queries to network_fn.
N_samples: int. Number of different times to sample along each ray.
retraw: bool. If True, include model's raw, unprocessed predictions.
perturb: float, 0 or 1. If non-zero, each ray is sampled at stratified
random points in time.
N_importance: int. Number of additional times to sample along each ray.
These samples are only passed to network_fine.
network_fine: "fine" network with same spec as network_fn.
object_network_fn_dict: dictinoary of functions. Model for predicting RGB and density at each point in
object frames
latent_vector_dict: Dictionary of latent codes
N_obj: Maximumn amount of objects per ray
obj_only: bool. If True, only run models from object_network_fn_dict
white_bkgd: bool. If True, assume a white background.
raw_noise_std: ...
sampling_mehtod: string. Select how points are sampled in space
plane_bds: array of shape [2, 3]. If sampling method planes, descirbing the first and last plane in space.
plane_normal: array of shape [3]. Normal of all planes
delta: float. Distance between adjacent planes.
id_planes: array of shape [N_samples]. Preselected planes for sampling method planes and a given sampling distribution
verbose: bool. If True, print more debugging info.
Returns:
rgb_map: [num_rays, 3]. Estimated RGB color of a ray. Comes from fine model.
disp_map: [num_rays]. Disparity map. 1 / depth.
acc_map: [num_rays]. Accumulated opacity along each ray. Comes from fine model.
raw: [num_rays, num_samples, 4]. Raw predictions from model.
rgb0: See rgb_map. Output for coarse model.
disp0: See disp_map. Output for coarse model.
acc0: See acc_map. Output for coarse model.
z_std: [num_rays]. Standard deviation of distances along ray for each
sample.
"""
def raw2outputs(raw, z_vals, rays_d, raw_noise_std=0, white_bkgd=False, pytest=False):
"""Transforms model's predictions to semantically meaningful values.
Args:
raw: [num_rays, num_samples along ray, 4]. Prediction from model.
z_vals: [num_rays, num_samples along ray]. Integration time.
rays_d: [num_rays, 3]. Direction of each ray.
Returns:
rgb_map: [num_rays, 3]. Estimated RGB color of a ray.
disp_map: [num_rays]. Disparity map. Inverse of depth map.
acc_map: [num_rays]. Sum of weights along each ray.
weights: [num_rays, num_samples]. Weights assigned to each sampled color.
depth_map: [num_rays]. Estimated distance to object.
"""
raw2alpha = lambda raw, dists, act_fn=F.relu: 1.-torch.exp(-act_fn(raw)*dists)
dists = z_vals[...,1:] - z_vals[...,:-1]
dists = torch.cat([dists, torch.Tensor([1e10]).expand(dists[...,:1].shape).to(device)], -1) # [N_rays, N_samples]
dists = dists * torch.norm(rays_d[...,None,:], dim=-1)
rgb = torch.sigmoid(raw[...,:3]) # [N_rays, N_samples, 3]
noise = 0.
if raw_noise_std > 0.:
noise = torch.randn(raw[...,3].shape) * raw_noise_std
# Overwrite randomly sampled data if pytest
if pytest:
np.random.seed(0)
noise = np.random.rand(*list(raw[...,3].shape)) * raw_noise_std
noise = torch.Tensor(noise).to(device)
alpha = raw2alpha(raw[...,3] + noise, dists) # [N_rays, N_samples]
# weights = alpha * tf.math.cumprod(1.-alpha + 1e-10, -1, exclusive=True)
weights = alpha * torch.cumprod(torch.cat([torch.ones((alpha.shape[0], 1)).to(device), 1.-alpha + 1e-10], -1), -1)[:, :-1].to(device)
rgb_map = torch.sum(weights[...,None] * rgb, -2) # [N_rays, 3]
depth_map = torch.sum(weights * z_vals, -1)
disp_map = 1./torch.max(1e-10 * torch.ones_like(depth_map).to(device), depth_map / torch.sum(weights, -1))
acc_map = torch.sum(weights, -1)
if white_bkgd:
rgb_map = rgb_map + (1.-acc_map[...,None])
return rgb_map, disp_map, acc_map, weights, depth_map
def sample_along_ray(near, far, N_samples, N_rays, sampling_method, perturb):
# Sample along each ray given one of the sampling methods. Under the logic, all rays will be sampled at
# the same times.
t_vals = np.linspace(0., 1., N_samples)
if sampling_method == 'squareddist':
z_vals = near * (1. - np.square(t_vals)) + far * (np.square(t_vals))
elif sampling_method == 'lindisp':
# Sample linearly in inverse depth (disparity).
z_vals = 1. / (1. / near * (1. - t_vals) + 1. / far * (t_vals))
else:
# Space integration times linearly between 'near' and 'far'. Same
# integration points will be used for all rays.
z_vals = near * (1.-t_vals) + far * (t_vals)
if sampling_method == 'discrete':
perturb = 0
# Perturb sampling time along each ray. (vanilla NeRF option)
if perturb > 0.:
# get intervals between samples
mids = .5 * (z_vals[..., 1:] + z_vals[..., :-1])
upper = torch.cat([mids, z_vals[..., -1:]], -1)
lower = torch.cat([z_vals[..., :1], mids], -1)
# stratified samples in those intervals
t_rand = torch.randn(z_vals.shape)
z_vals = lower + (upper - lower) * t_rand
return torch.expand_copy(z_vals, [N_rays, N_samples]), perturb
###############################
# batch size
ray_batch = ray_batch.cuda()
N_rays = int(ray_batch.shape[0])
# Extract ray origin, direction.
rays_o, rays_d = ray_batch[:, 0:3], ray_batch[:, 3:6] # [N_rays, 3] each
# Extract unit-normalized viewing direction.
viewdirs = ray_batch[:, 8:11] if ray_batch.shape[-1] > 8 else None
# Extract lower, upper bound for ray distance.
bounds = torch.reshape(ray_batch[..., 6:8], [-1, 1, 2])
near, far = bounds[..., 0], bounds[..., 1] # [-1,1]
if use_time:
time_stamp = ray_batch[:, 11][:, None]
# Extract object position, dimension and label
if N_obj:
obj_pose = ray_batch[:, 11:]
# [N_rays, N_obj, 8] with 3D position, y rot angle, track_id, (3D dimension - length, height, width)
obj_pose = torch.reshape(obj_pose, [N_rays, N_obj, obj_pose.shape[-1] // N_obj])
if N_importance > 0:
obj_pose_fine = tf.repeat(obj_pose[:, None, ...], N_importance + N_samples, axis=1)
else:
obj_pose = obj_pose_fine = None
if not obj_only:
# For training object models only sampling close to the objects is performed
if (sampling_method == 'planes' or sampling_method == 'planes_plus') and plane_bds is not None:
# Sample at ray plane intersection (Neural Scene Graphs)
pts, z_vals = plane_pts([rays_o, rays_d], [plane_bds, plane_normal, delta], id_planes, near,
method=sampling_method)
N_importance = 0
else:
# Sample along ray (vanilla NeRF)
z_vals, perturb = sample_along_ray(near, far, N_samples, N_rays, sampling_method, perturb)
pts = rays_o[..., None, :] + rays_d[..., None, :] * \
z_vals[..., :, None] # [N_rays, N_samples, 3]
####### DEBUG Sampling Points
# print('TURN OFF IF NOT DEBUGING!')
# axes_ls = plt.figure(1).axes
# for i in range(rays_o.shape[0]):
# plt.arrow(np.array(rays_o)[i, 0], np.array(rays_o)[i, 2],
# np.array(30 * rays_d)[i, 0],
# np.array(30 * rays_d)[i, 2], color='red')
#
# plt.sca(axes_ls[1])
# for i in range(rays_o.shape[0]):
# plt.arrow(np.array(rays_o)[i, 2], np.array(rays_o)[i, 1],
# np.array(30 * rays_d)[i, 2],
# np.array(30 * rays_d)[i, 1], color='red')
#
# plt.sca(axes_ls[2])
# for i in range(rays_o.shape[0]):
# plt.arrow(np.array(rays_o)[i, 0], np.array(rays_o)[i, 1],
# np.array(30 * rays_d)[i, 0],
# np.array(30 * rays_d)[i, 1], color='red')
####### DEBUG Sampling Points
# Choose input options
if not N_obj:
# No objects
if use_time:
# Time parameter input
time_stamp_fine = tf.repeat(time_stamp[:, None], N_importance + N_samples,
axis=1) if N_importance > 0 else None
time_stamp = tf.repeat(time_stamp[:, None], N_samples, axis=1)
pts = torch.cat([pts, time_stamp], axis=-1)
raw = network_query_fn(pts, viewdirs, network_fn)
else:
raw = network_query_fn(pts, viewdirs, network_fn)
else:
n_intersect = None
if not obj_pose.shape[-1] > 5:
# If no object dimension is given all points in the scene given in object coordinates will be used as an input to each object model
pts_obj, viewdirs_obj = world2object(pts, viewdirs, obj_pose[..., :3], obj_pose[..., 3],
dim=obj_pose[..., 5:8] if obj_pose.shape[-1] > 5 else None)
pts_obj = tf.transpose(torch.reshape(pts_obj, [N_rays, N_samples, N_obj, 3]), [0, 2, 1, 3])
inputs = torch.cat([pts_obj, tf.repeat(obj_pose[..., None, :3], N_samples, axis=2)], axis=3)
else:
# If 3D bounding boxes are given get intersecting rays and intersection points in scaled object frames
pts_box_w, viewdirs_box_w, z_vals_in_w, z_vals_out_w,\
pts_box_o, viewdirs_box_o, z_vals_in_o, z_vals_out_o, \
intersection_map, _ = box_pts(
[rays_o, rays_d], obj_pose[..., :3], obj_pose[..., 3], dim=obj_pose[..., 5:8],
one_intersec_per_ray=not obj_transparency)
if z_vals_in_o is None or len(z_vals_in_o) == 0:
if obj_only:
# No computation necesary if rays are not intersecting with any objects and no background is selected
raw = torch.zeros([N_rays, 1, 4]).to(device)
z_vals = torch.zeros([N_rays, 1]).to(device)
rgb_map, disp_map, acc_map, weights, depth_map = raw2outputs(
raw, z_vals, rays_d)
rgb_map = torch.ones([N_rays, 3]).to(device)
disp_map = torch.ones([N_rays]).to(device)*1e10
acc_map = torch.zeros([N_rays]).to(device)
depth_map = torch.zeros([N_rays]).to(device)
ret = {'rgb_map': rgb_map, 'disp_map': disp_map, 'acc_map': acc_map}
if retraw:
ret['raw'] = raw
return ret
else:
# TODO: Do not return anything for no intersections.
z_vals_obj_w = torch.zeros([1]).to(device)
intersection_map = torch.zeros([1, 3]).to(device)
else:
n_intersect = z_vals_in_o.shape[0]
# ipdb.set_trace()
obj_pose = obj_pose[intersection_map[:, 0], intersection_map[:, 1]]
# obj_pose = tf.repeat(obj_pose[:, None, :], N_samples_obj, axis=1)
obj_pose = torch.repeat_interleave(obj_pose[:, None, :], N_samples_obj, dim=1)
# Get additional model inputs for intersecting rays
if N_samples_obj > 1:
# ipdb.set_trace()
z_vals_box_o = torch.repeat_interleave(torch.linspace(0., 1., N_samples_obj)[None, :].to(device), n_intersect, dim=0) * \
(z_vals_out_o - z_vals_in_o)[:, None]
else:
z_vals_box_o = torch.repeat_interleave(torch.tensor(1/2)[None,None].to(device), n_intersect, dim=0) * \
(z_vals_out_o - z_vals_in_o)[:, None]
pts_box_samples_o = pts_box_o[:, None, :] + viewdirs_box_o[:, None, :] \
* z_vals_box_o[..., None]
# pts_box_samples_o = pts_box_samples_o[:, None, ...]
# pts_box_samples_o = torch.reshape(pts_box_samples_o, [-1, 3])
obj_pose_transform = torch.reshape(obj_pose, [-1, obj_pose.shape[-1]])
pts_box_samples_w, _ = world2object(torch.reshape(pts_box_samples_o, [-1, 3]), None,
obj_pose_transform[..., :3],
obj_pose_transform[..., 3],
dim=obj_pose_transform[..., 5:8] if obj_pose.shape[-1] > 5 else None,
inverse=True)
pts_box_samples_w = torch.reshape(pts_box_samples_w, [n_intersect, N_samples_obj, 3])
z_vals_obj_w = torch.linalg.norm(pts_box_samples_w - rays_o[intersection_map[:, 0, None][:, 0]][:, None, :], dim=-1)
# else:
# z_vals_obj_w = z_vals_in_w[:, None]
# pts_box_samples_o = pts_box_o[:, None, :]
# pts_box_samples_w = pts_box_w[:, None, :]
#####
# print('TURN OFF IF NOT DEBUGING!')
# axes_ls = plt.figure(1).axes
# plt.sca(axes_ls[0])
#
# pts = np.reshape(pts_box_samples_w, [-1, 3])
# plt.scatter(pts[:, 0], pts[:, 2], color='red')
####
# Extract objects
obj_ids = obj_pose[..., 4]
# object_y, object_idx = tf.unique(torch.reshape(obj_pose[..., 4], [-1]))
object_y, object_idx = torch.unique(torch.reshape(obj_pose[..., 4], [-1]), return_inverse=True)
# Extract classes
obj_class = obj_pose[..., 8]
unique_classes = {}
unique_classes_unique = torch.unique(torch.reshape(obj_class, [-1]), return_inverse=True)
unique_classes['y'] = unique_classes_unique[0]
unique_classes['idx'] = unique_classes_unique[1]
class_id = torch.reshape(unique_classes['idx'], obj_class.shape)
inputs = pts_box_samples_o
if latent_vector_dict is not None:
latent_vector_inputs = None
for y, obj_id in enumerate(object_y):
# ipdb.set_trace()
indices = torch.nonzero(object_idx==y).to(device)
latent_vector = latent_vector_dict['latent_vector_obj_' + str(int(obj_id)).zfill(5)][None, :]
latent_vector = torch.repeat_interleave(latent_vector, indices.shape[0], dim=0).to(device)
latent_vector = scatter_nd(indices, latent_vector, [n_intersect*N_samples_obj, latent_vector.shape[-1]])
if latent_vector_inputs is None:
latent_vector_inputs = latent_vector
else:
latent_vector_inputs += latent_vector
latent_vector_inputs = torch.reshape(latent_vector_inputs, [n_intersect, N_samples_obj, -1]).to(device)
# ipdb.set_trace()
inputs = torch.cat([inputs, latent_vector_inputs], dim=2).to(device)
# inputs = torch.cat([inputs, obj_pose[..., :3]], axis=-1)
# objdirs = torch.cat([tf.cos(obj_pose[:, 0, 3, None]), tf.sin(obj_pose[:, 0, 3, None])], axis=1)
# objdirs = objdirs / tf.reduce_sum(objdirs, axis=1)[:, None]
# viewdirs_obj = torch.cat([viewdirs_box_o, obj_pose[..., :3][:, 0, :], objdirs], axis=1)
if obj_location:
viewdirs_obj = torch.cat([viewdirs_box_o, obj_pose[..., :3][:, 0, :]], axis=1)
else:
viewdirs_obj = viewdirs_box_o
if not obj_only:
# Get integration step for all models
z_vals, id_z_vals_bckg, id_z_vals_obj = combine_z(z_vals,
z_vals_obj_w if z_vals_in_o is not None else None,
intersection_map,
N_rays,
N_samples,
N_obj,
N_samples_obj, )
else:
z_vals, _, id_z_vals_obj = combine_z(None, z_vals_obj_w, intersection_map, N_rays, N_samples, N_obj,
N_samples_obj)
if not obj_only:
# Run background model
raw = torch.zeros([N_rays, N_samples + N_obj*N_samples_obj, 4]).to(device)
raw_sh = [N_rays, N_samples + N_obj*N_samples_obj, 4]
# Predict RGB and density from background
raw_bckg = network_query_fn(pts, viewdirs, network_fn)
# ipdb.set_trace()
# -------------------- Hope this works --------------------
raw += scatter_nd_my(id_z_vals_bckg, raw_bckg, raw_sh)
else:
raw = torch.zeros([N_rays, N_obj*N_samples_obj, 4]).to(device)
raw_sh = raw.shape
if z_vals_in_o is not None and len(z_vals_in_o) != 0:
# Loop for one model per object and no latent representations
if latent_vector_dict is None:
obj_id = torch.reshape(object_idx, obj_pose[..., 4].shape)
for k, track_id in enumerate(object_y):
if track_id >= 0:
input_indices = torch.nonzero(torch.eq(obj_id, k))
input_indices = torch.reshape(input_indices, [-1, N_samples_obj, 2])
model_name = 'model_obj_' + str(np.array(track_id).astype(np.int32))
# print('Hit', model_name, n_intersect, 'times.')
if model_name in object_network_fn_dict:
obj_network_fn = object_network_fn_dict[model_name]
inputs_obj_k = inputs[input_indices[:,0], input_indices[:,1]]
viewdirs_obj_k = viewdirs_obj[input_indices[..., None, 0][:, 0]] if N_samples_obj == 1 else \
viewdirs_obj[input_indices[..., None,0, 0][:, 0]]
# Predict RGB and density from object model
raw_k = network_query_fn(inputs_obj_k, viewdirs_obj_k, obj_network_fn)
if n_intersect is not None:
# Arrange RGB and denisty from object models along the respective rays
raw_k = scatter_nd(input_indices[:, :], raw_k, [n_intersect, N_samples_obj, 4]) # Project the network outputs to the corresponding ray
raw_k = scatter_nd(intersection_map[:, :2], raw_k, [N_rays, N_obj, N_samples_obj, 4]) # Project to rays and object intersection order
raw_k = scatter_nd(id_z_vals_obj, raw_k, raw_sh) # Reorder along z and ray
else:
raw_k = scatter_nd(input_indices[:, 0][..., None], raw_k, [N_rays, N_samples, 4])
# Add RGB and density from object model to the background and other object predictions
raw += raw_k
# Loop over classes c and evaluate each models f_c for all latent object describtor
else:
for c, class_type in enumerate(unique_classes['y']):
# Ignore background class
if class_type >= 0:
input_indices = torch.nonzero(torch.eq(class_id, c))
input_indices = torch.reshape(input_indices, [-1, N_samples_obj, 2])
model_name = 'model_class_' + str(int(np.array(class_type.cpu()))).zfill(5)
if model_name in object_network_fn_dict:
obj_network_fn = object_network_fn_dict[model_name]
# ipdb.set_trace()
inputs_obj_c = inputs[input_indices[..., 0], input_indices[..., 1]]
# Legacy version 2
# latent_vector = torch.cat([
# latent_vector_dict['latent_vector_' + str(int(obj_id)).zfill(5)][None, :]
# for obj_id in np.array(tf.gather_nd(obj_pose[..., 4], input_indices)).astype(np.int32).flatten()],
# axis=0)
# latent_vector = torch.reshape(latent_vector, [inputs_obj_k.shape[0], inputs_obj_k.shape[1], -1])
# inputs_obj_k = torch.cat([inputs_obj_k, latent_vector], axis=-1)
# viewdirs_obj_k = tf.gather_nd(viewdirs_obj,
# input_indices[..., 0]) if N_samples_obj == 1 else \
# tf.gather_nd(viewdirs_obj, input_indices)
viewdirs_obj_c = viewdirs_obj[input_indices[..., None, 0][:, 0]][:,0,:]
# Predict RGB and density from object model
raw_k = network_query_fn(inputs_obj_c, viewdirs_obj_c, obj_network_fn)
if n_intersect is not None:
# Arrange RGB and denisty from object models along the respective rays
raw_k = scatter_nd_my(input_indices[:, :], raw_k, [n_intersect, N_samples_obj,
4]) # Project the network outputs to the corresponding ray
raw_k = scatter_nd_my(intersection_map[:, :2], raw_k, [N_rays, N_obj, N_samples_obj,
4]) # Project to rays and object intersection order
raw_k = scatter_nd_my(id_z_vals_obj, raw_k, raw_sh) # Reorder along z in positive ray direction
else:
raw_k = scatter_nd_my(input_indices[:, 0][..., None], raw_k,
[N_rays, N_samples, 4])
# Add RGB and density from object model to the background and other object predictions
raw += raw_k
else:
print('No model ', model_name,' found')
# raw_2 = render_mot_scene(pts, viewdirs, network_fn, network_query_fn,
# inputs, viewdirs_obj, z_vals_in_o, n_intersect, object_idx, object_y, obj_pose,
# unique_classes, class_id, latent_vector_dict, object_network_fn_dict,
# N_rays,N_samples, N_obj, N_samples_obj,
# obj_only=obj_only)
# TODO: Reduce computation by removing 0 entrys
rgb_map, disp_map, acc_map, weights, depth_map = raw2outputs(
raw, z_vals, rays_d)
if N_importance > 0:
rgb_map_0, disp_map_0, acc_map_0 = rgb_map, disp_map, acc_map
if sampling_method == 'planes' or sampling_method == 'planes_plus':
pts, z_vals = plane_pts([rays_o, rays_d], [plane_bds, plane_normal, delta], id_planes, near,
method=sampling_method)
else:
# Obtain additional integration times to evaluate based on the weights
# assigned to colors in the coarse model.
z_vals_mid = .5 * (z_vals[..., 1:] + z_vals[..., :-1])
z_samples = sample_pdf(
z_vals_mid, weights[..., 1:-1], N_importance, det=(perturb == 0.))
z_samples = tf.stop_gradient(z_samples)
# Obtain all points to evaluate color, density at.
z_vals = tf.sort(torch.cat([z_vals, z_samples], -1), -1)
pts = rays_o[..., None, :] + rays_d[..., None, :] * \
z_vals[..., :, None] # [N_rays, N_samples + N_importance, 3]
# Make predictions with network_fine.
if use_time:
pts = torch.cat([pts, time_stamp_fine], axis=-1)
run_fn = network_fn if network_fine is None else network_fine
raw = network_query_fn(pts, viewdirs, run_fn)
rgb_map, disp_map, acc_map, weights, depth_map = raw2outputs(
raw, z_vals, rays_d)
ret = {'rgb_map': rgb_map, 'disp_map': disp_map, 'acc_map': acc_map}
if retraw:
ret['raw'] = raw
if N_importance > 0:
ret['rgb0'] = rgb_map_0
ret['disp0'] = disp_map_0
ret['acc0'] = acc_map_0
if not sampling_method == 'planes':
ret['z_std'] = tf.math.reduce_std(z_samples, -1) # [N_rays]
# if latent_vector_dict is not None:
# ret['latent_loss'] = torch.reshape(latent_vector, [N_rays, N_samples_obj, -1])
# for k in ret:
# tf.debugging.check_numerics(ret[k], 'output {}'.format(k))
return ret
def batchify_rays(rays_flat, chunk=1024*32, **kwargs):
"""Render rays in smaller minibatches to avoid OOM."""
all_ret = {}
for i in range(0, rays_flat.shape[0], chunk):
ret = render_rays(rays_flat[i:i+chunk], **kwargs)
for k in ret:
if k not in all_ret:
all_ret[k] = []
all_ret[k].append(ret[k])
all_ret = {k: torch.cat(all_ret[k], 0) for k in all_ret}
return all_ret
def render(H,
W,
focal,
chunk=1024*32,
rays=None,
c2w=None,
obj=None,
time_stamp=None,
near=0.,
far=1.,
use_viewdirs=False,
c2w_staticcam=None,
**kwargs):
"""Render rays
Args:
H: int. Height of image in pixels.
W: int. Width of image in pixels.
focal: float. Focal length of pinhole camera.
chunk: int. Maximum number of rays to process simultaneously. Used to
control maximum memory usage. Does not affect final results.
rays: array of shape [2, batch_size, 3]. Ray origin and direction for
each example in batch.
c2w: array of shape [3, 4]. Camera-to-world transformation matrix.
obj: array of shape [batch_size, max_obj, n_obj_nodes]. Scene object's pose and propeties for each
example in the batch
time_stamp: bool. If True the frame will be taken into account as an additional input to the network
near: float or array of shape [batch_size]. Nearest distance for a ray.
far: float or array of shape [batch_size]. Farthest distance for a ray.
use_viewdirs: bool. If True, use viewing direction of a point in space in model.
c2w_staticcam: array of shape [3, 4]. If not None, use this transformation matrix for
camera while using other c2w argument for viewing directions.
Returns:
rgb_map: [batch_size, 3]. Predicted RGB values for rays.
disp_map: [batch_size]. Disparity map. Inverse of depth.
acc_map: [batch_size]. Accumulated opacity (alpha) along a ray.
extras: dict with everything returned by render_rays().
"""
if c2w is not None:
# special case to render full image
# rays = tf.random.shuffle(torch.cat([get_rays(H, W, focal, c2w)[0], get_rays(H, W, focal, c2w)[1]], axis=-1))
# rays_o = rays[..., :3]
# rays_d = rays[..., 3:]
rays_o, rays_d = get_rays(H, W, focal, c2w)
if obj is not None:
obj = torch.repeat_interleave(obj[None, ...], H*W, dim=0)
if time_stamp is not None:
time_stamp = torch.repeat_interleave(time_stamp[None, ...], H*W, dim=0)
else:
# use provided ray batch
rays_o, rays_d = rays
if use_viewdirs:
# provide ray directions as input
viewdirs = rays_d
if c2w_staticcam is not None:
# special case to visualize effect of viewdirs
rays_o, rays_d = get_rays(H, W, focal, c2w_staticcam)
# Make all directions unit magnitude.
# shape: [batch_size, 3]
# ipdb.set_trace()
viewdirs = viewdirs / torch.linalg.norm(viewdirs, dim=-1, keepdim=True)
viewdirs = torch.reshape(viewdirs, [-1, 3]).float().to(device)
sh = rays_d.shape # [..., 3]
# Create ray batch
# rays_o = tf.cast(torch.reshape(rays_o, [-1, 3]), dtype=tf.float32)
rays_o = torch.reshape(rays_o, [-1, 3]).to(device)
# rays_d = tf.cast(torch.reshape(rays_d, [-1, 3]), dtype=tf.float32)
rays_d = torch.reshape(rays_d, [-1, 3]).to(device)
near, far = near * \
torch.ones_like(rays_d[..., :1]).to(device), far * torch.ones_like(rays_d[..., :1]).to(device)
# (ray origin, ray direction, min dist, max dist) for each ray
rays = torch.cat([rays_o, rays_d, near, far], axis=-1)
viewdirs = viewdirs.to(device)
if use_viewdirs:
# (ray origin, ray direction, min dist, max dist, normalized viewing direction)
rays = torch.cat([rays, viewdirs], axis=-1)
if time_stamp is not None:
# time_stamp = tf.cast(torch.reshape(time_stamp, [len(rays), -1]), dtype=tf.float32)
time_stamp = torch.reshape(time_stamp, [len(rays), -1])
rays = torch.cat([rays, time_stamp], axis=-1)
if obj is not None:
# (ray origin, ray direction, min dist, max dist, normalized viewing direction, scene objects)
# obj = tf.cast(torch.reshape(obj, [obj.shape[0], obj.shape[1]*obj.shape[2]]), dtype=tf.float32)
obj = torch.reshape(obj, [obj.shape[0], obj.shape[1] * obj.shape[2]]).to(device)
rays = torch.cat([rays, obj], axis=-1)
# Render and reshape
all_ret = batchify_rays(rays, chunk, **kwargs)
for k in all_ret:
k_sh = list(sh[:-1]) + list(all_ret[k].shape[1:])
all_ret[k] = torch.reshape(all_ret[k], k_sh)
# all_ret[k] = torch.reshape(all_ret[k], [k_sh[0], k_sh[1], -1])
k_extract = ['rgb_map', 'disp_map', 'acc_map']
ret_list = [all_ret[k] for k in k_extract]
ret_dict = {k: all_ret[k] for k in all_ret if k not in k_extract}
return ret_list + [ret_dict]
def render_path(render_poses, hwf, chunk, render_kwargs, obj=None, obj_meta=None, gt_imgs=None, savedir=None,
render_factor=0, render_manipulation=None, rm_obj=None, time_stamp=None):
H, W, focal = hwf
if render_factor != 0:
# Render downsampled for speed
H = H//render_factor
W = W//render_factor
focal = focal/render_factor
rgbs = []
disps = []
t = time.time()
for i, c2w in enumerate(render_poses):
print(i, time.time() - t)
if time_stamp is not None:
time_st = time_stamp[i]
else:
time_st = None
if obj is None:
rgb, disp, acc, _ = render(
H, W, focal, chunk=chunk, c2w=c2w[:3, :4], obj=None, time_stamp=time_st, **render_kwargs)
rgbs.append(rgb.numpy())
disps.append(disp.numpy())
if i == 0:
print(rgb.shape, disp.shape)
if gt_imgs is not None and render_factor == 0:
p = -10. * np.log10(np.mean(np.square(rgb - gt_imgs[i])))
print(p)
if savedir is not None:
rgb8 = to8b(rgbs[-1])
filename = os.path.join(savedir, '{:03d}.png'.format(i))
imageio.imwrite(filename, rgb8)
print(i, time.time() - t)
else:
# Manipulate scene graph edges
# rm_obj = [3, 4, 8, 5, 12]
render_set = manipulate_obj_pose(render_manipulation, np.array(obj), obj_meta, i, rm_obj=rm_obj)
# Load manual generated scene graphs
if render_manipulation is not None and 'handcraft' in render_manipulation:
if str(i).zfill(3) + '.txt' in os.listdir(savedir):
print('Reloading', str(i).zfill(3) + '.txt')
render_set.pop()
loaded_obj_i = []
loaded_objs = np.loadtxt(os.path.join(savedir, str(i).zfill(3) + '.txt'))[:, :6]
loaded_objs[:, 5] = 0
loaded_objs[:, 4] = np.array([np.where(np.equal(obj_meta[:, 0], loaded_objs[j, 4])) for j in range(len(loaded_objs))])[:, 0, 0]
loaded_objs = tf.cast(loaded_objs, tf.float32)
loaded_obj_i.append(loaded_objs)
render_set.append(loaded_obj_i)
if '02' in render_manipulation:
c2w = render_poses[36]
if '03' in render_manipulation:
c2w = render_poses[20]
if '04' in render_manipulation or '05' in render_manipulation:
c2w = render_poses[20]
render_kwargs['N_obj'] = len(render_set[0][0])
steps = len(render_set)
for r, render_set_i in enumerate(render_set):
t = time.time()
j = steps * i + r
obj_i = render_set_i[0]
if obj_meta is not None:
obj_i_metadata = tf.gather(obj_meta, tf.cast(obj_i[:, 4], tf.int32),
axis=0)
batch_track_id = obj_i_metadata[..., 0]
print("Next Frame includes Objects: ")
if batch_track_id.shape[0] > 1:
for object_tracking_id in np.array(tf.squeeze(batch_track_id)).astype(np.int32):
if object_tracking_id >= 0:
print(object_tracking_id)
obj_i_dim = obj_i_metadata[:, 1:4]
obj_i_label = obj_i_metadata[:, 4][:, None]
# xyz + roty
obj_i = obj_i[..., :4]
obj_i = torch.cat([obj_i, batch_track_id[..., None], obj_i_dim, obj_i_label], axis=-1)
# obj_i = np.array(obj_i)
# rm_ls_0 = [0, 1, 2,]
# rm_ls_1 = [0, 1, 2]
# rm_ls_2 = [0, 1, 2, 3, 5]
# rm_ls = [rm_ls_0, rm_ls_1, rm_ls_2]
# for k in rm_ls[i]:
# obj_i[k] = np.ones([9]) * -1
rgb, disp, acc, _ = render(
H, W, focal, chunk=chunk, c2w=c2w[:3, :4], obj=obj_i, **render_kwargs)
rgbs.append(rgb.numpy())
disps.append(disp.numpy())
if j == 0:
print(rgb.shape, disp.shape)
if gt_imgs is not None and render_factor == 0:
p = -10. * np.log10(np.mean(np.square(rgb - gt_imgs[i])))
print(p)
if savedir is not None:
rgb8 = to8b(rgbs[-1])
filename = os.path.join(savedir, '{:03d}.png'.format(j))
imageio.imwrite(filename, rgb8)
if render_manipulation is not None:
if 'handcraft' in render_manipulation:
filename = os.path.join(savedir, '{:03d}.txt'.format(j))
np.savetxt(filename, np.array(obj_i), fmt='%.18e %.18e %.18e %.18e %.1e %.18e %.18e %.18e %.1e')
print(j, time.time() - t)
rgbs = np.stack(rgbs, 0)
disps = np.stack(disps, 0)
return rgbs, disps
def create_nerf(args):
"""Instantiate NeRF's MLP model."""
if args.obj_detection:
trainable = False
else:
trainable = True
embed_fn, input_ch = get_embedder(args.multires, args.i_embed)
if args.use_time:
input_ch += 1
input_ch_views = 0
embeddirs_fn = None
if args.use_viewdirs:
embeddirs_fn, input_ch_views = get_embedder(
args.multires_views, args.i_embed)
output_ch = 4
skips = [4]
model = NeRF(
D=args.netdepth, W=args.netwidth,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_color_head=input_ch_views, use_viewdirs=args.use_viewdirs, ).cuda()
grad_vars = list(model.parameters())
models = {'model': model}
model_fine = None
if args.N_importance > 0:
model_fine = NeRF(
D=args.netdepth_fine, W=args.netwidth_fine,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_color_head=input_ch_views, use_viewdirs=args.use_viewdirs, ).cuda()
grad_vars += list(model_fine.parameters())
models['model_fine'] = model_fine
models_dynamic_dict = None
embedobj_fn = None
latent_vector_dict = None if args.latent_size < 1 else {}
latent_encodings = None if args.latent_size < 1 else {}
if args.use_object_properties and not args.bckg_only:
models_dynamic_dict = {}
embedobj_fn, input_ch_obj = get_embedder(
args.multires_obj, -1 if args.multires_obj == -1 else args.i_embed, input_dims=3)
# Version a: One Network per object
if args.latent_size < 1:
input_ch = input_ch
input_ch_color_head = input_ch_views
# Don't add object location input for setting 1
if args.object_setting != 1:
input_ch_color_head += input_ch_obj
# TODO: Change to number of objects in Frames
for object_i in args.scene_objects:
model_name = 'model_obj_' + str(int(object_i)) # .zfill(5)
model_obj = NeRF(
D=args.netdepth_fine, W=args.netwidth_fine,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_color_head=input_ch_color_head, use_viewdirs=args.use_viewdirs,).cuda()
# latent_size=args.latent_size)
grad_vars += list(model_obj.parameters())
models[model_name] = model_obj
models_dynamic_dict[model_name] = model_obj
# Version b: One Network for all similar objects of the same class
else:
input_ch = input_ch + args.latent_size
input_ch_color_head = input_ch_views
# Don't add object location input for setting 1
if args.object_setting != 1:
input_ch_color_head += input_ch_obj
for obj_class in args.scene_classes:
model_name = 'model_class_' + str(int(obj_class)).zfill(5)
model_obj = NeRF(
D=args.netdepth_fine, W=args.netwidth_fine,
input_ch=input_ch, output_ch=output_ch, skips=skips,
input_ch_color_head=input_ch_color_head,
# input_ch_shadow_head=input_ch_obj,
use_viewdirs=args.use_viewdirs, ).cuda()
# use_shadows=args.use_shadows,
# latent_size=args.latent_size)
grad_vars += list(model_obj.parameters())
models[model_name] = model_obj
models_dynamic_dict[model_name] = model_obj
for object_i in args.scene_objects:
name = 'latent_vector_obj_'+str(int(object_i)).zfill(5)
latent_vector_obj = init_latent_vector(args.latent_size, name)
grad_vars.append(latent_vector_obj)
latent_encodings[name] = latent_vector_obj
latent_vector_dict[name] = latent_vector_obj
# TODO: Remove object embedding function
def network_query_fn(inputs, viewdirs, network_fn): return run_network(
inputs, viewdirs, network_fn,
embed_fn=embed_fn,
embeddirs_fn=embeddirs_fn,
embedobj_fn=embedobj_fn,
netchunk=args.netchunk)
render_kwargs_train = {
'network_query_fn': network_query_fn,
'perturb': args.perturb,
'N_importance': args.N_importance,
'network_fine': model_fine,
'N_samples': args.N_samples,
'N_samples_obj': args.N_samples_obj,
'network_fn': model,
'use_viewdirs': args.use_viewdirs,
'object_network_fn_dict': models_dynamic_dict,
'latent_vector_dict': latent_vector_dict if latent_vector_dict is not None else None,
'N_obj': args.max_input_objects if args.use_object_properties and not args.bckg_only else False,
'obj_only': args.obj_only,
'obj_transparency': not args.obj_opaque,
'white_bkgd': args.white_bkgd,
'raw_noise_std': args.raw_noise_std,
'sampling_method': args.sampling_method,
'use_time': args.use_time,
'obj_location': False if args.object_setting == 1 else True,
}
render_kwargs_test = {
k: render_kwargs_train[k] for k in render_kwargs_train}
render_kwargs_test['perturb'] = False
render_kwargs_test['raw_noise_std'] = 0.
# render_kwargs_test['obj_only'] = False
start = 0
basedir = args.basedir
expname = args.expname
weights_path = None
if args.ft_path is not None and args.ft_path != 'None':
ckpts = [args.ft_path]
elif args.model_library is not None and args.model_library != 'None':
obj_ckpts = {}
ckpts = []
for f in sorted(os.listdir(args.model_library)):
if 'model_' in f and 'fine' not in f and 'optimizer' not in f and 'obj' not in f:
ckpts.append(os.path.join(args.model_library, f))