1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # =============================================================================
4
+ # Created By : Jay Shah
5
+ # Contact : https://www.public.asu.edu/~jgshah1/
6
+ # =============================================================================
7
+ ''' Module converts numpy files to NIFTI-format
8
+ also converts DPMs generated to NIFTI-format of size [181 x 217 x181]
9
+ Usage: python3 npy_to_nii.py choose_your_npy_folder/ folder_to_store_nifti_files/ '''
10
+
11
+ # =============================================================================
12
+ # Imports
13
+ # =============================================================================
14
+ import nibabel as nib
15
+ import numpy as np
16
+ import glob , os , sys
17
+
18
+ def probability_to_risk (raw ):
19
+ x1 , x2 = raw [0 , :, :, :], raw [1 , :, :, :]
20
+ risk = np .exp (x2 ) / (np .exp (x1 ) + np .exp (x2 ))
21
+ return risk
22
+
23
+ def upsample (heat ):
24
+ new_heat = np .zeros ((46 * 4 , 55 * 4 , 46 * 4 ))
25
+ for start_idx1 in range (4 ):
26
+ for start_idx2 in range (4 ):
27
+ for start_idx3 in range (4 ):
28
+ new_heat [start_idx1 ::4 , start_idx2 ::4 , start_idx3 ::4 ] = heat
29
+ return new_heat [:181 , :217 , :181 ]
30
+
31
+ def numpy_to_nifti (file , input_folder , output_folder ):
32
+
33
+ if not os .path .exists (output_folder ):
34
+ os .mkdir (output_folder )
35
+
36
+ filename = str (file .split ('/' )[- 1 ].split ('.' )[0 ])
37
+ print ("Processing: " , filename )
38
+
39
+ img = np .load (file )
40
+ img = np .squeeze (img )
41
+
42
+ # only if converting DPMs to NIFTI format
43
+ # else comment it out
44
+ img = upsample (probability_to_risk (img ))
45
+
46
+ new_image = nib .Nifti1Image (img , affine = np .eye (4 ))
47
+ nib .save (new_image , out_folder + filename )
48
+
49
+
50
+ if __name__ == "__main__" :
51
+
52
+ in_folder = str (sys .argv [1 ])
53
+ out_folder = str (sys .argv [2 ])
54
+
55
+ for file in glob .glob (in_folder + '*.npy' ):
56
+ data = numpy_to_nifti (file , in_folder , out_folder )
57
+ print ("NIFTI files saved to " , out_folder )
58
+
0 commit comments