本文整理汇总了Python中nibabel.as_closest_canonical方法的典型用法代码示例。如果您正苦于以下问题:Python nibabel.as_closest_canonical方法的具体用法?Python nibabel.as_closest_canonical怎么用?Python nibabel.as_closest_canonical使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nibabel
的用法示例。
在下文中一共展示了nibabel.as_closest_canonical方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_limits
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def _get_limits(nifti_file, only_plot_noise=False):
if isinstance(nifti_file, str):
nii = nb.as_closest_canonical(nb.load(nifti_file))
data = nii.get_data()
else:
data = nifti_file
data_mask = np.logical_not(np.isnan(data))
if only_plot_noise:
data_mask = np.logical_and(data_mask, data != 0)
vmin = np.percentile(data[data_mask], 0)
vmax = np.percentile(data[data_mask], 61)
else:
vmin = np.percentile(data[data_mask], 0.5)
vmax = np.percentile(data[data_mask], 99.5)
return vmin, vmax
示例2: load_unit
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def load_unit(self, unit_id):
"""Loads the image data for display."""
img_path = self.unit_by_id[unit_id]['image']
params_path = self.unit_by_id[unit_id]['params']
try:
hdr = nib.load(img_path)
self.hdr_this_unit = nib.as_closest_canonical(hdr)
self.img_this_unit_raw = self.hdr_this_unit.get_data()
except Exception as exc:
print(exc)
print('Unable to read image at \n\t{}'.format(img_path))
skip_subject = True
else:
check_image_is_4d(self.img_this_unit_raw)
self.TR_this_unit = self.hdr_this_unit.header.get_zooms()[-1]
skip_subject = False
if np.count_nonzero(self.img_this_unit_raw) == 0:
skip_subject = True
print('Functional image is empty!')
return skip_subject
示例3: run
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def run(opts):
img = nib.as_closest_canonical(nib.load(opts.image[0])) # for pesky LR flipping
data = img.get_data()
hdr = img.get_header()
low_threshold, _ = autothreshold(data, threshold_type = opts.thresholdalgorithm)
print(low_threshold)
mask = np.zeros_like(data)
mask[:] = data
mask[mask < low_threshold] = 0
# mask[mask != 0] = 1
nib.save(nib.Nifti1Image(mask.astype(np.float32, order = "C"),affine=img.affine),'temp.nii.gz')
os.system(os.environ["FSLDIR"] + "/bin/bet temp.nii.gz temp_brain.nii.gz -m -f 0.3")
betmask = nib.as_closest_canonical(nib.load('temp_brain_mask.nii.gz')).get_data()
data[betmask!=1] = 0
if opts.output:
nib.save(nib.Nifti1Image(data.astype(np.float32, order = "C"),affine=img.affine), opts.output[0])
elif opts.replace:
base, name = os.path.split(opts.replace[0])
os.system("mv %s %s/backup_%s" % (opts.replace[0], base, name))
nib.save(nib.Nifti1Image(data.astype(np.float32, order = "C"),affine=img.affine), opts.replace[0])
else:
nib.save(nib.Nifti1Image(data.astype(np.float32, order = "C"),affine=img.affine),'bet_' + opts.image[0])
os.system("rm temp*.nii.gz")
示例4: __init__
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def __init__(self, input_filename, gt_filename, cache=True,
canonical=False):
self.input_filename = input_filename
self.gt_filename = gt_filename
self.canonical = canonical
self.cache = cache
self.input_handle = nib.load(self.input_filename)
# Unlabeled data (inference time)
if self.gt_filename is None:
self.gt_handle = None
else:
self.gt_handle = nib.load(self.gt_filename)
if len(self.input_handle.shape) > 3:
raise RuntimeError("4-dimensional volumes not supported.")
# Sanity check for dimensions, should be the same
input_shape, gt_shape = self.get_pair_shapes()
if self.gt_handle is not None:
if not np.allclose(input_shape, gt_shape):
raise RuntimeError('Input and ground truth with different dimensions.')
if self.canonical:
self.input_handle = nib.as_closest_canonical(self.input_handle)
# Unlabeled data
if self.gt_handle is not None:
self.gt_handle = nib.as_closest_canonical(self.gt_handle)
示例5: apply_transform
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def apply_transform(self, sample: Subject) -> dict:
for image_dict in sample.get_images(intensity_only=False):
affine = image_dict[AFFINE]
if nib.aff2axcodes(affine) == tuple('RAS'):
continue
array = image_dict[DATA][0].numpy()
nii = nib.Nifti1Image(array, affine)
reoriented = nib.as_closest_canonical(nii)
array = reoriented.get_fdata(dtype=np.float32)
# https://github.com/facebookresearch/InferSent/issues/99#issuecomment-446175325
array = array.copy()[np.newaxis, ...]
image_dict[DATA] = torch.from_numpy(array)
image_dict[AFFINE] = reoriented.affine
return sample
示例6: read_image
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def read_image(img_spec,
error_msg='image',
num_dims=3,
reorient_canonical=True):
"""Image reader. Removes stray values close to zero (smaller than 5 %ile)."""
if isinstance(img_spec, str):
if pexists(realpath(img_spec)):
hdr = nib.load(img_spec)
# trying to stick to an orientation
if reorient_canonical:
hdr = nib.as_closest_canonical(hdr)
img = hdr.get_data()
else:
raise IOError('Given path to {} does not exist!\n\t{}'
''.format(error_msg, img_spec))
elif isinstance(img_spec, np.ndarray):
img = img_spec
else:
raise ValueError('Invalid input specified! '
'Input either a path to image data, '
'or provide 3d Matrix directly.')
if num_dims == 3:
img = check_image_is_3d(img)
elif num_dims == 4:
check_image_is_4d(img)
else:
raise ValueError('Requested check for {} dims - allowed: 3 or 4!')
if not np.issubdtype(img.dtype, np.float64):
img = img.astype('float32')
return img
示例7: _run_interface
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def _run_interface(self, runtime):
# Load images, orient as RAS, collect shape and zoom data
in_names = np.array(self.inputs.t1w_list)
orig_imgs = np.vectorize(nb.load)(in_names)
reoriented = np.vectorize(nb.as_closest_canonical)(orig_imgs)
all_zooms = np.array([img.header.get_zooms()[:3] for img in reoriented])
all_shapes = np.array([img.shape[:3] for img in reoriented])
# Identify images that would require excessive up-sampling
valid = np.ones(all_zooms.shape[0], dtype=bool)
while valid.any():
target_zooms = all_zooms[valid].min(axis=0)
scales = all_zooms[valid] / target_zooms
if np.all(scales < self.inputs.max_scale):
break
valid[valid] ^= np.any(scales == scales.max(), axis=1)
# Ignore dropped images
valid_fnames = np.atleast_1d(in_names[valid]).tolist()
self._results["t1w_valid_list"] = valid_fnames
# Set target shape information
target_zooms = all_zooms[valid].min(axis=0)
target_shape = all_shapes[valid].max(axis=0)
self._results["target_zooms"] = tuple(target_zooms.tolist())
self._results["target_shape"] = tuple(target_shape.tolist())
# Create report
dropped_images = in_names[~valid]
segment = self._generate_segment(dropped_images, target_shape, target_zooms)
out_report = os.path.join(runtime.cwd, "report.html")
with open(out_report, "w") as fobj:
fobj.write(segment)
self._results["out_report"] = out_report
return runtime
示例8: reorient
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def reorient(in_file, newpath=None):
"""Reorient Nifti files to RAS."""
out_file = fname_presuffix(in_file, suffix="_ras", newpath=newpath)
nb.as_closest_canonical(nb.load(in_file)).to_filename(out_file)
return out_file
示例9: read_volume
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def read_volume(filepath, dtype=None, return_affine=False, to_ras=False):
"""Return numpy array of data from a neuroimaging file."""
img = nib.load(filepath)
if to_ras:
img = nib.as_closest_canonical(img)
data = img.get_fdata(caching="unchanged")
if dtype is not None:
data = data.astype(dtype)
return data if not return_affine else (data, img.affine)
示例10: reorient
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def reorient(filename):
img = nibabel.load(filename)
img = nibabel.as_closest_canonical(img)
nibabel.save(img, filename)
示例11: reorient_to_RAS
# 需要导入模块: import nibabel [as 别名]
# 或者: from nibabel import as_closest_canonical [as 别名]
def reorient_to_RAS(img_fname: str, output_fname: str = None):
img = nib.load(img_fname)
canonical_img = nib.as_closest_canonical(img)
if output_fname is None:
output_fname = img_fname
nib.save(canonical_img, output_fname)