def create_pial_mask(subject_id, subjects_dir, verbose=False): ribbon = os.path.abspath(os.path.join(subjects_dir, subject_id, 'mri','ribbon')) aseg = os.path.abspath(os.path.join(subjects_dir, subject_id, 'mri','aseg')) mc = MRIConvert() mc.inputs.in_file = ribbon + '.mgz' mc.inputs.out_file = ribbon + '.nii.gz' mc.inputs.out_type = 'nii' mc.cmdline mc.run() mc = MRIConvert() mc.inputs.in_file = aseg + '.mgz' mc.inputs.out_file = aseg + '.nii.gz' mc.inputs.out_type = 'nii' mc.cmdline mc.run() #tic_labels_remove aseg.nii.gz --out_nii 1.mask.nii.gz --remove 3 42 #fslmaths 1.mask.nii.gz -bin 1.mask.nii.gz #fslmaths 1.mask.nii.gz -add ribbon.nii.gz -bin 2.mask.nii.gz #fslmaths 2.mask.nii.gz -kernel sphere 10 -dilM -ero -fillh 3.mask.nii.gz return
def mgz2nii(file): from nipype.interfaces.freesurfer import MRIConvert mc = MRIConvert() mc.inputs.in_file = file mc.inputs.out_file = file[:-3] + 'nii' mc.inputs.out_type = 'nii' mc.run()
def convert_modalities(in_file=None, out_file=None): """Returns an undefined output if the in_file is not defined""" from nipype.interfaces.freesurfer import MRIConvert import os if in_file: convert = MRIConvert() convert.inputs.in_file = in_file convert.inputs.out_file = out_file convert.inputs.no_scale = True convert.run() out_file = os.path.abspath(convert.outputs.out_file) return out_file
def convert_fs_scan(in_file, out_file, resample_type=None): if not os.path.isfile(out_file): from nipype.interfaces.freesurfer import MRIConvert convert = MRIConvert() convert.inputs.in_file = in_file convert.inputs.out_file = out_file convert.inputs.out_orientation = "LPS" convert.inputs.conform = True convert.inputs.no_change = True if resample_type: convert.inputs.resample_type = resample_type convert.run() return os.path.abspath(out_file)
def checkT1s(T1_files, cw256=False): """Verifying size of inputs and setting workflow parameters""" import SimpleITK as sitk import os import sys # check that the files are in a list if not type(T1_files) == list: T1_files = [T1_files] if len(T1_files) == 0: print("ERROR: No T1's Given") sys.exit(-1) for i, t1 in enumerate(T1_files): if t1.endswith(".mgz"): # convert input fs files to NIFTI convert = MRIConvert() convert.inputs.in_file = t1 convert.inputs.out_file = os.path.abspath( os.path.basename(t1).replace('.mgz', '.nii.gz')) convert.run() T1_files[i] = convert.inputs.out_file size = None origvol_names = list() for i, t1 in enumerate(T1_files): # assign an input number file_num = str(i + 1) while len(file_num) < 3: file_num = '0' + file_num origvol_names.append("{0}.mgz".format(file_num)) # check the size of the image img = sitk.ReadImage(t1) if not size: size = img.GetSize() elif size != img.GetSize(): print( "ERROR: T1s not the same size. Cannot process {0} {1} together" .format(T1_files[0], otherFilename)) sys.exit(-1) # check if cw256 is set to crop the images if size is larger than 256 if not cw256: for dim in size: if dim > 256: print("Setting MRI Convert to crop images to 256 FOV") cw256 = True if len(T1_files) > 1: resample_type = 'cubic' else: resample_type = 'interpolate' return T1_files, cw256, resample_type, origvol_names
def change_orientation(image_file, out_file, orientation="LPS"): convert = MRIConvert() convert.inputs.in_file = image_file convert.inputs.out_file = os.path.abspath(out_file) convert.inputs.out_orientation = orientation result = convert.run() return result.outputs.out_file
def generate_ROI_file(FreeSurfer_ROI_file): """ This script generates a dictionary of ROIs found in the FreeSurfer parcellation filename """ from nipype.interfaces.freesurfer import MRIConvert mc = MRIConvert() mc.inputs.in_file = FreeSurfer_ROI_file mc.inputs.out_type = 'niigz' mc.run() import nipype.interfaces.cmtk as cmtk rg = cmtk.ROIGen() rg.inputs.aparc_aseg_file = FreeSurfer_ROI_file.split('.')[0] + '_out.nii.gz' rg.inputs.use_freesurfer_LUT = True out_file = rg.run() return out_file
def checkT1s(T1_files, cw256=False): """Verifying size of inputs and setting workflow parameters""" import SimpleITK as sitk import os import sys # check that the files are in a list if not type(T1_files) == list: T1_files = [T1_files] if len(T1_files) == 0: print("ERROR: No T1's Given") sys.exit(-1) for i, t1 in enumerate(T1_files): if t1.endswith(".mgz"): # convert input fs files to NIFTI convert = MRIConvert() convert.inputs.in_file = t1 convert.inputs.out_file = os.path.abspath(os.path.basename(t1).replace('.mgz', '.nii.gz')) convert.run() T1_files[i] = convert.inputs.out_file size = None origvol_names = list() for i, t1 in enumerate(T1_files): # assign an input number file_num = str(i + 1) while len(file_num) < 3: file_num = '0' + file_num origvol_names.append("{0}.mgz".format(file_num)) # check the size of the image img = sitk.ReadImage(t1) if not size: size = img.GetSize() elif size != img.GetSize(): print("ERROR: T1s not the same size. Cannot process {0} {1} together".format(T1_files[0], otherFilename)) sys.exit(-1) # check if cw256 is set to crop the images if size is larger than 256 if not cw256: for dim in size: if dim > 256: print("Setting MRI Convert to crop images to 256 FOV") cw256 = True if len(T1_files) > 1: resample_type = 'cubic' else: resample_type = 'interpolate' return T1_files, cw256, resample_type, origvol_names
def convert_fs_scan(in_file, out_file, resample_type=None): """ This function... :param in_file: :param out_file: :param resample_type: :return: """ if not os.path.isfile(out_file): from nipype.interfaces.freesurfer import MRIConvert convert = MRIConvert() convert.inputs.in_file = in_file convert.inputs.out_file = out_file convert.inputs.out_orientation = "LPS" convert.inputs.conform = True convert.inputs.no_change = True if resample_type: convert.inputs.resample_type = resample_type convert.run() return os.path.abspath(out_file)
def change_orientation(image_file, out_file, orientation="LPS"): """ This function... :param image_file: :param out_file: :param orientation: :return: result.outputs.out_file """ convert = MRIConvert() convert.inputs.in_file = image_file convert.inputs.out_file = os.path.abspath(out_file) convert.inputs.out_orientation = orientation result = convert.run() return result.outputs.out_file
def change_orientation(image_file, out_file, orientation="LPS"): """ This function... :param image_file: :param out_file: :param orientation: :return: """ convert = MRIConvert() convert.inputs.in_file = image_file convert.inputs.out_file = os.path.abspath(out_file) convert.inputs.out_orientation = orientation result = convert.run() return result.outputs.out_file
def create_pial_mask(subject_id, subjects_dir, output_filename, output_directory, reference=None, mo_radius=7, verbose=False, save=False): mri_directory = os.path.abspath( os.path.join(subjects_dir, subject_id, 'mri')) if False: # I attempted to use nipype to call the mri_surf2vol. This did not work so I had to use the subprocess method. surf2vol = Surface2VolTransform() # surf2vol.inputs.reg_file = 'register.mat' surf2vol.inputs.template_file = os.path.abspath( os.path.join(mri_directory, 'brain.mgz')) surf2vol.inputs.subjects_dir = subjects_dir surf2vol.inputs.subject_id = subject_id surf2vol.mkmask = True surf2vol.projfrac = 0.05 surf2vol.surf_name = 'pial' surf2vol.args = '--fillribbon --fill-projfrac -2 0 0.05' for ii in ['lh', 'rh']: surf2vol.inputs.hemi = 'lh' surf2vol.transformed_file = os.path.abspath( os.path.join(output_directory, '_cpm_mask_surf2vol.pial_' + ii + '.nii.gz')) if verbose: surf2vol.cmdline else: for ii in ['lh', 'rh']: ii_output = os.path.abspath( os.path.join(output_directory, '_cpm_mask_surf2vol.pial_' + ii + '.nii.gz')) command = [ 'mri_surf2vol', '--hemi', ii, '--surf', 'pial', '--o', ii_output, '--identity', subject_id, '--template', os.path.abspath( os.path.join(subjects_dir, subject_id, 'mri', 'brain.mgz')), '--mkmask', '--fillribbon', '--fill-projfrac', '-2', '0', '0.05' ] if not os.path.isfile(ii_output): util.iw_subprocess(command, verbose_flag=verbose) if not os.path.isfile(ii_output): print(ii_output + ' does not exist. Exiting!') exit() # Convert aseg.nii.gz aseg_nii_gz = os.path.abspath( os.path.join(output_directory, '_cpm_aseg.nii.gz')) if not os.path.isfile(aseg_nii_gz): mri_convert = MRIConvert(in_file=os.path.abspath( os.path.join(mri_directory, 'aseg.mgz')), out_file=aseg_nii_gz, out_type='niigz') mri_convert.run() # Remove GM Cortex from aseg.nii.gz mask_aseg_without_gm_cortex = os.path.join( output_directory, '_cpm_mask.aseg_without_gm_cortex.nii.gz') if not os.path.isfile(mask_aseg_without_gm_cortex): labels.remove(aseg_nii_gz, [3, 42], [], mask_aseg_without_gm_cortex, merge=1) # 1) Combine masks into a single mask # 2) Threshold and invert mask # 3) Grab largest component # 4) Threshold image to remove negative numbers # 5) ImageMath Opening operation with radius 3 # 6) Threshold image to remove negative numbers # 7) ImageMath Closing operation with radius 3 # 8) Threshold and invert mask. if not os.path.isfile(os.path.join(output_directory, '_cpm_01.mask.nii.gz')): os.chdir(output_directory) commands = [[ 'fslmaths', os.path.join(output_directory, '_cpm_mask.aseg_without_gm_cortex.nii.gz'), '-add', os.path.abspath( os.path.join(output_directory, '_cpm_mask_surf2vol.pial_lh.nii.gz')), '-add', os.path.abspath( os.path.join(output_directory, '_cpm_mask_surf2vol.pial_rh.nii.gz')), '-bin', '-fillh26', os.path.abspath( os.path.join(output_directory, '_cpm_01.mask.nii.gz')) ], [ 'fslmaths', os.path.join(output_directory, '_cpm_01.mask.nii.gz'), '-thr', 0, '-binv', os.path.join(output_directory, '_cpm_02.mask.nii.gz') ], [ 'ImageMath', 3, '_cpm_03.mask.nii.gz', 'GetLargestComponent', '_cpm_02.mask.nii.gz' ], [ 'ImageMath', 3, '_cpm_04.mask.nii.gz', 'MO', '_cpm_03.mask.nii.gz', 7 ], [ 'fslmaths', '_cpm_04.mask.nii.gz', '-thr', 0, '-bin', '_cpm_05.mask.nii.gz' ], [ 'ImageMath', 3, '_cpm_06.mask.nii.gz', 'MC', '_cpm_05.mask.nii.gz', 7 ], [ 'fslmaths', '_cpm_06.mask.nii.gz', '-thr', 0, '-binv', '_cpm_07.mask.nii.gz' ]] for ii in commands: util.iw_subprocess(ii, verbose_flag=verbose) if reference is not None: command = [ 'antsApplyTransforms', '-i', os.path.join(output_directory, '_cpm_07.mask.nii.gz'), '-r', reference, '-n', 'Multilabel', '-o', os.path.join(output_directory, output_filename), '-t', 'identity' ] util.iw_subprocess(command, verbose_flag=verbose) else: shutil.copy2(os.path.join(output_directory, '_cpm_07.mask.nii.gz'), os.path.join(output_directory, out_filename)) if not save: remove_files = [ os.path.join(output_directory, '_cpm_01.mask.nii.gz'), os.path.join(output_directory, '_cpm_02.mask.nii.gz'), os.path.join(output_directory, '_cpm_03.mask.nii.gz'), os.path.join(output_directory, '_cpm_04.mask.nii.gz'), os.path.join(output_directory, '_cpm_05.mask.nii.gz'), os.path.join(output_directory, '_cpm_06.mask.nii.gz'), os.path.join(output_directory, '_cpm_07.mask.nii.gz'), os.path.join(output_directory, '_cpm_aseg.nii.gz'), os.path.join(output_directory, '_cpm_mask.aseg_without_gm_cortex.nii.gz'), os.path.abspath( os.path.join(output_directory, '_cpm_mask_surf2vol.pial_lh.nii.gz')), os.path.abspath( os.path.join(output_directory, '_cpm_mask_surf2vol.pial_rh.nii.gz')) ] clean(remove_files) return
def __init__(self,coords, img_file, subject=None, coord_type='ras', working_dir=None, **traits): """ General class to work with coordinates Parameters ----------- coords: numpy array x,y,z coordinates matrix (npoints x 3) img_file: str path to image file subject: str subject name coord_type: str, {'ras', 'voxel'} coordinate system working_dir: the path to working directory **traits: other traits of the coordinates; the traits size should be equal to the number of npoints for instance, one can add "name" or "color" as extra traits for each coordinate Returns -------- An object of Coords class """ coords = np.atleast_2d(coords) self.img_file = img_file self.subject=subject self.coord_type = coord_type self.img = nib.load(img_file) self.working_dir = working_dir self.vox2ras = self.img.affine self.ras2vox = np.linalg.inv(self.vox2ras) self.npoints = coords.shape[0] self.coordinates = {} affineM= self._to_affine_matrix(coords) self._count=0 if coord_type=='ras': self.coordinates['ras_coord'] = coords self.coordinates['voxel_coord'] = np.round(np.dot(self.ras2vox,affineM).T[:,:3]) elif coord_type=='voxel': self.coordinates['voxel_coord'] = coords self.coordinates['ras_coord'] = np.dot(self.vox2ras,affineM).T[:,:3] else: raise ValueError('type should be either "ras" or "voxel"') ### to freesurfer coords rnum1 = np.random.randint(10**15,10**16) rnum2 = np.random.randint(10**10,10**11) rnum = '{rnum1}_{rnum2}'.format(rnum1=rnum1,rnum2=rnum2) os.makedirs(os.path.join(os.path.abspath('.'),'temp_{rnum}'.format(rnum=rnum))) wf_dir = os.path.join(os.path.abspath('.'),'temp_{rnum}'.format(rnum=rnum)) ## creating rawavg.mgz mc = MRIConvert() mc.inputs.in_file = img_file mc.inputs.out_file = os.path.join(wf_dir,'rawavg.mgz') mc.inputs.out_type = 'mgz' mc.run() ## creating orig.mgz mc = MRIConvert() mc.inputs.in_file = os.path.join(wf_dir,'rawavg.mgz') mc.inputs.out_file = os.path.join(wf_dir,'orig.mgz') mc.inputs.out_type = 'mgz' mc.inputs.conform = True mc.run() rawavg_file = os.path.join(wf_dir,'rawavg.mgz') orig_file = os.path.join(wf_dir,'orig.mgz') ### loading orig_img = nib.freesurfer.load(orig_file) self.ras2fsvox = orig_img.header.get_ras2vox() self.fsvox2ras_tkr = orig_img.header.get_vox2ras_tkr() self.ras2ras_tkr = np.dot(self.fsvox2ras_tkr,self.ras2fsvox) ras_affineM = self._to_affine_matrix(self.coordinates['ras_coord']) self.coordinates['ras_tkr_coord'] = np.dot(self.fsvox2ras_tkr,np.dot(self.ras2fsvox, ras_affineM)).T[:,:3] self.coordinates['fsvoxel_coord'] = np.round(np.dot(self.ras2fsvox,ras_affineM).T[:,:3]) shutil.rmtree(wf_dir) ##3 adding traits self.traits_list = [] for trait in traits: self.add_trait(trait,traits[trait])
def calculate_equivolumetric_layer(path, sub, n_layers, path_output): """ This script computes the volumetric layering from the FreeSurfer ribbon mask. Inputs: *path: path to the freesurfer segmentation folder. *sub: name of the freesurfer segmentation folder. *n_layers: number of layers. *path_output: path where output is saved. created by Daniel Haenelt Date created: 20-11-2018 Last modified: 02-09-2018 """ import os import nibabel as nb from nipype.interfaces.freesurfer import MRIConvert from nighres.surface import probability_to_levelset from nighres.laminar import volumetric_layering # make output folder if not os.path.exists(path_output): os.mkdir(path_output) if not os.path.exists(os.path.join(path_output,"binary")): os.mkdir(os.path.join(path_output,"binary")) if not os.path.exists(os.path.join(path_output,"levelset")): os.mkdir(os.path.join(path_output,"levelset")) # convert ribbon to nifti ribbon = MRIConvert() ribbon.inputs.in_file = os.path.join(path,sub,"mri","ribbon.mgz") ribbon.inputs.out_file = os.path.join(path,sub,"mri","ribbon.nii.gz") ribbon.inputs.out_type = "niigz" ribbon.run() # get GM/WM and GM/CSF boundaries ribbon_img = nb.load(os.path.join(path,sub,"mri","ribbon.nii.gz")) ribbon_array = ribbon_img.get_fdata() # layering using nighres hemi = ["lh", "rh"] wm = [2, 41] gm = [3, 42] for i in range(len(hemi)): wm_array = ribbon_array.copy() wm_array[wm_array == wm[i]] = 1 wm_array[wm_array != 1] = 0 csf_array = ribbon_array.copy() csf_array[csf_array == gm[i]] = 1 csf_array[csf_array == wm[i]] = 1 csf_array[csf_array != 1] = 0 output = nb.Nifti1Image(wm_array, ribbon_img.affine, ribbon_img.header) nb.save(output,os.path.join(path_output,"binary",hemi[i]+"_wm.nii")) output = nb.Nifti1Image(csf_array, ribbon_img.affine, ribbon_img.header) nb.save(output,os.path.join(path_output,"binary",hemi[i]+"_csf.nii")) # probability to levelset probability_to_levelset(os.path.join(path_output,"binary",hemi[i]+"_wm.nii"), save_data=True, output_dir=os.path.join(path_output,"levelset"), file_name=hemi[i]+"_wm") # probability to levelset probability_to_levelset(os.path.join(path_output,"binary",hemi[i]+"_csf.nii"), save_data=True, output_dir=os.path.join(path_output,"levelset"), file_name=hemi[i]+"_csf") # layering suffix = "_p2l-surf" volumetric_layering(os.path.join(path_output,"levelset",hemi[i]+"_wm"+suffix+".nii.gz"), os.path.join(path_output,"levelset",hemi[i]+"_csf"+suffix+".nii.gz"), n_layers=n_layers, topology_lut_dir=None, save_data=True, output_dir=path_output, file_name=hemi[i])
from nipype.interfaces.freesurfer import MRIConvert import os import shutil import csv import sys import csv from os import listdir from os.path import isfile, join ############# MRI CONVERT ############## # path of subjects in .mgz format sub_path = '/media/Ali/8A9E6F039E6EE6E3/freesurfer/subjects' # path of output converted files to .nii format output_dir = '/media/Ali/8A9E6F039E6EE6E3/MRI/MRI-Converted' dirs = [f for f in listdir(sub_path) if f.startswith('sub') == True] mc = MRIConvert() for sub in dirs: mgz_path = os.path.join(sub_path, sub, 'mri/brain.mgz') nii_path = os.path.join(output_dir, '{}-brain.nii'.format(sub)) mc.inputs.in_file = mgz_path mc.inputs.out_file = nii_path mc.inputs.out_type = 'nii' mc.run()