def make_atlas_surface(label, hemi, name='', output_dir='/tmp'): if os.path.exists('/neurospin/ibc'): dir_ = '/neurospin/ibc/derivatives/sub-01/ses-00/anat/fsaverage/surf' else: dir_ = '/storage/store/data/ibc/derivatives/sub-01/ses-00/anat/' + \ 'fsaverage/surf' if hemi == 'right': mesh = os.path.join(dir_, 'rh.inflated') bg_map = os.path.join(dir_, 'rh.sulc') else: mesh = os.path.join(dir_, 'lh.inflated') bg_map = os.path.join(dir_, 'lh.sulc') medial = os.path.join(output_dir, '%s_medial_%s.png' % (name, hemi)) lateral = os.path.join(output_dir, '%s_lateral_%s.png' % (name, hemi)) plotting.plot_surf_roi(mesh, label, hemi=hemi, bg_map=bg_map, view='lateral', output_file=lateral, alpha=.9) plotting.plot_surf_roi(mesh, label, hemi=hemi, bg_map=bg_map, view='medial', output_file=medial, alpha=.9)
def plot_brain_saliences(custom_roi, minval=0, maxval=None, figpath=None, cbar=False, cmap=None): mpl.rcParams.update(mpl.rcParamsDefault) if cmap is None: cmap = 'coolwarm' fsaverage = datasets.fetch_surf_fsaverage() orders = [('medial', 'left'), ('medial', 'right'), ('lateral', 'left'), ('lateral', 'right')] fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(8.0, 6.0), dpi=300, frameon=False, sharex=True, sharey=True, subplot_kw={'projection': '3d'}) fig.subplots_adjust(hspace=0., wspace=0.00005) axes_list = fig.axes for index, order in enumerate(orders): view = order[0] hemi = order[1] texture = surface.vol_to_surf(custom_roi, fsaverage['pial_%s' % hemi]) plotting.plot_surf_roi(fsaverage['infl_%s' % hemi], texture, cmap=cmap, hemi=hemi, view=view, bg_on_data=True, axes=axes_list[index], bg_map=fsaverage['sulc_%s' % hemi], vmin=minval, vmax=maxval, output_file=figpath, symmetric_cbar=False, figure=fig, darkness=.5, colorbar=cbar) plt.clf()
def plot_roi_img_surf(surf_img, saving_path, plot_name, mask=None, labels=None, inflated=False, compute_surf=True, colorbar=True, **kwargs): fsaverage = datasets.fetch_surf_fsaverage() if compute_surf: surf_img = vol_to_surf(surf_img, fsaverage[kwargs['surf_mesh']], interpolation='nearest', mask_img=mask) surf_img[np.isnan(surf_img)] = -2 if labels is not None: surf_img = np.round(surf_img) surf_img += 2 if saving_path: plt.close('all') plt.hist(surf_img, bins=50) plt.title(plot_name) plt.savefig(saving_path + "hist_{}.png".format(plot_name)) plt.close('all') if inflated: kwargs['surf_mesh'] = 'infl_left' if 'left' in kwargs['surf_mesh_type'] else 'infl_right' disp = plotting.plot_surf_roi( surf_mesh=fsaverage[kwargs['surf_mesh']], roi_map=surf_img, hemi=kwargs['hemi'], view=kwargs['view'], bg_map=fsaverage[kwargs['bg_map']], bg_on_data=kwargs['bg_on_data'], darkness=kwargs['darkness'], colorbar=colorbar) if saving_path: disp.savefig(saving_path + plot_name + '_{}_{}_{}.png'.format(kwargs['surf_mesh_type'], kwargs['hemi'], kwargs['view'])) plotting.show()
def plot_roi(names): labels = mne.read_labels_from_annot('fsaverage_1', parc='aparc', subjects_dir=join('/imaging/ai05/RED/RED_MEG/resting/STRUCTURALS','FS_SUBDIR')) #labels = labels[0:-1] label_names = [label.name for label in labels] #names = ['lingual-lh', 'parahippocampal-lh', 'parahippocampal-rh'] ninds = [label_names.index(i) for i in names] # nilearn parcellation is a list representing each vertex, do left and right seperatl # MNE labels are a list representing the index of each vertex the parcel contains parcellation = np.zeros([10242]) names_cmap_inds = [] for i in range(len(names)): vinds = labels[ninds[i]].get_vertices_used() names_cmap_inds.append(i+1) for ii in vinds: parcellation[ii] = i+1 fsaverage = datasets.fetch_surf_fsaverage() cmap = cm.get_cmap('gist_ncar') legend_elements = [patches.Patch(facecolor=cmap(x), edgecolor=cmap(x), label=y) for x,y in zip(names_cmap_inds, names)] fig, ax = plt.subplots(2,2, subplot_kw={'projection': '3d'}) plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=parcellation, hemi='left', view='medial', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5, axes=ax[0,0], title= 'Left Hemisphere Medial', cmap=cmap) plotting.plot_surf_roi(fsaverage['pial_right'], roi_map=parcellation, hemi='right', view='medial', bg_map=fsaverage['sulc_right'], bg_on_data=True, darkness=.5, axes=ax[0,1], title= 'Right Hemisphere Medial', cmap=cmap) plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5, axes=ax[1,0], title= 'Left Hemisphere Lateral', cmap=cmap) plotting.plot_surf_roi(fsaverage['pial_right'], roi_map=parcellation, hemi='right', view='lateral', bg_map=fsaverage['sulc_right'], bg_on_data=True, darkness=.5, axes=ax[1,1], title= 'Right Hemisphere Lateral', cmap=cmap) fig.legend() plt.subplots_adjust(right=0.85) return [fig, ax]
def plot_fragment(frag_file, filename, fpath_sphere, surface): """ Plot fragmented region on specific surface """ # Load labels of new fragmented annotation labels, _, _ = freesurfer.read_annot(frag_file) # Specify on which surface to plot surf_type = fpath_sphere.replace('.sphere', '.%s' % surface) # Plot fragmented region on surface with colored annotation plot_surf_roi(surf_type, roi_map=labels, hemi='left', view='lateral', cmap='Spectral', output_file=filename)
def surf_plot_roi(stat, hemi='left', mesh='infl', platform='camh', fsaverage='fsaverage5', **kwargs): stat_fsavg, fsaverage = sch2fsavg(stat, mesh=fsaverage) fig = plotting.plot_surf_roi(fsaverage[mesh + '_' + hemi], stat_fsavg[0 if hemi == 'left' else 1], hemi=hemi, bg_map=fsaverage['sulc_' + hemi], bg_on_data=True, **kwargs) return fig
# Re-mask previously masked nodes (medial wall) stat_map[np.where(np.mean(timeseries, axis=1) == 0)] = 0 ############################################################################### # Display ROI on surface # Transform ROI indices in ROI map pcc_map = np.zeros(parcellation.shape[0], dtype=int) pcc_map[pcc_labels] = 1 from nilearn import plotting plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=pcc_map, hemi='left', view='medial', bg_map=fsaverage['sulc_left'], bg_on_data=True, title='PCC Seed') ############################################################################### # Display unthresholded stat map with dimmed background plotting.plot_surf_stat_map(fsaverage['pial_left'], stat_map=stat_map, hemi='left', view='medial', colorbar=True, bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5, title='Correlation map')
print('Fsaverage5 inflated surface of left hemisphere is at: %s' % fsaverage['infl_left']) print('Fsaverage5 sulcal depth map of left hemisphere is at: %s' % fsaverage['sulc_left']) ############################################################################### # Visualization # ------------- # Display Destrieux parcellation on fsaverage5 pial surface using nilearn from nilearn import plotting plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5) ############################################################################### # Display Destrieux parcellation on inflated fsaverage5 surface plotting.plot_surf_roi(fsaverage['infl_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5) ###############################################################################
print('Fsaverage5 pial surface of left hemisphere is at: %s' % fsaverage['pial_left']) print('Fsaverage5 inflated surface of left hemisphere is at: %s' % fsaverage['infl_left']) print('Fsaverage5 sulcal depth map of left hemisphere is at: %s' % fsaverage['sulc_left']) ############################################################################### # Visualization # ------------- # Display Destrieux parcellation on fsaverage5 pial surface using nilearn from nilearn import plotting plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5) ############################################################################### # Display Destrieux parcellation on inflated fsaverage5 surface plotting.plot_surf_roi(fsaverage['infl_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5) ############################################################################### # Display Destrieux parcellation with different views: posterior plotting.plot_surf_roi(fsaverage['infl_left'], roi_map=parcellation, hemi='left', view='posterior', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5)
fsaverage = datasets.fetch_surf_fsaverage5() # The fsaverage dataset contains file names pointing to the file locations print('Fsaverage5 pial surface of left hemisphere is at: %s' % fsaverage['pial_left']) print('Fsaverage5 inflated surface of left hemisphere is at: %s' % fsaverage['infl_left']) print('Fsaverage5 sulcal depth map of left hemisphere is at: %s' % fsaverage['sulc_left']) ############################################################################### # Visualization # ------------- # Display Destrieux parcellation on fsaverage5 pial surface using nilearn from nilearn import plotting plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5, cmap='gist_ncar') ############################################################################### # Display Destrieux parcellation on inflated fsaverage5 surface plotting.plot_surf_roi(fsaverage['infl_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5, cmap='gist_ncar') plotting.show()
def plot_surface_ctx( roi_values, scale='scale1', cmap="Spectral", save_fig=False, output_dir="./", filename=None, fmt="png"): """ Plots a set of values on a cortex surface on a given scale of the Lausanne 2018 parcellation. Parameters ---------- roi_values: numpy array The values to be plotted on the surface. The array should have as many values as regions of interest scale: {'scale1', 'scale2', 'scale3', 'scale4', 'scale5'} Scale of the Lausanne 2018 atlas to be used cmap: string Colormap to use for plotting, default "Spectral" save_fig: bool Whether to save the generated figures, default: `False` output_dir: string Directory to save the figure, only used when `save_fig == True` filename: string Filename of the saved figure (without the extension), only used when `save_fig == True` fmt: string Format to save the figures in Default: "png", also accepted are "pdf", and "svg" (and others, depending on the backend used) """ # Surface mesh fsaverage = datasets.fetch_surf_fsaverage(mesh="fsaverage") # File paths to the annot files annots = [get_lausanne2018_parcellation_annot(scale=f'{scale}', hemi='rh'), get_lausanne2018_parcellation_annot(scale=f'{scale}', hemi='lh')] # Read annot files annot_right = nib.freesurfer.read_annot(annots[0]) annot_left = nib.freesurfer.read_annot(annots[1]) # Create vector to store intensity values (one value per vertex) roi_vect_right = np.zeros_like(annot_right[0], dtype=float) roi_vect_left = np.zeros_like(annot_left[0], dtype=float) # Convert labels to strings, labels are the same as 2018 is symmetric labels = [str(elem, 'utf-8') for elem in annot_right[2]] # Create roi vectors for i in range(len(labels[1:])): # skip 'unknown' ids_roi = np.where(annot_right[0] == i+1)[0] roi_vect_right[ids_roi] = roi_values[i] for i in range(len(labels[1:])): # skip 'unknown' ids_roi = np.where(annot_left[0] == i+1)[0] roi_vect_left[ids_roi] = roi_values[i+len(labels)-1] # Get min and max values vmin = min(roi_values) vmax = max(roi_values) # Center around 0 max_val = max([abs(vmin), vmax]) vmax = max_val vmin = -max_val # Creation of list to allow iteration # and reduce duplication of plotting.plot_surf_roi() hemis = [ 'right', 'left', 'right', 'left', 'right', 'left', 'right', 'left', ] views = [ 'lateral', 'lateral', 'medial', 'medial', 'ventral', 'ventral', 'dorsal', 'dorsal' ] surfaces = [f'pial_{hemi}' for hemi in hemis] bg_maps = [f'sulc_{hemi}' for hemi in hemis] roi_vectors = [roi_vect_right, roi_vect_left]*4 # Initial a figure with [2 x 4] subplots fig, axs = plt.subplots(nrows=2, ncols=4, subplot_kw={'projection': '3d'}, figsize=(20,10)) axs = axs.flatten() # Iterate over the list of views to render for i, (hemi, surf, bg_map, view, vector, ax) in enumerate( zip(hemis, surfaces, bg_maps, views, roi_vectors, axs) ): plotting.plot_surf_roi(fsaverage[f'{surf}'], roi_map=vector, hemi=hemi, view=view, bg_map=fsaverage[f'{bg_map}'], bg_on_data=True, darkness=.5, cmap=cmap, vmin=vmin, vmax=vmax, axes=axs[i]) # Save the figure in the desired format if enabled if save_fig: if filename is None: filename = f'atlas-{scale}_projection' fig.savefig(f'{output_dir}/{filename}.{fmt}')
roi_voxels = ((roi_surf == 1)) & (network <= samples_th) else: raise Exception('unknown thershold type') print( f'ROI name: {ROI_name}, number of voxels {np.sum(roi_voxels)}' ) fig = plt.figure(figsize=[11, 8]) ax0 = fig.add_axes((.05, .1, .6, .7), projection='3d') #plotting.plot_surf_stat_map(fsaverage['infl_' + hemi], network, hemi=hemi, # colormap='coolwarm', threshold=0,axes=ax0) plotting.plot_surf_roi(surf_mesh=fsaverage['infl_' + hemi], roi_map=roi_voxels, hemi=hemi, view='lateral', cmap='hot', bg_map=network, bg_on_data=True, alpha=.3, darkness=.2, axes=ax0) plotting.plot_surf_contours( fsaverage['infl_' + hemi], roi_surf, levels=[ 1, ], axes=ax0, legend=True, colors=[ 'k',
coords, faces = surface.load_surf_mesh(surf_file) # create a brain mask mask = image.math_img('img>0', img=label) # project labels onto surface projected_labels = surface.vol_to_surf(label, [coords, faces], interpolation='nearest', mask_img=mask) # In[8]: # there are nan's in projected labels projected_labels # In[9]: plotting.plot_surf_roi([coords, faces], projected_labels) # this is not how projected labels should look # In[17]: # checking out surface mesh coordinates -- plotting.plot_roi(label_file, bg_img=brain_file, alpha=.3, cut_coords=coords[15000, :]) plotting.show() # there shouldn't be a mesh vertex in the cerebellum! # so surface coordinate system is not "in alignment" with the volumetric data, but why is that? # brain.mgz and lh.pial (as generated by recon-all) should be in same space.
# Transform ROI indices in ROI map pcc_map = np.zeros(parcellation.shape[0], dtype=int) pcc_map[4294] = 1 pcc_map[4295] = 1 corr_flag = 'true' a = np.load(f'/home/senthil/Downloads/tmp/corr_ortho_{corr_flag}.npy') b = a[4294, :][:10240] b = np.pad(b, (0, 2), 'constant') from nilearn import plotting display = plotting.plot_surf_roi(fsaverage['infl_left'], roi_map=pcc_map, hemi='left', view='medial', darkness=0.6, bg_map=fsaverage['sulc_left'], title='Seed') display.savefig(f'/home/senthil/Desktop/1_{corr_flag}.png', dpi=1200) display = plotting.plot_surf_stat_map(fsaverage['infl_left'], stat_map=b, hemi='left', view='medial', colorbar=False, bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.3, title='Correlation map', vmax=b.max(),
for i in v_s_r: if i in regi_l: tmp_r[ss[0] == regi_l.index(i)] = regi_l.index(i) j = 1 plt.figure(figsize=(10, 20)) for i in [ 'lateral', 'medial', 'dorsal', 'ventral', 'anterior', 'posterior' ]: ax = plt.subplot(6, 2, 2 * j - 1, projection='3d') plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=tmp_l, hemi='left', view=i, title='Left_' + i, bg_map=fsaverage['sulc_left'], bg_on_data=True, axes=ax, darkness=1) ax = plt.subplot(6, 2, 2 * j, projection='3d') plotting.plot_surf_roi(fsaverage['pial_right'], roi_map=tmp_r, hemi='right', view=i, title='Right_' + i, bg_map=fsaverage['sulc_right'], bg_on_data=True, axes=ax, darkness=1) j += 1
stat_map[i] = stats.pearsonr(seed_timeseries, timeseries[i])[0] # Re-mask previously masked nodes (medial wall) stat_map[np.where(np.mean(timeseries, axis=1) == 0)] = 0 ############################################################################### # Display ROI on surface # Transform ROI indices in ROI map pcc_map = np.zeros(parcellation.shape[0], dtype=int) pcc_map[pcc_labels] = 1 from nilearn import plotting plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=pcc_map, hemi='left', view='medial', bg_map=fsaverage['sulc_left'], bg_on_data=True, title='PCC Seed') ############################################################################### # Display unthresholded stat map with a slightly dimmed background plotting.plot_surf_stat_map(fsaverage['pial_left'], stat_map=stat_map, hemi='left', view='medial', colorbar=True, bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.3, title='Correlation map') ############################################################################### # Many different options are available for plotting, for example thresholding, # or using custom colormaps plotting.plot_surf_stat_map(fsaverage['pial_left'], stat_map=stat_map, hemi='left', view='medial', colorbar=True, bg_map=fsaverage['sulc_left'], bg_on_data=True,
print('Fsaverage5 inflated surface of left hemisphere is at: %s' % fsaverage['infl_left']) print('Fsaverage5 sulcal depth map of left hemisphere is at: %s' % fsaverage['sulc_left']) ############################################################################### # Visualization # ------------- # Display Destrieux parcellation on fsaverage5 pial surface using nilearn from nilearn import plotting plotting.plot_surf_roi(fsaverage['pial_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5, cmap='gist_ncar') ############################################################################### # Display Destrieux parcellation on inflated fsaverage5 surface plotting.plot_surf_roi(fsaverage['infl_left'], roi_map=parcellation, hemi='left', view='lateral', bg_map=fsaverage['sulc_left'], bg_on_data=True, darkness=.5, cmap='gist_ncar')