本文整理汇总了Python中nilearn.image.index_img函数的典型用法代码示例。如果您正苦于以下问题:Python index_img函数的具体用法?Python index_img怎么用?Python index_img使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了index_img函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_mask_4d
def test_mask_4d():
# Dummy mask
mask = np.zeros((10, 10, 10), dtype=int)
mask[3:7, 3:7, 3:7] = 1
mask_bool = mask.astype(bool)
mask_img = Nifti1Image(mask, np.eye(4))
# Dummy data
data = np.zeros((10, 10, 10, 3), dtype=int)
data[..., 0] = 1
data[..., 1] = 2
data[..., 2] = 3
data_img_4d = Nifti1Image(data, np.eye(4))
data_imgs = [index_img(data_img_4d, 0), index_img(data_img_4d, 1),
index_img(data_img_4d, 2)]
# check whether transform is indeed selecting niimgs subset
sample_mask = np.array([0, 2])
masker = NiftiMasker(mask_img=mask_img, sample_mask=sample_mask)
masker.fit()
data_trans = masker.transform(data_imgs)
data_trans_img = index_img(data_img_4d, sample_mask)
data_trans_direct = data_trans_img.get_data()[mask_bool, :]
data_trans_direct = np.swapaxes(data_trans_direct, 0, 1)
assert_array_equal(data_trans, data_trans_direct)
masker = NiftiMasker(mask_img=mask_img, sample_mask=sample_mask)
masker.fit()
data_trans2 = masker.transform(data_img_4d)
assert_array_equal(data_trans2, data_trans_direct)
示例2: _post_run_hook
def _post_run_hook(self, runtime):
self._fixed_image_label = "after"
self._moving_image_label = "before"
self._fixed_image = index_img(self.aggregate_outputs(runtime=runtime).out_corrected, 0)
self._moving_image = index_img(self.inputs.in_files[0], 0)
self._contour = self.inputs.wm_seg if isdefined(self.inputs.wm_seg) else None
NIWORKFLOWS_LOG.info('Report - setting corrected (%s) and warped (%s) images',
self._fixed_image, self._moving_image)
return super(ApplyTOPUPRPT, self)._post_run_hook(runtime)
示例3: ica_vis
def ica_vis(subj_num):
# Use the mean as a background
mean_img_1 = image.mean_img(BOLD_file_1)
mean_img_2 = image.mean_img(BOLD_file_2)
mean_img_3 = image.mean_img(BOLD_file_3)
plot_stat_map(image.index_img(component_img_1, 5), mean_img_1, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task001_run001'+'ica_1'+'.jpg'))
plot_stat_map(image.index_img(component_img_1, 12), mean_img_1, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task001_run001'+'ica_2'+'.jpg'))
plot_stat_map(image.index_img(component_img_2, 5), mean_img_2, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task002_run001'+'ica_1'+'.jpg'))
plot_stat_map(image.index_img(component_img_2, 12), mean_img_2, output_file=os.path.join(data_path,'sub'+subj_num+'_BOLD','task002_run001'+'ica_2'+'.jpg'))
示例4: __main__
def __main__():
volume = image.index_img("E:\\Users\\Niall\\Documents\\Computer Science\\FinalYearProject\\data\\ds105_raw\\ds105\\sub001\\BOLD\\task001_run001\\bold.nii.gz", 0)
smoothed_img = image.smooth_img(volume, fwhm=5)
# print("Read the images");
plotting.plot_glass_brain(volume, title='plot_glass_brain',
black_bg=True, display_mode='xz')
plotting.plot_glass_brain(volume, title='plot_glass_brain',
black_bg=False, display_mode='xz')
plt.show()
# print("Finished");
#gemerate some numbers
t = np.linspace(1, 10, 2000) # 2000 points between 1 and 10
t
#plot the graph
plt.plot(t, np.cos(t))
plt.ylabel('Subject Response')
plt.show()
示例5: concat_RL
def concat_RL(R_img, L_img, rl_idx_pair, rl_sign_pair=None):
"""
Given R and L ICA images and their component index pairs, concatenate images to
create bilateral image using the index pairs. Sign flipping can be specified in rl_sign_pair.
"""
# Make sure images have same number of components and indices are less than the n_components
assert R_img.shape == L_img.shape
n_components = R_img.shape[3]
assert np.max(rl_idx_pair) < n_components
n_rl_imgs = len(rl_idx_pair[0])
assert n_rl_imgs == len(rl_idx_pair[1])
if rl_sign_pair:
assert n_rl_imgs == len(rl_sign_pair[0])
assert n_rl_imgs == len(rl_sign_pair[1])
# Match indice pairs and combine
terms = R_img.terms.keys()
rl_imgs = []
rl_term_vals = []
for i in range(n_rl_imgs):
rci, lci = rl_idx_pair[0][i], rl_idx_pair[1][i]
R_comp_img = index_img(R_img, rci)
L_comp_img = index_img(L_img, lci)
# sign flipping
r_sign = rl_sign_pair[0][i] if rl_sign_pair else 1
l_sign = rl_sign_pair[1][i] if rl_sign_pair else 1
R_comp_img = math_img("%d*img" % (r_sign), img=R_comp_img)
L_comp_img = math_img("%d*img" % (l_sign), img=L_comp_img)
# combine images
rl_imgs.append(math_img("r+l", r=R_comp_img, l=L_comp_img))
# combine terms
if terms:
r_ic_terms, r_ic_term_vals = get_ic_terms(R_img.terms, rci, sign=r_sign)
l_ic_terms, l_ic_term_vals = get_ic_terms(L_img.terms, lci, sign=l_sign)
rl_term_vals.append((r_ic_term_vals + l_ic_term_vals) / 2)
# Squash into single image
concat_img = nib.concat_images(rl_imgs)
if terms:
concat_img.terms = dict(zip(terms, np.asarray(rl_term_vals).T))
return concat_img
示例6: openBold
def openBold(self):
file = self.onOpen([('NIFTI files', '*.nii.gz'), ('All files', '*')])
print("anatomy file: " + file)
bold = image.index_img(file, 0)
plotting.plot_glass_brain(bold, title='glass_brain',
black_bg=True, display_mode='ortho')
plt.show()
示例7: mean_nodiff_fct
def mean_nodiff_fct(in_file, bval_file, nodiff_b=0):
import os, numpy as np
from nilearn import image
bvals = np.loadtxt(bval_file)
nodiff_index = bvals <= nodiff_b
nodiff_img = image.index_img(in_file, nodiff_index)
mean_nodiff_img = image.mean_img(nodiff_img)
out_file = os.path.abspath('mean_nodiff.nii.gz')
mean_nodiff_img.to_filename(out_file)
return out_file
示例8: plotCorrelationResults
def plotCorrelationResults(self, background, overlay, desired_resolution_file_location):
image_to_resample = nibabel.load(background)
image_to_use_for_sample = image.index_img(desired_resolution_file_location, 0)
resampled_background = resample_img(image_to_resample,target_affine = image_to_use_for_sample.get_affine(), target_shape=image_to_use_for_sample.shape)
mri_args = {
'background' : resampled_background,
'cmap_bg' : 'gray',
'cmap_overlay' : 'PiYG', # YlOrRd_r # pl.cm.autumn
'interactive' : cfg.getboolean('examples', 'interactive', True),
}
plot_lightbox(overlay=overlay, vlim=(-1.0, 1.0), do_stretch_colors=True, **mri_args)
示例9: run
def run(idx, reduction, alpha, mask, raw, n_components, init, func_filenames):
output_dir = join(trace_folder, 'experiment_%i' % idx)
try:
os.makedirs(output_dir)
except OSError:
pass
dict_fact = SpcaFmri(mask=mask,
smoothing_fwhm=3,
batch_size=40,
shelve=not raw,
n_components=n_components,
replacement=False,
dict_init=fetch_atlas_smith_2009().rsn70 if
init else None,
reduction=reduction,
alpha=alpha,
random_state=0,
n_epochs=2,
l1_ratio=0.5,
backend='c',
memory=expanduser("~/nilearn_cache"), memory_level=2,
verbose=5,
n_jobs=1,
trace_folder=output_dir
)
print('[Example] Learning maps')
t0 = time.time()
dict_fact.fit(func_filenames, raw=raw)
t1 = time.time() - t0
print('[Example] Dumping results')
# Decomposition estimator embeds their own masker
masker = dict_fact.masker_
components_img = masker.inverse_transform(dict_fact.components_)
components_img.to_filename(join(output_dir, 'components_final.nii.gz'))
print('[Example] Run in %.2f s' % t1)
# Show components from both methods using 4D plotting tools
import matplotlib.pyplot as plt
from nilearn.plotting import plot_prob_atlas, show
print('[Example] Displaying')
fig, axes = plt.subplots(2, 1)
plot_prob_atlas(components_img, view_type="filled_contours",
axes=axes[0])
plot_stat_map(index_img(components_img, 0),
axes=axes[1],
colorbar=False,
threshold=0)
plt.savefig(join(output_dir, 'components.pdf'))
show()
示例10: test_appy_realigment_and_extract_realignment_params_APIs
def test_appy_realigment_and_extract_realignment_params_APIs():
# setu
n_scans = 10
translation = np.array([1, 2, 3]) # mm
rotation = np.array([3, 2, 1]) # degrees
# create data
affine = np.array([[-3., 0., 0., 96.],
[0., 3., 0., -96.],
[0., 0., 3., -69.],
[0., 0., 0., 1.]])
film = create_random_image(shape=[16, 16, 16, n_scans], affine=affine)
# there should be no motion
for t in range(n_scans):
np.testing.assert_array_equal(
extract_realignment_params(index_img(film, t), index_img(film, 0)),
get_initial_motion_params())
# now introduce motion into other vols relative to the first vol
rp = np.ndarray((n_scans, 12))
for t in range(n_scans):
rp[t, ...] = get_initial_motion_params()
rp[t, :3] += _make_vol_specific_translation(translation, n_scans, t)
rp[t, 3:6] += _make_vol_specific_rotation(rotation, n_scans, t)
# apply motion (noise)
film = apply_realignment(film, rp)
# check that motion has been induced
for t in range(n_scans):
_tmp = get_initial_motion_params()
_tmp[:3] += _make_vol_specific_translation(translation, n_scans, t)
_tmp[3:6] += _make_vol_specific_rotation(rotation, n_scans, t)
np.testing.assert_array_almost_equal(
extract_realignment_params(film[t], film[0]), _tmp)
示例11: display_results
def display_results(self):
#load the high-res anatomy - this needs to be downsampled to fit the resolution of our data
original_anatomy = nibabel.load(self.processing_model.processing_request_model.anatomy_location)
#we will use the first volumne/sample from the bold data to
bold_data_sample = image.index_img(self.processing_model.processing_request_model.bold_location, 0)
#resample the original anatomy to meet the bold data
resampled_anatomy = resample_img(original_anatomy, target_affine = bold_data_sample.get_affine(), target_shape=bold_data_sample.shape)
mri_args = {
'background' : resampled_anatomy,
'cmap_bg' : 'gray',
'cmap_overlay' : 'PiYG', # YlOrRd_r # pl.cm.autumn
'interactive' : cfg.getboolean('examples', 'interactive', True),
}
self.result_view.plot_results(self.processing_model.result, mri_args)
示例12: _3d_in_file
def _3d_in_file(in_file):
''' if self.inputs.in_file is 3d, return it.
if 4d, pick an arbitrary volume and return that.
if in_file is a list of files, return an arbitrary file from
the list, and an arbitrary volume from that file
'''
in_file = filemanip.filename_to_list(in_file)[0]
try:
in_file = nb.load(in_file)
except AttributeError:
in_file = in_file
if in_file.get_data().ndim == 3:
return in_file
return nlimage.index_img(in_file, 0)
示例13: plot_roi
masker.fit(miyawaki_filename)
plot_roi(masker.mask_img_, miyawaki_mean_img,
title="Mask from already masked data")
###############################################################################
# From raw EPI data
# Load NYU resting-state dataset
nyu_dataset = datasets.fetch_nyu_rest(n_subjects=1)
nyu_filename = nyu_dataset.func[0]
# Restrict nyu to 100 frames to speed up computation
from nilearn.image import index_img
nyu_img = index_img(nyu_filename, slice(0, 100))
# To display the background
nyu_mean_img = image.mean_img(nyu_img)
# Simple mask extraction from EPI images
# We need to specify an 'epi' mask_strategy, as this is raw EPI data
masker = NiftiMasker(mask_strategy='epi')
masker.fit(nyu_img)
plot_roi(masker.mask_img_, nyu_mean_img, title='EPI automatic mask')
# Generate mask with strong opening
masker = NiftiMasker(mask_strategy='epi', mask_args=dict(opening=10))
masker.fit(nyu_img)
plot_roi(masker.mask_img_, nyu_mean_img, title='EPI Mask with strong opening')
示例14: method
data_path = sample.data_path()
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-vol-7-meg-inv.fif'
fname_evoked = data_path + '/MEG/sample/sample_audvis-ave.fif'
snr = 3.0
lambda2 = 1.0 / snr ** 2
method = "dSPM" # use dSPM method (could also be MNE or sLORETA)
# Load data
evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
inverse_operator = read_inverse_operator(fname_inv)
src = inverse_operator['src']
# Compute inverse solution
stc = apply_inverse(evoked, inverse_operator, lambda2, method)
stc.crop(0.0, 0.2)
# Export result as a 4D nifti object
img = stc.as_volume(src,
mri_resolution=False) # set True for full MRI resolution
# Save it as a nifti file
# nib.save(img, 'mne_%s_inverse.nii.gz' % method)
t1_fname = data_path + '/subjects/sample/mri/T1.mgz'
# Plotting with nilearn ######################################################
plot_stat_map(index_img(img, 61), t1_fname, threshold=8.,
title='%s (t=%.1f s.)' % (method, stc.times[61]))
plt.show()
示例15: GraphLassoCV
gsc_nets = GraphLassoCV(verbose=2, alphas=20)
gsc_nets.fit(FS_netproj)
np.save('%i_nets_cov' % sub_id, gsc_nets.covariance_)
np.save('%i_nets_prec' % sub_id, gsc_nets.precision_)
except:
pass
###############################################################################
# dump region poolings
###############################################################################
from nilearn.image import resample_img
crad = ds.fetch_atlas_craddock_2012()
# atlas_nii = index_img(crad['scorr_mean'], 19) # Craddock 200 region atlas
atlas_nii = index_img(crad['scorr_mean'], 9) # Craddock 100 region atlas
r_atlas_nii = resample_img(
img=atlas_nii,
target_affine=mask_file.get_affine(),
target_shape=mask_file.shape,
interpolation='nearest'
)
r_atlas_nii.to_filename('debug_ratlas.nii.gz')
from nilearn.input_data import NiftiLabelsMasker
nlm = NiftiLabelsMasker(
labels_img=r_atlas_nii, mask_img=mask_file,
standardize=True, detrend=True)
nlm.fit()