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 vizify(self): for hemi in self.hemis: print "visualize %s" % hemi # Bring up the beauty (the underlay) brain = Brain(self.subject_id, hemi, self.surf, \ config_opts=self.config_opts, \ subjects_dir=self.subjects_dir) surf_data = io.read_scalar_data(self.overlay_surf[hemi]) if (sum(abs(surf_data)) > 0): # Overlay another hopeful beauty (functional overlay) brain.add_overlay(self.overlay_surf[hemi], name=self.overlay_name, min=self.min, max=self.max, sign=self.sign) # Update colorbar #brain.overlays[self.overlay_name].pos_bar.lut_mode = self.colorbar tmp = brain.overlays[self.overlay_name] lut = tmp.pos_bar.lut.table.to_array() lut[:,0:3] = self.colorbar tmp.pos_bar.lut.table = lut # Refresh brain.show_view("lat") brain.hide_colorbar() # Save the beauts brain.save_imageset("%s_%s" % (self.outprefix, hemi), self.views, 'jpg', colorbar=None) # End a great journey, till another life brain.close() return
def test_label(): """Test plotting of label.""" _set_backend() subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) brain.add_label("BA1") brain.add_label("BA1", color="blue", scalar_thresh=.5) subj_dir = utils._get_subjects_dir() label_file = pjoin(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) brain.add_label("BA44", borders=True) brain.add_label("BA6", alpha=.7) brain.show_view("medial") brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6) brain.set_surf('white') # remove labels brain.remove_labels('V1') assert_in('V2', brain.labels_dict) assert_not_in('V1', brain.labels_dict) brain.remove_labels() assert_not_in('V2', brain.labels_dict) brain.close()
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 main(subid, overlay): _, fname = os.path.split(overlay) hemi = fname[:2] brain = Brain(subid, hemi, "pial", config_opts=dict(cortex="low_contrast")) brain.add_overlay(overlay, min=0.4, max=4, sign="pos") brain.show_view('m')
def curvature_normalization(data_dir, subj): """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") panels = [] for hemi in ["lh", "rh"]: # Load the curv values and apply registration to fsaverage curv_fname = op.join(surf_dir, "{}.curv".format(hemi)) curv_vals = nib.freesurfer.read_morph_data(curv_fname) subj_curv_vals = apply_surface_warp(data_dir, subj, hemi, curv_vals) subj_curv_binary = (subj_curv_vals > 0) # Load the template curvature norm_fname = op.join(data_dir, "fsaverage", "surf", "{}.curv".format(hemi)) norm_curv_vals = nib.freesurfer.read_morph_data(norm_fname) norm_curv_binary = (norm_curv_vals > 0) # Compute the curvature overlap image curv_overlap = np.zeros_like(norm_curv_binary, np.int) curv_overlap[norm_curv_binary & subj_curv_binary] = 1 curv_overlap[norm_curv_binary ^ subj_curv_binary] = 2 # Mask out the medial wall cortex_fname = op.join(data_dir, "fsaverage", "label", "{}.cortex.label".format(hemi)) cortex = nib.freesurfer.read_label(cortex_fname) medial_wall = ~np.in1d(np.arange(curv_overlap.size), cortex) curv_overlap[medial_wall] = 1 # Plot the curvature overlap image try: b = Brain("fsaverage", hemi, "inflated", background="white") except TypeError: # PySurfer <= 0.5 b = Brain("fsaverage", hemi, "inflated", config_opts=dict(background="white")) b.add_data(curv_overlap, min=0, max=2, colormap=[".9", ".45", "indianred"], colorbar=False) for view in ["lat", "med", "ven"]: b.show_view(view, distance="auto") panels.append(crop(b.screenshot())) b.close() # Make and save a figure f = multi_panel_brain_figure(panels) fname = op.join(snap_dir, "surface_registration.png") f.savefig(fname, bbox_inches="tight") plt.close(f)
def contrast_loop(subj, contrasts, stat_temp, mask_temp, png_temp, args, z_thresh, sign): """Iterate over contrasts and make surface images.""" for contrast in contrasts: # Calculate where the overlay should saturate z_max = calculate_sat_point(stat_temp, contrast, sign, subj) panels = [] for hemi in ["lh", "rh"]: # Initialize the brain object b_subj = subj if args.regspace == "epi" else "fsaverage" try: b = Brain(b_subj, hemi, args.geometry, background="white") except TypeError: # PySurfer <= v0.5 b = Brain(b_subj, hemi, args.geometry, config_opts={"background": "white"}) # Plot the mask mask_file = mask_temp.format(contrast=contrast, hemi=hemi, subj=subj) add_mask_overlay(b, mask_file) # Plot the overlay stat_file = stat_temp.format(contrast=contrast, hemi=hemi, subj=subj) add_stat_overlay(b, stat_file, z_thresh, z_max, sign, sig_to_z=args.regspace == "fsaverage") # Take screenshots for view in ["lat", "med", "ven"]: b.show_view(view, distance="auto") sleep(.1) panels.append(crop(b.screenshot())) b.close() # Make a single figure with all the panels f = multi_panel_brain_figure(panels) kwargs = {} if sign in ["pos", "abs"]: kwargs["pos_cmap"] = "Reds_r" if sign in ["neg", "abs"]: kwargs["neg_cmap"] = "Blues" add_colorbars(f, z_thresh, z_max, **kwargs) # Save the figure in both hemisphere outputs for hemi in ["lh", "rh"]: png_file = png_temp.format(hemi=hemi, contrast=contrast, subj=subj) f.savefig(png_file, bbox_inches="tight") plt.close(f)
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 test_label(): """Test plotting of label.""" mlab.options.backend = 'test' subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) brain.add_label("BA1") brain.add_label("BA1", color="blue", scalar_thresh=.5) label_file = pjoin(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) brain.add_label("BA44", borders=True) brain.add_label("BA6", alpha=.7) brain.show_view("medial") brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6) brain.close()
def test_label(): """Test plotting of label.""" _set_backend() subject_id = "fsaverage" hemi = "lh" surf = "inflated" brain = Brain(subject_id, hemi, surf) view = get_view(brain) extra, subj_dir = _get_extra() brain.add_label("BA1" + extra) check_view(brain, view) brain.add_label("BA1" + extra, color="blue", scalar_thresh=.5) label_file = pjoin(subj_dir, subject_id, "label", "%s.MT%s.label" % (hemi, extra)) brain.add_label(label_file) brain.add_label("BA44" + extra, borders=True) brain.add_label("BA6" + extra, alpha=.7) brain.show_view("medial") brain.add_label("V1" + extra, color="steelblue", alpha=.6) brain.add_label("V2" + extra, color="#FF6347", alpha=.6) brain.add_label("entorhinal" + extra, color=(.2, 1, .5), alpha=.6) brain.set_surf('white') brain.show_view(dict(elevation=40, distance=430), distance=430) with pytest.raises(ValueError, match='!='): brain.show_view(dict(elevation=40, distance=430), distance=431) # remove labels brain.remove_labels('V1' + extra) assert 'V2' + extra in brain.labels_dict assert 'V1' + extra not in brain.labels_dict brain.remove_labels() assert 'V2' + extra not in brain.labels_dict brain.close()
def surface_images(out_dir, subj): """Plot the white, pial, and inflated surfaces to look for defects.""" for surf in ["white", "pial", "inflated"]: panels = [] for hemi in ["lh", "rh"]: try: b = Brain(subj, hemi, surf, curv=False, background="white") except TypeError: # PySurfer <= 0.5 b = Brain(subj, hemi, surf, curv=False, config_opts=dict(background="white")) for view in ["lat", "med", "ven"]: b.show_view(view, distance="auto") panels.append(crop(b.screenshot())) b.close() # Make and save a figure f = multi_panel_brain_figure(panels) fname = op.join(out_dir, "{}_surface.png".format(surf)) f.savefig(fname, bbox_inches="tight") plt.close(f)
def test_views(): """Test showing different views.""" mlab.options.backend = 'test' brain = Brain(*std_args) brain.show_view('lateral') brain.show_view('m') brain.show_view('rostral') brain.show_view('caudal') brain.show_view('ve') brain.show_view('frontal') brain.show_view('par') brain.show_view('dor') brain.show_view({'distance': 432}) brain.show_view({'azimuth': 135, 'elevation': 79}, roll=107) brain.close()
import os from surfer import Brain, project_volume_data import numpy as np ### script to visualize cognitive components subject_id = "fsaverage" subjects_dir = os.environ["SUBJECTS_DIR"] brain = Brain("fsaverage", "lh", "inflated", views=['lat'], background="white") overlay_file = "/Volumes/neuro/Rest/ROIs/Yeo_12.nii.gz" reg_file = os.path.join(os.environ["FREESURFER_HOME"], "average/mni152.register.dat") zstat = project_volume_data(overlay_file, "lh", reg_file) zstat = project_volume_data(overlay_file, "lh", subject_id="fsaverage", smooth_fwhm=4) brain.add_data(zstat, min=1, max=5, thresh=1, colormap="hot", colorbar=False) brain.show_view("medial") #load data to visualize #mask_file = "Cortical_CI.nii.gz" ### to visualize ROI's CI assignment #load coordinates subject_id = "fsaverage" subjects_dir = os.environ["SUBJECTS_DIR"] brain = Brain("fsaverage", "rh", "inflated", views=['lat', 'med'], background="white") #brain = Brain("fsaverage", "rh", "inflated", background="white") coords = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_coordinates') CIs = np.loadtxt('/Volumes/neuro/Rest/ROIs/Gordon_consensus_CI') colors = {1:'red', 2:'purple', 3:'green', 4:'yellow', 5:'cyan', 6:'blue', 7:'brown', 8:'pink', 9:'teal', 12:'pink'}
Among the views available are lateral, rostral, caudal, frontal etc. """ print __doc__ from surfer import Brain sub = 'fsaverage' hemi = 'lh' surf = 'inflated' 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('ve') brain.show_view('frontal') brain.show_view('par') brain.show_view('dor') ############################################################################### # More advanced parameters brain.show_view({'distance': 432}) # with great power comes great responsibility brain.show_view({'azimuth': 135, 'elevation': 79}, roll=107)
data_min = data[data.nonzero()].min() """ You can pass this array to the add_overlay method for a typical activation overlay (with thresholding, etc.) """ brain.add_overlay(cwas_file, min=data_min, max=data_max, name="%s_lh" % factor) ## get overlay and color bar tmp1 = brain.overlays["%s_lh" % factor] lut = tmp1.pos_bar.lut.table.to_array() ## update color scheme lut[:, 0:3] = cols tmp1.pos_bar.lut.table = lut ## refresh view brain.show_view("lat") brain.hide_colorbar() """ Save some images """ odir = "/home/data/Projects/CWAS/%s/viz" % study brain.save_imageset( path.join(odir, "zpics_surface_%s_lh" % onames[i][j]), ['med', 'lat', 'ros', 'caud'], 'jpg') brain.close()
def test_views(): """Test showing different views """ mlab.options.backend = 'test' brain = Brain(*std_args) brain.show_view('lateral') brain.show_view('m') brain.show_view('rostral') brain.show_view('caudal') brain.show_view('ve') brain.show_view('frontal') brain.show_view('par') brain.show_view('dor') brain.show_view({'distance': 432}) brain.show_view({'azimuth': 135, 'elevation': 79}, roll=107) brain.close()
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')
# If the label lives in the normal place in the subjects directory, # you can plot it by just using the name brain.add_label("BA1") # Some labels have an associated scalar value at each ID in the label. # For example, they may be probabilistically defined. You can threshold # what vertices show up in the label using this scalar data brain.add_label("BA1", color="blue", scalar_thresh=.5) # Or you can give a path to a label in an arbitrary location subj_dir = os.environ["SUBJECTS_DIR"] label_file = os.path.join(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) # By default the label is 'filled-in', but you can # plot just the label boundaries brain.add_label("BA44", borders=True) # You can also control the opacity of the label color brain.add_label("BA6", alpha=.7) # Finally, you can plot the label in any color you want. brain.show_view(dict(azimuth=-42, elevation=105, distance=225, focalpoint=[-30, -20, 15])) # Use any valid matplotlib color. brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
We are going to plot the contour of the subject's curvature estimate after transforming that map into the common space (this step is performed outside of PySurfer using the Freesurfer program ``mri_surf2surf``). With a perfect transformation, the contour lines should follow the light/dark gray boundary on the fsaverage surface. Large deviations may reflect problems with the underlying data that you should investigate. """ import nibabel as nib from surfer import Brain print(__doc__) brain = Brain("fsaverage", "both", "inflated") for hemi in ["lh", "rh"]: # This file was created with mri_surf2surf curv = nib.load("example_data/%s.curv.fsaverage.mgz" % hemi) # Binarize the curvature at 0 curv_bin = (curv.get_data() > 0).squeeze() # Add the data as a contour overlay, but turn off the colorbar brain.add_contour_overlay(curv_bin, min=0, max=1.5, n_contours=2, line_width=3, hemi=hemi) brain.contour_list[-1]["colorbar"].visible = False brain.show_view("dorsal")
Now we plot the focus on the inflated surface at the vertex identified in the previous step. """ brain.add_foci([coord], map_surface="white", color="mediumseagreen") """ We can also do this using a vertex index, perhaps defined as the peak activation in a surface analysis. This will be more accurate than using a volume-based focus. """ coord = 0 utils.coord_to_label(subject_id, coord, label='example_data/coord', hemi='lh', n_steps=40, map_surface="white", coord_as_vert=True) brain.add_label('example_data/coord-lh.label', color='royalblue', alpha=.8) """ Now we plot the foci on the inflated surface. We will map the foci onto the surface by finding the vertex on the "white" mesh that is closest to the coordinate of the point we want to display. """ brain.add_foci([coord], map_surface="white", coords_as_verts=True, color="mediumblue") """ Set the camera position to show the extent of the labels. """ if not brain.patch_mode: brain.show_view(dict(elevation=40, distance=0.430))
mne.write_forward_solution(shared_dir+'\\'+mri_partic+'\\2020-fwd.fif',fwd) #leadfield = fwd['sol']['data'] #print("Leadfield size : %d sensors x %d dipoles" % leadfield.shape) # SENSITIVITY/FIELD MAP #-------------------------------- eeg_map = mne.sensitivity_map(fwd, ch_type='eeg', mode='fixed') if plot_steps_source==True: clim = dict(kind='percent', lims=(0.0, 50, 95), smoothing_steps=3) # let's see single dipoles brain = eeg_map.plot(subject=mri_partic, time_label='EEG sensitivity', surface='inflated', subjects_dir=shared_dir, clim=clim, smoothing_steps=8, alpha=0.9); view = 'lat' brain.show_view(view) # FIELD MAP #--------------- # Visualizing field lines based on coregistration from mne import make_field_map #make_field_map? maps = mne.make_field_map(evoked, trans=trans, subject=mri_partic, subjects_dir=shared_dir, n_jobs=1) # explore several points in time field_map = evoked.plot_field(maps, time=.07); else:
brain = Brain(subject_id=mri_partic,subjects_dir=shared_dir,surf='orig',hemi='both', background='white', size=(800, 600)) brain.add_annotation(parc) brain = stc.plot(surface='inflated', hemi='lh', subjects_dir=shared_dir) brain.set_data_time_index(300) # 221 for S2 brain.scale_data_colormap(fmin=-1e-12, fmid=1e-12, fmax=50e-12, transparent=True) brain.show_view('lateral') vertno_max, time_max = stc.get_peak(hemi='rh') surfer_kwargs = dict( subjects_dir=shared_dir, clim=dict(kind='value', lims=[8, 12, 15]), views='lateral', initial_time=time_max, time_unit='s', size=(800, 800), smoothing_steps=5) brain = stc.plot(**surfer_kwargs)
def bnsurf(data=None, val=None, cmap=None, min_val=None, max_val=None, mid_val=None, tail='greater', out=None): subjects_dir = '/Users/ACH/Documents/freesurfer/subjects' subject_id = 'fsaverage' hemi = 'lh' surf = 'inflated' brain = Brain(subject_id, hemi, surf, size=(1200, 1200), background='w', subjects_dir=subjects_dir, interaction='terrain', cortex='low_contrast', units='mm', title=out) aparc_file = os.path.join(subjects_dir, subject_id, "label", hemi + 'BN_pfc.annot') # hemi + ".BN_Atlas.annot") labels, ctab, names = nib.freesurfer.read_annot(aparc_file) # [187,179,183,177,41,47,49,13,11,1,9] # pfc_names = [b'Unknown',b'A32sg_L',b'A32p_L',b'A24cd_L',b'A24rv_L',b'A14m_L',b'A11m_L',b'A13_L',b'A10m_L',b'A9m_L',b'A8m_L',b'A6m_L'] # roi_data = rs.uniform(.5, .8, size=len(names)) rois = { 'A32sg': { 'name': b'A32sg_L', 'label': 187 }, 'A32p': { 'name': b'A32p_L', 'label': 179 }, 'A24cd': { 'name': b'A24cd_L', 'label': 183 }, 'A24rv': { 'name': b'A24rv_L', 'label': 177 }, 'A14m': { 'name': b'A14m_L', 'label': 41 }, 'A11m': { 'name': b'A11m_L', 'label': 47 }, 'A13': { 'name': b'A13_L', 'label': 49 }, 'A10m': { 'name': b'A10m_L', 'label': 13 }, 'A9m': { 'name': b'A9m_L', 'label': 11 }, 'A8m': { 'name': b'A8m_L', 'label': 1 }, 'A6m': { 'name': b'A6m_L', 'label': 9 } } #initialize the data with -1 so ROIs we don't care about are transparent if tail == 'greater': roi_data = np.repeat([-1.], len(names)) elif tail == 'less': roi_data = np.ones(len(names)) elif tail == 'two': roi_data = np.zeros(len(names)) #this is where we apply the value we want for roi in rois: roi_data[rois[roi]['label']] = data.loc[roi, val] #this maps the roi values onto the vertex data using repeated sampling vtx_data = roi_data[labels] #again cancelling out ROIs we don't care about if tail == 'greater': vtx_data[labels == -1] = -1 if tail == 'less': vtx_data[labels == -1] = -100 #this is where we actually put it on the brain if tail == 'greater': #get min/max values if not specified if min_val is None: min_val = data[val].astype(float).drop_duplicates().nsmallest(2)[1] if max_val is None: max_val = data[val].max() brain.add_data(vtx_data, min=min_val, max=max_val, mid=mid_val, colormap=cmap, thresh=0.00001, alpha=1) elif tail == 'less': brain.add_data(vtx_data, data[val].min(), 0, colormap=cmap, thresh=data[val].min(), alpha=1) elif tail == 'two': brain.add_data( vtx_data, data[val].min(), data[val].max(), center=0, colormap=cmap, ) # brain.show_view('m') brain.show_view({'azimuth': 40, 'elevation': 100}) if out is not None: brain.save_image('brainnetome_maps/%s.png' % (out), antialiased=True)
======================= """ print __doc__ from surfer import Brain sub = 'fsaverage' hemi = 'lh' surf = 'inflated' 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')
""" =================== 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')
config_opts=dict(background="white"), subjects_dir="/home2/data/PublicProgram/freesurfer") """Get the volume => surface file""" cwas_file = path.join(mdmr_dir, "surf_lh_fdr_logp_%s.nii.gz" % factor) """ You can pass this array to the add_overlay method for a typical activation overlay (with thresholding, etc.) """ brain.add_overlay(cwas_file, min=2, max=max_zvals[i], name="%s_lh" % factor) ## get overlay and color bar tmp1 = brain.overlays["%s_lh" % factor] lut = tmp1.pos_bar.lut.table.to_array() ## update color scheme lut[:,0:3] = cols tmp1.pos_bar.lut.table = lut ## refresh view brain.show_view("lat") brain.hide_colorbar() """Save Pictures""" brain.save_imageset(path.join(odir, "zpics_%s_%s_surface_lh" % (sample, factor)), ['med', 'lat', 'ros', 'caud'], 'jpg') brain.close()
#%% save figures if make_figures is not None: if len(make_figures) == 0: times = src_df.index.levels[1] else: times = make_figures outfiles = [] for time in times: brain.set_time(time) files = {} for hemi, view in views.iteritems(): brain.show_view(*view) file = os.path.join(figdir, 'motor_vertices_%s_%s_%s_%d%s.png' % (r_name, measure, hemi, time, datatype)) files[hemi] = file brain.save_image(file, antialiased=True) # stitch them together outfiles.append(os.path.join(figdir, 'motor_vertices_%s_%s_%d%s.png' % (r_name, measure, time, datatype))) os.system("montage -tile 2x1 -geometry +0+0 %s %s" % ( ' '.join([files['lh'], files['rh']]), outfiles[-1])) if len(times) > 1: import shutil for ind, file in enumerate(outfiles): shutil.copyfile(file, 'tmp_%d.png' % (ind+1))
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()
brain.add_label("BA1") # Some labels have an associated scalar value at each ID in the label. # For example, they may be probabilistically defined. You can threshold # what vertices show up in the label using this scalar data brain.add_label("BA1", color="blue", scalar_thresh=.5) # Or you can give a path to a label in an arbitrary location subj_dir = os.environ["SUBJECTS_DIR"] label_file = os.path.join(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) # By default the label is 'filled-in', but you can # plot just the label boundaries brain.add_label("BA44", borders=True) # You can also control the opacity of the label color brain.add_label("BA6", alpha=.7) # Finally, you can plot the label in any color you want. brain.show_view( dict(azimuth=-42, elevation=105, distance=225, focalpoint=[-30, -20, 15])) # Use any valid matplotlib color. brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6) # Finally, show everything on screen mlab.show(stop=True)
def visOverlay(pathToSurface, overlay, outputPath, hemi, type='white'): brain = Brain(pathToSurface, hemi, type) brain.add_overlay(overlay, -1, 1) brain.show_view('lateral') brain.save_imageset(outputPath, ['med', 'lat'], 'png') brain.close()
""" Now we plot the focus on the inflated surface at the vertex identified in the previous step. """ brain.add_foci([coord], map_surface="white", color="mediumseagreen") """ We can also do this using a vertex index, perhaps defined as the peak activation in a surface analysis. This will be more accurate than using a volume-based focus. """ coord = 0 utils.coord_to_label(subject_id, coord, label='example_data/coord', hemi='lh', n_steps=40, map_surface="white", coord_as_vert=True) brain.add_label('example_data/coord-lh.label', color='royalblue', alpha=.8) """ Now we plot the foci on the inflated surface. We will map the foci onto the surface by finding the vertex on the "white" mesh that is closest to the coordinate of the point we want to display. """ brain.add_foci([coord], map_surface="white", coords_as_verts=True, color="mediumblue") """ Set the camera position to show the extent of the labels. """ brain.show_view(dict(elevation=40, distance=0.430))
Freesurfer's curvature-driven normalization to a common template. We are going to plot the contour of the subject's curvature estimate after transforming that map into the common space (this step is performed outside of PySurfer using the Freesurfer program ``mri_surf2surf``). With a perfect transformation, the contour lines should follow the light/dark gray boundary on the fsaverage surface. Large deviations may reflect problems with the underlying data that you should investigate. """ import nibabel as nib from surfer import Brain brain = Brain("fsaverage", "both", "inflated") for hemi in ["lh", "rh"]: # This file was created with mri_surf2surf curv = nib.load("example_data/%s.curv.fsaverage.mgz" % hemi) # Binarize the curvature at 0 curv_bin = (curv.get_data() > 0).squeeze() # Add the data as a contour overlay, but turn off the colorbar brain.add_contour_overlay(curv_bin, min=0, max=1.5, n_contours=2, line_width=3, hemi=hemi) brain.contour_list[-1]["colorbar"].visible = False brain.show_view("dorsal")
============================== Among the views available are lateral, rostral, caudal, frontal etc. """ print __doc__ from surfer import Brain sub = 'fsaverage' hemi = 'lh' surf = 'inflated' 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('ve') brain.show_view('frontal') brain.show_view('par') brain.show_view('dor') ############################################################################### # More advanced parameters brain.show_view({'distance': 432}) # with great power comes great responsibility brain.show_view({'azimuth': 135, 'elevation': 79}, roll=107)
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")
surf = "smoothwm" brain = Brain(subject_id, hemi, surf) # If the label lives in the normal place in the subjects directory, # you can plot it by just using the name brain.add_label("BA1") # Or you can give a path to a label in an arbitrary location subj_dir = os.environ["SUBJECTS_DIR"] label_file = os.path.join(subj_dir, subject_id, "label", "%s.MT.label" % hemi) brain.add_label(label_file) # By default the label is 'filled-in', but you can # plot just the label boundaries brain.add_label("BA44", borders=True) # You can also control the opacity of the label color brain.add_label("BA6", alpha=.7) # Finally, you can plot the label in any color you want. brain.show_view("medial") # Use any valid matplotlib color. brain.add_label("V1", color="steelblue", alpha=.6) brain.add_label("V2", color="#FF6347", alpha=.6) brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
import source_visualisations as sv from surfer import Brain import mne figdir = os.path.expanduser('~/ZIH/texts/BeeMEG/figures') hemi = 'rh' parc = 'HCPMMP1_5_8' views = {'rh': ({'azimuth': -146.2, 'elevation': 76.8, 'focalpoint': (-4.3, -5.0, 0.0)}, 64.7, 300.), 'lh': ({'azimuth': 168.8, 'elevation': 60.3, 'focalpoint': (-0.60, 0., 0.)}, 90, 295.)} brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast', subjects_dir=sv.subjects_dir, background='w', foreground='k') labels = mne.read_labels_from_annot('fsaverage', parc=parc, hemi=hemi) pcc = sv.Glasser_areas[sv.Glasser_areas['main section'] == 18]['area name'] pcc = list(pcc.map(lambda s: hemi[0].upper() + '_' + s + '_ROI-' + hemi)) for label in labels: if label.name in pcc: brain.add_label(label, borders=1, hemi=hemi, alpha=0.6, color='k') brain.show_view(*views[hemi]) brain.save_image(os.path.join(figdir, 'pcc_map.png'), antialiased=True)