Source code for cmind.utils.nifti_utils

"""
**NIFTI Handling Utilities** 
A series of utilities for working with NIFTI files

cmind_save_nii_mod_header

"""
from __future__ import division, print_function, absolute_import
import numpy as np
import nibabel as nib
        
[docs]def cmind_save_nii_mod_header(old_nii,data,out_name,nii_type=None,cal_range=None): """save data to out_name.nii.gz, reusing the nifti header from old_nii with appropriate modifications to image dimensions Parameters ---------- old_nii : Nifti1Image Nifti-1 image as read in by nibabel data : ndarray array of image data to write to `out_name` out_name : str filename for the output image. File type will be determined by the extension given here (e.g. myfile.nii.gz would write a gzipped Nifti-1 image) nii_type : str, optional data type for the output image. if unspecified, will be whatever was in `old_nii` cal_range : list or tuple two-element list of the intensities to store in the cal_min and cal_max fields of the nifti file Notes ----- Write out an image file containing the data in `data` with header information copied from `old_nii`. If old_nii is 3D, but data is 4D, the image dimensions will be updated accordingly. Whether the output is NIFTI or NIFTI-GZ will be determined by the extension of `out_name` """ old_hdr=old_nii.get_header(); new_hdr=old_hdr.copy() new_hdr.set_data_shape(data.shape) if nii_type: new_hdr.set_data_dtype(nii_type) if cal_range: new_hdr['cal_min'] = cal_range[0]; new_hdr['cal_max'] = cal_range[1]; else: new_hdr['cal_min'] = np.min(data); new_hdr['cal_max'] = 0.8*np.max(data); #new_hdr['glmin'] = np.min(data) #new_hdr['glmax'] = np.max(data) new_BaselineCBF_nii=nib.Nifti1Image(data,old_nii.get_affine(),new_hdr); new_BaselineCBF_nii.to_filename(out_name) #nii_filename='IRC04H_00M016_P_1_WIP_T1W_3D_IRCstandard32_SENSE_4_1.nii.gz'
[docs]def round_affine_to_axial(nii_filename): """ Resets the affine to axial (preserving sign) """ nii=nib.load(nii_filename) aff=nii.get_affine() #aff[0:3,0:3]=np.round(aff[0:3,0:3]) aff[0:3,0:3]=np.eye(3)*np.sign(aff[0:3,0:3]) nii2=nib.Nifti1Image(data=nii.get_data(),affine=aff,header=nii.get_header()) nii2.to_filename(nii_filename)