Example #1
0
def _resize_nifti_images(data_nifti, resized_img_shape=(144, 144, 144), interpolation='linear'):
    data_nifti = reorder_img(data_nifti, resample=interpolation)  # bring pixel data to RAS format
    new_spacing = np.divide(np.multiply(data_nifti.header.get_data_shape(), data_nifti.header.get_zooms()),
                            resized_img_shape)

    data = data_nifti.get_data()
    data = np.rot90(data, 1, axes=(0, 2))  # converting to channel * width * height for sitk
    image_sitk = sitk.GetImageFromArray(data)
    image_sitk.SetSpacing(np.asarray(data_nifti.header.get_zooms(), dtype=np.float))
    new_size = np.asarray(resized_img_shape, dtype=np.int16)

    ref_image = sitk.GetImageFromArray(np.ones(new_size, dtype=np.float).T * 0.)
    ref_image.SetSpacing(new_spacing)
    ref_image.SetDirection(image_sitk.GetDirection())
    ref_image.SetOrigin(image_sitk.GetOrigin())

    resample_filter = sitk.ResampleImageFilter()
    transform = sitk.Transform()
    transform.SetIdentity()
    output_pixel_type = image_sitk.GetPixelID()
    resample_filter.SetOutputPixelType(output_pixel_type)
    if interpolation == 'nearest':
        resample_filter.SetInterpolator(sitk.sitkNearestNeighbor)  # nearest is used for modalities t1,t2,flair,t1ce
    else:
        resample_filter.SetInterpolator(sitk.sitkLinear)  # linear intrepolation for segmentation mask
    resample_filter.SetTransform(transform)
    resample_filter.SetDefaultPixelValue(0.)
    resample_filter.SetReferenceImage(ref_image)
    resampled_image = resample_filter.Execute(image_sitk)
    data = sitk.GetArrayFromImage(resampled_image)
    data = np.rot90(data, -1, axes=(0, 2))  # converting to height * width * channel

    return data, new_spacing
Example #2
0
def read_resize_image(in_file,
                      image_shape=None,
                      interpolation='linear',
                      crop=None):
    """
    Resizes nifti based on nibabel functions instead of SITK library used by read_image()
    :returns - resized image with proper affine matrices
    """
    print("Reading: {0}".format(in_file))
    image = nib.load(os.path.abspath(in_file))
    image = fix_shape(image)
    if crop:
        image = crop_img_to(image, crop, copy=True)
    if image_shape:
        new_shape = image_shape
        # Reorder (get rids of rotations in the affine)
        image = reorder_img(image, resample=interpolation)
        # Calculate voxel spacing for desired image shape
        zoom_level = np.divide(new_shape, image.shape)
        current_spacing = [1, 1, 1] * image.affine[:3, :3]
        new_spacing = np.divide(current_spacing, zoom_level)
        # Calculate the new affine matrix
        new_affine = np.eye(4)
        new_affine[:3, :3] = np.eye(3) * new_spacing
        new_affine[:3, 3] = image.affine[:3, 3]
        # Resample new image
        image = resample_img(image,
                             target_shape=new_shape,
                             target_affine=new_affine,
                             interpolation=interpolation)

    return image
Example #3
0
def main():
    namespace = parse_args()
    if not os.path.exists(namespace.output_dir):
        os.makedirs(namespace.output_dir)
    config = load_json(namespace.config_filename)
    labels1, labels2 = config["sequence_kwargs"]["labels"]
    for fn in glob.glob(os.path.join(namespace.prediction_dir, "*")):
        print(fn)
        bn = os.path.basename(fn)
        ofn = os.path.join(namespace.output_dir, bn)
        image = nib.load(fn)
        _image = reorder_img(image)
        data = _image.get_fdata()
        data1 = data[..., :len(labels1)]
        data2 = data[..., len(labels1):]
        for i, (l, d) in enumerate(((labels1, data1), (labels2, data2))):
            volumes = list()
            labels = list()
            for ii, label in enumerate(l):
                if type(label) == list and len(label) == 2:
                    volumes.extend(split_left_right(d[..., ii]))
                    labels.extend(label)
                else:
                    volumes.append(d[..., ii])
                    labels.append(label)
            fixed_data = resample_to_img(_image.__class__(
                dataobj=np.stack(volumes, axis=-1), affine=_image.affine),
                                         target_img=image).get_fdata()
            label_map = convert_one_hot_to_single_label_map_volume(
                fixed_data, labels, dtype=np.uint8)
            out_image = image.__class__(dataobj=label_map, affine=image.affine)
            out_image.to_filename(ofn.replace(".", "_pred{}.".format(i + 1),
                                              1))
Example #4
0
def format_feature_image(feature_image, window, crop=False, cropping_kwargs=None, augment_scale_std=None,
                         augment_scale_probability=1, additive_noise_std=None, additive_noise_probability=0,
                         flip_left_right_probability=0, augment_translation_std=None,
                         augment_translation_probability=0, augment_blur_mean=None, augment_blur_std=None,
                         augment_blur_probability=0, flip_front_back_probability=0, reorder=False,
                         interpolation="linear"):
    if reorder:
        feature_image = reorder_img(feature_image, resample=interpolation)
    if crop:
        if cropping_kwargs is None:
            cropping_kwargs = dict()
        affine, shape = crop_img(feature_image, return_affine=True, **cropping_kwargs)
    else:
        affine = feature_image.affine.copy()
        shape = feature_image.shape
    affine = augment_affine(affine, shape,
                            augment_scale_std=augment_scale_std,
                            augment_scale_probability=augment_scale_probability,
                            augment_translation_std=augment_translation_std,
                            augment_translation_probability=augment_translation_probability,
                            flip_left_right_probability=flip_left_right_probability,
                            flip_front_back_probability=flip_front_back_probability)
    feature_image = augment_image(feature_image,
                                  augment_blur_mean=augment_blur_mean,
                                  augment_blur_std=augment_blur_std,
                                  augment_blur_probability=augment_blur_probability,
                                  additive_noise_std=additive_noise_std,
                                  additive_noise_probability=additive_noise_probability)
    affine = resize_affine(affine, shape, window)
    return feature_image, affine
Example #5
0
def resample(image, new_shape, interpolation="linear"):
    # """
    # Resample image to new shape
    # :param image: input image
    # :param new_shape: chosen shape
    # :param interpolation: interpolation method
    # :return: resampled image
    # """
    # input_shape = np.asarray(image.shape, dtype=image.get_data_dtype())
    # ras_image = reorder_img(image, resample=interpolation)
    # output_shape = np.asarray(new_shape)
    # new_spacing = input_shape / output_shape
    # new_affine = np.copy(ras_image.affine)
    # new_affine[:3, :3] = ras_image.affine[:3, :3] * np.diag(new_spacing)
    #
    # return resample_img(ras_image, target_affine=new_affine, target_shape=output_shape, interpolation=interpolation)

    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)
Example #6
0
def view_mdfa_image(mdfa_filename, reference_filename):
    reference_image = nib.load(reference_filename)
    mdfa_image = reorder_img(nib.load(mdfa_filename), resample='linear')
    resampled_reference_image = resample_to_img(reference_image,
                                                mdfa_image,
                                                interpolation='linear')
    mdfa_data = mdfa_image.get_data()
    reference_data = resampled_reference_image.get_data()
    midway_points = np.asarray(np.divide(mdfa_image.shape[:3], 2), np.int)
    fig, axes = plt.subplots(3, 3, figsize=(12, 12), num=1)
    axes[0, 1].imshow(np.rot90(reference_data[midway_points[0], :, :]),
                      cmap='gray')
    axes[0, 2].imshow(np.rot90(reference_data[:, midway_points[1], :]),
                      cmap='gray')
    axes[0, 0].imshow(np.rot90(reference_data[:, :, midway_points[2]]),
                      cmap='gray')
    axes[1, 1].imshow(np.rot90(mdfa_data[midway_points[0], :, :, 0]),
                      cmap='gray')
    axes[1, 2].imshow(np.rot90(mdfa_data[:, midway_points[1], :, 0]),
                      cmap='gray')
    axes[1, 0].imshow(np.rot90(mdfa_data[:, :, midway_points[2], 0]),
                      cmap='gray')
    axes[2, 1].imshow(np.rot90(mdfa_data[midway_points[0], :, :, 1:]))
    axes[2, 2].imshow(np.rot90(mdfa_data[:, midway_points[1], :, 1:]))
    axes[2, 0].imshow(np.rot90(mdfa_data[:, :, midway_points[2], 1:]))
    plt.show()
Example #7
0
def resize(image, new_shape, interpolation="continuous"):
    input_shape = np.asarray(image.shape, dtype=np.float16)
    ras_image = reorder_img(image, resample=interpolation)
    output_shape = np.asarray(new_shape)
    new_spacing = input_shape/output_shape
    new_affine = np.copy(ras_image.affine)
    new_affine[:3, :3] = ras_image.affine[:3, :3] * np.diag(new_spacing)
    return resample_img(ras_image, target_affine=new_affine, target_shape=output_shape, interpolation=interpolation)
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)
Example #9
0
def split_yeo(out_path):
    # take yeo atlas and offset rois in rh +100
    atlas_yeo_2011 = datasets.fetch_atlas_yeo_2011()
    atlas_yeo = atlas_yeo_2011.thick_17
    atlas_yeo_img = image.reorder_img(image.image.check_niimg_3d(atlas_yeo))

    split_x = 128
    offset = np.zeros_like(atlas_yeo_img.dataobj)
    offset[split_x:, :, :] = 100
    offset[atlas_yeo_img.dataobj == 0] = 0
    offset_img = image.new_img_like(atlas_yeo_img,
                                    offset,
                                    copy_header=True,
                                    affine=atlas_yeo_img.affine)
    yeo_splithem_img = image.math_img("im1 + im2",
                                      im1=atlas_yeo_img,
                                      im2=offset_img)

    # create updated roi list
    yeo17_networks_str = StringIO("""roi,roi_name,dmn_subnetwork
    1,Visual A,
    2,Visual B,
    3,SomMot A,
    4,SomMot B,
    5,DorsAttn A,
    6,DorsAttn B,
    7,SalVentAttn A,
    8,SalVentAttn B,
    9,Limbic B,
    10,Limbic A,
    11,Control C,
    12,Control A,
    13,Control B,
    14,TempPar,
    15,Default C,mtl
    16,Default A,core
    17,Default B,dorsal medial""")
    df_labels = pd.read_csv(yeo17_networks_str, header=0)

    df_labels_lh = df_labels.copy()
    df_labels_rh = df_labels.copy()
    df_labels_lh["hemi"] = "lh"
    df_labels_rh["hemi"] = "rh"
    df_labels_rh["roi"] += 100

    df_combined = pd.concat((df_labels_lh, df_labels_rh))
    df_combined["full_roi_name"] = (df_combined.hemi + "_" +
                                    df_combined.roi_name).str.replace(
                                        " ", "_")
    # output
    os.makedirs(out_path, exist_ok=True)
    out_file = os.path.join(out_path, "yeo_2011_thick17_splithemi")
    yeo_splithem_img.to_filename(out_file + ".nii.gz")

    df_combined.to_csv(out_file + ".tsv", sep="\t", index=False)
Example #10
0
def resize(image, shape, interpolation='continuous'):
    input_shape = np.asarray(image.shape, dtype=np.float16)
    output_shape = np.asarray(shape)
    spacing = input_shape / output_shape
    
    ras = reorder_img(image, resample=interpolation)
    affine = np.copy(ras.affine)
    affine[:3, :3] = ras.affine[:3, :3] * np.diag(spacing)
    
    resampled = resample_img(ras, target_affine=affine, target_shape=shape, 
                             interpolation=interpolation)
    return resampled
def plot_segmentation(
        img, gm_filename, wm_filename=None, csf_filename=None,
        output_filename=None, cut_coords=None, display_mode='ortho',
        cmap=None, title='GM + WM + CSF segmentation', close=False):
    """
    Plot a contour mapping of the GM, WM, and CSF of a subject's anatomical.

    Parameters
    ----------
    img_filename: string or image object
                  path of file containing image data, or image object simply

    gm_filename: string
                 path of file containing Grey Matter template

    wm_filename: string (optional)
                 path of file containing White Matter template

    csf_filename: string (optional)
                 path of file containing Cerebro-Spinal Fluid template


    """
    # misc
    if cmap is None:
        cmap = plt.cm.gray
    if cut_coords is None:
        cut_coords = (-10, -28, 17)
    if display_mode in ['x', 'y', 'z']:
        cut_coords = (cut_coords['xyz'.index(display_mode)],)

    # plot img
    img = mean_img(img)
    img = reorder_img(img, resample="continuous")
    _slicer = plot_img(img, cut_coords=cut_coords, display_mode=display_mode,
                       cmap=cmap, black_bg=True)

    # add TPM contours
    gm = nibabel.load(gm_filename)
    _slicer.add_contours(gm, levels=[.51], colors=["r"])
    if not wm_filename is None:
        _slicer.add_contours(wm_filename, levels=[.51], colors=["g"])
    if not csf_filename is None:
        _slicer.add_contours(csf_filename, levels=[.51], colors=['b'])

    # misc
    _slicer.title(title, size=12, color='w', alpha=0)
    if not output_filename is None:
        plt.savefig(output_filename, bbox_inches='tight', dpi=200,
                    facecolor="k",
                    edgecolor="k")
        if close:
            plt.close()
Example #12
0
def resample(image, new_shape, interpolation="linear"):
    print("\n resampling ...")
    input_shape = np.asarray(image.shape, dtype=image.get_data_dtype())
    ras_image = reorder_img(image, resample=interpolation)
    output_shape = np.asarray(new_shape)
    new_spacing = input_shape / output_shape
    new_affine = np.copy(ras_image.affine)
    new_affine[:3, :3] = ras_image.affine[:3, :3] * np.diag(new_spacing)

    return resample_img(ras_image,
                        target_affine=new_affine,
                        target_shape=output_shape,
                        interpolation=interpolation)
Example #13
0
def load_single_image(filename,
                      resample=None,
                      reorder=True,
                      dtype=None,
                      verbose=False):
    if verbose:
        print("Loading", filename)
    image = nib.load(filename)
    if verbose:
        print("Finished loading", filename, "Shape:", image.shape)
    if dtype is not None:
        image = new_img_like(image, np.asarray(image.dataobj, dtype))
    if reorder:
        return reorder_img(image, resample=resample)
    return image
Example #14
0
def resample(image, new_shape, interpolation="continuous"):
    """
    Resample image to new shape
    :param image: input image
    :param new_shape: chosen shape
    :param interpolation: interpolation method
    :return: resampled image
    """
    input_shape = np.asarray(image.shape, dtype=image.get_data_dtype())
    ras_image = reorder_img(image, resample=interpolation)
    output_shape = np.asarray(new_shape)
    new_spacing = input_shape / output_shape
    new_affine = np.copy(ras_image.affine)
    new_affine[:3, :3] = ras_image.affine[:3, :3] * np.diag(new_spacing)

    return resample_img(ras_image, target_affine=new_affine, target_shape=output_shape, interpolation=interpolation)
Example #15
0
 def reorder(self,data):
     """
     This function reorder LAS to RAS.
     data : nibabel.nifti1.Nifti1Image.
     
     Returns a RAS coordinated nibabel.nifti1.Nifti1Image.
     """
     # Check the coordination and reorder the data LAS to RAS
     coord = nib.aff2axcodes(data.affine)
     if 'L' == coord[0]:
         data = nimg.reorder_img(data,resample=None)
         a = f"Reorder {nib.aff2axcodes(data.affine)}"
         print(a,"completed")
     else:
         a = f"Original {coord}"
         print(a,"checked")
     return data
Example #16
0
    def fit(self, X=None, y=None):  # noqa
        super(HemisphereMasker, self).fit(X, y)

        # x, y, z
        hemi_mask_data = reorder_img(self.mask_img_).get_data().astype(np.bool)

        xvals = hemi_mask_data.shape[0]
        midpt = np.ceil(xvals / 2.0)
        if self.hemi == "r":
            other_hemi_slice = slice(midpt, xvals)
        else:
            other_hemi_slice = slice(0, midpt)

        hemi_mask_data[other_hemi_slice] = False
        mask_data = self.mask_img_.get_data() * hemi_mask_data
        self.mask_img_ = new_img_like(self.mask_img_, data=mask_data)

        return self
Example #17
0
def _load_bg_img(stat_map_img, bg_img="MNI152", black_bg="auto", dim="auto"):
    """ Load and resample bg_img in an isotropic resolution,
        with a positive diagonal affine matrix.
        Returns: bg_img, bg_min, bg_max, black_bg
    """
    if (bg_img is None or bg_img is False) and black_bg == "auto":
        black_bg = False

    if bg_img is not None and bg_img is not False:
        if isinstance(bg_img, str) and bg_img == "MNI152":
            bg_img = load_mni152_template()
        bg_img, black_bg, bg_min, bg_max = _load_anat(bg_img,
                                                      dim=dim,
                                                      black_bg=black_bg)
    else:
        bg_img = new_img_like(stat_map_img, np.zeros(stat_map_img.shape),
                              stat_map_img.affine)
        bg_min = 0
        bg_max = 0
    bg_img = reorder_img(bg_img, resample="nearest")
    return bg_img, bg_min, bg_max, black_bg
Example #18
0
def swap_img_hemispheres(niimg):
    """Performs swapping of hemispheres in the indicated nifti.

       Use case: synchronizing ROIs across hemispheres

    Parameters
    ----------
    niimg: string or object
        If niimg is a string, it's considered as a path to Nifti image and
        calls nibabel.load on it. If it is an object, it's considered to be
        a nibabel.Nifti1Image object.

    Returns
    -------
    output: nibabel.Nifti1Image
        hemispherically swapped image

    Notes
    -----
    Supposes a nifti of a brain that is sagitally aligned

    Should be used with caution (confusion might be caused with
    radio/neuro conventions)

    Note that this does not require a change of the affine matrix.
    """

    # Check input is really a path to a nifti file or a nifti object
    niimg = check_niimg(niimg)

    # get nifti in x-y-z order
    niimg = reorder_img(niimg)

    # create swapped nifti object
    out_img = nibabel.Nifti1Image(niimg.get_data()[::-1],
                                  niimg.get_affine(),
                                  header=niimg.get_header())

    return out_img
Example #19
0
def swap_img_hemispheres(img):
    """Performs swapping of hemispheres in the indicated nifti.

       Use case: synchronizing ROIs across hemispheres

    Parameters
    ----------
    img: Niimg-like object
        See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg.
        One or several niimgs.

    Returns
    -------
    output: nibabel.Nifti1Image
        hemispherically swapped image

    Notes
    -----
    Supposes a nifti of a brain that is sagitally aligned

    Should be used with caution (confusion might be caused with
    radio/neuro conventions)

    Note that this does not require a change of the affine matrix.
    """

    # Check input is really a path to a nifti file or a nifti object
    img = check_niimg(img)

    # get nifti in x-y-z order
    img = reorder_img(img)

    # create swapped nifti object
    out_img = nibabel.Nifti1Image(img.get_data()[::-1],
                                  img.get_affine(),
                                  header=img.get_header())

    return out_img
Example #20
0
def swap_img_hemispheres(niimg):
    """Performs swapping of hemispheres in the indicated nifti.

       Use case: synchronizing ROIs across hemispheres

    Parameters
    ----------
    niimg: string or object
        If niimg is a string, it's considered as a path to Nifti image and
        calls nibabel.load on it. If it is an object, it's considered to be
        a nibabel.Nifti1Image object.

    Returns
    -------
    output: nibabel.Nifti1Image
        hemispherically swapped image

    Notes
    -----
    Supposes a nifti of a brain that is sagitally aligned

    Should be used with caution (confusion might be caused with
    radio/neuro conventions)

    Note that this does not require a change of the affine matrix.
    """

    # Check input is really a path to a nifti file or a nifti object
    niimg = check_niimg(niimg)

    # get nifti in x-y-z order
    niimg = reorder_img(niimg)

    # create swapped nifti object
    out_img = nibabel.Nifti1Image(niimg.get_data()[::-1], niimg.get_affine(),
        header=niimg.get_header())

    return out_img
Example #21
0
def resize(image, new_shape, interpolation="linear"):
    image = reorder_img(image, resample=interpolation)
    zoom_level = np.divide(new_shape, image.shape)
    # if the image should be enlarged place only 0s on the sides: works only if
    # none of the dimensions is to be downsampled,
    # otherwise enlarge it using the original function
    if np.any(zoom_level) < 1:
        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())
    else:
        new_data = np.zeros(new_shape)
        new_data[:image.shape[0], :image.shape[1], :image.
                 shape[2]] = image.get_data()
        # not sure if this affine is correct
        new_affine = np.eye(4)
    return new_img_like(image, new_data, affine=new_affine)
Example #22
0
def swap_img_hemispheres(img):
    """Performs swapping of hemispheres in the indicated nifti.

       Use case: synchronizing ROIs across hemispheres

    Parameters
    ----------
    img: Niimg-like object
        See http://nilearn.github.io/building_blocks/manipulating_mr_images.html#niimg.
        One or several niimgs.

    Returns
    -------
    output: nibabel.Nifti1Image
        hemispherically swapped image

    Notes
    -----
    Supposes a nifti of a brain that is sagitally aligned

    Should be used with caution (confusion might be caused with
    radio/neuro conventions)

    Note that this does not require a change of the affine matrix.
    """

    # Check input is really a path to a nifti file or a nifti object
    img = check_niimg(img)

    # get nifti in x-y-z order
    img = reorder_img(img)

    # create swapped nifti object
    out_img = nibabel.Nifti1Image(img.get_data()[::-1], img.get_affine(),
        header=img.get_header())

    return out_img
import os, glob
import numpy as np
import pandas as pd
import nibabel as nib
from nilearn.plotting import plot_epi, plot_anat, plot_img, plot_stat_map
from nilearn import image
BASE_DIR = '/disk4t/mehdi/data/pet_fdg_baseline_processed_ADNI'
data = pd.read_csv(os.path.join(BASE_DIR, 'description_file.csv'))

X = np.load('features_regions.npy')

for idx, row in data.iterrows():
    print idx
    pet_id = ''.join(['I', str(row['Image_ID_y'])])
    pet = glob.glob(os.path.join(BASE_DIR, pet_id, 'I*.nii'))[0]
    pet_img = image.reorder_img(pet, resample='nearest')
    
    seg_id = ''.join(['I', str(row['Image_ID_x'])])
    seg = glob.glob(os.path.join(BASE_DIR, seg_id, '*.nii'))[0]
    seg_img = image.reorder_img(seg, resample='nearest')
    
    seg_data = seg_img.get_data()[:, :, :, 0]
    seg_mean = np.zeros(seg_data.shape)
    for val in np.unique(seg_data):
        if val > 0:
            ind = (seg_data == val)
            seg_mean[ind] = X[idx,(val/256)-1]
    
    seg_img = nib.Nifti1Image(seg_mean, seg_img.get_affine())
    plot_stat_map(seg_img, seg_img, colorbar=True,
                  title='-'.join([pet_id, row.DX_Group]),
def generate_subject_stats_report(
        stats_report_filename,
        contrasts,
        z_maps,
        mask,
        design_matrices=None,
        subject_id=None,
        anat=None,
        display_mode="z",
        cut_coords=None,
        threshold=2.3,
        cluster_th=15,
        start_time=None,
        title=None,
        user_script_name=None,
        progress_logger=None,
        shutdown_all_reloaders=True,
        **glm_kwargs):
    """Generates a report summarizing the statistical methods and results

    Parameters
    ----------
    stats_report_filename: string:
        html file to which output (generated html) will be written

    contrasts: dict of arrays
        contrasts we are interested in; same number of contrasts as zmaps;
        same keys

    zmaps: dict of image objects or strings (image filenames)
        zmaps for contrasts we are interested in; one per contrast id

    mask: 'nifti image object'
        brain mask for ROI

    design_matrix: list of 'DesignMatrix', `numpy.ndarray` objects or of
    strings (.png, .npz, etc.) for filenames
        design matrices for the experimental conditions

    contrasts: dict of arrays
       dictionary of contrasts of interest; the keys are the contrast ids,
       the values are contrast values (lists)

    z_maps: dict of 3D image objects or strings (image filenames)
       dict with same keys as 'contrasts'; the values are paths of z-maps
       for the respective contrasts

    anat: 3D array (optional)
        brain image to serve bg unto which activation maps will be plotted

    anat_affine: 2D array (optional)
        affine data for the anat

    threshold: float (optional)
        threshold to be applied to activation maps voxel-wise

    cluster_th: int (optional)
        minimal voxel count for clusteres declared as 'activated'

    cmap: cmap object (default viz.cm.cold_hot)
        color-map to use in plotting activation maps

    start_time: string (optional)
        start time for the stats analysis (useful for the generated
        report page)

    user_script_name: string (optional, default None)
        existing filename, path to user script used in doing the analysis

    progress_logger: ProgressLogger object (optional)
        handle for logging progress

    shutdown_all_reloaders: bool (optional, default True)
        if True, all pages connected to the stats report page will
        be prevented from reloading after the stats report page
        has been completely generated

    **glm_kwargs:
        kwargs used to specify the control parameters used to specify the
        experimental paradigm and the GLM

    """
    # prepare for stats reporting
    if progress_logger is None:
        progress_logger = base_reporter.ProgressReport()

    output_dir = os.path.dirname(stats_report_filename)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # copy css and js stuff to output dir
    base_reporter.copy_web_conf_files(output_dir)

    # initialize gallery of design matrices
    design_thumbs = base_reporter.ResultsGallery(
        loader_filename=os.path.join(output_dir,
                                     "design.html")
        )

    # initialize gallery of activation maps
    activation_thumbs = base_reporter.ResultsGallery(
        loader_filename=os.path.join(output_dir,
                                     "activation.html")
        )

    # get caller module handle from stack-frame
    if user_script_name is None:
        user_script_name = sys.argv[0]
    user_source_code = base_reporter.get_module_source_code(
        user_script_name)

    methods = """
    GLM and Statistical Inference have been done using the <i>%s</i> script, \
powered by <a href="%s">nistats</a>.""" % (user_script_name,
                                           base_reporter.NISTATS_URL)

    # report the control parameters used in the paradigm and analysis
    design_params = ""
    glm_kwargs["contrasts"] = contrasts
    if len(glm_kwargs):
        design_params += ("The following control parameters were used for  "
                    " specifying the experimental paradigm and fitting the "
                    "GLM:<br/><ul>")

        # reshape glm_kwargs['paradigm']
        if "paradigm" in glm_kwargs:
            paradigm_ = glm_kwargs['paradigm']
            paradigm = {'name' : paradigm_['name'],
                        'onset' : paradigm_['onset']}
            if 'duration' in paradigm_.keys():
                paradigm['duration'] = paradigm_['duration']
            paradigm['n_conditions'] = len(set(paradigm['name']))
            paradigm['n_events'] = len(paradigm['name'])
            paradigm['type'] = 'event'
            if 'duration' in paradigm.keys() and paradigm['duration'][0] > 0:
                paradigm['type'] = 'block'
            glm_kwargs['paradigm'] = paradigm

        design_params += base_reporter.dict_to_html_ul(glm_kwargs)

    if start_time is None:
        start_time = base_reporter.pretty_time()

    if title is None:
        title = "GLM and Statistical Inference"
        if not subject_id is None:
            title += " for subject %s" % subject_id

    level1_html_markup = base_reporter.get_subject_report_stats_html_template(
        title=title,
        start_time=start_time,
        subject_id=subject_id,

        # insert source code stub
        source_script_name=user_script_name,
        source_code=user_source_code,

        design_params=design_params,
        methods=methods,
        threshold=threshold)

    with open(stats_report_filename, 'w') as fd:
        fd.write(str(level1_html_markup))
        fd.close()

    progress_logger.log("<b>Level 1 statistics</b><br/><br/>")

    # create design matrix thumbs
    if not design_matrices is None:
        if not hasattr(design_matrices, '__len__'):
            design_matrices = [design_matrices]

        for design_matrix, j in zip(design_matrices,
                                    range(len(design_matrices))):
            
            # Nistats: design matrices should be strings or pandas dataframes
            if isinstance(design_matrix, basestring):
                if not isinstance(design_matrix, pd.DataFrame):
                    # XXX should be a DataFrame pickle here ?
                    print design_matrix
                    design_matrix = pd.read_pickle(design_matrix)
                else:
                    raise TypeError(
                        "Unsupported design matrix type: %s" % type(
                            design_matrix))

            # plot design_matrix proper
            ax = plot_design_matrix(design_matrix)
            ax.set_position([.05, .25, .9, .65])
            dmat_outfile = os.path.join(output_dir,
                                        'design_matrix_%i.png' % (j + 1))
            pl.savefig(dmat_outfile, bbox_inches="tight", dpi=200)
            pl.close()

            thumb = base_reporter.Thumbnail()
            thumb.a = base_reporter.a(href=os.path.basename(dmat_outfile))
            thumb.img = base_reporter.img(src=os.path.basename(dmat_outfile),
                                     height="500px")
            thumb.description = "Design Matrix"
            thumb.description += " %s" % (j + 1) if len(
                design_matrices) > 1 else ""

            # commit activation thumbnail into gallery
            design_thumbs.commit_thumbnails(thumb)

    # create activation thumbs
    for contrast_id, contrast_val in contrasts.iteritems():
        z_map = z_maps[contrast_id]

        # load the map
        if isinstance(z_map, basestring):
            z_map = nibabel.load(z_map)

        # generate level 1 stats table
        title = "Level 1 stats for %s contrast" % contrast_id
        stats_table = os.path.join(output_dir, "%s_stats_table.html" % (
                contrast_id))
        generate_level1_stats_table(
            z_map, mask, stats_table, cluster_th=cluster_th,
            z_threshold=threshold, title=title)

        # plot activation proper
        # XXX: nilearn's plotting bug's about rotations inf affine, etc.
        z_map = reorder_img(z_map, resample="continuous")
        if not anat is None:
            anat = reorder_img(anat, resample="continuous")
        plot_stat_map(z_map, anat, threshold=threshold,
                      display_mode=display_mode, cut_coords=cut_coords,
                      black_bg=True)

        # store activation plot
        z_map_plot = os.path.join(output_dir,
                                  "%s_z_map.png" % contrast_id)
        pl.savefig(z_map_plot, dpi=200, bbox_inches='tight', facecolor="k",
                   edgecolor="k")
        pl.close()

        # create thumbnail for activation
        thumbnail = base_reporter.Thumbnail(
            tooltip="Contrast vector: %s" % contrast_val)
        thumbnail.a = base_reporter.a(href=os.path.basename(stats_table))
        thumbnail.img = base_reporter.img(src=os.path.basename(z_map_plot),
                                          height="150px",)
        thumbnail.description = contrast_id
        activation_thumbs.commit_thumbnails(thumbnail)

    # we're done, shut down re-loaders
    progress_logger.log('<hr/>')

    # prevent stats report page from reloading henceforth
    progress_logger.finish(stats_report_filename)

    # prevent any related page from reloading
    if shutdown_all_reloaders:
        progress_logger.finish_dir(output_dir)

    # return generated html
    with open(stats_report_filename, 'r') as fd:
        stats_report = fd.read()
        fd.close()

        return stats_report
Example #25
0
for file in os.listdir(dir):
    _, file_ext = os.path.splitext(file)
    if file_ext == ".nii" and file[0:3] == "mwp1":
        #create full path to file
        file_path = os.path.join(dir, file)

        #get number of the image
        file_num = [int(s) for s in file.split() if s.isdigit()]
        file_num = file_num[-1]

        #load .nii image
        img = nib.load(file_path)
        print ("found file num {0} with {1} shape".format(file_num, img.shape))

        #Affine Registration
        img = nimg.reorder_img(img)

        #Kernel Smoothing
        #   FWHM Kernel
        #   8mm smoothing
        img = nimg.smooth_img(img, 8)

        #get data
        train_tmp = img.get_data()

        #flatten data
        train_tmp.flatten()

        #add to train array
        train[file_num,:] = train_tmp
Example #26
0
if not os.path.isdir(pngs_dir):
    os.makedirs(pngs_dir)

#===============================================================================
# Read in the images using nibabel
#===============================================================================
img = nib.load(anat_file)

# Convert the data to float
data = img.get_data()
data = data.astype('float')

# Reslice the image so there are no rotations in the affine.
# This step is actually included in the nilearn plot_anat command below
# but it runs faster if the image has already been resliced.
img_reslice = reorder_img(img, resample='continuous')

# Do the same if you have an overlay file too
if not overlay_file is None:
    overlay_img = nib.load(overlay_file)
    data = overlay_img.get_data()
    data = data.astype('float')
    overlay_img_reslice = reorder_img(overlay_img, resample='nearest')

#===============================================================================
# Plot each slice unless it's empty!
#===============================================================================

# Loop through all the slices in this dimension
for i in np.arange(img_reslice.shape[dim_lookup_dict[axis]], dtype='float'):
Example #27
0
    # MRI        
    anat_path = os.path.join(BASE_DIR, subject_id, 'MRI', 'T1MRI')
    anat_list = glob.glob(os.path.join(anat_path, '[E-n]*.hdr'))
    
    if len(fmri_list) == 291 and len(anat_list) == 1 and subject_id != 'S14659':
        print subject_id, len(anat_list), len(fmri_list)

        subject_data = SubjectData(func=[fmri_list[2:]],
                                   anat=anat_list[0],
                                   output_dir=os.path.join(OUPUT_DIR,
                                   subject_id))
                                   
        
        anat_name = '_'.join([subject_id, 'anat'])
        r_img_anat = image.reorder_img(anat_list[0], resample=True)
        
        plotting.plot_img(r_img_anat,
                          output_file=os.path.join(OUPUT_DIR, 'figs', anat_name),
                          title=anat_name,
                          black_bg=True)
        #############################################
        do_subject_preproc(
            subject_data, #subject data class
            deleteorient=False, #
        
            slice_timing=True,
            slice_order="ascending",
            interleaved=True,
            refslice=1,
            TR=2.4,
Example #28
0
def plot_tsdiffs(results, use_same_figure=True):
    ''' Plotting routine for time series difference metrics

    Requires matplotlib

    Parameters
    ----------
    results : dict
        Results of format returned from
        :func:`pypreprocess.time_diff.time_slice_diff`

    use_same_figure : bool
        Whether to put all the plots on the same figure. If False, one
        figure will be created for each plot.

    '''
    import matplotlib.pyplot as plt

    session_lengths = results['session_length']
    session_starts = np.cumsum(session_lengths)[:-1]
    T = len(results['volume_means'])
    S = results['slice_mean_diff2'].shape[1]
    mean_means = np.mean(results['volume_means'])
    scaled_slice_diff = results['slice_mean_diff2'] / mean_means ** 2
    n_plots = 6

    if use_same_figure:
        fig, axes = plt.subplots((n_plots + 1) // 2, 2)
        # Slightly easier to flatten axes to treat the
        # use_same_figure=False case in a similar fashion
        axes = axes.T.reshape(-1)
        fig.set_size_inches(12, 6, forward=True)
        fig.subplots_adjust(top=0.97, bottom=0.08, left=0.1, right=0.98,
                            hspace=0.3, wspace=0.18)
    else:
        axes = [plt.figure().add_subplot(111)
                for _ in range(n_plots - 2)]

    def xmax_labels(ax, val, xlabel, ylabel):
        xlims = ax.axis()
        ax.axis((0, val) + xlims[2:])
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)

    def plot_session_starts(ax):
        for sep_start in session_starts:
            ax.axvline(sep_start, linestyle="--", c="k")

    iter_axes = iter(axes)

    # plot of mean volume variance
    ax = next(iter_axes)
    ax.plot(results['volume_mean_diff2'] / mean_means ** 2)
    # note: squaring the mean to obtain a dimensionless quantity
    xmax_labels(ax, T - 1, 'Image number', 'Scaled variance')
    plot_session_starts(ax)

    # mean intensity
    ax = next(iter_axes)
    ax.plot(results['volume_means'] / mean_means)
    xmax_labels(ax, T,
                'Image number',
                'Scaled mean \n voxel intensity')
    plot_session_starts(ax)

    # slice plots min max mean
    ax = next(iter_axes)
    ax.plot(np.mean(scaled_slice_diff, 0), 'k')
    ax.plot(np.min(scaled_slice_diff, 0), 'b')
    ax.plot(np.max(scaled_slice_diff, 0), 'r')
    xmax_labels(ax, S + 1, 'Slice number',
                'Max/mean/min \n slice variation')

    # plot of diff by slice
    ax = next(iter_axes)
    # Set up the color map for the different slices:
    X, Y = np.meshgrid(np.arange(scaled_slice_diff.shape[0]),
                       np.arange(scaled_slice_diff.shape[1]))

    # Use HSV in order to code the slices from bottom to top:
    ax.scatter(X.T.ravel(), scaled_slice_diff.ravel(),
               c=Y.T.ravel(), cmap=plt.cm.hsv,
               alpha=0.2)
    xmax_labels(ax, T - 1,
                'Image number',
                'Slice by slice variance')
    plot_session_starts(ax)

    kwargs = {}
    titles = ['mean squared difference', 'max squared difference']
    for title, which in zip(titles, ["diff2_mean_vol", "slice_diff2_max_vol"]):
        if use_same_figure:
            kwargs["axes"] = next(iter_axes)
        stuff = reorder_img(results[which], resample="continuous")

        # XXX: Passing axes=ax param to plot_stat_map produces miracles!
        # XXX: As a quick fix, we simply plot and then do ax = plt.gca()
        plot_stat_map(stuff, bg_img=None, display_mode='z', cut_coords=5,
                      black_bg=True, title=title, **kwargs)
        if not use_same_figure:
            axes.append(plt.gca())

    return axes
Example #29
0
def test_mni152template_is_reordered():
    """See issue #2550."""
    reordered_mni = reorder_img(load_mni152_template())
    assert np.allclose(get_data(reordered_mni), get_data(MNI152TEMPLATE))
    assert np.allclose(reordered_mni.affine, MNI152TEMPLATE.affine)
    assert np.allclose(reordered_mni.shape, MNI152TEMPLATE.shape)
Example #30
0
                new_filename = filename.replace(s,'s005')
                os.chdir(filedir)
                os.rename(filename, new_filename)
                print new_filename
            
    anat_path = os.path.join(BASE_DIR, subject, 'MRI', 'T1MRI')
    anat_files = glob.glob(os.path.join(anat_path, '*.*'))
    for f in anat_files:
        filedir, filename = os.path.split(f)
        filename = f.split('/')[-1]
        if 'nobias' in filename:
            new_filename = filename.replace('nobias_Exam','S')
            print new_filename
            os.chdir(filedir)
            os.rename(filename, new_filename)
        elif 'Exam' in filename:
            new_filename = filename.replace('Exam','S')
            print new_filename
            os.chdir(filedir)
            os.rename(filename, new_filename)            
            
    hdr_files = glob.glob(os.path.join(anat_path, '*.hdr'))
    if len(hdr_files)>0:
        img = nib.load(hdr_files[0])
        new_img = image.reorder_img(img,resample='continuous')
        ax = plotting.plot_img(new_img)
        ax.title(subject)


    
    
Example #31
0
def generate_subject_stats_report(stats_report_filename,
                                  contrasts,
                                  z_maps,
                                  mask,
                                  design_matrices=None,
                                  subject_id=None,
                                  anat=None,
                                  display_mode="z",
                                  cut_coords=None,
                                  threshold=2.3,
                                  cluster_th=15,
                                  start_time=None,
                                  title=None,
                                  user_script_name=None,
                                  progress_logger=None,
                                  shutdown_all_reloaders=True,
                                  **glm_kwargs):
    """Generates a report summarizing the statistical methods and results

    Parameters
    ----------
    stats_report_filename: string:
        html file to which output (generated html) will be written

    contrasts: dict of arrays
        contrasts we are interested in; same number of contrasts as zmaps;
        same keys

    zmaps: dict of image objects or strings (image filenames)
        zmaps for contrasts we are interested in; one per contrast id

    mask: 'nifti image object'
        brain mask for ROI

    design_matrix: list of 'DesignMatrix', `numpy.ndarray` objects or of
    strings (.png, .npz, etc.) for filenames
        design matrices for the experimental conditions

    contrasts: dict of arrays
       dictionary of contrasts of interest; the keys are the contrast ids,
       the values are contrast values (lists)

    z_maps: dict of 3D image objects or strings (image filenames)
       dict with same keys as 'contrasts'; the values are paths of z-maps
       for the respective contrasts

    anat: 3D array (optional)
        brain image to serve bg unto which activation maps will be plotted

    anat_affine: 2D array (optional)
        affine data for the anat

    threshold: float (optional)
        threshold to be applied to activation maps voxel-wise

    cluster_th: int (optional)
        minimal voxel count for clusteres declared as 'activated'

    cmap: cmap object (default viz.cm.cold_hot)
        color-map to use in plotting activation maps

    start_time: string (optional)
        start time for the stats analysis (useful for the generated
        report page)

    user_script_name: string (optional, default None)
        existing filename, path to user script used in doing the analysis

    progress_logger: ProgressLogger object (optional)
        handle for logging progress

    shutdown_all_reloaders: bool (optional, default True)
        if True, all pages connected to the stats report page will
        be prevented from reloading after the stats report page
        has been completely generated

    **glm_kwargs:
        kwargs used to specify the control parameters used to specify the
        experimental paradigm and the GLM

    """
    # prepare for stats reporting
    if progress_logger is None:
        progress_logger = base_reporter.ProgressReport()

    output_dir = os.path.dirname(stats_report_filename)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # copy css and js stuff to output dir
    base_reporter.copy_web_conf_files(output_dir)

    # initialize gallery of design matrices
    design_thumbs = base_reporter.ResultsGallery(
        loader_filename=os.path.join(output_dir, "design.html"))

    # initialize gallery of activation maps
    activation_thumbs = base_reporter.ResultsGallery(
        loader_filename=os.path.join(output_dir, "activation.html"))

    # get caller module handle from stack-frame
    if user_script_name is None:
        user_script_name = sys.argv[0]
    user_source_code = base_reporter.get_module_source_code(user_script_name)

    methods = """
    GLM and Statistical Inference have been done using the <i>%s</i> script, \
powered by <a href="%s">nistats</a>.""" % (user_script_name,
                                           base_reporter.NISTATS_URL)

    # report the control parameters used in the paradigm and analysis
    design_params = ""
    glm_kwargs["contrasts"] = contrasts
    if len(glm_kwargs):
        design_params += (
            "The following control parameters were used for  "
            " specifying the experimental paradigm and fitting the "
            "GLM:<br/><ul>")

        # reshape glm_kwargs['paradigm']
        if "paradigm" in glm_kwargs:
            paradigm_ = glm_kwargs['paradigm']
            paradigm = {'name': paradigm_['name'], 'onset': paradigm_['onset']}
            if 'duration' in paradigm_.keys():
                paradigm['duration'] = paradigm_['duration']
            paradigm['n_conditions'] = len(set(paradigm['name']))
            paradigm['n_events'] = len(paradigm['name'])
            paradigm['type'] = 'event'
            if 'duration' in paradigm.keys() and paradigm['duration'][0] > 0:
                paradigm['type'] = 'block'
            glm_kwargs['paradigm'] = paradigm

        design_params += base_reporter.dict_to_html_ul(glm_kwargs)

    if start_time is None:
        start_time = base_reporter.pretty_time()

    if title is None:
        title = "GLM and Statistical Inference"
        if not subject_id is None:
            title += " for subject %s" % subject_id

    level1_html_markup = base_reporter.get_subject_report_stats_html_template(
        title=title,
        start_time=start_time,
        subject_id=subject_id,

        # insert source code stub
        source_script_name=user_script_name,
        source_code=user_source_code,
        design_params=design_params,
        methods=methods,
        threshold=threshold)

    with open(stats_report_filename, 'w') as fd:
        fd.write(str(level1_html_markup))
        fd.close()

    progress_logger.log("<b>Level 1 statistics</b><br/><br/>")

    # create design matrix thumbs
    if not design_matrices is None:
        if not hasattr(design_matrices, '__len__'):
            design_matrices = [design_matrices]

        for design_matrix, j in zip(design_matrices,
                                    range(len(design_matrices))):

            # Nistats: design matrices should be strings or pandas dataframes
            if isinstance(design_matrix, _basestring):
                if not isinstance(design_matrix, pd.DataFrame):
                    # XXX should be a DataFrame pickle here ?
                    print(design_matrix)
                    design_matrix = pd.read_pickle(design_matrix)
                else:
                    raise TypeError("Unsupported design matrix type: %s" %
                                    type(design_matrix))

            # plot design_matrix proper
            ax = plot_design_matrix(design_matrix)
            ax.set_position([.05, .25, .9, .65])
            dmat_outfile = os.path.join(output_dir,
                                        'design_matrix_%i.png' % (j + 1))
            pl.savefig(dmat_outfile, bbox_inches="tight", dpi=200)
            pl.close()

            thumb = base_reporter.Thumbnail()
            thumb.a = base_reporter.a(href=os.path.basename(dmat_outfile))
            thumb.img = base_reporter.img(src=os.path.basename(dmat_outfile),
                                          height="500px")
            thumb.description = "Design Matrix"
            thumb.description += " %s" % (
                j + 1) if len(design_matrices) > 1 else ""

            # commit activation thumbnail into gallery
            design_thumbs.commit_thumbnails(thumb)

    # create activation thumbs
    for contrast_id, contrast_val in contrasts.items():
        z_map = z_maps[contrast_id]

        # load the map
        if isinstance(z_map, _basestring):
            z_map = nibabel.load(z_map)

        # generate level 1 stats table
        title = "Level 1 stats for %s contrast" % contrast_id
        stats_table = os.path.join(output_dir,
                                   "%s_stats_table.html" % (contrast_id))
        generate_level1_stats_table(z_map,
                                    mask,
                                    stats_table,
                                    cluster_th=cluster_th,
                                    z_threshold=threshold,
                                    title=title)

        # plot activation proper
        # XXX: nilearn's plotting bug's about rotations inf affine, etc.
        z_map = reorder_img(z_map, resample="continuous")
        if not anat is None:
            anat = reorder_img(anat, resample="continuous")
        plot_stat_map(z_map,
                      anat,
                      threshold=threshold,
                      display_mode=display_mode,
                      cut_coords=cut_coords,
                      black_bg=True)

        # store activation plot
        z_map_plot = os.path.join(output_dir, "%s_z_map.png" % contrast_id)
        pl.savefig(z_map_plot,
                   dpi=200,
                   bbox_inches='tight',
                   facecolor="k",
                   edgecolor="k")
        pl.close()

        # create thumbnail for activation
        thumbnail = base_reporter.Thumbnail(tooltip="Contrast vector: %s" %
                                            contrast_val)
        thumbnail.a = base_reporter.a(href=os.path.basename(stats_table))
        thumbnail.img = base_reporter.img(
            src=os.path.basename(z_map_plot),
            height="150px",
        )
        thumbnail.description = contrast_id
        activation_thumbs.commit_thumbnails(thumbnail)

    # we're done, shut down re-loaders
    progress_logger.log('<hr/>')

    # prevent stats report page from reloading henceforth
    progress_logger.finish(stats_report_filename)

    # prevent any related page from reloading
    if shutdown_all_reloaders:
        progress_logger.finish_dir(output_dir)

    # return generated html
    with open(stats_report_filename, 'r') as fd:
        stats_report = fd.read()
        fd.close()

        return stats_report
Example #32
0
    gr1_idx = data[data.DX_Group == gr[0]].index.values
    gr2_idx = data[data.DX_Group == gr[1]].index.values
    
    gr1_f = x[gr1_idx, :]
    gr2_f = x[gr2_idx, :]

    t = [0]*83
    p = [0]*83
    for i in np.arange(83):
        t[i], p[i] = stats.ttest_ind(gr1_f[:, i], gr2_f[:, i])
    
    # plot t-maps on the brain segmentation
    seg_path = glob.glob(os.path.join(BASE_DIR, 'I221122', '*.nii'))
    seg_img = nib.load(seg_path[0])
    seg_img = image.reorder_img(seg_img, resample='nearest')

    if len(seg_img.shape)==4:
        seg_data = seg_img.get_data()[:, :, :, 0]
    else:
        seg_data = seg_img.get_data()
        
    t_data = np.zeros(seg_data.shape)
    p_data = np.zeros(seg_data.shape)
    idx = 0
    for val in np.unique(seg_data):
        if val > 0:
            t_data[(seg_data == val)] = t[idx]
            p_data[(seg_data == val)] = -np.log10(p[idx])
            idx += 1
            
if not os.path.isdir(pngs_dir):
    os.makedirs(pngs_dir)

#===============================================================================
# Read in the images using nibabel
#===============================================================================
img = nib.load(anat_file)

# Convert the data to float
data = img.get_data()
data = data.astype('float')

# Reslice the image so there are no rotations in the affine.
# This step is actually included in the nilearn plot_anat command below
# but it runs faster if the image has already been resliced.
img_reslice = reorder_img(img, resample='continuous')

# Do the same if you have an overlay file too
if not overlay_file is None:
    overlay_img = nib.load(overlay_file)
    data = overlay_img.get_data()
    data = data.astype('float')
    overlay_img_reslice = reorder_img(overlay_img, resample='nearest')

#===============================================================================
# Plot each slice unless it's empty!
#===============================================================================

# Loop through all the slices in this dimension
for i in np.arange(img_reslice.shape[dim_lookup_dict[axis]], dtype='float'):
Example #34
0
#from .nilearn_custom_utils.nilearn_utils import crop_img_to
data_shape = tuple([0, 3] + list(config['image_shape']))

#print(data_shape)

import nibabel as nib
img = nib.load("/home/jbmai_sai/Documents/image.nii")
import numpy as np
image = nib.load("/home/jbmai_sai/Documents/image.nii")
#import numpy as np

# Get data from nibabel image object (returns numpy memmap object)
#img_data = img.get_data()

interpolation = "linear"
image = reorder_img(image, resample=interpolation)
#print(image.shape)
zoom_level = np.divide(config["image_shape"], image.shape)

print(image.header.get_zooms())
new_spacing = np.divide(image.header.get_zooms(), zoom_level)
print(new_spacing)
#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())

exit()

# -*- coding: utf-8 -*-
"""
A script that uses nilearn to resample a segmentation image
"""

import os, glob, time
import nibabel as nib
from nilearn import plotting, image



input_filename = ''.join(['/disk4t/mehdi/data/pet_fdg_baseline_processed_ADNI/',
                          'I218153/ADNI_011_S_0183_MR_MAPER_segmentation',
                          ',_masked_Br_20110218145719200_S12000_I218153.nii'])
                 

original_img = nib.load(input_filename)
ord_img = image.reorder_img(original_img, resample=True)

close('all')
plotting.plot_img(ord_img)
counter = 0
error_counter = 0
for root, dirs, files in os.walk(BASE_DIR):    
    for d in dirs:
        current_folder = os.path.join(root, d)
        # Load nii image
        filename = glob.glob(os.path.join(current_folder, '*.nii'))
        img = nib.load(filename[0])
        # prepare output image name
        output_fig_name = d
        counter += 1
        plt.clf
        print output_fig_name
        try:
            image.reorder_img(img)
            '''
            plotting.plot_img(img,
                  output_file=os.path.join('figs', output_fig_name),
                  title=str(img.shape),
                  black_bg=True)            
            '''
        except ValueError as exc:
                        
            ord_img = image.reorder_img(img, resample='nearest')
            resampled_image = image.resample_img(ord_img)
            affine = np.eye(4)
            plotting.plot_img(nib.Nifti1Image(img.get_data(), affine),
                  output_file=os.path.join('figures/visualization', output_fig_name+'x'),
                  title=str(img.shape),
                  black_bg=True)
def plot_registration(reference_img, coregistered_img,
                      title="untitled coregistration!",
                      cut_coords=None,
                      display_mode='ortho',
                      cmap=None, close=False,
                      output_filename=None):
    """Plots a coregistered source as bg/contrast for the reference image

    Parameters
    ----------
    reference_img: string
        path to reference (background) image

    coregistered_img: string
        path to other image (to be compared with reference)

    display_mode: string (optional, defaults to 'ortho')
        display_mode param

    cmap: matplotlib colormap object (optional, defaults to spectral)
        colormap to user for plots

    output_filename: string (optional)
        path where plot will be stored

    """
    # sanity
    if cmap is None:
        cmap = plt.cm.gray  # registration QA always gray cmap!

    reference_img = load_vols(reference_img)[0]
    coregistered_img = load_vols(coregistered_img)[0]

    if cut_coords is None:
        cut_coords = (-10, -28, 17)

    if display_mode in ['x', 'y', 'z']:
        cut_coords = (cut_coords['xyz'.index(display_mode)],)

    # XXX nilearn complains about rotations in affine, etc.
    coregistered_img = reorder_img(coregistered_img, resample="continuous")

    _slicer = plot_img(coregistered_img, cmap=cmap, cut_coords=cut_coords,
                       display_mode=display_mode, black_bg=True)

    # XXX nilearn complains about rotations in affine, etc.
    reference_img = reorder_img(reference_img, resample="continuous")

    _slicer.add_edges(reference_img)

    # misc
    _slicer.title(title, size=12, color='w', alpha=0)

    if not output_filename is None:
        try:
            plt.savefig(output_filename, dpi=200, bbox_inches='tight',
                        facecolor="k", edgecolor="k")
            if close:
                plt.close()
        except AttributeError:
            # XXX TODO: handle this case!!
            pass
Example #38
0
def plot_tsdiffs(results, use_same_figure=True):
    ''' Plotting routine for time series difference metrics

    Requires matplotlib

    Parameters
    ----------
    results : dict
        Results of format returned from
        :func:`pypreprocess.time_diff.time_slice_diff`

    use_same_figure : bool
        Whether to put all the plots on the same figure. If False, one
        figure will be created for each plot.

    '''
    import matplotlib.pyplot as plt

    session_lengths = results['session_length']
    session_starts = np.cumsum(session_lengths)[:-1]
    T = len(results['volume_means'])
    S = results['slice_mean_diff2'].shape[1]
    mean_means = np.mean(results['volume_means'])
    scaled_slice_diff = results['slice_mean_diff2'] / mean_means ** 2
    n_plots = 6

    if use_same_figure:
        fig, axes = plt.subplots((n_plots + 1) // 2, 2)
        # Slightly easier to flatten axes to treat the
        # use_same_figure=False case in a similar fashion
        axes = axes.T.reshape(-1)
        fig.set_size_inches(12, 6, forward=True)
        fig.subplots_adjust(top=0.97, bottom=0.08, left=0.1, right=0.98,
                            hspace=0.3, wspace=0.18)
    else:
        axes = [plt.figure().add_subplot(111)
                for _ in range(n_plots - 2)]

    def xmax_labels(ax, val, xlabel, ylabel):
        xlims = ax.axis()
        ax.axis((0, val) + xlims[2:])
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)

    def plot_session_starts(ax):
        for sep_start in session_starts:
            ax.axvline(sep_start, linestyle="--", c="k")

    iter_axes = iter(axes)

    # plot of mean volume variance
    ax = next(iter_axes)
    ax.plot(results['volume_mean_diff2'] / mean_means ** 2)
    # note: squaring the mean to obtain a dimensionless quantity
    xmax_labels(ax, T - 1, 'Image number', 'Scaled variance')
    plot_session_starts(ax)

    # mean intensity
    ax = next(iter_axes)
    ax.plot(results['volume_means'] / mean_means)
    xmax_labels(ax, T,
                'Image number',
                'Scaled mean \n voxel intensity')
    plot_session_starts(ax)

    # slice plots min max mean
    ax = next(iter_axes)
    ax.hold(True)
    ax.plot(np.mean(scaled_slice_diff, 0), 'k')
    ax.plot(np.min(scaled_slice_diff, 0), 'b')
    ax.plot(np.max(scaled_slice_diff, 0), 'r')
    ax.hold(False)
    xmax_labels(ax, S + 1, 'Slice number',
                'Max/mean/min \n slice variation')

    # plot of diff by slice
    ax = next(iter_axes)
    # Set up the color map for the different slices:
    X, Y = np.meshgrid(np.arange(scaled_slice_diff.shape[0]),
                       np.arange(scaled_slice_diff.shape[1]))

    # Use HSV in order to code the slices from bottom to top:
    ax.scatter(X.T.ravel(), scaled_slice_diff.ravel(),
               c=Y.T.ravel(), cmap=plt.cm.hsv,
               alpha=0.2)
    xmax_labels(ax, T - 1,
                'Image number',
                'Slice by slice variance')
    plot_session_starts(ax)

    kwargs = {}
    titles = ['mean squared difference', 'max squared difference']
    for title, which in zip(titles, ["diff2_mean_vol", "slice_diff2_max_vol"]):
        if use_same_figure:
            kwargs["axes"] = next(iter_axes)
        stuff = reorder_img(results[which], resample="continuous")

        # XXX: Passing axes=ax param to plot_stat_map produces miracles!
        # XXX: As a quick fix, we simply plot and then do ax = plt.gca()
        plot_stat_map(stuff, bg_img=None, display_mode='z', cut_coords=5,
                      black_bg=True, title=title, **kwargs)
        if not use_same_figure:
            axes.append(plt.gca())

    return axes
Example #39
0
# In[26]:

path_t2 = os.path.abspath("preprocessed/" + patname + "/T2.nii")

# In[27]:

path_mask = os.path.abspath("preprocessed/" + patname + "/Label.nii")

# In[28]:

T2 = nib.load(path_t2)
MASK = nib.load(path_mask)
T2_org = nib.load(path_t2)
#Reorder to RAS
T2 = reorder_img(T2, resample='continuous')
MASK = reorder_img(MASK, resample='nearest')
image = T2

# In[29]:

print(T2.affine)
print(nib.aff2axcodes(T2.affine))

# In[30]:

new_shape = (256, 256, 64)
zoom_level = np.divide(new_shape, image.shape)
current_spacing = [1, 1, 1] * T2.affine[:3, :3]
new_spacing = np.divide(current_spacing, zoom_level)
Example #40
0
"""
Plotting T1MRI
"""
import os, glob
from nilearn import plotting, image

BASE_DIR = os.path.join('/', 'shfj', 'Ppsypim', 'PSYDAT', 'Subjects')
OUPUT_DIR = os.path.join('figures')

subject_list = os.listdir(BASE_DIR)

for subject_id in subject_list:
    print subject_id
    # fMRI
    """
    fmri_path = os.path.join(BASE_DIR, subject_id, 'MRI', 'MID')
    fmri_list = glob.glob(os.path.join(fmri_path, '[E-S]*.nii'))
    """

    # MRI        
    anat_path = os.path.join(BASE_DIR, subject_id, 'MRI', 'T1MRI')
    anat_list = glob.glob(os.path.join(anat_path, '*.hdr'))
    
    if len(anat_list)>0:      
        anat_name = '_'.join([subject_id, 'anat'])
        r_img_anat = image.reorder_img(anat_list[0], resample='continuous')
        
        plotting.plot_anat(r_img_anat,
                          output_file=os.path.join(OUPUT_DIR, 't1mri', anat_name),
                          title=anat_name,
                          black_bg=True)