{{ message }}
Repository navigation
Expand file tree
/
Copy pathrender_utils.py
More file actions
2094 lines (1650 loc) · 78.2 KB
/
Copy pathrender_utils.py
File metadata and controls
2094 lines (1650 loc) · 78.2 KB
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, sys
import imageio
import random
import time
import numpy as np
from numpy import *
import math
from numpy import array
from math import pi, cos, sin, acos, asin, sqrt
import cupy
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from run_nerf_helpers import *
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
DEBUG = False
kernel_Softsplat_updateOutput = '''
extern "C" __global__ void kernel_Softsplat_updateOutput(
const int n,
const float* input,
const float* flow,
float* output
) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
const int intN = ( intIndex / SIZE_3(output) / SIZE_2(output) / SIZE_1(output) ) % SIZE_0(output);
const int intC = ( intIndex / SIZE_3(output) / SIZE_2(output) ) % SIZE_1(output);
const int intY = ( intIndex / SIZE_3(output) ) % SIZE_2(output);
const int intX = ( intIndex ) % SIZE_3(output);
float fltOutputX = (float) (intX) + VALUE_4(flow, intN, 0, intY, intX);
float fltOutputY = (float) (intY) + VALUE_4(flow, intN, 1, intY, intX);
int intNorthwestX = (int) (floor(fltOutputX));
int intNorthwestY = (int) (floor(fltOutputY));
int intNortheastX = intNorthwestX + 1;
int intNortheastY = intNorthwestY;
int intSouthwestX = intNorthwestX;
int intSouthwestY = intNorthwestY + 1;
int intSoutheastX = intNorthwestX + 1;
int intSoutheastY = intNorthwestY + 1;
float fltNorthwest = ((float) (intSoutheastX) - fltOutputX ) * ((float) (intSoutheastY) - fltOutputY );
float fltNortheast = (fltOutputX - (float) (intSouthwestX)) * ((float) (intSouthwestY) - fltOutputY );
float fltSouthwest = ((float) (intNortheastX) - fltOutputX ) * (fltOutputY - (float) (intNortheastY));
float fltSoutheast = (fltOutputX - (float) (intNorthwestX)) * (fltOutputY - (float) (intNorthwestY));
if ((intNorthwestX >= 0) & (intNorthwestX < SIZE_3(output)) & (intNorthwestY >= 0) & (intNorthwestY < SIZE_2(output))) {
atomicAdd(&output[OFFSET_4(output, intN, intC, intNorthwestY, intNorthwestX)], VALUE_4(input, intN, intC, intY, intX) * fltNorthwest);
}
if ((intNortheastX >= 0) & (intNortheastX < SIZE_3(output)) & (intNortheastY >= 0) & (intNortheastY < SIZE_2(output))) {
atomicAdd(&output[OFFSET_4(output, intN, intC, intNortheastY, intNortheastX)], VALUE_4(input, intN, intC, intY, intX) * fltNortheast);
}
if ((intSouthwestX >= 0) & (intSouthwestX < SIZE_3(output)) & (intSouthwestY >= 0) & (intSouthwestY < SIZE_2(output))) {
atomicAdd(&output[OFFSET_4(output, intN, intC, intSouthwestY, intSouthwestX)], VALUE_4(input, intN, intC, intY, intX) * fltSouthwest);
}
if ((intSoutheastX >= 0) & (intSoutheastX < SIZE_3(output)) & (intSoutheastY >= 0) & (intSoutheastY < SIZE_2(output))) {
atomicAdd(&output[OFFSET_4(output, intN, intC, intSoutheastY, intSoutheastX)], VALUE_4(input, intN, intC, intY, intX) * fltSoutheast);
}
} }
'''
kernel_Softsplat_updateGradInput = '''
extern "C" __global__ void kernel_Softsplat_updateGradInput(
const int n,
const float* input,
const float* flow,
const float* gradOutput,
float* gradInput,
float* gradFlow
) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
const int intN = ( intIndex / SIZE_3(gradInput) / SIZE_2(gradInput) / SIZE_1(gradInput) ) % SIZE_0(gradInput);
const int intC = ( intIndex / SIZE_3(gradInput) / SIZE_2(gradInput) ) % SIZE_1(gradInput);
const int intY = ( intIndex / SIZE_3(gradInput) ) % SIZE_2(gradInput);
const int intX = ( intIndex ) % SIZE_3(gradInput);
float fltGradInput = 0.0;
float fltOutputX = (float) (intX) + VALUE_4(flow, intN, 0, intY, intX);
float fltOutputY = (float) (intY) + VALUE_4(flow, intN, 1, intY, intX);
int intNorthwestX = (int) (floor(fltOutputX));
int intNorthwestY = (int) (floor(fltOutputY));
int intNortheastX = intNorthwestX + 1;
int intNortheastY = intNorthwestY;
int intSouthwestX = intNorthwestX;
int intSouthwestY = intNorthwestY + 1;
int intSoutheastX = intNorthwestX + 1;
int intSoutheastY = intNorthwestY + 1;
float fltNorthwest = ((float) (intSoutheastX) - fltOutputX ) * ((float) (intSoutheastY) - fltOutputY );
float fltNortheast = (fltOutputX - (float) (intSouthwestX)) * ((float) (intSouthwestY) - fltOutputY );
float fltSouthwest = ((float) (intNortheastX) - fltOutputX ) * (fltOutputY - (float) (intNortheastY));
float fltSoutheast = (fltOutputX - (float) (intNorthwestX)) * (fltOutputY - (float) (intNorthwestY));
if ((intNorthwestX >= 0) & (intNorthwestX < SIZE_3(gradOutput)) & (intNorthwestY >= 0) & (intNorthwestY < SIZE_2(gradOutput))) {
fltGradInput += VALUE_4(gradOutput, intN, intC, intNorthwestY, intNorthwestX) * fltNorthwest;
}
if ((intNortheastX >= 0) & (intNortheastX < SIZE_3(gradOutput)) & (intNortheastY >= 0) & (intNortheastY < SIZE_2(gradOutput))) {
fltGradInput += VALUE_4(gradOutput, intN, intC, intNortheastY, intNortheastX) * fltNortheast;
}
if ((intSouthwestX >= 0) & (intSouthwestX < SIZE_3(gradOutput)) & (intSouthwestY >= 0) & (intSouthwestY < SIZE_2(gradOutput))) {
fltGradInput += VALUE_4(gradOutput, intN, intC, intSouthwestY, intSouthwestX) * fltSouthwest;
}
if ((intSoutheastX >= 0) & (intSoutheastX < SIZE_3(gradOutput)) & (intSoutheastY >= 0) & (intSoutheastY < SIZE_2(gradOutput))) {
fltGradInput += VALUE_4(gradOutput, intN, intC, intSoutheastY, intSoutheastX) * fltSoutheast;
}
gradInput[intIndex] = fltGradInput;
} }
'''
kernel_Softsplat_updateGradFlow = '''
extern "C" __global__ void kernel_Softsplat_updateGradFlow(
const int n,
const float* input,
const float* flow,
const float* gradOutput,
float* gradInput,
float* gradFlow
) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
float fltGradFlow = 0.0;
const int intN = ( intIndex / SIZE_3(gradFlow) / SIZE_2(gradFlow) / SIZE_1(gradFlow) ) % SIZE_0(gradFlow);
const int intC = ( intIndex / SIZE_3(gradFlow) / SIZE_2(gradFlow) ) % SIZE_1(gradFlow);
const int intY = ( intIndex / SIZE_3(gradFlow) ) % SIZE_2(gradFlow);
const int intX = ( intIndex ) % SIZE_3(gradFlow);
float fltOutputX = (float) (intX) + VALUE_4(flow, intN, 0, intY, intX);
float fltOutputY = (float) (intY) + VALUE_4(flow, intN, 1, intY, intX);
int intNorthwestX = (int) (floor(fltOutputX));
int intNorthwestY = (int) (floor(fltOutputY));
int intNortheastX = intNorthwestX + 1;
int intNortheastY = intNorthwestY;
int intSouthwestX = intNorthwestX;
int intSouthwestY = intNorthwestY + 1;
int intSoutheastX = intNorthwestX + 1;
int intSoutheastY = intNorthwestY + 1;
float fltNorthwest = 0.0;
float fltNortheast = 0.0;
float fltSouthwest = 0.0;
float fltSoutheast = 0.0;
if (intC == 0) {
fltNorthwest = ((float) (-1.0)) * ((float) (intSoutheastY) - fltOutputY );
fltNortheast = ((float) (+1.0)) * ((float) (intSouthwestY) - fltOutputY );
fltSouthwest = ((float) (-1.0)) * (fltOutputY - (float) (intNortheastY));
fltSoutheast = ((float) (+1.0)) * (fltOutputY - (float) (intNorthwestY));
} else if (intC == 1) {
fltNorthwest = ((float) (intSoutheastX) - fltOutputX ) * ((float) (-1.0));
fltNortheast = (fltOutputX - (float) (intSouthwestX)) * ((float) (-1.0));
fltSouthwest = ((float) (intNortheastX) - fltOutputX ) * ((float) (+1.0));
fltSoutheast = (fltOutputX - (float) (intNorthwestX)) * ((float) (+1.0));
}
for (int intChannel = 0; intChannel < SIZE_1(gradOutput); intChannel += 1) {
float fltInput = VALUE_4(input, intN, intChannel, intY, intX);
if ((intNorthwestX >= 0) & (intNorthwestX < SIZE_3(gradOutput)) & (intNorthwestY >= 0) & (intNorthwestY < SIZE_2(gradOutput))) {
fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intNorthwestY, intNorthwestX) * fltNorthwest;
}
if ((intNortheastX >= 0) & (intNortheastX < SIZE_3(gradOutput)) & (intNortheastY >= 0) & (intNortheastY < SIZE_2(gradOutput))) {
fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intNortheastY, intNortheastX) * fltNortheast;
}
if ((intSouthwestX >= 0) & (intSouthwestX < SIZE_3(gradOutput)) & (intSouthwestY >= 0) & (intSouthwestY < SIZE_2(gradOutput))) {
fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intSouthwestY, intSouthwestX) * fltSouthwest;
}
if ((intSoutheastX >= 0) & (intSoutheastX < SIZE_3(gradOutput)) & (intSoutheastY >= 0) & (intSoutheastY < SIZE_2(gradOutput))) {
fltGradFlow += fltInput * VALUE_4(gradOutput, intN, intChannel, intSoutheastY, intSoutheastX) * fltSoutheast;
}
}
gradFlow[intIndex] = fltGradFlow;
} }
'''
def cupy_kernel(strFunction, objVariables):
strKernel = globals()[strFunction]
while True:
objMatch = re.search('(SIZE_)([0-4])(\()([^\)]*)(\))', strKernel)
if objMatch is None:
break
# end
intArg = int(objMatch.group(2))
strTensor = objMatch.group(4)
intSizes = objVariables[strTensor].size()
strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg]))
# end
while True:
objMatch = re.search('(OFFSET_)([0-4])(\()([^\)]+)(\))', strKernel)
if objMatch is None:
break
# end
intArgs = int(objMatch.group(2))
strArgs = objMatch.group(4).split(',')
strTensor = strArgs[0]
intStrides = objVariables[strTensor].stride()
strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg]) + ')' for intArg in range(intArgs) ]
strKernel = strKernel.replace(objMatch.group(0), '(' + str.join('+', strIndex) + ')')
# end
while True:
objMatch = re.search('(VALUE_)([0-4])(\()([^\)]+)(\))', strKernel)
if objMatch is None:
break
# end
intArgs = int(objMatch.group(2))
strArgs = objMatch.group(4).split(',')
strTensor = strArgs[0]
intStrides = objVariables[strTensor].stride()
strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg]) + ')' for intArg in range(intArgs) ]
strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')
# end
return strKernel
# end
@cupy.memoize(for_each_device=True)
def cupy_launch(strFunction, strKernel):
return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction)
# end
class _FunctionSoftsplat(torch.autograd.Function):
@staticmethod
def forward(self, input, flow):
self.save_for_backward(input, flow)
intSamples = input.shape[0]
intInputDepth, intInputHeight, intInputWidth = input.shape[1], input.shape[2], input.shape[3]
intFlowDepth, intFlowHeight, intFlowWidth = flow.shape[1], flow.shape[2], flow.shape[3]
assert(intFlowDepth == 2)
assert(intInputHeight == intFlowHeight)
assert(intInputWidth == intFlowWidth)
assert(input.is_contiguous() == True)
assert(flow.is_contiguous() == True)
output = input.new_zeros([ intSamples, intInputDepth, intInputHeight, intInputWidth ])
if input.is_cuda == True:
n = output.nelement()
cupy_launch('kernel_Softsplat_updateOutput', cupy_kernel('kernel_Softsplat_updateOutput', {
'input': input,
'flow': flow,
'output': output
}))(
grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
block=tuple([ 512, 1, 1 ]),
args=[ n, input.data_ptr(), flow.data_ptr(), output.data_ptr() ]
)
elif input.is_cuda == False:
raise NotImplementedError()
# end
return output
# end
@staticmethod
def backward(self, gradOutput):
input, flow = self.saved_tensors
intSamples = input.shape[0]
intInputDepth, intInputHeight, intInputWidth = input.shape[1], input.shape[2], input.shape[3]
intFlowDepth, intFlowHeight, intFlowWidth = flow.shape[1], flow.shape[2], flow.shape[3]
assert(intFlowDepth == 2)
assert(intInputHeight == intFlowHeight)
assert(intInputWidth == intFlowWidth)
assert(gradOutput.is_contiguous() == True)
gradInput = input.new_zeros([ intSamples, intInputDepth, intInputHeight, intInputWidth ]) if self.needs_input_grad[0] == True else None
gradFlow = input.new_zeros([ intSamples, intFlowDepth, intFlowHeight, intFlowWidth ]) if self.needs_input_grad[1] == True else None
if input.is_cuda == True:
if gradInput is not None:
n = gradInput.nelement()
cupy_launch('kernel_Softsplat_updateGradInput', cupy_kernel('kernel_Softsplat_updateGradInput', {
'input': input,
'flow': flow,
'gradOutput': gradOutput,
'gradInput': gradInput,
'gradFlow': gradFlow
}))(
grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
block=tuple([ 512, 1, 1 ]),
args=[ n, input.data_ptr(), flow.data_ptr(), gradOutput.data_ptr(), gradInput.data_ptr(), None ]
)
# end
if gradFlow is not None:
n = gradFlow.nelement()
cupy_launch('kernel_Softsplat_updateGradFlow', cupy_kernel('kernel_Softsplat_updateGradFlow', {
'input': input,
'flow': flow,
'gradOutput': gradOutput,
'gradInput': gradInput,
'gradFlow': gradFlow
}))(
grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
block=tuple([ 512, 1, 1 ]),
args=[ n, input.data_ptr(), flow.data_ptr(), gradOutput.data_ptr(), None, gradFlow.data_ptr() ]
)
# end
elif input.is_cuda == False:
raise NotImplementedError()
# end
return gradInput, gradFlow
# end
# end
def FunctionSoftsplat(tenInput, tenFlow, tenMetric, strType):
assert(tenMetric is None or tenMetric.shape[1] == 1)
assert(strType in ['summation', 'average', 'linear', 'softmax'])
if strType == 'average':
tenInput = torch.cat([ tenInput, tenInput.new_ones(tenInput.shape[0], 1, tenInput.shape[2], tenInput.shape[3]) ], 1)
elif strType == 'linear':
tenInput = torch.cat([ tenInput * tenMetric, tenMetric ], 1)
elif strType == 'softmax':
tenInput = torch.cat([ tenInput * tenMetric.exp(), tenMetric.exp() ], 1)
# end
tenOutput = _FunctionSoftsplat.apply(tenInput, tenFlow)
if strType != 'summation':
tenOutput = tenOutput[:, :-1, :, :] / (tenOutput[:, -1:, :, :] + 0.0000001)
# end
return tenOutput
# end
class ModuleSoftsplat(torch.nn.Module):
def __init__(self, strType):
super(ModuleSoftsplat, self).__init__()
self.strType = strType
# end
def forward(self, tenInput, tenFlow, tenMetric):
return FunctionSoftsplat(tenInput, tenFlow, tenMetric, self.strType)
# end
# end
class quaternion:
def __init__(self, *args):
self.vec = [];
if len(args) == 0:
# default is a null rotation
self.s = 1.0
self.v = matrix([0.0, 0.0, 0.0])
elif len(args) == 4:
self.s = args[0];
self.v = mat(args[1:4])
else:
print("error")
return None
def __repr__(self):
return "%f <%f, %f, %f>" % (self.s, self.v[0, 0], self.v[0, 1], self.v[0, 2])
def tr2q(self, t):
# TR2Q Convert homogeneous transform to a unit-quaternion
#
# Q = tr2q(T)
#
# Return a unit quaternion corresponding to the rotational part of the
# homogeneous transform T.
qs = sqrt(trace(t) + 1) / 2.0
kx = t[2, 1] - t[1, 2] # Oz - Ay
ky = t[0, 2] - t[2, 0] # Ax - Nz
kz = t[1, 0] - t[0, 1] # Ny - Ox
if (t[0, 0] >= t[1, 1]) and (t[0, 0] >= t[2, 2]):
kx1 = t[0, 0] - t[1, 1] - t[2, 2] + 1 # Nx - Oy - Az + 1
ky1 = t[1, 0] + t[0, 1] # Ny + Ox
kz1 = t[2, 0] + t[0, 2] # Nz + Ax
add = (kx >= 0)
elif (t[1, 1] >= t[2, 2]):
kx1 = t[1, 0] + t[0, 1] # Ny + Ox
ky1 = t[1, 1] - t[0, 0] - t[2, 2] + 1 # Oy - Nx - Az + 1
kz1 = t[2, 1] + t[1, 2] # Oz + Ay
add = (ky >= 0)
else:
kx1 = t[2, 0] + t[0, 2] # Nz + Ax
ky1 = t[2, 1] + t[1, 2] # Oz + Ay
kz1 = t[2, 2] - t[0, 0] - t[1, 1] + 1 # Az - Nx - Oy + 1
add = (kz >= 0)
if add:
kx = kx + kx1
ky = ky + ky1
kz = kz + kz1
else:
kx = kx - kx1
ky = ky - ky1
kz = kz - kz1
kv = matrix([kx, ky, kz])
nm = linalg.norm(kv)
if nm == 0:
self.s = 1.0
self.v = matrix([0.0, 0.0, 0.0])
else:
self.s = qs
self.v = (sqrt(1 - qs ** 2) / nm) * kv
############### OPERATORS #########################################
# PLUS Add two quaternion objects
#
# Invoked by the + operator
#
# q1+q2 standard quaternion addition
def __add__(self, q):
'''
Return a new quaternion that is the element-wise sum of the operands.
'''
if isinstance(q, quaternion):
qr = quaternion()
qr.s = 0
qr.s = self.s + q.s
qr.v = self.v + q.v
return qr
else:
raise ValueError
# MINUS Subtract two quaternion objects
#
# Invoked by the - operator
#
# q1-q2 standard quaternion subtraction
def __sub__(self, q):
'''
Return a new quaternion that is the element-wise difference of the operands.
'''
if isinstance(q, quaternion):
qr = quaternion()
qr.s = 0
qr.s = self.s - q.s
qr.v = self.v - q.v
return qr
else:
raise ValueError
# q * q or q * const
def __mul__(self, q2):
'''
Quaternion product. Several cases are handled
- q * q quaternion multiplication
- q * c element-wise multiplication by constant
- q * v quaternion-vector multiplication q * v * q.inv();
'''
qr = quaternion();
if isinstance(q2, quaternion):
# Multiply unit-quaternion by unit-quaternion
#
# QQ = qqmul(Q1, Q2)
# decompose into scalar and vector components
s1 = self.s;
v1 = self.v
s2 = q2.s;
v2 = q2.v
# form the product
qr.s = s1 * s2 - v1 * v2.T
qr.v = s1 * v2 + s2 * v1 + cross(v1, v2)
elif type(q2) is matrix:
# Multiply vector by unit-quaternion
#
# Rotate the vector V by the unit-quaternion Q.
if q2.shape == (1, 3) or q2.shape == (3, 1):
qr = self * quaternion(q2) * self.inv()
return qr.v;
else:
raise ValueError;
else:
qr.s = self.s * q2
qr.v = self.v * q2
return qr
def __rmul__(self, c):
'''
Quaternion product. Several cases are handled
- c * q element-wise multiplication by constant
'''
qr = quaternion()
qr.s = self.s * c
qr.v = self.v * c
return qr
def __imul__(self, x):
'''
Quaternion in-place multiplication
- q *= q2
'''
if isinstance(x, quaternion):
s1 = self.s;
v1 = self.v
s2 = x.s
v2 = x.v
# form the product
self.s = s1 * s2 - v1 * v2.T
self.v = s1 * v2 + s2 * v1 + cross(v1, v2)
elif isscalar(x):
self.s *= x;
self.v *= x;
return self;
def __pow__(self, p):
'''
Quaternion exponentiation. Only integer exponents are handled. Negative
integer exponents are supported.
'''
# check that exponent is an integer
if not isinstance(p, int):
raise ValueError
qr = quaternion()
q = quaternion(self);
# multiply by itself so many times
for i in range(0, abs(p)):
qr *= q
# if exponent was negative, invert it
if p < 0:
qr = qr.inv()
return qr
def double(self):
"""Return the quaternion as 4-element vector.
@rtype: 4-vector
@return: the quaternion elements
"""
return concatenate((mat(self.s), self.v), 1) # Debug present
def unit_Q(self):
'''
Function asserts a quaternion Q to be a unit quaternion
s is unchanged as the angle of rotation is assumed to be controlled by the user
v is cast into a unit vector based on |v|^2 = 1 - s^2 and dividing by |v|
'''
# Still have some errors with linalg.norm(self.v)
qr = quaternion()
try:
nm = linalg.norm(self.v) / sqrt(1 - pow(self.s, 2))
qr.s = self.s
qr.v = self.v / nm
except:
qr.s = self.s
qr.v = self.v
return qr
def interpolate(Q1, Q2, r):
q1 = Q1.double()
q2 = Q2.double()
theta = acos(q1 * q2.T)
q = []
count = 0
if isscalar(r):
if r < 0 or r > 1:
raise Exception('R out of range')
if theta == 0:
q = quaternion(Q1)
else:
Qq = np.copy((sin((1 - r) * theta) * q1 + sin(r * theta) * q2) / sin(theta))
q = quaternion(Qq[0, 0], Qq[0, 1], Qq[0, 2], Qq[0, 3])
else:
for R in r:
if theta == 0:
qq = Q1
else:
qq = quaternion((sin((1 - R) * theta) * q1 + sin(R * theta) * q2) / sin(theta))
q.append(qq)
return q
def mat2euler(M, cy_thresh=None):
M = np.asarray(M)
if cy_thresh is None:
try:
cy_thresh = np.finfo(M.dtype).eps * 4
except ValueError:
cy_thresh = _FLOAT_EPS_4
r11, r12, r13, r21, r22, r23, r31, r32, r33 = M.flat
# cy: sqrt((cos(y)*cos(z))**2 + (cos(x)*cos(y))**2)
cy = math.sqrt(r33*r33 + r23*r23)
if cy > cy_thresh: # cos(y) not close to zero, standard form
z = math.atan2(-r12, r11) # atan2(cos(y)*sin(z), cos(y)*cos(z))
y = math.atan2(r13, cy) # atan2(sin(y), cy)
x = math.atan2(-r23, r33) # atan2(cos(y)*sin(x), cos(x)*cos(y))
else: # cos(y) (close to) zero, so x -> 0.0 (see above)
# so r21 -> sin(z), r22 -> cos(z) and
z = math.atan2(r21, r22)
y = math.atan2(r13, cy) # atan2(sin(y), cy)
x = 0.0
return z, y, x
def quat2euler(q):
import nibabel.quaternions as nq
return mat2euler(nq.quat2mat(q))
def linear_translation(A, B, T):
'''
Interpolates between 2 start points A an dB linearly
Input:
A - Start point
B - Ending point
T - intermediate points within a range from 0 - 1, 0 representing point A and 1 representing point B
Output
C - intermediate pose as an array
'''
V_AB = B -A
C = A + T*(V_AB)
return C
def qvec2rotmat(qvec):
return np.array([
[1 - 2 * qvec[2]**2 - 2 * qvec[3]**2,
2 * qvec[1] * qvec[2] - 2 * qvec[0] * qvec[3],
2 * qvec[3] * qvec[1] + 2 * qvec[0] * qvec[2]],
[2 * qvec[1] * qvec[2] + 2 * qvec[0] * qvec[3],
1 - 2 * qvec[1]**2 - 2 * qvec[3]**2,
2 * qvec[2] * qvec[3] - 2 * qvec[0] * qvec[1]],
[2 * qvec[3] * qvec[1] - 2 * qvec[0] * qvec[2],
2 * qvec[2] * qvec[3] + 2 * qvec[0] * qvec[1],
1 - 2 * qvec[1]**2 - 2 * qvec[2]**2]])
def rotmat2qvec(R):
Rxx, Ryx, Rzx, Rxy, Ryy, Rzy, Rxz, Ryz, Rzz = R.flat
K = np.array([
[Rxx - Ryy - Rzz, 0, 0, 0],
[Ryx + Rxy, Ryy - Rxx - Rzz, 0, 0],
[Rzx + Rxz, Rzy + Ryz, Rzz - Rxx - Ryy, 0],
[Ryz - Rzy, Rzx - Rxz, Rxy - Ryx, Rxx + Ryy + Rzz]]) / 3.0
eigvals, eigvecs = np.linalg.eigh(K)
qvec = eigvecs[[3, 0, 1, 2], np.argmax(eigvals)]
if qvec[0] < 0:
qvec *= -1
return qvec
def linear_pose_interp(A_trans, A_rot, B_trans, B_rot, T):
track = {'lin': [], 'rot': []}
q_a = rotmat2qvec(A_rot)
q_b = rotmat2qvec(B_rot)
QA = quaternion(q_a[0], q_a[1], q_a[2], q_a[3])
QB = quaternion(q_b[0], q_b[1], q_b[2], q_b[3])
track['lin'] = linear_translation(A_trans, B_trans, T).tolist()
q = interpolate(QA, QB, T)
track['rot'] = [q.s] + (q.v).tolist()[0] # List of quaternion [w x y z]
return qvec2rotmat(track['rot']), np.array(track['lin'])
# INFERENCE = True
def splat_rgb_img(ret, ratio, R_w2t, t_w2t, j, H, W, focal, fwd_flow):
raw_rgba_s = torch.cat([ret['raw_rgb'], ret['raw_alpha'].unsqueeze(-1)], dim=-1)
raw_rgba = raw_rgba_s[:, :, j, :].permute(2, 0, 1).unsqueeze(0).contiguous().cuda()
pts_ref = ret['pts_ref'][:, :, j, :3]
pts_ref_e_G = NDC2Euclidean(pts_ref, H, W, focal)
if fwd_flow:
pts_post = pts_ref + ret['raw_sf_ref2post'][:, :, j, :]
else:
pts_post = pts_ref + ret['raw_sf_ref2prev'][:, :, j, :]
pts_post_e_G = NDC2Euclidean(pts_post, H, W, focal)
pts_mid_e_G = (pts_post_e_G - pts_ref_e_G) * ratio + pts_ref_e_G
pts_mid_e_local = se3_transform_points(pts_mid_e_G,
R_w2t.unsqueeze(0).unsqueeze(0),
t_w2t.unsqueeze(0).unsqueeze(0))
pts_2d_mid = perspective_projection(pts_mid_e_local, H, W, focal)
xx, yy = torch.meshgrid(torch.linspace(0, W - 1, W), torch.linspace(0, H - 1, H))
xx = xx.t()
yy = yy.t()
pts_2d_original = torch.stack([xx, yy], -1)
flow_2d = pts_2d_mid - pts_2d_original
flow_2d = flow_2d.permute(2, 0, 1).unsqueeze(0).contiguous().cuda()
splat_raw_rgba_dy = FunctionSoftsplat(tenInput=raw_rgba,
tenFlow=flow_2d,
tenMetric=None,
strType='average')
# splatting for static nerf
pts_rig_e_local = se3_transform_points(pts_ref_e_G,
R_w2t.unsqueeze(0).unsqueeze(0),
t_w2t.unsqueeze(0).unsqueeze(0))
pts_2d_rig = perspective_projection(pts_rig_e_local, H, W, focal)
flow_2d_rig = pts_2d_rig - pts_2d_original
flow_2d_rig = flow_2d_rig.permute(2, 0, 1).unsqueeze(0).contiguous().cuda()
raw_rgba_rig = torch.cat([ret['raw_rgb_rigid'], ret['raw_alpha_rigid'].unsqueeze(-1)], dim=-1)
raw_rgba_rig = raw_rgba_rig[:, :, j, :].permute(2, 0, 1).unsqueeze(0).contiguous().cuda()
splat_raw_rgba_rig = FunctionSoftsplat(tenInput=raw_rgba_rig,
tenFlow=flow_2d_rig,
tenMetric=None,
strType='average')
splat_alpha_dy = splat_raw_rgba_dy[0, 3:4, :, :]
splat_rgb_dy = splat_raw_rgba_dy[0, 0:3, :, :]
splat_alpha_rig = splat_raw_rgba_rig[0, 3:4, :, :]
splat_rgb_rig = splat_raw_rgba_rig[0, 0:3, :, :]
return splat_alpha_dy, splat_rgb_dy, splat_alpha_rig, splat_rgb_rig
def render_no_fixed(disps, render_poses, bt_poses,
hwf, chunk, render_kwargs,
gt_imgs=None, savedir=None,
render_factor=0, target_idx=10):
# import scipy.io
start_frame = target_idx - 6.
end_frame = target_idx + 6.
H, W, focal = hwf
if render_factor != 0:
# Render downsampled for speed
H = H // render_factor
W = W // render_factor
focal = focal / render_factor
t = time.time()
count = 0
save_img_dir = os.path.join(savedir, 'images')
os.makedirs(save_img_dir, exist_ok=True)
print("##########", target_idx, start_frame, end_frame)
for i, cur_time in enumerate(np.linspace(start_frame, end_frame, 200 + 1).tolist()):
flow_time = int(np.floor(cur_time))
ratio = cur_time - np.floor(cur_time)
print('cur_time ', i, cur_time, ratio)
t = time.time()
int_rot, int_trans = linear_pose_interp(render_poses[flow_time, :3, 3],
render_poses[flow_time, :3, :3],
render_poses[flow_time + 1, :3, 3],
render_poses[flow_time + 1, :3, :3],
ratio)
int_poses = np.concatenate((int_rot, int_trans[:, np.newaxis]), 1)
int_poses = np.concatenate([int_poses[:3, :4], np.array([0.0, 0.0, 0.0, 1.0])[np.newaxis, :]], axis=0)
int_poses = np.dot(int_poses, bt_poses[i])
render_pose = torch.Tensor(int_poses).to(device)
R_w2t = render_pose[:3, :3].transpose(0, 1)
t_w2t = -torch.matmul(R_w2t, render_pose[:3, 3:4])
num_img = gt_imgs.shape[0]
img_idx_embed_1 = (np.floor(cur_time)) / float(num_img) * 2. - 1.0
img_idx_embed_2 = (np.floor(cur_time) + 1) / float(num_img) * 2. - 1.0
print('img_idx_embed_1 ', cur_time, img_idx_embed_1)
ret1 = render_sm(img_idx_embed_1, 0,
num_img,
H, W, focal,
chunk=1024 * 16,
c2w=render_pose,
**render_kwargs)
ret2 = render_sm(img_idx_embed_2, 0,
num_img,
H, W, focal,
chunk=1024 * 16,
c2w=render_pose,
**render_kwargs)
T_i = torch.ones((1, H, W))
final_rgb = torch.zeros((3, H, W))
num_sample = ret1['raw_rgb'].shape[2]
# final_depth = torch.zeros((1, H, W))
z_vals = ret1['z_vals']
for j in range(0, num_sample):
splat_alpha_dy_1, splat_rgb_dy_1, \
splat_alpha_rig_1, splat_rgb_rig_1 = splat_rgb_img(ret1, ratio, R_w2t, t_w2t,
j, H, W, focal, True)
splat_alpha_dy_2, splat_rgb_dy_2, \
splat_alpha_rig_2, splat_rgb_rig_2 = splat_rgb_img(ret2, 1. - ratio, R_w2t, t_w2t,
j, H, W, focal, False)
final_rgb += T_i * (splat_alpha_dy_1 * splat_rgb_dy_1 + \
splat_alpha_rig_1 * splat_rgb_rig_1) * (1.0 - ratio)
final_rgb += T_i * (splat_alpha_dy_2 * splat_rgb_dy_2 + \
splat_alpha_rig_2 * splat_rgb_rig_2) * ratio
# splat_alpha = splat_alpha1 * (1. - ratio) + splat_alpha2 * ratio
# final_rgb += T_i * (splat_alpha1 * (1. - ratio) * splat_rgb1 + splat_alpha2 * ratio * splat_rgb2)
alpha_1_final = (1.0 - (1. - splat_alpha_dy_1) * (1. - splat_alpha_rig_1)) * (1. - ratio)
alpha_2_fianl = (1.0 - (1. - splat_alpha_dy_2) * (1. - splat_alpha_rig_2)) * ratio
alpha_final = alpha_1_final + alpha_2_fianl
# final_depth += T_i * (alpha_final) * z_vals[..., j]
T_i = T_i * (1.0 - alpha_final + 1e-10)
filename = os.path.join(savedir, 'slow-mo_%03d.jpg' % (i))
rgb8 = to8b(final_rgb.permute(1, 2, 0).cpu().numpy())
new_x = rgb8.shape[0] // 2 * 2
new_y = rgb8.shape[1] // 2 * 2
rgb8 = rgb8[:new_x, :new_y, :]
# final_depth = torch.clamp(final_depth/percentile(final_depth, 98), 0., 1.)
# depth8 = to8b(final_depth.permute(1, 2, 0).repeat(1, 1, 3).cpu().numpy())
filename = os.path.join(save_img_dir, '{:03d}.jpg'.format(i))
imageio.imwrite(filename, rgb8)
def render_fixed_view(ref_c2w, num_img,
hwf, chunk, render_kwargs,
gt_imgs=None, savedir=None,
render_factor=0,
target_idx=5):
H, W, focal = hwf
if render_factor != 0:
# Render downsampled for speed
H = H // render_factor
W = W // render_factor
focal = focal / render_factor
H, W, focal = hwf
if render_factor != 0:
# Render downsampled for speed
H = H // render_factor
W = W // render_factor
focal = focal / render_factor
t = time.time()
count = 0
for i, cur_time in enumerate(np.linspace(target_idx - 8., target_idx + 8., 160 + 1).tolist()):
ratio = cur_time - np.floor(cur_time)
render_pose = ref_c2w[:3, :4] # render_poses[i % num_frame_per_cycle][:3,:4]
R_w2t = render_pose[:3, :3].transpose(0, 1)
t_w2t = -torch.matmul(R_w2t, render_pose[:3, 3:4])
num_img = gt_imgs.shape[0]
img_idx_embed_1 = (np.floor(cur_time)) / float(num_img) * 2. - 1.0
img_idx_embed_2 = (np.floor(cur_time) + 1) / float(num_img) * 2. - 1.0
print('render lock camera time ', i, cur_time, ratio, time.time() - t)
t = time.time()
ret1 = render_sm(img_idx_embed_1, 0,
num_img,
H, W, focal,
chunk=1024 * 16,
c2w=render_pose,
**render_kwargs)
ret2 = render_sm(img_idx_embed_2, 0,
num_img,
H, W, focal,
chunk=1024 * 16,
c2w=render_pose,
**render_kwargs)
T_i = torch.ones((1, H, W))
final_rgb = torch.zeros((3, H, W))
num_sample = ret1['raw_rgb'].shape[2]
for j in range(0, num_sample):
splat_alpha_dy_1, splat_rgb_dy_1, \
splat_alpha_rig_1, splat_rgb_rig_1 = splat_rgb_img(ret1, ratio, R_w2t,
t_w2t, j, H, W,
focal, True)
splat_alpha_dy_2, splat_rgb_dy_2, \
splat_alpha_rig_2, splat_rgb_rig_2 = splat_rgb_img(ret2, 1. - ratio, R_w2t,
t_w2t, j, H, W,
focal, False)
final_rgb += T_i * (splat_alpha_dy_1 * splat_rgb_dy_1 + \
splat_alpha_rig_1 * splat_rgb_rig_1) * (1.0 - ratio)
final_rgb += T_i * (splat_alpha_dy_2 * splat_rgb_dy_2 + \
splat_alpha_rig_2 * splat_rgb_rig_2) * ratio
alpha_1_final = (1.0 - (1. - splat_alpha_dy_1) * (1. - splat_alpha_rig_1)) * (1. - ratio)
alpha_2_fianl = (1.0 - (1. - splat_alpha_dy_2) * (1. - splat_alpha_rig_2)) * ratio
alpha_final = alpha_1_final + alpha_2_fianl
T_i = T_i * (1.0 - alpha_final + 1e-10)
filename = os.path.join(savedir, '%03d.jpg' % (i))
rgb8 = to8b(final_rgb.permute(1, 2, 0).cpu().numpy())
new_x = rgb8.shape[0] // 2 * 2
new_y = rgb8.shape[1] // 2 * 2
rgb8 = rgb8[:new_x, :new_y, :]
#start_y = (rgb8.shape[1] - 512) // 2
You can’t perform that action at this time.
