Esempio n. 1
0
def check_diag_results(results, img_shape,
                       time_axis, slice_axis, ncomps,
                       out_path, froot, ext='.nii.gz'):

    S = img_shape[slice_axis]
    T = img_shape[time_axis]
    pca_shape = list(img_shape)
    pca_shape[time_axis] = ncomps
    assert_equal(results['pca'].shape, tuple(pca_shape))
    assert_equal(results['pca_res']['basis_projections'].shape,
                 tuple(pca_shape))
    # Roll pca axis last to test shape of output image
    ax_order = list(range(4))
    ax_order.remove(time_axis)
    ax_order.append(time_axis)
    rolled_shape = tuple(pca_shape[i] for i in ax_order)
    pca_img = load_image(pjoin(out_path, 'pca_' + froot + ext))
    assert_equal(pca_img.shape, rolled_shape)
    for prefix in ('mean', 'min', 'max', 'std'):
        fname = pjoin(out_path, prefix + '_' + froot + ext)
        img = load_image(fname)
        assert_equal(img.shape, rolled_shape[:-1])
    vars = np.load(pjoin(out_path, 'vectors_components_' + froot + '.npz'))
    assert_equal(set(vars),
                 set(['basis_vectors', 'pcnt_var', 'volume_means',
                      'slice_mean_diff2']))
    assert_equal(vars['volume_means'].shape, (T,))
    assert_equal(vars['basis_vectors'].shape, (T, T-1))
    assert_equal(vars['slice_mean_diff2'].shape, (T-1, S))
Esempio n. 2
0
def prepocess():
    images = get_files(PRE_IMAGE_PATH)
    labels = get_files(PRE_LABEL_PATH)
    files = get_files(PRE_IMAGE_PATH, prefix=False)

    def normlize_data(image):
        vaild_area = (image >= 0)
        invaild_area = (image < 0)

        image[vaild_area] = np.log(image[vaild_area] + 1)

        i_mean = image[vaild_area].mean()
        i_std = image[vaild_area].std()

        low = i_mean - 3.5 * i_std
        high = i_mean + 3.5 * i_std
        image = (image - low) / (high - low)

        image[invaild_area] = -1
        return image

    for f_i, f_l, f in tqdm(zip(images, labels, files)):
        im = load_image(f_i).get_data()
        label = load_image(f_l).get_data()

        im = normlize_data(im)
        label[label == 2] = 1
        np.save(IMAGE_PATH + f[:-7] + '.npy', im)
        np.save(LABEL_PATH + f[:-7] + '.npy', label)
Esempio n. 3
0
def EDA_warp():
    files = get_files(PRE_IMAGE_PATH, prefix=False)

    labels = []
    images = []
    for i in range(len(files)):
        im = load_image(PRE_IMAGE_PATH + files[i]).get_data()
        if im.shape == (256, 256, 180, 1):
            labels.append(PRE_LABEL_PATH + files[i])
            images.append(PRE_IMAGE_PATH + files[i])

    EDA(labels, images, '180')

    labels = []
    images = []
    for i in range(len(files)):
        im = load_image(PRE_IMAGE_PATH + files[i]).get_data()
        if im.shape == (256, 256, 166, 1):
            labels.append(PRE_LABEL_PATH + files[i])
            images.append(PRE_IMAGE_PATH + files[i])
    EDA(labels, images, '256_166')

    labels = []
    images = []
    for i in range(len(files)):
        im = load_image(PRE_IMAGE_PATH + files[i]).get_data()
        if im.shape == (192, 192, 160, 1):
            labels.append(PRE_LABEL_PATH + files[i])
            images.append(PRE_IMAGE_PATH + files[i])
    EDA(labels, images, '192')
Esempio n. 4
0
def read_niftis(file_list):
    '''Reads niftis from a file list into numpy array.

    Args:
        file_list (int): List of file paths.

    Returns:
        numpy.array: Array of data from nifti file list.
        list: New file list with bad files filtered.

    '''

    data0 = load_image(file_list[0]).get_data()

    x, y, z = data0.shape
    print 'Found %d files with data shape is %r' % (len(file_list), data0.shape)
    n = len(file_list)

    data = []

    new_file_list = []
    for i, f in enumerate(file_list):
        print '%d) Loading subject from file: %s' % (i, f)

        nifti = load_image(f)
        subject_data = nifti.get_data()
        if subject_data.shape != (x, y, z):
            raise ValueError('Shape mismatch')
        data.append(subject_data)
        new_file_list.append(f)
    data = np.array(data).astype('float32')

    return data, new_file_list
Esempio n. 5
0
def read_niftis(file_list):
    '''Finds nifti files in a directory.

    Args:
        source (str): The source directory for niftis

    Returns:
        list: List of file paths.

    '''
    data0 = load_image(file_list[0]).get_data()

    x, y, z, t = data0.shape
    print 'Found %d files with data shape is %r' % (len(file_list), data0.shape)

    data = []

    new_file_list = []
    for i, f in enumerate(file_list):
        print '%d) Loading subject from file: %s' % (i, f)

        nifti = load_image(f)
        subject_data = nifti.get_data()
        if subject_data.shape != (x, y, z, t):
            raise ValueError('Shape mismatch')
        subject_data -= subject_data.mean()
        subject_data /= subject_data.std()
        data.append(subject_data)
        new_file_list.append(f)
    data = np.array(data).transpose(0, 4, 1, 2, 3).astype('float32')

    return data, new_file_list
Esempio n. 6
0
def check_diag_results(results,
                       img_shape,
                       time_axis,
                       slice_axis,
                       ncomps,
                       out_path,
                       froot,
                       ext='.nii.gz'):

    S = img_shape[slice_axis]
    T = img_shape[time_axis]
    pca_shape = list(img_shape)
    pca_shape[time_axis] = ncomps
    assert_equal(results['pca'].shape, tuple(pca_shape))
    assert_equal(results['pca_res']['basis_projections'].shape,
                 tuple(pca_shape))
    # Roll pca axis last to test shape of output image
    ax_order = list(range(4))
    ax_order.remove(time_axis)
    ax_order.append(time_axis)
    rolled_shape = tuple(pca_shape[i] for i in ax_order)
    pca_img = load_image(pjoin(out_path, 'pca_' + froot + ext))
    assert_equal(pca_img.shape, rolled_shape)
    for prefix in ('mean', 'min', 'max', 'std'):
        fname = pjoin(out_path, prefix + '_' + froot + ext)
        img = load_image(fname)
        assert_equal(img.shape, rolled_shape[:-1])
    vars = np.load(pjoin(out_path, 'vectors_components_' + froot + '.npz'))
    assert_equal(
        set(vars),
        set(['basis_vectors', 'pcnt_var', 'volume_means', 'slice_mean_diff2']))
    assert_equal(vars['volume_means'].shape, (T, ))
    assert_equal(vars['basis_vectors'].shape, (T, T - 1))
    assert_equal(vars['slice_mean_diff2'].shape, (T - 1, S))
Esempio n. 7
0
def read_niftis(file_list):
    '''Reads niftis from a file list into numpy array.

    Args:
        file_list (int): List of file paths.

    Returns:
        numpy.array: Array of data from nifti file list.
        list: New file list with bad files filtered.

    '''

    data0 = load_image(file_list[0]).get_data()

    x, y, z = data0.shape
    print 'Found %d files with data shape is %r' % (len(file_list),
                                                    data0.shape)
    n = len(file_list)

    data = []

    new_file_list = []
    for i, f in enumerate(file_list):
        print '%d) Loading subject from file: %s' % (i, f)

        nifti = load_image(f)
        subject_data = nifti.get_data()
        if subject_data.shape != (x, y, z):
            raise ValueError('Shape mismatch')
        data.append(subject_data)
        new_file_list.append(f)
    data = np.array(data).astype('float32')

    return data, new_file_list
Esempio n. 8
0
def read_niftis(file_lists):
    """
    Read niftis.

    Parameters
    ----------
    file_lists: list of list of paths.
        Each list of file paths is a unique class.

    Returns
    -------
    data, labels: tuple of array-like and list
        The data and corresponding labels
    """

    data0 = load_image(file_lists[0][0]).get_data()
    if len(data0.shape) == 3:
        x, y, z = data0.shape
        t = 1
    elif len(data0.shape) == 4:
        x, y, z, t = data0.shape
    else:
        raise ValueError("Cannot parse data with dimensions %r" % data0.shape)

    dt = (sum(len(fl) for fl in file_lists)) * t
    data = np.zeros((dt, x, y, z))

    labels = [[i] * (len(fl) * t) for i, fl in enumerate(file_lists)]
    labels = [item for sublist in labels for item in sublist]

    for i, fl in enumerate(file_lists):
        assert len([j for j in labels if j == i]) == len(fl) * t

    flattened_list = [item for sublist in file_lists for item in sublist]
    for i, f in enumerate(flattened_list):
        logger.info("Loading subject from file: %s%s" % (f, '' * 30))

        nifti = load_image(f)
        subject_data = nifti.get_data()

        if len(subject_data.shape) == 3:
            data[i] = subject_data
        elif len(subject_data.shape) == 4:
            data[i * t: (i + 1) * t] = subject_data.transpose((3, 0, 1, 2))
        else:
            raise ValueError("Cannot parse subject data with dimensions %r"
                             % subject_data.shape)

    logger.info("\rLoading subject from file: %s\n" % ('DONE' + " "*30))
    if data.shape[0] != len(labels):
        raise ValueError("Data and labels have different number of samples.")

    base_file = flattened_list[0]
    # Use nibabel in case we need to convert from 4d to 3d
    base = nib.load(base_file)
    if len(base.shape) == 4:
        base = nib.four_to_three(base)[0]

    return data, labels, base
Esempio n. 9
0
def resample_image(source_file, target_file, outdir, w2wmap=None, order=3,
                   cval=0, verbose=0):
    """ Resample the source image to match the target image using Nipy.

    Parameters
    ----------
    source_file: str (mandatory)
        the image to resample.
    target_file: str (mandatory)
        the reference image.
    outdir: str (mandatory)
        the folder where the resampled image will be saved.
    w2wmap: array (4, 4) or callable
        physical to physical transformation.
    verbose: int (optional, default 0)
        the verbosity level.

    Returns
    -------
    resampled_file: str
        the resampled image.
    """
    # Get target image information
    target_image = nipy.load_image(target_file)
    onto_shape = target_image.shape[:3]
    onto_aff = xyz_affine(target_image.affine, xyz=[0, 1, 2], verbose=verbose)

    # Define index and physical coordinate systems
    arraycoo = "ijklmnopq"[:len(onto_shape)]
    spacecoo = "xyztrsuvw"[:len(onto_shape)]
    if verbose > 0:
        print("\narraycoo: ", arraycoo, "\nspacecoo: ", spacecoo,
              "\nonto_aff\n", onto_aff)
    dmaker = CoordSysMaker(arraycoo, 'generic-array')
    rmaker = CoordSysMaker(spacecoo, 'generic-scanner')
    cm_maker = cmap.CoordMapMaker(dmaker, rmaker)
    cmap_out = cm_maker.make_affine(onto_aff)
    if verbose > 0:
        print("cmap_out:\n", cmap_out)

    # Define the default physical to physical transformation
    if w2wmap is None:
        w2wmap = np.eye(onto_aff.shape[0])
    if verbose > 0:
        print("w2wmap:\n", w2wmap)

    # Resample
    source_image = nipy.load_image(source_file)
    resampled_image = resample(
        source_image, cmap_out, w2wmap, onto_shape, order=order, cval=cval)

    # Save the resampled image
    resampled_file = os.path.join(
        outdir, "resampled_{0}".format(os.path.basename(source_file)))
    nipy.save_image(resampled_image, resampled_file)

    return resampled_file
Esempio n. 10
0
def main(nifti_file, anat_file, roi_file, out_file, thr=2):
    '''
    Main function for running as a script.
    '''
    iscale = 2
    nifti = load_image(nifti_file)
    anat = load_image(anat_file)
    roi_dict = pickle.load(open(roi_file, 'rb'))
    montage(nifti, anat, roi_dict, out_file=out_file)
Esempio n. 11
0
def tissue_classification(img,
                          mask=None,
                          niters=25,
                          beta=0.5,
                          ngb_size=6,
                          probc=None,
                          probg=None,
                          probw=None):
    import numpy as np

    from nipy import load_image, save_image
    from nipy.core.image.image_spaces import (make_xyz_image, xyz_affine)
    from nipy.algorithms.segmentation import BrainT1Segmentation
    import os
    # Input image
    img = load_image(img)

    # Input mask image
    mask_img = mask
    if mask_img == None:
        mask_img = img
    else:
        mask_img = load_image(mask_img)

    # Other optional arguments
    #niters = int(get_argument('niters', 25))
    #beta = float(get_argument('beta', 0.5))
    #ngb_size = int(get_argument('ngb_size', 6))

    # Perform tissue classification
    mask = mask_img.get_data() > 0
    S = BrainT1Segmentation(img.get_data(),
                            mask=mask,
                            model='5k',
                            niters=niters,
                            beta=beta,
                            ngb_size=ngb_size)

    # Save label image
    outfile = os.path.abspath('hard_classif.nii')
    save_image(make_xyz_image(S.label, xyz_affine(img), 'scanner'), outfile)
    print('Label image saved in: %s' % outfile)

    # Compute fuzzy Dice indices if a 3-class fuzzy model is provided
    if not probc == None and\
       not probg == None and\
       not probw == None:
        print('Computing Dice index')
        gold_ppm = np.zeros(S.ppm.shape)
        gold_ppm_img = (probc, probg, probw)
        for k in range(3):
            img = load_image(gold_ppm_img[k])
            gold_ppm[..., k] = img.get_data()
        d = fuzzy_dice(gold_ppm, S.ppm, np.where(mask_img.get_data() > 0))
        print('Fuzzy Dice indices: %s' % d)
Esempio n. 12
0
def affine_registration_nipy(in_path, ref_path, out_path, 
                             in_ref_mat = '', ref_in_mat = '',
                             T = None, extra_params={}):
    """
    Affine registation and resampling. Use Histogram registration from nipy. 
    
    inputs:
        in_path: path to the source (input) image.
        ref_path: path to the target (reference) image.
        out_path: path to use to save the registered image. 
        in_ref_mat: if bool(in_ref_mat) is True, save the 4x4 transformation
                    matrix to a text file <in_ref_mat>. 
        ref_in_mat: if bool(ref_in_mat) is True, save the reverse of the 4x4
                    transformation matrix to a text file <ref_in_mat>. 
        T: affine transformation to use. if None, T will be estimated using 
           HistogramRegistration and optimizers; if type(T) is not Affine, 
           T = Affine(array=T)
        extra_params: extra parameters passing to HistogramRegistration,
                      HistogramRegistration.optimize, resample
        
    return T
    """

    source_image = load_image(in_path)
    target_image = load_image(ref_path)

    if T is None:
        print('assess the affine transformation using histogram registration. ')
        
#        R = HistogramRegistration(source_image, target_image)
        R = AllFeatures(HistogramRegistration,extra_params).run(source_image, target_image)
        
#        T = R.optimize('affine', optimizer='powell')
        T = AllFeatures(R.optimize,extra_params).run('affine', optimizer='powell')
        print('receive affine transformation %s' % T)

    else:
        if type(T) is not Affine:
            print('create Affine from T')
            T = Affine(array=T)
        print('using a predefined affine:\n%s\nwith a 4x4 matrix:\n%s\n' % (T, T.as_affine()))

#    It = resample(source_image, T.inv(), target_image)
    It = AllFeatures(resample,extra_params).run(source_image, T.inv(), target_image)

    # the second argument of resample takes an transformation from ref to mov
    # so that's why we need T.inv() here
    save_image(It, out_path)
    if in_ref_mat:
        np.savetxt(in_ref_mat, T.as_affine())
    if ref_in_mat:
        np.savetxt(ref_in_mat, T.inv().as_affine())
    
    return T
Esempio n. 13
0
def save_montage(NIFTI, ANAT, ONAME, SGN):

    nifti = load_image(NIFTI)
    anat = load_image(ANAT)

    imax = nifti.get_data().max()
    imin = nifti.get_data().min()

    imshow_args = {'vmax': imax, 'vmin': imin}

    mcmap = cmaps[SGN + 1]

    num_features = nifti.shape[-1]
    y = max([1, int(round(sqrt(num_features / 3)))])
    x = int(ceil(num_features / y) + 1)

    font = {'size': 8}
    rc('font', **font)

    f = figure(figsize=[iscale * y, iscale * x / 3])
    subplots_adjust(left=0.01,
                    right=0.99,
                    bottom=0.01,
                    top=0.99,
                    wspace=0.1,
                    hspace=0)

    for i in range(0, num_features):
        data = nifti.get_data()[:, :, :, i]
        data[sign(data) == negative(SGN)] = 0
        if max(abs(data.flatten())) > thr + 0.2:
            ax = subplot(x, y, i + 1)
            max_idx = np.unravel_index(argmax(data), data.shape)
            plot_map(data,
                     xyz_affine(nifti),
                     anat=anat.get_data(),
                     anat_affine=xyz_affine(anat),
                     black_bg=True,
                     threshold=thr,
                     cut_coords=coord_transform(max_idx[0], max_idx[1],
                                                max_idx[2], xyz_affine(nifti)),
                     annotate=False,
                     axes=ax,
                     cmap=mcmap,
                     draw_cross=False,
                     **imshow_args)
            text(0.,
                 0.95,
                 str(i),
                 transform=ax.transAxes,
                 horizontalalignment='center',
                 color=(1, 1, 1))
    savefig(ONAME, facecolor=(0, 0, 0))
Esempio n. 14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-1',
                        '--roi1',
                        type=str,
                        help='Filename of the first ROI image')
    parser.add_argument('-2',
                        '--roi2',
                        type=str,
                        help='Filename of the second ROI image')
    parser.add_argument('-c',
                        '--coord-image',
                        type=str,
                        help='Filename of the coordinates image')
    parser.add_argument('-o',
                        '--output-file',
                        type=str,
                        help='Filename to use for combined ROIs')

    args = parser.parse_args()
    print(args)

    # check that both images exist
    if not os.path.exists(args.roi1):
        print("File '" + args.roi1 + "' does not exist")
    if not os.path.exists(args.roi2):
        print("File '" + args.roi2 + "' does not exist")
    if not os.path.exists(args.coord_image):
        print("File '" + args.coord_image)

    # load both images for the purpose of checking coordinates
    roi1, coords1 = mil.loadBOLD(args.roi1)
    roi2, coords2 = mil.loadBOLD(args.roi2)
    img, imgCoords = mil.loadBOLD(args.coord_image)

    print("roi1", roi1.shape)
    print("roi2", roi2.shape)
    print("coords", img.shape)

    # perform the OR-ing of the 2 rois
    addingImgs = BinaryMaths()
    addingImgs.inputs.in_file = args.roi1
    addingImgs.inputs.operand_file = args.roi2
    addingImgs.inputs.operation = "max"
    addingImgs.inputs.out_file = args.output_file
    addingImgs.run()

    # resample the new roi to be in the coordinate frame of the coordinate image
    jointRoi = load_image(args.output_file)
    coordsImg = load_image(args.coord_image)
    print("joint rois", jointRoi.get_data().shape)
    newRoiImg = resample_img2img(jointRoi, coordsImg, order=0)
    save_image(newRoiImg, args.output_file)
def read_slice(name, dcm1, nii1, shape=512):
    name = ('_').join(name.split('_'))
    print name
    cls = dcm1.split('/')[-2]
    dcm2 = dcm1.replace('edema', 'enhanced')  #
    nii2 = nii1.replace('edema', 'enhanced')
    dir1 = save_dir + 'edema/' + cls + '/'
    dir2 = save_dir + 'enhanced/' + cls + '/'

    for d in [dir1, dir2]:
        if not os.path.exists(d):
            os.makedirs(d)

    inter = False
    mask1 = np.transpose(nipy.load_image(nii1), [2, 1, 0])
    mask2 = np.transpose(nipy.load_image(nii2), [2, 1, 0])
    if mask1.shape[1] != shape or mask2.shape[
            1] != shape:  #or mask3.shape[1] != shape:
        inter = True

    dcms1 = read_dcm(dcm1)
    for i, (ann, dcm) in enumerate(zip(mask1, dcms1)):
        if np.max(ann):
            # print i+1
            if inter:
                dcm, ann = resize(dcm, ann, shape)
            # plt.subplot(121)
            # plt.imshow(dcm, cmap='gray')
            # plt.subplot(122)
            # plt.imshow(ann, cmap='gray')
            # plt.show()

            roi = dcm * ann
            np.save(dir1 + name + '-{}.npy'.format(i + 1), roi)
            # print dir1 +name+'-{}.npy'.format(i+1)

    dcms2 = read_dcm(dcm2)
    for i, (ann, dcm) in enumerate(zip(mask2, dcms2)):
        if np.max(ann):
            # print i+1
            if inter:
                dcm, ann = resize(dcm, ann, shape)
            # plt.subplot(121)
            # plt.imshow(dcm, cmap='gray')
            # plt.subplot(122)
            # plt.imshow(ann, cmap='gray')
            # plt.show()

            roi = dcm * ann
            np.save(dir2 + name + '-{}.npy'.format(i + 1), roi)
Esempio n. 16
0
def test_dims():
    fimg = load_image(funcfile)
    # make sure time dimension is correctly set in affine
    yield assert_equal, fimg.coordmap.affine[3, 3], 2.0
    # should follow, but also make sure affine is invertible
    ainv = fimg.coordmap.inverse
    yield assert_false, ainv is None
Esempio n. 17
0
 def __init__(self, prcsd_bold_data_path, stmls_file_path, TR):
     """
 prcsd_bold_data_path (str): Path to the NIFTI1 file in nii.gz format.
 stmls_file_path (str): Path to the stimulus file covariate.
 TR (float): Time take to record each brain scan.
 """
     self._ni_data = nip.load_image(prcsd_bold_data_path).get_data()
     self._sf_path = stmls_file_path
     self._num_vols = self._ni_data.shape[3]
     self._TR = TR
     # Get the block specification where the 2D data columns represent "start",
     # "end", "amplitude".
     self._block_spec = np.loadtxt(
         self._sf_path)  # start, duration, amplitude.
     # Get "end" from "start" + "duration".
     self._block_spec[0][1] += self._block_spec[0][0]
     self._block_spec[1][1] += self._block_spec[1][0]
     self._task_regressor = block_amplitudes(
         "left_f", self._block_spec,
         np.arange(self._num_vols) * self._TR)[0]
     self._intercept = np.ones(self._num_vols)
     # Prepare the design matrix: X with dimension: # brain vols x # regressors.
     self._design_matrix = np.vstack(
         (self._intercept, self._task_regressor)).T
     # 1st column in design matrix is an intercept, 2nd column is task regressor.
     self._contrast = np.hstack((0, 1))
def expandFrames(imgFn, saveDir):
    """
    Expand a timeseries image into a set of individual frames in the
    specified directory

    Inputs:
    - imgFn: the timeseries image's filename
    - saveDir: the directory in which the frames will be stored

    Returns:
    - frameFns: the list of filenames
    """
    # Load the image
    img = load_image(imgFn)
    coord = img.coordmap
    frameFns = []

    # Make the save directory
    framesDir = saveDir + '/frames/'  # need to check for //
    # check for duplicate //
    framesDir = framesDir.replace("//", '/')
    if not os.path.exists(framesDir):
        os.mkdir(framesDir)

    for i in xrange(img.get_data().shape[3]):
        frame = img[:, :, :, i].get_data()[:, :, :, None]
        frameImg = Image(frame, coord)
        outFn = framesDir + str(i).zfill(3) + ".nii.gz"
        save_image(frameImg, outFn)
        frameFns.append(outFn)

    return frameFns
Esempio n. 19
0
def test_against_matlab_results():
    fimg = load_image(funcfile)
    results = tsd.time_slice_diffs(fimg)
    # struct as record only to avoid deprecation warning
    tsd_results = sio.loadmat(pjoin(TEST_DATA_PATH, 'tsdiff_results.mat'),
                              struct_as_record=True, squeeze_me=True)
    yield assert_array_almost_equal(
        results['volume_means'],
        tsd_results['g'])
    yield assert_array_almost_equal(
        results['volume_mean_diff2'],
        tsd_results['imgdiff'])
    yield assert_array_almost_equal(
        results['slice_mean_diff2'],
        tsd_results['slicediff'])
    # next tests are from saved, reloaded volumes at 16 bit integer
    # precision, so are not exact, but very close, given that the mean
    # of this array is around 3200
    yield assert_array_almost_equal(
        results['diff2_mean_vol'],
        tsd_results['diff2_mean_vol'],
        decimal=1)
    yield assert_array_almost_equal(
        results['slice_diff2_max_vol'],
        tsd_results['slice_diff2_max_vol'],
        decimal=1)
Esempio n. 20
0
def test_nipy_3_4d():
    # Test nipy_3dto4d and nipy_4dto3d
    fimg = load_image(funcfile)
    N = fimg.shape[-1]
    out_4d = 'func4d.nii'
    with InTemporaryDirectory() as tmpdir:
        cmd = ['nipy_4dto3d', funcfile,  '--out-path=' + tmpdir]
        run_command(cmd)
        imgs_3d = ['functional_%04d.nii' % i for i in range(N)]
        for iname in imgs_3d:
            assert_true(isfile(iname))
        cmd = ['nipy_3dto4d'] + imgs_3d  + ['--out-4d=' + out_4d]
        run_command(cmd)
        fimg_back = load_image(out_4d)
        assert_almost_equal(fimg.get_data(), fimg_back.get_data())
        del fimg_back
Esempio n. 21
0
def get_range(images_info):
    variables = ['h1_voxel', 'h2_voxel']

    for vari in variables:
        low_bundary = []
        high_bundary = []
        max_bundary = []
        for file in tqdm(images_info.keys()):
            info = images_info[file]
            image = load_image(PRE_IMAGE_PATH + file).get_data()
            image = np.log(image[image >= 0] + 1)

            # q3 = np.percentile(image,75)
            # q1 = np.percentile(image,25)
            # voxel_max = q3+2*(q3-q1)
            # voxel_min = 0
            voxel_mean = image.mean()
            voxel_std = image.std()
            voxel_max = voxel_mean + 3.5 * voxel_std
            voxel_min = voxel_mean - 3.5 * voxel_std
            voxel_range = voxel_max - voxel_min

            low = np.log(info[vari][0] + 1) - voxel_min
            low_bundary.append(low / voxel_range)
            high = np.log(info[vari][1] + 1) - voxel_min
            high_bundary.append(high / voxel_range)

        low_bundary = sorted(low_bundary)
        high_bundary = sorted(high_bundary)
        print(low_bundary)
        print(high_bundary)
Esempio n. 22
0
def load_epi(datafiles):
    """
    Loads EPIs

    Parameters
    ----------
    datafiles: list
        EPI image files

    Returns
    -------
    data: array_like
        Voxel signal values (M * N; N is the number of samples, M is the
        nubmer of voxels)
    xyz_array: array_like
        Coordiantes of voxels (3 * N)
    """

    data_list = []
    xyz = np.array([])

    for df in datafiles:
        print "Loading %s" % df

        # Load an EPI image
        img = nipy.load_image(df)

        xyz = _check_xyz(xyz, img)
        data_list.append(np.array(img.get_data().flatten(), dtype=np.float64))

    data = np.vstack(data_list)

    return data, xyz
Esempio n. 23
0
def save_4d_data(Hammer_atlas, image_path, path_4d, image_names):
    '''produce nparrays  (voxels in region) x (image in study)
    only if number of images less then 1000
    '''

    region_codes = np.unique(Hammer_atlas._data)
    region_codes = region_codes[region_codes != 0]
    region_coodinates = {
        i: np.where(Hammer_atlas._data == i)
        for i in region_codes
    }
    data_4d = {i: [] for i in region_codes}

    for im in image_names:
        print im
        try:
            images_data = nipy.load_image(os.path.join(image_path, im))._data
            for k in data_4d:
                data_4d[k].append(images_data[region_coodinates[k]])
        except:
            raise ValueError("Error during reading image {}".format(str(im)))

    for c in region_codes:
        c = int(c)
        np_4d = np.array(data_4d[c])
        print np_4d.shape
        np.save(os.path.join(path_4d, str(c) + "_" + str(1)), np_4d)
        convert_array_for_regression(path_4d, c)
        delete_arrays(path_4d, c)
Esempio n. 24
0
    def get_nifti(self, topo_view, base_nifti=None, **kwargs):
        """
        Process the nifti

        Parameters
        ----------
        topo_view: array-like
            Topological view to create nifti. 3D.

        Returns
        -------
        image: nipy image
            Nifti image from topological view.
        """
        if base_nifti is None:
            assert self.base_nifti is not None, ("`base.nii` not in dataset "
                                                 "directory. You may need to "
                                                 "reprocess.")
            base_nifti = self.base_nifti
            image = Image.from_image(base_nifti, data=topo_view)
        else:
            if isinstance(base_nifti, str):
                base_nifti = load_image(base_nifti)
            base2new_affine = np.linalg.inv(base_nifti.affine).dot(
                self.base_nifti.affine)
            cmap = AffineTransform("kji", "zxy", base2new_affine)
            image = Image.from_image(base_nifti, data=topo_view, coordmap=cmap)

        return image
def resample_file(fname_data, fname_out, new_size, new_size_type,
                  interpolation, verbose):
    """This function will resample the specified input
    image file to the target size.
    Can deal with 2d, 3d or 4d image objects.
    :param fname_data: The input image filename.
    :param fname_out: The output image filename.
    :param new_size: The target size, i.e. 0.25x0.25
    :param new_size_type: Unit of resample (mm, vox, factor)
    :param interpolation: The interpolation type
    :param verbose: verbosity level
    """

    # Load data
    sct.printv('\nLoad data...', verbose)
    nii = nipy.load_image(fname_data)

    nii_r = resample_image(nii, new_size, new_size_type, interpolation,
                           verbose)

    # build output file name
    if fname_out == '':
        fname_out = sct.add_suffix(fname_data, '_r')
    else:
        fname_out = fname_out

    # save data
    nipy.save_image(nii_r, fname_out)

    # to view results
    sct.display_viewer_syntax([fname_out], verbose=verbose)

    return nii_r
Esempio n. 26
0
def test_nipy_3_4d():
    # Test nipy_3dto4d and nipy_4dto3d
    fimg = load_image(funcfile)
    N = fimg.shape[-1]
    out_4d = 'func4d.nii'
    with InTemporaryDirectory() as tmpdir:
        cmd = ['nipy_4dto3d', funcfile, '--out-path=' + tmpdir]
        run_command(cmd)
        imgs_3d = ['functional_%04d.nii' % i for i in range(N)]
        for iname in imgs_3d:
            assert_true(isfile(iname))
        cmd = ['nipy_3dto4d'] + imgs_3d + ['--out-4d=' + out_4d]
        run_command(cmd)
        fimg_back = load_image(out_4d)
        assert_almost_equal(fimg.get_data(), fimg_back.get_data())
        del fimg_back
Esempio n. 27
0
def main(nifti_file, anat_file, roi_file, out_file, thr=2):
    '''Main function for running as a script.

    Args:
        nifti (str): path to 4D nifti file.
        anat (str): path to anatomical nifti file.
        roi_file (str): path to pickled roi dictionary file.
        out_file (str): path to output file.
        thr (float): threshold for `nipy.labs.viz.plot_map`

    '''
    iscale = 2
    nifti = load_image(nifti_file)
    anat = load_image(anat_file)
    roi_dict = pickle.load(open(roi_file, 'rb'))
    montage(nifti, anat, roi_dict, out_file=out_file)
Esempio n. 28
0
def save_4d_data(Hammer_atlas, image_path, path_4d, image_names):
    '''produce nparrays  (voxels in region) x (image in study)
    only if number of images less then 1000
    '''


    region_codes=np.unique(Hammer_atlas._data)
    region_codes=region_codes[region_codes!=0]
    region_coodinates={i:np.where(Hammer_atlas._data==i) for i in region_codes}
    data_4d={i:[] for i in region_codes}

    for im in image_names:
        print im
        try:
            images_data=nipy.load_image(os.path.join(image_path, im ))._data
            for k in data_4d:
                data_4d[k].append(images_data[region_coodinates[k]])
        except:
            raise ValueError("Error during reading image {}".format(str(im)))

    for c in region_codes:
            c=int(c)
            np_4d=np.array(data_4d[c])
            print np_4d.shape
            np.save(os.path.join(path_4d, str(c) +"_" + str(1)) ,  np_4d )
            convert_array_for_regression(path_4d, c)
            delete_arrays(path_4d, c)
Esempio n. 29
0
def test_screen():
    img = ni.load_image(funcfile)
    res = screen(img)
    assert_equal(res['mean'].ndim, 3)
    assert_equal(res['pca'].ndim, 4)
    assert_equal(sorted(res.keys()),
                 ['max', 'mean', 'min',
                  'pca', 'pca_res',
                  'std', 'ts_res'])
    data = img.get_data()

    assert_array_equal(np.max(data, axis=-1), res['max'].get_data())
    assert_array_equal(np.mean(data, axis=-1), res['mean'].get_data())
    assert_array_equal(np.min(data, axis=-1), res['min'].get_data())
    assert_array_equal(np.std(data, axis=-1), res['std'].get_data())
    pca_res = pca(data, axis=-1, standardize=False, ncomp=10)
    # On windows, there seems to be some randomness in the PCA output vector
    # signs; this routine sets the basis vectors to have first value positive,
    # and therefore standardized the signs
    pca_res = res2pos1(pca_res)
    screen_pca_res = res2pos1(res['pca_res'])
    for key in pca_res:
        assert_almost_equal(pca_res[key], screen_pca_res[key])
    ts_res = time_slice_diffs(data)
    for key in ts_res:
        assert_array_equal(ts_res[key], res['ts_res'][key])
Esempio n. 30
0
def test_diagnose():
    args = Args()
    img = load_image(funcfile)
    with InTemporaryDirectory() as tmpdir:
        # Copy the functional file to a temporary writeable directory
        os.mkdir('mydata')
        tmp_funcfile = pjoin(tmpdir, 'mydata', 'myfunc.nii.gz')
        shutil.copy(funcfile, tmp_funcfile)
        args.filename = tmp_funcfile
        args.time_axis = None
        args.slice_axis = None
        args.out_path = None
        args.out_fname_label = None
        args.ncomponents = 10
        res = diagnose(args)
        check_diag_results(res, img.shape, 3, 2, 10, 'mydata', 'myfunc')
        args.slice_axis = 'j'
        res = diagnose(args)
        check_diag_results(res, img.shape, 3, 1, 10, 'mydata', 'myfunc')
        # Time axis is not going to work because we'd have to use up one of the
        # needed spatial axes
        args.time_axis = 'i'
        assert_raises(NiftiError, diagnose, args)
        args.time_axis = 't'
        # Check that output works
        os.mkdir('myresults')
        args.out_path = 'myresults'
        args.out_fname_label = 'myana'
        res = diagnose(args)
        check_diag_results(res, img.shape, 3, 1, 10, 'myresults', 'myana')
Esempio n. 31
0
    def get_nifti(self, topo_view, base_nifti=None, **kwargs):
        """
        Process the nifti

        Parameters
        ----------
        topo_view: array-like
            Topological view to create nifti. 3D.

        Returns
        -------
        image: nipy image
            Nifti image from topological view.
        """
        if base_nifti is None:
            assert self.base_nifti is not None, ("`base.nii` not in dataset "
                                                 "directory. You may need to "
                                                 "reprocess.")
            base_nifti = self.base_nifti
            image = Image.from_image(base_nifti, data=topo_view)
        else:
            if isinstance(base_nifti, str):
                base_nifti = load_image(base_nifti)
            base2new_affine = np.linalg.inv(
                base_nifti.affine).dot(self.base_nifti.affine)
            cmap = AffineTransform("kji", "zxy", base2new_affine)
            image = Image.from_image(base_nifti, data=topo_view, coordmap=cmap)

        return image
Esempio n. 32
0
def get_voxel_size(file_path):
    load_image_obj = nipy.load_image(file_path)
    header = load_image_obj.header
    x_size = header['srow_x'][0]
    y_size = header['srow_y'][1]
    z_size = header['srow_z'][2]
    return [x_size, y_size, z_size]
Esempio n. 33
0
def sources_to_nifti(CHECKPOINT, MASKMAT, BASENIFTI, ONAME, savepath, voxels, win):
    bnifti = load_image(BASENIFTI)
    mask = loadmat(MASKMAT)['mask']
    model = np.load(CHECKPOINT) # Numpy array of sources from Infomax ICA

    for i in range(len(model)): # Goes component by component

        W = model[i,:].reshape([voxels,win])

        f = zeros(len(mask))
        idx = where(mask==1)
        data = zeros((bnifti.shape[0],bnifti.shape[1],bnifti.shape[2],W.shape[1]))

        f[idx[0].tolist()] = detrend(W)/std(W)

        for j in range(0,W.shape[1]):
            data[:,:,:,j] = reshape(f,(bnifti.shape[0],bnifti.shape[1],bnifti.shape[2] ), order='F')

        img = Image.from_image(bnifti,data=data)

        os.chdir(savepath)

        fn = ONAME + "%s.nii" % (str(i)) # Where result should be saved and under what name

        save_image(img,fn)
Esempio n. 34
0
def test_diagnose():
    args = Args()
    img = load_image(funcfile)
    with InTemporaryDirectory() as tmpdir:
        # Copy the functional file to a temporary writeable directory
        os.mkdir('mydata')
        tmp_funcfile = pjoin(tmpdir, 'mydata', 'myfunc.nii.gz')
        shutil.copy(funcfile, tmp_funcfile)
        args.filename = tmp_funcfile
        args.time_axis = None
        args.slice_axis = None
        args.out_path = None
        args.out_fname_label = None
        args.ncomponents = 10
        res = diagnose(args)
        check_diag_results(res, img.shape, 3, 2, 10, 'mydata', 'myfunc')
        args.slice_axis = 'j'
        res = diagnose(args)
        check_diag_results(res, img.shape, 3, 1, 10, 'mydata', 'myfunc')
        # Time axis is not going to work because we'd have to use up one of the
        # needed spatial axes
        args.time_axis = 'i'
        assert_raises(NiftiError, diagnose, args)
        args.time_axis = 't'
        # Check that output works
        os.mkdir('myresults')
        args.out_path = 'myresults'
        args.out_fname_label = 'myana'
        res = diagnose(args)
        check_diag_results(res, img.shape, 3, 1, 10, 'myresults', 'myana')
Esempio n. 35
0
def main():
    parser = ArgumentParser(description=DESCRIP,
                            epilog=EPILOG,
                            formatter_class=RawDescriptionHelpFormatter)
    parser.add_argument('filename', type=str,
                        help='4D image filename')
    parser.add_argument('--out-path', type=str,
                        help='path for output image files')
    parser.add_argument('--out-fname-label', type=str,
                        help='mid part of output image filenames')
    parser.add_argument('--ncomponents', type=int, default=10,
                        help='number of PCA components to write')
    # parse the command line
    args = parser.parse_args()
    # process inputs
    filename = args.filename
    out_path = args.out_path
    out_root = args.out_fname_label
    ncomps = args.ncomponents
    # collect extension for output images
    froot, ext, gz = splitext_addext(filename)
    pth, fname = os.path.split(froot)
    if out_path is None:
        out_path = pth
    if out_root is None:
        out_root = fname
    img = nipy.load_image(filename)
    res = nads.screen(img, ncomps)
    nads.write_screen_res(res, out_path, out_root, ext + gz)
Esempio n. 36
0
def test_dims():
    fimg = load_image(funcfile)
    # make sure time dimension is correctly set in affine
    yield assert_equal, fimg.coordmap.affine[3, 3], 2.0
    # should follow, but also make sure affine is invertible
    ainv = fimg.coordmap.inverse
    yield assert_false, ainv is None
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i',
                        '--input',
                        type=str,
                        help="Image that needs center of mass identified")
    args = parser.parse_args()

    # Load the image
    img = load_image(args.input)
    # Get the image data
    data = img.get_data()
    # Threshold the data
    labeled = (data > 0).astype(int)
    # Calculate the properties of the data
    properties = regionprops(labeled, data)
    # Print the centroid
    centroid = properties[0].centroid
    # Round to get the center of mass in voxels
    com = [int(round(i)) for i in centroid]

    # Create the name for the output file
    path = os.path.dirname(args.input)
    outFn = os.path.join(path, "center_of_mass.txt")

    with open(outFn, "w") as f:
        f.write(str(com))

    print("Center of mass located at:", com)
Esempio n. 38
0
def load_epi(datafiles):
    '''Load EPI files.

    The returned data and xyz are flattened by C-like order.

    Parameters
    ----------
    datafiles: list
        EPI image files.

    Returns
    -------
    data: array_like, shape = (M, N)
        Voxel signal values (M: the number of samples, N: the nubmer of
        voxels).
    xyz_array: array_like, shape = (3, N)
        XYZ Coordiantes of voxels.
    '''

    data_list = []
    xyz = np.array([])

    for df in datafiles:
        print("Loading %s" % df)

        # Load an EPI image
        img = nipy.load_image(df)

        xyz = _check_xyz(xyz, img)
        data_list.append(np.array(img.get_data().flatten(), dtype=np.float64))

    data = np.vstack(data_list)

    return data, xyz
Esempio n. 39
0
    def add_overlay(self, overlay, thr, limit, cmap, alpha=0.8):
        overlay = load_image(overlay)
        data = overlay.get_data()
        ovl = normalize_dims(data,self.diag)

        if limit == 'max':
            vmin = thr
            vmax = np.max(ovl)
            print 'using image max of ' + str(vmax) +' as threshold'
            ovl = np.ma.masked_less(ovl, thr)



        elif thr > limit:
            print "One or more overlays have inverse ranges,"
            print "beware of correct colormap!"
            ovl = np.ma.masked_greater(ovl, thr)
            vmax = thr
            vmin = limit

        else:
            ovl = np.ma.masked_less(ovl, thr)
            vmax = limit
            vmin = thr
        self.image_list.append((ovl, cmap, vmax, vmin, alpha))
Esempio n. 40
0
def save_qa_img_dirnme(in4d, outdir):
    pth, nme = os.path.split(in4d)
    img = nipy.load_image(in4d)
    diag.plot_tsdiffs(diag.time_slice_diffs(img))
    cleantime = time.asctime().replace(' ', '-').replace(':', '_')
    figfile = os.path.join(outdir, 'QA_%s_%s.png' % (nme, cleantime))
    pylab.savefig(figfile)
Esempio n. 41
0
def convert_nii_2_npy(nii_file, npy_file=''):
    data = nipy.load_image(nii_file).get_data()
    if npy_file == '':
        npy_file = nii_file[:-4] + '.npy'
        np.save(npy_file, data)
    else:
        np.save(npy_file, data)
Esempio n. 42
0
def save_qa_img_dirnme(in4d, outdir):
    pth, nme = os.path.split(in4d)
    img = nipy.load_image(in4d)
    diag.plot_tsdiffs(diag.time_slice_diffs(img))
    cleantime = time.asctime().replace(' ','-').replace(':', '_')
    figfile = os.path.join(outdir, 'QA_%s_%s.png'%(nme, cleantime))
    pylab.savefig(figfile)
Esempio n. 43
0
def space_time_realign(Images,TR=2,numslices=None,SliceTime='asc_alt_2',RefScan=None):
    '''
    4D simultaneous slice timing and spatial realignment. Adapted from
    Alexis Roche's example script, and extend to be used for multiplex
    imaging sequences
    
    Inputs:
    
        Images: list of images, input as a list of strings
        
        numslices: for non-multiplex sequence, default to be the number of
            slices in the image. For multiplex sequence, enter as a tuple,
            such that the first element is the number of planes acquired in
            parallel between each other, and the second element is the number
            of slices of each parallel plane/slab
        
        SliceTime:enter as a string to specify how the slices are ordered.
            Choices are the following
            1).'ascending': sequential ascending acquisition
            2).'descending': sequential descending acquisition
            3).'asc_alt_2': ascending interleaved, starting at first slice
            4).'asc_alt_2_1': ascending interleaved, starting at the second
                slice
            5).'desc_alt_2': descending interleaved, starting at last slice
            6).'asc_alt_siemens': ascending interleaved, starting at the first
                slice if odd number of slices, or second slice if even number
                of slices
            7).'asc_alt_half': ascending interleaved by half the volume
            8).'desc_alt_half': descending interleaved by half the volume
        
        RefScan: reference volume for spatial realignment movement estimation
    '''
    
    # load images    
    runs = [load_image(run) for run in Images]
    # parse data info
    if numslices is None:
        numslices = runs[0].shape[2]
        numplanes = 1
    elif isinstance(numslices,tuple):
        numslices = numslices[0]
        numplanes = numplanes[1]
    # parse slice timing according to the input
    slice_timing = getattr(timefuncs,SliceTime)(TR,numslices)
    #repeat the slice timing for multiplex seqquence
    slice_timing = np.tile(slice_timing,numplanes)
    # Spatio-temporal realigner assuming interleaved ascending slice order
    R = SpaceTimeRealign(runs, tr=TR, slice_times=slice_timing, slice_info=2,
                         affine_class='Rigid')
    
    print('Slice times: %s' % slice_timing)
    # Estimate motion within- and between-sessions
    R.estimate(refscan=RefScan)
    # Resample data on a regular space+time lattice using 4d interpolation
    print('Saving results ...')
    for i in range(len(runs)):
        corr_run = R.resample(i)
        fname = os.path.join(os.path.split(Images[i])[0],'ra' + os.path.split(Images[i])[1])
        save_image(corr_run, fname)
        print(fname)
Esempio n. 44
0
def __load_mri(fpath):
    '''Load a MRI image.

    - Returns data as 2D array (sample x voxel)
    - Returns voxle xyz coordinates (3 x voxel)
    - Returns voxel ijk indexes (3 x voxel)
    - Data, xyz, and ijk are flattened by Fortran-like index order
    '''
    img = nipy.load_image(fpath)

    data = img.get_data()
    if data.ndim == 4:
        data = data.reshape(-1, data.shape[-1], order='F').T
        i_len, j_len, k_len, t = img.shape
        affine = np.delete(np.delete(img.coordmap.affine, 3, axis=0), 3, axis=1)
    elif data.ndim == 3:
        data = data.flatten(order='F')
        i_len, j_len, k_len = img.shape
        affine = img.coordmap.affine
    else:
        raise ValueError('Invalid shape.')

    ijk = np.array(np.unravel_index(np.arange(i_len * j_len * k_len),
                                    (i_len, j_len, k_len), order='F'))
    ijk_b = np.vstack([ijk, np.ones((1, i_len * j_len * k_len))])
    xyz_b = np.dot(affine, ijk_b)
    xyz = xyz_b[:-1]

    return data, xyz, ijk
Esempio n. 45
0
def resample_file(fname_data, fname_out, new_size, new_size_type,
                  interpolation, verbose):
    """This function will resample the specified input
    image file to the target size.

    :param fname_data: The input image filename.
    :param fname_out: The output image filename.
    :param new_size: The target size, i.e. 0.25x0.25
    :param new_size_type: Unit of resample (mm, vox, factor)
    :param interpolation: The interpolation type
    :param verbose: verbosity level
    """

    # Load data
    sct.printv('\nLoad data...', verbose)
    nii = nipy.load_image(fname_data)

    nii_r = resample_image(nii, new_size, new_size_type, interpolation,
                           verbose)

    # build output file name
    if fname_out == '':
        fname_out = sct.add_suffix(fname_data, '_r')
    else:
        fname_out = fname_out

    # save data
    nipy.save_image(nii_r, fname_out)

    # to view results
    sct.printv('\nDone! To view results, type:', verbose)
    sct.printv('fslview ' + fname_out + ' &', verbose, 'info')

    return nii_r
Esempio n. 46
0
def save_image(nifti, anat, cluster_dict, out_path, f, image_threshold=2,
               texcol=1, bgcol=0, iscale=2, text=None, **kwargs):
    '''Saves a single nifti image.

    Args:
        nifti (str or nipy.core.api.image.image.Image): nifti file to visualize.
        anat (nipy.core.api.image.image.Image): anatomical nifti file.
        cluster_dict (dict): dictionary of clusters.
        f (int): index.
        image_threshold (float): treshold for `plot_map`.
        texcol (float): text color.
        bgcol (float): background color.
        iscale (float): image scale.
        text (Optional[str]): text for figure.
        **kwargs: extra keyword arguments

    '''
    if isinstance(nifti, str):
        nifti = load_image(nifti)
        feature = nifti.get_data()
    elif isinstance(nifti, nipy.core.image.image.Image):
        feature = nifti.get_data()
    font = {'size': 8}
    rc('font', **font)

    coords = cluster_dict['top_clust']['coords']
    if coords == None:
        return

    feature /= feature.std()
    imax = np.max(np.absolute(feature))
    imin = -imax
    imshow_args = dict(
        vmax=imax,
        vmin=imin,
        alpha=0.7
    )

    coords = ([-coords[0], -coords[1], coords[2]])

    plt.axis('off')
    plt.text(0.05, 0.8, text, horizontalalignment='center',
             color=(texcol, texcol, texcol))

    try:
        plot_map(feature,
                 xyz_affine(nifti),
                 anat=anat.get_data(),
                 anat_affine=xyz_affine(anat),
                 threshold=image_threshold,
                 cut_coords=coords,
                 annotate=False,
                 cmap=cmap,
                 draw_cross=False,
                 **imshow_args)
    except Exception as e:
        return

    plt.savefig(out_path, transparent=True, facecolor=(bgcol, bgcol, bgcol))
Esempio n. 47
0
def test_screen():
    img = ni.load_image(funcfile)
    res = screen(img)
    assert_equal(res['mean'].ndim, 3)
    assert_equal(res['pca'].ndim, 4)
    assert_equal(sorted(res.keys()),
                 ['max', 'mean', 'min',
                  'pca', 'pca_res',
                  'std', 'ts_res'])
    data = img.get_data()
    # Check summary images
    assert_array_equal(np.max(data, axis=-1), res['max'].get_data())
    assert_array_equal(np.mean(data, axis=-1), res['mean'].get_data())
    assert_array_equal(np.min(data, axis=-1), res['min'].get_data())
    assert_array_equal(np.std(data, axis=-1), res['std'].get_data())
    pca_res = pca(data, axis=-1, standardize=False, ncomp=10)
    # On windows, there seems to be some randomness in the PCA output vector
    # signs; this routine sets the basis vectors to have first value positive,
    # and therefore standardizes the signs
    pca_res = res2pos1(pca_res)
    _check_pca(res, pca_res)
    _check_ts(res, data, 3, 2)
    # Test that screens accepts and uses time axis
    data_mean = data.mean(axis=-1)
    res = screen(img, time_axis='t')
    assert_array_equal(data_mean, res['mean'].get_data())
    _check_pca(res, pca_res)
    _check_ts(res, data, 3, 2)
    res = screen(img, time_axis=-1)
    assert_array_equal(data_mean, res['mean'].get_data())
    _check_pca(res, pca_res)
    _check_ts(res, data, 3, 2)
    t0_img = rollimg(img, 't')
    t0_data = np.rollaxis(data, -1)
    res = screen(t0_img, time_axis='t')
    t0_pca_res = pca(t0_data, axis=0, standardize=False, ncomp=10)
    t0_pca_res = res2pos1(t0_pca_res)
    assert_array_equal(data_mean, res['mean'].get_data())
    _check_pca(res, t0_pca_res)
    _check_ts(res, t0_data, 0, 3)
    res = screen(t0_img, time_axis=0)
    assert_array_equal(data_mean, res['mean'].get_data())
    _check_pca(res, t0_pca_res)
    _check_ts(res, t0_data, 0, 3)
    # Check screens uses slice axis
    s0_img = rollimg(img, 2, 0)
    s0_data = np.rollaxis(data, 2, 0)
    res = screen(s0_img, slice_axis=0)
    _check_ts(res, s0_data, 3, 0)
    # And defaults to named slice axis
    # First re-show that when we don't specify, we get the default
    res = screen(img)
    _check_ts(res, data, 3, 2)
    assert_raises(AssertionError, _check_ts, res, data, 3, 0)
    # Then specify, get non-default
    slicey_img = img.renamed_axes(i='slice')
    res = screen(slicey_img)
    _check_ts(res, data, 3, 0)
    assert_raises(AssertionError, _check_ts, res, data, 3, 2)
def tissue_classification(img,mask=None,niters=25,beta=0.5,ngb_size=6,probc=None,probg=None,probw=None):
    import numpy as np

    from nipy import load_image, save_image
    from nipy.core.image.image_spaces import (make_xyz_image,
                                              xyz_affine)
    from nipy.algorithms.segmentation import BrainT1Segmentation
    import os
    # Input image
    img = load_image(img)

    # Input mask image
    mask_img = mask
    if mask_img == None:
        mask_img = img
    else:
        mask_img = load_image(mask_img)

    # Other optional arguments
    #niters = int(get_argument('niters', 25))
    #beta = float(get_argument('beta', 0.5))
    #ngb_size = int(get_argument('ngb_size', 6))

    # Perform tissue classification
    mask = mask_img.get_data() > 0
    S = BrainT1Segmentation(img.get_data(), mask=mask, model='5k',
        niters=niters, beta=beta, ngb_size=ngb_size)

    # Save label image
    outfile = os.path.abspath('hard_classif.nii')
    save_image(make_xyz_image(S.label, xyz_affine(img), 'scanner'),
        outfile)
    print('Label image saved in: %s' % outfile)

    # Compute fuzzy Dice indices if a 3-class fuzzy model is provided
    if not probc == None and\
       not probg == None and\
       not probw == None:
        print('Computing Dice index')
        gold_ppm = np.zeros(S.ppm.shape)
        gold_ppm_img = (probc, probg, probw)
        for k in range(3):
            img = load_image(gold_ppm_img[k])
            gold_ppm[..., k] = img.get_data()
        d = fuzzy_dice(gold_ppm, S.ppm, np.where(mask_img.get_data() > 0))
        print('Fuzzy Dice indices: %s' % d)
Esempio n. 49
0
def test_nipy_3_4d():
    # Test nipy_3dto4d and nipy_4dto3d
    fimg = load_image(funcfile)
    N = fimg.shape[-1]
    out_4d = 'func4d.nii'
    with InTemporaryDirectory() as tmpdir:
        # Quotes in case of space in arguments
        cmd = 'nipy_4dto3d "%s" --out-path="%s"' % (funcfile, tmpdir)
        run_command(cmd)
        imgs_3d = ['functional_%04d.nii' % i for i in range(N)]
        for iname in imgs_3d:
            assert_true(isfile(iname))
        cmd = 'nipy_3dto4d "%s" --out-4d="%s"' % ('" "'.join(imgs_3d), out_4d)
        run_command(cmd)
        fimg_back = load_image(out_4d)
        assert_almost_equal(fimg.get_data(), fimg_back.get_data())
        del fimg_back
Esempio n. 50
0
def smooth_mask_nipy(infile, outfile, fwhm=14):
    """uses nipy to smooth an image using gaussian filter of fwhm"""
    img = nipy.load_image(infile)
    lf = nipy.algorithms.kernel_smooth.LinearFilter(img.coordmap,
                                                    img.shape,
                                                    fwhm)
    simg = lf.smooth(img)
    outimg = nipy.save_image(simg, outfile)
    return outimg
Esempio n. 51
0
def sample_map_allen_space(image_path, annot_csv_path, save_path, type='well_id'):
    #assign values to samples in MNI space

    I=nipy.load_image(image_path)
    image_name=os.path.basename(image_path)
    df=pd.DataFrame.from_csv(annot_csv_path)
    coordinate, well_id=(np.array( df['mri_voxel_x']) , np.array(df['mri_voxel_y']), np.array(df['mri_voxel_z'] )), df[type]
    I._data[np.where(I._data!=0)]=0
    I._data[coordinate]=well_id
    nipy.save_image(I, os.path.join(save_path, image_name))
Esempio n. 52
0
def test_nipy_diagnose():
    # Test nipy diagnose script
    fimg = load_image(funcfile)
    ncomps = 12
    with InTemporaryDirectory() as tmpdir:
        cmd = ['nipy_diagnose', funcfile,
               '--ncomponents={0}'.format(ncomps),
               '--out-path=' + tmpdir]
        run_command(cmd)
        for out_fname in ('components_functional.png',
                          'pcnt_var_functional.png',
                          'tsdiff_functional.png',
                          'vectors_components_functional.npz'):
            assert_true(isfile(out_fname))
        for out_img in ('max_functional.nii.gz',
                        'mean_functional.nii.gz',
                        'min_functional.nii.gz',
                        'std_functional.nii.gz'):
            img = load_image(out_img)
            assert_equal(img.shape, fimg.shape[:-1])
            del img
        pca_img = load_image('pca_functional.nii.gz')
        assert_equal(pca_img.shape, fimg.shape[:-1] + (ncomps,))
        vecs_comps = np.load('vectors_components_functional.npz')
        vec_diff = vecs_comps['slice_mean_diff2'].copy()# just in case
        assert_equal(vec_diff.shape, (fimg.shape[-1]-1, fimg.shape[2]))
        del pca_img, vecs_comps
    with InTemporaryDirectory() as tmpdir:
        # Check we can pass in slice and time flags
        s0_img = rollimg(fimg, 'k')
        save_image(s0_img, 'slice0.nii')
        cmd = ['nipy_diagnose', 'slice0.nii',
               '--ncomponents={0}'.format(ncomps),
               '--out-path=' + tmpdir,
               '--time-axis=t',
               '--slice-axis=0']
        run_command(cmd)
        pca_img = load_image('pca_slice0.nii')
        assert_equal(pca_img.shape, s0_img.shape[:-1] + (ncomps,))
        vecs_comps = np.load('vectors_components_slice0.npz')
        assert_almost_equal(vecs_comps['slice_mean_diff2'], vec_diff)
        del pca_img, vecs_comps
Esempio n. 53
0
def read_niftis(file_list):
    data0 = load_image(file_list[0]).get_data()

    x, y, z = data0.shape
    print 'Found %d files with data shape is %r' % (len(file_list), data0.shape)
    n = len(file_list)

    data = []

    new_file_list = []
    for i, f in enumerate(file_list):
        print '%d) Loading subject from file: %s' % (i, f)

        nifti = load_image(f)
        subject_data = nifti.get_data()
        if subject_data.shape != (x, y, z):
            raise ValueError('Shape mismatch')
        data.append(subject_data)
        new_file_list.append(f)
    data = np.array(data).astype('float32')

    return data, new_file_list
Esempio n. 54
0
def test_write_screen_res():
    img = ni.load_image(funcfile)
    with InTemporaryDirectory():
        res = screen(img)
        os.mkdir('myresults')
        write_screen_res(res, 'myresults', 'myana')
        pca_img = ni.load_image(pjoin('myresults', 'pca_myana.nii'))
        assert_equal(pca_img.shape, img.shape[:-1] + (10,))
        # Make sure we get the same output image even from rolled image
        # Do fancy roll to put time axis first, and slice axis last. This does
        # a stress test on the axis ordering, but also makes sure that we are
        # getting the number of components from the right place.  If we were
        # getting the number of components from the length of the last axis,
        # instead of the length of the 't' axis in the returned pca image, this
        # would be wrong (=21) which would also be more than the number of
        # basis vectors (19) so raise an error
        rimg = img.reordered_axes([3, 2, 0, 1])
        os.mkdir('rmyresults')
        rres = screen(rimg)
        write_screen_res(rres, 'rmyresults', 'myana')
        rpca_img = ni.load_image(pjoin('rmyresults', 'pca_myana.nii'))
        assert_equal(rpca_img.shape, img.shape[:-1] + (10,))
        del pca_img, rpca_img
Esempio n. 55
0
    def load(self):

        if os.path.isfile(os.path.join(DATA_DIR,self.name,'Probes.csv')):
            print 'Start reading {} csv data'.format(self.name)
            with Timer() as t:
                self.pacall=pd.read_csv(os.path.join(DATA_DIR,self.name,'PACall.csv'), header=None).as_matrix()[:,1:]
                self.probes=pd.read_csv(os.path.join(DATA_DIR,self.name,'Probes.csv'))
                self.expression=pd.read_csv(os.path.join(DATA_DIR,self.name,'MicroarrayExpression.csv'), header=None).as_matrix()[:,1:]
                self.anot=pd.read_csv(os.path.join(DATA_DIR,self.name,'SampleAnnot_edit.csv'))
            print 'Finished in {}s'.format(t.secs)
            self.data_type='csv'
            self.data_path=os.path.join(DATA_DIR,self.name)
            self.sample_map=nipy.load_image(SAMPLE_MRI[self.name])

        elif os.path.isfile(os.path.join(DATA_DIR,self.name,self.name+'.db')):
            print 'Connecting to {} sql database...'.format(self.name)
            con=sql.connect(os.path.join(DATA_DIR,self.name,self.name+'.db'))
            print 'Connected'
            self.sample_map=nipy.load_image(SAMPLE_MRI[self.name])
            self.data_path=os.path.join(DATA_DIR,self.name)
            self.data_type='sql'
        else:
            raise ValueError('There is no Allen Brain data in {}'.format(os.path.join(DATA_DIR,self.name)))
Esempio n. 56
0
    def __init__(self, background):
        self.background = load_image(background)
        data = self.background.get_data()
        self.diag = self.background.affine.diagonal()[:3]
        self.x_trans, self.y_trans, self.z_trans = np.abs(self.diag)

        bg = normalize_dims(data, self.diag)

        vmax = bg.max()*.70
        vmin = bg.min()*.95

        self.xmin,self.xmax, self.ymin,self.ymax, self.zmin,self.zmax = get_crop(bg)
        self.image_list = []
        self.image_list.append((bg,cm.Greys_r, vmax, vmin, 1))