def image(data): """ Creates a NiBabel image for the supplied data. The image object will be of a generic type and only made concrete during the saving process (nibabel.loadsave.save() takes care of this). No special meta-data can be associated with the image. @param data: a numpy array of arbitrary type @return: a NiBabel image for data of generic type SpatialImage """ image = SpatialImage(data, None) image.update_header() return image
def mask_image(image: SpatialImage, mask: np.ndarray, data_type: type = None ) -> np.ndarray: """Mask image after optionally casting its type. Parameters ---------- image Image to mask. Can include time as the last dimension. mask Mask to apply. Must have the same shape as the image data. data_type Type to cast image to. Returns ------- np.ndarray Masked image. Raises ------ ValueError Image data and masks have different shapes. """ image_data = image.get_data() if image_data.shape[:3] != mask.shape: raise ValueError("Image data and mask have different shapes.") if data_type is not None: cast_data = image_data.astype(data_type) else: cast_data = image_data return cast_data[mask]
def image_new(data, filename): """ Creates a NiBabel image for the supplied data. The function intends to directly create the appropriate image type, depending on the image header. @param data: a numpy array of arbitrary type @param filename the intended filename with the file ending telling the image type @return: a NiBabel image for data of any nibabel image type """ # extract suffix and return apropriate image suffix = filename.split('.')[-1].lower() if not suffix in __suffix_to_type: suffix = '.'.join(map(lambda x: x.lower(), filename.split('.')[-2:])) if not suffix in __suffix_to_type: image = SpatialImage(data, None) image.update_header() return image image = __suffix_to_type[suffix](data, None) image.update_header() return image
def images(spatial_image: SpatialImage) -> Iterable[SpatialImage]: images = [spatial_image] image_data = spatial_image.get_data().copy() image_data[1, 1, 1, 0] = 2 images.append(Nifti1Pair(image_data, np.eye(4))) return images
def test_resample_equiv(from_shape, from_affine, to_shape, to_affine, order, seed): """Test resampling equivalences.""" rng = np.random.RandomState(seed) from_data = rng.randn(*from_shape) is_rand = False if isinstance(to_affine, str): assert to_affine == 'rand' to_affine = _rand_affine(rng) is_rand = True if isinstance(from_affine, str): assert from_affine == 'rand' from_affine = _rand_affine(rng) is_rand = True to_affine = np.array(to_affine, float) assert to_affine.shape == (4, 4) from_affine = np.array(from_affine, float) assert from_affine.shape == (4, 4) # # 1. nibabel.processing.resample_from_to # # for a 1mm iso / 256 -> 5mm / 51 one sample takes ~486 ms from nibabel.processing import resample_from_to from nibabel.spatialimages import SpatialImage start = np.linalg.norm(from_data) got_nibabel = resample_from_to(SpatialImage(from_data, from_affine), (to_shape, to_affine), order=order).get_fdata() end = np.linalg.norm(got_nibabel) assert end > 0.05 * start # not too much power lost # # 2. dipy.align.imaffine # # ~366 ms import dipy.align.imaffine interp = 'linear' if order == 1 else 'nearest' got_dipy = dipy.align.imaffine.AffineMap( None, to_shape, to_affine, from_shape, from_affine).transform(from_data, interpolation=interp, resample_only=True) # XXX possibly some error in dipy or nibabel (/SciPy), or some boundary # condition? nib_different = ((is_rand and order == 1) or (from_affine[0, 0] == 2. and not np.allclose(from_affine, to_affine))) nib_different = nib_different and not (is_rand and from_affine[0, 0] == 2 and order == 0) if nib_different: assert not np.allclose(got_dipy, got_nibabel), 'nibabel fixed' else: assert_allclose(got_dipy, got_nibabel, err_msg='dipy<->nibabel') # # 3. mne.source_space._grid_interp # # ~339 ms trans = np.linalg.inv(from_affine) @ to_affine # to -> from interp = _grid_interp(from_shape, to_shape, trans, order=order) got_mne = np.asarray(interp @ from_data.ravel(order='F')).reshape( to_shape, order='F') if order == 1: assert_allclose(got_mne, got_dipy, err_msg='MNE<->dipy') else: perc = 100 * np.isclose(got_mne, got_dipy).mean() assert 83 < perc <= 100
def tract_generate_mask(optional_flags, tractography, image, file_output): image = nibabel.load(image) mask = tract_operations.tract_mask(image, tractography) return SpatialImage(mask, image.get_affine())
def images(spatial_image: SpatialImage) -> Iterable[SpatialImage]: images = [spatial_image] image_data = spatial_image.get_data().copy() image_data[1, 1, 1] = 2 images.append(Nifti1Pair(image_data, np.eye(4))) return images