本文整理汇总了Python中nilearn.plotting.plot_anat函数的典型用法代码示例。如果您正苦于以下问题:Python plot_anat函数的具体用法?Python plot_anat怎么用?Python plot_anat使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了plot_anat函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_segmentation
def plot_segmentation(anat_file, segmentation, out_file,
**kwargs):
from nilearn.plotting import plot_anat
vmax = None
if kwargs.get('saturate', False):
import nibabel as nb
import numpy as np
vmax = np.percentile(nb.load(anat_file).get_data().reshape(-1),
70)
disp = plot_anat(
anat_file,
display_mode=kwargs.get('display_mode', 'ortho'),
cut_coords=kwargs.get('cut_coords', 8),
title=kwargs.get('title'),
vmax=vmax)
disp.add_contours(
segmentation,
levels=kwargs.get('levels', [1]),
colors=kwargs.get('colors', 'r'))
disp.savefig(out_file)
disp.close()
disp = None
return out_file
示例2: plot_segmentation
def plot_segmentation(anat_file, segmentation, out_file,
**kwargs):
from nilearn.plotting import plot_anat
vmax = kwargs.get('vmax')
vmin = kwargs.get('vmin')
if kwargs.get('saturate', False):
vmax = np.percentile(nb.load(anat_file).get_data().reshape(-1), 70)
if vmax is None and vmin is None:
vmin = np.percentile(nb.load(anat_file).get_data().reshape(-1), 10)
vmax = np.percentile(nb.load(anat_file).get_data().reshape(-1), 99)
disp = plot_anat(
anat_file,
display_mode=kwargs.get('display_mode', 'ortho'),
cut_coords=kwargs.get('cut_coords', 8),
title=kwargs.get('title'),
vmax=vmax, vmin=vmin)
disp.add_contours(
segmentation,
levels=kwargs.get('levels', [1]),
colors=kwargs.get('colors', 'r'))
disp.savefig(out_file)
disp.close()
disp = None
return out_file
示例3: plot_artifact
def plot_artifact(image_path, figsize=(20, 20), vmax=None, cut_coords=None, display_mode='ortho',
size=None):
import nilearn.plotting as nplt
fig = plt.figure(figsize=figsize)
nplt_disp = nplt.plot_anat(
image_path, display_mode=display_mode, cut_coords=cut_coords,
vmax=vmax, figure=fig, annotate=False)
if size is None:
size = figsize[0] * 6
bg_color = 'k'
fg_color = 'w'
ax = fig.gca()
ax.text(
.1, .95, 'L',
transform=ax.transAxes,
horizontalalignment='left',
verticalalignment='top',
size=size,
bbox=dict(boxstyle="square,pad=0", ec=bg_color, fc=bg_color, alpha=1),
color=fg_color)
ax.text(
.9, .95, 'R',
transform=ax.transAxes,
horizontalalignment='right',
verticalalignment='top',
size=size,
bbox=dict(boxstyle="square,pad=0", ec=bg_color, fc=bg_color),
color=fg_color)
return nplt_disp, ax
示例4: _plot_anat_with_contours
def _plot_anat_with_contours(image, segs=None, compress='auto',
**plot_params):
nsegs = len(segs or [])
plot_params = plot_params or {}
# plot_params' values can be None, however they MUST NOT
# be None for colors and levels from this point on.
colors = plot_params.pop('colors', None) or []
levels = plot_params.pop('levels', None) or []
missing = nsegs - len(colors)
if missing > 0: # missing may be negative
colors = colors + color_palette("husl", missing)
colors = [[c] if not isinstance(c, list) else c
for c in colors]
if not levels:
levels = [[0.5]] * nsegs
# anatomical
display = plot_anat(image, **plot_params)
# remove plot_anat -specific parameters
plot_params.pop('display_mode')
plot_params.pop('cut_coords')
plot_params['linewidths'] = 0.5
for i in reversed(range(nsegs)):
plot_params['colors'] = colors[i]
display.add_contours(segs[i], levels=levels[i],
**plot_params)
svg = extract_svg(display, compress=compress)
display.close()
return svg
示例5: _run_interface
def _run_interface(self, runtime):
import matplotlib
matplotlib.use('Agg')
import nibabel as nib
from nilearn import plotting, datasets, image
from nipype.interfaces.base import isdefined
import numpy as np
import pylab as plt
import os
wra_img = nib.load(self.inputs.wra_img)
canonical_img = nib.load(self.inputs.canonical_img)
title = self.inputs.title
mean_wraimg = image.mean_img(wra_img)
if title != "":
filename = title.replace(" ", "_")+".pdf"
else:
filename = "plot.pdf"
fig = plotting.plot_anat(mean_wraimg, title="wrafunc & canonical single subject", cut_coords=range(-40, 40, 10), display_mode='z')
fig.add_edges(canonical_img)
fig.savefig(filename)
fig.close()
self._plot = filename
runtime.returncode=0
return runtime
示例6: check_mask_coverage
def check_mask_coverage(epi,brainmask):
from os.path import abspath
from nipype import config, logging
config.enable_debug_mode()
logging.update_logging(config)
from nilearn import plotting
from nipype.interfaces.nipy.preprocess import Trim
trim = Trim()
trim.inputs.in_file = epi
trim.inputs.end_index = 1
trim.inputs.out_file = 'epi_vol1.nii.gz'
trim.run()
epi_vol = abspath('epi_vol1.nii.gz')
maskcheck_filename='maskcheck.png'
display = plotting.plot_anat(epi_vol, display_mode='ortho',
draw_cross=False,
title = 'brainmask coverage')
display.add_contours(brainmask,levels=[.5], colors='r')
display.savefig(maskcheck_filename)
display.close()
maskcheck_file = abspath(maskcheck_filename)
return(maskcheck_file)
示例7: _run_interface
def _run_interface(self, runtime):
import matplotlib
matplotlib.use("Agg")
import pylab as plt
wra_img = nib.load(self.inputs.wra_img)
canonical_img = nib.load(self.inputs.canonical_img)
title = self.inputs.title
mean_wraimg = image.mean_img(wra_img)
if title != "":
filename = title.replace(" ", "_") + ".pdf"
else:
filename = "plot.pdf"
fig = plotting.plot_anat(
mean_wraimg, title="wrafunc & canonical single subject", cut_coords=range(-40, 40, 10), display_mode="z"
)
fig.add_edges(canonical_img)
fig.savefig(filename)
fig.close()
self._plot = filename
runtime.returncode = 0
return runtime
示例8: make_anat_image
def make_anat_image(nifti_file,png_img_file=None):
"""Make anat image"""
nifti_file = str(nifti_file)
brain = plot_anat(nifti_file)
if png_img_file:
brain.savefig(png_img_file)
plt.close('all')
return brain
示例9: anatomical_overlay
def anatomical_overlay(in_file, overlay_file, out_file):
import os.path
import matplotlib as mpl
mpl.use('Agg')
from nilearn.plotting import plot_anat as plot_anat
mask_display = plot_anat(in_file)
mask_display.add_edges(overlay_file)
mask_display.dim = -1
# mask_display.add_contours(overlay_file)
# mask_display.add_overlay(overlay_file)
mask_display.title(out_file, x=0.01, y=0.99, size=15, color=None,
bgcolor=None, alpha=1)
mask_display.savefig(out_file)
return os.path.abspath(out_file)
示例10: plot_image
def plot_image(input_files, output_directory, edge_file=None,
overlay_file=None,
contour_file=None, name=None, overlay_cmap=None):
""" Plot image with edge/overlay/contour on top (useful for checking
registration).
<unit>
<input name="input_files" type="['List_File', 'File']" desc="An image
or a list of image to be displayed."/>
<input name="output_directory" type="Directory" description="The
destination folder."/>
<input name="edge_file" type="File" description="The target image
to extract the edges from."/>
<input name="overlay_file" type="File" description="The target image
to extract the overlay from."/>
<input name="contour_file" type="File" description="The target image
to extract the contour from."/>
<input name="name" type="Str" description="The name of the plot."/>
<input name="overlay_cmap" type="Str" description="The color map to
use: 'cold_hot' or 'blue_red' or None."/>
<output name="snap_file" type="File" description="A pdf snap of the
image."/>
</unit>
"""
input_file = input_files[0]
# Check the input images exist on the file system
for in_file in [input_file, edge_file, overlay_file, contour_file]:
if in_file is not None and not os.path.isfile(in_file):
raise ValueError("'{0}' is not a valid filename.".format(in_file))
# Create the 'snap_file' location
snap_file = os.path.join(
output_directory, os.path.basename(input_file).split(".")[0] + ".pdf")
# Create the plot
display = plotting.plot_anat(input_file, title=name or "")
if edge_file is not None:
display.add_edges(edge_file)
if overlay_file is not None:
cmap = plotting.cm.__dict__.get(
overlay_cmap, plotting.cm.alpha_cmap((1, 1, 0)))
display.add_overlay(overlay_file, cmap=cmap)
if contour_file is not None:
display.add_contours(contour_file, alpha=0.6, filled=True,
linestyles="solid")
display.savefig(snap_file)
display.close()
return snap_file
示例11: create_coreg_plot
def create_coreg_plot(epi,anat):
import os
from nipype import config, logging
config.enable_debug_mode()
logging.update_logging(config)
from nilearn import plotting
coreg_filename='coregistration.png'
display = plotting.plot_anat(epi, display_mode='ortho',
draw_cross=False,
title = 'coregistration to anatomy')
display.add_edges(anat)
display.savefig(coreg_filename)
display.close()
coreg_file = os.path.abspath(coreg_filename)
return(coreg_file)
示例12: edges_overlay
def edges_overlay(input_file, template_file, prefix="e", output_directory=None):
""" Plot image outline on top of another image (useful for checking
registration)
<unit>
<input name="input_file" type="File" desc="An image to display."/>
<input name="template_file" type="File" desc="The target image to
extract the edges from."/>
<input name="prefix" type="String" desc="the prefix of the result
file."/>
<input name="output_directory" type="Directory" desc="The destination
folder." optional="True"/>
<output name="edges_file" type="File" desc="A snap with two overlayed
images."/>
</unit>
"""
# Check the input images exist on the file system
for in_file in [input_file, template_file]:
if not os.path.isfile(in_file):
raise ValueError("'{0}' is not a valid filename.".format(in_file))
# Check that the outdir is valid
if output_directory is not None:
if not os.path.isdir(output_directory):
raise ValueError("'{0}' is not a valid directory.".format(output_directory))
else:
output_directory = os.path.dirname(input_file)
# Create the plot
display = plotting.plot_anat(input_file, title="Overlay")
display.add_edges(template_file)
edges_file = os.path.join(output_directory, prefix + os.path.basename(input_file).split(".")[0] + ".pdf")
display.savefig(edges_file)
display.close()
return edges_file
示例13: print
# is a 'nibabel' object. It has data, and an affine
anat_data = smooth_anat_img.get_data()
print('anat_data has shape: %s' % str(anat_data.shape))
anat_affine = smooth_anat_img.get_affine()
print('anat_affineaffine:\n%s' % anat_affine)
# Finally, it can be passed to nilearn function
smooth_anat_img = image.smooth_img(smooth_anat_img, 3)
#########################################################################
# Visualization
from nilearn import plotting
cut_coords = (0, 0, 0)
# Like all functions in nilearn, plotting can be given filenames
plotting.plot_anat(anat_filename, cut_coords=cut_coords,
title='Anatomy image')
# Or nibabel objects
plotting.plot_anat(smooth_anat_img,
cut_coords=cut_coords,
title='Smoothed anatomy image')
#########################################################################
# Saving image to file
smooth_anat_img.to_filename('smooth_anat_img.nii.gz')
#########################################################################
# Finally, showing plots when used inside a terminal
plotting.show()
示例14: Structure
#
# .. note:: In this tutorial, we load the data using a data downloading
# function. To input your own data, you will need to provide
# a list of paths to your own files in the ``subject_data`` variable.
# These should abide to the Brain Imaging Data Structure (BIDS)
# organization.
from nistats.datasets import fetch_spm_auditory
subject_data = fetch_spm_auditory()
print(subject_data.func) # print the list of names of functional images
###############################################################################
# We can display the first functional image and the subject's anatomy:
from nilearn.plotting import plot_stat_map, plot_anat, plot_img, show
plot_img(subject_data.func[0])
plot_anat(subject_data.anat)
###############################################################################
# Next, we concatenate all the 3D EPI image into a single 4D image,
# then we average them in order to create a background
# image that will be used to display the activations:
from nilearn.image import concat_imgs, mean_img
fmri_img = concat_imgs(subject_data.func)
mean_img = mean_img(fmri_img)
###############################################################################
# Specifying the experimental paradigm
# ------------------------------------
#
# We must now provide a description of the experiment, that is, define the
示例15: coord_transform
# Build the mean image because we have no anatomic data
from nilearn import image
func_filename = haxby_dataset.func[0]
mean_img = image.mean_img(func_filename)
z_slice = -24
from nilearn.image.resampling import coord_transform
affine = mean_img.get_affine()
_, _, k_slice = coord_transform(0, 0, z_slice,
linalg.inv(affine))
k_slice = round(k_slice)
fig = plt.figure(figsize=(4, 5.4), facecolor='k')
from nilearn.plotting import plot_anat
display = plot_anat(mean_img, display_mode='z', cut_coords=[z_slice],
figure=fig)
mask_vt_filename = haxby_dataset.mask_vt[0]
mask_house_filename = haxby_dataset.mask_house[0]
mask_face_filename = haxby_dataset.mask_face[0]
display.add_contours(mask_vt_filename, contours=1, antialiased=False,
linewidths=4., levels=[0], colors=['red'])
display.add_contours(mask_house_filename, contours=1, antialiased=False,
linewidths=4., levels=[0], colors=['blue'])
display.add_contours(mask_face_filename, contours=1, antialiased=False,
linewidths=4., levels=[0], colors=['limegreen'])
# We generate a legend using the trick described on
# http://matplotlib.sourceforge.net/users/legend_guide.httpml#using-proxy-artist
from matplotlib.patches import Rectangle
p_v = Rectangle((0, 0), 1, 1, fc="red")
p_h = Rectangle((0, 0), 1, 1, fc="blue")