def segmentation_pipeline(self, img_type=2, **name_maps): pipeline = self.new_pipeline( name='FAST_segmentation', name_maps=name_maps, inputs=[FilesetSpec('brain', nifti_gz_format)], outputs=[FilesetSpec('wm_seg', nifti_gz_format)], desc="White matter segmentation of the reference image", references=[fsl_cite]) fast = pipeline.add('fast', fsl.FAST(img_type=img_type, segments=True, out_basename='Reference_segmentation'), inputs={'in_files': ('brain', nifti_gz_format)}, requirements=[fsl_req.v('5.0.9')]), # Determine output field of split to use if img_type == 1: split_output = 'out3' elif img_type == 2: split_output = 'out2' else: raise ArcanaUsageError( "'img_type' parameter can either be 1 or 2 (not {})".format( img_type)) pipeline.add('split', Split(splits=[1, 1, 1], squeeze=True), connect={'inlist': (fast, 'tissue_class_files')}, outputs={split_output: ('wm_seg', nifti_gz_format)}) return pipeline
def build_nodes(self): # BET - Skullstrip anatomical Image self.bet_anat = Node(fsl.BET(frac=0.5, robust=True, output_type='NIFTI_GZ'), name="bet_anat") # image segmentation self.segmentation = Node(fsl.FAST(output_type='NIFTI_GZ'), name='segmentation') # threshold WM probability image self.threshold = Node(fsl.Threshold(thresh=0.5, args='-bin', output_type='NIFTI_GZ'), name='threshold') # flirt - pre-alignment of images self.coreg_pre = Node(fsl.FLIRT(dof=6, output_type='NIFTI_GZ'), name='coreg_pre') # co-reg self.coreg_mi = Node(fsl.FLIRT(bins=640, cost_func='bbr', interp='spline', searchr_x=[-180, 180], searchr_y=[-180, 180], searchr_z=[-180, 180], dof=6, output_type='NIFTI_GZ'), name='coreg_mi') # apply warp map to images self.applywarp = Node(fsl.preprocess.ApplyXFM(apply_xfm=True, output_type='NIFTI_GZ'), name='applywarp') # Apply coregistration warp to mean file self.applywarp_mean = Node(fsl.FLIRT(interp='spline',output_type='NIFTI_GZ'), name="applywarp_mean")
def segmentation_pipeline(self, img_type=2, **kwargs): pipeline = self.create_pipeline( name='FAST_segmentation', inputs=[DatasetSpec('brain', nifti_gz_format)], outputs=[DatasetSpec('wm_seg', nifti_gz_format)], desc="White matter segmentation of the reference image", version=1, citations=[fsl_cite], **kwargs) fast = pipeline.create_node(fsl.FAST(), name='fast', requirements=[fsl509_req]) fast.inputs.img_type = img_type fast.inputs.segments = True fast.inputs.out_basename = 'Reference_segmentation' pipeline.connect_input('brain', fast, 'in_files') split = pipeline.create_node(Split(), name='split') split.inputs.splits = [1, 1, 1] split.inputs.squeeze = True pipeline.connect(fast, 'tissue_class_files', split, 'inlist') if img_type == 1: pipeline.connect_output('wm_seg', split, 'out3') elif img_type == 2: pipeline.connect_output('wm_seg', split, 'out2') else: raise ArcanaUsageError( "'img_type' parameter can either be 1 or 2 (not {})".format( img_type)) return pipeline
def do_Tissue_Segmentation(infile): ''' Parameters ---------- infile : str full path to the input image. Returns ------- white matter, gray matter, csf tissue probablity maps ''' print(f'doing tissue segmentation for {infile}\n') fastr = fsl.FAST() fastr.inputs.in_files = infile if infile.find('hrT1') != -1 or infile.find('hrFLAIR') != -1: fastr.inputs.img_type = 1 elif infile.find('hrT2') != -1: fastr.inputs.img_type = 2 elif infile.find('hrPD') != -1: fastr.inputs.img_type = 3 fastr.inputs.output_biascorrected = False fastr.inputs.output_biasfield = False fastr.inputs.no_pve = True #fastr.inputs.out_basename = infile fastr.inputs.probability_maps = False fastr.inputs.segments = False fastr.inputs.output_type = 'NIFTI' fastr.run() print(f'tissue segmentation done for {infile}')
def gen_anat_segs(anat_loc): # # Custom inputs# # try: FSLDIR = os.environ['FSLDIR'] except KeyError: print('FSLDIR environment variable not set!') import nipype.interfaces.fsl as fsl #import nibabel as nib #from nilearn.image import resample_img from nipype.interfaces.fsl import ExtractROI print( '\nSegmenting anatomical image to create White Matter and Ventricular CSF masks for contraining the tractography...' ) # Create MNI ventricle mask print('Creating MNI space ventricle mask...') anat_dir = os.path.dirname(anat_loc) lvent_out_file = "%s%s" % (anat_dir, '/LVentricle.nii.gz') rvent_out_file = "%s%s" % (anat_dir, '/RVentricle.nii.gz') MNI_atlas = "%s%s" % ( FSLDIR, '/data/atlases/HarvardOxford/HarvardOxford-sub-prob-1mm.nii.gz') fslroi1 = ExtractROI(in_file=MNI_atlas, roi_file=lvent_out_file, t_min=2, t_size=1) os.system(fslroi1.cmdline) fslroi2 = ExtractROI(in_file=MNI_atlas, roi_file=rvent_out_file, t_min=13, t_size=1) os.system(fslroi2.cmdline) mni_csf_loc = anat_dir + '/VentricleMask.nii.gz' args = "%s%s%s" % ('-add ', rvent_out_file, ' -thr 0.1 -bin -dilF') maths = fsl.ImageMaths(in_file=lvent_out_file, op_string=args, out_file=mni_csf_loc) os.system(maths.cmdline) # Segment anatomical (should be in MNI space) print('Segmenting anatomical image using FAST...') fastr = fsl.FAST() fastr.inputs.in_files = anat_loc fastr.inputs.img_type = 1 fastr.run() old_file_csf = "%s%s" % (anat_loc.split('.nii.gz')[0], '_pve_0.nii.gz') new_file_csf = "%s%s" % (anat_dir, '/CSF.nii.gz') old_file_wm = "%s%s" % (anat_loc.split('.nii.gz')[0], '_pve_2.nii.gz') new_file_wm = "%s%s" % (anat_dir, '/WM.nii.gz') os.rename(old_file_csf, new_file_csf) os.rename(old_file_wm, new_file_wm) # Reslice to 1x1x1mm voxels #img=nib.load(anat_loc) #vox_sz = img.affine[0][0] #targ_aff = img.affine/(np.array([[int(abs(vox_sz)),1,1,1],[1,int(abs(vox_sz)),1,1],[1,1,int(abs(vox_sz)),1],[1,1,1,1]])) #new_file_csf_res = resample_img(new_file_csf, target_affine=targ_aff) #new_file_wm_res = resample_img(new_file_wm, target_affine=targ_aff) #nib.save(new_file_csf_res, new_file_csf) #nib.save(new_file_wm_res, new_file_wm) return new_file_csf, mni_csf_loc, new_file_wm
def _run_interface_pbr(self, runtime): #insert workflow here: import nipype.interfaces.fsl as fsl import nipype.pipeline.engine as pe import nipype.interfaces.freesurfer as fs import nipype.interfaces.io as nio bet = pe.MapNode(interface=fsl.BET(), name = 'bet', iterfield=['frac']) bet.inputs.in_file = #define in_file right here bet.inputs.frac = [0.7, 0.5, 0.3] fast = pe.MapNode(interface=fsl.FAST(), name='fast', iterfield=['in_files']) ss = pe.MapNode(interface=fs.SegStats(), name='ss', iterfield=['segmentation_file']) ds = pe.Node(interface=nio.DataSink(), name="ds", iterfield=['in_files']) ds.inputs.base_directory = #define the output here workflow = pe.Workflow(name='ute_flow') workflow.base_dir = '.' workflow.connect([(bet, fast, [('out_file', 'in_files')]), (fast, ss,[('mixeltype', 'segmentation_file')]), (ss, ds, [('avgwf_file', 'in_files')])]) workflow.run() """print(self.inputs)""" #this was used for checking if the workflow was being triggered and run #vi inserted into ucsf server side ute.py return runtime
def run_fast(outputs_dir, in_file, contrast): """ Deletes old Fast outputs and re-runs Fast in the old directory. Running with 4 classes Generally, for a neonatal T2: class 0 : CSF/hyperintense WM class 1 : WM class 2 : GM class 3 : Extra-axial CSF/Noise """ fast_dir = os.path.join(outputs_dir, "Fast_PVE") [os.remove(os.path.join(fast_dir, n)) for n in os.listdir(fast_dir)] shutil.copy2(os.path.join(outputs_dir, "T2_Bias_Corrected", in_file), fast_dir) cp_file = os.path.join(fast_dir, in_file) if contrast == "T2": img_type = 2 elif contrast == "T1": img_type = 1 os.chdir(fast_dir) FastSeg = fsl.FAST() FastSeg.inputs.img_type = img_type FastSeg.inputs.number_classes = 4 FastSeg.inputs.output_biascorrected = False FastSeg.inputs.in_files = cp_file FastSeg.run()
def segmentation(self, subject): """ Segmentation Outputs: masks/anatomy/grey.nii.gz Parameters subject = Subject Dir object """ print ">>> Segmentation" gm_mask_name = os.path.join( subject.masks_dir(), 'anatomy', 'grey.nii.gz') if os.path.isfile(gm_mask_name): return brain_image = subject.anatomical_nii("brain") # Fixing FAST bug lastcwd = os.getcwd() os.chdir(subject.anatomical_dir()) fast = fsl.FAST( in_files=brain_image, out_basename=os.path.join( subject.masks_dir(), 'anatomy', 'seg'), img_type=1, number_classes=3, hyper=0.4, segments=True) try: result = fast.run() os.chdir(lastcwd) gm_pve_file = result.outputs.partial_volume_files[1] except: gm_pve_file = os.path.join( subject.masks_dir(), 'anatomy', 'seg_pve_1.nii.gz') gm_seg_file = os.path.join( subject.masks_dir(), 'anatomy', 'seg_seg_1.nii.gz') if False: cmd = 'fslview {} {} -l Red -t 0.1 -b 0,0.1'.format( brain_image, gm_pve_file) pro = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) thr = float( raw_input("Insert a GM thershold for the mask: default is 0\n")) or 0.0 os.killpg(pro.pid, signal.SIGTERM) gen_mask = fsl.utils.ImageMaths( in_file=gm_pve_file, op_string='-thr {} -bin'.format(thr), out_file=gm_mask_name) gen_mask.run() else: os.rename(gm_seg_file, gm_mask_name)
def segment_fslFAST(population, workspace_dir): count = 0 #subject = population[subject_index] for subject in population: count += 1 print '========================================================================================' print '%s- Runnning FSL FAST Segmentation on subject %s_%s' % ( count, subject[0:10], workspace_dir[-1]) print '' # define subject directory and anatomical file path subject_dir = os.path.join(workspace_dir, subject[0:4]) anatomical_dir = os.path.join(subject_dir, 'anatomical_original') anatomical_file = os.path.join(anatomical_dir, 'ANATOMICAL.nii') # check if the file exists if os.path.isfile( os.path.join( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST', 'fslFAST_seg_2.nii.gz'))): print 'Brain already segmented......... moving on' else: # define destination directory for spm segmentation outputs try: os.makedirs( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST')) except OSError: out_dir = str( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST')) out_dir = str( os.path.join(workspace_dir, subject[0:4], 'segmentation_fslFAST')) # running bet print '..... Running Brain Extraction' os.chdir(out_dir) btr = fsl.BET() btr.inputs.in_file = anatomical_file btr.inputs.frac = 0.7 btr.run() # run FSL FAST segmentation print '..... Running FSL FAST Segmentation ' os.chdir(out_dir) seg = fsl.FAST() seg.inputs.in_files = os.path.join(out_dir, 'ANATOMICAL_brain.nii.gz') seg.inputs.out_basename = 'fslFAST' seg.inputs.segments = True seg.inputs.probability_maps = True seg.run() print '========================================================================================'
def functional_segmentation(self, subject): """ Functional Segmentation Outputs: masks/*run_name*/grey.nii.gz Parameters subject = Subject Dir object """ print ">>> Functional Segmentation" for task, directories in subject.dir_tree('functional').iteritems(): for directory in directories: run_name = directory.split('/')[-1] gm_mask_name = os.path.join( subject.masks_dir(), run_name, 'grey.nii.gz') if os.path.isfile(gm_mask_name): continue bold_file = os.path.join(directory, 'mid_func.nii.gz') out_basename = os.path.join( subject.masks_dir(), run_name, 'seg') # Fixing FAST bug lastcwd = os.getcwd() os.chdir(directory) fast = fsl.FAST(in_files=bold_file, out_basename=out_basename, img_type=2, number_classes=3, hyper=0.1, output_biascorrected=True, output_biasfield=True, bias_iters=5, iters_afterbias=2, segments=True) try: result = fast.run() os.chdir(lastcwd) gm_pve_file = result.outputs.partial_volume_files[0] except: gm_pve_file = '{}_pve_0.nii.gz'.format(out_basename) try: os.rename(gm_pve_file, gm_mask_name) except: pass
def preporcessFMRI(): global nii_file, preproc_status # skull stripping btr = fsl.BET() btr.inputs.in_file = nii_file btr.inputs.frac = 0.7 btr.inputs.out_file = nii_file btr.cmdline res = btr.run() preproc_status = 20 # segmentation and bias correction fastr = fsl.FAST() fastr.inputs.in_files = nii_file fastr.cmdline out = fastr.run() preproc_status = 40 # coregistration flt = fsl.FLIRT(bins=640, cost_func='mutualinfo') flt.inputs.in_file = nii_file flt.inputs.reference = nii_file flt.inputs.output_type = "NIFTI_GZ" preproc_status = 45 flt.cmdline preproc_status = 50 res = flt.run() preproc_status = 60 # motion correction mcflt = fsl.MCFLIRT() mcflt.inputs.in_file = nii_file mcflt.inputs.cost = 'mutualinfo' mcflt.inputs.out_file = nii_file mcflt.cmdline res = mcflt.run() preproc_status = 80 # smoothing sus = fsl.SUSAN() sus.inputs.in_file = nii_file sus.inputs.out_file = nii_file sus.inputs.brightness_threshold = 2000.0 sus.inputs.fwhm = 8.0 result = sus.run() preproc_status = 100
def gen_anat_segs(anat_loc, FSLDIR): import nipype.interfaces.fsl as fsl from nipype.interfaces.fsl import ExtractROI ##Create MNI ventricle mask print('Creating MNI space ventricle mask...') anat_dir = os.path.dirname(anat_loc) lvent_out_file = anat_dir + '/LVentricle.nii.gz' rvent_out_file = anat_dir + '/RVentricle.nii.gz' MNI_atlas = FSLDIR + '/data/atlases/HarvardOxford/HarvardOxford-sub-prob-1mm.nii.gz' fslroi1 = ExtractROI(in_file=MNI_atlas, roi_file=lvent_out_file, t_min=2, t_size=1) os.system(fslroi1.cmdline) fslroi2 = ExtractROI(in_file=MNI_atlas, roi_file=rvent_out_file, t_min=13, t_size=1) os.system(fslroi2.cmdline) mni_csf_loc = anat_dir + '/VentricleMask.nii.gz' args = '-add ' + rvent_out_file + ' -thr 0.1 -bin -dilF' maths = fsl.ImageMaths(in_file=lvent_out_file, op_string=args, out_file=mni_csf_loc) os.system(maths.cmdline) ##Segment anatomical (should be in MNI space) print('Segmenting anatomical image using FAST...') fastr = fsl.FAST() fastr.inputs.in_files = anat_loc fastr.inputs.img_type = 1 fastr.run() old_file_csf = anat_loc.split('.nii.gz')[0] + '_pve_0.nii.gz' new_file_csf = anat_dir + '/CSF.nii.gz' os.rename(old_file_csf, new_file_csf) old_file_wm = anat_loc.split('.nii.gz')[0] + '_pve_2.nii.gz' new_file_wm = anat_dir + '/WM.nii.gz' os.rename(old_file_wm, new_file_wm) return (new_file_csf, new_file_wm, mni_csf_loc)