a b/tool/run_FatSegNet.py
1
import argparse
2
import sys
3
import os
4
import time
5
6
sys.path.append('./')
7
8
from Code.adipose_pipeline import run_adipose_pipeline
9
from Code.utilities.misc import locate_file,locate_dir
10
import pandas as pd
11
import numpy as np
12
13
import warnings
14
15
if not sys.warnoptions:
16
    warnings.simplefilter("ignore")
17
18
19
def check_paths(save_folder,subject_id,flags):
20
21
    save_path=os.path.join(flags['output_path'],save_folder)
22
23
    if not os.path.isdir(save_path):
24
        os.mkdir(save_path)
25
26
    if not os.path.isdir(os.path.join(save_path,subject_id)):
27
        os.mkdir(os.path.join(save_path,subject_id))
28
29
    final_path = os.path.join(save_path,subject_id)
30
    return final_path
31
32
33
class Transcript(object):
34
35
    def __init__(self, filename):
36
        self.terminal = sys.stdout
37
        self.logfile = open(filename, "a")
38
39
    def write(self, message):
40
        self.terminal.write(message)
41
        self.logfile.write(message)
42
43
    def flush(self):
44
        # this flush method is needed for python 3 compatibility.
45
        # this handles the flush command by doing nothing.
46
        # you might want to specify some extra behavior here.
47
        pass
48
49
50
51
def option_parse():
52
53
54
    parser = argparse.ArgumentParser(
55
        description='Adipose Pipeline to segment the  abdominal adipose tissue into VAT and SAT. '
56
                    'Each subject should have a independent folder with the water and fat images. '
57
                    'Input images have to be nifti files and should be named consistently in all subjects. '
58
                    'The Output path is define by the user ; all the outputs from the pipeline will be store under $output_path/$subject_id. '
59
                    'The predicted segmentation mask is save under ($AAT_pred) and all the statistics under $ATT_stats',
60
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
61
    parser.add_argument("-f", "--file", help="csv file containing the subjects to process, the csv file should be order as follow : $subject_id,$subject_path", required=False,default='participants.csv')
62
    parser.add_argument("-outp", "--output_folder",
63
                        help="Main folder where the variables and control images are going to be store", required=False, default='')
64
65
    parser.add_argument("-fat", "--fat_image", type=str, help="Name of the fat image", required=False,
66
                        default='FatImaging_F.nii.gz')
67
    parser.add_argument("-water", "--water_image", type=str, help="Name of the water image", required=False,
68
                        default='FatImaging_W.nii.gz')
69
70
    parser.add_argument('-No_QC',"--control_images",action='store_true',help='Plot subjects prediction for visual quality control',required=False,default=False)
71
72
    parser.add_argument('-loc', "--run_localization", action='store_true',
73
                        help='run abdominal region localization model ', required=False, default=False)
74
75
    parser.add_argument('-axial', "--axial", action='store_true',
76
                        help='run only axial model ', required=False, default=False)
77
78
    parser.add_argument('-order', "--order", type=int,
79
                        help='interpolation order (0=nearest,1=linear(default),2=quadratic,3=cubic) ', required=False, default=1)
80
81
    parser.add_argument('-comp', "--compartments", type=int,
82
                        help='Number of equal compartments to run the analysis, by default the whole region(wb) is calculated', required=False, default=0)
83
84
    parser.add_argument('-AAT', "--increase_threshold", type=float,
85
                        help='Warning flag for an increase in AAT over threhold between consecutive scans', required=False, default=0.4)
86
87
    parser.add_argument('-ratio', "--sat_to_vat_threshold", type=float,
88
                        help='Warning flag for a high vat to sat ratio', required=False, default=2.0)
89
90
    parser.add_argument('-stats', "--run_stats", action='store_true',
91
                        help='run only stats , segmentation map required ', required=False, default=False)
92
93
    parser.add_argument('-gpu_id', "--gpu_id", type=int,
94
                        help='if using gpu, please give the gpu device name', required=False, default=0)
95
96
97
98
99
    args = parser.parse_args()
100
101
    FLAGS = {}
102
    FLAGS['multiviewModel'] = '/tool/Adipose_Seg_Models/Segmentation/'
103
    FLAGS['singleViewModels'] = '/tool/Adipose_Seg_Models/Segmentation/'
104
    FLAGS['localizationModels'] = '/tool/Adipose_Seg_Models/Localization/'
105
    FLAGS['input_path']='/tool/Data'
106
    FLAGS['output_path']='/tool/Output'
107
    FLAGS['imgSize'] = [256, 224, 72]
108
    FLAGS['spacing'] = [float(1.9531), float(1.9531),float(5.0)]
109
    FLAGS['base_ornt'] = np.array([[0, -1], [1, 1], [2, 1]])
110
    #FLAGS['compartments']=0
111
    #control_images = True
112
113
114
    return args,FLAGS
115
116
117
def run_fatsegnet(args,FLAGS):
118
119
    # load file
120
    participant_file=locate_file('*'+args.file,FLAGS['input_path'])
121
    if participant_file:
122
        print('Loading participant from file : %s'%participant_file[0])
123
        df =pd.read_csv(participant_file[0],header=None)
124
        if df.empty:
125
            print('Participant file empty ')
126
        else:
127
            file_list=df.values
128
            for sub in file_list:
129
                id=sub[0]
130
                path = locate_dir('*'+str(id)+'*',FLAGS['input_path'])
131
                if path:
132
                    if os.path.isdir(path[0]):
133
134
                        start = time.time()
135
136
                        save_path = check_paths(save_folder=args.output_folder, subject_id=str(id),flags=FLAGS)
137
138
                        sys.stdout= Transcript(filename=save_path + '/temp.log')
139
140
                        run_adipose_pipeline(args=args, flags=FLAGS, save_path=save_path,data_path=path[0],id=str(id))
141
142
                        end = time.time() - start
143
144
                        print("Total time for computation of segmentation is %0.4f seconds."%end)
145
146
                        sys.stdout.logfile.close()
147
                        sys.stdout = sys.stdout.terminal
148
                    else:
149
                        print ('Directory %s not found'%path)
150
                else :
151
                    print('Directory name %s not found' % id)
152
            print('\n')
153
            print('Thank you for using FatSegNet')
154
            print('If you find it useful and use it for a publication, please cite: ')
155
            print('\n')
156
            print('Estrada S, Lu R, Conjeti S, et al.'
157
                  'FatSegNet: A fully automated deep learning pipeline for adipose tissue segmentation on abdominal dixon MRI.'
158
                  'Magn Reson Med. 2019;00:1-13. https:// doi.org/10.1002/mrm.28022')
159
    else:
160
        print('No partipant file found, please provide one the input data folder')
161
162
163
164
if __name__=='__main__':
165
166
167
    args,FLAGS= option_parse()
168
169
    os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID";
170
    # The GPU id to use, usually either "0" or "1";
171
    os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id);
172
173
    run_fatsegnet(args,FLAGS)
174
175
    sys.exit(0)
176