File size: 8,571 Bytes
f1783eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Post-process Mindboggle-101 volume images for distribution,
using Mindboggle, FreeSurfer, and FSL tools.

This is modified from the original code_postprocess_Mindboggle101.py to
(1) only generate DKT31 (not DKT25) labeling protocol data
(2) use the existing T1 data and transforms (don't generate new ones):

  - Convert label volume from FreeSurfer to original space
  x Extract brain by masking with manual cortical and automated subcortical labels
  - Remove non-DKT31 (non-cortical) labels
  - Affine register T1-weighted brain to MNI152 brain
  - Transfer whole-head images with affine transform
  - Transfer labeled images with affine transform (nearest-neighbor interpolation)

Authors:  Arno Klein  .  arno@mindboggle.info  .  www.binarybottle.com

(c) 2013-2019  Mindbogglers (www.mindboggle.info), under Apache License Version 2.0

"""

import os


# Paths, template, and label conversion files
mb101_path = os.path.join('/Users', 'arno.klein', 'Data', 'Mindboggle101')
mb_info_path = os.path.join(mb101_path, 'docs')
template = os.path.join(mb101_path, 'MNI152_T1_1mm_brain.nii.gz')

# Loop through subjects
list_file = os.path.join(mb_info_path, 'mindboggle101_list.txt')
fid = open(list_file, 'r')
subjects = fid.readlines()
subjects = [''.join(x.split()) for x in subjects]


def keep_volume_labels(input_file, labels_to_keep, output_file='',
                       second_file=''):
    """
    Keep only given labels in an image volume (or use to mask second volume).

    Parameters
    ----------
    input_file : string
        labeled nibabel-readable (e.g., nifti) file
    labels_to_keep : list of integers
        labels to keep
    output_file : string
        output file name
    second_file : string
        second nibabel-readable file (keep/erase voxels in this file instead)

    Returns
    -------
    output_file : string
        output file name

    Examples
    --------
    >>> # Remove right hemisphere labels
    >>> import os
    >>> from mindboggle.guts.relabel import keep_volume_labels
    >>> from mindboggle.mio.labels import DKTprotocol
    >>> from mindboggle.mio.fetch_data import prep_tests
    >>> urls, fetch_data = prep_tests()
    >>> input_file = fetch_data(urls['freesurfer_labels'], '', '.nii.gz')
    >>> second_file = ''
    >>> labels_to_keep = list(range(1000, 1036))
    >>> output_file = 'keep_volume_labels.nii.gz'
    >>> output_file = keep_volume_labels(input_file, labels_to_keep,
    ...                                  output_file, second_file)

    View nifti file (skip test):

    >>> from mindboggle.mio.plots import plot_volumes
    >>> plot_volumes(output_file) # doctest: +SKIP

    """
    import os
    import numpy as np
    import nibabel as nb

    # ------------------------------------------------------------------------
    # Load labeled image volume and extract data as 1-D array:
    # ------------------------------------------------------------------------
    vol = nb.load(input_file)
    xfm = vol.get_affine()
    data = vol.get_data().ravel()

    # ------------------------------------------------------------------------
    # If second file specified, erase voxels whose corresponding
    # voxels in the input_file have labels not in labels_to_keep:
    # ------------------------------------------------------------------------
    if second_file:
        # Load second image volume and extract data as 1-D array:
        vol = nb.load(second_file)
        xfm = vol.get_affine()
        new_data = vol.get_data().ravel()
        if not output_file:
            output_file = os.path.join(os.getcwd(),
                                       os.path.basename(second_file))
    # ------------------------------------------------------------------------
    # If second file not specified, remove labels not in labels_to_keep:
    # ------------------------------------------------------------------------
    else:
        new_data = data.copy()
        if not output_file:
            output_file = os.path.join(os.getcwd(),
                                       os.path.basename(input_file))

    # ------------------------------------------------------------------------
    # Erase voxels as specified above:
    # ------------------------------------------------------------------------
    ulabels = np.unique(data)
    for label in ulabels:
        label = int(label)
        if label not in labels_to_keep:
            new_data[np.where(data == label)[0]] = 0

    # ------------------------------------------------------------------------
    # Reshape to original dimensions:
    # ------------------------------------------------------------------------
    new_data = np.reshape(new_data, vol.shape)

    # ------------------------------------------------------------------------
    # Save relabeled file:
    # ------------------------------------------------------------------------
    img = nb.Nifti1Image(new_data, xfm)
    img.to_filename(output_file)

    if not os.path.exists(output_file):
        raise IOError("keep_volume_labels() did not create " + output_file + ".")

    return output_file


for subject in subjects:

    print(">>> Process subject: {0}...".format(subject))
    subject_path = os.path.join(mb101_path, 'subjects', subject, 'mri')

    # Identify original files
    full_labels_orig = os.path.join(subject_path, 'aparcNMMjt+aseg.nii.gz')
    head = os.path.join(subject_path, 't1weighted.nii.gz')
    brain = os.path.join(subject_path, 't1weighted_brain.nii.gz')

    # Name all output files
    full_labels = os.path.join(subject_path, 'labels.DKT31.manual+aseg.nii.gz')
    DKT31_labels = os.path.join(subject_path, 'labels.DKT31.manual.nii.gz')
    xfm_matrix = os.path.join(subject_path, 't1weighted_brain.MNI152.affine.txt')
    xfm_brain = os.path.join(subject_path, 't1weighted_brain.MNI152.nii.gz')
    xfm_head = os.path.join(subject_path, 't1weighted.MNI152.nii.gz')
    xfm_DKT31 = os.path.join(subject_path, 'labels.DKT31.manual.MNI152.nii.gz')
    xfm_DKT31aseg = os.path.join(subject_path, 'labels.DKT31.manual+aseg.MNI152.nii.gz')



    # Remove old labels and affine-transformed files
    rm_files = [x for x in os.listdir(subject_path) if 'labels.' in x or '.MNI152.' in x]
    for rm_file in rm_files:
        os.remove(os.path.join(subject_path, rm_file))

    # Convert label volume from FreeSurfer to original space
    print("Convert label volume from FreeSurfer to original space...")
    cmd = ' '.join(['mri_vol2vol --nearest --mov', full_labels_orig, '--targ', head,
                    '--regheader --o', full_labels])
    print(cmd); os.system(cmd)



    # Affine register T1-weighted brain to MNI152 brain using FSL's flirt
    print("Affine register T1-weighted brain to MNI152 brain using FSL's flirt...")
    cmd = ' '.join(['flirt', '-in', brain, '-ref', template,
                    '-out', xfm_brain, '-omat', xfm_matrix])
    print(cmd); os.system(cmd)

    # Transfer whole-head images with affine transform using FSL's flirt
    print("Apply affine transform to whole-head using FSL's flirt...")
    cmd = ' '.join(['flirt', '-in', head, '-ref', template,
                    '-applyxfm -init', xfm_matrix, '-out', xfm_head])
    print(cmd); os.system(cmd)

    # Transfer DKT31- plus FreeSurfer-aseg-labeled images with affine transform (nearest-neighbor interpolation)
    print("Apply affine transform to labeled images (with nearest neighbor interpolation)...")

    cmd = ' '.join(['flirt', '-in', full_labels, '-ref', template,
                    '-applyxfm -init', xfm_matrix,
                    '-interp nearestneighbour -out', xfm_DKT31aseg])
    print(cmd); os.system(cmd)



    # Remove all but DKT31 (cortical) labels
    print("Remove non-DKT31 (cortical) labels...")
    DKT31_numbers = [2, 3] + list(range(5, 32)) + [34, 35]
    labels_to_keep = [1000 + x for x in DKT31_numbers]
    labels_to_keep.extend([2000 + x for x in DKT31_numbers])
    output_file = keep_volume_labels(full_labels, labels_to_keep, output_file=DKT31_labels, second_file='')

    # Transfer DKT31-labeled images with affine transform (nearest-neighbor interpolation)
    cmd = ' '.join(['flirt', '-in', DKT31_labels, '-ref', template,
                    '-applyxfm -init', xfm_matrix,
                    '-interp nearestneighbour -out', xfm_DKT31])
    print(cmd); os.system(cmd)


    # Compress subject directory
    #subject_path2 = os.path.join(mb101_path, 'subjects', subject)
    #cmd =  ' '.join(['tar cvfz', subject_path2+'.tar.gz', subject_path2])
    #print(cmd); os.system(cmd)