def test_get_target_dtype(): img = Nifti1Image(np.ones((2, 2, 2), dtype=np.float64), affine=np.eye(4)) assert_equal(img.get_data().dtype.kind, 'f') dtype_kind_float = niimg._get_target_dtype(img.get_data().dtype, target_dtype='auto') assert_equal(dtype_kind_float, np.float32) img2 = Nifti1Image(np.ones((2, 2, 2), dtype=np.int64), affine=np.eye(4)) assert_equal(img2.get_data().dtype.kind, 'i') dtype_kind_int = niimg._get_target_dtype(img2.get_data().dtype, target_dtype='auto') assert_equal(dtype_kind_int, np.int32)
def test_get_target_dtype(): img = Nifti1Image(np.ones((2, 2, 2), dtype=np.float64), affine=np.eye(4)) assert get_data(img).dtype.kind == 'f' dtype_kind_float = niimg._get_target_dtype(get_data(img).dtype, target_dtype='auto') assert dtype_kind_float == np.float32 img2 = Nifti1Image(np.ones((2, 2, 2), dtype=np.int64), affine=np.eye(4)) assert get_data(img2).dtype.kind == 'i' dtype_kind_int = niimg._get_target_dtype(get_data(img2).dtype, target_dtype='auto') assert dtype_kind_int == np.int32
def test_get_target_dtype(): img = Nifti1Image(np.ones((2, 2, 2), dtype=np.float64), affine=np.eye(4)) assert_equal(img.get_data().dtype.kind, 'f') dtype_kind_float = niimg._get_target_dtype(img.get_data().dtype, target_dtype='auto') assert_equal(dtype_kind_float, np.float32) img2 = Nifti1Image(np.ones((2, 2, 2), dtype=np.int64), affine=np.eye(4)) assert_equal(img2.get_data().dtype.kind, 'i') dtype_kind_int = niimg._get_target_dtype(img2.get_data().dtype, target_dtype='auto') assert_equal(dtype_kind_int, np.int32)
def our_load_niimg(niimg, dtype=None): """Load a niimg, check if it is a nibabel SpatialImage and cast if needed Parameters: ----------- niimg: Niimg-like object See http://nilearn.github.io/manipulating_images/input_output.html. Image to load. dtype: {dtype, "auto"} Data type toward which the data should be converted. If "auto", the data will be converted to int32 if dtype is discrete and float32 if it is continuous. Returns: -------- img: image A loaded image object. """ from nilearn.image import new_img_like # avoid circular imports if isinstance(niimg, _basestring): # data is a filename, we load it niimg = nibabel.load(niimg) elif not isinstance(niimg, nibabel.spatialimages.SpatialImage): raise TypeError("Data given cannot be loaded because it is" " not compatible with nibabel format:\n" + short_repr(niimg)) try: this_dtype = niimg.get_data_dtype() except AttributeError: # Nibabel bug this_dtype = niimg.get_data().dtype dtype = _get_target_dtype(this_dtype, dtype) if dtype is not None: niimg = new_img_like(niimg, niimg.get_data().astype(dtype), get_affine(niimg)) return niimg