def test_offscreen(): """Test offscreen rendering.""" mlab.options.backend = 'auto' brain = Brain(*std_args, offscreen=True) # Sometimes the first screenshot is rendered with a different # resolution on OS X brain.screenshot() shot = brain.screenshot() assert_array_equal(shot.shape, (800, 800, 3)) brain.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 test_offscreen(): """Test offscreen rendering.""" if sys.platform == 'darwin' and os.getenv('TRAVIS', 'false') == 'true': raise SkipTest('Offscreen Travis tests fail on OSX') _set_backend() brain = Brain(*std_args, offscreen=True) # Sometimes the first screenshot is rendered with a different # resolution on OS X brain.screenshot() shot = brain.screenshot() assert_array_equal(shot.shape, (800, 800, 3)) brain.close()
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 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_offscreen(): """Test offscreen rendering """ mlab.options.backend = 'auto' brain = Brain(*std_args, offscreen=True) shot = brain.screenshot() assert_array_equal(shot.shape, (800, 800, 3))
def panel_mesh_axial(foci, foci_colors, color_scales): if not withsurfer: print "Cannot do 3D without PySurder. Exiting" exit() foci_colors = np.array(foci_colors) brain = Brain(subject_id, "both", "pial", cortex='ivory', alpha=0.1, background='white'); for color in np.unique(foci_colors): brain.add_foci(foci[foci_colors==color, :], hemi='rh', scale_factor=color_scales[color], color=color); brain.show_view(view=dict(azimuth=0.0, elevation=0), roll=90); pic = brain.screenshot() plt.imshow(pic); # small axis #plt.xlabel('MNI Y', size=24); #plt.xticks(np.arange(0, 800, 40), np.asarray(np.arange(-75, 106, 9.0), dtype='int'), size=18, rotation=90); #plt.ylabel('MNI X', size=24); #plt.yticks(np.arange(0, 800, 40), np.asarray(np.arange(-94.5, 93.5, 9.4), dtype='int'), size=18); # big axis plt.xlabel('MNI Y', size=24); plt.xticks(np.arange(0, 800, 50), np.asarray(np.arange(-75, 106, 11.3125), dtype='int'), size=24, rotation=90); plt.ylabel('MNI Z', size=24); plt.yticks(np.arange(0, 800, 50), np.asarray(np.arange(-94.5, 93.5, 11.75), dtype='int'), size=24); plt.xlim(0, 800); plt.ylim(800, 0);
def test_offscreen(): """Test offscreen rendering """ mlab.options.backend = 'auto' brain = Brain(*std_args, offscreen=True) shot = brain.screenshot() assert_array_equal(shot.shape, (800, 800, 3)) 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.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_offscreen(): """Test offscreen rendering.""" _set_backend() brain = Brain(*std_args, offscreen=True) shot = brain.screenshot() assert_array_less((400, 400, 2), shot.shape) assert_array_less(shot.shape, (801, 801, 4)) brain.close()
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 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 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 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 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 plot_brains(axes, palette): lat_ax, med_ax = axes lat_color, med_color = palette b = Brain("fsaverage", "lh", "pial", background="white", size=(1200, 1200)) b.add_morphometry("curv", grayscale=True, min=-.5, max=.5, colormap="Greys", colorbar=False) b.add_label("roi_labels/lh.ifs.label", alpha=.9, color="#feb308") b.add_label("roi_labels/lh.mfc.label", alpha=.9, color="#cf6275") mlab.view(160, 70) lat_ax.imshow(crop(b.screenshot()), rasterized=True) mlab.view(15, 90) med_ax.imshow(crop(b.screenshot()), rasterized=True) b.close() for ax in axes: ax.set_axis_off()
def plot_roi(hemi, labels, colors, view='parietal', fs_dir=os.environ['SUBJECTS_DIR']): import os subject_id = "fsaverage" surf = "inflated" brain = Brain(subject_id, hemi, surf, offscreen=True) for label, color in zip(labels, colors): label_file = os.path.join(fs_dir, subject_id, 'label', (label.replace('-rh', '.label') .replace('-lh', '.label') .replace('&', '_and_') .replace('_Havg', '') .replace('_Lateralized', ''))) brain.add_label(label_file, color=color) brain.show_view(view) return brain.screenshot()
def plot_roi( hemi, labels, color, annotation="HCPMMP1", view="parietal", fs_dir=os.environ["SUBJECTS_DIR"], subject_id="S04", surf="inflated", ): import matplotlib import os import glob from surfer import Brain from mne import Label color = np.array(matplotlib.colors.to_rgba(color)) brain = Brain(subject_id, hemi, surf, offscreen=False) labels = [label.replace("-rh", "").replace("-lh", "") for label in labels] # First select all label files label_names = glob.glob( os.path.join(fs_dir, subject_id, "label", "lh*.label")) label_names = [ label for label in label_names if any([l in label for l in labels]) ] for label in label_names: brain.add_label(label, color=color) # Now go for annotations from nibabel.freesurfer import io ids, colors, annot_names = io.read_annot( os.path.join(fs_dir, subject_id, "label", "lh.%s.annot" % annotation), orig_ids=True, ) for i, alabel in enumerate(annot_names): if any([label in alabel.decode("utf-8") for label in labels]): label_id = colors[i, -1] vertices = np.where(ids == label_id)[0] l = Label(np.sort(vertices), hemi="lh") brain.add_label(l, color=color) brain.show_view(view) return brain.screenshot()
def plot_brains(subjects, axes): for subj, subj_axes in zip(subjects, axes): exp = dict(pc="dots", ti="sticks")[subj[:2]] data_fname = "roi_cache/{}_{}_ifs.npz".format(subj, exp) with np.load(data_fname) as dobj: vox_ijk = dobj["vox_ijk"] res_fname = "decoding_analysis/{}_{}_ifs.pkz".format(subj, exp) res = moss.load_pkl(res_fname) prefs = res.prefs surf_vals = roi_to_surf(exp, subj, prefs, vox_ijk) lut = get_colormap(exp, False) for hemi, ax in zip(["lh", "rh"], subj_axes): b = Brain(subj, hemi, "inflated", background="white", cortex=("binary", -4, 8, False), size=(1000, 600)) b.add_data(surf_vals.ix[hemi].fillna(-11).values, colormap=lut, colorbar=False, thresh=-10, min=-1.75, max=1.75) mlab.view(*get_ifs_view(subj, hemi)) img = crop(b.screenshot()) ax.imshow(img, rasterized=True) ax.set(xticks=[], yticks=[]) b.close()
def plot_rois( labels, clusters, view="lat", fs_dir=os.environ["SUBJECTS_DIR"], subject_id="S04", surf="inflated", ): hemi = "lh" from surfer import Brain import seaborn as sns colors = sns.color_palette("husl", len(clusters)) brain = Brain(subject_id, hemi, surf, offscreen=False) for color, cluster in zip(colors, clusters): for label in labels[cluster]: if "rh" in label.name: continue # print(cluster, label) brain.add_label(label, color=color) brain.show_view(view) return brain, brain.screenshot()
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)