Пример #1
0
def auto_crop(image, ):
    """Loads data.
    """
    nifti_img = nib.Nifti1Image(image, affine=np.eye(4))
    image_croped = nil_image.crop_img(nifti_img)

    volume = image_croped.get_data()

    return volume
Пример #2
0
def crop(img, ZOOM='N'):
    img = crop_img(img)  # crop it
    img = img.get_data()[:, :, :, 0]  # make it array
    # This is only to make the code exectuable on local machine.
    if ZOOM == 'Y':
        img = ndimage.zoom(img, 0.25, order=1, mode='reflect', prefilter=False)
        logging.info('Downsampling ON')
    else:
        pass
    return img
Пример #3
0
def crop_blackspace(ffVOL, ffOUT):
    """
    Crop blackspace in MRI volume.
    Will retain 1 voxel grid of zeros before the nonzero part. Will write
    output at ffOUT.


    Parameters
    ----------
    ffVOL: str
    ffOUT: str

    Returns
    -------
    None
    """
    img = ni.load_img(ffVOL)
    img = ni.crop_img(img, copy=True)
    img.to_filename(ffOUT)
Пример #4
0
def crop_nifti(input_img, ref_img):
    """

    :param input_img:
    :param crop_sagittal:
    :param crop_coronal:
    :param crop_axial:
    :return:
    """

    import nibabel as nib
    import os
    import numpy as np
    from nilearn.image import resample_img, crop_img, resample_to_img
    from nibabel.spatialimages import SpatialImage

    basedir = os.getcwd()
    crop_ref = crop_img(ref_img, rtol=0.5)
    crop_ref.to_filename(
        os.path.join(
            basedir,
            os.path.basename(input_img).split('.nii')[0] +
            '_cropped_template.nii.gz'))
    crop_template = os.path.join(
        basedir,
        os.path.basename(input_img).split('.nii')[0] +
        '_cropped_template.nii.gz')

    ## resample the individual MRI onto the cropped template image
    crop_img = resample_to_img(input_img, crop_template)
    crop_img.to_filename(
        os.path.join(
            basedir,
            os.path.basename(input_img).split('.nii')[0] + '_cropped.nii.gz'))

    output_img = os.path.join(
        basedir,
        os.path.basename(input_img).split('.nii')[0] + '_cropped.nii.gz')

    return output_img, crop_template
Пример #5
0
def test_cropping_code_paths():
    # Will mask data with an identically sampled mask and
    # with a smaller mask. The results must be identical
    rng = np.random.RandomState(42)
    data = np.zeros([20, 30, 40, 5])
    data[10:15, 5:20, 10:30, :] = 1. + rng.rand(5, 15, 20, 5)

    affine = np.eye(4)

    img = nibabel.Nifti1Image(data, affine=affine)

    mask = (data[..., 0] > 0).astype(int)
    mask_img = nibabel.Nifti1Image(mask, affine=affine)

    # the mask in mask_img has the same shape and affine as the
    # data and should thus avoid resampling

    # we now crop the mask to its non-zero part. Masking with this
    # mask must yield the same result

    cropped_mask_img = image.crop_img(mask_img)

    parameters = {"smoothing_fwhm": None,
                  "high_pass": None,
                  "low_pass": None,
                  "t_r": None,
                  "detrend": None,
                  "standardize": None
                  }

    # Now do the two maskings
    out_data_uncropped, affine_uncropped = filter_and_mask(img,
                                                           mask_img,
                                                           parameters)
    out_data_cropped, affine_cropped = filter_and_mask(img,
                                                       cropped_mask_img,
                                                       parameters)

    assert_array_almost_equal(out_data_cropped, out_data_uncropped)
Пример #6
0
def test_cropping_code_paths():
    # Will mask data with an identically sampled mask and
    # with a smaller mask. The results must be identical
    rng = np.random.RandomState(42)
    data = np.zeros([20, 30, 40, 5])
    data[10:15, 5:20, 10:30, :] = 1. + rng.rand(5, 15, 20, 5)

    affine = np.eye(4)

    img = nibabel.Nifti1Image(data, affine=affine)

    mask = (data[..., 0] > 0).astype(int)
    mask_img = nibabel.Nifti1Image(mask, affine=affine)

    # the mask in mask_img has the same shape and affine as the
    # data and should thus avoid resampling

    # we now crop the mask to its non-zero part. Masking with this
    # mask must yield the same result

    cropped_mask_img = image.crop_img(mask_img)

    parameters = {
        "smoothing_fwhm": None,
        "high_pass": None,
        "low_pass": None,
        "t_r": None,
        "detrend": None,
        "standardize": None
    }

    # Now do the two maskings
    out_data_uncropped, affine_uncropped = filter_and_mask(
        img, mask_img, parameters)
    out_data_cropped, affine_cropped = filter_and_mask(img, cropped_mask_img,
                                                       parameters)

    assert_array_almost_equal(out_data_cropped, out_data_uncropped)
Пример #7
0
a minimum and compresses the files with a high enough compression level. This
all to reduce the disk size and control the load time (driven by the level of
compression).
"""

import nibabel as nb
from glob import glob
from nilearn.image import crop_img

# Get the list of atlases
atlases = sorted(glob('atlases/atlas_*nii.gz'))

for fname in atlases:

    # Load atlas and crop image
    img = crop_img(fname)

    # Get data array
    data = img.get_fdata()

    # Decide which datatype to use
    if data.max() <= 255 and data.min() >= 0:
        dtype = '>u1'
    elif data.max() <= 65535 and data.min() >= 0:
        dtype = '>u2'
    else:
        dtype = 'i2'

    # Create a new image with the correct datatype
    img.set_data_dtype(dtype)
    new_img = nb.Nifti1Image(data.astype(dtype),
def NIFTI_to_PNG(path_list, dir):
    """
    :param  LOS  path_list: the list of paths to NIFTI images
    :param  string  dir: a specified path to create directory
    NIFTI_to_PNG: creates a directory to save NIFTI images as png files
                If the directory already exists, then that part is skipped.
                Each NIFITI image is augmented in 3 different ways and the 3
                resulting images are saved.  This is done to increase the
                size of the small sample of available NIFTI images
    """
    ## Create location for NIFTI images to be saved
    try:
        os.makedirs(dir)
    except OSError:
        print("error: directory already exists")

    #augment the images and save them as pngs
    count = 0  # a count of the files saved so far
    for path in gm_img_paths:
        #first augmentation -- color
        fig = plt.figure(figsize=(5, 7), facecolor='k')
        img_crop_1 = image.crop_img(path, rtol=1e-0001, copy=True)
        display = plotting.plot_img(img_crop_1,
                                    display_mode='z',
                                    cut_coords=[23],
                                    annotate=False,
                                    figure=fig)
        fig.savefig(dir + '\\' + 'brain' + str(count + 1) + '.png')
        count += 1
        plt.close(fig)

        # second augmentation -- added countours to color
        fig = plt.figure(figsize=(5, 7), facecolor='k')
        img_crop_2 = image.crop_img(path, rtol=1e-0001, copy=True)
        display_2 = plotting.plot_anat(img_crop_2,
                                       display_mode='z',
                                       cut_coords=[23],
                                       annotate=False,
                                       figure=fig)
        display_2.add_contours(img_crop_2,
                               contours=1,
                               antialiased=False,
                               linewidths=1.,
                               levels=[0],
                               colors=['red'])
        display_2.add_contours(img_crop_2,
                               contours=1,
                               antialiased=False,
                               linewidths=1.,
                               levels=[.3],
                               colors=['blue'])
        display_2.add_contours(img_crop_2,
                               contours=1,
                               antialiased=False,
                               linewidths=1.,
                               levels=[.5],
                               colors=['limegreen'])
        fig.savefig(dir + '\\' + 'brain' + str(count + 1) + '.png')
        count += 1
        plt.close(fig)

        #third augmentation -- gray scale
        fig = plt.figure(figsize=(5, 7), facecolor='k')
        img_crop_3 = image.crop_img(path, rtol=1e-0001, copy=True)
        display_3 = plotting.plot_anat(img_crop_3,
                                       display_mode='z',
                                       cut_coords=[23],
                                       annotate=False,
                                       figure=fig)
        fig.savefig(dir + '\\' + 'brain' + str(count + 1) + '.png')
        count += 1
        plt.close(fig)
Пример #9
0
from nilearn.image import crop_img
import numpy as np
from ecoggui import ElectrodeGUI

fname = 'T1_post_deface.nii.gz'
niimg = crop_img(fname)  # to automatically zoom on useful voxels

# We know we have a 8x8 grid of ecog channels, separated by 10 mm.
xy = np.meshgrid(range(0, 80, 10), range(0, 80, 10))
xy = np.transpose([ii.ravel() for ii in xy])

# Click on the grid to select the electrode and press spacebar to add it.
gui = ElectrodeGUI(niimg=niimg, xy=xy)

# Show electrode manually identified positions
print(gui.ch_user)

# Show electrodes predictions
print(gui.ch_pred)