Skip to content

Instantly share code, notes, and snippets.

@lebedov
Created October 10, 2016 14:58
Show Gist options
  • Save lebedov/94f1caf8a792d80cd91e7b99c1a0c1d7 to your computer and use it in GitHub Desktop.
Save lebedov/94f1caf8a792d80cd91e7b99c1a0c1d7 to your computer and use it in GitHub Desktop.
How to normalize intensity of brain images to the range [0, 1] with nipype and FSL.
#!/usr/bin/env python
"""
How to normalize intensity of brain images to the range [0, 1] with nipype and FSL.
"""
import os.path
import nipype
import nipype.interfaces
import nipype.interfaces.fsl as fsl
# Assume that inputs and outputs live in subdirectories of this directory:
base_dir = os.path.join(os.environ['HOME'], 'project')
# Source and sink:
grabber = nipype.Node(interface=nipype.DataGrabber(infields=['arg'],
outfields=['out_file']),
name='grabber')
grabber.inputs.base_directory = os.path.join(base_dir, 'input')
grabber.inputs.sort_filelist = False
grabber.inputs.template = '%s.nii'
grabber.inputs.arg = '*'
# Use substition to force all output files to be dumped into the same
# directory:
sink = nipype.Node(interface=nipype.DataSink(),
name='sink')
sink.inputs.base_directory = os.path.join(base_dir, 'output')
sink.inputs.regexp_substitutions = [('_\w+\d+', '.')]
# Intensity normalization - subtract minimum, then divide by difference of maximum and minimum:
fslstats = nipype.MapNode(interface=fsl.ImageStats(op_string='-R'),
name='fslstats', iterfield=['in_file'])
def func(in_stat):
min_val, max_val = in_stat
return '-sub %s -div %s' % (min_val, (max_val-min_val))
stat_to_op_string = nipype.MapNode(interface=nipype.interfaces.Function(input_names=['in_stat'],
output_names=['op_string'],
function=func),
name='stat_to_op_string', iterfield=['in_stat'])
fslmaths = nipype.MapNode(interface=fsl.ImageMaths(),
name='fslmaths', iterfield=['in_file', 'op_string'])
# Use @ to prevent creation of subdirectories in sink's base directory
# when saving output:
workflow = nipype.Workflow('workflow')
workflow.connect([(grabber, fslstats, [('out_file', 'in_file')]),
(grabber, fslmaths, [('out_file', 'in_file')]),
(fslstats, stat_to_op_string, [('out_stat', 'in_stat')]),
(stat_to_op_string, fslmaths, [('op_string', 'op_string')]),
(fslmaths, sink, [('out_file', '@in_file')])])
workflow.run('MultiProc', plugin_args={'n_procs': 4})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment