def genrDcm2nii(hq, dcm, oniiDir, series_desc, series_id, quality): if not os.path.exists(oniiDir): os.makedirs(oniiDir) #set the output name based on the seq_dictionary if hq: niiOutName = seq_dict[series_desc] + '_' + str(series_id) + '_best' else: niiOutName = seq_dict[series_desc] + '_' + str(series_id) if os.path.exists(os.path.join(oniiDir, niiOutName + '.nii.gz')) and not overwriteExisting: return #run the dcm2nii conversion dcmCvt = dcm2nii.Dcm2nii(source_names=dcm, terminal_output='stream', gzip_output=True, output_dir=oniiDir, reorient=False, reorient_and_crop=False) #print dcmCvt.cmdline dcmCvt.run() #it outputs some nonsense, so we have to rename it os.rename(dcmCvt.output_files[0], os.path.join(oniiDir, niiOutName + '.nii.gz')) if hasattr(dcmCvt, 'bvecs'): if len(dcmCvt.bvecs) > 0: os.rename(dcmCvt.bvecs[0], os.path.join(oniiDir, niiOutName + '.bvec')) os.rename(dcmCvt.bvals[0], os.path.join(oniiDir, niiOutName + '.bval')) #data prov. addcmd = True if convertIdc: #remove any instance of R-number... addcmd = False logFile = os.path.join(oniiDir, niiOutName + '.log') write_log(dcmCvt.cmdline, logFile, addcmd, [series_id, series_desc, quality])
def convert_fieldmap_dicom(name='convert_fmap_dicoms'): inputnode = pe.Node( utility.IdentityInterface(fields=['fieldmap_dicom_dir']), name='inputspec') outputnode = pe.Node(utility.IdentityInterface( fields=['phase_difference', 'magnitude', 'delta_TE']), name='outputspec') n_fieldmap_dicom_files = pe.Node(nio.DataGrabber( template='*.dcm', sort_filelist=True, ), name='fieldmap_dicom_files') n_convert_b0_dicom = pe.Node(dcm2nii.Dcm2nii( gzip_output=True, id_in_filename=True, date_in_filename=True, config_file='/home_local/bpinsard/.dcm2nii/dcm2nii.ini'), name='convert_b0_dicom') n_extract_dicom_parameters = pe.Node(utility.Function( input_names=['dicom_folder'], output_names=[ 'TE1', 'TE2', 'delta_TE', 'rwv_rescale_intercept', 'rwv_rescale_slope' ], function=fieldmap_extract_dicom_parameters), name='extract_dicom_parameters') n_prepare_files = pe.Node(utility.Function( input_names=[ 'converted_files', 'rwv_rescale_intercept', 'rwv_rescale_slope' ], output_names=['phase_difference', 'magnitude'], function=fieldmap_prepare_files), name='prepare_files') w = pe.Workflow(name=name) w.connect([ (inputnode, n_fieldmap_dicom_files, [('fieldmap_dicom_dir', 'base_directory')]), (n_fieldmap_dicom_files, n_convert_b0_dicom, [('outfiles', 'source_names')]), (inputnode, n_extract_dicom_parameters, [('fieldmap_dicom_dir', 'dicom_folder')]), (n_extract_dicom_parameters, n_prepare_files, [('rwv_rescale_intercept', 'rwv_rescale_intercept'), ('rwv_rescale_slope', 'rwv_rescale_slope')]), (n_convert_b0_dicom, n_prepare_files, [('converted_files', 'converted_files')]), (n_prepare_files, outputnode, [('phase_difference', 'phase_difference'), ('magnitude', 'magnitude')]), (n_extract_dicom_parameters, outputnode, [('delta_TE', 'delta_TE')]), ]) return w
def convert_rsfmri_dicom(name='convert_rsfmri_dicom'): inputnode = pe.Node( utility.IdentityInterface( fields=['rsfmri_dicom_pattern']), name='inputspec') outputnode = pe.Node( utility.IdentityInterface( fields=['rsfmri_file','dicom_pars']), name='outputspec') n_dcm2nii = pe.Node( dcm2nii.Dcm2nii( gzip_output=True, id_in_filename=True, date_in_filename=True, convert_all_pars=False, config_file='/home_local/bpinsard/.dcm2nii/dcm2nii.ini',), name='dcm2nii') n_rename_rsfmri = pe.Node( utility.Rename( format_string='%(site)s_S_%(subj)s_%(data)s_%(time)s_rsfMRI.nii.gz', parse_string='(?P<data>\d{8})_(?P<time>\d{6})(?P<site>\d{3})S(?P<subj>\d{4})'), name='rename_rsfmri') n_get_dicom_par=pe.Node( utility.Function( input_names=['dicom_pattern'], output_names=['dicom_pars'], function=get_dicom_par), name='get_dicom_par') w=pe.Workflow(name=name) w.connect([ (inputnode, n_dcm2nii, [('rsfmri_dicom_pattern','source_names')]), (n_dcm2nii, n_rename_rsfmri,[('converted_files','in_file')]), (inputnode,n_get_dicom_par,[('rsfmri_dicom_pattern','dicom_pattern')]), (n_rename_rsfmri, outputnode, [('out_file','rsfmri_file')]), (n_get_dicom_par, outputnode, [('dicom_pars','dicom_pars')]), ]) return w
def biograph_to_nifti(dicomf): """ given a dicom file <dicomf> in a directory of dicoms , use dcm2nii to convert to a 4d.nii.gz file in a tempdir""" tmp, _ = os.path.split(os.path.abspath(__file__)) default_file = os.path.join(tmp, 'dcm2nii.ini') tmpdir = tempfile.mkdtemp() convert = dcm2nii.Dcm2nii() convert.inputs.source_names = dicomf convert.inputs.output_dir = tmpdir convert.inputs.config_file = default_file cout = convert.run() if not cout.runtime.returncode == 0: logging.error(cout.runtime.stderr) return None else: ext = '' if 'GZip' in cout.runtime.stdout: ext = '.gz' outf = cout.runtime.stdout.split('->')[-1].split('\n')[0] return os.path.join(tmpdir,outf + ext)
# name of dicom and output folder dicom_dir = 'Dicom' data_dir = 'Data' #------------------------------------------------------------ # Node: infosource: specify the list of subjects the pipeline #should be executed on #------------------------------------------------------------ infosource = pe.Node(interface = util.IdentityInterface(fields = ['subject_id']), name='infosource') infosource.iterables = ('subject_id', subjects_list) # main node for data conversion dicom2nifti = pe.Node(interface=d2n.Dcm2nii(), name='dicom2nifti') dicom2nifti.terminal_output = 'file' # store nifti files output dicom2nifti.inputs.output_dir = experiment_dir + data_dir # specify optional inputs #dicom2nifti.inputs.file_mapping = [('nifti', '*.nii'), ('info', 'dicom.txt'), ('dti', '*dti.bv*')] #dicom2nifti.inputs.out_type = 'nii' #dicom2nifti.inputs.subject_dir_template = '%s' #------------------------------------------------------------ # Node ParseDICOMDIR - creates a nicer nifti overview textfile #------------------------------------------------------------
dg.inputs.pwd = getpass.getpass() dg.inputs.server = args.server.strip('/') else: dg.inputs.config = os.path.abspath(args.config) r.connect(infosource, 'projects', dg, 'project') r.connect(infosource, 'subjects', dg, 'subject') r.connect(infosource, 'experiments', dg, 'experiment') r.connect(infosource, 'scans', dg, 'scan') dg.inputs.project = args.project dg.inputs.subject = args.subject dg.inputs.experiment = args.experiment dg.inputs.scan = args.scan dcm2nii = pe.Node(interface=mricron.Dcm2nii(), name='dcm2nii') dcm2nii.inputs.args = '-d n' dcm2nii.inputs.gzip_output = True dcm2nii.inputs.anonymize = True dcm2nii.inputs.reorient = True dcm2nii.inputs.reorient_and_crop = True ds = pe.Node(nio.DataSink(), name='ds') ds.inputs.parameterization = False get_sink_container = pe.Node(interface=niu.Function( input_names=['directory', 'project', 'subject', 'experiment', 'scan'], output_names=['container'], function=get_sink_container_function), name='get_sink_container') get_sink_container.inputs.directory = result_dir
def FUNCPIPE(): #--- 1) Import modules import os # system functions os.system('clear') import nipype.interfaces.dcm2nii as dcm2nii import nipype.interfaces.io as nio # Data i/o import nipype.interfaces.fsl as fsl # fsl import nipype.interfaces.utility as util # utility import nipype.pipeline.engine as pe # pypeline engine import nipype.interfaces.fsl.utils as fslu import nipype.interfaces.fsl.preprocess as fslp from nipype.interfaces import afni as afni from nipype.interfaces.utility import Function import matplotlib from nilearn import plotting from nilearn import image import os import nipype.interfaces.fsl as fsl # fsl import nipype.interfaces.utility as util # utility import nipype.pipeline.engine as pe # pypeline engine import nipype.interfaces.freesurfer as fs # freesurfer tolist = lambda x: [x] highpass_operand = lambda x:'-bptf %.10f -1'%x #--- 2) Prompt user for directory containing DICOM FILES INITDIR=os.getcwd(); #--- 3) Prompt user for inputs. DICOMDIR=raw_input('Please drag in the directory of\nDICOM files you wish to pre-process\n(ensure there is no blank space at the end)\n') os.system('clear') print ('---\n') DICOMDIR=DICOMDIR.strip('\'"') frac=float(input('Please enter the fractional anisotropy threshold [0 - 1] \n')) os.system('clear') print ('---\n') grad=float(input('Please enter the threshold gradient [-1 - 1] \n')) os.system('clear') print ('---\n') FWHM=float(input('Please enter the FWHM of the smoother (mm) \n')) os.system('clear') print ('---\n') HIGHPASS=float(input('Please enter the High Pass filter cutoff (s)\n')) os.system('clear') print ('---\n') TR=float(input('Please enter the TR (s)\n')) os.system('clear') print ('---\n') #--- 4) Define workflow and input node. workflow = pe.Workflow(name='FUNCPIPE') inputnode = pe.Node(interface=util.IdentityInterface(fields=['fwhm','highpass','TR']),name='inputspec') inputnode.inputs.fwhm=FWHM inputnode.inputs.TR=TR inputnode.inputs.highpass=float(HIGHPASS/(inputnode.inputs.TR*2.5)) #--- 5) Move to directory os.chdir(DICOMDIR) #--- 6) Set up converter node for conversion to nifti converter=pe.Node(interface=dcm2nii.Dcm2nii(),name='CONVERTED') converter.inputs.source_dir=DICOMDIR converter.inputs.gzip_output=bool(1) #--- 7) Set up realigner node to match orientation of MNI 152 realigner=pe.Node(interface=fslu.Reorient2Std(),name='REORIENTED') realigner.inputs.output_type='NIFTI_GZ' workflow.connect(converter,'converted_files',realigner,'in_file') #--- 8) Set up a slice timing node slicetimer=pe.Node(interface=fslp.SliceTimer(),name='SLICETIMED') slicetimer.inputs.interleaved = True workflow.connect(inputnode, 'TR', slicetimer, 'time_repetition') workflow.connect(realigner, 'out_file', slicetimer, 'in_file') #--- 9) Convert to float. img2float = pe.Node(interface=fsl.ImageMaths(out_data_type='float',op_string='',suffix='_dtype'),name='IMG2FLOATED') workflow.connect(slicetimer,'slice_time_corrected_file',img2float,'in_file') #--- 10) Motion correct. motion_correct = pe.Node(interface=fsl.MCFLIRT(save_mats=True,save_plots=True,interpolation='spline'),name='MCORRECTED') workflow.connect(img2float, 'out_file', motion_correct, 'in_file') #--- 11) Despike despiker=pe.Node(interface=afni.Despike(),name='DESPIKED') despiker.inputs.outputtype = 'NIFTI_GZ' workflow.connect(motion_correct,'out_file',despiker,'in_file') #--- 12) Plot motion. plot_motion = pe.Node(interface=fsl.PlotMotionParams(in_source='fsl'),name='MOTIONPLOTTED') plot_motion.iterables = ('plot_type', ['rotations', 'translations']) workflow.connect(motion_correct, 'par_file', plot_motion, 'in_file') #--- 13) Extract extracter=pe.Node(interface=fsl.BET(),name='EXTRACTED') extracter.inputs.frac=float(frac) extracter.inputs.vertical_gradient=float(grad) extracter.inputs.mask=bool(1) extracter.inputs.functional=bool(1) workflow.connect(despiker, 'out_file', extracter, 'in_file') #--- 14) Smooth smoother=pe.MapNode(interface=afni.BlurInMask(),name='SMOOTHED',iterfield=['fwhm']) smoother.inputs.outputtype='NIFTI_GZ' workflow.connect(inputnode, 'fwhm', smoother, 'fwhm') workflow.connect(extracter, 'out_file', smoother, 'in_file') workflow.connect(extracter, 'mask_file', smoother, 'mask') #--- 15) Highpass filter # Filtering node highpass = pe.MapNode(interface=fsl.ImageMaths(suffix='_tempfilt'),name='HIGHPASSED',iterfield=['in_file']) workflow.connect(inputnode, ('highpass', highpass_operand), highpass, 'op_string') workflow.connect(smoother, 'out_file', highpass, 'in_file') #--- 16) Mean functional volume # Need to add back the mean removed by FSL meanfunc = pe.MapNode(interface=fsl.ImageMaths(op_string='-Tmean',suffix='_mean'),name='meanfunc',iterfield=['in_file']) workflow.connect(smoother, 'out_file', meanfunc, 'in_file') #--- 17) Add mean back to highpassed data (FINAL OUTPUT) addmean = pe.MapNode(interface=fsl.BinaryMaths(operation='add'),name='PREPROCESSED',iterfield=['in_file','operand_file']) workflow.connect(highpass, 'out_file', addmean, 'in_file') workflow.connect(meanfunc, 'out_file', addmean, 'operand_file') outputnode = pe.Node(interface=util.IdentityInterface(fields=['highpassed_files']),name='outputnode') workflow.connect(addmean, 'out_file', outputnode, 'highpassed_files') # Utility function for plotting extraction def bplot(in_file,in_file2,in_file3): from nilearn import image from nilearn import plotting import matplotlib niftifiledim=len(image.load_img(in_file).shape) firstim=image.index_img(in_file, 0) firstim2=image.index_img(in_file2, 0) display=plotting.plot_anat(firstim2) display.add_contours(firstim,filled=True, alpha=0.5,levels=[0.2], colors='b') display.add_edges(in_file3) matplotlib.pyplot.show() return niftifiledim #--- 18) Show extraction showextract= pe.Node(Function(input_names=['in_file','in_file2','in_file3'],output_names=['niftifiledim'],function=bplot),name='SHOWEXTRACT') workflow.connect(despiker,'out_file', showextract,'in_file2') workflow.connect(extracter,'out_file', showextract,'in_file') workflow.connect(extracter,'mask_file', showextract,'in_file3') # Utility function for plotting extraction def splot(in_file): from nilearn import image from nilearn import plotting import matplotlib niftifiledim=len(image.load_img(in_file).shape) firstim=image.index_img(in_file, 0) display=plotting.plot_anat(firstim,display_mode='z',cut_coords=10) matplotlib.pyplot.show() return niftifiledim #--- 19) Show smoothing showsmooth= pe.MapNode(Function(input_names=['in_file'],output_names=['niftifiledim'],function=splot),iterfield=['in_file'],name='SHOWSMOOTH') workflow.connect(smoother,'out_file', showsmooth,'in_file') #--- 20) Mean functional volume (for plotting stats) meanfunc2 = pe.Node(interface=fsl.ImageMaths(op_string='-Tmean',suffix='_mean'),name='MEANFUNCTIONAL') workflow.connect(extracter, 'out_file', meanfunc2, 'in_file') workflow.connect(meanfunc2, 'out_file', outputnode, 'mean_functional_volume') #--- 21) Plot workflow workflow.base_dir = DICOMDIR workflow.write_graph(graph2use='exec') #--- 22) Plot workflow result=workflow.run() #--- 23) Show plots #--- 24) Return to initial working directory print ("Workflow completed. Returning to intital directory\n") os.chdir(INITDIR)
def CONVERTER(): #--- 1) Import modules import nipype.interfaces.dcm2nii as dcm2nii import nipype.pipeline.engine as pe import matplotlib import os os.system('clear') from glob import glob from nilearn import plotting from nilearn import image from nipype.interfaces.utility import Function import nipype.interfaces.fsl.utils as fsl #--- 2) Record intial working directory INITDIR = os.getcwd() #--- 3) Prompt user for directory containing DICOM FILES DICOMDIR = raw_input( 'Please drag in the directory of\nDICOM files you wish to convert\n(ensure there is no blank space at the end)\n' ) os.system('clear') print '---\n' # Get rid of extra strings (Linux terminal) DICOMDIR = DICOMDIR.strip('\'"') #--- 3) Move to directory os.chdir(DICOMDIR) #--- 4) Set up converter node for conversion to nifti converter = pe.Node(interface=dcm2nii.Dcm2nii(), name='CONVERTED') converter.inputs.source_dir = DICOMDIR converter.inputs.gzip_output = bool(1) #--- 5) Set up realigner node to match orientation of MNI 152 realigner = pe.Node(interface=fsl.Reorient2Std(), name='REORIENTED') realigner.inputs.output_type = 'NIFTI_GZ' #--- 6) Set up a plotting node def bplot(in_file): from nilearn import image from nilearn import plotting import matplotlib niftifiledim = len(image.load_img(in_file).shape) if niftifiledim == 3: display = plotting.plot_anat(in_file) matplotlib.pyplot.show() else: firstim = image.index_img(in_file, 0) display = plotting.plot_anat(firstim) matplotlib.pyplot.show() return niftifiledim showconvert = pe.Node(Function(input_names=['in_file'], output_names=['niftifiledim'], function=bplot), name='SHOWCONVERT') #--- 7) Set up workflow workflow = pe.Workflow(name='CONVERTER') workflow.base_dir = DICOMDIR #--- 8) Connect nodes. workflow.connect(converter, 'converted_files', realigner, 'in_file') workflow.connect(realigner, 'out_file', showconvert, 'in_file') workflow.write_graph(graph2use='exec') #--- 9) Run workflow result = workflow.run() #--- 10) Show plot print "Node completed. Returning to intital directory\n" os.chdir(INITDIR)