本文整理汇总了Python中nipy.labs.viz.plot_map函数的典型用法代码示例。如果您正苦于以下问题:Python plot_map函数的具体用法?Python plot_map怎么用?Python plot_map使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了plot_map函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:satra,项目名称:sad,代码行数:33,代码来源:sad_figures.py
示例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
开发者ID:GaelVaroquaux,项目名称:nignore,代码行数:25,代码来源:reporting.py
示例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))
开发者ID:Jeremy-E-Johnson,项目名称:cortex,代码行数:59,代码来源:nifti_viewer.py
示例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
开发者ID:BenoitDamota,项目名称:regions,代码行数:9,代码来源:roi.py
示例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))
开发者ID:edamaraju,项目名称:cortex,代码行数:47,代码来源:nifti_viewer.py
示例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))
开发者ID:ecastrow,项目名称:pl2mind,代码行数:47,代码来源:nifti_viewer.py
示例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)
开发者ID:satra,项目名称:sad,代码行数:10,代码来源:models_skl.py
示例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')
开发者ID:jdnc,项目名称:ml-project,代码行数:13,代码来源:plotting.py
示例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
开发者ID:GaelVaroquaux,项目名称:nignore,代码行数:17,代码来源:viz_utils.py
示例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
开发者ID:INCF,项目名称:BrainImagingPipelines,代码行数:41,代码来源:QA_utils.py
示例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
开发者ID:INCF,项目名称:BrainImagingPipelines,代码行数:46,代码来源:QA_utils.py
示例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()
开发者ID:edamaraju,项目名称:cortex,代码行数:99,代码来源:nifti_viewer.py
示例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,
开发者ID:Naereen,项目名称:nipy,代码行数:31,代码来源:viz.py
示例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)
开发者ID:NanoResearch,项目名称:python-cogstats,代码行数:31,代码来源:plot_permutation.py
示例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()
开发者ID:baca790,项目名称:nipy,代码行数:30,代码来源:compute_fmri_contrast.py
示例16: plot_cv_tc
def plot_cv_tc(epi_data, session_ids, subject_id,
do_plot=True,
write_image=True, mask=True, bg_image=False,
plot_diff=True,
_output_dir=None,
cv_tc_plot_outfile=None):
""" Compute coefficient of variation of the data and plot it
Parameters
----------
epi_data: list of strings, input fMRI 4D images
session_ids: list of strings of the same length as epi_data,
session indexes (for figures)
subject_id: string, id of the subject (for figures)
do_plot: bool, optional,
should we plot the resulting time course
write_image: bool, optional,
should we write the cv image
mask: bool or string, optional,
(string) path of a mask or (bool) should we mask the data
bg_image: bool or string, optional,
(string) pasth of a background image for display or (bool)
should we compute such an image as the mean across inputs.
if no, an MNI template is used (works for normalized data)
"""
if _output_dir is None:
if not cv_tc_plot_outfile is None:
_output_dir = os.path.dirname(cv_tc_plot_outfile)
else:
_output_dir = tempfile.mkdtemp()
cv_tc_ = []
if isinstance(mask, basestring):
mask_array = nibabel.load(mask).get_data() > 0
elif mask == True:
mask_array = compute_mask_files(epi_data[0])
else:
mask_array = None
for (session_id, fmri_file) in zip(session_ids, epi_data):
nim = do_3Dto4D_merge(fmri_file, output_dir=_output_dir)
affine = nim.get_affine()
if len(nim.shape) == 4:
# get the data
data = nim.get_data()
else:
raise TypeError("Expecting 4D image!")
pass
# compute the CV for the session
cache_dir = os.path.join(_output_dir, "CV")
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
mem = joblib.Memory(cachedir=cache_dir, verbose=5)
cv = mem.cache(compute_cv)(data, mask_array=mask_array)
if write_image:
# write an image
nibabel.save(nibabel.Nifti1Image(cv, affine),
os.path.join(_output_dir, 'cv_%s.nii' % session_id))
if bg_image == False:
try:
viz.plot_map(
cv, affine, threshold=.01, cmap=viz.cm.cold_hot)
except IndexError:
print traceback.format_exc()
else:
if isinstance(bg_image, basestring):
_tmp = nibabel.load(bg_image)
anat, anat_affine = (
_tmp.get_data(),
_tmp.get_affine())
else:
anat, anat_affine = data.mean(-1), affine
try:
viz.plot_map(
cv, affine, threshold=.01, cmap=viz.cm.cold_hot,
anat=anat, anat_affine=anat_affine)
except IndexError:
print traceback.format_exc()
# compute the time course of cv
cv_tc_sess = np.median(
np.sqrt((data[mask_array > 0].T /
data[mask_array > 0].mean(-1) - 1) ** 2), 1)
cv_tc_.append(cv_tc_sess)
cv_tc = np.concatenate(cv_tc_)
if do_plot:
# plot the time course of cv for different subjects
pl.figure()
pl.plot(cv_tc, label=subject_id)
pl.legend()
pl.xlabel('time(scans)')
pl.ylabel('Median coefficient of variation')
pl.axis('tight')
if not cv_tc_plot_outfile is None:
pl.savefig(cv_tc_plot_outfile,
bbox_inches="tight", dpi=200)
#.........这里部分代码省略.........
开发者ID:jcketz,项目名称:pypreprocess,代码行数:101,代码来源:check_preprocessing.py
示例17: concat_images
# concatenate the individual images
first_level_image = concat_images(betas)
# set the model
design_matrix = np.ones(len(betas))[:, np.newaxis] # only the intercept
grp_model = FMRILinearModel(first_level_image, design_matrix, grp_mask)
# GLM fitting using ordinary least_squares
grp_model.fit(do_scaling=False, model='ols')
# specify and estimate the contrast
contrast_val = np.array(([[1]])) # the only possible contrast !
z_map, = grp_model.contrast(contrast_val, con_id='one_sample', output_z=True)
# write the results
save(z_map, path.join(write_dir, 'one_sample_z_map.nii'))
# look at the result
vmax = max(- z_map.get_data().min(), z_map.get_data().max())
vmin = - vmax
plot_map(z_map.get_data(), z_map.get_affine(),
cmap=cm.cold_hot,
vmin=vmin,
vmax=vmax,
threshold=3.,
black_bg=True)
plt.savefig(path.join(write_dir, '%s_z_map.png' % 'one_sample'))
plt.show()
print "Wrote all the results in directory %s" % write_dir
开发者ID:satra,项目名称:nipy,代码行数:29,代码来源:one_sample_t_test.py
示例18: generate_ica_report
def generate_ica_report(
stats_report_filename,
ica_maps,
mask=None,
report_title='ICA Report',
methods_text='ICA',
anat=None,
anat_affine=None,
threshold=2.,
cluster_th=0,
cmap=viz.cm.cold_hot,
start_time=None,
user_script_name=None,
progress_logger=None,
shutdown_all_reloaders=True,
**glm_kwargs
):
"""Generates a report summarizing the statistical methods and results
Parameters
----------
stats_report_filename: string:
html file to which output (generated html) will be written
contrasts: dict of arrays
contrasts we are interested in; same number of contrasts as zmaps;
same keys
zmaps: dict of image objects or strings (image filenames)
zmaps for contrasts we are interested in; one per contrast id
mask: 'nifti image object'
brain mask for ROI
design_matrix: list of 'DesignMatrix', `numpy.ndarray` objects or of
strings (.png, .npz, etc.) for filenames
design matrices for the experimental conditions
contrasts: dict of arrays
dictionary of contrasts of interest; the keys are the contrast ids,
the values are contrast values (lists)
z_maps: dict of 3D image objects or strings (image filenames)
dict with same keys as 'contrasts'; the values are paths of z-maps
for the respective contrasts
anat: 3D array (optional)
brain image to serve bg unto which activation maps will be plotted;
passed to viz.plot_map API
anat_affine: 2D array (optional)
affine data for the anat
threshold: float (optional)
threshold to be applied to activation maps voxel-wise
cluster_th: int (optional)
minimal voxel count for clusteres declared as 'activated'
cmap: cmap object (default viz.cm.cold_hot)
color-map to use in plotting activation maps
start_time: string (optional)
start time for the stats analysis (useful for the generated
report page)
user_script_name: string (optional, default None)
existing filename, path to user script used in doing the analysis
progress_logger: ProgressLogger object (optional)
handle for logging progress
shutdown_all_reloaders: bool (optional, default True)
if True, all pages connected to the stats report page will
be prevented from reloading after the stats report page
has been completely generated
**glm_kwargs:
kwargs used to specify the control parameters used to specify the
experimental paradigm and the GLM
"""
# prepare for stats reporting
if progress_logger is None:
progress_logger = base_reporter.ProgressReport()
output_dir = os.path.dirname(stats_report_filename)
# copy css and js stuff to output dir
base_reporter.copy_web_conf_files(output_dir)
# initialize gallery of activation maps
activation_thumbs = base_reporter.ResultsGallery(
loader_filename=os.path.join(output_dir,
"activation.html")
)
# get caller module handle from stack-frame
if user_script_name is None:
#.........这里部分代码省略.........
开发者ID:fabianp,项目名称:pypreprocess,代码行数:101,代码来源:ica_reporter.py
示例19: montage
def montage(nifti, anat, roi_dict, thr=2,
fig=None, out_file=None, feature_dict=None,
target_stat=None, target_value=None):
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 = 1
bgcol = 0
iscale = 2
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, iscale * x / 2.5])
plt.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99, wspace=0.1, hspace=0)
for f in xrange(features):
roi = roi_dict.get(f, None)
if roi is None:
continue
coords = roi["top_clust"]["coords"]
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, f + 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:
logger.exception(e)
plt.text(0.05, 0.8, str(f),
transform=ax.transAxes,
horizontalalignment="center",
color=(texcol,texcol,texcol))
pos = [(0.05, 0.05), (0.4, 0.05), (0.8, 0.05)]
colors = ["purple", "yellow", "green"]
if feature_dict is not None and feature_dict.get(f, None) is not None:
d = feature_dict[f]
for i, key in enumerate([k for k in d if k != "real_id"]):
plt.text(pos[i][0], pos[i][1], "%s=%.2f" % (key, d[key]) ,transform=ax.transAxes,
horizontalalignment="left", color=colors[i])
if key == target_stat:
assert target_value is not None
if d[key] >= target_value:
p_fancy = FancyBboxPatch((0.1, 0.1), 2.5 - .1, 1 - .1,
boxstyle="round,pad=0.1",
ec=(1., 0.5, 1.),
fc="none")
ax.add_patch(p_fancy)
elif d[key] <= -target_value:
p_fancy = FancyBboxPatch((0.1, 0.1), iscale * 2.5 - .1, iscale - .1,
boxstyle="round,pad=0.1",
ec=(0., 0.5, 0.),
fc="none")
ax.add_patch(p_fancy)
# stdout.write("\rSaving montage: DONE\n")
if out_file is not None:
plt.savefig(out_file, transparent=True, facecolor=(bgcol, bgcol, bgcol))
else:
plt.draw()
开发者ID:ecastrow,项目名称:pl2mind,代码行数:89,代码来源:nifti_viewer.py
示例20: load
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Example of activation image vizualization
with nipy.labs vizualization tools
"""
print __doc__
import os.path
import pylab as pl
from nibabel import load
from nipy.labs import viz
import get_data_light
# get the data
data_dir = get_data_light.get_it()
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)
pl.show()
开发者ID:Hiccup,项目名称:nipy,代码行数:24,代码来源:viz.py
注:本文中的nipy.labs.viz.plot_map函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论