Python nibabel 模块,Nifti1Image() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用nibabel.Nifti1Image()

项目:segmentation_DLMI    作者:imatge-upc    | 项目源码 | 文件源码
def load_ROI_mask(self):

        proxy = nib.load(self.FLAIR_FILE)
        image_array = np.asarray(proxy.dataobj)

        mask = np.ones_like(image_array)
        mask[np.where(image_array < 90)] = 0

        # img = nib.Nifti1Image(mask, proxy.affine)
        # nib.save(img, join(modalities_path,'mask.nii.gz'))

        struct_element_size = (20, 20, 20)
        mask_augmented = np.pad(mask, [(21, 21), (21, 21), (21, 21)], 'constant', constant_values=(0, 0))
        mask_augmented = binary_closing(mask_augmented, structure=np.ones(struct_element_size, dtype=bool)).astype(
            np.int)

        return mask_augmented[21:-21, 21:-21, 21:-21].astype('bool')
项目:ISLES2017    作者:MiguelMonteiro    | 项目源码 | 文件源码
def export_data(prediction_dir, nii_image_dir, tfrecords_dir, export_dir, transformation=None):

    for file_path in os.listdir(prediction_dir):
        name, prediction, probability = read_prediction_file(os.path.join(prediction_dir, file_path))

        if transformation:
            image, ground_truth = get_original_image(os.path.join(tfrecords_dir, name + '.tfrecord'), False)
            prediction = transformation.transform_image(prediction, probability, image)

        # build cv_predictions .nii image
        img = nib.Nifti1Image(prediction, np.eye(4))
        img.set_data_dtype(dtype=np.uint8)

        path = os.path.join(nii_image_dir, name)

        adc_name = next(l for l in os.listdir(path) if 'MR_ADC' in l)
        export_image = nib.load(os.path.join(nii_image_dir, name, adc_name, adc_name + '.nii'))

        i = export_image.get_data()
        i[:] = img.get_data()

        # set name to specification and export
        _id = next(l for l in os.listdir(path) if 'MR_MTT' in l).split('.')[-1]
        export_path = os.path.join(export_dir, 'SMIR.' + name + '.' + _id + '.nii')
        nib.save(export_image, os.path.join(export_path))
项目:brats17    作者:xf4j    | 项目源码 | 文件源码
def batch_works(k):
    if k == n_processes - 1:
        paths = all_paths[k * int(len(all_paths) / n_processes) : ]
    else:
        paths = all_paths[k * int(len(all_paths) / n_processes) : (k + 1) * int(len(all_paths) / n_processes)]

    for path in paths:
        probs = np.load(os.path.join(input_path, path))
        pred = np.argmax(probs, axis=3)
        fg_prob = 1 - probs[..., 0]
        pred = clean_contour(fg_prob, pred)
        seg = np.zeros(pred.shape, dtype=np.int16)
        seg[pred == 1] = 1
        seg[pred == 2] = 2
        seg[pred == 3] = 4
        img = nib.Nifti1Image(seg, np.eye(4))
        nib.save(img, os.path.join(output_path, path.replace('_probs.npy', '.nii.gz')))
项目:modl    作者:arthurmensch    | 项目源码 | 文件源码
def _make_test_data(n_subjects=8, noisy=False):
    rng = np.random.RandomState(0)
    shape = (20, 20, 1)
    components = _make_components(shape)
    if noisy:  # Creating noisy non positive data
        components[rng.randn(*components.shape) > .8] *= -5.
        for component in components:
            assert(component.max() <= -component.min())  # Goal met ?

    # Create a "multi-subject" dataset
    data = _make_data_from_components(components, n_subjects=n_subjects)
    affine = np.eye(4)
    mask_img = nibabel.Nifti1Image(np.ones(shape, dtype=np.int8),
                                   affine)
    masker = MultiNiftiMasker(mask_img).fit()
    init = components + 1 * rng.randn(*components.shape)
    components = masker.inverse_transform(components)
    init = masker.inverse_transform(init)
    data = masker.inverse_transform(data)

    return data, mask_img, components, init
项目:mriqc    作者:poldracklab    | 项目源码 | 文件源码
def _binarize(in_file, threshold=0.5, out_file=None):
    import os.path as op
    import numpy as np
    import nibabel as nb

    if out_file is None:
        fname, ext = op.splitext(op.basename(in_file))
        if ext == '.gz':
            fname, ext2 = op.splitext(fname)
            ext = ext2 + ext
        out_file = op.abspath('{}_bin{}'.format(fname, ext))

    nii = nb.load(in_file)
    data = nii.get_data()

    data[data <= threshold] = 0
    data[data > 0] = 1

    hdr = nii.header.copy()
    hdr.set_data_dtype(np.uint8)
    nb.Nifti1Image(data.astype(np.uint8), nii.affine, hdr).to_filename(
        out_file)
    return out_file
项目:mriqc    作者:poldracklab    | 项目源码 | 文件源码
def image_gradient(in_file, snr, out_file=None):
    """Computes the magnitude gradient of an image using numpy"""
    import os.path as op
    import numpy as np
    import nibabel as nb
    from scipy.ndimage import gaussian_gradient_magnitude as gradient

    if out_file is None:
        fname, ext = op.splitext(op.basename(in_file))
        if ext == '.gz':
            fname, ext2 = op.splitext(fname)
            ext = ext2 + ext
        out_file = op.abspath('{}_grad{}'.format(fname, ext))

    imnii = nb.load(in_file)
    data = imnii.get_data().astype(np.float32)  # pylint: disable=no-member
    datamax = np.percentile(data.reshape(-1), 99.5)
    data *= 100 / datamax
    grad = gradient(data, 3.0)
    gradmax = np.percentile(grad.reshape(-1), 99.5)
    grad *= 100.
    grad /= gradmax

    nb.Nifti1Image(grad, imnii.get_affine(), imnii.get_header()).to_filename(out_file)
    return out_file
项目:mriqc    作者:poldracklab    | 项目源码 | 文件源码
def thresh_image(in_file, thres=0.5, out_file=None):
    """Thresholds an image"""
    import os.path as op
    import nibabel as nb

    if out_file is None:
        fname, ext = op.splitext(op.basename(in_file))
        if ext == '.gz':
            fname, ext2 = op.splitext(fname)
            ext = ext2 + ext
        out_file = op.abspath('{}_thresh{}'.format(fname, ext))

    im = nb.load(in_file)
    data = im.get_data()
    data[data < thres] = 0
    data[data > 0] = 1
    nb.Nifti1Image(
        data, im.get_affine(), im.get_header()).to_filename(out_file)
    return out_file
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_set_new_data_simple_modifications():

    aff = np.eye(4); aff[2, 1] = 42.0

    im_0 = nib.Nifti1Image(np.zeros([3,3,3]), affine=aff)
    im_0_header = im_0.header
    # default intent_code
    assert_equals(im_0_header['intent_code'], 0)
    # change intento code
    im_0_header['intent_code'] = 5

    # generate new nib from the old with new data
    im_1 = set_new_data(im_0, np.ones([3,3,3]))
    im_1_header = im_1.header
    # see if the infos are the same as in the modified header
    assert_array_equal(im_1.get_data()[:], np.ones([3,3,3]))
    assert_equals(im_1_header['intent_code'], 5)
    assert_array_equal(im_1.get_affine(), aff)
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_stack_images_cascade():

    d = 2
    im1 = nib.Nifti1Image(np.zeros([d,d]), affine=np.eye(4))
    assert_array_equal(im1.shape, (d, d))

    list_images1 = [im1] * d
    im2 = stack_images(list_images1)
    assert_array_equal(im2.shape, (d,d,d))

    list_images2 = [im2] * d
    im3 = stack_images(list_images2)
    assert_array_equal(im3.shape, (d,d,d,d))

    list_images3 = [im3] * d
    im4 = stack_images(list_images3)
    assert_array_equal(im4.shape, (d, d, d, d, d))
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_remove_nan():
    data_ts = np.array([[[0, 1, 2, 3],
                         [4, 5, np.nan, 7],
                         [8, 9, 10, np.nan]],

                        [[12, 13, 14, 15],
                         [16, np.nan, 18, 19],
                         [20, 21, 22, 23]]])
    im = nib.Nifti1Image(data_ts, np.eye(4))
    im_no_nan = remove_nan(im)

    data_no = np.array([[[0, 1, 2, 3],
                         [4, 5, 0, 7],
                         [8, 9, 10, 0]],

                        [[12, 13, 14, 15],
                         [16, 0, 18, 19],
                         [20, 21, 22, 23]]])

    assert_array_equal(im_no_nan.get_data(), data_no)
项目:ndmg    作者:neurodata    | 项目源码 | 文件源码
def tensor2fa(tensors, tensor_name, dti, derivdir, qcdir):
    '''
    outdir: location of output directory.
    fname: name of output fa map file. default is none (name created based on
    input file)
    '''
    dti_data = nb.load(dti)
    affine = dti_data.get_affine()
    dti_data = dti_data.get_data()

    # create FA map
    FA = fractional_anisotropy(tensors.evals)
    FA[np.isnan(FA)] = 0

    # generate the RGB FA map
    FA = np.clip(FA, 0, 1)
    RGB = color_fa(FA, tensors.evecs)

    fname = os.path.split(tensor_name)[1].split(".")[0] + '_fa_rgb.nii.gz'
    fa = nb.Nifti1Image(np.array(255 * RGB, 'uint8'), affine)
    nb.save(fa, derivdir + fname)

    fa_pngs(fa, fname, qcdir)
项目:niworkflows    作者:poldracklab    | 项目源码 | 文件源码
def test_ROIsPlot(oasis_dir):
    """ the BET report capable test """
    import nibabel as nb
    import numpy as np

    labels = nb.load(os.path.join(oasis_dir, 'T_template0_glm_4labelsJointFusion.nii.gz'))
    data = labels.get_data()
    out_files = []
    ldata = np.zeros_like(data)
    for i, l in enumerate([1, 3, 4, 2]):
        ldata[data == l] = 1
        out_files.append(os.path.abspath('label%d.nii.gz' % i))
        lfile = nb.Nifti1Image(ldata, labels.affine, labels.header)
        lfile.to_filename(out_files[-1])

    roi_rpt = ROIsPlot(
        generate_report=True,
        in_file=os.path.join(oasis_dir, 'T_template0.nii.gz'),
        in_mask=out_files[-1],
        in_rois=out_files[:-1],
        colors=['g', 'y']
    )
    _smoke_test_report(roi_rpt, 'testROIsPlot.svg')
项目:pyAFQ    作者:yeatmanlab    | 项目源码 | 文件源码
def test_register_dwi():
    fdata, fbval, fbvec = dpd.get_data('small_64D')
    with nbtmp.InTemporaryDirectory() as tmpdir:
        # Use an abbreviated data-set:
        img = nib.load(fdata)
        data = img.get_data()[..., :10]
        nib.save(nib.Nifti1Image(data, img.affine),
                 op.join(tmpdir, 'data.nii.gz'))
        # Convert from npy to txt:
        bvals = np.load(fbval)
        bvecs = np.load(fbvec)
        np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals[:10])
        np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs[:10])
        reg_file = register_dwi(op.join(tmpdir, 'data.nii.gz'),
                                op.join(tmpdir, 'bvals.txt'),
                                op.join(tmpdir, 'bvecs.txt'))
        npt.assert_(op.exists(reg_file))
项目:bruker2nifti    作者:SebastianoF    | 项目源码 | 文件源码
def test_set_new_data_basic():

    data_1 = np.random.normal(5, 10, [10, 10, 5])
    affine_1 = np.diag([1, 2, 3, 1])

    data_2 = np.random.normal(5, 10, [3, 2, 4]).astype(np.float32)
    im_data_1 = nib.Nifti1Image(data_1, affine_1)
    im_data_1.set_data_dtype(np.uint8)
    im_data_1.header['descrip'] = 'Spam'

    im_data_2 = set_new_data(im_data_1, data_2)

    assert_array_equal(im_data_2.get_data(), data_2)
    assert_array_equal(im_data_2.get_affine(), affine_1)
    assert_equal(im_data_2.header['descrip'], b'Spam')
    assert_equal(im_data_1.get_data_dtype(), np.uint8)
    assert_equal(im_data_2.get_data_dtype(), np.float32)
项目:brain_segmentation    作者:Ryo-Ito    | 项目源码 | 文件源码
def preprocess(inputfile, outputfile, order=0, df=None, input_key=None, output_key=None):
    img = nib.load(inputfile)
    data = img.get_data()
    affine = img.affine
    zoom = img.header.get_zooms()[:3]
    data, affine = reslice(data, affine, zoom, (1., 1., 1.), order)
    data = np.squeeze(data)
    data = np.pad(data, [(0, 256 - len_) for len_ in data.shape], "constant")
    if order == 0:
        if df is not None:
            tmp = np.zeros_like(data)
            for target, source in zip(df[output_key], df[input_key]):
                tmp[np.where(data == source)] = target
            data = tmp
        data = np.int32(data)
        assert data.ndim == 3, data.ndim
    else:
        data_sub = data - gaussian_filter(data, sigma=1)
        img = sitk.GetImageFromArray(np.copy(data_sub))
        img = sitk.AdaptiveHistogramEqualization(img)
        data_clahe = sitk.GetArrayFromImage(img)[:, :, :, None]
        data = np.concatenate((data_clahe, data[:, :, :, None]), 3)
        data = (data - np.mean(data, (0, 1, 2))) / np.std(data, (0, 1, 2))
        assert data.ndim == 4, data.ndim
        assert np.allclose(np.mean(data, (0, 1, 2)), 0.), np.mean(data, (0, 1, 2))
        assert np.allclose(np.std(data, (0, 1, 2)), 1.), np.std(data, (0, 1, 2))
        data = np.float32(data)
    img = nib.Nifti1Image(data, affine)
    nib.save(img, outputfile)
项目:pyconnectome    作者:neurospin    | 项目源码 | 文件源码
def roi_from_bbox(
        input_file,
        bbox,
        output_file):
    """ Create a ROI image from a bounding box.

    Parameters
    ----------
    input_file: str
        the reference image where the bbox is defined.
    bbox: 6-uplet
        the corner of the bbox in voxel coordinates: xmin, xmax, ymin, ymax,
        zmin, zmax.
    output_file: str
        the desired ROI image file.
    """
    # Load the reference image and generate a grid
    im = nibabel.load(input_file)
    xv, yv, zv = numpy.meshgrid(
        numpy.linspace(0, im.shape[0] - 1, im.shape[0]),
        numpy.linspace(0, im.shape[1] - 1, im.shape[1]),
        numpy.linspace(0, im.shape[2] - 1, im.shape[2]))
    xv = xv.astype(int)
    yv = yv.astype(int)
    zv = zv.astype(int)

    # Intersect the grid with the bbox
    xa = numpy.bitwise_and(xv >= bbox[0], xv <= bbox[1])
    ya = numpy.bitwise_and(yv >= bbox[2], yv <= bbox[3])
    za = numpy.bitwise_and(zv >= bbox[4], zv <= bbox[5])

    # Generate bbox indices
    indices = numpy.bitwise_and(numpy.bitwise_and(xa, ya), za)

    # Generate/save ROI
    roi = numpy.zeros(im.shape, dtype=int)
    roi[xv[indices].tolist(), yv[indices].tolist(), zv[indices].tolist()] = 1
    roi_im = nibabel.Nifti1Image(roi, affine=im.get_affine())
    nibabel.save(roi_im, output_file)
项目:pyconnectome    作者:neurospin    | 项目源码 | 文件源码
def extract_image(in_file, index, out_file=None):
    """ Extract the image at 'index' position.

    Parameters
    ----------
    in_file: str (mandatory)
        the input image.
    index: int (mandatory)
        the index of last image dimention to extract.
    out_file: str (optional, default None)
        the name of the extracted image file.

    Returns
    -------
    out_file: str
        the name of the extracted image file.
    """
    # Set default output if necessary
    dirname = os.path.dirname(in_file)
    basename = os.path.basename(in_file).split(".")[0]
    if out_file is None:
        out_file = os.path.join(
            dirname, "extract{0}_{1}.nii.gz".format(index, basename))

    # Extract the image of interest
    image = nibabel.load(in_file)
    affine = image.get_affine()
    extracted_array = image.get_data()[..., index]
    extracted_image = nibabel.Nifti1Image(extracted_array, affine)
    nibabel.save(extracted_image, out_file)

    return out_file
项目:acdc_segmenter    作者:baumgach    | 项目源码 | 文件源码
def save_nii(img_path, data, affine, header):
    '''
    Shortcut to save a nifty file
    '''

    nimg = nib.Nifti1Image(data, affine=affine, header=header)
    nimg.to_filename(img_path)
项目:LiviaNET    作者:josedolz    | 项目源码 | 文件源码
def saveImageAsNifti(imageToSave,
                     imageName,
                     imageOriginalName,
                     imageType):

    printFileNames = False

    if printFileNames == True:
        print(" ... Saving image in {}".format(imageName))

    [imageData,img_proxy] = load_nii(imageOriginalName, printFileNames)

    # Generate the nii file
    niiToSave = nib.Nifti1Image(imageToSave, img_proxy.affine)
    niiToSave.set_data_dtype(imageType)

    dim = len(imageToSave.shape)
    zooms = list(img_proxy.header.get_zooms()[:dim])
    if len(zooms) < dim :
        zooms = zooms + [1.0]*(dim-len(zooms))

    niiToSave.header.set_zooms(zooms)
    nib.save(niiToSave, imageName)

    print "... Image succesfully saved..."


## ========= For Matlab files ========== ##
项目:brainiak    作者:brainiak    | 项目源码 | 文件源码
def extract_data(nifti_file, mask_file, out_file, zscore, detrend, smoothing_fwmw):
    if mask_file is None:
        #whole brain, get coordinate info from nifti_file itself
        mask = nib.load(nifti_file.name)
    else:
        mask = nib.load(mask_file.name)
    affine = mask.get_affine()
    if mask_file is None:
        mask_data = mask.get_data()
        if mask_data.ndim == 4:
            #get mask in 3D
            img_data_type = mask.header.get_data_dtype()
            n_tr = mask_data.shape[3]
            mask_data = mask_data[:,:,:,n_tr//2].astype(bool)
            mask = nib.Nifti1Image(mask_data.astype(img_data_type), affine)
        else:
            mask_data = mask_data.astype(bool)
    else:
        mask_data = mask.get_data().astype(bool)

    #get voxel coordinates
    R = np.float64(np.argwhere(mask_data))

    #get scanner RAS coordinates based on voxel coordinates
    if affine is not []:
        R = (np.dot(affine[:3,:3], R.T) + affine[:3,3:4]).T

    #get ROI data, and run preprocessing
    nifti_masker = NiftiMasker(mask_img=mask, standardize=zscore, detrend=detrend, smoothing_fwhm=smoothing_fwmw)
    img = nib.load(nifti_file.name)
    all_images = np.float64(nifti_masker.fit_transform(img))
    data = all_images.T.copy()

    #save data
    subj_data = {'data': data, 'R': R}
    scipy.io.savemat(out_file.name, subj_data)
项目:pisap    作者:neurospin    | 项目源码 | 文件源码
def save(self, image, outpath):
        """ A method that save the image data and associated metadata.

        Parameters
        ----------
        image: Image
            the image to be saved.
        outpath: str
            the path where the the image will be saved.
        """
        diag = (1. / image.spacing).tolist() + [1]
        _image = nibabel.Nifti1Image(image.data, numpy.diag(diag))
        nibabel.save(_image, outpath)
项目:MDT    作者:cbclab    | 项目源码 | 文件源码
def write_nifti(data, output_fname, header=None, affine=None, use_data_dtype=True, **kwargs):
    """Write data to a nifti file.

    This will write the output directory if it does not exist yet.

    Args:
        data (ndarray): the data to write to that nifti file
        output_fname (str): the name of the resulting nifti file, this function will append .nii.gz if no
            suitable extension is given.
        header (nibabel header): the nibabel header to use as header for the nifti file. If None we will use
            a default header.
        affine (ndarray): the affine transformation matrix
        use_data_dtype (boolean): if we want to use the dtype from the data instead of that from the header
            when saving the nifti.
        **kwargs: other arguments to Nifti2Image from NiBabel
    """
    if header is None:
        header = nib.nifti2.Nifti2Header()

    if use_data_dtype:
        header = copy.deepcopy(header)
        dtype = data.dtype
        if data.dtype == np.bool:
            dtype = np.char
        try:
            header.set_data_dtype(dtype)
        except nib.spatialimages.HeaderDataError:
            pass

    if not (output_fname.endswith('.nii.gz') or output_fname.endswith('.nii')):
        output_fname += '.nii.gz'

    if not os.path.exists(os.path.dirname(output_fname)):
        os.makedirs(os.path.dirname(output_fname))

    if isinstance(header, nib.nifti2.Nifti2Header):
        format = nib.Nifti2Image
    else:
        format = nib.Nifti1Image

    format(data, affine, header=header, **kwargs).to_filename(output_fname)
项目:miccai17-mmwhs-hybrid    作者:xy0806    | 项目源码 | 文件源码
def remove_minor_cc(vol_data, rej_ratio, rename_map):
    """Remove small connected components refer to rejection ratio"""
    """Usage
        # rename_map = [0, 205, 420, 500, 550, 600, 820, 850]
        # nii_path = '/home/xinyang/project_xy/mmwhs2017/dataset/ct_output/test/test_4.nii'
        # vol_file = nib.load(nii_path)
        # vol_data = vol_file.get_data().copy()
        # ref_affine = vol_file.affine
        # rem_vol = remove_minor_cc(vol_data, rej_ratio=0.2, class_n=8, rename_map=rename_map)
        # # save
        # rem_path = 'rem_cc.nii'
        # rem_vol_file = nib.Nifti1Image(rem_vol, ref_affine)
        # nib.save(rem_vol_file, rem_path)

        #===# possible be parallel in future
    """

    rem_vol = copy.deepcopy(vol_data)
    class_n = len(rename_map)
    # retrieve all classes
    for c in range(1, class_n):
        print 'processing class %d...' % c

        class_idx = (vol_data==rename_map[c])*1
        class_vol = np.sum(class_idx)
        labeled_cc, num_cc = measurements.label(class_idx)
        # retrieve all connected components in this class
        for cc in range(1, num_cc+1):
            single_cc = ((labeled_cc==cc)*1)
            single_vol = np.sum(single_cc)
            # remove if too small
            if single_vol / (class_vol*1.0) < rej_ratio:
                rem_vol[labeled_cc==cc] = 0

    return rem_vol
项目:som    作者:vsoch    | 项目源码 | 文件源码
def read_series(dicoms,return_nifti=True):
    '''read_series will read in a series of dicoms belonging to a group
    :param dicoms: a list of dicom files to parse, assumed in same series and
    equal size
    :param return_nifti: If True (default) will turn image as Nifti File
    '''
    # Sort the dicoms
    dicoms.sort()

    # Get the size of the image
    params = sniff_header(dicoms[0])
    xdim = params['xdim']
    ydim = params['ydim']   
    windom_center = params['window_center']

    bot.debug("First dicom found with dimension %s by %s, using as standard." %(xdim,ydim))

    # Let's get ordering of images based on InstanceNumber
    ordered = dict()
    for d in range(len(dicoms)):    
        ds = dicom.read_file(dicoms[d])
        if ds.Rows == xdim and ds.Columns == ydim:
            ordered[int(ds.InstanceNumber)] = ds.pixel_array

    # Sort by order
    zdim = len(ordered)    
    data = numpy.ndarray((xdim,ydim,zdim))

    # Start at window center, then go back to zero
    index = 0
    for key in sorted(ordered.keys()):
        data[:,:,index] = ordered[key]
        index +=1

    if return_nifti == True:
        affine = numpy.diag((1,1,1,0))
        data = nibabel.Nifti1Image(data,affine=affine)
    return data
项目:mriqc    作者:poldracklab    | 项目源码 | 文件源码
def _enhance(in_file, out_file=None):
    import os.path as op
    import numpy as np
    import nibabel as nb

    if out_file is None:
        fname, ext = op.splitext(op.basename(in_file))
        if ext == '.gz':
            fname, ext2 = op.splitext(fname)
            ext = ext2 + ext
        out_file = op.abspath('{}_enhanced{}'.format(fname, ext))

    imnii = nb.load(in_file)
    data = imnii.get_data().astype(np.float32)  # pylint: disable=no-member
    range_max = np.percentile(data[data > 0], 99.98)
    range_min = np.median(data[data > 0])

    # Resample signal excess pixels
    excess = np.where(data > range_max)
    data[excess] = 0
    data[excess] = np.random.choice(data[data > range_min], size=len(excess[0]))

    nb.Nifti1Image(data, imnii.get_affine(), imnii.get_header()).to_filename(
        out_file)

    return out_file
项目:mriqc    作者:poldracklab    | 项目源码 | 文件源码
def reorient_and_discard_non_steady(in_file, float32=False):
    import nibabel as nb
    import os
    import numpy as np
    import nibabel as nb
    from statsmodels.robust.scale import mad

    _, outfile = os.path.split(in_file)

    nii = nb.as_closest_canonical(nb.load(in_file))
    in_data = nii.get_data()

    # downcast to reduce space consumption and improve performance
    if float32 and np.dtype(in_data.dtype).itemsize > 4:
        in_data = in_data.astype(np.float32)

    data = in_data[:, :, :, :50]
    timeseries = data.max(axis=0).max(axis=0).max(axis=0)
    outlier_timecourse = (timeseries - np.median(timeseries)) / mad(
        timeseries)
    exclude_index = 0
    for i in range(10):
        if outlier_timecourse[i] > 10:
            exclude_index += 1
        else:
            break

    nb.Nifti1Image(in_data[:, :, :, exclude_index:], nii.affine, nii.header).to_filename(outfile)
    nii.uncache()
    return exclude_index, os.path.abspath(outfile)
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_compare_two_nib_equals():

    im_0 = nib.Nifti1Image(np.zeros([3, 3, 3]), affine=np.eye(4))
    im_1 = nib.Nifti1Image(np.zeros([3, 3, 3]), affine=np.eye(4))
    assert_equals(compare_two_nib(im_0, im_1), True)
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_compare_two_nib_different_nifti_version():

    im_0 = nib.Nifti1Image(np.zeros([3, 3, 3]), affine=np.eye(4))
    im_1 = nib.Nifti2Image(np.zeros([3, 3, 3]), affine=np.eye(4))
    assert_equals(compare_two_nib(im_0, im_1), False)
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_compare_two_nib_different_affine():

    aff_1 = np.eye(4)
    aff_1[3,3] = 5
    im_0 = nib.Nifti1Image(np.zeros([3, 3, 3]), affine=np.eye(4))
    im_1 = nib.Nifti1Image(np.zeros([3, 3, 3]), affine=aff_1)
    assert_equals(compare_two_nib(im_0, im_1), False)


# def test_eliminates_consecutive_duplicates():
#
#     l_in = [0,0,0,1,1,2,3,4,5,5,5,6,7,8,9]
#     l_out = range(10)
#     assert_array_equal(eliminates_consecutive_duplicates(l_in), l_out)
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_covariance_matrices():
    arr_1 = np.array([[[0, 0, 0, 0, 0, 0, 0, 0, 0],
                       [0, 0, 0, 0, 0, 0, 0, 0, 0],
                       [0, 1, 1, 1, 1, 1, 0, 0, 0],
                       [0, 1, 1, 1, 1, 1, 0, 0, 0],
                       [0, 1, 1, 1, 1, 1, 2, 2, 0],
                       [0, 1, 1, 1, 1, 1, 2, 2, 0],
                       [0, 1, 1, 1, 1, 1, 0, 3, 3],
                       [0, 0, 0, 0, 0, 0, 0, 3, 3],
                       [0, 0, 0, 0, 0, 3, 3, 3, 3]],

                      [[0, 0, 0, 0, 0, 0, 0, 0, 0],
                       [0, 0, 0, 0, 0, 0, 0, 0, 0],
                       [0, 1, 1, 1, 1, 1, 0, 0, 0],
                       [0, 1, 1, 1, 1, 1, 0, 0, 0],
                       [0, 1, 1, 1, 1, 1, 2, 2, 0],
                       [0, 1, 1, 1, 1, 1, 2, 2, 0],
                       [0, 1, 1, 1, 1, 1, 0, 0, 3],
                       [0, 0, 0, 0, 0, 0, 0, 3, 3],
                       [0, 0, 0, 0, 0, 0, 3, 3, 3]]
                      ])

    im1 = nib.Nifti1Image(arr_1, np.eye(4))

    cov =  covariance_matrices(im1, [1, 2, 3])
    assert len(cov) == 3
    for i in cov:
        assert_array_equal(i.shape, [3, 3])
        if np.count_nonzero(i - np.diag(np.diagonal(i))) == 0:
            assert_array_equal(np.diag(np.diag(i)), i)

    cov1 = covariance_matrices(im1, [1, 2, 3, 4])
    assert_array_equal(cov1[-1], np.nan * np.ones([3, 3]))
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_covariance_distance_range():
    factor = 10
    m1 = np.random.randint(3, size=[20, 20, 20])
    im1 = nib.Nifti1Image(m1, np.eye(4))
    for _ in range(20):
        m2 = np.random.randint(3, size=[20, 20, 20])
        im2 = nib.Nifti1Image(m2, np.eye(4))
        cd = covariance_distance(im1, im2, [1, 2], ['label1', 'label2'], factor=factor)
        print m1
        print m2
        print cd
        assert 0 <= cd['label1'] <= factor
        assert 0 <= cd['label2'] <= factor
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def test_set_new_header_description():
    arr_data = np.zeros([10,10,10])
    im = nib.Nifti1Image(arr_data, np.eye(4))

    hd = im.header
    hd['descrip'] = 'Old Spam'

    im_new_header = set_new_header_description(im, new_header_description='New Spam')

    new_hd = im_new_header.header
    assert new_hd['descrip'] == 'New Spam'
项目:LabelsManager    作者:SebastianoF    | 项目源码 | 文件源码
def set_new_data(image, new_data, new_dtype=None, remove_nan=True):
    """
    From a nibabel image and a numpy array it creates a new image with
    the same header of the image and the new_data as its data.
    :param image: nibabel image
    :param new_data:
    :param new_dtype: numpy array
    :param remove_nan:
    :return: nibabel image
    """
    hd = image.header
    if remove_nan:
        new_data = np.nan_to_num(new_data)

    # update data type:
    if new_dtype is not None:
        new_data = new_data.astype(new_dtype)
        image.set_data_dtype(new_dtype)

    # if nifty1
    if hd['sizeof_hdr'] == 348:
        new_image = nib.Nifti1Image(new_data, image.affine, header=hd)
    # if nifty2
    elif hd['sizeof_hdr'] == 540:
        new_image = nib.Nifti2Image(new_data, image.affine, header=hd)
    else:
        raise IOError('Input image header problem')

    return new_image
项目:segmentation    作者:zengyu714    | 项目源码 | 文件源码
def save_as_nii(y, savename):
    y_nii = nib.Nifti1Image(y.astype(np.uint8), np.eye(4))
    nib.save(y_nii, savename + '.nii')
项目:cnn-ms-lesion-segmentation    作者:sergivalverde    | 项目源码 | 文件源码
def test_scan(model, test_x_data, options, save_nifti= True, candidate_mask = None):
    """
    Test data based on one model 
    Input: 
    - test_x_data: a nested dictionary containing training image paths: 
            train_x_data['scan_name']['modality'] = path_to_image_modality
    - save_nifti: save image segmentation 
    - candidate_mask: a binary masks containing voxels to classify

    Output:
    - test_scan = Output image containing the probability output segmetnation 
    - If save_nifti --> Saves a nifti file at specified location options['test_folder']/['test_scan']
    """

    # get_scan name and create an empty nifti image to store segmentation
    scans = test_x_data.keys()
    flair_scans = [test_x_data[s]['FLAIR'] for s in scans]
    flair_image = load_nii(flair_scans[0])
    seg_image = np.zeros_like(flair_image.get_data())


    # compute lesion segmentation in batches of size options['batch_size'] 
    for batch, centers in load_test_patches(test_x_data, options['patch_size'], options['batch_size'], candidate_mask):
        y_pred = model.predict_proba(np.squeeze(batch))
        [x, y, z] = np.stack(centers, axis=1)
        seg_image[x, y, z] = y_pred[:, 1]

    if save_nifti:
        out_scan = nib.Nifti1Image(seg_image, affine=flair_image.affine)
        out_scan.to_filename(os.path.join(options['test_folder'], options['test_scan'], options['experiment'], options['test_name']))
        #out_scan.to_filename(os.path.join(test_folder, scan, options['experiment'], options['test_name']))

    return seg_image
项目:cnn-ms-lesion-segmentation    作者:sergivalverde    | 项目源码 | 文件源码
def post_process_segmentation(input_scan, options, save_nifti = True):
    """
    Post-process the probabilistic segmentation using parameters t_bin and l_min
    t_bin: threshold to binarize the output segmentations 
    l_min: minimum lesion volume

    Inputs: 
    - input_scan: probabilistic input image (segmentation)
    - options dictionary
    - save_nifti: save the result as nifti 

    Output:
    - output_scan: final binarized segmentation 
    """

    from scipy import ndimage

    t_bin = options['t_bin']
    l_min = options['l_min']
    output_scan = np.zeros_like(input_scan)

    # threshold input segmentation
    t_segmentation = input_scan >= t_bin

    # filter candidates by size and store those > l_min
    labels, num_labels = ndimage.label(t_segmentation)
    label_list = np.unique(labels)
    num_elements_by_lesion = ndimage.labeled_comprehension(t_segmentation, labels, label_list, np.sum, float, 0)

    for l in range(len(num_elements_by_lesion)):
        if num_elements_by_lesion[l]>l_min:
            # assign voxels to output
            current_voxels = np.stack(np.where(labels == l), axis =1)
            output_scan[current_voxels[:,0], current_voxels[:,1], current_voxels[:,2]] = 1

    #save the output segmentation as Nifti1Image
    if save_nifti:
        nifti_out = nib.Nifti1Image(output_scan, np.eye(4))
        nifti_out.to_filename(os.path.join(options['test_folder'], options['test_scan'], options['experiment'], options['test_name']))

    return output_scan
项目:cnn-ms-lesion-segmentation    作者:sergivalverde    | 项目源码 | 文件源码
def test_scan(model, test_x_data, options, save_nifti= True, candidate_mask = None):
    """
    Test data based on one model 
    Input: 
    - test_x_data: a nested dictionary containing training image paths: 
            train_x_data['scan_name']['modality'] = path_to_image_modality
    - save_nifti: save image segmentation 
    - candidate_mask: a binary masks containing voxels to classify

    Output:
    - test_scan = Output image containing the probability output segmetnation 
    - If save_nifti --> Saves a nifti file at specified location options['test_folder']/['test_scan']
    """

    # get_scan name and create an empty nifti image to store segmentation
    scans = test_x_data.keys()
    flair_scans = [test_x_data[s]['FLAIR'] for s in scans]
    flair_image = load_nii(flair_scans[0]).get_data()
    seg_image = np.zeros_like(flair_image)

    # compute lesion segmentation in batches of size options['batch_size'] 
    for batch, centers in load_test_patches(test_x_data, options['patch_size'], options['batch_size'], candidate_mask):
        y_pred = model.predict_proba(np.squeeze(batch))
        [x, y, z] = np.stack(centers, axis=1)
        seg_image[x, y, z] = y_pred[:, 1]

    if save_nifti:
        out_scan = nib.Nifti1Image(seg_image, np.eye(4))
        out_scan.to_filename(os.path.join(options['test_folder'], options['test_scan'], options['experiment'], options['test_name']))

    return seg_image
项目:cnn-ms-lesion-segmentation    作者:sergivalverde    | 项目源码 | 文件源码
def post_process_segmentation(input_scan, options, save_nifti = True):
    """
    Post-process the probabilistic segmentation using parameters t_bin and l_min
    t_bin: threshold to binarize the output segmentations 
    l_min: minimum lesion volume

    Inputs: 
    - input_scan: probabilistic input image (segmentation)
    - options dictionary
    - save_nifti: save the result as nifti 

    Output:
    - output_scan: final binarized segmentation 
    """

    from scipy import ndimage

    t_bin = options['t_bin']
    l_min = options['l_min']
    output_scan = np.zeros_like(input_scan)

    # threshold input segmentation
    t_segmentation = input_scan >= t_bin

    # filter candidates by size and store those > l_min
    labels, num_labels = ndimage.label(t_segmentation)
    label_list = np.unique(labels)
    num_elements_by_lesion = ndimage.labeled_comprehension(t_segmentation, labels, label_list, np.sum, float, 0)

    for l in range(len(num_elements_by_lesion)):
        if num_elements_by_lesion[l]>l_min:
            # assign voxels to output
            current_voxels = np.stack(np.where(labels == l), axis =1)
            output_scan[current_voxels[:,0], current_voxels[:,1], current_voxels[:,2]] = 1

    #save the output segmentation as Nifti1Image
    if save_nifti:
        nifti_out = nib.Nifti1Image(output_scan, np.eye(4))
        nifti_out.to_filename(os.path.join(options['test_folder'], options['test_scan'], options['experiment'], options['test_name']))

    return output_scan
项目:sim    作者:big-data-lab-team    | 项目源码 | 文件源码
def save_nifti(x, output, client):
    filename = x[0].split('/')[-1]
    im = nib.Nifti1Image(x[1][1], x[1][0])
    nib.save(im, filename)
    client.upload(output,filename, overwrite=True)
    return (x[0], 0)
项目:sim    作者:big-data-lab-team    | 项目源码 | 文件源码
def get_data(x):
    fh = nib.FileHolder(fileobj=GzipFile(fileobj=BytesIO(x[1])))
    im = nib.Nifti1Image.from_file_map({'header': fh, 'image': fh})
    return (x[0], (im.affine, im.get_data()))
项目:sim    作者:big-data-lab-team    | 项目源码 | 文件源码
def save_nifti(x):
    filename = x[0].split('/')[-1]
    im = nib.Nifti1Image(x[1][1], x[1][0])
    nib.save(im, os.path.join('/run/user/1000', filename))
    return filename
项目:sim    作者:big-data-lab-team    | 项目源码 | 文件源码
def get_data(x):
    fh = nib.FileHolder(fileobj=GzipFile(fileobj=BytesIO(x[1])))
    im = nib.Nifti1Image.from_file_map({'header': fh, 'image': fh})
    return (x[0], (im.affine, im.get_data()))
项目:openfmri    作者:gablab    | 项目源码 | 文件源码
def median(in_files):
    """Computes an average of the median of each realigned timeseries

    Parameters
    ----------

    in_files: one or more realigned Nifti 4D time series

    Returns
    -------

    out_file: a 3D Nifti file
    """
    average = None
    for idx, filename in enumerate(filename_to_list(in_files)):
        img = nb.load(filename)
        data = np.median(img.get_data(), axis=3)
        if average is None:
            average = data
        else:
            average = average + data
    median_img = nb.Nifti1Image(average / float(idx + 1), img.affine,
                                img.header)
    filename = os.path.join(os.getcwd(), 'median.nii.gz')
    median_img.to_filename(filename)
    return filename
项目:openfmri    作者:gablab    | 项目源码 | 文件源码
def bandpass_filter(files, lowpass_freq, highpass_freq, fs):
    """Bandpass filter the input files

    Parameters
    ----------
    files: list of 4d nifti files
    lowpass_freq: cutoff frequency for the low pass filter (in Hz)
    highpass_freq: cutoff frequency for the high pass filter (in Hz)
    fs: sampling rate (in Hz)
    """
    out_files = []
    for filename in filename_to_list(files):
        path, name, ext = split_filename(filename)
        out_file = os.path.join(os.getcwd(), name + '_bp' + ext)
        img = nb.load(filename)
        timepoints = img.shape[-1]
        F = np.zeros((timepoints))
        lowidx = int(timepoints / 2) + 1
        if lowpass_freq > 0:
            lowidx = np.round(float(lowpass_freq) / fs * timepoints)
        highidx = 0
        if highpass_freq > 0:
            highidx = np.round(float(highpass_freq) / fs * timepoints)
        F[highidx:lowidx] = 1
        F = ((F + F[::-1]) > 0).astype(int)
        data = img.get_data()
        if np.all(F == 1):
            filtered_data = data
        else:
            filtered_data = np.real(np.fft.ifftn(np.fft.fftn(data) * F))
        img_out = nb.Nifti1Image(filtered_data, img.affine, img.header)
        img_out.to_filename(out_file)
        out_files.append(out_file)
    return list_to_filename(out_files)
项目:ndmg    作者:neurodata    | 项目源码 | 文件源码
def load_bval_bvec_dti(self, fbval, fbvec, dti_file, dti_file_out):
        """
        Takes bval and bvec files and produces a structure in dipy format

        **Positional Arguments:**
        """

        # Load Data
        img = nb.load(dti_file)
        data = img.get_data()

        bvals, bvecs = read_bvals_bvecs(fbval, fbvec)

        # Get rid of spurrious scans
        idx = np.where((bvecs[:, 0] == 100) & (bvecs[:, 1] == 100) &
                       (bvecs[:, 2] == 100))
        bvecs = np.delete(bvecs, idx, axis=0)
        bvals = np.delete(bvals, idx, axis=0)
        data = np.delete(data, idx, axis=3)

        # Save corrected DTI volume
        dti_new = nb.Nifti1Image(data, affine=img.get_affine(),
                                 header=img.get_header())
        dti_new.update_header()
        nb.save(dti_new, dti_file_out)

        gtab = gradient_table(bvals, bvecs, atol=0.01)

        print(gtab.info)
        return gtab
项目:niworkflows    作者:poldracklab    | 项目源码 | 文件源码
def mask(in_file, mask_file, new_name):
    import nibabel as nb
    import os

    in_nii = nb.load(in_file)
    mask_nii = nb.load(mask_file)
    data = in_nii.get_data()
    data[mask_nii.get_data() == 0] = 0
    new_nii = nb.Nifti1Image(data, in_nii.affine, in_nii.header)
    new_nii.to_filename(new_name)
    return os.path.abspath(new_name)
项目:niworkflows    作者:poldracklab    | 项目源码 | 文件源码
def _run_interface(self, runtime):
        orig_file_nii = nb.load(self.inputs.in_file)
        in_file_data = orig_file_nii.get_data()

        # pad the data to avoid the mask estimation running into edge effects
        in_file_data_padded = np.pad(in_file_data, (1, 1), 'constant',
                                     constant_values=(0, 0))

        padded_nii = nb.Nifti1Image(in_file_data_padded, orig_file_nii.affine,
                                    orig_file_nii.header)

        mask_nii = compute_epi_mask(padded_nii, exclude_zeros=True)

        mask_data = mask_nii.get_data()
        if isdefined(self.inputs.dilation):
            mask_data = nd.morphology.binary_dilation(mask_data).astype(np.uint8)

        # reverse image padding
        mask_data = mask_data[1:-1, 1:-1, 1:-1]

        # exclude zero and NaN voxels
        mask_data[in_file_data == 0] = 0
        mask_data[np.isnan(in_file_data)] = 0

        better_mask = nb.Nifti1Image(mask_data, orig_file_nii.affine,
                                     orig_file_nii.header)
        better_mask.set_data_dtype(np.uint8)
        better_mask.to_filename("mask_file.nii.gz")

        self._mask_file = os.path.abspath("mask_file.nii.gz")

        runtime.returncode = 0
        return super(ComputeEPIMask, self)._run_interface(runtime)
项目:pestilli-teaching-2017    作者:francopestilli    | 项目源码 | 文件源码
def write_num_peaks(peaks, affine, out_name):
    # also print out a volume for number peaks
    # sum the values greater than 5 in the third dimension
    img = nib.Nifti1Image(np.sum(peaks.peak_values > 0, 3), affine)
    nib.save(img, out_name)
项目:pestilli-teaching-2017    作者:francopestilli    | 项目源码 | 文件源码
def main():

    argParseObj = argparse.ArgumentParser(description="Load stanford hardi dataset")

    # this is the whole dwi with all the volumes yo
    argParseObj.add_argument('-dir', help="the path where you want"
                                          "this stuff to be dumped",
                             type=str, nargs='?', required=True)
    args = argParseObj.parse_args()

    outputDir = args.dir

    from dipy.data import read_stanford_labels
    hardi_img, gtab, label_img = read_stanford_labels()

    hardi_data = hardi_img.get_data()
    hardi_write = nib.Nifti1Image(hardi_data, hardi_img.get_affine())
    outName = ''.join([outputDir, 'stanfordHardi_dwi.nii.gz'])
    nib.save(hardi_write, outName)

    label_data = label_img.get_data()
    label_write = nib.Nifti1Image(label_data, label_img.get_affine())
    outName = ''.join([outputDir, 'stanfordHardi_fsLabels.nii.gz'])
    nib.save(label_write, outName)

    # from dipy.data import read_stanford_pve_maps
    # csf_img , gm_img , wm_img = read_stanford_pve_maps()

    from dipy.external import fsl
    outName = ''.join([outputDir, 'stanfordHardi.'])
    fsl.write_bvals_bvecs(gtab.bvals, gtab.bvecs, prefix=outName)
项目:pyAFQ    作者:yeatmanlab    | 项目源码 | 文件源码
def _brain_mask(row, median_radius=4, numpass=4, autocrop=False,
                vol_idx=None, dilate=None, force_recompute=False):
    brain_mask_file = _get_fname(row, '_brain_mask.nii.gz')
    if not op.exists(brain_mask_file) or force_recompute:
        img = nib.load(row['dwi_file'])
        data = img.get_data()
        gtab = row['gtab']
        mean_b0 = np.mean(data[..., ~gtab.b0s_mask], -1)
        _, brain_mask = median_otsu(mean_b0, median_radius, numpass,
                                    autocrop, dilate=dilate)
        be_img = nib.Nifti1Image(brain_mask.astype(int),
                                 img.affine)
        nib.save(be_img, brain_mask_file)
    return brain_mask_file