Image
This file contains functions and classes related image manipulation.
- fmriproc.image.bin_fov()[source]
This function returns a binarized version of the input image. If no output name was specified, it will return the dataframe in nifti-format
- Parameters:
img (str) – path to input image
thresh (int) – threshold to use (default = 0)
out (str) – path to output image (default is None, and will return the data array of the image)
fsl (bool) – if you reeeally want a binary image also run fslmaths -bin.. Can only be in combination with an output image and on a linux system with FSL (default is false)
- Returns:
niimg-object with a binarized FOV of input image img
- Return type:
nibabel.Nifti1Image
Example
file = bin_fov("/path/to/image.nii.gz") bin_fov("/path/to/image.nii.gz", thresh=1, out="/path/to/image.nii.gz", fsl=True) bin_fov("/path/to/image.nii.gz", thres=2)
- fmriproc.image.clip_image()[source]
This function takes an image or numpy array, and takes the <thr>-value as threshold to clip the maximum value of the input. This is especially useful to increase contrast in the masked_mp2rage-files. For some reason, the masking can be detrimental for the contrast resulting in failing segmentations.
- Parameters:
img (numpy.ndarray, nibabel.Nifti1Image, str) – input data; can either be a numpy array, a Nifti-image, or a string pointing to a nifti-file.
thr (float, optional) – cut-off to use as threshold of image intensity. This represents 0.5% occuring values, after which a drop of intensities is seen.
val (float, optional) – cut-off to use as threshold of image intensity. This represents a hard threshold of literal image values
return_type (str, optional) – output type; can either be a numpy array (‘arr’), a Nifti-image (‘nib’), or a file (‘file’). In the case of the latter, an output name should be provided
out_file (str, optional) – string to output name if ‘return_type=”file”’ is specified
- Returns:
nibabel.Nifti1Image – if return_type==”file”, a niimg-object is returned
numpy.ndarray – if return_type==”arr”, an array with the shape of img is returned
str – if return_type==”file”, a new file is created and nothing is returned
Example
new_img = clip_image("input.nii.gz", thr=0.005, return_type="nib") clip_image("input.nii.gz", return_type='file', out_file='output.nii.gz')
- fmriproc.image.create_line_from_slice()[source]
This creates a binary image of the outline of the line. The line’s dimensions are 16 voxels of 0.25mm x 2.5 mm (slice thickness) and 0.25 mm (frequency encoding direction). We know that the middle of the line is at the center of the slice, so the entire line encompasses 8 voxels up/down from the center. This is represented by the ‘width’ flag, set to 16 by default
- Parameters:
in_file (str) – path to image that should be used as reference (generally this should be the 1 slice file of the first run or something)
out_file (str, optional) – path specifying the output name of the newly created ‘line’ or ‘beam’ file
width (int, optional) – how many voxels should we use to define the line. Remember that the center of the line is width/2, so if it’s set to 16, we take 8 voxels below center and 8 voxels above center.
fold (str, optional) – string denoting the type of foldover direction that was used. We can find this in the info-file in the pycortex directory and can either be FH (line = LR), or LR (line = FH)
keep_input (boolean, optional) – Keep the native input of the input data rather than binarizing the input image
shift (int, optional) – Sometimes the slice had to be moved in foldover direction to place the saturation slabs in the right position. We need to correct for this. This argument moves the line shift millimeter in fold direction. For instance, if fold=”FH” and shift=2, the line will be moved up. Use negative values to move the line down.
- Returns:
nibabel.Nifti1Image – if out_file==None, a niimg-object is returned
str – an actual file if the specified output name is created (NOT RETURNED)
Examples
img = create_line_from_slice(“input.nii.gz”) img <nibabel.nifti1.Nifti1Image at 0x7f5a1de00df0> img.to_filename(‘sub-001_ses-2_task-LR_run-8_bold.nii.gz’)
- fmriproc.image.create_ribbon_from_beam()[source]
This creates a binary image of the outline of the ribbon based on the beam image (see
fmriproc.image.create_line_from_slice()). The line’s dimensions are 16 voxels of 0.25mm x 2.5 mm (slice thickness) and 0.25 mm (frequency encoding direction). We know that the middle of the line is at the center of the slice, so the entire line encompasses 8 voxels up/down from the center. We then select only the voxels from ribbon.- Parameters:
in_file (str) – path to image that should be used as reference (generally this should be the 1 slice file of the first run or something)
ribbon (list, tuple) – input representing the ribbon, e.g., (358,363)
out_file (str, optional) – path specifying the output name of the newly created ‘line’ or ‘beam’ file
- Returns:
nibabel.Nifti1Image – if out_file==None, a niimg-object is returned
str – an actual file if the specified output name is created (NOT RETURNED)
- fmriproc.image.define_mr_parameters()[source]
Returns a dictionary of MR acquisition parameters for MP2RAGE or MP2RAGE-ME sequences.
Parameters can either be loaded from a JSON file or returned as a predefined default (including Universal Pulses presets for MP2RAGE). The function performs basic validation to ensure required keys are present.
- Parameters:
pars_file (str or None, optional) – Path to a JSON file containing sequence parameters. If None, default values are used.
ups (bool, optional) – If True, use Universal Pulses (UPs) parameters when is_mp2rage is True and pars_file is not provided. Ignored when is_mp2rage is False. Default is False.
is_mp2rage (bool, optional) – If True, load or define parameters for an MP2RAGE sequence. If False, parameters for an MP2RAGE-ME (multi-echo) sequence are used. Default is True.
- Returns:
Dictionary containing MR parameters, with required fields depending on the sequence type:
- If is_mp2rage is True:
”TR”: Repetition time of MP2RAGE sequence (in seconds)
”inv_times”: List of inversion times (in seconds)
”fa”: List of flip angles for the two readouts (in degrees)
”nZ”: Number of slices
”FLASH_tr”: List of readout TRs (in seconds)
- If is_mp2rage is False:
”echo_times”: List of echo times (in seconds)
”inv_times”: List of inversion times (in seconds)
”TR”: Repetition time of the MP2RAGE-ME sequence (in seconds)
”fa”: List of flip angles
”nZ”: Number of slices
”FLASH_tr”: List of readout TRs (in seconds)
- Return type:
dict
- Raises:
ValueError – If a required parameter key is missing from the provided JSON file.
Notes
This function is useful for standardized MP2RAGE or MP2RAGE-ME parameter extraction during simulation, reconstruction, or post-processing workflows. Universal Pulses (UPs) presets can be enabled with ups=True for modified acquisition protocols.
- fmriproc.image.get_isocenter()[source]
This function returns the RAS coordinates of the input image’s origin. This resembles the offset relative to the magnetic isocenter
- Parameters:
img (str,nibabel.Nifti1Image) – input image to extract the isocenter coordinate from
- Returns:
array containing isocenter coordinate from img
- Return type:
numpy.ndarray
Example
img = 'sub-001_space-ses1_hemi-R_vert-6002.nii.gz' get_isocenter(img) array([ 0.27998984, 1.49000375, -15.34000604])
- fmriproc.image.get_max_coordinate()[source]
Fetches the point with the maximum value given an input image_file. Useful if you want to find the voxel with the highest value after warping a binary file with ANTs. Mind you, it outputs the VOXEL value, not the actual index of the array. The VOXEL value = idx_array+1 to account for different indexing in nifti & python.
- Parameters:
in_img (str,numpy.ndarray,nibabel.Nifti1Image) – nibabel.Nifti1Image object, string to nifti image or numpy array
- Returns:
np.ndarray – if only 1 max value was detected
list – list of np.ndarray containing the voxel coordinates with max value
Examples
get_max_coordinate('sub-001_space-ses1_hemi-L_vert-875.nii.gz') array([142, 48, 222])
get_max_coordinate('sub-001_space-ses1_hemi-R_vert-6002.nii.gz') [array([139, 35, 228]), array([139, 36, 228])]
- fmriproc.image.get_minmax()[source]
Compute the minimum and maximum intensity values of a neuroimaging file using FSL’s ImageStats.
- Parameters:
file (str) – Path to the neuroimaging file (e.g., NIfTI format).
- Returns:
list –
The minimum intensity value in the image.
The maximum intensity value in the image.
- Return type:
A list containing two float values:
Example
>>> minmax = get_minmax("path/to/image.nii.gz") >>> print(minmax) [0.0, 255.0]
Notes: - Requires Nipype and FSL to be installed and configured. - The function uses the ‘-R’ option in ImageStats, which returns the range of intensity values. - Ensure the input file is in a format supported by FSL, such as .nii or .nii.gz.
- fmriproc.image.layers2line()[source]
Project layer delineations to the line by calculating the probability of each layer membership in each voxel of the 16x720 beam and then average these to get a 1x720 line. Discrete layers are assigned by means of the highest probability of a particular layer membership.
- Parameters:
data (list, numpy.ndarray, str) – (720,720) numpy array with the middle 16 rows containing information about the layers
line (str,nibabel.Nifti1Image,numpy.ndarray) – used for the direction of the line and should have the same dimensions as data. Generally this is the output from create_line_from_slice
- Returns:
(1,720) array of your data in the line
- Return type:
numpy.ndarray
- fmriproc.image.massp_mask_img()[source]
This function extracts the average of each structure in the MASSP-segmentation given an image (e.g., T1map)
- Parameters:
label_file (str) – path to nifti image (MASSP-output ‘label’ file)
img_to_mask (str) – path to nifti image for which we want to extract the averages in the MASSP-structures
out (str) – path to output name. You can either safe it as a csv, json, txt, or pickle file.
nr_structures (int) – set to 31 by default as per the massp script
- Returns:
dictionary containing the average value of each ROI in the units of img_to_mask
- Return type:
dict
Example
file = massp_mask_img(sub-001_desc-massp_label.nii.gz', 'sub-001_T1map.nii.gz', out='massp_t1map.json') file 'massp_t1map.json'
massp_mask_img('sub-001_desc-massp_label.nii.gz', 'sub-001_T1map.nii.gz', out='massp_t1map.json') {'Str-l': 1502,234, 'Str-r': 1081.1125, 'STN-l': 1326.6179, 'STN-r': 1492.2731, 'SN-l': 1540.4317, 'SN-r': 1532.9537, ... }
- fmriproc.image.massp_to_table()[source]
This function creates a tabular output from the label image generated by call_nighresmassp (or any other version of MASSP). Just input the ‘label’ file and hit go. You can either have the dataframe returned or create a file by specifying an output name.
- Parameters:
label_file (str) – path to nifti image (MASSP-output ‘label’ file)
out (str) – path to output name. You can either safe it as a csv, json, txt, or pickle file.
nr_structures (int) – set to 31 by default as per the massp script
unit (str) – output unit (voxels or mm3). Should be ‘vox’ for voxel output, or ‘mm’ for mm^3
- Returns:
dictionary containing the average volume of each ROI in label_file in units of voxel count or mm^3
- Return type:
dict
Example
file = massp_to_table('sub-001_desc-massp_label.nii.gz', out='massp_lut.json') file 'massp_lut.json'
massp_to_table( 'sub-001_desc-massp_label.nii.gz', unit="mm" ) {'Str-l': 10702.2163, 'Str-r': 10816.1125, 'STN-l': 136.6179, 'STN-r': 149.2731, 'SN-l': 540.4317, 'SN-r': 532.9537, ... }
- fmriproc.image.mgz2nii(input, output=None, return_type='file')[source]
wrapper for call_mriconvert to convert mgz image to nifti
- fmriproc.image.nii2mgz(input, output=None, return_type='file')[source]
wrapper for mri_convert to convert mgz image to nifti
- fmriproc.image.reorient_img()[source]
Python wrapper for fslswapdim to reorient an input image given an orientation code. Valid options are: RAS, AIL for now. You can also specify “nb” as code, which reorients the input image to nibabel’s RAS+ convention. If no output name is given, it will overwrite the input image.
- Parameters:
img (str) – nifti-image to be reoriented
code (str, optional) – code for new orientation (default = “RAS”)
out (str, optional) – string to output nifti image
qform (str,int, optional) – set qform code to original (str ‘orig’ = default) or a specified integer
- Returns:
if out==”None”, then img will receive the new coordinate code, otherwise out is created. The function only operates, it doesn’t actually return something that can be captured in a variable
- Return type:
str
Examples
reorient_img(“input.nii.gz”, code=”RAS”, out=”output.nii.gz”) reorient_img(“input.nii.gz”, code=”AIL”, qform=1) reorient_img(“input.nii.gz”, code=”AIL”, qform=’orig’)
- fmriproc.image.slice_timings(nr_slices: int, tr: float, mb_factor: int = 1, order: str = 'ascending', interleaved: bool = False, file: str = None) list[source]
Compute slice timing values for an fMRI acquisition sequence.
- Parameters:
nr_slices (int) – Total number of slices in the acquisition.
tr (float) – Repetition time (TR) of the sequence in seconds.
mb_factor (int, optional) – Multi-band acceleration factor. Defaults to 1.
order (str, optional) – Order of slice acquisitions: ‘ascending’ or ‘descending’.
interleaved (bool, optional) – If True, use interleaved ordering within each band.
file (str, optional) – Use slice timings in a specified txt file. Must match number of slices!
- Returns:
A list of length nr_slices giving the acquisition time (in seconds) for each slice index.
- Return type:
list
- Raises:
ValueError – If nr_slices or tr is not provided, or if order is invalid.
- fmriproc.image.slice_timings_to_json()[source]
Compute and update slice timing information in a JSON file or dictionary.
- Parameters:
json_file (str, dict) – Path to the JSON file containing metadata or a dictionary
- Returns:
If json_file is a dictionary, returns the updated dictionary with slice timings.
If json_file is a file, updates the file in place and returns None.
- Return type:
dict or None
- Raises:
ValueError – If the input is neither a JSON file path nor a dictionary.:
Notes
If tr is provided but differs from the TR in the JSON file, the function logs a warning and takes the TR from the JSON file.
Uses the slice_timings function to compute slice timings.
If json_file is a string (file path), the function updates the file in place.
If json_file is a dictionary, it returns the updated dictionary.
Example
>>> updated_data = slice_timings_to_json("metadata.json", nr_slices=32, tr=2.0) >>> print(updated_data["SliceTiming"])
- fmriproc.image.tissue2line()[source]
Project tissue probability maps to the line by calculating the probability of each tissue type in each voxel of the 16x720 beam and then average these to get a 1x720 line. Discrete tissues are assigned by means of the highest probability of a particular tissue type.
- Parameters:
data (list,numpy.ndarray,str) – for tissue data: list of three numpy array/nifti images/strings describing the probability of white matter/gray matter and CSF
line (str,nibabel.Nifti1Image,numpy.ndarray) – used for the direction of the line and should have the same dimensions as data. Generally this is the output from create_line_from_slice
- Returns:
(1,720) array of your data in the line
- Return type:
numpy.ndarray
- fmriproc.image.tsnr()[source]
This function calculates the temporal SNR of an input image. Can also create 3D tSNR map, but generally will just output the mean tSNR
- Parameters:
img (numpy.ndarray, nibabel.Nifti1Image, str) – input data; can either be a numpy array, a Nifti-image, or a string pointing to a nifti-file.
file_name (str, optional) – path to tSNR-map file. Set to None by default
clip (int, float, optional) – lip the values to tSNR. Default is None
- Returns:
tSNR in array with shape of img (minus last dimension if img.shape>3)
- Return type:
numpy.ndarray
Example
tsnr = tsnr('path/to/func.nii.gz')
- fmriproc.image.write_pymp2rage_nifti()[source]
Calculate and write multiparametric maps to an output directory.
- Parameters:
file (str) – Path to the output NIfTI file.
descriptor (str) – The type of map to be generated (e.g., “t1map”, “r2starmap”).
obj (pymp2rage.MP2RAGE or pymp2rage.MEMP2RAGE object) – An object containing the computed map attributes.
input_files (list or str) – List of input file paths used for computation.
is_mp2rageme (bool, optional) – Indicates whether the MEMP2RAGE sequence is used. Defaults to False (MP2RAGE).
- Returns:
dict –
“nifti” (str): Path to the saved NIfTI file.
”json” (str): Path to the corresponding JSON metadata file.
- Return type:
A dictionary containing:
Notes
Uses pymp2rage for processing and writing multiparametric maps.
The descriptor determines the algorithm and estimation method.
Ensures output files are written only if they do not already exist.
Writes metadata to a JSON file with details on estimation methodology and input data.
- Parameters:
write_pymp2rage_nifti("output.nii.gz" (>>> output =)
"t1map"
obj
input_files)
print(output["nifti"] (>>>)
output["json"])