Exemplo n.º 1
0
def image_search(args=None):
    parser = _get_parser()
    args = parser.parse_args(args=args)
    img = args.query_img
    if img is None:
        img = datasets.fetch_neurovault_motor_task()["images"][0]
    try:
        image_name = Path(img).name
    except Exception:
        image_name = "Image"
    search = NeuroQueryImageSearch()
    results = search(img,
                     n_studies=args.n_studies,
                     n_terms=args.n_terms,
                     transform=args.transform,
                     rescale_similarities=(not args.no_rescaling))
    if args.output is None:
        results_to_html(results, image_name).open_in_browser()
        print("Displaying results in web browser")
        print("Use '--output' to write results in a file")
        return
    output_file = Path(args.output)
    print(f"Saving results in {output_file}")
    if output_file.suffix in [".html", ".htm"]:
        results_to_html(results, image_name).save_as_html(output_file)
        return
    results.pop("image")
    output_file.write_text(json.dumps(results, cls=_JSONEncoder))
def test_create_output(tmpdir):

    # create mock data
    motor_images = fetch_neurovault_motor_task()
    stat_img = motor_images.images[0]
    stat_img_name = os.path.basename(stat_img)[:-7]

    # temporary output
    output_dir = tmpdir.mkdir('mni_test')

    atlas_reader.create_output(stat_img,
                               atlas=['Harvard_Oxford'],
                               outDir=output_dir)

    # test if output exists and if the key .csv and .png files were created
    assert os.path.exists(output_dir)
    assert len(os.listdir(output_dir)) > 0
    assert os.path.isfile(
        os.path.join(output_dir, '{}.csv'.format(stat_img_name)))
    assert os.path.isfile(
        os.path.join(output_dir, '{}.png'.format(stat_img_name)))
"""

###############################################################################
# First, we retrieve data from nilearn provided (general-purpose) datasets
# -------------------------------------------------------------------------

from nilearn import datasets

# haxby dataset to have anatomical image, EPI images and masks
haxby_dataset = datasets.fetch_haxby()
haxby_anat_filename = haxby_dataset.anat[0]
haxby_mask_filename = haxby_dataset.mask_vt[0]
haxby_func_filename = haxby_dataset.func[0]

# localizer dataset to have contrast maps
motor_images = datasets.fetch_neurovault_motor_task()
stat_img = motor_images.images[0]

###############################################################################
# Now, we show from here how to visualize the retrieved datasets using plotting
# tools from nilearn.

from nilearn import plotting

###############################################################################
# Visualizing in - 'sagittal', 'coronal' and 'axial' with given coordinates
# -------------------------------------------------------------------------
#
# The first argument ``stat_img`` is a path to the filename of a contrast map.
# The optional argument ``display_mode`` is given as a string 'ortho' to
# visualize the map in three specific directions xyz. Because of this, the
# Statistical maps
# ================

######################################################################
# Download and plot an individual-level statistical map and plot it on the
# subject's T1 image:

from nilearn import datasets, plotting
localizer = datasets.fetch_localizer_button_task()
plotting.view_img(localizer['tmap'], bg_img=localizer['anat'], threshold='97%')


######################################################################
# Download and plot a group-level statistical map:

img = datasets.fetch_neurovault_motor_task()['images'][0]
plotting.view_img(img, threshold='95%')


######################################################################
# More about dataset downloaders: https://nilearn.github.io/modules/reference.html#module-nilearn.datasets
#
# More about plotting: https://nilearn.github.io/plotting/index.html

######################################################################
# Static plots that can be saved in a variety of formats:

plotting.plot_stat_map(img, threshold=3)


######################################################################
Exemplo n.º 5
0
===============================

The goal of this example is to illustrate the use of the function
:func:`nilearn.image.resample_to_img` to resample an image to a template.
We use the MNI152 template as the reference for resampling a t-map image.
Function :func:`nilearn.image.resample_img` could also be used to achieve this.
"""

###############################################################################
# First we load the required datasets using the nilearn datasets module.
from nilearn.datasets import fetch_neurovault_motor_task
from nilearn.datasets import load_mni152_template

template = load_mni152_template()

motor_images = fetch_neurovault_motor_task()
stat_img = motor_images.images[0]

###############################################################################
# Now, the localizer t-map image can be resampled to the MNI template image.
from nilearn.image import resample_to_img

resampled_stat_img = resample_to_img(stat_img, template)

###############################################################################
# Let's check the shape and affine have been correctly updated.

# First load the original t-map in memory:
from nilearn.image import load_img
tmap_img = load_img(stat_img)
Exemplo n.º 6
0
import os
import numpy as np
from atlasreader import atlasreader
import nibabel as nb
from nilearn.datasets import fetch_neurovault_motor_task
import pytest
import pandas as pd

STAT_IMG = fetch_neurovault_motor_task().images[0]
EXAMPLE_COORDS = dict(affine=np.array([[1, 0, 0, -90], [0, 1, 0, -150],
                                       [0, 0, 1, -80], [0, 0, 0, 1]]),
                      coords=[
                          dict(ijk=[0, 0, 0], xyz=np.array([[-90, -150,
                                                             -80]])),
                          dict(ijk=[[10, 10, 10], [100, 50, 100]],
                               xyz=np.array([[-80, -140, -70], [10, -100,
                                                                20]])),
                          dict(ijk=[[54, 32, 20], [82, 205, 38], [32, 51, 82]],
                               xyz=np.array([[-36, -118, -60], [-8, 55, -42],
                                             [-58, -99, 2]]))
                      ],
                      bad_coords=[
                          dict(ijk_in=np.array([80, 80, 80]),
                               ijk_out=np.array([80, 80, 80])),
                          dict(ijk_in=np.array([-1, 0, 0]),
                               ijk_out=np.array([0, 0, 0])),
                          dict(ijk_in=np.array([80, 80, 100]),
                               ijk_out=np.array([0, 0, 0]))
                      ],
                      bounding_shape=np.array([90, 90, 90]))
EXPECTED_TABLES = dict(cluster=np.array([[42, -25, 58, 6.66003, 36936],
###############################################################################
# Retrieve the data
# ------------------
#
# Nilearn comes with set of functions that download public data from Internet
#
# Let us first see where the data will be downloded and stored on our disk:
#
from nilearn import datasets
print('Datasets shipped with nilearn are stored in: %r' % datasets.get_data_dirs())

###############################################################################
# Let us now retrieve a motor task contrast map
# corresponding to a group one-sample t-test

motor_images = datasets.fetch_neurovault_motor_task()
stat_img = motor_images.images[0]
# stat_img is just the name of the file that we downloded
print(stat_img)

###############################################################################
# Demo glass brain plotting
# --------------------------
from nilearn import plotting

# Whole brain sagittal cuts and map is thresholded at 3
plotting.plot_glass_brain(stat_img, threshold=3)


###############################################################################
# With a colorbar
Exemplo n.º 8
0
 def __init__(self, indice=0):
     from nilearn import datasets
     motor_images = datasets.fetch_neurovault_motor_task()
     self.dataset = motor_images.images[indice]
Exemplo n.º 9
0
}


def plot_surf(mesh, data, view="right", threshold="85%", output_file=None):
    coords, triangles = surface.load_surf_mesh(mesh)
    x, y, z = coords.T
    i, j, k = triangles.T
    colors = colorscale(cold_hot, data, threshold)
    vertexcolor = _get_vertexcolor(
        data,
        colors["cmap"],
        colors["norm"],
        colors["abs_threshold"],
        surface.load_surf_data(fsaverage["sulc_right"]),
    )
    mesh_3d = go.Mesh3d(x=x, y=y, z=z, i=i, j=j, k=k, vertexcolor=vertexcolor)
    fig = go.Figure(data=[mesh_3d])
    fig.update_layout(scene_camera=CAMERAS[view], **LAYOUT)
    if output_file is not None:
        fig.write_image(output_file)
    return fig


if __name__ == "__main__":
    img = datasets.fetch_neurovault_motor_task()["images"][0]
    fsaverage = datasets.fetch_surf_fsaverage()
    mesh = fsaverage["pial_right"]
    data = surface.vol_to_surf(img, fsaverage["pial_right"])
    fig = plot_surf(mesh, data, output_file="/tmp/surface_plot.png")
    fig.show()