def plot_brain_color_legend(palette): from surfer import Brain from pymeg import atlas_glasser as ag from pymeg import source_reconstruction as sr labels = sr.get_labels(subject='S04', filters=['*wang*.label', '*JWDG*.label'], annotations=['HCPMMP1']) labels = sr.labels_exclude(labels=labels, exclude_filters=[ 'wang2015atlas.IPS4', 'wang2015atlas.IPS5', 'wang2015atlas.SPL', 'JWDG_lat_Unknown' ]) labels = sr.labels_remove_overlap(labels=labels, priority_filters=['wang', 'JWDG']) lc = ag.labels2clusters(labels) brain = Brain('S04', 'lh', 'inflated', views=['lat'], background='w') for cluster, labelobjects in lc.items(): if cluster in palette.keys(): color = palette[cluster] for l0 in labelobjects: if l0.hemi == 'lh': brain.add_label(l0, color=color, alpha=1) brain.save_montage( '/Users/nwilming/Dropbox/UKE/confidence_study/brain_colorbar.png', [['par', 'fro'], ['lat', 'med']]) return brain
def visMontage(pathToSurface, overlay, outputPath, hemi, type='white'): brain = Brain(pathToSurface, hemi, type) brain.add_overlay(overlay, -5, 3) brain.save_montage(outputPath, ['l', 'm'], orientation='v') brain.close() return outputPath
def plot_one_brain(dsignal, signal, lc, cmap, ex_sub='S04', classifier='SCVlin', epoch='response', measure='auc', views=[['par', 'fro'], ['lat', 'med']]): from surfer import Brain print('Creating Brain') brain = Brain(ex_sub, 'lh', 'inflated', views=['lat'], background='w') # subjects_dir='/Users/nwilming/u/freesurfer_subjects/') print('Created Brain') ms = dsignal.mean() if (signal == 'CONF_signed') and (measure == 'accuracy'): plot_labels_on_brain(brain, lc, ms, cmap) if (signal == 'SSD'): plot_labels_on_brain(brain, lc, ms, cmap) else: plot_labels_on_brain(brain, lc, ms, cmap) brain.save_montage( '/Users/nwilming/Desktop/%s_montage_%s_%s_%s.png' % (signal, measure, classifier, epoch), views) return brain
def corr_image(resting_image,fwhm): """This function makes correlation image on brain surface""" import numpy as np import nibabel as nb import matplotlib.pyplot as plt from surfer import Brain, Surface import os img = nb.load(resting_image) corrmat = np.corrcoef(np.squeeze(img.get_data())) corrmat[np.isnan(corrmat)] = 0 corrmat_npz = os.path.abspath('corrmat.npz') np.savez(corrmat_npz,corrmat=corrmat) br = Brain('fsaverage5', 'lh', 'smoothwm') #br.add_overlay(corrmat[0,:], min=0.2, name=0, visible=True) lh_aparc_annot_file = os.path.join(os.environ["FREESURFER_HOME"],'/subjects/label/lh.aparc.annot') values = nb.freesurfer.read_annot(lh_aparc_annot_file) #br.add_overlay(np.mean(corrmat[values[0]==5,:], axis=0), min=0.8, name='mean', visible=True) data = img.get_data() data = np.squeeze(img.get_data()) # precuneus_signal = np.mean(data[values[0]==np.nonzero(np.array(values[2])=='precuneus')[0][0],:], axis=0) precuneus = np.corrcoef(precuneus_signal, data) #precuneus.shape #br.add_overlay(precuneus[0,1:], min=0.3, sign='pos', name='mean', visible=True) br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True) #br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True) plt.hist(precuneus[0,1:], 128) plt.savefig(os.path.abspath("histogram.png")) plt.close() corr_image = os.path.abspath("corr_image%s.png"%fwhm) br.save_montage(corr_image) ims = br.save_imageset(prefix=os.path.abspath('fwhm_%s'%str(fwhm)),views=['medial','lateral','caudal','rostral','dorsal','ventral']) br.close() print ims #precuneus[np.isnan(precuneus)] = 0 #plt.hist(precuneus[0,1:]) roitable = [['Region','Mean Correlation']] for i, roi in enumerate(np.unique(values[2])): roitable.append([roi,np.mean(precuneus[values[0]==np.nonzero(np.array(values[2])==roi)[0][0]])]) #images = [corr_fimage]+ims+[os.path.abspath("histogram.png"), roitable] roitable=[roitable] histogram = os.path.abspath("histogram.png") return corr_image, ims, roitable, histogram, corrmat_npz
def make_brain(subject_id,image_path): from surfer import Brain hemi = 'lh' surface = 'inflated' brain = Brain(subject_id, hemi, surface) brain.add_overlay(image_path,min=thr) outpath = os.path.join(os.getcwd(),os.path.split(image_path)[1]+'_surf.png') brain.save_montage(outpath) return outpath
def make_brain(subject_id,image_path): from surfer import Brain hemi = 'lh' surface = 'inflated' brain = Brain(subject_id, hemi, surface) brain.add_overlay(image_path,min=thr) outpath = os.path.join(os.getcwd(),os.path.split(image_path)[1]+'_surf.png') brain.save_montage(outpath) return outpath
def corr_image(resting_image,fwhm): """This function makes correlation image on brain surface""" import numpy as np import nibabel as nb import matplotlib.pyplot as plt from surfer import Brain, Surface import os img = nb.load(resting_image) corrmat = np.corrcoef(np.squeeze(img.get_data())) corrmat[np.isnan(corrmat)] = 0 corrmat_npz = os.path.abspath('corrmat.npz') np.savez(corrmat_npz,corrmat=corrmat) br = Brain('fsaverage5', 'lh', 'smoothwm') #br.add_overlay(corrmat[0,:], min=0.2, name=0, visible=True) lh_aparc_annot_file = os.path.join(os.environ["FREESURFER_HOME"],'/subjects/label/lh.aparc.annot') values = nb.freesurfer.read_annot(lh_aparc_annot_file) #br.add_overlay(np.mean(corrmat[values[0]==5,:], axis=0), min=0.8, name='mean', visible=True) data = img.get_data() data = np.squeeze(img.get_data()) # precuneus_signal = np.mean(data[values[0]==np.nonzero(np.array(values[2])=='precuneus')[0][0],:], axis=0) precuneus = np.corrcoef(precuneus_signal, data) #precuneus.shape #br.add_overlay(precuneus[0,1:], min=0.3, sign='pos', name='mean', visible=True) br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True) #br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True) plt.hist(precuneus[0,1:], 128) plt.savefig(os.path.abspath("histogram.png")) plt.close() corr_image = os.path.abspath("corr_image%s.png"%fwhm) br.save_montage(corr_image) ims = br.save_imageset(prefix=os.path.abspath('fwhm_%s'%str(fwhm)),views=['medial','lateral','caudal','rostral','dorsal','ventral']) br.close() print ims #precuneus[np.isnan(precuneus)] = 0 #plt.hist(precuneus[0,1:]) roitable = [['Region','Mean Correlation']] for i, roi in enumerate(np.unique(values[2])): roitable.append([roi,np.mean(precuneus[values[0]==np.nonzero(np.array(values[2])==roi)[0][0]])]) #images = [corr_fimage]+ims+[os.path.abspath("histogram.png"), roitable] roitable=[roitable] histogram = os.path.abspath("histogram.png") return corr_image, ims, roitable, histogram, corrmat_npz
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 img2disc(data, foci_all=False, foci_dmn=False, labelfile=False, hemi='lh', filename='temp.png'): brain = Brain('fsaverage5', hemi, 'inflated', curv=False) brain.add_data(data, data.min(), data.max(), colormap="spectral", alpha=0.6) if labelfile: brain.add_label(labelfile, borders=True, color='grey') if foci_all: brain.add_foci(foci_all, coords_as_verts=True, scale_factor=.5, color='black') if foci_dmn: brain.add_foci(foci_dmn, coords_as_verts=True, scale_factor=.7, color='blue') brain.save_montage(filename, order=['lat', 'med'], orientation='h', border_size=10)
def make_brain_figures(srcdf, measure, cinfo, filepat_base, top=5): views = {'rh': ['medial', 'lateral'], 'lh': ['lateral', 'medial']} toplabels = {} for hemi in ['lh', 'rh']: brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir=sv.subjects_dir, background='w', foreground='k') sv.show_labels_as_data(srcdf, measure, brain, time_label=None, parc=parc, **cinfo) if top: ind = srcdf.index.get_level_values('label').map( lambda x: x.startswith(hemi[0].upper())) topl = srcdf[ind].abs().sort_values( measure, ascending=False).head(top) topl = ( topl[(topl[measure] != 0) & topl[measure].notna()] .index.droplevel('time')) toplabels[hemi] = topl alllabels = mne.read_labels_from_annot( 'fsaverage', parc=parc, hemi=hemi) brain.remove_labels() for label in alllabels: if label.name in topl: brain.add_label(label, borders=1, hemi=hemi, alpha=0.8, color='k') # increase font size of colorbar - this only works by increasing the # colorbar itself and setting the ratio of colorbar to text brain.data['colorbar'].scalar_bar.bar_ratio = 0.35 brain.data['colorbar'].scalar_bar_representation.position = [0.075, 0.01] brain.data['colorbar'].scalar_bar_representation.position2 = [0.85, 0.12] filepat = os.path.join(figdir, filepat_base + '_{}.png'.format(hemi)) brain.save_montage(filepat, views[hemi], colorbar=0) brain.close() infiles = [ os.path.join(figdir, filepat_base + '_{}.png'.format(hemi)) for hemi in ['lh', 'rh']] outfile = os.path.join(figdir, filepat_base + '.png') os.system("montage -tile 2x1 -geometry +0+0 {} {}".format( ' '.join(infiles), outfile)) return toplabels
def plot_vertices(vertices_lh, vertices_rh, alpha=0.5, save=False, fname=None, simulated=False, col='green'): from surfer import Brain # Read labels subjects_dir = sample.data_path() + '/subjects' lh_vertex = 114573 # Auditory label rh_vertex = 53641 # Medial occipital label brain = Brain('sample', hemi='lh', surf='inflated', subjects_dir=subjects_dir, title='lh', background='white') if simulated: brain.add_foci(lh_vertex, coords_as_verts=True, color='red', hemi='lh') brain.add_foci(vertices_lh, coords_as_verts=True, color=col, alpha=alpha, hemi='lh') if save: brain.save_montage('paper_figures/images/' + fname + '_lat_lh.png', order=['lat'], border_size=1) brain = Brain('sample', hemi='rh', surf='inflated', subjects_dir=subjects_dir, title='rh', views=['lat'], background='white') if simulated: brain.add_foci(rh_vertex, coords_as_verts=True, color='red', hemi='rh') brain.add_foci(vertices_rh, coords_as_verts=True, color=col, alpha=alpha, hemi='rh') if save: brain.save_montage('paper_figures/images/' + fname + '_lat_rh.png', order=['lat'], border_size=1) return brain
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 vizBrain(data, subject_id='fsaverage5', hemi='lh', surface='pial', filename='brain.png'): brain = Brain(subject_id, hemi, surface) dmin = data.min() #+(data.std()/2) dmax = data.max() #-(data.std()/2) brain.add_data(data, dmin, dmax, colormap="hot", alpha=0.7) brain.save_montage(filename, order=['lat', 'med'], orientation='h', border_size=10)
def visMorph(pathToSurface, overlay, outputPath, hemi): ''' Display anything morphometric ''' # check the overlay if (not overlay == 'sulc' and not overlay == 'thickness' and not overlay == 'curv'): message = ('You specified %s as overlay, this doesn\'t make sense' % (overlay)) raise Exception(message) brain = Brain(pathToSurface, hemi, 'white') brain.add_morphometry(overlay) brain.save_montage(outputPath, ['l', 'm'], orientation='v') brain.close()
def plot_single_roi(roi): fsaverage = "fsaverage" hemi = "lh" surf = "inflated" t, p, str_names, labels = get_data() df = pd.DataFrame({'labs': str_names, 't': 0}) df.loc[df.labs == roi, 't'] = -4 data = df.t.values data = data[labels] brain = Brain(fsaverage, hemi, surf, background="white", views=['lateral', 'ventral', 'medial', 'frontal']) brain.add_data(data, -10, 11, thresh=None, colormap="RdBu_r", alpha=1) f = brain.save_montage(None, [['lateral', 'parietal'], ['medial', 'frontal']], border_size=0, colorbar=None) fig, a = plt.subplots() im = plt.imshow(f, cmap='RdBu_r') a.set(xticks=[], yticks=[]) sns.despine(bottom=True, left=True) cbar = fig.colorbar(im, ticks=[f.min(), (f.min() + 255) / 2, 255], orientation='horizontal', drawedges=False) cbar.ax.set_xticklabels(['-10', '0', '10']) a.set_title(roi) return f, data
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 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' 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 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 brain_labels(labels, names, subjects_dir, stc=None, title=None, hemi='both', view=['med'], save=False, fname='', dataset='sample_LAud'): from surfer import Brain n_support = names.shape[0] label_names = [label.name for label in labels] # Plot the selected labels in a Brain brain = Brain('sample', hemi=hemi, surf='inflated', subjects_dir=subjects_dir, title=title, views=view, background='white') for label in np.unique(names[:n_support // 2]): if hemi == 'both': # Left hemi idx = label_names.index(label) brain.add_label(labels[idx], color=labels[idx].color) # Right hemi idx = label_names.index(label[:-3] + '-rh') brain.add_label(labels[idx], color=labels[idx].color) elif hemi == 'lh': # Left hemi idx = label_names.index(label) brain.add_label(labels[idx], color=labels[idx].color) elif hemi == 'rh': # Right hemi idx = label_names.index(label[:-3] + '-rh') brain.add_label(labels[idx], color=labels[idx].color) if save: brain.save_montage('paper_figures/images/' + fname + '_' + view[0] + '_' + hemi + '.png', order=view, border_size=1)
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 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 make_pysurfer_images_lh_rh(folder,suffix='cope1',hemi='lh',threshold=0.9499,coords=(),surface='inflated',fwhm=0,filename='',saveFolder=[],vmax=5.0,bsize=5): 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",hemi,surface, 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 = io.project_volume_data(mri_file, hemi, 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, min=smin, max=vmax, name="activation", hemi=hemi) # brain.overlays["activation"] # brain.add_overlay(surf_data_rh, min=smin, max=5, name="ang_corr_rh", hemi='rh') if len(coords)>0: if coords[0]>0: hemi2='rh' else: hemi2='lh' brain.add_foci(coords, map_surface="pial", color="gold",hemi=hemi2) if len(saveFolder)>0: folder=saveFolder image_out=brain.save_montage('%s/%s-%s.png' % (folder,hemi,filename),order=['l','m'],orientation='h',border_size=bsize,colorbar=None) else: image_out=brain.save_image('%s/surfaceplot.jpg' % folder) brain.close() return image_out
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()
def montage_plot(parameter, fdr_correct=True): fsaverage = "fsaverage" hemi = "lh" surf = "inflated" t_data, p_data, str_names, labels = get_data() if fdr_correct is True: data = fdr_filter(t_data, p_data, parameter) else: data = t_data[parameter].values data = data[labels] brain = Brain(fsaverage, hemi, surf, background="white") brain.add_data(data, -10, 10, thresh=None, colormap="RdBu_r", alpha=.8) montage = brain.save_montage( None, [['lateral', 'parietal'], ['medial', 'frontal']], border_size=0, colorbar=None) fig, a = plt.subplots(figsize=(24, 24)) im = plt.imshow(montage, cmap='RdBu_r') a.set(xticks=[], yticks=[]) sns.despine(bottom=True, left=True) cbar = fig.colorbar(im, ticks=[montage.min(), (montage.min() + 255) / 2, 255], orientation='horizontal', drawedges=False) cbar.ax.set_xticklabels(['-10', '0', '10']) plt.rcParams['pdf.fonttype'] = 3 plt.rcParams['ps.fonttype'] = 3 sns.set(style='ticks', font_scale=1, rc={ 'axes.labelsize': 6, 'axes.titlesize': 40, 'xtick.labelsize': 40, 'ytick.labelsize': 5, 'legend.fontsize': 250, 'axes.linewidth': 0.25, 'xtick.major.width': 0.25, 'ytick.major.width': 0.25, 'ytick.major.width': 0.25, 'ytick.major.width': 0.25, 'ytick.major.pad': 2.0, 'ytick.minor.pad': 2.0, 'xtick.major.pad': 2.0, 'xtick.minor.pad': 2.0, 'axes.labelpad': 4.0, }) a.set_title(parameter) return fig
""" vtx_data = roi_data[labels] # Check if there are akwardly labelled regions and reset their values if len(np.where(labels == -1)[0]) > 0: vtx_data[np.where(labels == -1)] = default_value """ 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. """ brain.add_data(vtx_data, min=vtx_data.min(), max=vtx_data.max(), colormap="jet", alpha=.6) image = brain.save_montage("Example_FDG-PET_FreesurferRegions.png", ['l', 'd', 'm'], orientation='v') brain.close() ############################################################################### # View created image import pylab as pl fig = pl.figure(figsize=(5, 3), facecolor=bgcolor) ax = pl.axes(frameon=False) ax.imshow(image, origin='upper') pl.draw() pl.show()
Make a multiview image ====================== Make one image from multiple views. """ print __doc__ from surfer import Brain sub = 'fsaverage' hemi = 'lh' surf = 'inflated' brain = Brain(sub, hemi, surf) ############################################################################### # Save a set of images as a montage brain.save_montage('/tmp/fsaverage_h_montage.png', ['l', 'v', 'm'], orientation='v') brain.close() ############################################################################### # View created image import Image import pylab as pl image = Image.open('/tmp/fsaverage_h_montage.png') fig = pl.figure(figsize=(5,3)) pl.imshow(image, origin='lower') pl.xticks(()) pl.yticks(())
====================== Make one image from multiple views. """ print __doc__ from surfer import Brain sub = 'fsaverage' hemi = 'lh' surf = 'inflated' brain = Brain(sub, hemi, surf) ############################################################################### # Save a set of images as a montage brain.save_montage('/tmp/fsaverage_h_montage.png', ['l', 'v', 'm'], orientation='v') brain.close() ############################################################################### # View created image import Image import pylab as pl image = Image.open('/tmp/fsaverage_h_montage.png') fig = pl.figure(figsize=(5, 3)) pl.imshow(image, origin='lower') pl.xticks(()) pl.yticks(())
}) """ Get a path to the overlay file """ overlay_file = op.join("example_data", "lh.sig.nii.gz") """ Add the contour overlay with the default display settings Contours overlays only ever use the positive components of your image, but they get threshold and colormap saturation from your configuration settings just as normal overlays do. """ brain.add_contour_overlay(overlay_file) """ The Brain object can only display one contour overlay at a time, So if we bring up another one, it will remove the original overlay behind the scenes for us. Here let's specify a different number of contours and use a different line width. """ brain.add_contour_overlay(overlay_file, max=20, n_contours=9, line_width=2) """ At the moment, the Brain object itself does not expose an interface to manipulate what the contour overlay looks like after it has been loaded, but if you know a little bit about the underlying Mayavi engine, you can control aspects of the visualization through the contour dictionary attribute. """ brain.contour['surface'].actor.property.line_width = 1 brain.contour['surface'].contour.number_of_contours = 10 brain.save_montage('toto.png')
subjects_dir=data_mri_directory) # Add source time course brain.add_data(stc_data[hemi], colormap=colormap, vertices=stc_vertices[hemi], smoothing_steps=10, time=time_array, time_label=time_label, hemi=hemi, initial_time=0.) # Scale the F-map brain.scale_data_colormap(fmin=fmin, fmid=fmid, fmax=fmax, transparent=True) # Add the image array to all images for time in times: brain.set_time(time) fig_temp[hemi].append(brain.save_montage(filename=None, orientation='h')) fig_temp[hemi] = np.concatenate(fig_temp[hemi], axis=0) brain.close() # Correct for different lengths min_len = min(len(fig_temp['lh']), len(fig_temp['rh'])) fig_temp['lh'] = fig_temp['lh'][0:min_len, :, :] fig_temp['rh'] = fig_temp['rh'][0:min_len, :, :] # Collapse hemispheric images into one fig_array = np.concatenate([fig_temp['lh'], fig_temp['rh']], axis=1) # Plot figure and save it to report fig, ax = subplots(figsize=(20, len(times) * 2))
def brain_plot(brain, wname, toplabels=False, save=False, backface_culling=True): if r_name in ['dot_x', 'dot_y', 'dot_x_sign']: views = { 'rh': ['medial', 'parietal'], #{'azimuth': -20, 'elevation': 62, 'roll': -68}], 'lh': ['parietal', 'medial'] } elif r_name in ['sum_dot_x', 'response']: views = {'rh': ['medial', 'lateral'], 'lh': ['lateral', 'medial']} if type(brain) is str: hemi = brain brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir=sv.subjects_dir, background='w', foreground='k') else: hemi = brain.geo.keys()[0] if common_color_scale: cinfo = get_colorinfo(avsrcdf) else: cinfo = get_colorinfo(results[wname]['avsrcdf']) sv.show_labels_as_data(results[wname]['avsrcdf'], show_measure, brain, time_label=None, parc=parc, **cinfo) if backface_culling: brain.data['surfaces'][0].actor.property.backface_culling = True if toplabels: brain.remove_labels() alllabels = mne.read_labels_from_annot('fsaverage', parc=parc, hemi=hemi) for label in alllabels: if label.name in results[wname]['toplabels'][hemi]: brain.add_label(label, borders=1, hemi=hemi, alpha=0.8, color='k') if backface_culling: for ldict in brain._label_dicts.values(): ldict['surfaces'][0].actor.property.backface_culling = True # increase font size of colorbar - this only works by increasing the # colorbar itself and setting the ratio of colorbar to text brain.data['colorbar'].scalar_bar.bar_ratio = 0.35 brain.data['colorbar'].scalar_bar_representation.position = [0.075, 0.01] brain.data['colorbar'].scalar_bar_representation.position2 = [0.85, 0.12] if save: filepat = os.path.join(figdir, filepat_base + '_{}_{}.png'.format(wname, hemi)) brain.save_montage(filepat, views[hemi], colorbar=0) return brain
def brain_plot( wname, brain, toplabels=None, save=False, ): views = { 'rh': ['medial', 'lateral'], #{'azimuth': -20, 'elevation': 62, 'roll': -68}], 'lh': ['lateral', 'medial'] } if type(brain) is str: hemi = brain brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir=sv.subjects_dir, background='w', foreground='k') else: hemi = brain.geo.keys()[0] srcdf = pd.DataFrame(xma_win[wname].values.copy(), index=pd.MultiIndex.from_product( [labels, [0]], names=['label', 'time']), columns=[measure]) # get colorinfo based on distribution of differences before nulling cinfo = get_colorinfo(srcdf) # set all areas to 0 for which there is insufficient evidence that they # represent evidence; for positive differences supporting dot_x only # consider significant dot_x areas and equally for accev and negative for reg in regressors: if reg == 'accev': siglabels = srcdf[srcdf[measure] < 0].xs(0, level='time').index else: siglabels = srcdf[srcdf[measure] > 0].xs(0, level='time').index siglabels = is_significant.xs( reg, level='regressor').loc[list(siglabels), wname] siglabels = siglabels[~siglabels].index srcdf.loc[(list(siglabels), 0), measure] = 0 sv.show_labels_as_data(srcdf, measure, brain, time_label=None, parc=parc, **cinfo) # if toplabels is not None: # alllabels = mne.read_labels_from_annot( # 'fsaverage', parc=parc, hemi=hemi) # for label in alllabels: # if label.name in toplabels[hemi]: # brain.add_label(label, borders=1, hemi=hemi, alpha=0.8, # color='k') # increase font size of colorbar - this only works by increasing the # colorbar itself and setting the ratio of colorbar to text brain.data['colorbar'].scalar_bar.bar_ratio = 0.35 brain.data['colorbar'].scalar_bar_representation.position = [ 0.075, 0.01 ] brain.data['colorbar'].scalar_bar_representation.position2 = [ 0.85, 0.12 ] if save: filepat = os.path.join( figdir, filepat_base + '_{}_{}.png'.format(hemi, wname)) brain.save_montage(filepat, views[hemi], colorbar=0) return brain, srcdf[srcdf[measure].abs() > cinfo['fmid']].xs( 0, level='time')
roi_data = data_to_plot[pos] """ Make a vector containing the data point at each vertex. """ vtx_data = roi_data[labels] # Check if there are akwardly labelled regions and reset their values if len(np.where(labels==-1)[0]) > 0: vtx_data[np.where(labels==-1)] = default_value """ 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. """ brain.add_data(vtx_data, min=vtx_data.min(), max=vtx_data.max(), colormap="jet", alpha=.6) image = brain.save_montage("Example_FDG-PET_FreesurferRegions.png", ['l', 'd', 'm'], orientation='v') brain.close() ############################################################################### # View created image import pylab as pl fig = pl.figure(figsize=(5, 3), facecolor=bgcolor) ax = pl.axes(frameon=False) ax.imshow(image, origin='upper') pl.draw() pl.show()
# compute the distances between COM's of the labels rounded_coms, coords, coms_lh, coms_rh = get_label_distances(subject, subjects_dir, parc=parc) # np.save('%s_distances.npy' % subject, rounded_com) # get maximum distance between ROIs print('Max distance between ROIs', rounded_coms.ravel().max()) # do plotting using PySurfer brain = Brain(subject, hemi='both', surf='inflated', subjects_dir=subjects_dir) brain.add_foci(coms_lh, coords_as_verts=True, hemi='lh') brain.add_foci(coms_rh, coords_as_verts=True, hemi='rh') brain.save_montage('%s_%s_coms.png' % (subject, parc), order=['lat', 'ven', 'med'], orientation='h', border_size=15, colorbar='auto', row=-1, col=-1) brain.close() # show the label ROIs using Nilearn plotting fig = plotting.plot_connectome(rounded_coms, coords, edge_threshold='99%', node_color='cornflowerblue', title='%s - label distances' % parc) fig.savefig('%s_label_distances.png' % parc)
surf_data = surf_data.squeeze() surf_f = '%s/fsaverage5/surf/%s.orig' % (fsDir, hemi) surf_faces = nib.freesurfer.io.read_geometry(surf_f)[1] mask = np.zeros((10242)) while True in np.isnan(surf_data): nans = np.unique(np.where(np.isnan(surf_data))[0]) mask[nans] = 1 bad = [] good = {} for node in nans: neighbors = np.unique(surf_faces[np.where(np.in1d(surf_faces.ravel(), [node]).reshape(surf_faces.shape))[0]]) bad_neighbors = neighbors[np.unique(np.where(np.isnan(surf_data[neighbors]))[0])] good_neighbors = np.setdiff1d(neighbors, bad_neighbors) bad.append((node, len(bad_neighbors))) good[node] = good_neighbors bad = np.array(bad).transpose() nodes_with_least_bad_neighbors = bad[0][bad[1] == np.min(bad[1])] for node in nodes_with_least_bad_neighbors: surf_data[node] = np.mean(surf_data[list(good[node])], axis=0) surf_img._data = np.expand_dims(np.expand_dims(surf_data, axis=1), axis=1) brain = Brain('fsaverage5', hemi, 'pial', curv=False) brain.add_data(mask, mask.min(), mask.max(), colormap="spectral", alpha=0.6) brain.save_montage(mask_img_f, order=['lat', 'med'], orientation='h', border_size=10) np.save(mask_f, mask) else: surf_img._data = surf_data surf_img.to_filename(rest_interp_f)
subjects_dir = op.join(data_path, "subjects") os.environ['SUBJECTS_DIR'] = subjects_dir subject_id = "Bend1" hemi = "lh" surf = "pial" bgcolor = 'w' brain = Brain(subject_id, hemi, surf, config_opts={'background': bgcolor}, subjects_dir=subjects_dir) volume_file = op.abspath("example_fspet/corrected_pet_to_t1/_subject_id_Bend1/r_volume_MGRousset_flirt.nii") pet = project_volume_data(volume_file, hemi, subject_id=subject_id) brain.add_data(pet, min=250, max=12000, colormap="jet", alpha=.6, colorbar=True) image = brain.save_montage("Example_FDG-PET.png", ['l', 'd', 'm'], orientation='v') brain.close() ############################################################################### # View created image import pylab as pl fig = pl.figure(figsize=(5, 3), facecolor=bgcolor) ax = pl.axes(frameon=False) ax.imshow(image, origin='upper') pl.draw() pl.show()
""" Add the contour overlay with the default display settings Contours overlays only ever use the positive components of your image, but they get threshold and colormap saturation from your configuration settings just as normal overlays do. """ brain.add_contour_overlay(overlay_file) """ The Brain object can only display one contour overlay at a time, So if we bring up another one, it will remove the original overlay behind the scenes for us. Here let's specify a different number of contours and use a different line width. """ brain.add_contour_overlay(overlay_file, max=20, n_contours=9, line_width=2) """ At the moment, the Brain object itself does not expose an interface to manipulate what the contour overlay looks like after it has been loaded, but if you know a little bit about the underlying Mayavi engine, you can control aspects of the visualization through the contour dictionary attribute. """ brain.contour['surface'].actor.property.line_width = 1 brain.contour['surface'].contour.number_of_contours = 10 brain.save_montage('toto.png')
height = 400 if ri == 2 else 800 brain = Brain(subject_id='fsaverage', hemi=hemi, surf='inflated_pre', size=(height, width), offscreen=True, background='white') # Load corresponding label from fsaverage if roi_name == 'G_temp_sup-G_T_transv-rh.label': brain.add_label(aud_label_fsaverage, color=label_color, alpha=0.75) else: fname_load_label = op.join(struct_dir, model_subj, 'label', roi_name) temp_roi = mne.read_label(fname_load_label, subject=model_subj) brain.add_label(temp_roi, color=label_color, alpha=0.75) # Save montage as an image montage = brain.save_montage(None, order=view_dict[roi_name], orientation='v', border_size=15, colorbar=None) axes[0, ri].imshow(montage, interpolation='nearest', origin='upper', aspect='equal') brain.close() ax_coord = plt.axes(coord_ax_dims[ri], axisbg='none', projection='3d', aspect='equal') # Turn off appropriate ticks and spines and plot coordinate frame indicator if ri == 0: # This roundabout way preserves ability to set ylabel axes[0, 0].xaxis.set_visible(False) axes[0, 0].xaxis.set_ticklabels([]) axes[0, 0].yaxis.set_ticks([]) for spine in axes[0, 0].spines.values(): spine.set_visible(False)
def vizBrain(data, subject_id='fsaverage5', hemi='lh', surface='pial', filename='brain.png'): brain = Brain(subject_id, hemi, surface) dmin = data.min()#+(data.std()/2) dmax = data.max()#-(data.std()/2) brain.add_data(data, dmin, dmax, colormap="hot", alpha=0.7) brain.save_montage(filename, order=['lat', 'med'], orientation='h', border_size=10)
your image, but they get threshold and colormap saturation from your configuration settings just as normal overlays do. """ brain.add_contour_overlay(overlay_file) """ The Brain object can only display one contour overlay at a time, So if we bring up another one, it will remove the original overlay behind the scenes for us. Here let's specify a different number of contours and use a different line width. """ brain.add_contour_overlay(overlay_file, max=20, n_contours=9, line_width=2) """ At the moment, the Brain object itself does not expose an interface to manipulate what the contour overlay looks like after it has been loaded, but if you know a little bit about the underlying Mayavi engine, you can control aspects of the visualization through the contour dictionary attribute. """ brain.contour['surface'].actor.property.line_width = 1 brain.contour['surface'].contour.number_of_contours = 10 """ We can save several different views of this hemisphere to one file. """ brain.save_montage('examples/fmri_activation.png', colorbar='auto')
====================== Make one image from multiple views. """ print __doc__ from surfer import Brain sub = 'fsaverage' hemi = 'lh' surf = 'inflated' bgcolor = 'w' brain = Brain(sub, hemi, surf, config_opts={'background': bgcolor}) ############################################################################### # Get a set of images as a montage, note the data could be saved if desired image = brain.save_montage(None, ['l', 'v', 'm'], orientation='v') brain.close() ############################################################################### # View created image import pylab as pl fig = pl.figure(figsize=(5, 3), facecolor=bgcolor) ax = pl.axes(frameon=False) ax.imshow(image, origin='upper') pl.xticks(()) pl.yticks(()) pl.draw() pl.show()
bad = [] good = {} for node in nans: neighbors = np.unique(surf_faces[np.where( np.in1d(surf_faces.ravel(), [node]).reshape(surf_faces.shape))[0]]) bad_neighbors = neighbors[np.unique( np.where(np.isnan(surf_data[neighbors]))[0])] good_neighbors = np.setdiff1d(neighbors, bad_neighbors) bad.append((node, len(bad_neighbors))) good[node] = good_neighbors bad = np.array(bad).transpose() nodes_with_least_bad_neighbors = bad[0][bad[1] == np.min( bad[1])] for node in nodes_with_least_bad_neighbors: surf_data[node] = np.mean(surf_data[list(good[node])], axis=0) brain = Brain('fsaverage5', hemi, 'pial', curv=False) brain.add_data(mask, mask.min(), mask.max(), colormap="spectral", alpha=0.6) brain.save_montage(mask_img_f, order=['lat', 'med'], orientation='h', border_size=10) np.save(mask_f, mask) surf_img.to_filename(rest_interp_f)