def plot_overlays_diff_group_window(condition,method,modality,hemi,window,azimuth,elevation): subject_id, surface = 'fsaverage', 'inflated' hemi = hemi brain = Brain(subject_id, hemi, surface, size=(600, 600)) stc_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized' + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method + '_ico-5-fwd-fsaverage.stc-'+ hemi +'.stc') stcl_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized' + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method + '_ico-5-fwd-fsaverage.stc-lh.stc') stcr_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized' + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method + '_ico-5-fwd-fsaverage.stc-rh.stc') stcl = read_stc(stcl_fname) stcr = read_stc(stcr_fname) datal = stcl['data'] datar = stcr['data'] stc = read_stc(stc_fname) data = stc['data'] vertices = stc['vertices'] time = np.linspace(stc['tmin'], stc['tmin'] + data.shape[1] * stc['tstep'], data.shape[1]) winstart = np.where(time < window[0])[0][-1] winend = np.where(time >= window[1])[0][0] meanval = np.mean(data[:,winstart:winend],1) meanvalr = np.mean(datar[:,winstart:winend],1) meanvall = np.mean(datal[:,winstart:winend],1) maxval = np.max([np.max(meanvalr),np.max(meanvall)]) minval = np.min([np.min(meanvalr),np.min(meanvall)]) fmin = -np.max(np.abs([maxval,minval]))*0.8 fmax = np.max(np.abs([maxval,minval]))*0.8 colormap = mne.viz.mne_analyze_colormap(limits=[fmin, fmin/3, fmin/3.1, fmax/3.1, fmax/3, fmax], format='mayavi') #colormap = 'jet' time_label = lambda t: 'time=%0.2f ms' % (0) brain.add_data(meanval, colormap=colormap, vertices=vertices, smoothing_steps=15, time=time, time_label=time_label, hemi=hemi) brain.scale_data_colormap(fmin=fmin, fmid=0, fmax=fmax, transparent=False) brain.show_view(dict(azimuth=azimuth,elevation=elevation, distance=None)) # mayavi.mlab.view(azimuth=0, elevation=None, distance=None, focalpoint=None, # roll=None, reset_roll=True, figure=None) PlotDir = [] PlotDir = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/Plots/IcaCorr_Window_' + condition[0] + '-' + condition[1] + str(window[0]) + '-' + str(window[1])) if not os.path.exists(PlotDir): os.makedirs(PlotDir) brain.save_image(PlotDir + '/IcaCorr_' + modality + '_' + method + '_' + '_Normalized' + condition[0] + '-' + condition[1] + '_' + str(window[0]) + '-' + str(window[1]) + hemi + '_'+ str(azimuth)+ '_ico-5-fwd-fsaverage-'+'.png')
def plot_overlays_Fgroup(condition,modality,hemi,azimuth): brain = Brain(subject_id='fsaverage', hemi=hemi,surf='pial',cortex = 'low_contrast', size=(600, 600)) stc_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/Plot_STATS/' +"_vs_".join(condition) +'/fmap'+ modality+ '_' +"_vs_".join(condition)+ '-' + hemi+'.stc') stc = read_stc(stc_fname) data = stc['data'] vertices = stc['vertices'] brain.add_data(data, thresh = 3.259,colormap='hot',alpha=1, vertices=vertices, smoothing_steps=3,hemi=hemi) brain.set_data_time_index(0) brain.scale_data_colormap(fmin=3.26, fmid=5.84, fmax= 8.42, transparent=False) brain.show_view(dict(azimuth=azimuth,elevation=None, distance=None)) # mayavi.mlab.view(azimuth=0, elevation=None, distance=None, focalpoint=None, # roll=None, reset_roll=True, figure=None) PlotDir = [] PlotDir = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/Plot_STATS/' + "_vs_".join(condition)) if not os.path.exists(PlotDir): os.makedirs(PlotDir) brain.save_image(PlotDir + '/Fmap_IcaCorr_' + modality + '_' + 'dSPM' + '_' + '_' + "_vs_".join(condition) + '_' + hemi + '_'+ str(azimuth)+ '_ico-5-fwd-fsaverage-'+'.png')
def plot_ctx(): # Visualize the left or right hemisphere activation map per run with Yeo 2011 overlay of functional connectivity maps # State path to statistical mask files generated by freesurfer processes path = "/home/lauri/Documents/temp/" statpath = os.listdir(path) statfile = [] hemispheres = ['lh','rh'] # Creates a function to grab all cortical statistical files for h in hemispheres: for s in statpath: if s.startswith(h) and s.endswith("gz"): statfile.append(s) print('Making images for:') statfile.sort() print(statfile) # Create the image using pysurfer with backend function initialized for h in hemispheres: for f in statfile: sig = os.path.join(path,f) sub = "fsaverage" hemi = h surf = "inflated" view_types = ['lat','med'] brain = Brain(sub, hemi, surf, cortex=None, background="midnightblue", views=view_types) overlay_file = sig brain.add_overlay(sig, min=1, max=3, name="ovrlay") # To change colour of activations: note replace pos or neg: brain.overlays["ovrlay"].neg_bar.lut_mode = "winter" subjects_dir = os.environ["SUBJECTS_DIR"] annot_path = os.path.join(subjects_dir, sub, "label", "lh.Yeo2011_7Networks_N1000.annot") brain.add_annotation(annot_path, hemi=h, borders=False, alpha=.33) brain.save_image(os.path.join(path,f + ".jpeg"))
def drawROI(): for hemi in ["lh"]: # load data roivol = io.project_volume_data(roifile, hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="avg", projarg=[0,6,0.1], surf="white") # create label roivol = abs(roivol) roivol[roivol < 0.33] = 0 #if max(roivol) < 1: # brain.close() # continue #else: write_label(np.asarray(np.nonzero(roivol)),"/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label") # load brain my_fig = mlab.figure(figure="new_fig1", size=(800,800)) brain = Brain("fsaverage",hemi,"inflated",curv=True,size=[800,800],background="white",cortex=(("gist_yarg",-1.5,3.5,False)),figure=my_fig) set_mylights(my_fig,lights[hemi]) #add label brain.add_label("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label",borders=False,color="#ffff00",alpha=1) brain.add_label("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.label",borders=1,color="black",alpha=0.5) brain.show_view('lat') brain.save_image("/gablab/p/bps/zqi_ytang/scripts/roi/surf-IFG.tiff") brain.close()
def curvature_normalization(data_dir, subj, close=True): """Normalize the curvature map and plot contour over fsaverage.""" surf_dir = op.join(data_dir, subj, "surf") snap_dir = op.join(data_dir, subj, "snapshots") for hemi in ["lh", "rh"]: cmd = ["mri_surf2surf", "--srcsubject", subj, "--trgsubject", "fsaverage", "--hemi", hemi, "--sval", op.join(surf_dir, "%s.curv" % hemi), "--tval", op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi)] sub.check_output(cmd) b = Brain("fsaverage", hemi, "inflated", config_opts=dict(background="white", width=700, height=500)) curv = nib.load(op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi)) curv = (curv.get_data() > 0).squeeze() b.add_contour_overlay(curv, min=0, max=1.5, n_contours=2, line_width=4) b.contour["colorbar"].visible = False for view in ["lat", "med"]: b.show_view(view) mlab.view(distance=330) png = op.join(snap_dir, "%s.surf_warp_%s.png" % (hemi, view)) b.save_image(png) if close: b.close()
def test_image(): """Test image saving """ mlab.options.backend = 'auto' brain = Brain(*std_args, config_opts=small_brain) tmp_name = mktemp() + '.png' brain.save_image(tmp_name) brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.screenshot()
def test_image(): """Test image saving """ mlab.options.backend = 'auto' brain = Brain(*std_args, config_opts=small_brain) tmp_name = mktemp() + '.png' brain.save_image(tmp_name) brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.screenshot() brain.close()
def pysurfer_plot_perm_ttest_results(vertices, vertives_values, max_vals, fol): T = max(vertices.keys()) for t in range(T+1): print(t) brain = Brain('fsaverage', 'split', 'pial', curv=False, offscreen=False, views=['lat', 'med'], title='{} ms'.format(t)) for hemi in ['rh', 'lh']: if t in vertices: brain.add_data(np.array(vertives_values[t][hemi]), hemi=hemi, min=1, max=max_vals, remove_existing=True, colormap="YlOrRd", alpha=1, vertices=np.array(vertices[t][hemi])) brain.save_image(os.path.join(fol, '{}.jpg'.format(t))) brain.close()
def inflated_surfaces(out_dir, subj, close=True): """Native inflated surfaces with cortical label.""" for hemi in ["lh", "rh"]: b = Brain(subj, hemi, "inflated", curv=False, config_opts=dict(background="white", width=800, height=500)) b.add_label("cortex", color="#6B6B6B") for view in ["lat", "med"]: b.show_view(view) mlab.view(distance=400) png = op.join(out_dir, "%s.surface_%s.png" % (hemi, view)) b.save_image(png) if close: b.close()
def make_pysurfer_images(folder,suffix='cope1',threshold=0.9499,coords=(),surface='inflated',fwhm=0,filename='',saveFolder=[]): from surfer import Brain, io TFCEposImg,posImg,TFCEnegImg,negImg=getFileNamesfromFolder(folder,suffix) pos=image.math_img("np.multiply(img1,img2)", img1=image.threshold_img(TFCEposImg,threshold=threshold),img2=posImg) neg=image.math_img("np.multiply(img1,img2)", img1=image.threshold_img(TFCEnegImg,threshold=threshold),img2=negImg) fw=image.math_img("img1-img2",img1=pos,img2=neg) if fwhm==0: smin=np.min(np.abs(fw.get_data()[fw.get_data()!=0])) else: smin=2 mri_file = "%s/thresholded_posneg.nii.gz" % folder fw.to_filename(mri_file) """Bring up the visualization""" brain = Brain("fsaverage", "split", surface ,views=['lat', 'med'], offscreen=True , background="white") """Project the volume file and return as an array""" reg_file = os.path.join("/opt/freesurfer","average/mni152.register.dat") surf_data_lh = io.project_volume_data(mri_file, "lh", reg_file,smooth_fwhm=fwhm) surf_data_rh = io.project_volume_data(mri_file, "rh", reg_file,smooth_fwhm=fwhm) """ You can pass this array to the add_overlay method for a typical activation overlay (with thresholding, etc.). """ brain.add_overlay(surf_data_lh, min=smin, max=5, name="ang_corr_lh", hemi='lh') brain.add_overlay(surf_data_rh, min=smin, max=5, name="ang_corr_rh", hemi='rh') if len(coords)>0: if coords[0]>0: hemi='rh' else: hemi='lh' brain.add_foci(coords, map_surface="pial", color="gold",hemi=hemi) if len(saveFolder)>0: folder=saveFolder brain.save_image('%s/%s.png' % (folder,filename)) else: brain.save_image('%s/surfaceplot.jpg' % folder) brain.close()
def plot_data_surf_bh(in_file, colormap='jet', thr_list=[(None, None, None)],roi_coords=(), fwhm=0): ''' allows more flexible visualization than plot_rs_surf_bh thr_list = [(min, max, thresh)] colormap: matplotlib colormap (http://matplotlib.org/examples/color/colormaps_reference.html) ''' # in_file .nii to be projected on surface import os from surfer import Brain, io out_file_list = [] in_file_name = os.path.basename(in_file) reg_file = os.path.join(os.environ["FREESURFER_HOME"],"average/mni152.register.dat") for thr in thr_list: min_thr = thr[0] max_thr = thr[1] thr_thr = thr[2] brain = Brain("fsaverage", "split", "inflated", views=['lat', 'med'], config_opts=dict(background="white")) surf_data_lh = io.project_volume_data(in_file, "lh", reg_file, smooth_fwhm=fwhm) surf_data_rh = io.project_volume_data(in_file, "rh", reg_file, smooth_fwhm=fwhm) brain.add_data(surf_data_lh, min=min_thr, max=max_thr, thresh=thr_thr, colormap=colormap, hemi='lh') brain.add_data(surf_data_rh, min=min_thr, max=max_thr, thresh=thr_thr, colormap=colormap, hemi='rh') roi_str = '' if not(roi_coords == ()): if roi_coords[0] <0: #lh hemi_str = 'lh' else: hemi_str = 'rh' roi_str = '_roi_%s.%s.%s' % roi_coords brain.add_foci(roi_coords, map_surface="white", hemi=hemi_str, color='red', scale_factor=2) out_filename = os.path.join(os.getcwd(), in_file_name + roi_str + '_thr_%s' % min_thr + '.png') out_file_list += [out_filename] brain.save_image(out_filename) brain.close() return out_file_list
def plot_rs_surf(in_file, thr_list=[(.2,1)],roi_coords=(), fwhm=0): # in_file .nii to be projected on surface # list of tuples defining min and max thr_list=[(.2,1)] import os import subprocess from surfer import Brain, io arch = subprocess.check_output('arch') if arch.startswith('x86_'): # set offscrene rendering to avoid intereference on linux from mayavi import mlab mlab.options.offscreen = True out_file_list = [] in_file_name = os.path.basename(in_file) reg_file = os.path.join(os.environ["FREESURFER_HOME"],"average/mni152.register.dat") for thr in thr_list: min_thr = thr[0] max_thr = thr[1] print(min_thr) print(max_thr) for hemi in ['lh', 'rh']: brain = Brain("fsaverage", hemi, "inflated", views=['lat', 'med'], config_opts=dict(background="white")) surf_data = io.project_volume_data(in_file, hemi, reg_file, smooth_fwhm=fwhm) brain.add_overlay(surf_data, min=min_thr, max=max_thr, name="ang_corr", hemi=hemi) roi_str = '' if not(roi_coords == ()): if roi_coords[0] <0: #lh hemi_str = 'lh' else: hemi_str = 'rh' roi_str = '_roi_%s.%s.%s' % roi_coords if hemi_str == hemi: brain.add_foci(roi_coords, map_surface="white", hemi=hemi_str, color='red', scale_factor=2) out_filename = os.path.join(os.getcwd(), in_file_name + roi_str + '_thr_%s' % min_thr + '_' + hemi + '.png') out_file_list += [out_filename] brain.save_image(out_filename) brain.close() return out_file_list
def test_image(tmpdir): """Test image saving.""" tmp_name = tmpdir.join('temp.png') tmp_name = str(tmp_name) # coerce to str to avoid PIL error _set_backend() subject_id, _, surf = std_args brain = Brain(subject_id, 'both', surf=surf, size=100) brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos") brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain.save_image(tmp_name) brain.save_image(tmp_name, 'rgba', True) brain.screenshot() brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h') brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']]) brain.close()
def vis_ers_comp(group=None,phase=None,surf=None,cmap=None,split='lh'): mri_file = f'/mnt/c/Users/ACH/Desktop/ers_comps/{group}_{phase}/{group}_{phase}_ClusterEffEst.nii.gz' #find the file containing stats surf_data_lh = project_volume_data(mri_file, "lh", reg_file, projarg=[0, 1, .01], smooth_fwhm=1) #project to lh _max = .55 if phase == 'acquisition' else .3 for view in ['med','lat']: #lateral and medial views brain = Brain('MNI2009c', split, surf, cortex='low_contrast',size=1000, views=view, background='white', foreground=None) #initialize the brain object brain.add_data(surf_data_lh, 0, _max, center=None, hemi='lh', thresh=None, colorbar=False, colormap=cmap, transparent=True) #add lh data for vert, color in zip([115262,135014],['white','black']): #add focal ROIs brain.add_foci(vert,coords_as_verts=True,color=color,alpha=1) fname = f'/mnt/c/Users/ACH/Documents/gPPI/paper/pysurfer/{group}_{phase}_{view}.png' os.system(f'rm {fname}') brain.save_image(fname,antialiased=True)
def test_image(): """Test image saving.""" tmp_name = mktemp() + '.png' _set_backend() subject_id, _, surf = std_args brain = Brain(subject_id, 'both', surf=surf, size=100) brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos") brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain = Brain(*std_args, size=100) brain.save_image(tmp_name) brain.save_image(tmp_name, 'rgba', True) brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h') brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']]) brain.screenshot() brain.close()
def test_image(): """Test image saving """ tmp_name = mktemp() + '.png' mlab.options.backend = 'auto' subject_id, _, surf = std_args brain = Brain(subject_id, 'both', surf=surf, config_opts=small_brain) brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos") brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain = Brain(*std_args, config_opts=small_brain) brain.save_image(tmp_name) brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h') brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']]) brain.screenshot() brain.close()
def plot_surface_vertices(common_space, morph_data, vertex_idx, aug_data, hemi, surf, view, cmap, save_path): b = Brain(common_space, hemi, surf, background="white", views=view) x, y, z = b.geo[hemi].coords.T coords = np.array([x, y, z]).T print('Number of vertices to be plotted {}'.format(len(vertex_idx))) if aug_data: aug_vertex_idx = get_nbrs(coords, vertex_idx) print('Number of vertices to be plotted after augmentation {}'.format( len(aug_vertex_idx))) morph_data[aug_vertex_idx] = 1 else: morph_data[vertex_idx] = 1 print(np.sum(morph_data)) b.add_data(morph_data, colormap=cmap, alpha=.9, colorbar=True) print(save_path) b.save_image(save_path)
def test_image(): """Test image saving """ tmp_name = mktemp() + '.png' mlab.options.backend = 'auto' subject_id, _, surf = std_args brain = Brain(subject_id, 'both', surf=surf, size=100) brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos") brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain = Brain(*std_args, size=100) brain.save_image(tmp_name) brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h') brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']]) brain.screenshot() brain.close()
def test_image(): """Test image saving.""" tmp_name = mktemp() + '.png' _set_backend() subject_id, _, surf = std_args brain = Brain(subject_id, 'both', surf=surf, size=100) brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos") brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain.close() brain = Brain(*std_args, size=100) brain.save_image(tmp_name) brain.save_image(tmp_name, 'rgba', True) brain.screenshot() if not os.getenv('TRAVIS', 'false') == 'true': # for some reason these fail on Travis sometimes brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h') brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']]) brain.close()
def plot_rs_surf_bh(in_file, thr_list=[(.2,1)],roi_coords=(), fwhm=0): # in_file .nii to be projected on surface # list of tuples defining min and max thr_list=[(.2,1)] import os from surfer import Brain, io out_file_list = [] in_file_name = os.path.basename(in_file) reg_file = os.path.join(os.environ["FREESURFER_HOME"],"average/mni152.register.dat") for thr in thr_list: min_thr = thr[0] max_thr = thr[1] print(min_thr) print(max_thr) brain = Brain("fsaverage", "split", "inflated", views=['lat', 'med'], config_opts=dict(background="white")) surf_data_lh = io.project_volume_data(in_file, "lh", reg_file, smooth_fwhm=fwhm) surf_data_rh = io.project_volume_data(in_file, "rh", reg_file, smooth_fwhm=fwhm) brain.add_overlay(surf_data_lh, min=min_thr, max=max_thr, name="ang_corr_lh", hemi='lh') brain.add_overlay(surf_data_rh, min=min_thr, max=max_thr, name="ang_corr_rh", hemi='rh') roi_str = '' if not(roi_coords == ()): if roi_coords[0] <0: #lh hemi_str = 'lh' else: hemi_str = 'rh' roi_str = '_roi_%s.%s.%s' % roi_coords brain.add_foci(roi_coords, map_surface="white", hemi=hemi_str, color='red', scale_factor=2) out_filename = os.path.join(os.getcwd(), in_file_name + roi_str + '_thr_%s' % min_thr + '.png') out_file_list += [out_filename] brain.save_image(out_filename) brain.close() return out_file_list
def plot_overlays_diff_singlesubj(subject,condition,method,modality,hemi,indextime, azimuth): subject_id, surface = 'fsaverage', 'inflated' hemi = hemi brain = Brain(subject_id, hemi, surface, size=(600, 600)) stc_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/' + subject + '/mne_python/STCS_diff/IcaCorr_' + condition[0] + '-' + condition[1] + '/' + modality + '_' + method + '_' + subject + '_' + condition[0] + '-' + condition[1] + '_' + '_ico-5-fwd-fsaverage-.stc-'+hemi+'.stc') stc = read_stc(stc_fname) data = stc['data'] vertices = stc['vertices'] time = np.linspace(stc['tmin'], stc['tmin'] + data.shape[1] * stc['tstep'], data.shape[1]) colormap = 'hot' time_label = lambda t: 'time=%0.2f ms' % (t * 1e3) brain.add_data(data, colormap=colormap, vertices=vertices, smoothing_steps=4, time=time, time_label=time_label, hemi=hemi) brain.set_data_time_index(indextime) brain.scale_data_colormap(fmin=0, fmid=2.5, fmax=5, transparent=True) brain.show_view(dict(azimuth=azimuth,elevation=None, distance=None)) # mayavi.mlab.view(azimuth=0, elevation=None, distance=None, focalpoint=None, # roll=None, reset_roll=True, figure=None) realtime = stc['tmin'] + stc['tstep']*indextime PlotDir = [] PlotDir = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/' + subject + '/mne_python/BrainMaps/IcaCorr_' + + condition[0] + '-' + condition[1]) if not os.path.exists(PlotDir): os.makedirs(PlotDir) brain.save_image(PlotDir + '/IcaCorr_' + modality + '_' + method + '_' + subject + '_' + condition[0] + '-' + condition[1] + '_' + str(realtime) + hemi + '_'+ str(azimuth)+ '_ico-5-fwd-fsaverage-' +'.png')
def test_image(tmpdir): """Test image saving.""" tmp_name = tmpdir.join('temp.png') tmp_name = str(tmp_name) # coerce to str to avoid PIL error _set_backend() subject_id, _, surf = std_args brain = Brain(subject_id, 'both', surf=surf, size=100) brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos") brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain.close() brain = Brain(*std_args, size=100) brain.save_image(tmp_name) brain.save_image(tmp_name, 'rgba', True) brain.screenshot() if os.getenv('TRAVIS', '') != 'true': # for some reason these fail on Travis sometimes brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h') brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']]) brain.close()
def plot_overlays_diff_group(condition,method,modality,hemi,indextime,azimuth): hemi = hemi brain = Brain(subject_id='fsaverage', hemi=hemi, surface='pial', size=(600, 600)) stc_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_' + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method + '_ico-5-fwd-fsaverage.stc-'+ hemi +'.stc') stc = read_stc(stc_fname) data = stc['data'] vertices = stc['vertices'] time = np.linspace(stc['tmin'], stc['tmin'] + data.shape[1] * stc['tstep'], data.shape[1]) # colormap = 'seismic' colormap = mne.viz.mne_analyze_colormap(limits=[-3,-1.81,-1.80, 1.80,1.81, 3], format='mayavi') time_label = lambda t: 'time=%0.2f ms' % (t * 1e3) brain.add_data(data, colormap=colormap, vertices=vertices, smoothing_steps=20, time=time, time_label=time_label, hemi=hemi) brain.set_data_time_index(indextime) brain.scale_data_colormap(fmin=-1.82, fmid=0, fmax= 1.82, transparent=False) brain.show_view(dict(azimuth=azimuth,elevation=None, distance=None)) # mayavi.mlab.view(azimuth=0, elevation=None, distance=None, focalpoint=None, # roll=None, reset_roll=True, figure=None) realtime = stc['tmin'] + stc['tstep']*indextime PlotDir = [] PlotDir = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/Plots/IcaCorr_' + condition[0] + '-' + condition[1] ) if not os.path.exists(PlotDir): os.makedirs(PlotDir) brain.save_image(PlotDir + '/IcaCorr_' + modality + '_' + method + '_' + '_' + condition[0] + '-' + condition[1] + '_' + str(realtime) + hemi + '_'+ str(azimuth)+ '_ico-5-fwd-fsaverage-'+'.png')
def visualize_brain(subject, hemi, annot_name, subjects_dir, parcels_selected, fig_dir='figs', ext='.png'): # visualize the brain with the parcellations and the source of the signal if not os.path.isdir(fig_dir): os.mkdir(fig_dir) brain = Brain(subject, hemi, 'inflated', subjects_dir=subjects_dir, cortex='low_contrast', background='white', size=(800, 600)) for parcel in parcels_selected: brain.add_label(parcel, alpha=1, color=parcel.color) save_fig = os.path.join(fig_dir, 'brain_' + annot_name + ext) brain.save_image(save_fig) print('brain image saved in {}'.format(save_fig))
def test_image(tmpdir): """Test image saving.""" tmp_name = tmpdir.join('temp.png') tmp_name = str(tmp_name) # coerce to str to avoid PIL error _set_backend() subject_id, _, surf = std_args brain = Brain(subject_id, 'both', surf=surf, size=100) brain.add_overlay(overlay_fname, hemi='lh', min=5, max=20, sign="pos") brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg') brain.close() brain = Brain(*std_args, size=100) if sys.platform == 'darwin' and os.getenv('TRAVIS', '') == 'true': raise SkipTest('image saving on OSX travis is not supported') brain.save_image(tmp_name) brain.save_image(tmp_name, 'rgba', True) brain.screenshot() if os.getenv('TRAVIS', '') != 'true': # for some reason these fail on Travis sometimes brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v') brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='h') brain.save_montage(tmp_name, [['l', 'v'], ['m', 'f']]) brain.close()
right_df = pd.DataFrame({ 'col': [ key.replace('rh_', '').replace('.', '-').replace('_thickness_D', '') for key, val in right_count.items() ], 'val': [val for key, val in right_count.items()] }) label_dir = '/cm/shared/openmind/freesurfer/5.3.0/subjects/fsaverage/label' left_label_file = 'lh.aparc.a2009s.annot' right_label_file = 'rh.aparc.a2009s.annot' lh_aparc_file = os.path.join(label_dir, left_label_file) rh_aparc_file = os.path.join(label_dir, right_label_file) lh_labels, lh_ctab, lh_names = nb.freesurfer.read_annot(lh_aparc_file) rh_labels, rh_ctab, rh_names = nb.freesurfer.read_annot(rh_aparc_file) left_df = left_df.set_index('col').loc[lh_names].reset_index().fillna(0) right_df = right_df.set_index('col').loc[rh_names].reset_index().fillna(0) vtx_lh = left_df.val.values[lh_labels] vtx_lh[lh_labels == -1] = 0 vtx_rh = right_df.val.values[rh_labels] vtx_rh[rh_labels == -1] = 0 brain.add_data(vtx_lh, 0, 400, colormap="Reds", alpha=.8, hemi='lh') brain.add_annotation(lh_aparc_file, hemi='lh') brain.add_data(vtx_rh, 0, 400, colormap="Reds", alpha=.8, hemi='rh') brain.add_annotation(rh_aparc_file, hemi='rh', remove_existing=False) save_name = "../images/{}_brain.png".format(save_name) brain.save_image(save_name)
hemi='lh') brain.add_overlay(surf_data_rh, min=minval, max=maxval, name="thirty_sec_rh", hemi='rh') for overlay in brain.overlays_dict["thirty_sec_lh"]: overlay.remove() for overlay in brain.overlays_dict["thirty_sec_rh"]: overlay.remove() brain.add_data(surf_data_lh, 0, maxval, colormap="rainbow", alpha=.65, hemi='lh') brain.add_data(surf_data_rh, 0, maxval, colormap="rainbow", alpha=.65, hemi='rh') brain.save_image(datadir + 'plots/avg_raw_zthresh_' + str(z) + ".png") mlab.show() brain.show_view(view)
""" =================== Save a set of views =================== Save some views in png files. """ print(__doc__) from surfer import Brain sub = 'fsaverage' hemi = 'lh' surf = 'inflated' brain = Brain(sub, hemi, surf) ############################################################################### # save 1 image brain.show_view('lat') brain.save_image("%s_lat.png" % sub) ############################################################################### # save some images brain.save_imageset(sub, ['med', 'lat', 'ros', 'caud'], 'jpg')
grade = 3 annot = "aparc_sub" subject = "fsaverage" subjects_dir = config.get_subjects_dir_subj("sample") ground_metric = np.load("data/ground_metric.npy") hemi = "lh" label_index = 0 labels = mne.read_labels_from_annot(subject, annot, hemi, subjects_dir=subjects_dir) labels = [label.morph(subject_to=subject, subject_from=subject, grade=grade, subjects_dir=subjects_dir) for label in labels] distances = np.zeros(642) label_vertices = labels[label_index].vertices for ii, label_i in enumerate(labels): v_i = label_i.vertices distances[v_i] = ground_metric[0][ii] f = mlab.figure(size=(700, 600)) brain = Brain(subject, hemi, "inflated", subjects_dir=subjects_dir, figure=f, background="white", foreground='black') vertices = np.arange(642) brain.add_annotation('aparc_sub', alpha=0.2) brain.add_data(distances, vertices=vertices, hemi="lh", transparent=True, smoothing_steps=5, colormap="hot", alpha=0.95, mid=40) brain.save_image("data/ground_metric.png")
from surfer import Brain DST = '../images/brain_%s.png' subjects_dir = '/Volumes/Seagate/refpred/mri' surfaces = ('inflated', 'inflated_avg', 'inflated_pre', # 'orig', # 'pial', 'smoothwm', 'sphere', 'white') for surf in surfaces: brain = Brain('fsaverage', 'lh', surf, size=400, background='white', subjects_dir=subjects_dir) brain.screenshot() brain.save_image(DST % surf, 'rgba', True)
brain = Brain(sub, hemi, surf) ############################################################################### # show all views brain.show_view('lateral') brain.show_view('m') brain.show_view('rostral') brain.show_view('caudal') brain.show_view('dor') brain.show_view('ve') brain.show_view('frontal') brain.show_view('par') ############################################################################### # save some images brain.show_view('lat') brain.save_image("%s_lat.png" % sub) brain.save_imageset(sub, ['med', 'lat', 'ros', 'caud'], 'jpg') ############################################################################### # More advanced parameters brain.show_view({'distance': 375}) # with great power comes great responsibility brain.show_view({'azimuth': 20, 'elevation': 30}, roll=20) ############################################################################### # Save a set of images as a montage brain.save_montage('fsaverage_h_montage.png', ['l', 'v', 'm'], orientation='h') brain.save_montage('fsaverage_v_montage.png', ['l', 'v', 'm'], orientation='v')
label_fname = os.path.join(root, f) label = mne.read_label(label_fname) #label.values.fill(1.0) #label_morph = label.morph(subject_from='fsaverage', subject_to=subject, smooth=5, # n_jobs=1, copy=True) if label.hemi == 'lh': brain.add_label(label, color=random.choice(color)) elif label.hemi == 'rh': brain.add_label(label, color=random.choice(color)) #brain.add_foci(vertno_max, coords_as_verts=True, hemi='lh', color='blue', scale_factor=0.6) # If the label lives in the normal place in the subjects directory, # you can plot it by just using the name #ref_ROI_fname = '/home/qdong/freesurfer/subjects/fsaverage/label/lh.Auditory_82.label' #ref_label = mne.read_label(ref_ROI_fname) #brain.add_label(ref_label, color="blue") #brain.add_label("ROI1", color="blue") #brain.add_label("ROI2", color="red") #brain.add_label("ROI3", color="green") #brain.add_label("ROI4", color="blue") #brain.add_label("ROI5", color="blue") #brain.add_label("ROI6", color="blue") #brain.add_label("ROI7", color="blue") #brain.add_label("ROI8", color="blue") #brain.add_label("ROI9", color="blue") #brain.add_label("ROI10", color="blue") #brain.add_label("ROI11", color="blue") #brain.add_label("RefROI1", color="yellow") # brain.show_view("lateral") brain.save_image('/home/qdong/freesurfer/subjects/101611/lh_ROI2.tiff')
from surfer import Brain DST = '../images/brain_%s.png' subjects_dir = '/Volumes/Seagate/refpred/mri' surfaces = ('inflated', 'inflated_avg', 'inflated_pre', # 'orig', # 'pial', 'smoothwm', 'sphere', 'white') for surf in surfaces: brain = Brain('fsaverage', 'lh', surf, size=400, background='white', subjects_dir=subjects_dir) brain.save_image(DST % surf, 'rgba', True)
time=str(time), subid=subid)) ############################################ # Visualize accuracy (for given subject) ############################################ from surfer import Brain, project_volume_data tr_shift_test_list = [0, 2, 4, 6, 8, 10, 12] # seconds to shift onset forward by # for subid in subj_info.subid: subid = 'ap101' for time in tr_shift_test_list: brain = Brain(subid, "split", "inflated", views=['lat', 'med', 'ven'], background="white") volume_file = '/Volumes/group/awagner/sgagnon/AP/analysis/mvpa_raw/searchlight_test/sourcehit_time{time}_acc_{subid}.nii.gz'.format( time=str(time), subid=subid) for hemi in ['lh', 'rh']: zstat = project_volume_data(volume_file, hemi, subject_id=subid, smooth_fwhm=0.5) brain.add_overlay(zstat, hemi=hemi, min=.333) brain.save_image( '/Volumes/group/awagner/sgagnon/AP/analysis/mvpa_raw/searchlight_test/sourcehit_time{time}_acc_{subid}.png' .format(time=str(time), subid=subid))
#Plot grid locations on brain, save to source_peripheral #NEED TO DO - FIGURE OUT HOW TO GET CHILD WINDOW brain = Brain(subj_id, "both", "inflated", views="frontal") for b in brain.brains: surf = b._geo if surf.hemi == 'lh': vertidx = np.where(src[0]['inuse'])[0] elif surf.hemi == 'rh': vertidx = np.where(src[1]['inuse'])[0] mayavi.mlab.points3d(surf.x[vertidx], surf.y[vertidx], surf.z[vertidx], color=(1, 1, 0), scale_factor=1.5) brain.save_image(sourceP_dir + subj_id + '_vertex.png') brain.close() #Compute BEM / forward model (aka electromagnetic current runs thusly...) conductivity = (0.3, ) # for single layer model = mne.make_bem_model(subject=subj_id, ico=4, conductivity=conductivity) mne.write_bem_surfaces(sourceP_dir + subj_id[:4] + '_bem_model.fif', model) bem_sol = mne.make_bem_solution(model) mne.write_bem_solution(sourceP_dir + subj_id[:4] + '_bem_sol.fif', bem_sol) infosrc = sensor_dir + subj_id[:4] + '_conds_freqs-ave.fif' fname = sourceP_dir + subj_id[:4] + '-fwd.fif' fwd = mne.make_forward_solution(info=infosrc,
surf_data_lh = project_volume_data(mri_file,"lh",reg_file) surf_data_rh = project_volume_data(mri_file,"rh",reg_file) qmri_file = '/Users/jamalw/Desktop/PNI/music_event_structures/qstats_map.nii.gz' qdata_lh = project_volume_data(qmri_file,"lh",reg_file) surf_data_lh[np.logical_or(qdata_lh>0.005,surf_data_lh<0)] = 0 qdata_rh = project_volume_data(qmri_file,"rh",reg_file) surf_data_rh[np.logical_or(qdata_rh>0.005, surf_data_rh<0)] = 0 brain.add_overlay(surf_data_lh,min=minval,max=maxval,name="thirty_sec_lh", hemi='lh',sign="pos") brain.add_overlay(surf_data_rh,min=minval,max=maxval,name="thirty_sec_rh", hemi='rh',sign="pos") # #for overlay in brain.overlays_dict["thirty_sec_lh"]: # overlay.remove() #for overlay in brain.overlays_dict["thirty_sec_rh"]: # overlay.remove() # #brain.add_data(surf_data_lh, minval,maxval, colormap="CMRmap", alpha=1, # hemi='lh') #brain.add_data(surf_data_rh, minval,maxval, colormap="CMRmap", alpha=1, # hemi='rh') # brain.save_image("zstats_human_bounds_srm_k30.png") # mlab.show() brain.show_view(view)
def drawContrast(infile,outname): for hemi in ["rh"]: # load data volpos = io.project_volume_data(infile, hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="pial") """ volneg = io.project_volume_data(rsfcfile_neg, hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="white") volneg=volneg*-1 ccvol=volpos+volneg """ # load brain my_fig = mlab.figure(figure="new_fig1", size=(800,800)) brain = Brain("fsaverage",hemi,"inflated",curv=True,size=[800,800],background="white",cortex=(("gist_yarg",-1.5,3.5,False)),figure=my_fig) set_mylights(my_fig,lights[hemi]) if outname == "fig6b": # create label labIFG = volpos labIFG[labIFG < 2.0739] = 0 write_label(np.asarray(np.nonzero(labIFG)),"fig6prep/roi_IFG.label") #brain.add_label("fig6prep/roi_IFG.label",borders=False,color="red",alpha=0.125) brain.add_label("fig6prep/roi_IFG.label",borders=2,color="#e7298a",alpha=1) if outname == "fig6d": # create label labAG = io.project_volume_data("/gablab/p/CASL/Results/Imaging/resting/zqi/conn_CASL_pre_post_training13o/results/secondlevel/ANALYSIS_01/3mohsk_all(0).3mohsk(1)/pre-training(-1).post-training(1)/anat_func_lifg_1_1/roi_AG.nii.gz", hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="pial") labAG[labAG < 0.33] = 0 write_label(np.asarray(np.nonzero(labAG)),"fig6prep/roi_AG.label") labSTGMTG = io.project_volume_data("/gablab/p/CASL/Results/Imaging/resting/zqi/conn_CASL_pre_post_training13o/results/secondlevel/ANALYSIS_01/3mohsk_all(0).3mohsk(1)/pre-training(-1).post-training(1)/anat_func_lifg_1_1/roi_STGMTG.nii.gz", hemi, subject_id=surfsubj, smooth_fwhm=4.0, projmeth="dist", projsum="max", projarg=[-6,6,0.1], surf="pial") labSTGMTG[labSTGMTG < 0.66] = 0 write_label(np.asarray(np.nonzero(labSTGMTG)),"fig6prep/roi_STGMTG.label") #brain.add_label("fig6prep/roi_AG.label",borders=False,color="black",alpha=0.125) brain.add_label("fig6prep/roi_AG.label",borders=2,color="#1b9e77",alpha=1) #brain.add_label("fig6prep/roi_STGMTG.label",borders=False,color="blue",alpha=0.125) brain.add_label("fig6prep/roi_STGMTG.label",borders=2,color="#7570b3",alpha=1) brain.add_overlay(volpos, min=2.0739, #p = 0.025 2-tailed max=5.0216, #p = 0.000025, 2-tailed sign="abs", name=outname, hemi=hemi) brain.show_view('lat') brain.save_image("fig6prep/%s.tiff"%(outname)) brain.close()
from mayavi import mlab from surfer import Brain, io subject = 'fsaverage' # SAD_017 surface = 'pial' br1 = Brain(subject, 'rh', surface, title='lgroup') l_surf_data = io.project_volume_data('/mindhive/scratch/satra/sadfigures/nipype_mem/nipype-interfaces-spm-model-EstimateContrast/cf535c8b3e6380c2c8512307f3c294ad/spmT_0001.img', 'rh', subject_id='fsaverage', target_subject=subject) br1.add_overlay(l_surf_data, min=2, max=3.7, sign='pos', name='lgroup') br2 = Brain(subject, 'rh', surface, title='hgroup') h_surf_data = io.project_volume_data('/mindhive/scratch/satra/sadfigures/nipype_mem/nipype-interfaces-spm-model-EstimateContrast/d1fbe9c9d24038d7d1e16b16936f52ed/spmT_0001.img', 'rh', subject_id='fsaverage', target_subject=subject) br2.add_overlay(h_surf_data, min=2, max=3.7, sign='pos', name='hgroup') mlab.sync_camera(br1._f, br2._f) mlab.sync_camera(br2._f, br1._f) """ br1.save_image('lgroup.png') br2.save_image('hgroup.png') """
def plot_4_view(data1, parcel_names, parcellation, style='linear', alpha=0.95, zmin=None, zmax=None, zmid=None, cmap='auto', show=True, filename=None, surface='inflated', null_val=0, transparent=True, subj='fsaverage', sub_dir='K:\\palva\\resting_state\\_fsaverage\\'): ''' Plots 1d array of data. Plotted views are lateral and medial on both HS. Used brain is fsaverage. INPUT: data1: 1-dimensional data array, len = # parcels. 1st half must be left HS, 2nd half right. parcel_names: Parcel_names, in the same order as the data. parcellation: Abbreviation, e.g. 'parc2018yeo7_100' or "parc2009' style: 'linear': pos. values only, 'divergent': both pos & neg alpha: Transparency value; transparency might look weird. zmin: The minimum value of a linear z-axis, or center of a divergent axis (thus should be 0) zmax: Maximum value of linear z-axis, or max/-min of div. zmid: Midpoint of z-axis. cmap: Colormap by name. Default is 'rocket' for linear, and 'icefire' for divergent; other recommended options: 'YlOrRd' for linear, or 'bwr' for divergent. show: If False, plot is closed after creation. filename: File to save plot as, e.g. 'plot_13.png' surface: Surface type. null_val: Value for unassigned vertices transparent: Whether parcels with minimum value should be transparent. OUTPUT: instance of surfer.Brain, if show==True ''' N_parc = len(data1) # the number of actually used parcels if len(parcel_names) != N_parc: raise ValueError('Number of parcels != len(data1) ') if parcel_names[0][-3:] != '-lh': parcel_names[:N_parc // 2] = [p + '-lh' for p in parcel_names[:N_parc // 2]] parcel_names[N_parc // 2:] = [p + '-rh' for p in parcel_names[N_parc // 2:]] hemi = 'split' #### load parcels if parcellation == 'parc2009': aparc_lh_file = sub_dir + '\\' + subj + '\\label\\lh.aparc.a2009s.annot' aparc_rh_file = sub_dir + '\\' + subj + '\\label\\rh.aparc.a2009s.annot' else: aparc_lh_file = sub_dir + '\\' + subj + '\\label\\lh.' + parcellation + '.annot' aparc_rh_file = sub_dir + '\\' + subj + '\\label\\rh.' + parcellation + '.annot' labels_lh, ctab, names_lh = nib.freesurfer.read_annot(aparc_lh_file) labels_rh, ctab, names_rh = nib.freesurfer.read_annot(aparc_rh_file) names_lh = [str(n)[2:-1] + '-lh' for n in names_lh] names_rh = [str(n)[2:-1] + '-rh' for n in names_rh] N_label_lh = len( names_lh ) # number of labels/parcels with unkown and med. wall included N_label_rh = len(names_rh) #### map parcels in data to loaded parcels indicesL = np.full(N_label_lh, -1) indicesR = np.full(N_label_rh, -1) for i in range(N_parc): for j in range(N_label_lh): if names_lh[j] == parcel_names[i]: indicesL[j] = i for j in range(N_label_rh): if names_rh[j] == parcel_names[i]: indicesR[j] = i - N_parc // 2 indicesL += 1 indicesR += 1 ## assign values to loaded parcels data1L = np.concatenate(([null_val], data1[:N_parc // 2])) data1R = np.concatenate(([null_val], data1[N_parc // 2:])) data_left = data1L[indicesL] data_right = data1R[indicesR] ## map parcel values to vertices vtx_data_left = data_left[labels_lh] vtx_data_left[labels_lh == -1] = null_val vtx_data_right = data_right[labels_rh] vtx_data_right[labels_rh == -1] = null_val if zmin == None: zmin = 0 if zmax == None: zmax = np.nanmax(abs(data1)) if zmid == None: zmid = zmax / 2 if style == 'linear': # shows only positive values center = None elif style == 'divergent': # shows positive and negative values center = 0 #### plot to 4-view Brain hemi = 'split' brain = Brain(subj, hemi, background='white', surf=surface, size=[900, 800], cortex='classic', subjects_dir=sub_dir, views=['lat', 'med']) brain.add_data(vtx_data_left, zmin, zmax, colormap=cmap, center=center, alpha=alpha, hemi='lh') brain.add_data(vtx_data_right, zmin, zmax, colormap=cmap, center=center, alpha=alpha, hemi='rh') # adjust colorbar brain.scale_data_colormap(zmin, zmid, zmax, transparent=transparent, center=center, alpha=alpha, verbose=None) #data=None, hemi=None, if filename != None: brain.save_image(filename) if show: return brain
CIs = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_consensus_CI') coords = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_coordinates') PC = np.loadtxt('//Volumes/neuro/Rest/Thalamic_parcel/roiPC') PC = PC/100 PC[PC>0.8] = 1 #PC[PC<0.3] = 0 PC = PC/0.9 from matplotlib import cm for i, coord in enumerate(coords): if CIs[i] != 0: if coord[0] < 0: brain.add_foci(coord, map_surface="white", color=cm.inferno(int(PC[i]*255))[0:3]) # save 1 image brain.save_image("pc_lat.tiff") ###### to visualize cortical ROI wmd values subject_id = "fsaverage" subjects_dir = os.environ["SUBJECTS_DIR"] brain = Brain("fsaverage", "lh", "inflated", views=['lat', 'med'], background="white") CIs = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_consensus_CI') coords = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_coordinates') WMD = np.loadtxt('//Volumes/neuro/Rest/Thalamic_parcel/roiWMD') WMD = WMD/100 WMD = WMD+1.5 WMD[WMD<0] =0 WMD = WMD/3 WMD[WMD>1] = 1
from surfer import Brain subj_dir = '/usr/local/freesurfer/subjects' subject = 'fsaverage' hemi = 'lh' surf = 'inflated' brain = Brain(subject, hemi, surf, subjects_dir=subj_dir) brain.show_view('lat') brain.save_image("pysurfer_test.png")
for hem,h in zip(['lh','rh'],[0,1]): vtx, _, t = stc_avg_cropped.center_of_mass(subject = 'fsaverage',hemi=h, restrict_vertices=False) # vtx2,_2,t2 = stc_avg_cropped.center_of_mass(subject = 'fsaverage',hemi=hem, restrict_vertices=False) print(vtx) np.save(meg_dir + '_STCS/%s/%s/%s/_CM_%s_%s_%s_%s_cropped.npy' % (tonetype,key,freq,tonetype,key,freq,hem), (vtx, _, t)) tonetype = 'pure' hemi = 'rh' hem = 1 cmap = cm.rainbow(np.linspace(0,1,len(frequencies))) t_bin = [] b = Brain('fsaverage', hemi = hemi , surf = 'pial',background='white',alpha=0.5) for f,freq in enumerate(frequencies): vtx, _, t = np.load(meg_dir + '_STCS/%s/%s/%s/_CM_%s_%s_%s_%s_cropped.npy' % (tonetype,key,freq,tonetype,key,freq,hemi)) # vtx, _, t = np.load(meg_dir + '_STCS/%s/%s/_CM_%s_%s_%s_cropped.npy' % (tonetype,freq,tonetype,freq,hemi)) # get the mni co-ordinates of the center of mass coords = vertex_to_mni(int(vtx), hemis=hem, subject='fsaverage') print (coords) # plot result b.add_foci(coords, color=cmap[f], map_surface='pial', scale_factor=0.5) t_bin.append(t) b.save_image(meg_dir + '_STCS/%s/%s/_CM_%s.png'%(tonetype,key,key)) brain = stc_avg.plot(subject='fsaverage',hemi='rh',colormap='rainbow',smoothing_steps=1) brain.scale_data_colormap(fmin=220, fmid=370, fmax=624,transparent=True)
rh_aparc_file = os.path.join(label_dir, right_label_file) lh_labels, lh_ctab, lh_names = nb.freesurfer.read_annot(lh_aparc_file) rh_labels, rh_ctab, rh_names = nb.freesurfer.read_annot(rh_aparc_file) left_df = left_df.set_index('col').loc[lh_names].reset_index().fillna(0) right_df = right_df.set_index('col').loc[rh_names].reset_index().fillna(0) vtx_lh = left_df.val.values[lh_labels] vtx_lh[lh_labels == -1] = 0 vtx_rh = right_df.val.values[rh_labels] vtx_rh[rh_labels == -1] = 0 brain.add_data(vtx_lh, 0, 400, colormap="Reds", alpha=.8, hemi='lh') brain.add_annotation(lh_aparc_file, hemi='lh') brain.add_data(vtx_rh, 0, 400, colormap="Reds", alpha=.8, hemi='rh') brain.add_annotation(rh_aparc_file, hemi='rh', remove_existing=False) save_name = "../images/{}_brain.png".format(save_name) brain.save_image(save_name)
def drawBrainSurface(args): import pandas as pd subject_id = args.subject_id hemi = args.hemi surface = args.surface """ Read in the Buckner resting state network annotation. (This requires a relatively recent version of Freesurfer, or it can be downloaded separately). """ aparc_file = os.path.join(os.environ["SUBJECTS_DIR"], subject_id, "label", hemi + ".aparc.annot") labels, ctab, names = nib.freesurfer.read_annot(aparc_file) """ Make a random vector of scalar data corresponding to a value for each region in the parcellation. """ matData = pd.read_csv(args.input) ePhenLabel = matData['ePhenLabel'].as_matrix() values = matData['value'].as_matrix() if hemi == "lh": prefixStr = 'Left-' prefixStrLen = len(prefixStr) else: prefixStr = 'Right-' prefixStrLen = len(prefixStr) # match the name of values with ROI's idx = [] roi_data = np.zeros((len(names), )) # fill in with default for i in range(0, len(ePhenLabel)): if (str(ePhenLabel[i]))[prefixStrLen:] in names: #print "name of structure on MATLAB side :" , ePhenLabel[i] #print "name of structure on freesurfer side :", names[ names.index( (str(ePhenLabel[i]))[prefixStrLen:] ) ] #print "---------------------------" idx.append(i) roi_data[names.index( (str(ePhenLabel[i]))[prefixStrLen:])] = values[i] if (args.interval == [np.inf, -np.inf]): minVal = roi_data.min() maxVal = roi_data.max() else: minVal = args.interval[0] maxVal = args.interval[1] #minVal = 0 #maxVal = 1 """ Make a vector containing the data point at each vertex. """ vtx_data = roi_data[labels] """ Display these values on the brain. Use a sequential colormap (assuming these data move from low to high values), and add an alpha channel so the underlying anatomy is visible. """ """ Bring up the visualization. """ brain = Brain(subject_id, hemi, surface, config_opts=dict(background="white")) brain.add_data(vtx_data, minVal, maxVal, colormap=args.colormap, alpha=args.alpha) brain.save_image(args.output) brain.show_view(view=args.view) brain.save_image(args.output)
from surfer import Brain print(__doc__) brain = Brain("fsaverage", "both", "inflated", views="lateral", background="white") """ You can also use a custom colormap and tweak its range. """ brain.add_morphometry("thickness", colormap="Blues", min=1, max=4, colorbar=False) brain.save_image('./figures/elements_fig_concept_anatomy.png')
""" Get a path to the overlay file. """ mri_file = '/Volumes/scratch/jamalw/HMM_searchlight_K_sweep_srm_bound_match/zstats_map_srmK=' + srmK + '.nii.gz' reg_file = '/Applications/freesurfer/average/mni152.register.dat' data = nib.load(mri_file) minval = 0.2 maxval = np.max(data.get_data()) surf_data_lh = project_volume_data(mri_file,"lh",reg_file) surf_data_rh = project_volume_data(mri_file,"rh",reg_file) qmri_file = '/Volumes/scratch/jamalw/HMM_searchlight_K_sweep_srm_bound_match/qstats_map_srmK=' + srmK + '.nii.gz' qdata_lh = project_volume_data(qmri_file,"lh",reg_file) surf_data_lh[np.logical_or(qdata_lh>0.005,surf_data_lh<0)] = 0 qdata_rh = project_volume_data(qmri_file,"rh",reg_file) surf_data_rh[np.logical_or(qdata_rh>0.005, surf_data_rh<0)] = 0 brain.add_overlay(surf_data_lh,min=minval,max=maxval,name="thirty_sec_lh", hemi='lh',sign="pos") brain.add_overlay(surf_data_rh,min=minval,max=maxval,name="thirty_sec_rh", hemi='rh',sign="pos") brain.save_image("zstats_human_bounds_srm_k" + srmK + ".png") mlab.show() brain.show_view(view)