def test_get_template(): """Test nimare.utils.get_template.""" # 1mm template img = utils.get_template(space="mni152_1mm", mask=None) assert isinstance(img, nib.Nifti1Image) assert not nib.is_proxy(img.dataobj) img = utils.get_template(space="mni152_1mm", mask="brain") assert isinstance(img, nib.Nifti1Image) # 2mm template (default) img = utils.get_template(space="mni152_2mm", mask=None) assert isinstance(img, nib.Nifti1Image) img = utils.get_template(space="mni152_2mm", mask="brain") assert isinstance(img, nib.Nifti1Image) assert not nib.is_proxy(img.dataobj) # ALE template img = utils.get_template(space="ale_2mm", mask=None) assert isinstance(img, nib.Nifti1Image) img = utils.get_template(space="ale_2mm", mask="brain") assert isinstance(img, nib.Nifti1Image) assert not nib.is_proxy(img.dataobj) # Expect exceptions when incompatible spaces or masks are requested. with pytest.raises(ValueError): utils.get_template(space="something", mask=None) with pytest.raises(ValueError): utils.get_template(space="mni152_1mm", mask="gm") with pytest.raises(ValueError): utils.get_template(space="mni152_2mm", mask="gm") with pytest.raises(ValueError): utils.get_template(space="ale_2mm", mask="gm")
def printInfo(self): print("Printing information for {0}".format(self.filename)) obj = self.img.dataobj isArray = nib.is_proxy(obj) print("Proxy: {0}".format(str(isArray))) data = self.img.get_data() print("Shape:\n{0}".format(str(data.shape))) print("Array:\n{0}".format(data[:, :, 115]))
def img_data_dtype(niimg): """Determine type of data contained in image Based on the information contained in ``niimg.dataobj``, determine the dtype of ``np.array(niimg.dataobj).dtype``. """ dataobj = niimg.dataobj # Neuroimages that scale data should be interpreted as floating point if nibabel.is_proxy(dataobj) and (dataobj.slope, dataobj.inter) != (1.0, 0.0): return np.float_ # ArrayProxy gained the dtype attribute in nibabel 2.2 if hasattr(dataobj, 'dtype'): return dataobj.dtype return niimg.get_data_dtype()
def check_img(img): """ Very basic checker that loads `img`` and ensures it's 3D/int Parameters -------- img : str or niimg-like Filepath to or in-memory loaded image Returns ------- img : niimg-like Loaded 3D/int image """ if isinstance(img, (str, os.PathLike)) and os.path.exists(img): img = nib.load(img) elif not isinstance(img, nib.spatialimages.SpatialImage): raise TypeError('Provided image must be an existing filepath or a ' 'pre-loaded niimg-like object') # ensure 3D or squeezable to 3D img = nib.funcs.squeeze_image(img) if len(img.shape) != 3: raise ValueError('Provided image must be 3D') # check if atlas data is int or castable to int # if image is arrayproxy convert it to an array for speed-up data = np.asarray(img.dataobj) cast = nib.is_proxy(img.dataobj) if img.header.get_data_dtype().kind not in ['i', 'u']: idata = data.astype('int32') cast = np.allclose(idata, data) data = idata if not cast: raise ValueError('Provided image should have integer values or ' 'be safely castable to int without data loss') if cast: img = img.__class__(data, img.affine, header=img.header) img.header.set_data_dtype(np.int32) return img
def test_dataset_smoke(): """Smoke test for nimare.dataset.Dataset initialization and get methods.""" db_file = op.join(get_test_data_path(), "neurosynth_dset.json") dset = dataset.Dataset(db_file) dset.update_path(get_test_data_path()) assert isinstance(dset, nimare.dataset.Dataset) # Test that Dataset.masker is portable assert not nib.is_proxy(dset.masker.mask_img_.dataobj) methods = [ dset.get_images, dset.get_labels, dset.get_metadata, dset.get_texts ] for method in methods: assert isinstance(method(), list) assert isinstance(method(ids=dset.ids[:5]), list) assert isinstance(method(ids=dset.ids[0]), list) assert isinstance(dset.get_images(imtype="beta"), list) assert isinstance(dset.get_metadata(field="sample_sizes"), list) assert isinstance(dset.get_studies_by_label("cogat_cognitive_control"), list) assert isinstance(dset.get_studies_by_coordinate(np.array([[20, 20, 20]])), list) # If label is not available, raise ValueError with pytest.raises(ValueError): dset.get_studies_by_label("dog") mask_data = np.zeros(dset.masker.mask_img.shape, int) mask_data[40, 40, 40] = 1 mask_img = nib.Nifti1Image(mask_data, dset.masker.mask_img.affine) assert isinstance(dset.get_studies_by_mask(mask_img), list) dset1 = dset.slice(dset.ids[:5]) dset2 = dset.slice(dset.ids[5:]) assert isinstance(dset1, dataset.Dataset) dset_merged = dset1.merge(dset2) assert isinstance(dset_merged, dataset.Dataset)
img.affine img.header header = img.header print(header) print(header.get_data_shape()) # Use: get_data_dtype() to get the numpy data type in which the image data is stored (or will be stored if you save the image): print(header.get_data_dtype()) #Use: get_zooms() to get the voxel sizes in millimeters: print(header.get_zooms()) img.dataobj nib.is_proxy(img.dataobj) array_data = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) affine = np.diag([1, 2, 3, 1]) array_img = nib.Nifti1Image(array_data, affine) array_img.dataobj array_img.dataobj is array_data nib.is_proxy(array_img.dataobj) image_data = array_img.get_data() image_data.shape image_data is array_data image_data = img.get_data() image_data.shape img.dataobj data_again = img.get_data()
cosa = np.cos(alpha) sina = np.sin(alpha) Trotate = np.array([[1, 0, 0, 0], [0, cosa, -sina, 0], [0, sina, cosa, 0], [0, 0, 0, 1]]) Tsclrot = Tscale.dot(Trotate) Ttranslate = np.array([[1, 0, 0, -78], [0, 1, 0, -76], [0, 0, 1, -64], [0, 0, 0, 1]]) Twhole = Ttranslate.dot(Tsclrot) # epi image proxy (i.e. points to epi image without loading it from disk yet): nib.is_proxy(epi.dataobj) # Creating a nifti image from an array using nibable: mat = np.arange(24, dtype=np.int16).reshape((2, 3, 4)) affine = np.diag([1, 2, 3, 1]) newnifti = nib.Nifti1Image(mat, affine) ''' Here the newnifti data is already a numpy array, and there is no version of the array on disk. The dataobj property of newnifti is the array itself rather than a proxy for the array: ''' print(newnifti.dataobj) print(newnifti.dataobj is mat) print(nib.is_proxy(newnifti.dataobj))