示例#1
0
def reorient_img(img, out_dir, overwrite=True):
    """
    A function to reorient any non-dwi image to RAS+.

    Parameters
    ----------
    img : str
        File path to a Nifti1Image.
    out_dir : str
        Path to output directory.

    Returns
    -------
    out_name : str
        File path to reoriented Nifti1Image.

    """
    from pynets.registration.reg_utils import normalize_xform

    # Load image, orient as RAS
    orig_img = nib.load(img)
    normalized = normalize_xform(nib.as_closest_canonical(orig_img))

    # Image may be reoriented
    if normalized is not orig_img:
        print(f"{'Reorienting '}{img}{' to RAS+...'}")
        out_name = (f"{out_dir}/{img.split('/')[-1].split('.nii')[0]}_"
                    f"reor-RAS.nii{img.split('/')[-1].split('.nii')[1]}")
    else:
        out_name = (f"{out_dir}/{img.split('/')[-1].split('.nii')[0]}_"
                    f"noreor-RAS.nii{img.split('/')[-1].split('.nii')[1]}")

    if overwrite is False and os.path.isfile(out_name):
        pass
    else:
        normalized.to_filename(out_name)
        orig_img.uncache()
        normalized.uncache()
        del orig_img

    return out_name
示例#2
0
def reorient_img(img, out_dir):
    """
    A function to reorient any non-dwi image to RAS+.

    Parameters
    ----------
    img : str
        File path to a Nifti1Image.
    out_dir : str
        Path to output directory.

    Returns
    -------
    out_name : str
        File path to reoriented Nifti1Image.
    """
    from pynets.registration.reg_utils import normalize_xform

    # Load image, orient as RAS
    orig_img = nib.load(img)
    normalized = normalize_xform(nib.as_closest_canonical(orig_img))

    # Image may be reoriented
    if normalized is not orig_img:
        print("%s%s%s" % ('Reorienting ', img, ' to RAS+...'))
        out_name = "%s%s%s%s%s" % (out_dir, '/', img.split('/')[-1].split(
            '.nii')[0], '_reor-RAS.nii', img.split('/')[-1].split('.nii')[1])
    else:
        out_name = "%s%s%s%s%s" % (out_dir, '/', img.split('/')[-1].split(
            '.nii')[0], '_noreor-RAS.nii', img.split('/')[-1].split('.nii')[1])

    normalized.to_filename(out_name)
    orig_img.uncache()
    normalized.uncache()
    del orig_img

    return out_name
示例#3
0
def reorient_dwi(dwi_prep, bvecs, out_dir, overwrite=True):
    """
    A function to reorient any dwi image and associated bvecs to RAS+.

    Parameters
    ----------
    dwi_prep : str
        File path to a dwi Nifti1Image.
    bvecs : str
        File path to corresponding bvecs file.
    out_dir : str
        Path to output directory.

    Returns
    -------
    out_fname : str
        File path to the reoriented dwi Nifti1Image.
    out_bvec_fname : str
        File path to corresponding reoriented bvecs file.

    """
    import os
    from pynets.registration.reg_utils import normalize_xform

    fname = dwi_prep
    bvec_fname = bvecs

    out_dir = f"{out_dir}/reg"
    if not os.path.isdir(out_dir):
        os.makedirs(out_dir)

    out_bvec_fname = (
        f"{out_dir}/{dwi_prep.split('/')[-1].split('.nii')[0]}_bvecs_reor.bvec"
    )

    input_img = nib.load(fname)
    input_axcodes = nib.aff2axcodes(input_img.affine)
    reoriented = nib.as_closest_canonical(input_img)
    normalized = normalize_xform(reoriented)
    # Is the input image oriented how we want?
    new_axcodes = ("R", "A", "S")
    if normalized is not input_img:
        out_fname = (f"{out_dir}/{dwi_prep.split('/')[-1].split('.nii')[0]}_"
                     f"reor-RAS.nii{dwi_prep.split('/')[-1].split('.nii')[1]}")
        if (overwrite is False and os.path.isfile(out_fname)
                and os.path.isfile(out_bvec_fname)):
            pass
        else:
            print(f"Reorienting {dwi_prep} to RAS+...")

            # Flip the bvecs
            transform_orientation = nib.orientations.ornt_transform(
                nib.orientations.axcodes2ornt(input_axcodes),
                nib.orientations.axcodes2ornt(new_axcodes),
            )
            bvec_array = np.loadtxt(bvec_fname)
            if bvec_array.shape[0] != 3:
                bvec_array = bvec_array.T
            if not bvec_array.shape[0] == transform_orientation.shape[0]:
                raise ValueError("Unrecognized bvec format")
            output_array = np.zeros_like(bvec_array)
            for this_axnum, (axnum, flip) in enumerate(transform_orientation):
                output_array[this_axnum] = bvec_array[int(axnum)] * float(flip)
            np.savetxt(out_bvec_fname, output_array, fmt="%.8f ")
    else:
        out_fname = (
            f"{out_dir}/{dwi_prep.split('/')[-1].split('.nii')[0]}_"
            f"noreor-RAS.nii{dwi_prep.split('/')[-1].split('.nii')[1]}")
        out_bvec_fname = bvec_fname

    if (overwrite is False and os.path.isfile(out_fname)
            and os.path.isfile(out_bvec_fname)):
        pass
    else:
        normalized.to_filename(out_fname)
        normalized.uncache()
        input_img.uncache()
        del normalized, input_img
    return out_fname, out_bvec_fname
示例#4
0
def reorient_dwi(dwi_prep, bvecs, out_dir):
    """
    A function to reorient any dwi image and associated bvecs to RAS+.

    Parameters
    ----------
    dwi_prep : str
        File path to a dwi Nifti1Image.
    bvecs : str
        File path to corresponding bvecs file.
    out_dir : str
        Path to output directory.

    Returns
    -------
    out_fname : str
        File path to the reoriented dwi Nifti1Image.
    out_bvec_fname : str
        File path to corresponding reoriented bvecs file.
    """
    from pynets.registration.reg_utils import normalize_xform
    fname = dwi_prep
    bvec_fname = bvecs
    out_bvec_fname = "%s%s" % (out_dir, '/bvecs_reor.bvec')

    input_img = nib.load(fname)
    input_axcodes = nib.aff2axcodes(input_img.affine)
    reoriented = nib.as_closest_canonical(input_img)
    normalized = normalize_xform(reoriented)
    # Is the input image oriented how we want?
    new_axcodes = ('R', 'A', 'S')
    if normalized is not input_img:
        out_fname = "%s%s%s%s%s" % (
            out_dir, '/', dwi_prep.split('/')[-1].split('.nii')[0],
            '_reor-RAS.nii', dwi_prep.split('/')[-1].split('.nii')[1])
        print("%s%s%s" % ('Reorienting ', dwi_prep, ' to RAS+...'))

        # Flip the bvecs
        transform_orientation = nib.orientations.ornt_transform(
            nib.orientations.axcodes2ornt(input_axcodes),
            nib.orientations.axcodes2ornt(new_axcodes))
        bvec_array = np.loadtxt(bvec_fname)
        if bvec_array.shape[0] != 3:
            bvec_array = bvec_array.T
        if not bvec_array.shape[0] == transform_orientation.shape[0]:
            raise ValueError("Unrecognized bvec format")
        output_array = np.zeros_like(bvec_array)
        for this_axnum, (axnum, flip) in enumerate(transform_orientation):
            output_array[this_axnum] = bvec_array[int(axnum)] * float(flip)
        np.savetxt(out_bvec_fname, output_array, fmt="%.8f ")
    else:
        out_fname = "%s%s%s%s%s" % (
            out_dir, '/', dwi_prep.split('/')[-1].split('.nii')[0],
            '_noreor-RAS.nii', dwi_prep.split('/')[-1].split('.nii')[1])
        out_bvec_fname = bvec_fname

    normalized.to_filename(out_fname)
    normalized.uncache()
    input_img.uncache()
    del normalized, input_img
    return out_fname, out_bvec_fname