python类save()的实例源码

labels_manipulator.py 文件源码 项目:LabelsManager 作者: SebastianoF 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def assign_all_other_labels_the_same_value(self, pfi_input, pfi_output=None,
        labels_to_keep=(), same_value_label=255):

        pfi_in, pfi_out = get_pfi_in_pfi_out(pfi_input, pfi_output, self.pfo_in, self.pfo_out)

        im_labels = nib.load(pfi_in)
        data_labels = im_labels.get_data()
        data_reassigned = assign_all_other_labels_the_same_value(data_labels,
                                labels_to_keep=labels_to_keep, same_value_label=same_value_label)

        im_reassigned = set_new_data(im_labels, data_reassigned)
        nib.save(im_reassigned, pfi_out)
        print('Reassigned labels from image {0} saved in {1}.'.format(pfi_in, pfi_out))
        return pfi_out
labels_manipulator.py 文件源码 项目:LabelsManager 作者: SebastianoF 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def keep_one_label(self, pfi_input, pfi_output=None, label_to_keep=1):

        pfi_in, pfi_out = get_pfi_in_pfi_out(pfi_input, pfi_output, self.pfo_in, self.pfo_out)

        im_labels = nib.load(pfi_in)
        data_labels = im_labels.get_data()
        data_one_label = keep_only_one_label(data_labels, label_to_keep)

        im_one_label = set_new_data(im_labels, data_one_label)
        nib.save(im_one_label, pfi_out)
        print('Label {0} kept from image {1} and saved in {2}.'.format(label_to_keep, pfi_in, pfi_out))
        return pfi_out
cutter.py 文件源码 项目:LabelsManager 作者: SebastianoF 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def apply_a_mask_path(pfi_input, pfi_mask, pfi_output):
    # TODO expose in facade
    """
    Adaptative - if the mask is 3D and the image is 4D, will create a temporary mask,
    generate the stack of masks, and apply the stacks to the image.
    :param pfi_input: path to file 3d x T image
    :param pfi_mask: 3d mask same dimension as the 3d of the pfi_input
    :param pfi_output: apply the mask to each time point T in the fourth dimension if any.
    :return: None, save the output in pfi_output.
    """
    im_input = nib.load(pfi_input)
    im_mask = nib.load(pfi_mask)

    assert len(im_mask.shape) == 3

    if not im_mask.shape == im_input.shape[:3]:
        msg = 'Mask {0} and image {1} does not have compatible dimension: {2} and {3}'.format(
            pfi_input, pfi_mask, im_input, im_mask.shape)
        raise IOError(msg)

    if len(im_input.shape) == 3:
        new_data = im_input.get_data() * im_mask.get_data().astype(np.bool)
    else:
        new_data = np.zeros_like(im_input.get_data())
        for t in range(im_input.shape[3]):
            new_data[..., t] = im_input.get_data()[..., t] * im_mask.get_data().astype(np.bool)

    new_im = set_new_data(image=im_input, new_data=new_data)

    nib.save(new_im, filename=pfi_output)
submit.py 文件源码 项目:segmentation 作者: zengyu714 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def save_as_nii(y, savename):
    y_nii = nib.Nifti1Image(y.astype(np.uint8), np.eye(4))
    nib.save(y_nii, savename + '.nii')
binarize_spark.py 文件源码 项目:sim 作者: big-data-lab-team 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
binarize_fsl.py 文件源码 项目:sim 作者: big-data-lab-team 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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
utils.py 文件源码 项目:ndmg 作者: neurodata 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
source_space.py 文件源码 项目:decoding_challenge_cortana_2016_3rd 作者: kingjr 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def save(self, fname):
        """Save the source spaces to a fif file

        Parameters
        ----------
        fname : str
            File to write.
        """
        write_source_spaces(fname, self)
source_space.py 文件源码 项目:decoding_challenge_cortana_2016_3rd 作者: kingjr 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _do_src_distances(con, vertno, run_inds, limit):
    """Helper to compute source space distances in chunks"""
    if limit < np.inf:
        func = partial(sparse.csgraph.dijkstra, limit=limit)
    else:
        func = sparse.csgraph.dijkstra
    chunk_size = 20  # save memory by chunking (only a little slower)
    lims = np.r_[np.arange(0, len(run_inds), chunk_size), len(run_inds)]
    n_chunks = len(lims) - 1
    # eventually we want this in float32, so save memory by only storing 32-bit
    d = np.empty((len(run_inds), len(vertno)), np.float32)
    min_dist = np.empty((n_chunks, con.shape[0]))
    min_idx = np.empty((n_chunks, con.shape[0]), np.int32)
    range_idx = np.arange(con.shape[0])
    for li, (l1, l2) in enumerate(zip(lims[:-1], lims[1:])):
        idx = vertno[run_inds[l1:l2]]
        out = func(con, indices=idx)
        midx = np.argmin(out, axis=0)
        min_idx[li] = idx[midx]
        min_dist[li] = out[midx, range_idx]
        d[l1:l2] = out[:, vertno]
    midx = np.argmin(min_dist, axis=0)
    min_dist = min_dist[midx, range_idx]
    min_idx = min_idx[midx, range_idx]
    d[d == np.inf] = 0  # scipy will give us np.inf for uncalc. distances
    return d, min_idx, min_dist
microstruct_mapsNmetrics_ver1.py 文件源码 项目:pestilli-teaching-2017 作者: francopestilli 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
load_stanford_hardi.py 文件源码 项目:pestilli-teaching-2017 作者: francopestilli 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
test_api.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def create_dummy_preproc_path(n_subjects, n_sessions):
    preproc_dir = tempfile.mkdtemp()
    subjects = ['sub-%s' % (d + 1) for d in range(n_subjects)]
    sessions = ['sess-%s' % (d + 1) for d in range(n_sessions)]
    for subject in subjects:
        for session in sessions:
            for modality in ['anat', 'dwi']:
                os.makedirs(op.join(preproc_dir, subject, session, modality))
            # Make some dummy data:
            aff = np.eye(4)
            data = np.ones((10, 10, 10, 6))
            bvecs = np.vstack([np.eye(3), np.eye(3)])
            bvecs[0] = 0
            bvals = np.ones(6) * 1000.
            bvals[0] = 0
            np.savetxt(op.join(preproc_dir, subject, session, 'dwi',
                               'dwi.bvals'),
                       bvals)
            np.savetxt(op.join(preproc_dir, subject, session, 'dwi',
                               'dwi.bvecs'),
                       bvecs)
            nib.save(nib.Nifti1Image(data, aff),
                     op.join(preproc_dir, subject, session, 'dwi',
                             'dwi.nii.gz'))
            nib.save(nib.Nifti1Image(data, aff),
                     op.join(preproc_dir, subject, session, 'anat',
                             'T1w.nii.gz'))
            nib.save(nib.Nifti1Image(data, aff),
                     op.join(preproc_dir, subject, session, 'anat',
                             'aparc+aseg.nii.gz'))

    return preproc_dir
testing.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def make_dki_data(out_fbval, out_fbvec, out_fdata, out_shape=(5, 6, 7)):
    """
    Create a synthetic data-set with a 2-shell acquisition

    out_fbval, out_fbvec, out_fdata : str
        Full paths to generated data and bval/bvec files

    out_shape : tuple
        The 3D shape of the output volum

    """
    # This is one-shell (b=1000) data:
    fimg, fbvals, fbvecs = dpd.get_data('small_64D')
    img = nib.load(fimg)
    bvals, bvecs = dio.read_bvals_bvecs(fbvals, fbvecs)
    # So  we create two shells out of it
    bvals_2s = np.concatenate((bvals, bvals * 2), axis=0)
    bvecs_2s = np.concatenate((bvecs, bvecs), axis=0)
    gtab_2s = dpg.gradient_table(bvals_2s, bvecs_2s)

    # Simulate a signal based on the DKI model:
    mevals_cross = np.array([[0.00099, 0, 0], [0.00226, 0.00087, 0.00087],
                             [0.00099, 0, 0], [0.00226, 0.00087, 0.00087]])
    angles_cross = [(80, 10), (80, 10), (20, 30), (20, 30)]
    fie = 0.49
    frac_cross = [fie * 50, (1 - fie) * 50, fie * 50, (1 - fie) * 50]
    # Noise free simulates
    signal_cross, dt_cross, kt_cross = multi_tensor_dki(gtab_2s, mevals_cross,
                                                        S0=100,
                                                        angles=angles_cross,
                                                        fractions=frac_cross,
                                                        snr=None)
    DWI = np.zeros(out_shape + (len(gtab_2s.bvals), ))
    DWI[:] = signal_cross
    nib.save(nib.Nifti1Image(DWI, img.affine), out_fdata)
    np.savetxt(out_fbval, bvals_2s)
    np.savetxt(out_fbvec, bvecs_2s)
dti.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def predict(params_file, gtab, S0_file=None, out_dir=None):
    """
    Create a signal prediction from DTI params

    params_file : str
        Full path to a file with parameters saved from a DKI fit

    gtab : GradientTable object
        The gradient table to predict for

    S0_file : str
        Full path to a nifti file that contains S0 measurements to incorporate
        into the prediction. If the file contains 4D data, the volumes that
        contain the S0 data must be the same as the gtab.b0s_mask.
    """
    if out_dir is None:
        out_dir = op.join(op.split(params_file)[0])

    if S0_file is None:
        S0 = 100
    else:
        S0 = nib.load(S0_file).get_data()
        # If the S0 data is 4D, we assume it comes from an acquisition that had
        # B0 measurements in the same volumes described in the gtab:
        if len(S0.shape) == 4:
            S0 = np.mean(S0[..., gtab.b0s_mask], -1)
        # Otherwise, we assume that it's already a 3D volume, and do nothing

    img = nib.load(params_file)
    params = img.get_data()
    pred = dti.tensor_prediction(params, gtab, S0=S0)
    fname = op.join(out_dir, 'dti_prediction.nii.gz')
    nib.save(nib.Nifti1Image(pred, img.affine), fname)

    return fname
api.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
api.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _dti(row, force_recompute=False):
    dti_params_file = _get_fname(row, '_dti_params.nii.gz')
    if not op.exists(dti_params_file) or force_recompute:
        img = nib.load(row['dwi_file'])
        data = img.get_data()
        gtab = row['gtab']
        brain_mask_file = _brain_mask(row)
        mask = nib.load(brain_mask_file).get_data()
        dtf = dti_fit(gtab, data, mask=mask)
        nib.save(nib.Nifti1Image(dtf.model_params, row['dwi_affine']),
                 dti_params_file)
    return dti_params_file
api.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _dti_fa(row, force_recompute=False):
    dti_fa_file = _get_fname(row, '_dti_fa.nii.gz')
    if not op.exists(dti_fa_file) or force_recompute:
        tf = _dti_fit(row)
        fa = tf.fa
        nib.save(nib.Nifti1Image(fa, row['dwi_affine']),
                 dti_fa_file)
    return dti_fa_file
api.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def _bundles(row, wm_labels, odf_model="DTI", directions="det",
             force_recompute=False):
    bundles_file = _get_fname(row,
                              '%s_%s_bundles.trk' % (odf_model,
                                                     directions))
    if not op.exists(bundles_file) or force_recompute:
        streamlines_file = _streamlines(row, wm_labels,
                                        odf_model=odf_model,
                                        directions=directions,
                                        force_recompute=force_recompute)
        tg = nib.streamlines.load(streamlines_file).tractogram
        sl = tg.apply_affine(np.linalg.inv(row['dwi_affine'])).streamlines
        bundle_dict = make_bundle_dict()
        reg_template = dpd.read_mni_template()
        mapping = reg.read_mapping(_mapping(row), row['dwi_file'],
                                   reg_template)
        bundles = seg.segment(row['dwi_file'],
                              row['bval_file'],
                              row['bvec_file'],
                              sl,
                              bundle_dict,
                              reg_template=reg_template,
                              mapping=mapping)
        tgram = _tgramer(bundles, bundle_dict, row['dwi_affine'])
        nib.streamlines.save(tgram, bundles_file)
    return bundles_file
dki.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def predict(params_file, gtab, S0_file=None, out_dir=None):
    """
    Create a signal prediction from DKI params

    params_file : str
        Full path to a file with parameters saved from a DKI fit

    gtab : GradientTable object
        The gradient table to predict for

    S0_file : str
        Full path to a nifti file that contains S0 measurements to incorporate
        into the prediction. If the file contains 4D data, the volumes that
        contain the S0 data must be the same as the gtab.b0s_mask.


    """
    if out_dir is None:
        out_dir = op.join(op.split(params_file)[0])

    if S0_file is None:
        S0 = 100
    else:
        S0 = nib.load(S0_file).get_data()
        # If the S0 data is 4D, we assume it comes from an acquisition that had
        # B0 measurements in the same volumes described in the gtab:
        if len(S0.shape) == 4:
            S0 = np.mean(S0[..., gtab.b0s_mask], -1)
        # Otherwise, we assume that it's already a 3D volume, and do nothing

    img = nib.load(params_file)
    params = img.get_data()
    pred = dki.dki_prediction(params, gtab, S0=S0)
    fname = op.join(out_dir, 'dki_prediction.nii.gz')
    nib.save(nib.Nifti1Image(pred, img.affine), fname)

    return fname
data.py 文件源码 项目:pyAFQ 作者: yeatmanlab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def organize_stanford_data(path=None):
    """
    Create the expected file-system structure for the Stanford HARDI data-set
    """
    dpd.fetch_stanford_hardi()

    if path is None:
        if not op.exists(afq_home):
            os.mkdir(afq_home)
        base_folder = op.join(afq_home, 'stanford_hardi')
    else:
        base_folder = op.join(path, 'stanford_hardi')

    if not op.exists(base_folder):
        os.mkdir(base_folder)
        os.mkdir(op.join(base_folder, 'sub-01'))
        os.mkdir(op.join(base_folder, 'sub-01', 'sess-01'))
        anat_folder = op.join(base_folder, 'sub-01', 'sess-01', 'anat')
        os.mkdir(anat_folder)
        dwi_folder = op.join(base_folder, 'sub-01', 'sess-01', 'dwi')
        os.mkdir(dwi_folder)
        t1_img = dpd.read_stanford_t1()
        nib.save(t1_img, op.join(anat_folder, 'sub-01_sess-01_T1w.nii.gz'))
        seg_img = dpd.read_stanford_labels()[-1]
        nib.save(seg_img, op.join(anat_folder,
                                  'sub-01_sess-01_aparc+aseg.nii.gz'))
        dwi_img, gtab = dpd.read_stanford_hardi()
        nib.save(dwi_img, op.join(dwi_folder, 'sub-01_sess-01_dwi.nii.gz'))
        np.savetxt(op.join(dwi_folder, 'sub-01_sess-01_dwi.bvecs'), gtab.bvecs)
        np.savetxt(op.join(dwi_folder, 'sub-01_sess-01_dwi.bvals'), gtab.bvals)


问题


面经


文章

微信
公众号

扫码关注公众号