本文整理汇总了Python中nibabel.load方法的典型用法代码示例。如果您正苦于以下问题:Python nibabel.load方法的具体用法?Python nibabel.load怎么用?Python nibabel.load使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nibabel
的用法示例。
在下文中一共展示了nibabel.load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _run_interface
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def _run_interface(self, runtime):
import nibabel as nib
from nipype.utils.filemanip import fname_presuffix
bold_img = nib.load(self.inputs.timeseries_file)
bold_mask_img = nib.load(self.inputs.mask_file)
bold_data = bold_img.get_fdata()
bold_mask = bold_mask_img.get_fdata().astype(bool)
outliers = is_outlier(bold_data[bold_mask].T, thresh=self.inputs.threshold)
out = fname_presuffix(self.inputs.timeseries_file, suffix='_censored')
bold_img.__class__(bold_data[..., ~outliers],
bold_img.affine, bold_img.header).to_filename(out)
self._results['censored_file'] = out
self._results['outliers'] = outliers
return runtime
示例2: test_censor_volumes
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def test_censor_volumes(tmp_path, betaseries_file, brainmask_file):
outlier_file = tmp_path / 'betaseries_outlier.nii.gz'
# make an outlier volume
outlier_idx = 6
beta_img = nib.load(str(betaseries_file))
beta_data = beta_img.get_fdata()
beta_data[..., outlier_idx] += 1000
beta_img.__class__(
beta_data, beta_img.affine, beta_img.header).to_filename(str(outlier_file))
censor_volumes = CensorVolumes(timeseries_file=str(outlier_file),
mask_file=str(brainmask_file))
res = censor_volumes.run()
assert nib.load(res.outputs.censored_file).shape[-1] == beta_img.shape[-1] - 1
assert res.outputs.outliers[outlier_idx]
示例3: forget_importer
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def forget_importer(name):
'''
forget_importer(name) yields True if an importer of type name was successfully forgotten from
the neuropythy importers list and false otherwise. This function must be called before an
importer can be replaced.
'''
global importers
name = name.lower()
if name in importers:
importers = importers.discard(name)
delattr(load, name)
return True
else:
return False
# The list of exporter types we understand
示例4: load_json
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def load_json(filename, to='auto'):
'''
load_json(filename) yields the object represented by the json file or stream object filename.
The optional argument to may be set to None to indicate that the JSON data should be returned
verbatim rather than parsed by neuropythy's denormalize system.
'''
from neuropythy.util import denormalize as denorm
if pimms.is_str(filename):
try:
with gzip.open(filename, 'rt') as fl: dat = json.load(fl)
except Exception:
with open(filename, 'rt') as fl: dat = json.load(fl)
else:
dat = json.load(filename)
filename = '<stream>'
if to is None: return dat
elif to == 'auto': return denorm(dat)
else: raise ValueError('unrecognized to option: %s' % to)
示例5: generateImgSlicesFolder
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def generateImgSlicesFolder(data_folder = '../Data/MS2017a/scans/'):
scan_folders = glob.glob(data_folder + '*')
for sf in scan_folders:
slice_dir_path = os.path.join(sf, 'slices/')
if not os.path.exists(slice_dir_path):
print('Creating directory at:' , slice_dir_path)
os.makedirs(slice_dir_path)
img = nib.load(os.path.join(sf, 'pre/FLAIR.nii.gz'))
img_np = img.get_data()
img_affine = img.affine
print(sf)
print('The img shape', img_np.shape[2])
for i in range(img_np.shape[2]):
slice_img_np = img_np[:,:,i]
nft_img = nib.Nifti1Image(slice_img_np, img_affine)
nib.save(nft_img, slice_dir_path + 'FLAIR_' + str(i) + '.nii.gz')
if os.path.basename(sf) == '0':
slice_img = nib.load(slice_dir_path + 'FLAIR_' + str(i) + '.nii.gz').get_data() / 5
print('DID I GET HERE?')
print('Writing to', str(i) + '.jpg')
示例6: generateGTSlicesFolder
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def generateGTSlicesFolder(data_folder = '../Data/MS2017a/scans/'):
scan_folders = glob.glob(data_folder + '*')
for sf in scan_folders:
slice_dir_path = os.path.join(sf, 'gt_slices/')
if not os.path.exists(slice_dir_path):
print('Creating directory at:' , slice_dir_path)
os.makedirs(slice_dir_path)
img = nib.load(os.path.join(sf, 'wmh.nii.gz'))
img_np = img.get_data()
img_affine = img.affine
print(sf)
print('The img shape', img_np.shape[2])
for i in range(img_np.shape[2]):
slice_img_np = img_np[:,:,i]
nft_img = nib.Nifti1Image(slice_img_np, img_affine)
nib.save(nft_img, slice_dir_path + 'wmh_' + str(i) + '.nii.gz')
if os.path.basename(sf) == '0':
slice_img = nib.load(slice_dir_path + 'wmh_' + str(i) + '.nii.gz').get_data() * 256
#cv2.imwrite('temp/' + str(i) + '.jpg', slice_img)
示例7: load_surfaces
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def load_surfaces(filename, suppress_echo = False):
'''
separate a cifti file into surfaces,
then loads the surface data
'''
## separate the cifti file into left and right surfaces
with TempDir() as tempdir:
L_data_surf=os.path.join(tempdir, 'Ldata.func.gii')
R_data_surf=os.path.join(tempdir, 'Rdata.func.gii')
run(['wb_command','-cifti-separate', filename, 'COLUMN',
'-metric', 'CORTEX_LEFT', L_data_surf,
'-metric', 'CORTEX_RIGHT', R_data_surf],
suppress_echo = suppress_echo)
## load both surfaces and concatenate them together
Ldata = load_gii_data(L_data_surf)
Rdata = load_gii_data(R_data_surf)
return Ldata, Rdata
示例8: __get_tr
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def __get_tr(self, tr_arg):
'''read tr from func file is not indicated'''
if tr_arg:
tr = float(tr_arg)
else:
if self.func.type == "nifti":
tr_ms = nib.load(self.func.path).header.get_zooms()[3]
if tr_ms > 150:
'''nowing that no tr is never between 20 and 200, we assume seconds vs ms'''
logger.info('The TR is greater than 150, we beleive this is in ms, dividing by 1000')
tr = float(tr_ms) / 1000
else:
tr = tr_ms
if self.func.type == "cifti":
tr_out = ciftify.utils.get_stdout(['wb_command','-file-information',
'-only-step-interval', self.func.path])
tr = float(tr_out.strip())
if tr > 150:
logger.warning("TR should be specified in seconds, improbable value {} given".format(tr))
return tr
示例9: _calculate_dadt_nifti
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def _calculate_dadt_nifti(msh, nifti_image, coil_matrix, didt, geo_fn):
""" auxiliary function that interpolates the dA/dt field from a nifti file """
if isinstance(nifti_image, str):
nifti_image = nib.load(nifti_image)
elif isinstance(nifti_image, nib.nifti1.Nifti1Image):
pass
else:
raise NameError('Failed to parse input volume (not string or nibabel nifti1 volume)')
coords = msh.nodes.node_coord
out = _get_field(nifti_image, coords, coil_matrix)
out = out * didt
node_data = mesh_io.NodeData(out.T)
if geo_fn is not None:
y_axis = np.arange(1, 10, dtype=float)[:, None] * (0, 1, 0)
z_axis = np.arange(1, 30, dtype=float)[:, None] * (0, 0, 1)
pos = np.vstack((((0, 0, 0)), y_axis, z_axis))
pos = (coil_matrix[:3, :3].dot(pos.T) + coil_matrix[:3, 3][:, None]).T
mesh_io.write_geo_spheres(pos, geo_fn,
name='coil_directions')
return node_data
示例10: _get_vol_info
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def _get_vol_info(self):
if self.anisotropy_vol is not None:
if self.anisotropy_affine is not None:
return self.anisotropy_vol, self.anisotropy_affine
if not self.fn_tensor_nifti:
raise ValueError('could not get anisotropy information: '
'fn_tensor_nifti not set')
fn_nifti = \
os.path.abspath(os.path.expanduser(self.fn_tensor_nifti))
if not os.path.isfile(fn_nifti):
raise ValueError(
'Could not find file \'{0}\' to get anisotropy '
'information'.format(self.fn_tensor_nifti))
# Load the nifti and interpolate the conductivieis
image = nibabel.load(fn_nifti)
affine = image.affine
return image.dataobj, affine
示例11: read_gifti_surface
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def read_gifti_surface(fn):
''' Reads a gifti surface
Parameters
-----------
fn: str
File name
Returns
---------
msh: Msh()
mesh structure with geometrical information
'''
s = nibabel.load(fn)
faces = s.get_arrays_from_intent('NIFTI_INTENT_TRIANGLE')[0].data
nodes = s.get_arrays_from_intent('NIFTI_INTENT_POINTSET')[0].data
msh = Msh()
msh.elm = Elements(triangles=np.array(faces + 1, dtype=int))
msh.nodes = Nodes(np.array(nodes, dtype=float))
return msh
示例12: load_nifti_img
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def load_nifti_img(filepath, dtype):
'''
NIFTI Image Loader
:param filepath: path to the input NIFTI image
:param dtype: dataio type of the nifti numpy array
:return: return numpy array
'''
nim = nib.load(filepath)
out_nii_array = np.array(nim.get_data(),dtype=dtype)
out_nii_array = np.squeeze(out_nii_array) # drop singleton dim in case temporal dim exists
meta = {'affine': nim.get_affine(),
'dim': nim.header['dim'],
'pixdim': nim.header['pixdim'],
'name': os.path.basename(filepath)
}
return out_nii_array, meta
示例13: auto_crop_image
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def auto_crop_image(input_name, output_name, reserve):
nim = nib.load(input_name)
image = nim.get_data()
X, Y, Z = image.shape[:3]
# Detect the bounding box of the foreground
idx = np.nonzero(image > 0)
x1, x2 = idx[0].min() - reserve, idx[0].max() + reserve + 1
y1, y2 = idx[1].min() - reserve, idx[1].max() + reserve + 1
z1, z2 = idx[2].min() - reserve, idx[2].max() + reserve + 1
x1, x2 = max(x1, 0), min(x2, X)
y1, y2 = max(y1, 0), min(y2, Y)
z1, z2 = max(z1, 0), min(z2, Z)
print('Bounding box')
print(' bottom-left corner = ({},{},{})'.format(x1, y1, z1))
print(' top-right corner = ({},{},{})'.format(x2, y2, z2))
# Crop the image
image = image[x1:x2, y1:y2, z1:z2]
# Update the affine matrix
affine = nim.affine
affine[:3, 3] = np.dot(affine, np.array([x1, y1, z1, 1]))[:3]
nim2 = nib.Nifti1Image(image, affine)
nib.save(nim2, output_name)
示例14: _split_segments
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def _split_segments(in_file):
from pathlib import Path
import numpy as np
import nibabel as nb
segimg = nb.load(in_file)
data = np.int16(segimg.dataobj)
hdr = segimg.header.copy()
hdr.set_data_dtype('uint8')
out_files = []
for i, label in enumerate(("GM", "WM", "CSF"), 1):
out_fname = str(Path.cwd() / f"aseg_label-{label}_mask.nii.gz")
segimg.__class__(data == i, segimg.affine, hdr).to_filename(out_fname)
out_files.append(out_fname)
return out_files
示例15: apply_lut
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import load [as 别名]
def apply_lut(in_dseg, lut, newpath=None):
"""Map the input discrete segmentation to a new label set (lookup table, LUT)."""
import numpy as np
import nibabel as nb
from nipype.utils.filemanip import fname_presuffix
if newpath is None:
from os import getcwd
newpath = getcwd()
out_file = fname_presuffix(in_dseg, suffix='_dseg', newpath=newpath)
lut = np.array(lut, dtype='int16')
segm = nb.load(in_dseg)
hdr = segm.header.copy()
hdr.set_data_dtype('int16')
segm.__class__(lut[np.asanyarray(segm.dataobj, dtype=int)].astype('int16'),
segm.affine, hdr).to_filename(out_file)
return out_file