Created
June 8, 2018 15:54
-
-
Save mrajchl/e141bc006097e4daea48cf19d279cb7f to your computer and use it in GitHub Desktop.
A read function for .nii images using SimpleITK
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def read_fn(file_references, mode, params=None): | |
# We define a `read_fn` and iterate through the `file_references`, which | |
# can contain information about the data to be read (e.g. a file path): | |
for meta_data in file_references: | |
# Here, we parse the `subject_id` to construct a file path to read | |
# an image from. | |
subject_id = meta_data[0] | |
data_path = '../../data/IXI_HH/1mm' | |
t1_fn = os.path.join(data_path, '{}/T1_1mm.nii.gz'.format(subject_id)) | |
# Read the .nii image containing a brain volume with SimpleITK and get | |
# the numpy array: | |
sitk_t1 = sitk.ReadImage(t1_fn) | |
t1 = sitk.GetArrayFromImage(sitk_t1) | |
# Normalise the image to zero mean/unit std dev: | |
t1 = whitening(t1) | |
# Create a 4D Tensor with a dummy dimension for channels | |
t1 = t1[..., np.newaxis] | |
# If in PREDICT mode, yield the image (because there will be no label | |
# present). Additionally, yield the sitk.Image pointer (including all | |
# the header information) and some metadata (e.g. the subject id), | |
# to facilitate post-processing (e.g. reslicing) and saving. | |
# This can be useful when you want to use the same read function as | |
# python generator for deployment. | |
if mode == tf.estimator.ModeKeys.PREDICT: | |
yield {'features': {'x': t1}} | |
# Labels: Here, we parse the class *sex* from the file_references | |
# \in [1,2] and shift them to \in [0,1] for training: | |
sex = np.int32(meta_data[1]) - 1 | |
y = sex | |
# If training should be done on image patches for improved mixing, | |
# memory limitations or class balancing, call a patch extractor | |
if params['extract_examples']: | |
images = extract_random_example_array( | |
t1, | |
example_size=params['example_size'], | |
n_examples=params['n_examples']) | |
# Loop the extracted image patches and yield | |
for e in range(params['n_examples']): | |
yield {'features': {'x': images[e].astype(np.float32)}, | |
'labels': {'y': y.astype(np.int32)}} | |
# If desired (i.e. for evaluation, etc.), return the full images | |
else: | |
yield {'features': {'x': images}, | |
'labels': {'y': y.astype(np.int32)}} | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment