How to use the nilearn.image.new_img_like function in nilearn

To help you get started, we’ve selected a few nilearn examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ellisdg / 3DUnetCNN / unet3d / normalize.py View on Github external
def get_complete_foreground(training_data_files):
    for i, set_of_files in enumerate(training_data_files):
        subject_foreground = get_foreground_from_set_of_files(set_of_files)
        if i == 0:
            foreground = subject_foreground
        else:
            foreground[subject_foreground > 0] = 1

    return new_img_like(read_image(training_data_files[0][-1]), foreground)
github IntelAI / models / models / image_segmentation / tensorflow / 3d_unet / inference / fp32 / unet3d / augment.py View on Github external
def scale_image(image, scale_factor):
    scale_factor = np.asarray(scale_factor)
    new_affine = np.copy(image.affine)
    new_affine[:3, :3] = image.affine[:3, :3] * scale_factor
    new_affine[:, 3][:3] = image.affine[:, 3][:3] + (image.shape * np.diag(image.affine)[:3] * (1 - scale_factor)) / 2
    return new_img_like(image, data=image.get_data(), affine=new_affine)
github poldracklab / niworkflows / niworkflows / interfaces / freesurfer.py View on Github external
def inject_skullstripped(subjects_dir, subject_id, skullstripped):
    mridir = op.join(subjects_dir, subject_id, "mri")
    t1 = op.join(mridir, "T1.mgz")
    bm_auto = op.join(mridir, "brainmask.auto.mgz")
    bm = op.join(mridir, "brainmask.mgz")

    if not op.exists(bm_auto):
        img = nb.load(t1)
        mask = nb.load(skullstripped)
        bmask = new_img_like(mask, np.asanyarray(mask.dataobj) > 0)
        resampled_mask = resample_to_img(bmask, img, "nearest")
        masked_image = new_img_like(
            img, np.asanyarray(img.dataobj) * resampled_mask.dataobj
        )
        masked_image.to_filename(bm_auto)

    if not op.exists(bm):
        copyfile(bm_auto, bm, copy=True, use_hardlink=True)

    return subjects_dir, subject_id
github nilearn / nilearn / nilearn / plotting / img_plotting.py View on Github external
if img is not False and img is not None:
        img = _utils.check_niimg_3d(img, dtype='auto')
        data = _safe_get_data(img, ensure_finite=True)
        affine = img.affine

        if np.isnan(np.sum(data)):
            data = np.nan_to_num(data)

        # Deal with automatic settings of plot parameters
        if threshold == 'auto':
            # Threshold epsilon below a percentile value, to be sure that some
            # voxels pass the threshold
            threshold = fast_abs_percentile(data) - 1e-5

        img = new_img_like(img, as_ndarray(data), affine)

    display = display_factory(display_mode)(
        img,
        threshold=threshold,
        cut_coords=cut_coords,
        figure=figure, axes=axes,
        black_bg=black_bg,
        colorbar=colorbar,
        brain_color=brain_color,
        )

    if bg_img is not None:
        bg_img = _utils.check_niimg_3d(bg_img)
        display.add_overlay(bg_img,
                            vmin=bg_vmin, vmax=bg_vmax,
                            cmap=plt.cm.gray, interpolation=interpolation)
github ellisdg / 3DUnetCNN / unet3d / augment.py View on Github external
def scale_image(image, scale_factor):
    scale_factor = np.asarray(scale_factor)
    new_affine = np.copy(image.affine)
    new_affine[:3, :3] = image.affine[:3, :3] * scale_factor
    new_affine[:, 3][:3] = image.affine[:, 3][:3] + (image.shape * np.diag(image.affine)[:3] * (1 - scale_factor)) / 2
    return new_img_like(image, data=image.get_data(), affine=new_affine)
github nilearn / nilearn / examples / 04_manipulating_images / plot_roi_extraction.py View on Github external
# voxels across the brain. To consolidate such brain images towards more compact
# shapes, we use a `morphological dilation
# `_. This is a common step
# to be sure not to forget voxels located on the edge of a ROI. In other words,
# such operations can fill "holes" in masked voxel representations.

# We use ndimage function from scipy Python library for mask dilation
from scipy import ndimage

# Input here is a binarized and intersected mask data from previous section
dil_bin_p_values_and_vt = ndimage.binary_dilation(bin_p_values_and_vt)

# Now, we visualize the same using `plot_roi` with data being converted to Nifti
# image. In all new image like, reference image is the same but second argument
# varies with data specific
dil_bin_p_values_and_vt_img = new_img_like(
    fmri_img,
    dil_bin_p_values_and_vt.astype(np.int))
# Visualization goes here without 'L', 'R' annotation and coordinates being the
# same
plot_roi(dil_bin_p_values_and_vt_img, mean_img,
         title='Dilated mask', cut_coords=cut_coords,
         annotate=False)
#############################################################################
# Finally, we end with splitting the connected ROIs to two hemispheres into two
# separate regions (ROIs). The function `scipy.ndimage.label` from the scipy
# Python library.

##############################################################################
# **Identification of connected components** - The function
# :func:`scipy.ndimage.label` from the scipy Python library identifies
# immediately neighboring voxels in our voxels mask. It assigns a separate
github ellisdg / 3DUnetCNN / unet3d / utils / utils.py View on Github external
def resize(image, new_shape, interpolation="linear"):
    image = reorder_img(image, resample=interpolation)
    zoom_level = np.divide(new_shape, image.shape)
    new_spacing = np.divide(image.header.get_zooms(), zoom_level)
    new_data = resample_to_spacing(image.get_data(), image.header.get_zooms(), new_spacing,
                                   interpolation=interpolation)
    new_affine = np.copy(image.affine)
    np.fill_diagonal(new_affine, new_spacing.tolist() + [1])
    new_affine[:3, 3] += calculate_origin_offset(new_spacing, image.header.get_zooms())
    return new_img_like(image, new_data, affine=new_affine)
github GalDude33 / Fetal-MRI-Segmentation / fetal_net / utils / utils.py View on Github external
def resize(image, new_shape, interpolation="linear"):
    image = reorder_img(image, resample=interpolation)
    zoom_level = np.divide(new_shape, image.shape)
    new_spacing = np.divide(image.header.get_zooms(), zoom_level)
    new_data = resample_to_spacing(image.get_data(), image.header.get_zooms(), new_spacing,
                                   interpolation=interpolation)
    new_affine = np.copy(image.affine)
    np.fill_diagonal(new_affine, new_spacing.tolist() + [1])
    new_affine[:3, 3] += calculate_origin_offset(new_spacing, image.header.get_zooms())
    return new_img_like(image, new_data, affine=new_affine)
github poldracklab / niworkflows / niworkflows / viz / utils.py View on Github external
if cuts is None:
        raise NotImplementedError  # TODO

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

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

    if ribbon:
        contour_data = contour.get_fdata() % 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)
github nilearn / nilearn / nilearn / datasets / atlas.py View on Github external
`Lancaster JL, Rainey LH, Summerlin JL, Freitas CS, Fox PT, Evans AC, Toga
    AW, Mazziotta JC. Automated labeling of the human brain: A preliminary
    report on the development and evaluation of a forward-transform method. Hum
    Brain Mapp 5, 238-242, 1997.`
    """
    if level_name not in _TALAIRACH_LEVELS:
        raise ValueError('"level_name" should be one of {}'.format(
            _TALAIRACH_LEVELS))
    position = _TALAIRACH_LEVELS.index(level_name)
    atlas_file, labels_file = _get_talairach_all_levels(data_dir, verbose)
    atlas_img = check_niimg(atlas_file)
    with open(labels_file) as fp:
        labels = json.load(fp)[position][1]
    level_data = (get_data(atlas_img) >> 8 * position) & 255
    atlas_img = new_img_like(atlas_img, data=level_data)
    description = _get_dataset_descr(
        'talairach_atlas').decode('utf-8').format(level_name)
    return Bunch(maps=atlas_img, labels=labels, description=description)