Python nibabel.aff2axcodes() Examples
The following are 12
code examples of nibabel.aff2axcodes().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
nibabel
, or try the search function
.
Example #1
Source File: sanity_checks.py From nnUNet with Apache License 2.0 | 6 votes |
def verify_all_same_orientation(folder): """ This should run after cropping :param folder: :return: """ nii_files = subfiles(folder, suffix=".nii.gz", join=True) orientations = [] for n in nii_files: img = nib.load(n) affine = img.affine orientation = nib.aff2axcodes(affine) orientations.append(orientation) # now we need to check whether they are all the same orientations = np.array(orientations) unique_orientations = np.unique(orientations, axis=0) all_same = len(unique_orientations) == 1 return all_same, unique_orientations
Example #2
Source File: test_orientationd.py From MONAI with Apache License 2.0 | 5 votes |
def test_orntd(self): data = {"seg": np.ones((2, 1, 2, 3)), "seg_meta_dict": {"affine": np.eye(4)}} ornt = Orientationd(keys="seg", axcodes="RAS") res = ornt(data) np.testing.assert_allclose(res["seg"].shape, (2, 1, 2, 3)) code = nib.aff2axcodes(res["seg_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("R", "A", "S"))
Example #3
Source File: test_orientationd.py From MONAI with Apache License 2.0 | 5 votes |
def test_orntd_3d(self): data = { "seg": np.ones((2, 1, 2, 3)), "img": np.ones((2, 1, 2, 3)), "seg_meta_dict": {"affine": np.eye(4)}, "img_meta_dict": {"affine": np.eye(4)}, } ornt = Orientationd(keys=("img", "seg"), axcodes="PLI") res = ornt(data) np.testing.assert_allclose(res["img"].shape, (2, 2, 1, 3)) np.testing.assert_allclose(res["seg"].shape, (2, 2, 1, 3)) code = nib.aff2axcodes(res["seg_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("P", "L", "I")) code = nib.aff2axcodes(res["img_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("P", "L", "I"))
Example #4
Source File: test_orientationd.py From MONAI with Apache License 2.0 | 5 votes |
def test_orntd_2d(self): data = { "seg": np.ones((2, 1, 3)), "img": np.ones((2, 1, 3)), "seg_meta_dict": {"affine": np.eye(4)}, "img_meta_dict": {"affine": np.eye(4)}, } ornt = Orientationd(keys=("img", "seg"), axcodes="PLI") res = ornt(data) np.testing.assert_allclose(res["img"].shape, (2, 3, 1)) code = nib.aff2axcodes(res["seg_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("P", "L", "S")) code = nib.aff2axcodes(res["img_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("P", "L", "S"))
Example #5
Source File: test_orientationd.py From MONAI with Apache License 2.0 | 5 votes |
def test_orntd_1d(self): data = { "seg": np.ones((2, 3)), "img": np.ones((2, 3)), "seg_meta_dict": {"affine": np.eye(4)}, "img_meta_dict": {"affine": np.eye(4)}, } ornt = Orientationd(keys=("img", "seg"), axcodes="L") res = ornt(data) np.testing.assert_allclose(res["img"].shape, (2, 3)) code = nib.aff2axcodes(res["seg_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("L", "A", "S")) code = nib.aff2axcodes(res["img_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("L", "A", "S"))
Example #6
Source File: test_orientationd.py From MONAI with Apache License 2.0 | 5 votes |
def test_orntd_canonical(self): data = { "seg": np.ones((2, 1, 2, 3)), "img": np.ones((2, 1, 2, 3)), "seg_meta_dict": {"affine": np.eye(4)}, "img_meta_dict": {"affine": np.eye(4)}, } ornt = Orientationd(keys=("img", "seg"), as_closest_canonical=True) res = ornt(data) np.testing.assert_allclose(res["img"].shape, (2, 1, 2, 3)) np.testing.assert_allclose(res["seg"].shape, (2, 1, 2, 3)) code = nib.aff2axcodes(res["seg_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("R", "A", "S")) code = nib.aff2axcodes(res["img_meta_dict"]["affine"], ornt.ornt_transform.labels) self.assertEqual(code, ("R", "A", "S"))
Example #7
Source File: to_canonical.py From torchio with MIT License | 5 votes |
def apply_transform(self, sample: Subject) -> dict: for image_dict in sample.get_images(intensity_only=False): affine = image_dict[AFFINE] if nib.aff2axcodes(affine) == tuple('RAS'): continue array = image_dict[DATA][0].numpy() nii = nib.Nifti1Image(array, affine) reoriented = nib.as_closest_canonical(nii) array = reoriented.get_fdata(dtype=np.float32) # https://github.com/facebookresearch/InferSent/issues/99#issuecomment-446175325 array = array.copy()[np.newaxis, ...] image_dict[DATA] = torch.from_numpy(array) image_dict[AFFINE] = reoriented.affine return sample
Example #8
Source File: image.py From torchio with MIT License | 5 votes |
def orientation(self): return nib.aff2axcodes(self.affine)
Example #9
Source File: orientation.py From torchio with MIT License | 5 votes |
def name_dimensions(tensor, affine): axcodes = nib.aff2axcodes(affine) names = [AXCODES_TO_WORDS[axcode] for axcode in axcodes] with warnings.catch_warnings(): warnings.simplefilter('ignore', UserWarning) tensor.rename_(*names)
Example #10
Source File: mgdm_segmentation.py From nighres with Apache License 2.0 | 5 votes |
def _get_mgdm_orientation(affine, mgdm): ''' Transforms nibabel affine information into orientation and slice order that MGDM understands ''' orientation = nb.aff2axcodes(affine) # set mgdm slice order if orientation[-1] == "I" or orientation[-1] == "S": sliceorder = mgdm.AXIAL elif orientation[-1] == "L" or orientation[-1] == "R": sliceorder = mgdm.SAGITTAL else: sliceorder = mgdm.CORONAL # set mgdm orientations if "L" in orientation: LR = mgdm.R2L elif "R" in orientation: LR = mgdm.L2R # flipLR = True if "A" in orientation: AP = mgdm.P2A # flipAP = True elif "P" in orientation: AP = mgdm.A2P if "I" in orientation: IS = mgdm.S2I # flipIS = True elif "S" in orientation: IS = mgdm.I2S return sliceorder, LR, AP, IS
Example #11
Source File: functional.py From mriqc with BSD 3-Clause "New" or "Revised" License | 4 votes |
def spikes_mask(in_file, in_mask=None, out_file=None): """Calculate a mask in which check for :abbr:`EM (electromagnetic)` spikes.""" import os.path as op import nibabel as nb import numpy as np from nilearn.image import mean_img from nilearn.plotting import plot_roi from scipy import ndimage as nd 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('{}_spmask{}'.format(fname, ext)) out_plot = op.abspath('{}_spmask.pdf'.format(fname)) in_4d_nii = nb.load(in_file) orientation = nb.aff2axcodes(in_4d_nii.affine) if in_mask: mask_data = nb.load(in_mask).get_data() a = np.where(mask_data != 0) bbox = np.max(a[0]) - np.min(a[0]), np.max(a[1]) - \ np.min(a[1]), np.max(a[2]) - np.min(a[2]) longest_axis = np.argmax(bbox) # Input here is a binarized and intersected mask data from previous section dil_mask = nd.binary_dilation( mask_data, iterations=int(mask_data.shape[longest_axis] / 9)) rep = list(mask_data.shape) rep[longest_axis] = -1 new_mask_2d = dil_mask.max(axis=longest_axis).reshape(rep) rep = [1, 1, 1] rep[longest_axis] = mask_data.shape[longest_axis] new_mask_3d = np.logical_not(np.tile(new_mask_2d, rep)) else: new_mask_3d = np.zeros(in_4d_nii.shape[:3]) == 1 if orientation[0] in ['L', 'R']: new_mask_3d[0:2, :, :] = True new_mask_3d[-3:-1, :, :] = True else: new_mask_3d[:, 0:2, :] = True new_mask_3d[:, -3:-1, :] = True mask_nii = nb.Nifti1Image(new_mask_3d.astype(np.uint8), in_4d_nii.affine, in_4d_nii.header) mask_nii.to_filename(out_file) plot_roi(mask_nii, mean_img(in_4d_nii), output_file=out_plot) return out_file, out_plot
Example #12
Source File: cifti.py From niworkflows with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _reorient_image(img, *, target_img=None, orientation=None): """ Coerce an image to a target orientation. .. note:: Only RAS -> LAS conversion is currently supported Parameters ---------- img : :obj:`SpatialImage` image to be reoriented target_img : :obj:`SpatialImage`, optional target in desired orientation orientation : :obj:`str` or :obj:`tuple`, optional desired orientation, if no target image is provided .. testsetup:: >>> img = nb.load(Path(test_data) / 'testRobustMNINormalizationRPTMovingWarpedImage.nii.gz') >>> las_img = img.as_reoriented([[0, -1], [1, 1], [2, 1]]) Examples -------- >>> nimg = _reorient_image(img, target_img=img) >>> nb.aff2axcodes(nimg.affine) ('R', 'A', 'S') >>> nimg = _reorient_image(img, target_img=las_img) >>> nb.aff2axcodes(nimg.affine) ('L', 'A', 'S') >>> nimg = _reorient_image(img, orientation='LAS') >>> nb.aff2axcodes(nimg.affine) ('L', 'A', 'S') >>> _reorient_image(img, orientation='LPI') Traceback (most recent call last): ... NotImplementedError: Cannot reorient ... >>> _reorient_image(img) Traceback (most recent call last): ... RuntimeError: No orientation ... """ orient0 = nb.aff2axcodes(img.affine) if target_img is not None: orient1 = nb.aff2axcodes(target_img.affine) elif orientation is not None: orient1 = tuple(orientation) else: raise RuntimeError("No orientation to reorient to!") if orient0 == orient1: # already in desired orientation return img elif orient0 == tuple("RAS") and orient1 == tuple("LAS"): # RAS -> LAS return img.as_reoriented([[0, -1], [1, 1], [2, 1]]) else: raise NotImplementedError( "Cannot reorient {0} to {1}.".format(orient0, orient1) )