-
Notifications
You must be signed in to change notification settings - Fork 2
/
dcm-convert.py
executable file
·132 lines (102 loc) · 4.16 KB
/
dcm-convert.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
#!/usr/bin/env python
import os
import json
import logging
import datetime
logging.basicConfig()
log = logging.getLogger('dcmConvert')
import scitran.data as scidata
def dicom_convert(fp, outbase=None):
"""
Attempts multiple types of conversion on dicom files.
Attempts to create a nifti for all files, except screen shots.
Also attempts to create montages of all files.
"""
if not os.path.exists(fp):
print 'could not find %s' % fp
print 'checking input directory ...'
if os.path.exists(os.path.join('/input', fp)):
fp = os.path.join('/input', fp)
print 'found %s' % fp
if not outbase:
fn = os.path.basename(fp)
outbase = os.path.join('/output', fn[:fn.index('_dicom')]) # take everything before dicom...
log.info('setting outbase to %s' % outbase)
# CONFIG: If there is a config file then load that, else load the manifest and read the default values.
if os.path.exists('/flywheel/v0/config.json'):
config_file = '/flywheel/v0/config.json'
MANIFEST=False
else:
config_file = '/flywheel/v0/manifest.json'
MANIFEST=True
with open(config_file, 'r') as jsonfile:
config = json.load(jsonfile)
config = config.pop('config')
if MANIFEST:
convert_montage = config['convert_montage']['default']
convert_nifti = config['convert_nifti']['default']
convert_png = config['convert_png']['default']
else:
convert_montage = config['convert_montage']
convert_nifti = config['convert_nifti']
convert_png = config['convert_png']
# CONVERSION
log.info('converting dicom file %s' % fp)
ds = scidata.parse(fp, filetype='dicom', ignore_json=True, load_data=True)
log.info('loaded and parsed')
final_results = []
# create nifti and Montage
if ds.scan_type != 'screenshot':
if convert_montage:
log.info('performing non screenshot conversion, montage')
final_results += scidata.write(ds, ds.data, outbase=outbase + '.montage', filetype='montage', voxel_order='LPS') # always LPS
if convert_nifti:
log.info('performing non screenshot conversion, nifti')
final_results += scidata.write(ds, ds.data, outbase=outbase, filetype='nifti') # no reorder
elif ds.scan_type == 'screenshot':
if convert_png:
log.info('performing screenshot conversion, png')
final_results += scidata.write(ds, ds.data, outbase=outbase + '.screenshot', filetype='png')
# Write metadata file
output_files = os.listdir(os.path.dirname(outbase))
files = []
if len(output_files) > 0:
for f in output_files:
fdict = {}
fdict['name'] = f
if f.endswith('.nii.gz'):
ftype = 'nifti'
elif f.endswith('bvec'):
ftype = 'bvec'
elif f.endswith('bval'):
ftype = 'bval'
elif f.endswith('montage.zip'):
ftype = 'montage'
elif f.endswith('.png'):
ftype = 'screenshot'
else:
ftype = 'None'
fdict['type'] = ftype
files.append(fdict)
metadata = {}
metadata['acquisition'] = {}
metadata['acquisition']['files'] = files
with open(os.path.join(os.path.dirname(outbase),'.metadata.json'), 'w') as metafile:
json.dump(metadata, metafile)
return final_results
if __name__ == '__main__':
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('dcmtgz', help='path to dicom zip')
ap.add_argument('outbase', nargs='?', help='outfile name prefix')
ap.add_argument('--log_level', help='logging level', default='info')
args = ap.parse_args()
log.setLevel(getattr(logging, args.log_level.upper()))
logging.getLogger('sctran.data').setLevel(logging.INFO)
log.info('job start: %s' % datetime.datetime.utcnow())
results = dicom_convert(args.dcmtgz, args.outbase)
log.info('job stop: %s' % datetime.datetime.utcnow())
if results:
log.info('generated %s' % ', '.join(results))
else:
log.info('Failed.')