def test_tolerance_of_affine_mismatch_check(): """Verify that affine mismatch error is thrown only for mismatches above a certain tolerance.""" # ERROR NOT EXPECTED (Affine matrices have slight differences, but are close enough to be equivalent) # NB: Specific values taken from anonymized data from https://github.com/neuropoly/spinalcordtoolbox/issues/3251 qform_affine = np.array([[-0.0000000613307, -0.0032542832702, -0.8999945527288, 36.8009071350098], [-0.9322916865349, -0.0000000613307, 0.0000000594134, 214.2190246582031], [0.0000000615451, -0.9322860067718, 0.0031415651366, 122.8873901367188], [0.0000000000000, 0.0000000000000, 0.0000000000000, 1.0000000000000]]) sform_affine = np.array([[-0.0000000000007, -0.0032542543486, -0.8999945521355, 36.8009071350098], [-0.9322916865349, 0.0000000001912, -0.0000000000000, 214.2190246582031], [-0.0000000001912, -0.9322860240936, 0.0031415862031, 122.8873901367188], [0.0000000000000, 0.0000000000000, 0.0000000000000, 1.0000000000000]]) header_e7 = nibabel.Nifti1Header() header_e7.set_sform(affine=sform_affine) header_e7.set_qform(affine=qform_affine) msct_image.Image(param=[1, 1, 1], hdr=header_e7, check_sform=True) # ERROR NOT EXPECTED (A bigger discrepancy is introduced, but it doesn't exceed the tolerance of the check) qform_affine_e3 = qform_affine.copy() qform_affine_e3[0, 0] += 1e-3 header_e3 = nibabel.Nifti1Header() header_e3.set_sform(affine=sform_affine) header_e3.set_qform(affine=qform_affine_e3) msct_image.Image(param=[1, 1, 1], hdr=header_e3, check_sform=True) # ERROR EXPECTED (A bigger discrepancy is introduced, and it does exceed the tolerance of the check) qform_affine_e2 = qform_affine.copy() qform_affine_e2[0, 0] += 1e-2 header_e2 = nibabel.Nifti1Header() header_e2.set_sform(affine=sform_affine) header_e2.set_qform(affine=qform_affine_e2) with pytest.raises(ValueError) as e: msct_image.Image(param=[1, 1, 1], hdr=header_e2, check_sform=True) assert "Image sform does not match qform" in str(e.value)
def test_header(): # Property header interface deprecated arr = np.arange(24).reshape((2, 3, 4)) coordmap = AffineTransform.from_params('xyz', 'ijk', np.eye(4)) header = nib.Nifti1Header() img = Image(arr, coordmap, metadata={'header': header}) assert_equal(img.metadata['header'], header) # This interface deprecated assert_equal(img.header, header) hdr2 = nib.Nifti1Header() hdr2['descrip'] = 'from fullness of heart' assert_not_equal(img.header, hdr2) img.header = hdr2 assert_equal(img.header, hdr2)
def nsd_write_vol(data, res, outputfile, origin=None): """nsd_write_vol writes volumes to disk Args: data (nd-array): volumetric data to write res (float): data acquisition resolution (in mm) outputfile (filename/path): where to save origin (1d-array, optional): the origin point of the volume. Defaults to None. Raises: ValueError: [description] """ data_class = data.dtype # create a default header header = nib.Nifti1Header() header.set_data_dtype(data_class) # affine affine = np.diag([res] * 3 + [1]) if origin is None: origin = (([1, 1, 1] + np.asarray(data.shape)) / 2) - 1 affine[0, -1] = -origin[0] * res affine[1, -1] = -origin[1] * res affine[2, -1] = -origin[2] * res # write the nifti volume img = nib.Nifti1Image(data, affine, header) img.to_filename(outputfile)
def backtoitensity(path): #get the header correspondingimg = nib.load( '/homes/tzheng/CTdata/CTMicroNUrespsurg/converted/DICOM_nulung026_cb_003_zf_ringRem.nii.gz' ) correspondingheader = correspondingimg.header empty_header = nib.Nifti1Header() empty_header = correspondingheader #print(empty_header) #print(correspondingimg.affine) #正规化导致neuves不能正常渲染 thisimg = correspondingimg.get_fdata() valid_hr_slices = thisimg.shape[2] dpath = path img = nib.load(dpath) data = img.get_fdata() data = data * 12000. thisimg[160:810, 160:810, int(valid_hr_slices * 0.1 / 8) * 8 + 10:int(valid_hr_slices * 0.1 / 8) * 8 + 410] = data[10:660, 10:660, 10:410] #saveimg = nib.Nifti1Image(data, correspondingimg.affine, empty_header) saveimg = nib.Nifti1Image(thisimg, correspondingimg.affine, empty_header) nib.save( saveimg, '/homes/tzheng/Mypythonfiles/densunetdiscirminator/samples/medicaltest3D/SRbacktoitensity.nii.gz' )
def create_nii(dcm, creation): data = tp.Tensor(dcm) if not isinstance(dcm, DCM) and hasattr(dcm, 'bundle'): bundle = dcm.bundle else: header = nib.Nifti1Header() header['regular'] = b'r' header['dim'] = [data.ndim, *data.shape] + [1] * (7 - data.ndim) bits = len(data.flatten()[0].tobytes()) * 8 header['bitpix'] = bits header.set_data_dtype(data.numpy().dtype) if isinstance(dcm, DCM): meta = dcm.bundle else: meta = None if meta and 'PixelSpacing' in meta: spacing = [float(x) for x in meta.PixelSpacing] else: spacing = [1.0, 1.0] if meta and 'SliceThickness' in meta: dz = [float(meta.SliceThickness)] else: dz = [1.0] header['pixdim'] = [1.0] + spacing + dz + [1.0] * (7 - data.ndim) header['qform_code'] = 1 header['xyzt_units'] = 2 if meta: header['qoffset_x'] = -float(meta.ImagePositionPatient[0]) header['qoffset_y'] = -float(meta.ImagePositionPatient[1]) header['qoffset_z'] = float(meta.ImagePositionPatient[2]) qa, qb, qc, qd = orn2quatern( *[float(x) for x in meta.ImageOrientationPatient]) header['quatern_b'] = qb header['quatern_c'] = qc header['quatern_d'] = qd bundle = nib.Nifti1Image(data, None, header=header) instance = creation(data) instance.bundle = bundle instance.path = getattr(dcm, 'path', 'Unknown') return instance
def load_volume(path_volume, im_only=True, squeeze=True, dtype=None): """ Load volume file. :param path_volume: path of the volume to load. Can either be a nii, nii.gz, mgz, or npz format. If npz format, 1) the variable name is assumed to be 'vol_data', 2) the volume is associated with a identity affine matrix and blank header. :param im_only: if False, the function also returns the affine matrix and header of the volume. :param squeeze: whether to squeeze the volume when loading. :param dtype: if not None, convert the loaded volume to this numpy dtype. :return: the volume, with corresponding affine matrix and header if im_only is False. """ assert path_volume.endswith(('.nii', '.nii.gz', '.mgz', '.npz')), 'Unknown data file: %s' % path_volume if path_volume.endswith(('.nii', '.nii.gz', '.mgz')): x = nib.load(path_volume) if squeeze: volume = np.squeeze(x.get_data()) else: volume = x.get_data() aff = x.affine header = x.header else: # npz volume = np.load(path_volume)['vol_data'] if squeeze: volume = np.squeeze(volume) aff = np.eye(4) header = nib.Nifti1Header() if dtype is not None: volume = volume.astype(dtype=dtype) if im_only: return volume else: return volume, aff, header
def genNiftiVol(data, dtype=np.uint8): shape = np.array(np.shape(data), dtype=np.float32) if np.ndim(data) > 3: shape = shape[1:] affine = np.identity(4) affine[0:3, 3] = -0.5 * shape[:3] hdr = nb.Nifti1Header() hdr.set_data_dtype(np.uint8) hdr.set_xyzt_units('mm') hdr.set_data_dtype(dtype) hdr['data_type'] = 2 hdr['qform_code'] = 2 # aligned hdr['sform_code'] = 1 # scanner hdr['scl_slope'] = 1.0 hdr['regular'] = np.array('r', dtype='|S1') pixdim = np.ones(shape=(8,)) pixdim[4:] = 0 hdr['pixdim'] = pixdim if np.ndim(data) > 3: hdr.set_xyzt_units('mm', 'sec') # hdr['xyzt_units'] = 2 + 8 # mm + sec pixdim[4] = 1 hdr['pixdim'] = pixdim nii_array = [] for im in data: nii_array.append(nb.Nifti1Image(im.astype(dtype), affine, hdr)) nii = nb.concat_images(nii_array) else: nii = nb.Nifti1Image(data.astype(dtype), affine, hdr) return nii
def test_save_dtype(): # Test we can specify the dtype on conversion data = np.random.normal(size=(2, 3, 4)) cmap = vox2mni(np.diag([2., 3, 4, 1])) for dt_code in ('i1', 'u1', 'i2', 'u2', 'i4', 'u4', 'i8', 'u8', 'f4', 'f8', 'c8', 'c16'): dt = np.dtype(dt_code) img = Image(data.astype(dt_code), cmap) ni_img = nipy2nifti(img, data_dtype=dt_code) assert_equal(get_header(ni_img).get_data_dtype(), dt) ni_img = nipy2nifti(img, data_dtype=dt) assert_equal(get_header(ni_img).get_data_dtype(), dt) # None results in trying to get the code from the input header, then from the # data. # From data, when there's nothing in the header img = Image(data.astype(np.int16), cmap) ni_img = nipy2nifti(img, data_dtype=None) assert_equal(get_header(ni_img).get_data_dtype(), np.dtype(np.int16)) # From the header hdr = nib.Nifti1Header() hdr.set_data_dtype(np.int32) img = Image(data.astype(np.int16), cmap, metadata={'header': hdr}) ni_img = nipy2nifti(img, data_dtype=None) assert_equal(get_header(ni_img).get_data_dtype(), np.dtype(np.int32)) # Bad dtype assert_raises(TypeError, nipy2nifti, img, data_dtype='foo') # Fancy dtype data = np.zeros((2, 3, 4), dtype=[('f0', 'i2'), ('f1', 'f4')]) img = Image(data, cmap) assert_raises(HeaderDataError, nipy2nifti, img, data_dtype=None)
def create_files_in_directory(request): func_prev_type = set_output_type(request.param) testdir = os.path.realpath(mkdtemp()) origdir = os.getcwd() os.chdir(testdir) filelist = ['a.nii', 'b.nii'] for f in filelist: hdr = nb.Nifti1Header() shape = (3, 3, 3, 4) hdr.set_data_shape(shape) img = np.random.random(shape) nb.save(nb.Nifti1Image(img, np.eye(4), hdr), os.path.join(testdir, f)) out_ext = Info.output_type_to_ext(Info.output_type()) def fin(): if os.path.exists(testdir): rmtree(testdir) set_output_type(func_prev_type) os.chdir(origdir) request.addfinalizer(fin) return (filelist, testdir, out_ext)
def analyze_pair_image_files(outdir, filelist, shape): for f in filename_to_list(filelist): hdr = nb.Nifti1Header() hdr.set_data_shape(shape) img = np.random.random(shape) analyze = nb.AnalyzeImage(img, np.eye(4), hdr) analyze.to_filename(os.path.join(outdir, f))
def save_volume(volume, aff, header, path, res=None, dtype=None, n_dims=3): """ Save a volume. :param volume: volume to save :param aff: affine matrix of the volume to save. If aff is None, the volume is saved with an identity affine matrix. aff can also be set to 'FS', in which case the volume is saved with the affine matrix of FreeSurfer outputs. :param header: header of the volume to save. If None, the volume is saved with a blank header. :param path: path where to save the volume. :param res: (optional) update the resolution in the header before saving the volume. :param dtype: (optional) numpy dtype for the saved volume. :param n_dims: (optional) number of dimensions, to avoid confusion in multi-channel case. Default is None, where n_dims is automatically inferred. """ if dtype is not None: volume = volume.astype(dtype=dtype) if '.npz' in path: np.savez_compressed(path, vol_data=volume) else: if header is None: header = nib.Nifti1Header() if isinstance(aff, str): if aff == 'FS': aff = np.array([[-1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]]) elif aff is None: aff = np.eye(4) nifty = nib.Nifti1Image(volume, aff, header) if res is not None: if n_dims is None: n_dims, _ = get_dims(volume.shape) res = reformat_to_list(res, length=n_dims, dtype=None) nifty.header.set_zooms(res) nib.save(nifty, path)
def test_DerivativesDataSink_bold(tmp_path, space, size, units, xcodes, zipped, fixed): fname = str(tmp_path / 'source.nii') + ('.gz' if zipped else '') hdr = nb.Nifti1Header() hdr.set_qform(np.eye(4), code=xcodes[0]) hdr.set_sform(np.eye(4), code=xcodes[1]) hdr.set_xyzt_units(*units) nb.Nifti1Image(np.zeros(size), np.eye(4), hdr).to_filename(fname) # BOLD derivative in T1w space dds = bintfs.DerivativesDataSink( base_directory=str(tmp_path), keep_dtype=True, desc='preproc', source_file=BOLD_PATH, space=space or Undefined, in_file=fname, ).run() nii = nb.load(dds.outputs.out_file) assert dds.outputs.fixed_hdr == fixed assert int(nii.header['qform_code']) == XFORM_CODES[space] assert int(nii.header['sform_code']) == XFORM_CODES[space] assert nii.header.get_xyzt_units() == ('mm', 'sec')
def save_nifti( image: Any, uri: str, compress: bool = True, partition: Optional[str] = None, # Format-specific kwargs nifti_version: int = 2): if partition is None: partition = "xyz" for img, _uri in partition_gen(image, partition, uri): if nifti_version == 1: header = nib.Nifti1Header() else: header = nib.Nifti2Header() header.set_data_shape(img.shape[::-1]) header.set_data_dtype(img.dtype) header.set_xyzt_units(xyz=get_spacing_units(image, "x") or None, t=get_spacing_units(image, "t") or None) affine = np.eye(img.ndim + 1, img.ndim + 1) for i, ax in enumerate(get_axes(img)): affine[i, i] = get_spacing(img, ax) or 1.0 if nifti_version == 1: ni = nib.Nifti1Image(img.data, affine=affine, header=header) else: ni = nib.Nifti2Image(img.data, affine=affine, header=header) nib.save(ni, _uri)
def test_DerivativesDataSink_bold( tmp_path, space, size, units, xcodes, zipped, fixed, data_dtype ): fname = str(tmp_path / "source.nii") + (".gz" if zipped else "") hdr = nb.Nifti1Header() hdr.set_qform(np.eye(4), code=xcodes[0]) hdr.set_sform(np.eye(4), code=xcodes[1]) hdr.set_xyzt_units(*units) nb.Nifti1Image(np.zeros(size), np.eye(4), hdr).to_filename(fname) # BOLD derivative in T1w space dds = bintfs.DerivativesDataSink( base_directory=str(tmp_path), keep_dtype=True, data_dtype=data_dtype or Undefined, desc="preproc", source_file=BOLD_PATH, space=space or Undefined, in_file=fname, ).run() nii = nb.load(dds.outputs.out_file) assert dds.outputs.fixed_hdr == fixed if data_dtype: assert nii.get_data_dtype() == np.dtype(data_dtype) assert int(nii.header["qform_code"]) == XFORM_CODES[space] assert int(nii.header["sform_code"]) == XFORM_CODES[space] assert nii.header.get_xyzt_units() == ("mm", "sec")
def create_nifti_header(affine, dimensions, voxel_sizes): """ Write a standard nifti header from spatial attribute """ new_header = nib.Nifti1Header() new_header.set_sform(affine) new_header['dim'][1:4] = dimensions new_header['pixdim'][1:4] = voxel_sizes return new_header
def saveNiftiObject(data, unit, filepath): import nibabel as nib print(unit) header_ = nib.Nifti1Header() header_['pixdim'] = np.array([unit, unit, unit, unit, 1., 1., 1., 1.], dtype=np.float32) nifti_img = nib.Nifti1Image(data, affine=None, header=header_) nib.save(nifti_img, filepath)
def get_return_nifti(self): if self.nifti == None: warnings.warn( "Can only output as Nifti if a Nifti was supplied in the first place.", DeprecationWarning) return # TODO: check if results ready return nib.Nifti1Image(self.return_data, self.nifti.affine, nib.Nifti1Header())
def save_mri(image_numpy, image_path, affine=np.eye(4)): """Save a numpy image to the disk Parameters: image_numpy (numpy array) -- input numpy array image_path (str) -- the path of the image """ Imagenii = nib.Nifti1Image(image_numpy, affine, nib.Nifti1Header()) nib.save(Imagenii, image_path)
def convert_single_subject(subj_folder): import os import nibabel as nb import numpy as np t1_folder = path.join(subj_folder, 'PROCESSED', 'MPRAGE', 'SUBJ_111') subj_id = os.path.basename(subj_folder) print('Converting ', subj_id) numerical_id = (subj_id.split("_"))[1] bids_id = 'sub-OASIS1' + str(numerical_id) bids_subj_folder = path.join(dest_dir, bids_id) if not os.path.isdir(bids_subj_folder): os.mkdir(bids_subj_folder) session_folder = path.join(bids_subj_folder, 'ses-M00') if not os.path.isdir(session_folder): os.mkdir(path.join(session_folder)) os.mkdir(path.join(session_folder, 'anat')) # In order do convert the Analyze format to Nifti the path to the .img file is required img_file_path = glob(path.join(t1_folder, '*.img'))[0] output_path = path.join(session_folder, 'anat', bids_id + '_ses-M00_T1w.nii.gz') # First, convert to Nifti so that we can extract the s_form with NiBabel # (NiBabel creates an 'Spm2AnalyzeImage' object that does not contain 'get_sform' method img_with_wrong_orientation_analyze = nb.load(img_file_path) # OASIS-1 images have the same header but sform is incorrect # To solve this issue, we use header from images converted with FreeSurfer # to generate a 'clean hard-coded' header # affine: # [[ 0. 0. -1. 80.] # [ 1. 0. 0. -128.] # [ 0. 1. 0. -128.] # [ 0. 0. 0. 1.]] affine = np.array( [0, 0, -1, 80, 1, 0, 0, -128, 0, 1, 0, -128, 0, 0, 0, 1]).reshape(4, 4) s_form = affine.astype(np.int16) hdr = nb.Nifti1Header() hdr.set_data_shape((256, 256, 160)) hdr.set_data_dtype(np.int16) hdr['bitpix'] = 16 hdr.set_sform(s_form, code='scanner') hdr.set_qform(s_form, code='scanner') hdr['extents'] = 16384 hdr['xyzt_units'] = 10 img_with_good_orientation_nifti = nb.Nifti1Image(np.round( img_with_wrong_orientation_analyze.get_data()).astype( np.int16), s_form, header=hdr) nb.save(img_with_good_orientation_nifti, output_path)
def save(self, data_type, file_name, format=None): """Exports simulated data to a file with a JSON sidecar. Resets the measurement class attribute to zero before simulating. Simulates the signal for each echo-time provided. If defined, adds noise to the complex simulated signal measurements using an SNR value. Args: data_type: Export data type. "Magnitude", "Phase", "Real", or "Imaginary". file_name: Filename of exported file, with or without file extension. format: File format for exported data. If no value given, will attempt to extract format from filename file extension, otherwise default to NIfTI. """ if format is None: format = "nifti" if file_name[-4:] == ".nii": if format != "nifti": print( "File extension and format do not match - saving to NIfTI format" ) format = "nifti" file_name = file_name[0:-4] elif file_name[-4:] == ".mat": if format != "mat": print( "File extension and format do not match - saving to MAT format" ) format = "mat" file_name = file_name[0:-4] if data_type == "Magnitude": vol = self.get_magnitude() elif data_type == "Phase": vol = self.get_phase() elif data_type == "Real": vol = self.get_real() elif data_type == "Imaginary": vol = self.get_imaginary() else: Exception("Unknown datatype") if format == "nifti": empty_header = nib.Nifti1Header() img = nib.Nifti1Image(np.rot90(vol), affine=np.eye(4), header=empty_header) nib.save(img, Path(file_name + ".nii")) self._write_json(file_name) elif format == "mat": savemat(Path(file_name + ".mat"), {"vol": vol}) self._write_json(file_name)
def _get_small_fake_talairach(): labels = ['*', 'b', 'a'] all_labels = itertools.product(*(labels, ) * 5) labels_txt = '\n'.join(map('.'.join, all_labels)) extensions = nibabel.nifti1.Nifti1Extensions( [nibabel.nifti1.Nifti1Extension('afni', labels_txt.encode('utf-8'))]) img = nibabel.Nifti1Image( np.arange(243).reshape((3, 9, 9)), np.eye(4), nibabel.Nifti1Header(extensions=extensions)) return serialize_niimg(img, gzipped=False)
def create_nifti_header(affine, dimensions, voxel_sizes): """ Write a standard nifti header from spatial attribute """ new_header = nib.Nifti1Header() new_header['srow_x'] = affine[0, 0:4] new_header['srow_y'] = affine[1, 0:4] new_header['srow_z'] = affine[2, 0:4] new_header['dim'][1:4] = dimensions new_header['pixdim'][1:4] = voxel_sizes return new_header
def rotatenii_180(): img = nib.load(config.VALID.Clinicalmedical_path) data = img.get_fdata() empty_header = nib.Nifti1Header() empty_header = img.header for i in range(0, data.shape[2]): tempimg = FZ(data[:,:,i]) data[:,:,i] = tempimg data = nib.Nifti1Image(data, img.affine, empty_header) nib.save(data, '/homes/tzheng/Mypythonfiles/densunetdiscirminator/samples/medicaltest3D/rotatedclinical.nii.gz')
def save(filename, obj): """ Save an nipy image object to a file. """ obj = as_volume_img(obj, copy=False) hdr = nib.Nifti1Header() for key, value in obj.metadata.iteritems(): if key in hdr: hdr[key] = value img = nib.Nifti1Image(obj.get_data(), obj.affine, header=hdr) nib.save(img, filename)
def create_surf_file(): outdir = os.path.realpath(mkdtemp()) cwd = os.getcwd() os.chdir(outdir) surf = 'lh.a.nii' hdr = nif.Nifti1Header() shape = (1, 100, 1) hdr.set_data_shape(shape) img = np.random.random(shape) nif.save(nif.Nifti1Image(img, np.eye(4), hdr), os.path.join(outdir, surf)) return surf, outdir, cwd
def _save_dicom_to_nifti(self, si): """Convert DICOM to Nifti""" hdr = nibabel.Nifti1Header() img = si if si.slices > 1: hdr, slice_direction = self._header_dicom_to_nifti(hdr, si) if slice_direction < 0: hdr, img = self._nii_flip_z(hdr, si) slice_direction = abs(slice_direction) img = self._nii_set_ortho(hdr, img) self._nii_save_attributes(si, hdr)
def create_files_in_directory(): outdir = mkdtemp() cwd = os.getcwd() os.chdir(outdir) filelist = ['a.nii', 'b.nii'] for f in filelist: hdr = nb.Nifti1Header() shape = (3, 3, 3, 4) hdr.set_data_shape(shape) img = np.random.random(shape) nb.save(nb.Nifti1Image(img, np.eye(4), hdr), os.path.join(outdir, f)) return filelist, outdir, cwd
def test_endianness(self, endianness, use_array, image_only): hdr = nib.Nifti1Header(endianness=endianness) nii = nib.Nifti1Image(self.im, np.eye(4), header=hdr) nib.save(nii, self.fname) data = [self.fname] if use_array else [{"image": self.fname}] tr = LoadImage(image_only=image_only) if use_array else LoadImaged( "image", image_only=image_only) check_ds = Dataset(data, tr) check_loader = DataLoader(check_ds, batch_size=1) _ = next(iter(check_loader))
def load_volume(path_volume, im_only=True, squeeze=True, dtype=None, aff_ref=None): """ Load volume file. :param path_volume: path of the volume to load. Can either be a nii, nii.gz, mgz, or npz format. If npz format, 1) the variable name is assumed to be 'vol_data', 2) the volume is associated with a identity affine matrix and blank header. :param im_only: (optional) if False, the function also returns the affine matrix and header of the volume. :param squeeze: (optional) whether to squeeze the volume when loading. :param dtype: (optional) if not None, convert the loaded volume to this numpy dtype. :param aff_ref: (optional) If not None, the loaded volume is aligned to this affine matrix. The returned affine matrix is also given in this new space. Must be a numpy array of dimension 4x4. :return: the volume, with corresponding affine matrix and header if im_only is False. """ assert path_volume.endswith( ('.nii', '.nii.gz', '.mgz', '.npz')), 'Unknown data file: %s' % path_volume if path_volume.endswith(('.nii', '.nii.gz', '.mgz')): x = nib.load(path_volume) if squeeze: volume = np.squeeze(x.get_data()) else: volume = x.get_data() aff = x.affine header = x.header else: # npz volume = np.load(path_volume)['vol_data'] if squeeze: volume = np.squeeze(volume) aff = np.eye(4) header = nib.Nifti1Header() if dtype is not None: volume = volume.astype(dtype=dtype) # align image to reference affine matrix if aff_ref is not None: from . import edit_volumes # the import is done here to avoid import loops n_dims, _ = get_dims(list(volume.shape), max_channels=10) volume, aff = edit_volumes.align_volume_to_ref(volume, aff, aff_ref=aff_ref, return_aff=True, n_dims=n_dims) if im_only: return volume else: return volume, aff, header
def test_negative_load_save(): shape = (1, 2, 5) data = np.arange(10).reshape(shape) - 10.0 affine = np.eye(4) hdr = nib.Nifti1Header() hdr.set_data_dtype(np.int16) img = nib.Nifti1Image(data, affine, hdr) str_io = StringIO() img.file_map['image'].fileobj = str_io img.to_file_map() str_io.seek(0) re_img = nib.Nifti1Image.from_file_map(img.file_map) yield assert_array_almost_equal(re_img.get_data(), data, 4)