本文整理汇总了Python中nilearn.image.resample_to_img方法的典型用法代码示例。如果您正苦于以下问题:Python image.resample_to_img方法的具体用法?Python image.resample_to_img怎么用?Python image.resample_to_img使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nilearn.image
的用法示例。
在下文中一共展示了image.resample_to_img方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: report_slm_oasis
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def report_slm_oasis(): # pragma: no cover
n_subjects = 5 # more subjects requires more memory
oasis_dataset = nilearn.datasets.fetch_oasis_vbm(n_subjects=n_subjects)
# Resample the images, since this mask has a different resolution
mask_img = resample_to_img(nilearn.datasets.fetch_icbm152_brain_gm_mask(),
oasis_dataset.gray_matter_maps[0],
interpolation='nearest',
)
design_matrix = _make_design_matrix_slm_oasis(oasis_dataset, n_subjects)
second_level_model = SecondLevelModel(smoothing_fwhm=2.0, mask=mask_img)
second_level_model.fit(oasis_dataset.gray_matter_maps,
design_matrix=design_matrix)
contrast = [[1, 0, 0], [0, 1, 0]]
report = make_glm_report(
model=second_level_model,
contrasts=contrast,
bg_img=nilearn.datasets.fetch_icbm152_2009()['t1'],
height_control=None,
)
output_filename = 'generated_report_slm_oasis.html'
output_filepath = os.path.join(REPORTS_DIR, output_filename)
report.save_as_html(output_filepath)
report.get_iframe()
示例2: inject_skullstripped
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def inject_skullstripped(subjects_dir, subject_id, skullstripped):
mridir = op.join(subjects_dir, subject_id, "mri")
t1 = op.join(mridir, "T1.mgz")
bm_auto = op.join(mridir, "brainmask.auto.mgz")
bm = op.join(mridir, "brainmask.mgz")
if not op.exists(bm_auto):
img = nb.load(t1)
mask = nb.load(skullstripped)
bmask = new_img_like(mask, np.asanyarray(mask.dataobj) > 0)
resampled_mask = resample_to_img(bmask, img, "nearest")
masked_image = new_img_like(
img, np.asanyarray(img.dataobj) * resampled_mask.dataobj
)
masked_image.to_filename(bm_auto)
if not op.exists(bm):
copyfile(bm_auto, bm, copy=True, use_hardlink=True)
return subjects_dir, subject_id
示例3: augment_data
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def augment_data(data, truth, affine, scale_deviation=None, flip=True):
n_dim = len(truth.shape)
if scale_deviation:
scale_factor = random_scale_factor(n_dim, std=scale_deviation)
else:
scale_factor = None
if flip:
flip_axis = random_flip_dimensions(n_dim)
else:
flip_axis = None
data_list = list()
for data_index in range(data.shape[0]):
image = get_image(data[data_index], affine)
data_list.append(resample_to_img(distort_image(image, flip_axis=flip_axis,
scale_factor=scale_factor), image,
interpolation="continuous").get_data())
data = np.asarray(data_list)
truth_image = get_image(truth, affine)
truth_data = resample_to_img(distort_image(truth_image, flip_axis=flip_axis, scale_factor=scale_factor),
truth_image, interpolation="nearest").get_data()
return data, truth_data
示例4: apply_mask
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def apply_mask(self, mask, resample_mask_to_brain=False):
""" Mask Brain_Data instance
Note target data will be resampled into the same space as the mask. If you would like the mask
resampled into the Brain_Data space, then set resample_mask_to_brain=True.
Args:
mask: (Brain_Data or nifti object) mask to apply to Brain_Data object.
resample_mask_to_brain: (bool) Will resample mask to brain space before applying mask (default=False).
Returns:
masked: (Brain_Data) masked Brain_Data object
"""
masked = deepcopy(self)
mask = check_brain_data(mask)
if not check_brain_data_is_single(mask):
raise ValueError('Mask must be a single image')
n_vox = len(self) if check_brain_data_is_single(self) else self.shape()[1]
if resample_mask_to_brain:
mask = resample_to_img(mask.to_nifti(), masked.to_nifti())
mask = check_brain_data(mask, masked.mask)
nifti_masker = NiftiMasker(mask_img=mask.to_nifti()).fit()
if n_vox == len(mask):
if check_brain_data_is_single(masked):
masked.data = masked.data[mask.data.astype(bool)]
else:
masked.data = masked.data[:, mask.data.astype(bool)]
else:
masked.data = nifti_masker.fit_transform(masked.to_nifti())
masked.nifti_masker = nifti_masker
if (len(masked.shape()) > 1) & (masked.shape()[0] == 1):
masked.data = masked.data.flatten()
return masked
示例5: _post_run_hook
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def _post_run_hook(self, runtime):
self._fixed_image = self.inputs.after
self._moving_image = self.inputs.before
if self.inputs.base == "before":
resampled_after = nli.resample_to_img(self._fixed_image, self._moving_image)
fname = fname_presuffix(
self._fixed_image, suffix="_resampled", newpath=runtime.cwd
)
resampled_after.to_filename(fname)
self._fixed_image = fname
else:
resampled_before = nli.resample_to_img(
self._moving_image, self._fixed_image
)
fname = fname_presuffix(
self._moving_image, suffix="_resampled", newpath=runtime.cwd
)
resampled_before.to_filename(fname)
self._moving_image = fname
self._contour = self.inputs.wm_seg if isdefined(self.inputs.wm_seg) else None
NIWORKFLOWS_LOG.info(
"Report - setting before (%s) and after (%s) images",
self._fixed_image,
self._moving_image,
)
runtime = super(ResampleBeforeAfterRPT, self)._post_run_hook(runtime)
NIWORKFLOWS_LOG.info("Successfully created report (%s)", self._out_report)
os.unlink(fname)
return runtime
示例6: peaks2maps_workflow
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def peaks2maps_workflow(sleuth_file, output_dir=None, prefix=None, n_iters=10000):
"""
"""
LGR.info('Loading coordinates...')
dset = convert_sleuth_to_dataset(sleuth_file)
LGR.info('Reconstructing unthresholded maps...')
k = Peaks2MapsKernel(resample_to_mask=False)
imgs = k.transform(dset, return_type='image')
mask_img = resample_to_img(dset.mask, imgs[0], interpolation='nearest')
z_data = apply_mask(imgs, mask_img)
LGR.info('Estimating the null distribution...')
res = rfx_glm(z_data, null='empirical', n_iters=n_iters)
res = MetaResult('rfx_glm', maps=res, mask=mask_img)
if output_dir is None:
output_dir = os.path.dirname(os.path.abspath(sleuth_file))
else:
pathlib.Path(output_dir).mkdir(parents=True, exist_ok=True)
if prefix is None:
base = os.path.basename(sleuth_file)
prefix, _ = os.path.splitext(base)
prefix += '_'
LGR.info('Saving output maps...')
res.save_maps(output_dir=output_dir, prefix=prefix)
示例7: get_studies_by_mask
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def get_studies_by_mask(self, mask):
"""
Extract list of studies with at least one coordinate in mask.
Parameters
----------
mask : img_like
Mask across which to search for coordinates.
Returns
-------
found_ids : :obj:`list`
A list of IDs from the Dataset with at least one focus in the mask.
"""
from scipy.spatial.distance import cdist
if isinstance(mask, str):
mask = nib.load(mask)
dset_mask = self.masker.mask_img
if not np.array_equal(dset_mask.affine, mask.affine):
from nilearn.image import resample_to_img
mask = resample_to_img(mask, dset_mask, interpolation='nearest')
mask_ijk = np.vstack(np.where(mask.get_fdata())).T
distances = cdist(mask_ijk, self.coordinates[['i', 'j', 'k']].values)
distances = np.any(distances == 0, axis=0)
found_ids = list(self.coordinates.loc[distances, 'id'].unique())
return found_ids
示例8: crop_nifti
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def crop_nifti(input_img, ref_crop):
"""
:param input_img:
:param crop_sagittal:
:param crop_coronal:
:param crop_axial:
:return:
"""
import nibabel as nib
import os
import numpy as np
from nilearn.image import resample_img, resample_to_img
from nibabel.spatialimages import SpatialImage
basedir = os.getcwd()
# crop_ref = crop_img(ref_img, rtol=0.5)
# crop_ref.to_filename(os.path.join(basedir, os.path.basename(input_img).split('.nii')[0] + '_cropped_template.nii.gz'))
# crop_template = os.path.join(basedir, os.path.basename(input_img).split('.nii')[0] + '_cropped_template.nii.gz')
# resample the individual MRI onto the cropped template image
crop_img = resample_to_img(input_img, ref_crop, force_resample=True)
crop_img.to_filename(os.path.join(basedir, os.path.basename(input_img).split('.nii')[0] + '_cropped.nii.gz'))
output_img = os.path.join(basedir, os.path.basename(input_img).split('.nii')[0] + '_cropped.nii.gz')
crop_template = ref_crop
return output_img, crop_template
示例9: transform
# 需要导入模块: from nilearn import image [as 别名]
# 或者: from nilearn.image import resample_to_img [as 别名]
def transform(self, dataset, masker=None, return_type='image'):
"""
Generate peaks2maps modeled activation images for each Contrast in dataset.
Parameters
----------
dataset : :obj:`nimare.dataset.Dataset`
Dataset for which to make images.
masker : img_like, optional
Only used if dataset is a DataFrame.
return_type : {'image', 'array'}, optional
Whether to return a niimg ('image') or a numpy array.
Default is 'image'.
Returns
-------
imgs : :obj:`list` of :class:`nibabel.Nifti1Image` or :class:`numpy.ndarray`
If return_type is 'image', a list of modeled activation images
(one for each of the Contrasts in the input dataset).
If return_type is 'array', a 2D numpy array (C x V), where C is
contrast and V is voxel.
"""
if isinstance(dataset, pd.DataFrame):
assert masker is not None, 'Argument "masker" must be provided if dataset is a DataFrame'
mask = masker.mask_img
coordinates = dataset.copy()
else:
mask = dataset.masker.mask_img
coordinates = dataset.coordinates
coordinates_list = []
for id_, data in coordinates.groupby('id'):
mm_coords = []
for coord in np.vstack((data.i.values, data.j.values, data.k.values)).T:
mm_coords.append(vox2mm(coord, dataset.masker.mask_img.affine))
coordinates_list.append(mm_coords)
imgs = peaks2maps(coordinates_list, skip_out_of_bounds=True)
if self.resample_to_mask:
mask = dataset.masker.mask_img
resampled_imgs = []
for img in imgs:
resampled_imgs.append(resample_to_img(img, mask))
imgs = resampled_imgs
else:
# Resample mask to data instead of data to mask
mask = resample_to_img(dataset.masker.mask_img,
imgs[0], interpolation='nearest')
if return_type == 'array':
imgs = masker.transform(imgs)
else:
masked_images = []
for img in imgs:
masked_images.append(math_img('map*mask', map=img, mask=mask))
imgs = masked_images
return imgs