def plot_epi_T1_corregistration(mean_epi_file, anat_edge, figsize=(11.7, 8.3)): fig = plt.figure(figsize=figsize) func = nb.load(mean_epi_file).get_data() func_affine = nb.load(mean_epi_file).get_affine() anat = nb.load(anat_edge).get_data() anat_affine = nb.load(anat_edge).get_affine() slicer = viz.plot_anat( np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable cut_coords=(-6, 3, 28), figure=fig, draw_cross=False) slicer.contour_map(np.asarray(anat), np.asarray(anat_affine), levels=[.51], colors=[ 'r', ]) return fig
def warp_report(in_file): """Plot the registration summary using nipy contours""" mni_file = op.join(os.environ["FSL_DIR"], "data/standard/MNI152_T1_1mm_brain.nii.gz") mni_img = nib.load(mni_file) mni_data, mni_aff = mni_img.get_data(), mni_img.get_affine() sub_img = nib.load(in_file) sub_data, sub_aff = sub_img.get_data(), sub_img.get_affine() sub_data[sub_data < 1] = 0 kwargs = dict(draw_cross=False, annotate=False) cut_coords = dict(x=(-45, -12, 12, 45), y=(-55, -25, 5, 45), z=(-30, -5, 20, 40)) colors = sns.color_palette("bright") im_data = dict() for axis in ["x", "y", "z"]: f = plt.figure(figsize=(10, 2.5)) coords = cut_coords[axis] slicer = viz.plot_anat(sub_data, sub_aff, slicer=axis, cut_coords=coords, figure=f, **kwargs) slicer.contour_map(mni_data, mni_aff, colors=colors) fname = "slices_%s.png" % axis f.savefig(fname, facecolor="k", edgecolor="k") im_data[axis] = mplimg.imread(fname) concat_data = [im_data[axis] for axis in ["x", "y", "z"]] concat_data = np.concatenate(concat_data, axis=0) mplimg.imsave("warp_report.png", concat_data) return op.abspath("warp_report.png")
def contour_image(contour, mean, mask, title=''): import nibabel as nib import numpy as np import nipy.labs.viz as viz import os import matplotlib.pyplot as plt def get_data(imfile): img = nib.load(imfile) data, affine = img.get_data(), img.get_affine() return data, affine bold_data, nat_aff = get_data(mean) wm_data, _ = get_data(contour) brain_mask, _ = get_data(mask) f = plt.figure(figsize=(12, 6)) kwargs = dict(figure=f, draw_cross=False, annotate=False, slicer="y") for cut_coords, ax_pos in zip( np.linspace(-50, 70, 8).reshape(2, 4), [(0, 0, 1, .5), (0, .5, 1, .5)]): slicer = viz.plot_anat(bold_data, nat_aff, cut_coords=cut_coords, axes=ax_pos, **kwargs) slicer.contour_map(wm_data, nat_aff, colors="palegreen") slicer.contour_map(brain_mask, nat_aff, colors="tomato") plt.gca().set_title("%s" % title, size=14) outfile = os.path.abspath('%s_contour.png' % title) plt.savefig(outfile) return outfile
def plot_T1_brainmask(T1, brainmask, figsize=(11.7, 8.3)): fig = plt.figure(figsize=figsize) ax = plt.subplot(1, 1, 1) T1_data = nb.load(T1).get_data() T1_affine = nb.load(T1).get_affine() brain_nii = nb.load(brainmask) brain_data = brain_nii.get_data() #brain_data[wm_data > 1] = 1 brain_affine = brain_nii.get_affine() slicer = viz.plot_anat( np.asarray(T1_data), np.asarray(T1_affine), black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable figure=fig, axes=ax, draw_cross=False) slicer.contour_map(np.asarray(brain_data), np.asarray(brain_affine), linewidths=[0.1], colors=[ 'r', ]) fig.suptitle('FS brain extraction', fontsize='14') return fig plt.show(fig)
def plot_hipp_subfields(brain_file, subfield_file, figsize=(40.7, 20.3)): fig = plt.figure(figsize=figsize) ax = plt.subplot(1, 1, 1) print "hello" brain = nb.load(brain_file).get_data() brain_affine = nb.load(brain_file).get_affine() subfield = nb.load(subfield_file).get_data() subfield_affine = nb.load(subfield_file).get_affine() plt.histogram(subfield[:]) # #plt.imshow(subfield[:,:,175], cmap="gray", origin="lower") #plt.show() subfield[subfield > 1] = 1 slicer = viz.plot_anat( np.asarray(brain), np.asarray(brain_affine), cut_coords=np.arange(-238, -220, 2), #None, #[0,50,100,150,200,250], slicer='z', black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable figure=fig, axes=ax, draw_cross=False) slicer.edge_map(np.asarray(subfield), np.asarray(subfield_affine), color='r') # # fig.suptitle('subfields', fontsize='14') plt.show() return fig
def plot_epi_T1_corregistration(mean_epi_file, wm_file, subject_id, similarity_distribution=None, figsize=(11.7,8.3),): fig = plt.figure(figsize=figsize) if similarity_distribution: ax = plt.subplot(2,1,1) sns.distplot(similarity_distribution.values(), ax=ax) ax.set_xlabel("EPI-T1 mincost function (over all subjects)") cur_similarity = similarity_distribution[subject_id] label = "mincost function = %g"%cur_similarity plot_vline(cur_similarity, label, ax=ax) ax = plt.subplot(2,1,2) else: ax = plt.subplot(1,1,0) func = nb.load(mean_epi_file).get_data() func_affine = nb.load(mean_epi_file).get_affine() wm_data = nb.load(wm_file).get_data() wm_affine = nb.load(wm_file).get_affine() slicer = viz.plot_anat(np.asarray(func), np.asarray(func_affine), black_bg=True, cmap = cm.Greys_r, # @UndefinedVariable figure = fig, axes = ax, draw_cross = False) slicer.contour_map(np.asarray(wm_data), np.asarray(wm_affine), linewidths=[0.1], colors=['r',]) fig.suptitle('coregistration', fontsize='14') return fig
def plot_epi_to_t1_coregistration(epi_file, reg_file, ribbon, fssubjects_dir): import pylab as plt from nipy.labs import viz import nibabel as nb import numpy as np import os import nipype.interfaces.freesurfer as fs anat = nb.load(ribbon).get_data() anat[anat > 1] = 1 anat_affine = nb.load(ribbon).get_affine() func = nb.load(epi_file).get_data() func_affine = nb.load(epi_file).get_affine() fig = plt.figure(figsize=(8, 6), edgecolor="k", facecolor="k") slicer = viz.plot_anat( np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=plt.cm.spectral, cut_coords=(-6, 3, 12), figure=fig, axes=[0, 0.50, 1, 0.33], ) slicer.contour_map(np.asarray(anat), np.asarray(anat_affine), levels=[0.51], colors=["r"]) slicer.title( "Mean EPI with cortical surface contour overlay (before registration)", size=12, color="w", alpha=0 ) res = fs.ApplyVolTransform( source_file=epi_file, reg_file=reg_file, fs_target=True, subjects_dir=fssubjects_dir ).run() func = nb.load(res.outputs.transformed_file).get_data() func_affine = nb.load(res.outputs.transformed_file).get_affine() slicer = viz.plot_anat( np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=plt.cm.spectral, cut_coords=(-6, 3, 12), figure=fig, axes=[0, 0, 1, 0.33], ) slicer.contour_map(np.asarray(anat), np.asarray(anat_affine), levels=[0.51], colors=["r"]) slicer.title("Mean EPI with cortical surface contour overlay (after registration)", size=12, color="w", alpha=0) plt.savefig("reg_plot.png", facecolor=fig.get_facecolor(), edgecolor="none") return os.path.abspath("reg_plot.png")
def plot_epi_T1_corregistration( mean_epi_file, reg_file, fssubjects_dir, subject_id, similarity_distribution=None, figsize=(11.7, 8.3), ): fig = plt.figure(figsize=figsize) if similarity_distribution: ax = plt.subplot(2, 1, 1) sns.distplot(similarity_distribution.values(), ax=ax) ax.set_xlabel( "EPI-T1 similarity after coregistration (over all subjects)") cur_similarity = similarity_distribution[subject_id] label = "similarity = %g" % cur_similarity plot_vline(cur_similarity, label, ax=ax) ax = plt.subplot(2, 1, 0) else: ax = plt.subplot(1, 1, 0) res = ApplyVolTransform(source_file=mean_epi_file, reg_file=reg_file, fs_target=True, subjects_dir=fssubjects_dir, terminal_output="none").run() func = nb.load(res.outputs.transformed_file).get_data() func_affine = nb.load(res.outputs.transformed_file).get_affine() ribbon_file = "%s/%s/mri/ribbon.mgz" % (fssubjects_dir, subject_id) ribbon_nii = nb.load(ribbon_file) ribbon_data = ribbon_nii.get_data() ribbon_data[ribbon_data > 1] = 1 ribbon_affine = ribbon_nii.get_affine() slicer = viz.plot_anat( np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable cut_coords=(-6, 3, 32), figure=fig, axes=ax, draw_cross=False) slicer.contour_map(np.asarray(ribbon_data), np.asarray(ribbon_affine), levels=[.51], colors=[ 'r', ]) return fig
def plot_unwarping( mean_epi, mean_epi_uncorrected, figsize=(11.7, 8.3), ): fig = plt.figure(figsize=figsize) ax = plt.subplot(2, 1, 1) before_unwarp_data = nb.load(mean_epi_uncorrected).get_data() before_unwarp_affine = nb.load(mean_epi_uncorrected).get_affine() slicer = viz.plot_anat( np.asarray(before_unwarp_data), np.asarray(before_unwarp_affine), black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable cut_coords=(-8, 0, 8), slicer='x', figure=fig, axes=ax, draw_cross=False) ax = plt.subplot(2, 1, 2) unwarped_data = nb.load(mean_epi).get_data() unwarped_affine = nb.load(mean_epi).get_affine() slicer = viz.plot_anat( np.asarray(unwarped_data), np.asarray(unwarped_affine), black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable cut_coords=(-8, 0, 8), slicer='x', figure=fig, axes=ax, draw_cross=False) fig.suptitle('fieldmap correction', fontsize='14') return fig
def plot_anat(brain): import os.path import pylab as pl from nibabel import load from nipy.labs import viz import numpy as np img = load(brain) data = img.get_data() data[np.isnan(data)] = 0 affine = img.get_affine() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='x') x_view = os.path.abspath('x_view.png') y_view = os.path.abspath('y_view.png') z_view = os.path.abspath('z_view.png') pl.savefig(x_view,bbox_inches='tight') viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='y') pl.savefig(y_view,bbox_inches='tight') viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='z') pl.savefig(z_view,bbox_inches='tight') images = [x_view, y_view, z_view] pl.close() return images
def plot_ribbon(Brain): import os.path import pylab as pl from nibabel import load from nipy.labs import viz images = [] for brain in Brain: if os.path.split(brain)[1] == 'ribbon.mgz': img = load(brain) data = img.get_data()*100 affine = img.get_affine() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='x', cmap=viz.cm.black_green) x_view = os.path.abspath('x_view.png') y_view = os.path.abspath('y_view.png') z_view = os.path.abspath('z_view.png') pl.savefig(x_view,bbox_inches='tight') pl.close() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='y', cmap=viz.cm.black_green) pl.savefig(y_view,bbox_inches='tight') pl.close() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='z', cmap=viz.cm.black_green) pl.savefig(z_view,bbox_inches='tight') images = [x_view, y_view, z_view] pl.close() return images
def plot_anat(brain): import os.path import pylab as pl from nibabel import load from nipy.labs import viz import numpy as np img = load(brain) data = img.get_data() data[np.isnan(data)] = 0 affine = img.get_affine() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='x') x_view = os.path.abspath('x_view.png') y_view = os.path.abspath('y_view.png') z_view = os.path.abspath('z_view.png') pl.savefig(x_view,bbox_inches='tight') viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='y') pl.savefig(y_view,bbox_inches='tight') viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='z') pl.savefig(z_view,bbox_inches='tight') images = [x_view, y_view, z_view] pl.close() return images
def plot_ribbon(Brain): import os.path import pylab as pl from nibabel import load from nipy.labs import viz images = [] for brain in Brain: if os.path.split(brain)[1] == 'ribbon.mgz': img = load(brain) data = img.get_data()*100 affine = img.get_affine() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='x', cmap=viz.cm.black_green) x_view = os.path.abspath('x_view.png') y_view = os.path.abspath('y_view.png') z_view = os.path.abspath('z_view.png') pl.savefig(x_view,bbox_inches='tight') pl.close() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='y', cmap=viz.cm.black_green) pl.savefig(y_view,bbox_inches='tight') pl.close() viz.plot_anat(anat=data, anat_affine=affine, draw_cross=False, slicer='z', cmap=viz.cm.black_green) pl.savefig(z_view,bbox_inches='tight') images = [x_view, y_view, z_view] pl.close() return images
def plot_epi_T1_corregistration(mean_epi_file, wm_file, reg_file, fssubjects_dir, subject_id, figsize=(11.7, 8.3)): fig = plt.figure(figsize=figsize) ax = plt.subplot(1, 1, 1) print ax res = ApplyVolTransform(source_file=mean_epi_file, reg_file=reg_file, fs_target=True, subjects_dir=fssubjects_dir, terminal_output="none").run() func = nb.load(res.outputs.transformed_file).get_data() func_affine = nb.load(res.outputs.transformed_file).get_affine() # ribbon_file = "%s/%s/mri/ribbon.mgz"%(fssubjects_dir, subject_id) # ribbon_nii = nb.load(ribbon_file) # ribbon_data = ribbon_nii.get_data() # ribbon_data[ribbon_data > 1] = 1 # ribbon_affine = ribbon_nii.get_affine() wm_nii = nb.load(wm_file) wm_data = wm_nii.get_data() wm_data[wm_data > 1] = 1 wm_affine = wm_nii.get_affine() slicer = viz.plot_anat( np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable figure=fig, axes=ax, draw_cross=False) slicer.contour_map(np.asarray(wm_data), np.asarray(wm_affine), linewidths=[0.1], colors=[ 'r', ]) fig.suptitle('coregistration', fontsize='14') return fig plt.show(fig)
def plot_epi_T1_corregistration( mean_epi_file, wm_file, subject_id, similarity_distribution=None, figsize=(11.7, 8.3), ): fig = plt.figure(figsize=figsize) if similarity_distribution: ax = plt.subplot(2, 1, 1) sns.distplot(similarity_distribution.values(), ax=ax) ax.set_xlabel("EPI-T1 mincost function (over all subjects)") cur_similarity = similarity_distribution[subject_id] label = "mincost function = %g" % cur_similarity plot_vline(cur_similarity, label, ax=ax) ax = plt.subplot(2, 1, 2) else: ax = plt.subplot(1, 1, 0) func = nb.load(mean_epi_file).get_data() func_affine = nb.load(mean_epi_file).get_affine() wm_data = nb.load(wm_file).get_data() wm_affine = nb.load(wm_file).get_affine() slicer = viz.plot_anat( np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=cm.Greys_r, # @UndefinedVariable figure=fig, axes=ax, draw_cross=False) slicer.contour_map(np.asarray(wm_data), np.asarray(wm_affine), linewidths=[0.1], colors=[ 'r', ]) fig.suptitle('coregistration', fontsize='14') return fig
def plot_epi_T1_corregistration(mean_epi_file, reg_file, fssubjects_dir, subject_id, similarity_distribution=None, figsize=(11.7,8.3),): fig = plt.figure(figsize=figsize) if similarity_distribution: ax = plt.subplot(2,1,1) sns.distplot(similarity_distribution.values(), ax=ax) ax.set_xlabel("EPI-T1 similarity after coregistration (over all subjects)") cur_similarity = similarity_distribution[subject_id] label = "similarity = %g"%cur_similarity plot_vline(cur_similarity, label, ax=ax) ax = plt.subplot(2,1,0) else: ax = plt.subplot(1,1,0) res = ApplyVolTransform(source_file = mean_epi_file, reg_file = reg_file, fs_target = True, subjects_dir = fssubjects_dir, terminal_output = "none").run() func = nb.load(res.outputs.transformed_file).get_data() func_affine = nb.load(res.outputs.transformed_file).get_affine() ribbon_file = "%s/%s/mri/ribbon.mgz"%(fssubjects_dir, subject_id) ribbon_nii = nb.load(ribbon_file) ribbon_data = ribbon_nii.get_data() ribbon_data[ribbon_data > 1] = 1 ribbon_affine = ribbon_nii.get_affine() slicer = viz.plot_anat(np.asarray(func), np.asarray(func_affine), black_bg=True, cmap = cm.Greys_r, # @UndefinedVariable cut_coords = (-6,3,32), figure = fig, axes = ax, draw_cross = False) slicer.contour_map(np.asarray(ribbon_data), np.asarray(ribbon_affine), levels=[.51], colors=['r',]) return fig
def contour_image(contour,mean,mask,title=''): import nibabel as nib import numpy as np import nipy.labs.viz as viz import os import matplotlib.pyplot as plt def get_data(imfile): img = nib.load(imfile) data, affine = img.get_data(), img.get_affine() return data,affine bold_data, nat_aff = get_data(mean) wm_data, _ = get_data(contour) brain_mask, _ = get_data(mask) f = plt.figure(figsize=(12, 6)) kwargs = dict(figure=f, draw_cross=False, annotate=False, slicer="y") for cut_coords, ax_pos in zip(np.linspace(-50, 70, 8).reshape(2, 4), [(0, 0, 1, .5), (0, .5, 1, .5)]): slicer = viz.plot_anat(bold_data, nat_aff, cut_coords=cut_coords, axes=ax_pos, **kwargs) slicer.contour_map(wm_data, nat_aff, colors="palegreen") slicer.contour_map(brain_mask, nat_aff, colors="tomato") plt.gca().set_title("%s"%title, size=14) outfile = os.path.abspath('%s_contour.png'%title) plt.savefig(outfile) return outfile
def plot_epi_to_t1_coregistration(epi_file, reg_file, ribbon, fssubjects_dir): import pylab as plt from nipy.labs import viz import nibabel as nb import numpy as np import os import nipype.interfaces.freesurfer as fs anat = nb.load(ribbon).get_data() anat[anat > 1] = 1 anat_affine = nb.load(ribbon).get_affine() func = nb.load(epi_file).get_data() func_affine = nb.load(epi_file).get_affine() fig = plt.figure(figsize=(8, 6), edgecolor='k', facecolor='k') slicer = viz.plot_anat(np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=plt.cm.spectral, cut_coords=(-6, 3, 12), figure=fig, axes=[0, .50, 1, .33]) slicer.contour_map(np.asarray(anat), np.asarray(anat_affine), levels=[.51], colors=[ 'r', ]) slicer.title( "Mean EPI with cortical surface contour overlay (before registration)", size=12, color='w', alpha=0) res = fs.ApplyVolTransform(source_file=epi_file, reg_file=reg_file, fs_target=True, subjects_dir=fssubjects_dir).run() func = nb.load(res.outputs.transformed_file).get_data() func_affine = nb.load(res.outputs.transformed_file).get_affine() slicer = viz.plot_anat(np.asarray(func), np.asarray(func_affine), black_bg=True, cmap=plt.cm.spectral, cut_coords=(-6, 3, 12), figure=fig, axes=[0, 0, 1, .33]) slicer.contour_map(np.asarray(anat), np.asarray(anat_affine), levels=[.51], colors=[ 'r', ]) slicer.title( "Mean EPI with cortical surface contour overlay (after registration)", size=12, color='w', alpha=0) plt.savefig("reg_plot.png", facecolor=fig.get_facecolor(), edgecolor='none') return os.path.abspath("reg_plot.png")
cmaps_list = (cmaps['Yl'], cmaps['Gr'], cmaps['Rd'], cmaps['Ma'], cmaps['Or'], cmaps['Bl'], cmaps['Cy'], cmaps['Pu']) ############################################################################### atlas_name = atlas_file.replace('.nii.gz', '') if os.path.exists(atlas_name): shutil.rmtree(atlas_name, ignore_errors=True) os.mkdir(atlas_name) fnames = list() for axis, cut in cuts: slicer = viz.plot_anat(slicer=axis, cut_coords=(cut, ),) for level in (1, 2, 3): level_labels = np.trunc(atlas / 1000. * 10 ** (level - 1)) level_labels = level_labels.astype(np.int) for label in np.unique(level_labels): if label == 0: continue slicer.contour_map(level_labels == label, affine, levels=[.5], colors='k', linewidths=linewidths[level]) for label in range(1, 9): this_altas = atlas.copy() this_altas[atlas >= 1000 * (label + 1)] = 0 slicer.plot_map(atlas, affine, cmap=cmaps_list[label - 1], threshold=1000 * label - 2,
The idea is to represent the anatomical image to be checked with an overlay of the edges of the reference image. This idea is borrowed from FSL. Needs the *templates* data package. Needs matplotlib. """ print(__doc__) try: import matplotlib.pyplot as plt except ImportError: raise RuntimeError("This script needs the matplotlib library") from nipy.labs import viz from nipy.labs.viz_tools import anat_cache # Get the data. Here we are using the reference T1 image anat, affine, _ = anat_cache._AnatCache.get_anat() # Here we use the same image as a reference. As a result it is perfectly # aligned. reference = anat reference_affine = affine slicer = viz.plot_anat(anat, affine, dim=.2, black_bg=True) slicer.edge_map(reference, reference_affine) plt.show()
def plot_segmentation(img, gm_filename, wm_filename=None, csf_filename=None, output_filename=None, cut_coords=None, slicer='ortho', cmap=None, title='GM + WM + CSF segmentation'): """ Plot a contour mapping of the GM, WM, and CSF of a subject's anatomical. Parameters ---------- img_filename: string or image object path of file containing image data, or image object simply gm_filename: string path of file containing Grey Matter template wm_filename: string (optional) path of file containing White Matter template csf_filename: string (optional) path of file containing Cerebro-Spinal Fluid template """ # sanity if cmap is None: cmap = pl.cm.gray if cut_coords is None: cut_coords = (-10, -28, 17) if slicer in ['x', 'y', 'z']: cut_coords = (cut_coords['xyz'.index(slicer)],) # plot img if hasattr(img, '__len__'): img = compute_mean_3D_image(img) # XXX else i'm assuming a nifi object ;) anat = img.get_data() anat_affine = img.get_affine() _slicer = viz.plot_anat( anat, anat_affine, cut_coords=cut_coords, slicer=slicer, cmap=cmap, # black_bg=True, ) # draw a GM contour map gm = nibabel.load(gm_filename) gm_template = gm.get_data() gm_affine = gm.get_affine() _slicer.contour_map(gm_template, gm_affine, levels=[.51], colors=["r"]) # draw a WM contour map if not wm_filename is None: wm = nibabel.load(wm_filename) wm_template = wm.get_data() wm_affine = wm.get_affine() _slicer.contour_map(wm_template, wm_affine, levels=[.51], colors=["g"]) # draw a CSF contour map if not csf_filename is None: csf = nibabel.load(csf_filename) csf_template = csf.get_data() csf_affine = csf.get_affine() _slicer.contour_map( csf_template, csf_affine, levels=[.51], colors=['b']) # misc _slicer.title("%s (cmap: %s)" % (title, cmap.name), size=12, color='w', alpha=0) # pl.legend(("WM", "CSF", "GM"), loc="lower left", ncol=len(cut_coords)) if not output_filename is None: pl.savefig(output_filename, bbox_inches='tight', dpi=200, facecolor="k", edgecolor="k")
def plot_registration(reference_img, coregistered_img, title="untitled coregistration!", cut_coords=None, slicer='ortho', cmap=None, output_filename=None): """Plots a coregistered source as bg/contrast for the reference image Parameters ---------- reference_img: string path to reference (background) image coregistered_img: string path to other image (to be compared with reference) slicer: string (optional, defaults to 'ortho') slicer param to pass to the nipy.labs.viz.plot_??? APIs cmap: matplotlib colormap object (optional, defaults to spectral) colormap to user for plots output_filename: string (optional) path where plot will be stored """ # sanity if cmap is None: cmap = pl.cm.gray # registration QA always gray cmap! if cut_coords is None: cut_coords = (-10, -28, 17) if slicer in ['x', 'y', 'z']: cut_coords = (cut_coords['xyz'.index(slicer)],) # plot the coregistered image if hasattr(coregistered_img, '__len__'): coregistered_img = compute_mean_3D_image(coregistered_img) # XXX else i'm assuming a nifi object ;) coregistered_data = coregistered_img.get_data() coregistered_affine = coregistered_img.get_affine() _slicer = viz.plot_anat( anat=coregistered_data, anat_affine=coregistered_affine, cmap=cmap, cut_coords=cut_coords, slicer=slicer, # black_bg=True, ) # overlap the reference image if hasattr(reference_img, '__len__'): reference_img = compute_mean_3D_image(reference_img) # XXX else i'm assuming a nifi object ;) reference_data = reference_img.get_data() reference_affine = reference_img.get_affine() _slicer.edge_map(reference_data, reference_affine) # misc _slicer.title("%s (cmap: %s)" % (title, cmap.name), size=12, color='w', alpha=0) if not output_filename is None: try: pl.savefig(output_filename, dpi=200, bbox_inches='tight', facecolor="k", edgecolor="k") except AttributeError: # XXX TODO: handy this case!! pass
The idea is to represent the anatomical image to be checked with an overlay of the edges of the reference image. This idea is borrowed from FSL. Needs the *templates* data package. Needs matplotlib. """ print(__doc__) try: import matplotlib.pyplot as plt except ImportError: raise RuntimeError("This script needs the matplotlib library") from nipy.labs import viz from nipy.labs.viz_tools import anat_cache # Get the data. Here we are using the reference T1 image anat, affine, _ = anat_cache._AnatCache.get_anat() # Here we use the same image as a reference. As a result it is perfectly # aligned. reference = anat reference_affine = affine slicer = viz.plot_anat(anat, affine, dim=.2, black_bg=True) slicer.edge_map(reference, reference_affine) plt.show()