本文整理汇总了Python中nipy.labs.viz.plot_map函数的典型用法代码示例。如果您正苦于以下问题:Python plot_map函数的具体用法?Python plot_map怎么用?Python plot_map使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了plot_map函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: show_slices
def show_slices(img, coords=None, threshold=0.1, cmap=None, prefix=None,
show_colorbar=None, formatter='%.2f'):
if cmap is None:
cmap = pylab.cm.hot
data, aff = img.get_data(), img.get_affine()
anatimg = load('/usr/share/fsl/data/standard/MNI152_T1_1mm_brain.nii.gz')
anatdata, anataff = anatimg.get_data(), anatimg.get_affine()
anatdata = anatdata.astype(np.float)
anatdata[anatdata<10.] = np.nan
outfile = 'cluster.svg'
if prefix:
outfile = '_'.join((prefix, outfile))
outfile = os.path.join('figures', outfile)
if coords is None:
osl = viz.plot_map(np.asarray(data), aff, threshold=threshold,
cmap=cmap, black_bg=False)
osl.frame_axes.figure.savefig(outfile, transparent=True)
else:
for idx,coord in enumerate(coords):
outfile = 'cluster%02d' % idx
if prefix:
outfile = '_'.join((prefix, outfile))
outfile = os.path.join('figures', outfile)
osl = viz.plot_map(np.asarray(data), aff, anat=anatdata, anat_affine=anataff,
threshold=threshold, cmap=cmap,
black_bg=False, cut_coords=coord)
if show_colorbar:
cb = colorbar(gca().get_images()[1], cax=axes([0.4, 0.075, 0.2, 0.025]),
orientation='horizontal', format=formatter)
cb.set_ticks([cb._values.min(), cb._values.max()])
show()
osl.frame_axes.figure.savefig(outfile+'.svg', bbox_inches='tight', transparent=True)
osl.frame_axes.figure.savefig(outfile+'.png', dpi=600, bbox_inches='tight', transparent=True)
示例2: plot_map
def plot_map(self, niimg, title):
data = niimg.get_data().squeeze()
params = self.plot_map_params.copy()
fig = pl.figure(facecolor='k', edgecolor='k')
if 'percentile' in self.plot_map_params:
threshold = scoreatpercentile(
data.ravel(), self.plot_map_params['percentile'])
params.pop('percentile')
params['threshold'] = threshold
# vmax = np.abs(data).max()
vmax = np.percentile(np.abs(data), 99)
plot_map(data,
affine=niimg.get_affine(),
vmin=-vmax,
vmax=vmax,
title=title,
figure=fig,
**params)
fname = title.replace(' ', '_').replace('/', '_')
pl.savefig(os.path.join(
self.report_dir, '%s.png' % fname), **self.save_params)
path = os.path.join(self.report_dir, '%s.nii.gz' % fname)
nb.save(niimg, path)
pl.close('all')
return path
示例3: save_image
def save_image(nifti, anat, cluster_dict, out_path, f, image_threshold=2,
texcol=1, bgcol=0, iscale=2, text=None, **kwargs):
'''Saves a single nifti image.
Args:
nifti (str or nipy.core.api.image.image.Image): nifti file to visualize.
anat (nipy.core.api.image.image.Image): anatomical nifti file.
cluster_dict (dict): dictionary of clusters.
f (int): index.
image_threshold (float): treshold for `plot_map`.
texcol (float): text color.
bgcol (float): background color.
iscale (float): image scale.
text (Optional[str]): text for figure.
**kwargs: extra keyword arguments
'''
if isinstance(nifti, str):
nifti = load_image(nifti)
feature = nifti.get_data()
elif isinstance(nifti, nipy.core.image.image.Image):
feature = nifti.get_data()
font = {'size': 8}
rc('font', **font)
coords = cluster_dict['top_clust']['coords']
if coords == None:
return
feature /= feature.std()
imax = np.max(np.absolute(feature))
imin = -imax
imshow_args = dict(
vmax=imax,
vmin=imin,
alpha=0.7
)
coords = ([-coords[0], -coords[1], coords[2]])
plt.axis('off')
plt.text(0.05, 0.8, text, horizontalalignment='center',
color=(texcol, texcol, texcol))
try:
plot_map(feature,
xyz_affine(nifti),
anat=anat.get_data(),
anat_affine=xyz_affine(anat),
threshold=image_threshold,
cut_coords=coords,
annotate=False,
cmap=cmap,
draw_cross=False,
**imshow_args)
except Exception as e:
return
plt.savefig(out_path, transparent=True, facecolor=(bgcol, bgcol, bgcol))
示例4: show
def show(self, label=None, rcmap=None, **options):
self.P = np.array(self.P)
if label is None:
return viz.plot_map(self.P, self.affine, **options)
else:
color = rcmap or "black"
slicer = viz.plot_map(self.P == label, self.affine, **options)
slicer.contour_map(self.mask, self.affine, levels=[0], colors=(color,))
return slicer
示例5: save_image
def save_image(nifti, anat, cluster_dict, out_path, f, image_threshold=2,
texcol=1, bgcol=0, iscale=2, text=None, **kwargs):
'''
Saves a single nifti image.
'''
if isinstance(nifti, str):
nifti = load_image(nifti)
feature = nifti.get_data()
elif isinstance(nifti, nipy.core.image.image.Image):
feature = nifti.get_data()
font = {'size': 8}
rc('font', **font)
coords = cluster_dict['top_clust']['coords']
if coords == None:
return
feature /= feature.std()
imax = np.max(np.absolute(feature))
imin = -imax
imshow_args = dict(
vmax=imax,
vmin=imin,
alpha=0.7
)
coords = ([-coords[0], -coords[1], coords[2]])
plt.axis('off')
plt.text(0.05, 0.8, text, horizontalalignment='center',
color=(texcol, texcol, texcol))
try:
plot_map(feature,
xyz_affine(nifti),
anat=anat.get_data(),
anat_affine=xyz_affine(anat),
threshold=image_threshold,
cut_coords=coords,
annotate=False,
cmap=cmap,
draw_cross=False,
**imshow_args)
except Exception as e:
return
plt.savefig(out_path, transparent=True, facecolor=(bgcol, bgcol, bgcol))
示例6: save_image
def save_image(nifti, anat, cluster_dict, out_path, f, image_threshold=2,
texcol=1, bgcol=0, iscale=2, text=None, **kwargs):
if isinstance(nifti, str):
nifti = load_image(nifti)
feature = nifti.get_data()
elif isinstance(nifti, nipy.core.image.image.Image):
feature = nifti.get_data()
font = {"size":8}
rc("font", **font)
coords = cluster_dict["top_clust"]["coords"]
if coords == None:
logger.warning("No cluster found for %s" % nifti_file)
return
feature /= feature.std()
imax = np.max(np.absolute(feature))
imin = -imax
imshow_args = dict(
vmax=imax,
vmin=imin,
alpha=0.7
)
coords = ([-coords[0], -coords[1], coords[2]])
#ax = fig.add_subplot(1, 1, 1)
plt.axis("off")
plt.text(0.05, 0.8, text, horizontalalignment="center",
color=(texcol, texcol, texcol))
try:
plot_map(feature,
xyz_affine(nifti),
anat=anat.get_data(),
anat_affine=xyz_affine(anat),
threshold=image_threshold,
cut_coords=coords,
annotate=False,
cmap=cmap,
draw_cross=False,
**imshow_args)
except Exception as e:
logger.exception(e)
return
plt.savefig(out_path, transparent=True, facecolor=(bgcol, bgcol, bgcol))
示例7: brainplot
def brainplot(brainmat, savepath):
"""
takes a matrix (e.g. from loading an image file) and plots the activation
the figure is saved at 'savepath'
"""
# savepath should end in .png
plt.figure()
osl = viz.plot_map(np.asarray(brainmat), imgaff, anat=anat_data, anat_affine=anat_aff,
threshold=0.0001, black_bg=True, draw_cross=False)
pylab.savefig(savepath)
示例8: plot_brain
def plot_brain(x, affine, template, template_affine, imgfile):
new_brain = x
img = nb.Nifti1Image(new_brain, affine)
nb.save(img, imgfile+".nii.gz")
#title = imgfile.split("/")[-1]
#slicer = plot_map(new_brain, affine, anat=template, anat_affine=template_affine, cmap = plt.cm.jet, title=title)
slicer = plot_map(new_brain, affine, anat=template, anat_affine=template_affine, cmap=cm.cold_hot, black_bg=True)#.cm.jet
slicer.contour_map(template, template_affine, cmap=plt.cm.binary, black_bg=True)# plt.cm.Greys
#plt.show()
#plt.savefig(imgfile+'.png', format='png')
plt.savefig(imgfile+'.pdf', format='pdf', facecolot='k', edgecolor='k')
示例9: plot_bg
def plot_bg(cut_coords=None, title=None):
anat, anat_affine, anat_max = anat_cache._AnatCache.get_anat()
figure = pl.figure(figsize=(8, 2.6), facecolor='w', edgecolor='w')
ax = pl.axes([.0, .0, .85, 1], axisbg='w')
slicer = plot_map(anat,
anat_affine,
cmap=pl.cm.gray,
vmin=.1 * anat_max,
vmax=.8 * anat_max,
figure=figure,
cut_coords=cut_coords,
axes=ax, )
slicer.annotate()
slicer.draw_cross()
if title:
slicer.title(title, x=.05, y=.9)
return slicer
示例10: show_slices
def show_slices(image_in, anat_file, coordinates,thr):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import pylab as pl
import numpy as np
from nibabel import load
import os
from nipy.labs import viz
anat = anat_file
img = image_in
coords = coordinates[0]
threshold=thr
cmap=pl.cm.jet
prefix=None,
show_colorbar=True
formatter='%.2f'
img1 = load(img)
data, aff = img1.get_data(), img1.get_affine()
anatimg = load(anat) #load('/usr/share/fsl/data/standard/MNI152_T1_1mm_brain.nii.gz')
anatdata, anataff = anatimg.get_data(), anatimg.get_affine()
anatdata = anatdata.astype(np.float)
anatdata[anatdata<10.] = np.nan
outfile1 = os.path.split(img)[1][0:-7]
outfiles = []
for idx,coord in enumerate(coords):
outfile = outfile1+'cluster%02d' % idx
osl = viz.plot_map(np.asarray(data), aff, anat=anatdata, anat_affine=anataff,
threshold=threshold, cmap=cmap,
black_bg=False, cut_coords=coord)
if show_colorbar:
cb = plt.colorbar(plt.gca().get_images()[1], cax=plt.axes([0.4, 0.075, 0.2, 0.025]),
orientation='horizontal', format=formatter)
cb.set_ticks([cb._values.min(), cb._values.max()])
#osl.frame_axes.figure.savefig(outfile+'.svg', bbox_inches='tight', transparent=True)
osl.frame_axes.figure.savefig(os.path.join(os.getcwd(),outfile+'.png'), dpi=600, bbox_inches='tight', transparent=True)
#pl.savefig(os.path.join(os.getcwd(),outfile+'.png'), dpi=600, bbox_inches='tight', transparent=True)
outfiles.append(os.path.join(os.getcwd(),outfile+'.png'))
return outfiles
示例11: overlay_new
def overlay_new(stat_image,background_image,threshold):
import os.path
import pylab as pl
from nibabel import load
from nipy.labs import viz
from pylab import colorbar, gca, axes
import numpy as np
# Second example, with a given anatomical image slicing in the Z
# direction
fnames = [os.path.abspath('z_view.png'),
os.path.abspath('x_view.png'),
os.path.abspath('y_view.png')]
formatter='%.2f'
img = load(stat_image)
data, affine = img.get_data(), img.get_affine()
anat_img = load(background_image)
anat = anat_img.get_data()
anat_affine = anat_img.get_affine()
anat = np.ones(anat.shape) - anat
viz.plot_map(data, affine, anat=anat, anat_affine=anat_affine,
slicer='z', threshold=threshold, cmap=viz.cm._cm.hot)
cb = colorbar(gca().get_images()[1], cax=axes([0.3, 0.00, 0.4, 0.07]),
orientation='horizontal', format=formatter)
cb.set_ticks([cb._values.min(), cb._values.max()])
pl.savefig(fnames[0],bbox_inches='tight')
viz.plot_map(data, affine, anat=anat, anat_affine=anat_affine,
slicer='x', threshold=threshold, cmap=viz.cm._cm.hot)
cb = colorbar(gca().get_images()[1], cax=axes([0.3, -0.06, 0.4, 0.07]),
orientation='horizontal', format=formatter)
cb.set_ticks([cb._values.min(), cb._values.max()])
pl.savefig(fnames[1],bbox_inches='tight')
viz.plot_map(data, affine, anat=anat, anat_affine=anat_affine,
slicer='y', threshold=threshold, cmap=viz.cm._cm.hot)
cb = colorbar(gca().get_images()[1], cax=axes([0.3, -0.08, 0.4, 0.07]),
orientation='horizontal', format=formatter)
cb.set_ticks([cb._values.min(), cb._values.max()])
pl.savefig(fnames[2],bbox_inches='tight')
pl.close()
return fnames
示例12: montage
def montage(nifti, anat, roi_dict, thr=2,
fig=None, out_file=None,
order=None, stats=dict()):
'''
Saves a montage of nifti images.
'''
if isinstance(anat, str):
anat = load_image(anat)
assert nifti is not None
assert anat is not None
assert roi_dict is not None
texcol = 0
bgcol = 1
iscale = 2
if isinstance(nifti, list):
weights = np.array([n.get_data() for n in nifti]).astype('float32')
weights = weights.transpose(1, 2, 3, 0)
nifti = nifti[0]
else:
weights = nifti.get_data(); #weights = weights / weights.std(axis=3)
features = weights.shape[-1]
indices = [0]
y = 8
x = int(ceil(1.0 * features / y))
font = {'size': 8}
rc('font',**font)
if fig is None:
fig = plt.figure(figsize=[iscale * y, (1.5 * iscale) * x / 2.5])
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.05, top=0.99, wspace=0.05, hspace=0.5)
if order is None:
order = range(features)
for i, f in enumerate(order):
roi = roi_dict.get(f, None)
if roi is None:
continue
if 'top_clust' in roi.keys():
coords = roi['top_clust']['coords']
else:
coords = (0., 0., 0.)
assert coords is not None
feat = weights[:, :, :, f]
feat = feat / feat.std()
imax = np.max(np.absolute(feat)); imin = -imax
imshow_args = {'vmax': imax, 'vmin': imin}
coords = ([-coords[0], -coords[1], coords[2]])
ax = fig.add_subplot(x, y, i + 1)
#plt.axis('off')
try:
plot_map(feat,
xyz_affine(nifti),
anat=anat.get_data(),
anat_affine=xyz_affine(anat),
threshold=thr,
figure=fig,
axes=ax,
cut_coords=coords,
annotate=False,
cmap=cmap,
draw_cross=False,
**imshow_args)
except Exception as e:
print e
pass
plt.text(0.05, 0.8, str(f),
transform=ax.transAxes,
horizontalalignment='center',
color=(texcol, texcol, texcol))
for j, r in enumerate(roi['top_clust']['rois']):
plt.text(0.05, -0.15 * (.5 + j), r[:35],
transform=ax.transAxes,
horizontalalignment='left',
color=(0, 0, 0))
pos = [(0.05, 0.05), (0.4, 0.05), (0.8, 0.05)]
colors = ['purple', 'blue', 'green']
for i, (k, vs) in enumerate(stats.iteritems()):
v = vs[f]
plt.text(pos[i][0], pos[i][1], '%s=%.2f' % (k, v),
transform=ax.transAxes,
horizontalalignment='left',
color=colors[i])
if out_file is not None:
plt.savefig(out_file, transparent=True, facecolor=(bgcol, bgcol, bgcol))
else:
plt.draw()
示例13: get_second_level_dataset
from nipy.labs import viz
from nipy.utils import example_data
# Local import
from get_data_light import get_second_level_dataset
# get the data
data_dir = get_second_level_dataset()
# First example, with a anatomical template
img = load(os.path.join(data_dir, 'spmT_0029.nii.gz'))
data = img.get_data()
affine = img.get_affine()
viz.plot_map(data, affine, cut_coords=(-52, 10, 22),
threshold=2.0, cmap=viz.cm.cold_hot)
plt.savefig('ortho_view.png')
# Second example, with a given anatomical image slicing in the Z direction
try:
anat_img = load(example_data.get_filename('neurospin', 'sulcal2000',
'nobias_anubis.nii.gz'))
anat = anat_img.get_data()
anat_affine = anat_img.get_affine()
except OSError as e:
# File does not exist: the data package is not installed
print(e)
anat = None
anat_affine = None
viz.plot_map(data, affine, anat=anat, anat_affine=anat_affine,
示例14: FMRILinearModel
########################################
# Perform a GLM analysis on H1
########################################
fmri_glm = FMRILinearModel(fmri_data,
design_matrix.matrix, mask='compute')
fmri_glm.fit(do_scaling=True, model='ar1')
# Estimate the contrast
z_map, = fmri_glm.contrast(reading_vs_visual, output_z=True)
# Plot the contrast
vmax = max(-z_map.get_data().min(), z_map.get_data().max())
plot_map(z_map.get_data(), z_map.get_affine(),
cmap=cm.cold_hot, vmin=-vmax, vmax=vmax,
slicer='z', black_bg=True, threshold=2.5,
title='Reading vs visual')
# Count all the clusters for |Z| > 2.5
Z = z_map.get_data()
from scipy import ndimage
cluster_map, n_clusters = ndimage.label(np.abs(Z) > 2.5)
cluster_sizes = np.bincount(cluster_map.ravel())[1:]
print "Cluster sizes:"
print np.sort(cluster_sizes)
mask = fmri_glm.mask
########################################
# Perform GLM analysis on H0 (permuted)
示例15: print
# GLM fitting
print('Starting fit...')
glms = []
for x, y in zip(X, Y):
glm = GeneralLinearModel(x)
data, mean = data_scaling(y.get_data()[mask_array].T)
glm.fit(data, 'ar1')
glms.append(glm)
# Compute the required contrast
print('Computing test contrast image...')
nregressors = X[0].shape[1]
## should check that all design matrices have the same
c = np.zeros(nregressors)
c[0:4] = cvect
z_vals = (glms[0].contrast(c) + glms[1].contrast(c)).z_score()
# Show Zmap image
z_map = mask_array.astype(np.float)
z_map[mask_array] = z_vals
mean_map = mask_array.astype(np.float)
mean_map[mask_array] = mean
plot_map(z_map,
affine,
anat=mean_map,
anat_affine=affine,
cmap=cm.cold_hot,
threshold=2.5,
black_bg=True)
plt.show()