Пример #1
0
    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
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)
Пример #3
0
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
0
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
Пример #5
0
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
	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
Пример #7
0
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
Пример #8
0
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
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
0
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
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
0
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
0
fieldmap_pa = join(raw_nifti_dir, scanInfo.loc['se_fieldmap_pa']['scanName'])
ref_epi = join(raw_nifti_dir, scanInfo.loc[last_scan]['scanName'])

# run topup
get_ipython().system("{join(codedir, 'prep_unwarpFiles.sh')} {outdir} {fieldmap_ap} {fieldmap_pa}
                      {acqparams_file} {config_file} {ref_epi}")


# MAKE FIELDMAP FIGURES ----------------------------------------------

# Original SE maps
fieldmap = join(outdir, 'concat_fieldmaps.nii.gz')
print('saving images of original SE maps...')
for i in range(3):
    plot_title = 'orig_se_ap_' + str(i)
    plotting.plot_anat(image.index_img(fieldmap,i), dim=-1, title=plot_title,
                       output_file = join(fm_outdir, plot_title + '.png'))
for i in range(3,6):
    plot_title = 'orig_se_pa_' + str(i)
    plotting.plot_anat(image.index_img(fieldmap,i), dim=-1, title=plot_title,
                       output_file = join(fm_outdir, plot_title + '.png'))

# Corrected SE maps
fieldmap = join(outdir, 'topup_iout.nii.gz')
print('saving images of corrected SE maps...')
for i in range(3):
    plot_title = 'corr_se_ap_' + str(i)
    plotting.plot_anat(image.index_img(fieldmap,i), dim=-1, title=plot_title,
                       output_file = join(fm_outdir, plot_title + '.png'))
for i in range(3,6):
    plot_title = 'corr_se_pa_' + str(i)
    plotting.plot_anat(image.index_img(fieldmap,i), dim=-1, title=plot_title,
Пример #14
0
# view.open_in_browser()

###############################################################################
# Plotting statistical maps in a glass brain with function `plot_glass_brain`
# ---------------------------------------------------------------------------
#
# Now, the t-map image is mapped on glass brain representation where glass
# brain is always a fixed background template
plotting.plot_glass_brain(stat_img, title='plot_glass_brain', threshold=3)

###############################################################################
# Plotting anatomical images with function `plot_anat`
# -----------------------------------------------------
#
# Visualizing anatomical image of haxby dataset
plotting.plot_anat(haxby_anat_filename, title="plot_anat")

###############################################################################
# Plotting ROIs (here the mask) with function `plot_roi`
# -------------------------------------------------------
#
# Visualizing ventral temporal region image from haxby dataset overlaid on
# subject specific anatomical image with coordinates positioned automatically on
# region of interest (roi)
plotting.plot_roi(haxby_mask_filename,
                  bg_img=haxby_anat_filename,
                  title="plot_roi")

###############################################################################
# Plotting EPI image with function `plot_epi`
# ---------------------------------------------
Пример #15
0
def plot_denoise(lowb_nii,
                 highb_nii,
                 div_id,
                 plot_params=None,
                 highb_plot_params=None,
                 order=('z', 'x', 'y'),
                 cuts=None,
                 estimate_brightness=False,
                 label=None,
                 lowb_contour=None,
                 highb_contour=None,
                 compress='auto',
                 overlay=None,
                 overlay_params=None):
    """
    Plot the foreground and background views.
    Default order is: axial, coronal, sagittal

    Updated version from sdcflows
    """
    plot_params = plot_params or {}
    highb_plot_params = highb_plot_params or {}

    # Use default MNI cuts if none defined
    if cuts is None:
        raise NotImplementedError

    # Do the low-b image first
    out_files = []
    if estimate_brightness:
        plot_params = robust_set_limits(
            lowb_nii.get_fdata(dtype='float32').reshape(-1), plot_params)
    # Plot each cut axis for low-b
    for i, mode in enumerate(list(order)):
        plot_params['display_mode'] = mode
        plot_params['cut_coords'] = cuts[mode]
        if i == 0:
            plot_params['title'] = label + ": low-b"
        else:
            plot_params['title'] = None

        # Generate nilearn figure
        display = plot_anat(lowb_nii, **plot_params)
        if lowb_contour is not None:
            display.add_contours(lowb_contour, linewidths=1)

        svg = extract_svg(display, compress=compress)
        display.close()

        # Find and replace the figure_1 id.
        xml_data = etree.fromstring(svg)
        find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
        find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))

        svg_fig = SVGFigure()
        svg_fig.root = xml_data
        out_files.append(svg_fig)

    # Plot each cut axis for high-b
    if estimate_brightness:
        highb_plot_params = robust_set_limits(
            highb_nii.get_fdata(dtype='float32').reshape(-1),
            highb_plot_params)
    for i, mode in enumerate(list(order)):
        highb_plot_params['display_mode'] = mode
        highb_plot_params['cut_coords'] = cuts[mode]
        if i == 0:
            highb_plot_params['title'] = label + ': high-b'
        else:
            highb_plot_params['title'] = None

        # Generate nilearn figure
        display = plot_anat(highb_nii, **highb_plot_params)
        if highb_contour is not None:
            display.add_contours(highb_contour, linewidths=1)

        svg = extract_svg(display, compress=compress)
        display.close()

        # Find and replace the figure_1 id.
        xml_data = etree.fromstring(svg)
        find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
        find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))

        svg_fig = SVGFigure()
        svg_fig.root = xml_data
        out_files.append(svg_fig)

    return out_files
# Create a memory context
from nipype.caching import Memory
mem = Memory('/tmp/no_workflow')

# Give the paths to spm
paths = ['/i2bm/local/spm12-standalone-6472/spm12_mcr/spm12/']

# Compute mean functional
from procasl import preprocessing
average = mem.cache(preprocessing.Average)
out_average = average(in_file='/tmp/func.nii')
mean_func = out_average.outputs.mean_file

# Coregister anat to mean functional
from nipype.interfaces import spm
coregister = mem.cache(spm.Coregister)
out_coregister = coregister(
    target=mean_func,
    source='/tmp/anat.nii',
    write_interp=3)

# Check coregistration
import matplotlib.pylab as plt
from nilearn import plotting
figure = plt.figure(figsize=(5, 4))
display = plotting.plot_anat(mean_func, figure=figure,
                             title='anat edges on mean functional')
display.add_edges(out_coregister.outputs.coregistered_source)
figure.suptitle('Impact of tagging correction')
plt.show()
Пример #17
0

# plotting slices for finer alignment
# e.g. parieto-occipital sulcus

def add_brain_schematics(display):
    for axes in display.axes.values():
        kwargs = {'alpha': 0.5, 'linewidth': 1, 'edgecolor': 'orange'}
        object_bounds = glass_brain.plot_brain_schematics(axes.ax,
                                                          axes.direction,
                                                          **kwargs)
        axes.add_object_bounds(object_bounds)


# side
display = plotting.plot_anat(display_mode='x', cut_coords=[-2])
add_brain_schematics(display)

# top
display = plotting.plot_anat(display_mode='z', cut_coords=[20])
add_brain_schematics(display)

# front
display = plotting.plot_anat(display_mode='y', cut_coords=[-20])
add_brain_schematics(display)

# all in one
display = plotting.plot_anat(display_mode='ortho', cut_coords=(-2, -20, 20))
add_brain_schematics(display)

# Plot multiple slices
Пример #18
0
def regular(args):
    # Initialize extractor
    if glob(os.path.join(args.outdir, '*')) != []:
        raise Exception("The dir '{0}' is not empty!".format(args.outdir))

    try:

        # get an tmp dir change dir
        tmpdir = tempfile.mkdtemp()
        prevdir = os.getcwd()
        os.chdir(tmpdir)

        # 
        ImageFilePath = args.image
        work_in = os.path.basename(ImageFilePath) 
        OutDirPath = args.outdir

        # base/XX/model02/XX_bfc.nii.gz -> cropped
        tmp_cropped = 'fov_cropped'
        # create cropped volume
        cmd = ['fsl5.0-robustfov',
               '-i', ImageFilePath,
               '-m', tmp_cropped]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)

        # get cropped xfromation
        cmd = ['fsl5.0-robustfov',
               '-i', ImageFilePath,
               '-r', tmp_cropped]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)

        # apply xfromation to get the file cropped in working dir and remain
        # in native referential
        cmd = ['fsl5.0-flirt',
               '-in', tmp_cropped,
               '-ref', ImageFilePath, 
               '-init', tmp_cropped, 
               '-applyxfm',
               '-out', work_in ]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)
            
        # perform bet extraction and mask transcoding in float32
        mask_bet = work_in.replace('bfc', 'bfc_betmask')
        mask_bin = mask_bet.replace('betmask', 'betmask_mask')
        cmd = ['fsl5.0-bet', work_in, mask_bet, '-m', '-S', '-R']
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)
        
        print ">>> ", os.getcwd(), " <<<", "Convert bet mask in float image: ",mask_bin
        nimg = ni.load(mask_bin)
        ni.save(ni.Nifti1Image(nimg.get_data().astype('float32'),
                               affine=nimg.get_affine()),
                mask_bin)

        # performe fast segmentation
        # --out flag does not seem to work : ugly workaround ...
        cmd = ['fsl5.0-fast', 
               ' -t 1 -n 3 ', 
               mask_bet]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)

#        rename_fns = unique(glob('*seg*') + glob('*pve*')).tolist()
#        for rename_fn in rename_fns:
#            shutil.move(rename_fn, 
#                        rename_fn.replace('betmask', 
#                                          work_in.replace('.nii.gz', '')))
#        rename_fns = unique(glob('*betmask*')).tolist()
#        for rename_fn in rename_fns:
#            shutil.move(rename_fn,
#                        rename_fn.replace('betmask', 
#                                          '{}_betmask'.format(work_in.replace('.nii.gz', '')))
        # QC :  pdf sheet
        bg = ni.load(work_in.replace('.nii.gz', '_betmask_pveseg.nii.gz'))
        # image axial
        display = plotting.plot_anat(bg, title="FAST segmentation", 
                                     display_mode = 'z',
                                     cut_coords = 20)
        display.savefig('{}_pveseg.pdf'.format(work_in.replace('.nii.gz', '')))
        display.close()

        
        # affine registration -in betmask -ref MNI_brain_1mm
        cmd = [
            'fsl5.0-flirt',
            '-dof', '12',
            '-omat', 'nat2mni',
            '-in', mask_bet,
            '-ref', MNI_BRAIN
            ]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)

        #invert Xformation
        cmd = [
            'fsl5.0-convert_xfm',
            '-omat', 'mni2nat',
            '-inverse', 'nat2mni'
            ]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)
        tmp_cropped = 'fov_cropped'

        # create a 40 mm height hat box in mni
        mni = ni.load(MNI_BRAIN)
        hat_data = mni.get_data()
        hat_data[hat_data < 800] = 0
        _, _, zmax = hat_data.shape
        hat_data[:, :, 121:zmax] = 0
        hat_data[:, :, 0:79] = 0
        hat_data[hat_data != 0] = 1
        ni.save(ni.Nifti1Image(hat_data, affine=mni.get_affine()),
                'hatbox.nii.gz')

        #
        cmd = ['fsl5.0-flirt',
               '-applyxfm',
               '-init', 'mni2nat',
               '-ref', ImageFilePath,
               '-in', 'hatbox.nii.gz',
               '-out', 'native_hatbox.nii.gz'
               ]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)
        hat_box = ni.load('native_hatbox.nii.gz')
        hat_data = hat_box.get_data()
        hat_data[hat_data != 0] = 1
        ni.save(ni.Nifti1Image(hat_data, affine=hat_box.get_affine()),
                'native_hatbox.nii.gz')

        # create QC for hat_box steps
        bg = ni.load('native_hatbox.nii.gz')
        display = plotting.plot_anat(
                    ni.load(ImageFilePath), 
                    title="T1 Gado with hatbox contours",
                    display_mode = 'z',
                    cut_coords = 10)
        display.add_overlay(bg, threshold=0)
        display.savefig("QC_axial_hatbox.pdf")
        display.close()
        display = plotting.plot_anat(
                    ni.load(ImageFilePath), 
                    title="T1 Gado with hatbox contours",
                    display_mode = 'x',
                    cut_coords = 10)
        display.add_overlay(bg, threshold=0)
        display.savefig("QC_sagital_hatbox.pdf")
        display.close()

        # move selected files
        flist = unique(glob('*'))
        for f in flist:
            shutil.move(f, OutDirPath)

    except Exception:
        print 'model03_mni registration/segmentation FAILED:\n%s', traceback.format_exc()

    # finale housekeeping
    os.chdir(prevdir)
    shutil.rmtree(tmpdir)
Пример #19
0
    get_tmaps=True)
localizer_anat_filename = localizer_dataset.anats[1]
localizer_cmap_filename = localizer_dataset.cmaps[1]
localizer_tmap_filename = localizer_dataset.tmaps[1]

###############################################################################
# demo the different plotting functions

# Plotting statistical maps
plotting.plot_stat_map(localizer_cmap_filename, bg_img=localizer_anat_filename,
                       threshold=3, title="plot_stat_map",
                       cut_coords=(36, -27, 66))

# Plotting glass brain
plotting.plot_glass_brain(localizer_tmap_filename, title='plot_glass_brain',
                          threshold=3)

# Plotting anatomical maps
plotting.plot_anat(haxby_anat_filename, title="plot_anat")

# Plotting ROIs (here the mask)
plotting.plot_roi(haxby_mask_filename, bg_img=haxby_anat_filename,
                  title="plot_roi")

# Plotting EPI haxby
mean_haxby_img = image.mean_img(haxby_func_filename)
plotting.plot_epi(mean_haxby_img, title="plot_epi")

import matplotlib.pyplot as plt
plt.show()
Пример #20
0
 def plotAnatomyExternal(self):
     plotting.plot_anat(self.anatomy_location, title='Anatomy')
     plt.show()
from mne.simulation import simulate_evoked
from mne.forward import make_forward_dipole

# evoked=evoked_full
evoked_full = evoked.copy()
evoked.crop(0.14, 0.16)
# Fit a dipole
dip = mne.fit_dipole(evoked, cov, bem, trans)[0]
# Plot the result in 3D brain with the MRI image.
dip.plot_locations(trans, mri_partic, subjects_dir=mri_dir, mode='orthoview')
#plot on scan
mni_pos = mne.head_to_mni(dip.pos, mri_head_t=trans,subject=mri_partic, subjects_dir=mri_dir)
mri_pos = mne.head_to_mri(dip.pos, mri_head_t=trans,subject=mri_partic, subjects_dir=mri_dir)

t1_fname = mri_dir+'\\'+ mri_partic+ '\\mri\\T1.mgz'
fig_T1 = plot_anat(t1_fname, cut_coords=mri_pos[0], title='Dipole loc.')
# #plot on standard
# from nilearn.datasets import load_mni152_template
# template = load_mni152_template()
# fig_template = plot_anat(template, cut_coords=mni_pos[0],title='Dipole loc. (MNI Space)')

#plot fied predicted by dipole with max goodness of fit, compare to data and take diff
fwd_dip, stc_dip = make_forward_dipole(dip, bem, evoked.info, trans)
pred_evoked = simulate_evoked(fwd_dip, stc_dip, evoked.info, cov=None, nave=np.inf)

# find time point with highest goodness of fit (gof)
best_idx = np.argmax(dip.gof)
best_time = dip.times[best_idx]
print('Highest GOF %0.1f%% at t=%0.1f ms with confidence volume %0.1f cm^3'
      % (dip.gof[best_idx], best_time * 1000,
         dip.conf['vol'][best_idx] * 100 ** 3))
Пример #22
0
    reg_func_file = path_fmri + subjectID + "/ants/epi2braints.nii.gz"
    t1_file = "/shared/nonrestricted/connectome/Subjects/" + subjectID + \
            "/T1w/T1w_acpc_dc_restore_brain_2.00.nii.gz"
    if os.path.exists(reg_func_file) and os.path.exists(t1_file):

        try:
            reg_func = nibabel.load(reg_func_file)
            first_vol = image.index_img(reg_func, 0)
            t1 = nibabel.load(t1_file)

        except:
            print("{}: Error reading image".format(subjectID))
            continue

        struct = plotting.plot_anat(t1, title = subjectID)
        struct.add_edges(first_vol)
        struct.savefig("reports/" + subjectID + "/epi2struct.png")

        epi2struct = "reports/" + subjectID + "/epi2struct.png "
        subjects_as_string += epi2struct

    else:
        print("{}: Missing image".format(subjectID))

    #break

# Creates a pdf of functional images overlaid on T1 for all subjects
os.system("convert " + subjects_as_string + " reports/missing_subs_epi2struct.pdf")

Пример #23
0
print([[lab, np.sum(mask_clustlabels_arr == lab)] for lab in labels])
#[[1, 95], [2, 179484], [3, 28], [4, 24], [5, 49], [6, 35], [7, 56], [8, 23], [9, 48], [10, 50], [11, 425], [12, 68], [13, 22], [14, 79], [15, 151], [16, 33], [17, 78], [18, 54], [19, 308], [20, 22], [21, 29], [22, 118], [23, 125], [24, 122], [25, 48], [26, 51], [27, 266], [28, 31], [29, 129], [30, 58], [31, 187287], [32, 27], [33, 24], [34, 39], [35, 29], [36, 68], [37, 30], [38, 21], [39, 83], [40, 324], [41, 122], [42, 108], [43, 37], [44, 48], [45, 106], [46, 24], [47, 63], [48, 47], [49, 263], [50, 37], [51, 46], [52, 23], [53, 76], [54, 43], [55, 22], [56, 68], [57, 70], [58, 34]]

assert mask_arr.sum() == 371278

nibabel.Nifti1Image(mask_arr.astype(int), affine=ref_img.affine).to_filename(
    os.path.join(ANALYSIS_DATA_PATH, "mask.nii.gz"))

# Plot mask
mask_img = nibabel.Nifti1Image(mask_arr.astype(float), affine=ref_img.affine)
nslices = 8
fig = plt.figure(figsize=(19.995, 11.25))
ax = fig.add_subplot(311)
plotting.plot_anat(mask_img,
                   display_mode='z',
                   cut_coords=nslices,
                   figure=fig,
                   axes=ax)
ax = fig.add_subplot(312)
plotting.plot_anat(mask_img,
                   display_mode='y',
                   cut_coords=nslices,
                   figure=fig,
                   axes=ax)
ax = fig.add_subplot(313)
plotting.plot_anat(mask_img,
                   display_mode='x',
                   cut_coords=nslices,
                   figure=fig,
                   axes=ax)
plt.savefig(os.path.join(ANALYSIS_DATA_PATH, "mask.png"))
from nipype.caching import Memory

cache_directory = "/tmp"
mem = Memory("/tmp")
os.chdir(cache_directory)

# Compute mean functional
from procasl import preprocessing

average = mem.cache(preprocessing.Average)
out_average = average(in_file=heroes["raw ASL"][0])
mean_func = out_average.outputs.mean_image

# Coregister anat to mean functional
from nipype.interfaces import spm

coregister = mem.cache(spm.Coregister)
out_coregister = coregister(target=mean_func, source=raw_anat, write_interp=3)

# Check coregistration
import matplotlib.pylab as plt
from nilearn import plotting

for anat, label in zip([raw_anat, out_coregister.outputs.coregistered_source], ["native", "coregistered"]):
    figure = plt.figure(figsize=(5, 4))
    display = plotting.plot_anat(
        anat, figure=figure, display_mode="z", cut_coords=(-66,), title=label + " anat edges on mean functional"
    )
    display.add_edges(mean_func)
plotting.show()
# First, we plot a network of index=4 without region extraction (left plot)
img = image.index_img(components_img, 4)
coords = plotting.find_xyz_cut_coords(img)
display = plotting.plot_stat_map(img,
                                 cut_coords=coords,
                                 colorbar=False,
                                 title='Showing one specific network')

# Now, we plot (right side) same network after region extraction to show that
# connected regions are nicely seperated.
# Each brain extracted region is identified as separate color.

# For this, we take the indices of the all regions extracted related to original
# network given as 4.
regions_indices_of_map3 = np.where(np.array(regions_index) == 4)

display = plotting.plot_anat(cut_coords=coords,
                             title='Extracted regions in one specific network')

# Now add as an overlay by looping over all the regions of index 4
# color list is random (you can choose your own color)
color_list = [[0., 1., 0.29, 1.], [0., 1., 0.54, 1.], [0., 1., 0.78, 1.],
              [0., 0.96, 1., 1.], [0., 0.73, 1., 1.], [0., 0.47, 1., 1.],
              [0., 0.22, 1., 1.], [0.01, 0., 1., 1.], [0.26, 0., 1., 1.]]
for each_index_of_map3, color in zip(regions_indices_of_map3[0], color_list):
    display.add_overlay(image.index_img(regions_extracted_img,
                                        each_index_of_map3),
                        cmap=plotting.cm.alpha_cmap(color))

plotting.show()
Пример #26
0
def rescue(args):
    # Initialize extractor
    try:

        # get an tmp dir change dir
        tmpdir = tempfile.mkdtemp()
        prevdir = os.getcwd()
        os.chdir(tmpdir)
        
        # 
        ImageFilePath = (args.image).replace('model02', 'model03')
        OutDirPath = args.outdir
        #
        atlas_im = '/neurospin/radiomics/studies/metastasis/base/187962757123/model02/187962757123_enh-gado_T1w_bfc.nii.gz'
        atlas_nat2mni = '/neurospin/radiomics/studies/metastasis/base/187962757123/model03/nat2mni'

        # intermediate path
        cmd = ['fsl5.0-flirt',
               '-in', ImageFilePath,
               '-ref', atlas_im,
               '-dof', '12',
               '-omat', 'image2atlas']
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)   
        
        cmd = ['fsl5.0-convert_xfm',
               '-omat', 'nat2mni',
               '-concat', atlas_nat2mni, 'image2atlas']
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)
        
        #invert Xformation
        cmd = [
            'fsl5.0-convert_xfm',
            '-omat', 'mni2nat',
            '-inverse', 'nat2mni'
            ]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)

        cmd = ['fsl5.0-flirt',
               '-applyxfm',
               '-init', 'mni2nat',
               '-ref', ImageFilePath,
               '-in', os.path.join(os.path.dirname(ImageFilePath), 'hatbox.nii.gz'),
               '-out', 'native_hatbox.nii.gz'
               ]
        print ">>> ", os.getcwd(), " <<<", " ".join(cmd)
        results = subprocess.check_call(cmd)
        hat_box = ni.load('native_hatbox.nii.gz')
        hat_data = hat_box.get_data()
        hat_data[hat_data != 0] = 1
        ni.save(ni.Nifti1Image(hat_data, affine=hat_box.get_affine()),
                'native_hatbox.nii.gz')

        # create QC for hat_box steps
        bg = ni.load('native_hatbox.nii.gz')
        display = plotting.plot_anat(
                    ni.load(ImageFilePath), 
                    title="T1 Gado with hatbox contours",
                    display_mode = 'z',
                    cut_coords = 10)
        display.add_overlay(bg, threshold=0)
        display.savefig("QC_axial_hatbox.pdf")
        display.close()
        display = plotting.plot_anat(
                    ni.load(ImageFilePath), 
                    title="T1 Gado with hatbox contours",
                    display_mode = 'x',
                    cut_coords = 10)
        display.add_overlay(bg, threshold=0)
        display.savefig("QC_sagital_hatbox.pdf")
        display.close()

        # move selected files
        flist = ['image2atlas', 'mni2nat',
                 'nat2mni', 'native_hatbox.nii.gz', 'QC_axial_hatbox.pdf',
                 'QC_sagital_hatbox.pdf']
        for f in flist:
            if os.path.exists(os.path.join(OutDirPath, f)):
                os.remove(os.path.join(OutDirPath, f))
        for f in flist:
            shutil.move(f, OutDirPath)
        
    except Exception:
        print 'model03_mni rescue registration/segmentation FAILED:\n%s', traceback.format_exc()

    # finale housekeeping
    os.chdir(prevdir)
    shutil.rmtree(tmpdir)
Пример #27
0
    group_means = math_img(
        'img * (np.sum(img!=0, axis=-1)>=(img.shape[-1]/2.))[..., None]',
        img=group_means)

    # Create tsnr mean map
    group_img = math_img('np.mean(img, axis=-1)', img=group_means)
    group_img.to_filename('%s/group_tsnr%s.nii.gz' % (res_path, method))

    # Plot figure
    display = plot_anat(
        group_img,
        display_mode='xz',
        cut_coords=[-20, 10],
        colorbar=False,
        cmap='Spectral_r',
        threshold=350,
        vmin=350,
        vmax=1400,
        dim=1,
        annotate=False,
        draw_cross=False,
        black_bg=True,
    )
    img_tmp = nb.load(template_gm)
    display.savefig('%s/group_tsnr%s_%s.svg' % (res_path, postfix, method))

    tsnr_values.append([method, group_img.get_data()])

# Plot histograms of voxel distribution above threshold
sns.set_style('darkgrid')
plt.style.use('seaborn-colorblind')
threshold = 1
Пример #28
0
        img=group_means)

    # Create standard deviation map
    group_img = math_img('np.std(img, axis=-1)', img=group_means)
    group_img.to_filename('%s/group_stdev_%s.nii.gz' % (res_path, method))

    # Plot figure
    fig = plt.figure(figsize=(4, 4))
    display = plot_anat(
        group_img,
        display_mode='yz',
        cut_coords=[-10, 10],
        colorbar=False,
        cmap='Spectral_r',
        threshold=150,
        vmin=150,
        vmax=500,
        #title=method,
        dim=1,
        annotate=False,
        draw_cross=False,
        black_bg=True,
        figure=fig,
    )
    img_tmp = nb.load(template_gm)
    img_tmp = new_img_like(img_tmp, (img_tmp.get_data() >= 0.05).astype('int'),
                           copy_header=True)
    display.add_contours(img_tmp, color='w')
    fig.savefig('%s/group_stdev_%s.svg' % (res_path, method))

    stdev_values.append([method, group_img.get_data()])
Пример #29
0
plotting.plot_stat_map(localizer_cmap_filename,
                       display_mode='yx',
                       cut_coords=(-27, 36),
                       title="display_mode='yx', cut_coords=(-27, 36)")

plotting.plot_stat_map(localizer_cmap_filename,
                       display_mode='yz',
                       cut_coords=(-27, 60),
                       title="display_mode='yz', cut_coords=(-27, 60)")

###############################################################################
# demo display objects with add_ methods
mean_haxby_img = image.mean_img(haxby_func_filename)

# Plot T1 outline on top of the mean EPI (useful for checking coregistration)
display = plotting.plot_anat(mean_haxby_img, title="add_edges")
display.add_edges(haxby_anat_filename)

# Plotting outline of the mask on top of the EPI
display = plotting.plot_anat(mean_haxby_img,
                             title="add_contours",
                             cut_coords=(28, -34, -22))
display.add_contours(haxby_mask_filename, levels=[0.5], colors='r')

###############################################################################
# demo saving plots to file

plotting.plot_stat_map(localizer_cmap_filename,
                       title='Using plot_stat_map output_file',
                       output_file='plot_stat_map.png')
Пример #30
0
anat_img = nibabel.load(anat_filename)

# Accessing image data and affine #############################################
anat_data = anat_img.get_data()
print 'anat_data has shape:', anat_data.shape
anat_affine = anat_img.get_affine()
print 'anat_affine:\n', anat_affine

# Using image in nilearn functions ############################################
from nilearn import image
# functions containing 'img' can take either a filename or an image as input
smooth_anat_img = image.smooth_img(anat_filename, 6)
smooth_anat_img = image.smooth_img(anat_img, 6)


# Visualization ###############################################################
from nilearn import plotting
cut_coords = (0, 0, 0)
plotting.plot_anat(anat_filename, cut_coords=cut_coords,
                   title='Anatomy image')
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')

# Showing plots ###############################################################
import matplotlib.pyplot as plt
plt.show()
#
# .. 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
# Plot regions extracted for only one specific network
# ----------------------------------------------------

# First, we plot a network of index=4 without region extraction (left plot)
from nilearn import image

img = image.index_img(components_img, 4)
coords = plotting.find_xyz_cut_coords(img)
display = plotting.plot_stat_map(img, cut_coords=coords, colorbar=False,
                                 title='Showing one specific network')

################################################################################
# Now, we plot (right side) same network after region extraction to show that
# connected regions are nicely seperated.
# Each brain extracted region is identified as separate color.

# For this, we take the indices of the all regions extracted related to original
# network given as 4.
regions_indices_of_map3 = np.where(np.array(regions_index) == 4)

display = plotting.plot_anat(cut_coords=coords,
                             title='Regions from this network')

# Add as an overlay all the regions of index 4
colors = 'rgbcmyk'
for each_index_of_map3, color in zip(regions_indices_of_map3[0], colors):
    display.add_overlay(image.index_img(regions_extracted_img, each_index_of_map3),
                        cmap=plotting.cm.alpha_cmap(color))

plotting.show()
Пример #33
0
 def openAnatomy(self):
     file = self.onOpen([('NIFTI files', '*.nii.gz'), ('All files', '*')])
     print("anatomy file: " + file)
     plotting.plot_anat(file, title='Anatomy')
     plt.show()
Пример #34
0
# for the conversion we use our estimated transformation matrix and the
# MEG coordinates extracted from the raw file. `subjects` and `subjects_dir`
# are used internally, to point to the T1-weighted MRI file: `t1_mgh_fname`
mri_pos = head_to_mri(pos=pos,
                      subject='sample',
                      mri_head_t=estim_trans,
                      subjects_dir=op.join(data_path, 'subjects'))

# Our MRI written to BIDS, we got `anat_dir` from our `write_anat` function
t1_nii_fname = op.join(anat_dir, 'sub-01_ses-01_T1w.nii.gz')

# Plot it
fig, axs = plt.subplots(3, 1)
for point_idx, label in enumerate(('LPA', 'NAS', 'RPA')):
    plot_anat(t1_nii_fname,
              axes=axs[point_idx],
              cut_coords=mri_pos[point_idx, :],
              title=label)
plt.show()

###############################################################################
# We can deface the MRI for anonymization by passing ``deface=True``.
t1w_bids_path = write_anat(
    t1w=t1_mgh_fname,  # path to the MRI scan
    bids_path=bids_path,
    raw=raw,  # the raw MEG data file connected to the MRI
    trans=trans,  # our transformation matrix
    deface=True,
    overwrite=True,
    verbose=True  # this will print out the sidecar file
)
anat_dir = t1w_bids_path.directory
# Import image processing tool for basic processing of functional brain image
from nilearn import image

# Compute voxel-wise mean functional image across time dimension. Now we have
# functional image in 3D assigned in mean_haxby_img
mean_haxby_img = image.mean_img(haxby_func_filename)

########################################
# Now let us see how to use `add_edges`, method useful for checking
# coregistration by overlaying anatomical image as edges (red) on top of
# mean functional image (background), both being of same subject.

# First, we call the `plot_anat` plotting function, with a background image
# as first argument, in this case the mean fMRI image.
display = plotting.plot_anat(mean_haxby_img, title="add_edges")

# We are now able to use add_edges method inherited in plotting object named as
# display. First argument - anatomical image  and by default edges will be
# displayed as red 'r', to choose different colors green 'g' and  blue 'b'.
display.add_edges(haxby_anat_filename)

########################################
# Plotting outline of the mask (red) on top of the mean EPI image with
# `add_contours`. This method is useful for region specific interpretation
# of brain images

# As seen before, we call the `plot_anat` function with a background image
# as first argument, in this case again the mean fMRI image and argument
# `cut_coords` as list for manual cut with coordinates pointing at masked
# brain regions
    group_means = math_img(
        'img * (np.sum(img!=0, axis=-1)>=(img.shape[-1]/2.))[..., None]',
        img=group_means)

    # Create tsnr mean map
    group_img = math_img('np.mean(img, axis=-1)', img=group_means)
    group_img.to_filename('%s/group_tsnr%s.nii.gz' % (res_path, method))

    # Plot figure
    display = plot_anat(
        group_img,
        display_mode='xz',
        cut_coords=[-20, 10],
        colorbar=False,
        cmap='magma',
        threshold=800,
        vmin=800,
        vmax=3200,
        dim=1,
        annotate=False,
        draw_cross=False,
        black_bg=True,
    )
    img_tmp = nb.load(template_gm)
    display.savefig('%s/group_tsnr_%s.svg' % (res_path, method))

    tsnr_values.append([method, group_img.get_data()])

# Plot histograms of voxel distribution above threshold
sns.set_style('darkgrid')
plt.style.use('seaborn-colorblind')
threshold = 1
Пример #37
0
def _nilearn_display(input_file, edge_file, overlay_file, contour_file,
                     name, overlay_cmap, cut_coords, display_mode,
                     lowerbound, upperbound, figsize):
    """ Create a nice dispaly with nilearn.
    """
    # Monkey patch the 'find_cut_coords' class method in case of int
    # 'cut_coords'
    if isinstance(cut_coords, numbers.Number):
        def monkeypatch(cls):
            def decorator(func):
                setattr(cls, func.__name__, types.MethodType(func, cls))
                return func
            return decorator

        @monkeypatch(plotting.displays.SLICERS[display_mode])
        def find_cut_coords(cls, img=None, threshold=None, cut_coords=None):
            """ Instanciate the slicer and find cut coordinates.
            """
            # Fig size
            cls._default_figsize = list(figsize)

            # Translation
            direction = cls._direction
            n_cuts = cut_coords

            # Misc
            if direction not in "xyz":
                raise ValueError(
                    "'direction' must be one of 'x', 'y', or 'z'. Got '%s'" % (
                        direction))
            affine = img.get_affine()

            # Compute slice location in physical space
            cut_coords = numpy.unique(
                numpy.linspace(lowerbound, upperbound, n_cuts, dtype=int))

            return plotting.find_cuts._transform_cut_coords(
                cut_coords, direction, affine)
    else:
        plotting.displays.SLICERS[display_mode]._default_figsize = list(
            figsize)

    # Create the renderer
    display = plotting.plot_anat(
        input_file, title=name or "", cut_coords=cut_coords,
        display_mode=display_mode)
    if edge_file is not None:
        display.add_edges(edge_file)
    if overlay_file is not None:
        # Create a custom discrete colormap
        norm = None
        if isinstance(overlay_cmap, numpy.ndarray):
            cmap = colors.ListedColormap(overlay_cmap.tolist())
            # cmap.set_over((1., 0., 0., 1.))
            # cmap.set_under((1., 0., 0., 1.))
            bounds = numpy.asarray(range(overlay_cmap.shape[0] + 1)) - 0.5
            norm = BoundaryNorm(bounds, cmap.N)
            # m = cm.ScalarMappable(cmap=cmap, norm=norm)
            # print(m.to_rgba(41), m.to_rgba(214))
        elif overlay_cmap in dir(plotting.cm):
            cmap = getattr(plotting.cm, overlay_cmap)
        elif overlay_cmap in dir(cm):
            cmap = cm.get_cmap(overlay_cmap)
        # Default
        else:
            cmap = plotting.cm.alpha_cmap((1, 1, 0))
        display.add_overlay(overlay_file, cmap=cmap, norm=norm)
    if contour_file is not None:
        display.add_contours(contour_file, alpha=0.6, filled=True,
                             linestyles="solid")
    return display
Пример #38
0
# 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 = np.round(k_slice)

fig = plt.figure(figsize=(4, 5.4), facecolor='k')

from nilearn.plotting import plot_anat, show
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],
Пример #39
0
def plot_registration(anat_nii, div_id, plot_params=None,
                      order=('z', 'x', 'y'), cuts=None,
                      estimate_brightness=False, label=None, contour=None,
                      compress='auto'):
    """
    Plots the foreground and background views
    Default order is: axial, coronal, sagittal
    """
    plot_params = {} if plot_params is None else plot_params

    # Use default MNI cuts if none defined
    if cuts is None:
        raise NotImplementedError  # TODO

    out_files = []
    if estimate_brightness:
        plot_params = robust_set_limits(anat_nii.get_data().reshape(-1),
                                        plot_params)

    # FreeSurfer ribbon.mgz
    ribbon = contour is not None and np.array_equal(
        np.unique(contour.get_data()), [0, 2, 3, 41, 42])

    if ribbon:
        contour_data = contour.get_data() % 39
        white = nlimage.new_img_like(contour, contour_data == 2)
        pial = nlimage.new_img_like(contour, contour_data >= 2)

    # Plot each cut axis
    for i, mode in enumerate(list(order)):
        plot_params['display_mode'] = mode
        plot_params['cut_coords'] = cuts[mode]
        if i == 0:
            plot_params['title'] = label
        else:
            plot_params['title'] = None

        # Generate nilearn figure
        display = plot_anat(anat_nii, **plot_params)
        if ribbon:
            kwargs = {'levels': [0.5], 'linewidths': 0.5}
            display.add_contours(white, colors='b', **kwargs)
            display.add_contours(pial, colors='r', **kwargs)
        elif contour is not None:
            display.add_contours(contour, colors='b', levels=[0.5],
                                 linewidths=0.5)

        svg = extract_svg(display, compress=compress)
        display.close()

        # Find and replace the figure_1 id.
        try:
            xml_data = etree.fromstring(svg)
        except etree.XMLSyntaxError as e:
            NIWORKFLOWS_LOG.info(e)
            return
        find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
        find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))

        svg_fig = SVGFigure()
        svg_fig.root = xml_data
        out_files.append(svg_fig)

    return out_files
Пример #40
0
def nilearn_snapshot(inputfile,
                     outdir,
                     overlayfile=None,
                     basename="nilearn_snap",
                     mask_alpha=50,
                     cmap=None,
                     mask_cmap=None,
                     dr=None,
                     mask_dr=None,
                     black_bg=True):
    """ Create a tri-view snapshot with one overlay.

    Parameters
    ----------
    inputfile: str
        path to the input image to snap.
    outdir: str
        directoy where to output.
    overlayfile: str, default None
        path to the image to overlay.
    basename: str, default 'nilearn_snap'
        basename without extension of the output snapshot.
    mask_alpha: int, default 50
        a overlay alpha value (0-100).
    cmap: str, default None
        a valid nilearn color map for the input file.
    mask_cmap: str, default None
        a valid nilearn color map for the mask file.
    dr: 2-uplet, default None
        athe display range (LO, HI) for the input file.
    mask_dr: 2-uplet, default None
        athe display range (LO, HI) for the mask file.
    black_bg: bool, default True
        If True, the background of the image is set to be black

    Return
    ------
    snap: str
        path to the output snapshot: <outdir>/<basename>.png
    """
    # Display the image
    kwargs = {}
    if cmap is not None:
        try:
            kwargs["cmap"] = getattr(plotting.cm, cmap)
        except:
            raise ValueError("Invalid color map '{0}'.".format(cmap))
    if dr is not None:
        kwargs["vmin"] = dr[0]
        kwargs["vmax"] = dr[1]
    display = plotting.plot_anat(inputfile,
                                 black_bg=black_bg,
                                 draw_cross=False,
                                 **kwargs)

    # Add the overlay
    if overlayfile is not None:
        kwargs = {}
        if mask_cmap is not None:
            try:
                kwargs["cmap"] = getattr(plotting.cm, mask_cmap)
            except:
                raise ValueError("Invalid color map '{0}'.".format(mask_cmap))
        if mask_dr is not None:
            kwargs["vmin"] = mask_dr[0]
            kwargs["vmax"] = mask_dr[1]
        if mask_alpha is not None:
            kwargs["alpha"] = mask_alpha / 100.
        display.add_overlay(inputfile, **kwargs)

    # Save the result
    snap = os.path.join(outdir, basename + ".png")
    display.savefig(snap)
    display.close()

    return snap
Пример #41
0
import os
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
from nilearn.plotting import plot_anat

# Directory where your data set resides.
dataDir = '/tmp/Data/ds102'

# reading in the T1 image data array
f_sMRI = os.path.join(dataDir, 'sub-26/anat/sub-26_T1w.nii.gz')
sMRI = nib.load(f_sMRI)
X_sMRI = sMRI.get_data()

# displaying image
plot_anat(f_sMRI, display_mode='ortho', dim=-1, draw_cross=True, annotate=True)

# average intensity in the x-direction
avgX_X_sMRI = X_sMRI.mean(axis=0)

# showing the resulting image
plt.imshow(np.rot90(avgX_X_sMRI), cmap='gray')
plt.axis('off')
Пример #42
0
###############################################################################
# Apply transformations and plot

# morph img data
img_sdr_affine = mapping.transform(affine.transform(img))

# make transformed ndarray a nifti
img_vol_sdr_affine = nib.Nifti1Image(img_sdr_affine, affine=t1_s_grid2world)

# save morphed grid
nib.save(img_vol_sdr_affine, 'lcmv_inverse_fsavg.nii.gz')

# plot result
imgs = [img_vol_first, img_vol_first, nib.load('lcmv_inverse_fsavg.nii.gz')]

t1_imgs = [t1_m_img, t1_s_img, t1_s_img]

titles = [
    'subject brain', 'fsaverage brian', 'fsaverage brian\nmorphed source'
]

saveas = [
    'lcmv_subject.png', 'lcmv_fsaverage.png', 'lcmv_fsaverage_morphed.png'
]

for img, t1_img, title, fname in zip(imgs, t1_imgs, titles, saveas):
    display = plot_anat(t1_img, display_mode='x', title=title)
    display.add_overlay(img)
    display.savefig(fname)
    display.close()
Пример #43
0
        path = opj(folder, path)

        #print path, display_mode, cut_coords

        data = nb.load(path).get_data().flatten()
        data = sorted(data[~np.isnan(data)])
        vmax = data[int(len(data) * 0.99)]
        #print vmax

        #title = names of plotted files
        title = '  <- edges:  '.join([
            e.split()[0].split('/')[-1].split('.nii.gz')[0] for e in elements
        ])
        display = plotting.plot_anat(path,
                                     vmin=0,
                                     vmax=vmax,
                                     display_mode=display_mode,
                                     cut_coords=int(cut_coords),
                                     title=title)

        #print elements
        for element in elements[1:]:
            #print
            path = element.split()[0]
            path = opj(folder, path)
            #print element, 'path = ', path
            #display.add_edges(path)
            verb = verbs.pop(0)
            #print verb
            if verb == 'add_contours':
                display.add_contours(path, levels=[0.5, 6500], colors='r')
                display.add_contours(path, levels=[5000], colors='g')
Пример #44
0
def plot_registration(anat_nii,
                      div_id,
                      plot_params=None,
                      order=('z', 'x', 'y'),
                      cuts=None,
                      estimate_brightness=False,
                      label=None,
                      contour=None,
                      compress='auto'):
    """
    Plot the foreground and background views.

    Default order is: axial, coronal, sagittal
    """
    from uuid import uuid4

    from lxml import etree
    from nilearn.plotting import plot_anat
    from svgutils.transform import SVGFigure
    from niworkflows.viz.utils import robust_set_limits, extract_svg, SVGNS

    plot_params = plot_params or {}

    # Use default MNI cuts if none defined
    if cuts is None:
        raise NotImplementedError  # TODO

    out_files = []
    if estimate_brightness:
        plot_params = robust_set_limits(anat_nii.get_data().reshape(-1),
                                        plot_params)

    # Plot each cut axis
    for i, mode in enumerate(list(order)):
        plot_params['display_mode'] = mode
        plot_params['cut_coords'] = cuts[mode]
        if i == 0:
            plot_params['title'] = label
        else:
            plot_params['title'] = None

        # Generate nilearn figure
        display = plot_anat(anat_nii, **plot_params)
        if contour is not None:
            display.add_contours(contour,
                                 colors='g',
                                 levels=[0.5],
                                 linewidths=0.5)

        svg = extract_svg(display, compress=compress)
        display.close()

        # Find and replace the figure_1 id.
        xml_data = etree.fromstring(svg)
        find_text = etree.ETXPath("//{%s}g[@id='figure_1']" % SVGNS)
        find_text(xml_data)[0].set('id', '%s-%s-%s' % (div_id, mode, uuid4()))

        svg_fig = SVGFigure()
        svg_fig.root = xml_data
        out_files.append(svg_fig)

    return out_files
Пример #45
0
# Affine registration
# -------------------
from sammba.registration import anats_to_common

affine_register = anats_to_common(retest.anat, write_dir, caching=True)

##############################################################################
# We set caching to True, so that this step computations are not restarted.
# The paths to the registered images can be accessed easilly
registered_anats = affine_register.registered
print(registered_anats)

##############################################################################
# Visalize results
# ----------------
# We plot the edges of one individual anat on top of the average image
from nilearn import plotting, image

average_img = image.mean_img(registered_anats)
display = plotting.plot_anat(average_img, dim=-1.8, title='affine register')
display.add_edges(registered_anats[0])
plotting.show()

##############################################################################
# Visualize pipeline steps
# -------------------------
from sammba.registration import create_pipeline_graph

graph_file = os.path.join(write_dir, 'affine_registration_graph')
create_pipeline_graph('anats_to_common_affine', graph_file)
Пример #46
0
localizer = datasets.fetch_localizer_contrasts(["left vs right button press"],
                                               n_subjects=4,
                                               get_anats=True)


###############################################################################
# demo the different plotting function

# Plotting statistical maps
plotting.plot_stat_map(localizer.cmaps[3], bg_img=localizer.anats[3],
                       threshold=3, title="plot_stat_map",
                       cut_coords=(36, -27, 66))

# Plotting anatomical maps
plotting.plot_anat(haxby.anat[0], title="plot_anat")

# Plotting ROIs (here the mask)
plotting.plot_roi(haxby.mask_vt[0], bg_img=haxby.anat[0], title="plot_roi")

# Plotting EPI haxby
mean_haxby_img = image.mean_img(haxby.func[0])
plotting.plot_epi(mean_haxby_img, title="plot_epi")


###############################################################################
# demo the different display_mode

plotting.plot_stat_map(localizer.cmaps[3], display_mode='ortho',
                       cut_coords=(36, -27, 60),
                       title="display_mode='ortho', cut_coords=(36, -27, 60)")
Пример #47
0
#
# .. 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
# Loop through all the slices in this dimension
for i in np.arange(img_reslice.shape[dim_lookup_dict[axis]], dtype='float'):

    # Test to see if there is anything worth showing in the image
    # If the anat image (img) is empty then don't make a picture
    if slice_dict[axis](i, img).mean() == 0.0:
        continue

    # Get the co-ordinate you want
    coord = coord_transform_dict[axis](i, img_reslice)

    # Make the image
    slicer = plotting.plot_anat(img_reslice,
                                threshold=None,
                                cmap=cmap,
                                display_mode=axis,
                                black_bg=black_bg,
                                annotate=annotate,
                                draw_cross=draw_cross,
                                cut_coords=(coord,))

    # Add the overlay if given
    if not overlay_file is None:
        slicer.add_overlay(overlay_img_reslice, cmap=overlay_cmap)

    # Save the png file
    output_file = os.path.join(pngs_dir,
                       '{}_{:03.0f}{}.png'.format(label_lookup_dict[axis],
                                                    i,
                                                    overlay_name))

    slicer.savefig(output_file, dpi=dpi)
Пример #49
0
"""
Docstring.
"""
from nidata.multimodal import MyConnectome2015Dataset

# runs the member function 'fetch' from the class 'Laumann2015Dataset'
dataset = MyConnectome2015Dataset().fetch(data_types=['functional'],
                                          session_ids=range(2, 13))
print(dataset)

from nilearn.plotting import plot_anat
from nilearn.image import index_img
from matplotlib import pyplot as plt

plot_anat(index_img(dataset['functional'][0], 0))
plt.show()
Пример #50
0
subject = 'sample'
mni_pos = dip.to_mni(subject=subject, trans=fname_trans,
                     subjects_dir=subjects_dir)

mri_pos = dip.to_mri(subject=subject, trans=fname_trans,
                     subjects_dir=subjects_dir)

# Find an anatomical label for the best fitted dipole
best_dip_idx = dip.gof.argmax()
label = dip.to_volume_labels(fname_trans, subject=subject,
                             subjects_dir=subjects_dir,
                             aseg='aparc.a2009s+aseg')[best_dip_idx]

# Draw dipole position on MRI scan and add anatomical label from parcellation
t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')
fig_T1 = plot_anat(t1_fname, cut_coords=mri_pos[0],
                   title=f'Dipole location: {label}')

try:
    template = load_mni152_template(resolution=1)
except TypeError:  # in nilearn < 0.8.1 this did not exist
    template = load_mni152_template()
fig_template = plot_anat(template, cut_coords=mni_pos[0],
                         title='Dipole loc. (MNI Space)')

# %%
# Calculate and visualise magnetic field predicted by dipole with maximum GOF
# and compare to the measured data, highlighting the ipsilateral (right) source
fwd, stc = make_forward_dipole(dip, fname_bem, evoked.info, fname_trans)
pred_evoked = simulate_evoked(fwd, stc, evoked.info, cov=None, nave=np.inf)

# find time point with highest GOF to plot
# 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")
Пример #52
0
# Compute voxel-wise mean functional image across time dimension. Now we have
# functional image in 3D assigned in mean_haxby_img
mean_haxby_img = image.mean_img(haxby_func_filename)

########################################
# Showing how to use `add_edges`
# ------------------------------
# Now let us see how to use `add_edges`, method useful for checking
# coregistration by overlaying anatomical image as edges (red) on top of
# mean functional image (background), both being of same subject.

# First, we call the `plot_anat` plotting function, with a background image
# as first argument, in this case the mean fMRI image.

display = plotting.plot_anat(mean_haxby_img, title="add_edges")

# We are now able to use add_edges method inherited in plotting object named as
# display. First argument - anatomical image  and by default edges will be
# displayed as red 'r', to choose different colors green 'g' and  blue 'b'.
display.add_edges(haxby_anat_filename)

########################################
# How to use `add_contours`
# -------------------------
# Plotting outline of the mask (red) on top of the mean EPI image with
# `add_contours`. This method is useful for region specific interpretation
# of brain images

# As seen before, we call the `plot_anat` function with a background image
# as first argument, in this case again the mean fMRI image and argument
Пример #53
0
# 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()
Пример #54
0
def plot_image(input_file, edge_file=None, overlay_file=None, contour_file=None,
               snap_file=None, name=None, overlay_cmap=None,
               cut_coords=None):
    """ Plot image with edge/overlay/contour on top (useful for checking
    registration).

    Parameters
    ----------
    input_file: str (mandatory)
        An image to display.
    outline_file: str (optional, default None)
        The target image to extract the edges from.
    snap_file: str (optional, default None)
        The destination file: if not specified will be the 'input_file'
        name with a 'png' extension.
    name: str (optional, default None)
        The name of the plot.
    overlay_cmap: str (optional, default None)
        The color map to use: 'cold_hot' or 'blue_red' or None,
        or a N*4 array with values in 0-1 (r, g, b, a).
    cut_coords: 3-uplet (optional, default None)
        The MNI coordinates of the point where the cut is performed.
        If None is given, the cuts is calculated automaticaly.

    Returns
    -------
    snap_file: str
        A pdf snap of the image.
    """
    # 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))

    # Check that the snap_file has been specified
    if snap_file is None:
        snap_file = input_file.split(".")[0] + ".png"

    # Create the plot
    display = plotting.plot_anat(input_file, title=name or "",
                                 cut_coords=cut_coords)
    if edge_file is not None:
        display.add_edges(edge_file)
    if overlay_file is not None:

        # Create a custom discrete colormap
        if isinstance(overlay_cmap, numpy.ndarray):
            cmap = colors.LinearSegmentedColormap.from_list(
                "my_colormap", overlay_cmap)
            #cmap, _ = colors.from_levels_and_colors(
            #    range(overlay_cmap.shape[0] + 1), overlay_cmap)
        # This is probably a matplotlib colormap
        elif overlay_cmap in dir(plotting.cm):
            cmap = getattr(plotting.cm, overlay_cmap)
        # Default
        else:
            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
Пример #55
0
>>> def show_slices(slices):
...    """ Function to display row of image slices """
...    fig, axes = plt.subplots(1, len(slices))
...    for i, slice in enumerate(slices):
...        axes[i].imshow(slice.T, cmap="gray", origin="lower")
>>>

#遍历序列和下标  enumerate
for i,value in enumerate(some_array)

#显示图像
slice0 = img_data[2,:,:]

slice1 = img_data[:,2,:]

slice2 = img_data[:,:,3]

  ([slice0,slice2,slice2])

#或者使用nilearn提供的方法
from nilearn import plotting
cut_coords = [2,2,2]
plotting.plot_anat(img,cut_coords=cut_coords,title='标题')

#直接将某个矩阵保存成图像
from scipy.misc import imsave
imsave("aa1.png",slice1)

#在nilearn中,一个3-D图像的list可以当作一个4-D图像

Пример #56
0
# In MRI coordinates and in MNI coordinates (template brain)

trans = mne.read_trans(fname_trans)
subject = 'sample'
mni_pos = mne.head_to_mni(dip.pos,
                          mri_head_t=trans,
                          subject=subject,
                          subjects_dir=subjects_dir)

mri_pos = mne.head_to_mri(dip.pos,
                          mri_head_t=trans,
                          subject=subject,
                          subjects_dir=subjects_dir)

t1_fname = op.join(subjects_dir, subject, 'mri', 'T1.mgz')
fig = plot_anat(t1_fname, cut_coords=mri_pos[0], title='Dipole loc.')

template = load_mni152_template()
fig = plot_anat(template,
                cut_coords=mni_pos[0],
                title='Dipole loc. (MNI Space)')

###############################################################################
# Calculate and visualise magnetic field predicted by dipole with maximum GOF
# and compare to the measured data, highlighting the ipsilateral (right) source
fwd, stc = make_forward_dipole(dip, fname_bem, evoked.info, fname_trans)
pred_evoked = simulate_evoked(fwd, stc, evoked.info, cov=None, nave=np.inf)

# find time point with highest GOF to plot
best_idx = np.argmax(dip.gof)
best_time = dip.times[best_idx]
Пример #57
0
# We will dive deeper into affine transformations in the preprocessing tutorial.

# ## Plotting Data with Nilearn
# There are many useful tools from the [nilearn](https://nilearn.github.io/index.html) library to help manipulate and visualize neuroimaging data. See their [documentation](https://nilearn.github.io/plotting/index.html#different-plotting-functions) for an example.
#
# In this section, we will explore a few of their different plotting functions, which can work directly with nibabel instances.

# In[32]:

get_ipython().run_line_magic('matplotlib', 'inline')

from nilearn.plotting import view_img, plot_glass_brain, plot_anat, plot_epi

# In[33]:

plot_anat(data)

# Nilearn plotting functions are very flexible and allow us to easily customize our plots

# In[34]:

plot_anat(data, draw_cross=False, display_mode='z')

# try to get more information how to use the function with `?` and try to add different commands to change the plot.
#
# nilearn also has a neat interactive viewer called `view_img` for examining images directly in the notebook.

# In[35]:

view_img(data)
                      colorbar=True,
                      annotate=False,
                      draw_cross=False)

############################################################################
# .. image:: ../_static/tissue_classification2.png
#############################################################################

############################################################################
# MGDM also creates an image which represents for each voxel the distance to
# its nearest border. It is useful to assess where partial volume effects
# may occur
if not skip_plots:
    plotting.plot_anat(mgdm_results['distance'],
                       vmin=0,
                       vmax=20,
                       annotate=False,
                       draw_cross=False,
                       colorbar=True)

############################################################################
# .. image:: ../_static/tissue_classification3.png
#############################################################################

#############################################################################
# If the example is not run in a jupyter notebook, render the plots:
if not skip_plots:
    plotting.show()

#############################################################################
# References
# -----------
functional.
"""
# Create a memory context
from nipype.caching import Memory
mem = Memory('/tmp')

# Compute mean functional
from procasl import preprocessing
average = mem.cache(preprocessing.Average)
out_average = average(in_file='/tmp/func.nii')
mean_func = out_average.outputs.mean_file

# Coregister anat to mean functional
from nipype.interfaces import spm
coregister = mem.cache(spm.Coregister)
out_coregister = coregister(
    target=mean_func,
    source='/tmp/anat.nii',
    write_interp=3)

# Check coregistration
import matplotlib.pylab as plt
from nilearn import plotting
figure = plt.figure(figsize=(5, 4))
display = plotting.plot_anat(mean_func, figure=figure, display_mode='z',
                             cut_coords=(-7, 32),
                             title='anat edges on mean functional')
display.add_edges(out_coregister.outputs.coregistered_source)
figure.suptitle('Impact of tagging correction')
plt.show()
# First, we plot a network of index=4 without region extraction (left plot)
from nilearn import image

img = image.index_img(components_img, 1)
coords = plotting.find_xyz_cut_coords(img)
display = plotting.plot_stat_map(img,
                                 cut_coords=coords,
                                 colorbar=False,
                                 title='Showing one specific network')

################################################################################
# Now, we plot (right side) same network after region extraction to show that
# connected regions are nicely seperated.
# Each brain extracted region is identified as separate color.

# For this, we take the indices of the all regions extracted related to original
# network given as 4.
regions_indices_of_map3 = np.where(np.array(regions_index) == 1)

display = plotting.plot_anat(cut_coords=coords,
                             title='Regions from this network')

# Add as an overlay all the regions of index 4
colors = 'rgbcmyk'
for each_index_of_map3, color in zip(regions_indices_of_map3[0], colors):
    display.add_overlay(image.index_img(regions_extracted_img,
                                        each_index_of_map3),
                        cmap=plotting.cm.alpha_cmap(color))

plotting.show()