forked from sarafridov/plenoxels
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp4_copy2.py
1497 lines (1257 loc) · 63 KB
/
p4_copy2.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
from ast import Assert
import os
import json
from argparse import ArgumentParser
from re import split
# from tkinter.messagebox import NO
import numpy as np
from tqdm import tqdm
import imageio
from PIL import Image
import time
import config as config
import config2 as config2
import math
import tifffile
np.random.seed(0)
def get_freer_gpu():
os.system('nvidia-smi -q -d Memory | grep Free >tmp')
memory_available = [int(x.split()[2]) for i, x in enumerate(open('tmp', 'r').readlines()) if i % 3 == 0]
print(f"memory available = {memory_available}")
print(f"np.argmax() = {np.argmax(memory_available)}")
return np.argmax(memory_available)
gpu = get_freer_gpu()
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu)
print(f'gpu is {gpu}')
# Import jax only after setting the visible gpu
import jax
print(f"jax devices is {jax.devices()}")
import jax.numpy as jnp
from functools import partial
import plenoxel_og_copy2
# from jax.ops import index, index_update, index_add
from jax.lib import xla_bridge
print(xla_bridge.get_backend().platform)
if __name__ != "__main__":
os.environ['XLA_PYTHON_CLIENT_MEM_FRACTION'] = '.001'
flags = ArgumentParser()
flags.add_argument(
"--data_dir", '-d',
type=str,
# default='/data/datasets/', #for corrected projections and spike
default='/home/datasets/',
# default = '/data/fabriziov/ct_scans/organSegs/', #for orgsegs
help="Dataset directory e.g. ct_scans/"
)
flags.add_argument(
"--expname",
type=str,
# default="experiment",
# default = "corr_proj_img", # for the Corrected projections
# default = "source_proj_img", # for the source projections
# default = "jerry_gt_img", # for jerry_gt (fake projections)
# default = "newjerry2",
# default = 'spike_img', #in tmux 1
# default = 'fullradius9_test_spike_tiff_res900_epoch1_tv0.001_nonneg_views720',
# default = 'semi_easy_synthetic_nonnegative',
default = 'shepp_fifthdensity/nonlinear_1_nonnegative',
# default = 'test_jerry_tiff_res64_epoch4_split2_tv0.001_nonneg',
# default = 'organSegs_img1', # For organ Segmentations dataset
help="Experiment name."
)
flags.add_argument(
"--scene",
type=str,
# default='Corrected_Projections/', #for jerry corrected projections
# default='scans/', # For organ Segmentations
# default='spike-cbct/', # For Spike
default='ct_shepp',
# default = 'scans/', #for jerry
help="Name of the scene."
)
flags.add_argument(
"--log_dir",
type=str,
default='jax_logs/',
help="Directory to save outputs."
)
flags.add_argument(
"--resolution",
type=int,
default=128, #900 for spike
help="Grid size."
)
flags.add_argument(
"--ini_rgb",
type=float,
default=0.0,
help="Initial harmonics value in grid."
)
flags.add_argument(
"--ini_sigma",
type=float,
default=0.1,
help="Initial sigma value in grid."
)
flags.add_argument(
"--radius", # affects resolution
type=float,
default=5, #9, # 6 for jerry and spike and 1.3 for orgSegs # 5 is for synthetic ct dataset
help="Grid radius. 1.3 works well on most scenes, but ship requires 1.5"
)
flags.add_argument(
"--harmonic_degree",
type=int,
default=-1,
help="Degree of spherical harmonics. Supports 0, 1, 2, 3, 4."
)
flags.add_argument(
'--num_epochs',
type=int,
default=1,
help='Epochs to train for.'
)
flags.add_argument(
'--render_interval',
type=int,
default = 30, #change to 1 to get the projection images
help='Render images during test/val step every x images.'
)
flags.add_argument(
'--val_interval',
type=int,
default=2,
help='Run test/val step every x epochs.'
)
flags.add_argument(
'--lr_rgb',
type=float,
default=None,
help='SGD step size for rgb. Default chooses automatically based on resolution.'
)
flags.add_argument(
'--lr_sigma',
type=float,
default=0.001, #0.001 for orgSegs and jerry, but now trying 0.01 for jerry in tmux one
# default=0.01, # for jerry has to be less than 0.05, currently trying 0.005 in tmux 1 & 0.001 in tmux 3
help='SGD step size for sigma. Default chooses automatically based on resolution.'
)
flags.add_argument(
'--physical_batch_size',
type=int,
default=3000,
help='Number of rays per batch, to avoid OOM.'
)
flags.add_argument(
'--logical_batch_size',
type=int,
default=3000,
help='Number of rays per optimization batch. Must be a multiple of physical_batch_size.'
)
flags.add_argument(
'--jitter',
type=float,
default=0.0,
help='Take samples that are jittered within each voxel, where values are computed with trilinear interpolation. Parameter controls the std dev of the jitter, as a fraction of voxel_len.'
)
flags.add_argument(
'--uniform',
type=float,
default=0.5,
help='Initialize sample locations to be uniformly spaced at this interval (as a fraction of voxel_len), rather than at voxel intersections (default if uniform=0).'
)
flags.add_argument(
'--occupancy_penalty',
type=float,
default=0.0,
help='Penalty in the loss term for occupancy; encourages a sparse grid.'
)
flags.add_argument(
'--reload_epoch',
type=int,
default=None,
help='Epoch at which to resume training from a saved model.'
)
flags.add_argument(
'--save_interval',
type=int,
default=1,
help='Save the grid checkpoints after every x epochs.'
)
flags.add_argument(
'--prune_epochs',
type=int,
nargs='+',
default=[],
help='List of epoch numbers when pruning should be done.'
)
flags.add_argument(
'--prune_method',
type=str,
default='weight',
help='Weight or sigma: prune based on contribution to training rays, or opacity.'
)
flags.add_argument(
'--prune_threshold',
type=float,
default=0.001,
help='Threshold for pruning voxels (either by weight or by sigma).'
)
flags.add_argument(
'--split_epochs',
type=int,
nargs='+',
default=[], # Try w/ 0, 1, or 2
help='List of epoch numbers when splitting should be done.'
)
flags.add_argument(
'--interpolation',
type=str,
default='trilinear',
help='Type of interpolation to use. Options are constant, trilinear, or tricubic.'
)
flags.add_argument(
'--nv',
action='store_true',
help='Use the Neural Volumes rendering formula instead of the Max (NeRF) rendering formula.'
)
flags.add_argument(
'--ct',
action='store_true',
help='Optimize sigma only, based on the gt alpha channel.'
)
flags.add_argument(
'--nonnegative',
action='store_true',
help='Clip stored grid values to be nonnegative. Intended for ct.'
)
# flags.add_argument(
# '--linear',
# action='store_true',
# help='Use a linear version of the forward model. Intended for ct.'
# )
flags.add_argument(
'--num_views',
type=int,
default=20,
help='Number of CT projections to train with. Only used with Jerry-CBCT.'
)
flags.add_argument(
'--cut_cube',
action='store_true',
help='cuts the cube in half and halves the radius aswell'
)
FLAGS = flags.parse_args()
data_dir = FLAGS.data_dir + FLAGS.scene
radius = FLAGS.radius
np.random.seed(0)
# This is where I would call for a function or a seperate file that would be able to make a projection matrix for the new datasets
# the plenoptimize_static file has a def get_jerry(root) function that reads the projection numbers from a csv file.
def get_ct_pepper(root, stage):
# assert FLAGS.ct
# all_c2w = []
all_gt = []
print('LOAD DATA', root)
all_c2w, num_proj = config.ct(root) # Get the all_c2w array and the number of projections from the ct function in the config file
print(all_c2w.shape)
# projection_matrices = np.genfromtxt(os.path.join(root, 'proj_mat.csv'), delimiter=',') # [719, 12]
# Loop through the number of projections
for i in range(1, num_proj+1):
index = "{:04d}".format(i)
im_gt = imageio.imread(os.path.join('/data/fabriziov/ct_scans/pepper/scans', f'Pepper_{index}.tif')).astype(np.float32) / 255.0
im_gt = 1 - im_gt / np.max(im_gt)
# print(f'im_gt ranges from {np.min(im_gt)} to {np.max(im_gt)}')
all_gt.append(im_gt)
# focal = 75 # cm
focal = 600000
all_gt = np.asarray(all_gt)
mask = np.zeros(len(all_c2w))
# n_train = 25
# n_test = 10
# idx = np.random.choice(len(all_c2w), n_train + n_test)
idx = np.random.choice(len(all_c2w), 25, replace = False)
# train_idx = idx[0:n_train]
# test_idx = idx[n_train:]
# # mask = np.zeros_like(a)
mask[idx] = 1
mask = mask.astype(bool)
if stage == 'train':
all_gt = all_gt[mask]
print(f'all_gt[mask] is {all_gt.shape}')
all_c2w = all_c2w[mask]
print(f'all_c2w[mask] is {all_c2w.shape}')
# all_gt = all_gt[train_idx]
# all_c2w = all_c2w[train_idx]
elif stage == 'test':
all_gt = all_gt[~mask]
all_c2w = all_c2w[~mask]
# all_gt = all_gt[test_idx]
# all_c2w = all_c2w[test_idx]
print(f'all_gt has shape {all_gt.shape}')
return focal, all_c2w, all_gt
def get_ct_pomegranate(root, stage):
all_gt = []
print('LOAD DATA', root)
all_c2w, num_proj = config.ct(root) # Get the all_c2w array and the number of projections from the ct function in the config file
# Loop through the number of projections
for i in range(1, num_proj+1):
index = "{:04d}".format(i)
im_gt = imageio.imread(os.path.join('/data/fabriziov/ct_scans/pomegranate/scans', f'Pomegranate_{index}.tif')).astype(np.float32) / 255.0
im_gt = 1 - im_gt / np.max(im_gt)
all_gt.append(im_gt)
focal = 600000
all_gt = np.asarray(all_gt)
mask = np.zeros(len(all_c2w))
# n_train = 50
# n_test = 10
# idx = np.random.choice(len(all_c2w), n_train + n_test)
idx = np.random.choice(len(all_c2w), 50, replace = False)
# train_idx = idx[0:n_train]
# test_idx = idx[n_train:]
# # mask = np.zeros_like(a)
mask[idx] = 1
mask = mask.astype(bool)
if stage == 'train':
all_gt = all_gt[mask]
all_c2w = all_c2w[mask]
elif stage == 'test':
all_gt = all_gt[~mask]
all_c2w = all_c2w[~mask]
return focal, all_c2w, all_gt
def get_ct_organSegs(root, stage):
all_gt = []
print('LOAD DATA', root)
all_c2w, num_proj = config2.ct(root) # Get the all_c2w array and the number of projections from the ct function in the config file
print(f'number of projections: {num_proj}')
print(f'all_c2w has shape {all_c2w.shape}')
print(f'all_c2w has size {all_c2w.size}')
for i in range(0, num_proj):
# im_gt = 1 - imageio.imread(filenames[i]).astype(np.float32) / 255.0
# im_gt = im_gt - np.min(im_gt) # Normalize so empty space is always zero
index = "{:04d}".format(i)
im_gt = imageio.imread(os.path.join('/data/fabriziov/ct_scans/organSegs/scans', f'{index}_0001.png')).astype(np.float32) / 255.0
# im_gt = 1 - im_gt / np.max(im_gt)
all_gt.append(im_gt[...,0])
# all_gt.append(im_gt)
# focal = 75 # cm
# focal = 2.85 / 0.024
# focal = 500
focal = 750
# focal = 300000
all_gt = np.asarray(all_gt)
print(f'all_gt has shape {all_gt.shape}')
mask = np.zeros(len(all_c2w))
idx = np.random.choice(len(all_c2w), 100, replace = False)
mask[idx] = 1
mask = mask.astype(bool)
# train and test can be commented out ot get the full 360 ground truth projections
if stage == 'train':
all_gt = all_gt[mask]
all_c2w = all_c2w[mask]
elif stage == 'test':
all_gt = all_gt[~mask]
all_c2w = all_c2w[~mask]
print(f'all_gt has shape {all_gt.shape}')
return focal, all_c2w, all_gt
# This is a dataloader for the ct datasets
def get_ct_jerry(root, stage):
all_gt = []
all_c2w =[]
print('LOAD DATA', root)
# all_c2w, num_proj = config2.ct(root) # Get the all_c2w array and the number of projections from the ct function in the config file
# all_c2w, num_proj = config2.ct('/data/datasets/jerry-cbct/projections/') # Source
all_c2w, num_proj = config2.ct('/data/sfk/plenoxel-ct/jerry_gt') #might have ran tmux3 with source instead of this one
# proj_mat = np.genfromtxt(os.path.join('/data/datasets/jerry-cbct/', 'proj_mat.csv'), delimiter=',')
print(f'number of projections: {num_proj}')
print(f'all_c2w has shape {all_c2w.shape}')
print(f'all_c2w has size {all_c2w.size}')
for i in range(0, num_proj):
# im_gt = 1 - imageio.imread(filenames[i]).astype(np.float32) / 255.0
# im_gt = im_gt - np.min(im_gt) # Normalize so empty space is always zero
index = "{:04d}".format(i)
# try with the reprojections
# im_gt = imageio.imread(os.path.join('/data/datasets/Corrected_Projections', f'Cor_Proj{index}.png')).astype(np.float32) / 255.0
# im_gt = imageio.imread(os.path.join('/data/datasets/jerry-cbct/projections', f'Source_Projections{index}.png')).astype(np.float32) / 255.0
im_gt = imageio.imread(os.path.join('/data/sfk/plenoxel-ct/jerry_gt', f'{index}_0001.png')).astype(np.float32) / 255.0
# im_gt = 1 - im_gt / np.max(im_gt)
# im_gt = 1 - im_gt
# w2c = np.reshape(num_proj[i], (3,4))
# w2c[:,-1] = (w2c[:,-1] - [400, 220, 200])
# c2w = np.linalg.inv(np.concatenate([w2c, [[0,0,0,1]]], axis=0))
all_gt.append(im_gt[..., 0])
# all_gt.append(im_gt)
# all_gt = all_gt[15:]
# all_c2w = all_c2w[15:]
# focal = 50
# focal = 75 # cm
# focal = 11
# focal = 2.85 / 0.024 # no
# focal = 250
# focal = 500 # meh
# focal = 750
# focal = 1187.5
focal = 2375
# focal = 11875 # do not use
# focal = 2000
# focal = 600000
# focal = 1000000
all_gt = np.asarray(all_gt)
print(f'all_gt has shape {all_gt.shape}')
# all_gt = np.asarray(all_c2w)
mask = np.zeros(len(all_c2w))
idx = np.random.choice(len(all_c2w), 100, replace = False) #tmux one
# idx = np.random.choice(len(all_c2w), 50, replace = False) #tmux two
mask[idx] = 1
mask = mask.astype(bool)
print(f'all_gt has shape {all_gt.shape}')
# train and test can be commented out ot get the full 360 ground truth projections
if stage == 'train':
all_gt = all_gt[mask]
all_c2w = all_c2w[mask]
elif stage == 'test':
all_gt = all_gt[~mask]
all_c2w = all_c2w[~mask]
# all_gt = all_gt[15:]
# all_c2w = all_c2w[15:]
print(f'all_gt has shape {all_gt.shape}')
return focal, all_c2w, all_gt
def get_ct_jerry2(root, stage, max_projections, xoff, yoff, zoff):
all_w2c = []
all_gt = []
print('LOAD DATA', root)
# Would be good to test this for Jerry and Spike
projection_matrices = np.genfromtxt(os.path.join('/home/fabriz/data/jerry/', 'proj_mat_jerry.csv'), delimiter=',') # [719, 12]
print(f'proj mat len is {len(projection_matrices)}')
#Traslation matrix along x,y,z
Tz = np.matlib.zeros((4,4))
Tz[0,0]=1.0
Tz[1,1]=1.0
Tz[2,2]=1.0
Tz[3,3]=1.0
Tz[0,3]=-xoff #test
Tz[1,3]=-yoff #test
Tz[2,3]=-zoff #test
# tif_proj = tifffile.imread('/data/datasets/jerry_tiff/Source_Projections.tif')
tif_proj = tifffile.imread('/home/fabriz/data/jerry/jerry_corr_src_proj.tif')
# reads #max_projections projection images
for i in range(len(projection_matrices)-1):
index = "{:04d}".format(i)
# im_gt = imageio.imread(os.path.join('/data/datasets/newJerryProj', f'NewJerryProj_{index}.png')).astype(np.float32) / 255.0
# im_gt = imageio.imread(os.path.join('/data/datasets/New_Corrected_Projections', f'New_Cor_Proj{index}.png')).astype(np.float32) / 255.0
im_gt = tif_proj[i,:,:]
im_gt = 1 - im_gt
# projection matrices P_(3,4)
w2c = np.reshape(projection_matrices[i], (3,4))
w2c = np.matmul(w2c,Tz) #applico una traslazione per centrate il volume
#w2c[:,-1] = (w2c[:,-1] - [400, 220, 200])
all_w2c.append(w2c)
all_gt.append(im_gt)
all_gt = np.asarray(all_gt)
all_w2c = np.asarray(all_w2c)
focal = 100 # 150 in tmux one, 100 in tmux two
mask = np.zeros(len(all_w2c))
print(f'max is {len(all_w2c)}')
idx = np.random.choice(len(all_w2c), max_projections, replace = False) # Just look at a subset of projections, to save time/memory for debuggin
mask[idx] = 1
mask = mask.astype(bool)
# train and test can be commented out to get the full 360 ground truth projections
if stage == 'train':
all_gt = all_gt[mask]
all_w2c = all_w2c[mask]
elif stage == 'test':
all_gt = all_gt[~mask]
all_w2c = all_w2c[~mask]
return focal, all_w2c,all_gt
def get_ct_spike(root, stage):
# assert FLAGS.ct
all_c2w = []
all_gt = []
print('using spike')
print('LOAD DATA', root)
# filenames = glob.glob(os.path.join(os.path.join(root, 'projections'), '*.png')) # only has 718 projections
projection_matrices = np.genfromtxt(os.path.join('/data/datasets/spike-cbct/', 'proj_mat_720frames.csv'), delimiter=',') # [719, 12]
for i in range(len(projection_matrices)-1):
# for i in range (360):
# im_gt = 1 - imageio.imread(filenames[i]).astype(np.float32) / 255.0
# im_gt = im_gt - np.min(im_gt) # Normalize so empty space is always zero
index = "{:04d}".format(i)
# im_gt = imageio.imread(os.path.join('./jerry_gt', f'{index}_0001.png')).astype(np.float32) / 255.0
im_gt = imageio.imread(os.path.join('/data/datasets/spike-cbct/spike720', f'Spike92_8_16_33_proj{index}.png')).astype(np.float32) / 255.0
# im_gt = imageio.imread(os.path.join('/data/sfk/plenoxel-ct/jerry_gt', f'{index}_0001.png')).astype(np.float32) / 255.0 #Jerry gt
# im_gt = imageio.imread(os.path.join('/data/datasets/Corrected_Projections', f'Cor_Proj{index}.png')).astype(np.float32) / 255.0 # Corrected projections
# im_gt = imageio.imread(filenames[i]).astype(np.float32) / 255.0
# im_gt = -np.log(np.where(im_gt > 1/255., im_gt, 1/255.))
# im_gt = jnp.concatenate([im_gt[...,np.newaxis], jnp.zeros((im_gt.shape[0], im_gt.shape[1], 2))], -1)
im_gt = 1 - im_gt
w2c = np.reshape(projection_matrices[i], (3,4))
# w2c[:,-1] = (w2c[:,-1] - [400, 220, 200])
# w2c[:,-1] = (w2c[:,-1] - [510, 800, -60])
# w2c[:,-1] = (w2c[:,-1] - [465, 750, 200])
# w2c[:,-1] = (w2c[:,-1] - [375, 745, 150])
# w2c[:,-1] = (w2c[:,-1] - [300, 300, 300])
# 654 664 -> 650 670 -> 550 -770
# w2c[:,-1] = (w2c[:,-1] - [520, 800, 200])
# w2c[:,-1] = (w2c[:,-1] - [560, 840, 200])
# w2c[:,-1] = (w2c[:,-1] - [400, 840, 0]) #moved to the right instead
# w2c[:,-1] = (w2c[:,-1] - [400, 840, 100]) #moves to the left
# w2c[:,-1] = (w2c[:,-1] - [500, 900, 100]) #centered first pic
# w2c[:,-1] = (w2c[:,-1] - [300, 700, 30]) # moved the image down
# w2c[:,-1] = (w2c[:,-1] - [400, 700, 40]) # looks fine until image 240 (moves to right)
# w2c[:,-1] = (w2c[:,-1] - [400, 700, 45]) #tried with focal = 2.85 / 0.024 in tmux2
w2c[:,-1] = (w2c[:,-1] - [300, 700, 45]) # tmux1 w/ 50 and now tmux2 w/ 25
# w2c[:,-1] = (w2c[:,-1] - [500, 200, 100])# tmux 3
# w2c[:,-1] = (w2c[:,-1] - [0, 600, 600])
# invert world -> camera to get camera -> world
c2w = np.linalg.inv(np.concatenate([w2c, [[0,0,0,1]]], axis=0))
all_c2w.append(c2w)
# all_gt.append(im_gt[..., 0])
all_gt.append(im_gt)
# focal = 1 # cm
focal = 2
# focal = 10
# focal = 15 # looks good for a z of 75
# focal = 25
# focal = 50 #tmux one w/ z of 50
# focal = 2.85 / 0.024 #tmux two w/ z of 45
# focal = 200
# focal = 500
# iin tmux1 = radius 10
# in tmux 2 focal 2.85/0.024
# in tmux 3 focal = 500
# focal = 1000
all_gt = np.asarray(all_gt)
# all_gt = all_gt[:,:,0]
all_c2w = np.asarray(all_c2w)
print(f'all_c2w has size {all_c2w.size}')
print(f'all_c2w has shape {all_c2w.shape}')
# Remove the first 15 projections because the bulb is warming up so exposure is varying
# all_gt = np.asarray(all_gt)
# if len(all_gt.shape) < 4:
# all_gt = np.concatenate((all_gt[..., None], all_gt[..., None], all_gt[..., None]), axis=-1) # Add a fake channel dimension for CT
# all_c2w = np.asarray(all_c2w)
print(f'all_gt has shape {all_gt.shape}')
# Remove the first 15 projections because the bulb is warming up so exposure is varying
# all_gt = all_gt[15:]
# all_c2w = all_c2w[15:]
mask = np.zeros(len(all_c2w))
idx = np.random.choice(len(all_c2w), 100, replace = False) #tmux one
# idx = np.random.choice(len(all_c2w), 25, replace = False) #tmux two
mask[idx] = 1
mask = mask.astype(bool)
print(f'all_gt has shape {all_gt.shape}')
# train and test can be commented out ot get the full 360 ground truth projections
if stage == 'train':
all_gt = all_gt[mask]
all_c2w = all_c2w[mask]
elif stage == 'test':
all_gt = all_gt[~mask]
all_c2w = all_c2w[~mask]
print(f'all_gt has shape {all_gt.shape}')
return focal, all_c2w, all_gt
def get_ct_spike2(root, stage, max_projections, xoff, yoff, zoff):
all_w2c = []
all_gt = []
print('LOAD DATA', root)
# Would be good to test this for Jerry and Spike
# projection_matrices = np.genfromtxt(os.path.join('/data/datasets/jerry-cbct/', 'proj_mat.csv'), delimiter=',') # [719, 12]
projection_matrices = np.genfromtxt(os.path.join('/home/fabriz/data/spike/', 'proj_mat_720frames.csv'), delimiter=',') # [719, 12] /home/fabriz/data/spike/proj_mat_720frames.csv
# print(f'proj mat len is {len(projection_matrices)}')
#Traslation matrix along x,y,z
Tz = np.matlib.zeros((4,4))
Tz[0,0]=1.0
Tz[1,1]=1.0
Tz[2,2]=1.0
Tz[3,3]=1.0
Tz[0,3]=-xoff #test
Tz[1,3]=-yoff #test
Tz[2,3]=-zoff #test
tif_proj = tifffile.imread('/home/fabriz/data/spike/Spike_702_proj.tif')
# reads #max_projections projection images
for i in range(len(projection_matrices)):
index = "{:04d}".format(i)
# im_gt = imageio.imread(os.path.join('/data/datasets/newJerryProj', f'NewJerryProj_{index}.png')).astype(np.float32) / 255.0
# im_gt = imageio.imread(os.path.join('/data/datasets/New_Corrected_Projections', f'New_Cor_Proj{index}.png')).astype(np.float32) / 255.0
# im_gt = imageio.imread(os.path.join('/data/datasets/spike-cbct/spike720', f'Spike92_8_16_33_proj{index}.png')).astype(np.float32) / 255.0
im_gt = tif_proj[i,:,:]
im_gt = 1 - im_gt
# projection matrices P_(3,4)
w2c = np.reshape(projection_matrices[i], (3,4))
w2c = np.matmul(w2c,Tz) #applico una traslazione per centrate il volume
#w2c[:,-1] = (w2c[:,-1] - [400, 220, 200])
all_w2c.append(w2c)
all_gt.append(im_gt)
all_gt = np.asarray(all_gt)
all_w2c = np.asarray(all_w2c)
focal = 100
mask = np.zeros(len(all_w2c))
# print(f'max is {len(all_w2c)}')
idx = np.random.choice(len(all_w2c), max_projections, replace = False) # Just look at a subset of projections, to save time/memory for debuggin
mask[idx] = 1
mask = mask.astype(bool)
# train and test can be commented out to get the full 360 ground truth projections
if stage == 'train':
all_gt = all_gt[mask]
all_w2c = all_w2c[mask]
elif stage == 'test':
all_gt = all_gt[~mask]
all_w2c = all_w2c[~mask]
return focal, all_w2c,all_gt
# assert FLAGS.ct
def get_ct_shepp(root, stage, max_projections, xoff, yoff, zoff):
all_w2c = []
all_gt = []
print('LOAD DATA', root)
# Use the same projection matrices as Spike
projection_matrices = np.genfromtxt(os.path.join('/home/fabriz/data/spike/', 'proj_mat_720frames.csv'), delimiter=',') # [719, 12] /home/fabriz/data/spike/proj_mat_720frames.csv
#Traslation matrix along x,y,z
Tz = np.zeros((4,4))
Tz[0,0]=1.0
Tz[1,1]=1.0
Tz[2,2]=1.0
Tz[3,3]=1.0
Tz[0,3]=-xoff #test
Tz[1,3]=-yoff #test
Tz[2,3]=-zoff #test
# tif_proj = tifffile.imread(os.path.join(root, 'synthetic0.2_projections_raw_radius5_reso128_H140_W128_dhw0.12.tif'))
tif_proj = tifffile.imread(os.path.join(root, 'fifthdensity_1_projections_raw_radius5_reso128_H140_W128_dhw0.12.tif'))
# reads #max_projections projection images
for i in range(len(projection_matrices)):
im_gt = tif_proj[i,:,:]
# For linear baseline experiment
# im_gt = -1*np.log(1 - im_gt)
# projection matrices P_(3,4)
w2c = np.reshape(projection_matrices[i], (3,4))
w2c = np.matmul(w2c,Tz) #applico una traslazione per centrate il volume
all_w2c.append(w2c)
all_gt.append(im_gt)
all_gt = np.asarray(all_gt)
all_w2c = np.asarray(all_w2c)
focal = 100
return focal, all_w2c,all_gt
def get_ct_synthetic(root, stage, max_projections, xoff, yoff, zoff):
all_w2c = []
all_gt = []
print('LOAD DATA', root)
# Use the same projection matrices as Spike
projection_matrices = np.genfromtxt(os.path.join('/home/fabriz/data/spike/', 'proj_mat_720frames.csv'), delimiter=',') # [719, 12] /home/fabriz/data/spike/proj_mat_720frames.csv
#Traslation matrix along x,y,z
Tz = np.zeros((4,4))
Tz[0,0]=1.0
Tz[1,1]=1.0
Tz[2,2]=1.0
Tz[3,3]=1.0
Tz[0,3]=-xoff #test
Tz[1,3]=-yoff #test
Tz[2,3]=-zoff #test
# tif_proj = tifffile.imread(os.path.join(root, 'synthetic_projections_raw_radius5_reso50_H700.tif'))
# tif_proj = tifffile.imread(os.path.join(root, 'easy_synthetic_projections_raw_radius5_reso50_H700.tif'))
tif_proj = tifffile.imread(os.path.join(root, 'semi_easy_synthetic_projections_raw_radius5_reso50_H700.tif'))
# tif_proj = tifffile.imread(os.path.join(root, 'very_easy_synthetic_projections_raw_radius5_reso50_H700.tif'))
# tif_proj = tifffile.imread(os.path.join(root, 'super_easy_synthetic_projections_raw_radius5_reso50_H700.tif'))
# reads #max_projections projection images
for i in range(len(projection_matrices)):
im_gt = tif_proj[i,:,:]
# im_gt = 1 - im_gt # Not necessary for the synthetic dataset
# For linear baseline experiment
# im_gt = -1*np.log(1 - im_gt)
# projection matrices P_(3,4)
w2c = np.reshape(projection_matrices[i], (3,4))
w2c = np.matmul(w2c,Tz) #applico una traslazione per centrate il volume
all_w2c.append(w2c)
all_gt.append(im_gt)
all_gt = np.asarray(all_gt)
all_w2c = np.asarray(all_w2c)
focal = 100
# mask = np.zeros(len(all_w2c))
# # print(f'max is {len(all_w2c)}')
# idx = np.random.choice(len(all_w2c), max_projections, replace = False) # Just look at a subset of projections, to save time/memory for debuggin
# mask[idx] = 1
# mask = mask.astype(bool)
# # train and test can be commented out to get the full 360 ground truth projections
# if stage == 'train':
# all_gt = all_gt[mask]
# all_w2c = all_w2c[mask]
# elif stage == 'test':
# all_gt = all_gt[~mask]
# all_w2c = all_w2c[~mask]
return focal, all_w2c,all_gt
# This function takesn in the given root and uses the appropriate
# data loader to get the focal, c2w, and gt
def get_data(root, stage):
max_projections = 720
# to align the volume and the detector it is possibile to use a traslation matrix T to
# premultiply the projection matrices P'=P*T
# For Jerry
# xoff = 0.0
# yoff = 0.0
# zoff = -2.4
# For Spike
xoff = 0.0
yoff = -1.3 # side to side (lower goes to left)
zoff = -5.2 # up down (the higher the number the higher the cube goes)
if root == '/data/fabriziov/ct_scans/pepper/scans/':
focal, all_c2w, all_gt = get_ct_pepper(root, stage)
# idx = np.random.choice(len(all_c2w), FLAGS.num_views) # Pick a subset of the data at random
# return focal, all_c2w[idx], all_gt[idx]
return focal, all_c2w, all_gt
elif root == '/data/fabriziov/ct_scans/pomegranate/scans/':
focal, all_c2w, all_gt = get_ct_pomegranate(root, stage)
return focal, all_c2w, all_gt
elif root == '/data/fabriziov/ct_scans/organSegs/scans/':
focal, all_c2w, all_gt = get_ct_organSegs(root, stage)
return focal, all_c2w, all_gt
# elif root == '/data/datasets/Corrected_Projections/':
# focal, all_c2w, all_gt = get_ct_jerry(root, stage)
# return focal, all_c2w, all_gt
elif root == '/data/datasets/Corrected_Projections/':
focal, all_c2w, all_gt = get_ct_jerry2(root, stage, max_projections, xoff, yoff, zoff)
# idx = np.random.choice(len(all_c2w), FLAGS.num_views) # Pick a subset of the data at random
return focal, all_c2w, all_gt
elif root == '/data/datasets/spike-cbct/':
focal, all_c2w, all_gt = get_ct_spike2(root, stage, max_projections, xoff, yoff, zoff)
# idx = np.random.choice(len(all_c2w), FLAGS.num_views) # Pick a subset of the data at random
return focal, all_c2w, all_gt
elif 'ct_synthetic' in root:
focal, all_c2w, all_gt = get_ct_synthetic(root, stage, max_projections, xoff, yoff, zoff)
return focal, all_c2w, all_gt
elif 'ct_shepp' in root:
focal, all_c2w, all_gt = get_ct_shepp(root, stage, max_projections, xoff, yoff, zoff)
return focal, all_c2w, all_gt
# elif root == '/data/datasets/spike-cbct/':
# focal, all_c2w, all_gt = get_ct_spike(root, stage)
# # idx = np.random.choice(len(all_c2w), FLAGS.num_views) # Pick a subset of the data at random
# return focal, all_c2w, all_gt
all_c2w = []
all_gt = []
data_path = os.path.join(root, stage)
data_json = os.path.join(root, 'transforms_' + stage + '.json')
print('LOAD DATA', data_path)
j = json.load(open(data_json, 'r'))
for frame in tqdm(j['frames']):
fpath = os.path.join(data_path, os.path.basename(frame['file_path']) + '.png')
c2w = frame['transform_matrix']
im_gt = imageio.imread(fpath).astype(np.float32) / 255.0
# Adding next line from the plenotimize_static file, said to be for the linear version
# This line makes more static-y images that seen to have depth
# im_gt = jnp.concatenate([-jnp.log(1 - 0.99*im_gt[..., 3:]), jnp.zeros((im_gt.shape[0], im_gt.shape[1], 2))], -1)
# This line makes more white images that look cleaner(sara said to ise this one)
im_gt = jnp.concatenate([im_gt[..., 3:], jnp.zeros((im_gt.shape[0], im_gt.shape[1], 2))], -1) # If we want to train with alpha
# Might want to comment out next line; plenoptimize_static file says to only use it when you want to train with color
# im_gt = im_gt[..., :3] * im_gt[..., 3:] + (1.0 - im_gt[..., 3:])
all_c2w.append(c2w)
all_gt.append(im_gt)
focal = 0.5 * all_gt[0].shape[1] / np.tan(0.5 * j['camera_angle_x'])
all_gt = np.asarray(all_gt)
all_c2w = np.asarray(all_c2w)
return focal, all_c2w, all_gt
# This uses calls get_data to get a training set and a test set
# for a focal, c2w, and gt.
# If the focal is not equal to the test_focal then an AssertionError is raised.
# The height and width are set to the shape of index 0 of the training gt from
# the begining to index 2
# Finally the length of the trianing and test c2w's are obtained
if __name__ == "__main__":
print(f'the data directory is {data_dir}')
focal, train_c2w, train_gt = get_data(data_dir, "train")
test_focal, test_c2w, test_gt = get_data(data_dir, "test")
assert focal == test_focal
H, W = train_gt[0].shape[:2]
dW = 0.024
dH = 0.024
n_train_imgs = len(train_c2w)
n_test_imgs = len(test_c2w)
if 'shepp' in FLAGS.expname:
H = 140
W = 128
dH = 0.12
dW = 0.12
# Sets the new log_dirs to be the exsiting log_dir plus the experiment name
# makes the neccessary directories for it if they don't exist.
log_dir = FLAGS.log_dir + FLAGS.expname
os.makedirs(log_dir, exist_ok=True)
automatic_lr = False
if FLAGS.lr_rgb is None or FLAGS.lr_sigma is None:
automatic_lr = True
# Added two If statements, the content of them however, was in the original code
if FLAGS.lr_rgb is None:
FLAGS.lr_rgb = 150 * (FLAGS.resolution ** 1.75)
if FLAGS.lr_sigma is None:
FLAGS.lr_sigma = 51.5 * (FLAGS.resolution ** 2.37)
if FLAGS.reload_epoch is not None:
reload_dir = os.path.join(log_dir, f'epoch_{FLAGS.reload_epoch}')
# reload_dir = "./jax_logs/test_spike_tiff_res256_epoch2_split0_lr0.001/epoch_0"
print(f'Reloading the grid from {reload_dir}')
data_dict = plenoxel_og_copy2.load_grid(dirname=reload_dir, sh_dim = (FLAGS.harmonic_degree + 1)**2)
# import pdb; pdb.set_trace()
else:
print(f'Initializing the grid')
data_dict = plenoxel_og_copy2.initialize_grid(resolution=FLAGS.resolution, ini_rgb=FLAGS.ini_rgb, ini_sigma=FLAGS.ini_sigma, harmonic_degree=FLAGS.harmonic_degree)
# low-pass filter the ground truth image so the effective resolution matches twice that of the grid
def lowpass(gt, resolution):
if gt.ndim > 3:
print(f'lowpass called on image with more than 3 dimensions; did you mean to use multi_lowpass?')
H = gt.shape[0]
W = gt.shape[1]
im = Image.fromarray((np.squeeze(np.asarray(gt))*255).astype(np.uint8))
im = im.resize(size=(resolution*2, resolution*2))
im = im.resize(size=(H, W))
return np.asarray(im) / 255.0
# low-pass filter a stack of images where the first dimension indexes over the images
# Takes a high resolution picture, blurs it, gets the low sine waves and creates a lower resolution picture from it
def multi_lowpass(gt, resolution):
if gt.ndim <= 3:
print(f'multi_lowpass called on image with 3 or fewer dimensions; did you mean to use lowpass instead?')
H = gt.shape[-3]
W = gt.shape[-2]
clean_gt = np.copy(gt)
for i in range(len(gt)):
# print(np.squeeze(gt[i,...] * 255).shape)
im = Image.fromarray(np.squeeze(gt[i,...] * 255).astype(np.uint8))
im = im.resize(size=(resolution*2, resolution*2))
# In the plenoptimize_static file the line below was changed because jerry needed it, not sure if I would need to change it for
# making ct scans in general or is this is just a jerry thing
# OMG LOL IT IS A CT THING HAHAHA
# Keep this line as (W, H) and not (H, W)!!!
# or not ???
# now it only works if it is (H,W)
# nvm idk which is right
# print(im)
im = im.resize(size=(W, H))
im = np.asarray(im) / 255.0
clean_gt[i,...] = im
return clean_gt
def compute_tv(t):
# xdim, ydim, zdim = t.shape
x_tv = jnp.abs(t[1:, :, :] - t[:-1, :, :]).mean()
y_tv = jnp.abs(t[:, 1:, :] - t[:, :-1, :]).mean()
z_tv = jnp.abs(t[:, :, 1:] - t[:, :, :-1]).mean()
return x_tv + y_tv + z_tv
def get_loss(data_dict, c2w, gt, H, W, focal, resolution, radius, harmonic_degree, jitter, uniform, key, sh_dim, occupancy_penalty, interpolation, nv):
rays = plenoxel_og_copy2.get_rays(H, W, focal, c2w)
# rays = get_rays_np(H, W, dH, dW, w2c) # I think we should be using this version with jerry/spike/synthetic. But it only matters if physical_batch_size is None
rgb, disp, acc, weights, voxel_ids = plenoxel_og_copy2.render_rays(data_dict, rays, resolution, key, radius, harmonic_degree, jitter, uniform, interpolation, nv)
mse = jnp.mean((rgb - lowpass(gt, resolution))**2)
indices, data = data_dict
loss = mse + occupancy_penalty * jnp.mean(jax.nn.relu(data_dict[-1]))
return loss
# The plenotimize_static file has this added line to the top of this function, not sure if is necessary
@partial(jax.jit, static_argnums=(3,4,5,6,7,9,11,12))
def get_loss_rays(data_dict, rays, gt, resolution, radius, harmonic_degree, jitter, uniform, key, sh_dim, occupancy_penalty, interpolation, nv):
# data_dict = [jnp.array(d) for d in data_dict] # Convert data_dict list to JAX array
rgb, disp, acc, weights, voxel_ids = plenoxel_og_copy2.render_rays(data_dict, rays, resolution, key, radius, harmonic_degree, jitter, uniform, interpolation, nv)
# The plenoptimize_static file has this next line a little bit different, for the "alpha" channel only ???
# mse = jnp.mean((rgb - gt)**2)
mse = jnp.mean((acc - gt[...,0])**2)# Optimize the alpha channel only
# indices, data = data_dict