本文整理汇总了Python中nipy.io.imageformats.save函数的典型用法代码示例。如果您正苦于以下问题:Python save函数的具体用法?Python save怎么用?Python save使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了save函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: feature_map
def feature_map(self, feature, imPath=None, pw=0.95):
"""
Given a set of feature values, produce a feature map,
assuming that one feature corresponds to one region
Parameters
----------
feature, array of shape (self.k) : the information to map
imPath=None, string yielding the output image path
if not None
pw=0.95: volume of the Gaussian ellipsoid associated with the ROIs
Returns
-------
The image object
"""
if np.size(feature)!=self.k:
raise ValueError, 'Incompatible feature dimension'
from nipy.io.imageformats import save, Nifti1Image
label = self.map_label(self.generate_coordinates(), pval=pw)
label = np.reshape(label, self.shape)
values = np.zeros(self.shape)
values[label>-1] = feature[label[label>-1].astype(np.int)]
wim = Nifti1Image(values, self.affine)
wim.get_header()['descrip']='feature image'
if imPath!=None:
save(wim,imPath)
return wim
示例2: make_image
def make_image(self, path=None):
"""
write a int image where the nonzero values are the ROIs
Parameters
----------
path: string, optional
the desired image path
Returns
-------
brifti image instance
Note
----
the background values are set to -1
the ROIs values are set as [0..self.k-1]
"""
if self.shape==None:
raise ValueError, 'Need self.shape to be defined'
data = -np.ones(self.shape,np.int)
for k in range(self.k):
dk = self.xyz[k].T
data[dk[0], dk[1], dk[2]] = k
wim = Nifti1Image(data, self.affine)
header = wim.get_header()
header['descrip'] = "Multiple ROI image"
if path!=None:
save(wim, path)
return wim
示例3: ffx
def ffx( maskImages, effectImages, varianceImages, resultImage=None):
"""
Computation of the fixed effecst statistics
Parameters
----------
maskImages, string or list of strings
the paths of one or several masks
when several masks, the half thresholding heuristic is used
effectImages, list of strings
the paths ofthe effect images
varianceImages, list of strings
the paths of the associated variance images
resultImage=None, string,
path of the result images
Returns
-------
the computed values
"""
# fixme : check that the images have same referntial
# fixme : check that mask_Images is a list
if len(effectImages)!=len(varianceImages):
raise ValueError, 'Not the correct number of images'
tiny = 1.e-15
nsubj = len(effectImages)
mask = intersect_masks(maskImages, None, threshold=0.5, cc=True)
effects = []
variance = []
for s in range(nsubj):
rbeta = load(effectImages[s])
beta = rbeta.get_data()[mask>0]
rbeta = load(varianceImages[s])
varbeta = rbeta.get_data()[mask>0]
effects.append(beta)
variance.append(varbeta)
effects = np.array(effects)
variance = np.array(variance)
effects[np.isnan(effects)] = 0
effects[np.isnan(variance)] = 0
variance[np.isnan(variance)] = tiny
variance[variance==0] = tiny
t = effects/np.sqrt(variance)
t = t.mean(0)*np.sqrt(nsubj)
#t = np.sum(effects/variance,0)/np.sum(1.0/np.sqrt(variance),0)
nim = load(effectImages[0])
affine = nim.get_affine()
tmap = np.zeros(nim.get_shape())
tmap[mask>0] = t
tImage = Nifti1Image(tmap, affine)
if resultImage!=None:
save(tImage, resultImage)
return tmap
示例4: save_results
def save_results(ppm, id_algo, noise):
savedir = os.path.join(baseres, subjects[s_idx])
tag = id_algo
if noise == 'laplace':
tag += '_laplace'
for i in range(ntissues):
im = Image(ppm[:,:,:,i], affine)
fname = id_posterior + '_' + regs[r_idx] + '_' + tag + '_' + str(i) + '.nii'
save(Nifti1Image(im), os.path.join(savedir, fname))
示例5: intersect_masks
def intersect_masks(input_masks, output_filename=None, threshold=0.5, cc=True):
"""
Given a list of input mask images, generate the output image which
is the the threshold-level intersection of the inputs
Parameters
----------
input_masks: list of strings or ndarrays
paths of the input images nsubj set as len(input_mask_files), or
individual masks.
output_filename, string:
Path of the output image, if None no file is saved.
threshold: float within [0, 1], optional
gives the level of the intersection.
threshold=1 corresponds to keeping the intersection of all
masks, whereas threshold=0 is the union of all masks.
cc: bool, optional
If true, extract the main connected component
Returns
-------
grp_mask, boolean array of shape the image shape
"""
grp_mask = None
for this_mask in input_masks:
if isinstance(this_mask, basestring):
# We have a filename
this_mask = load(this_mask).get_data()
if grp_mask is None:
grp_mask = this_mask.copy().astype(np.int)
else:
grp_mask += this_mask
grp_mask = grp_mask>(threshold*len(input_masks))
if np.any(grp_mask>0) and cc:
grp_mask = largest_cc(grp_mask)
if output_filename is not None:
if isinstance(input_masks[0], basestring):
nim = load(input_masks[0])
header = nim.get_header()
affine = nim.get_affine()
else:
header = dict()
affine = np.eye(4)
header['descrip'] = 'mask image'
output_image = nifti1.Nifti1Image(grp_mask.astype(np.uint8),
affine=affine,
header=header,
)
save(output_image, output_filename)
return grp_mask>0
示例6: to_image
def to_image(self, path=None):
"""
Write itself as an image, and returns it
"""
data = np.zeros(self.shape).astype(np.int8)
data[self.ijk[:,0], self.ijk[:,1], self.ijk[:,2]] = 1
nim = Nifti1Image(data, self.affine)
nim.get_header()['descrip'] = 'mask image'
if path is not None:
save(nim, path)
return nim
示例7: save
def save(filename, obj):
""" Save an nipy image object to a file.
"""
obj = as_volume_img(obj, copy=False)
hdr = imageformats.Nifti1Header()
for key, value in obj.metadata.iteritems():
if key in hdr:
hdr[key] = value
img = imageformats.Nifti1Image(obj.get_data(),
obj.affine,
header=hdr)
imageformats.save(img, filename)
示例8: parcellation_output_with_paths
def parcellation_output_with_paths(Pa, mask_images, group_path, indiv_path):
"""
Function that produces images that describe the spatial structure
of the parcellation. It mainly produces label images at the group
and subject level
Parameters
----------
Pa : Parcellation instance that describes the parcellation
mask_images: list of images paths that define the mask
coord: array of shape (nvox,3) that contains(approximated)
MNI-coordinates of the brain mask voxels considered in the
parcellation process
group_path, string, path of the group-level parcellation image
indiv_path, list of strings, paths of the individual parcellation images
fixme
-----
the referential-defining information should be part of the Pa instance
"""
nsubj = Pa.nb_subj
mxyz = Pa.ijk
# write the template image
tlabs = Pa.group_labels
rmask = load(mask_images[0])
ref_dim = rmask.get_shape()
grid_size = np.prod(ref_dim)
affine = rmask.get_affine()
Label = np.zeros(ref_dim)
Label[Pa.ijk[:,0],Pa.ijk[:,1],Pa.ijk[:,2]]=tlabs+1
wim = Nifti1Image (Label, affine)
hdr = wim.get_header()
hdr['descrip'] = 'group_level Label image obtained from a \
parcellation procedure'
save(wim, group_path)
# write subject-related stuff
for s in range(nsubj):
# write the images
labs = Pa.label[:,s]
Label = np.zeros(ref_dim).astype(np.int)
Label[Pa.ijk[:,0],Pa.ijk[:,1],Pa.ijk[:,2]]=labs+1
wim = Nifti1Image (Label, affine)
hdr = wim.get_header()
hdr['descrip'] = 'individual Label image obtained \
from a parcellation procedure'
save(wim, indiv_path[s])
示例9: ffx_from_stat
def ffx_from_stat( maskImages, statImages, resultImage=None):
"""
Computation of the fixed effects statistics from statistic
Parameters
----------
maskImages, string or list of strings
the paths of one or several masks
when several masks, the half thresholding heuristic is used
statImages, list of strings
the paths ofthe statitsic images
resultImage=None, string,
path of the result images
Returns
-------
the computed values
"""
# fixme : check that the images have same referntial
# fixme : check that mask_Images is a list
nsubj = len(statImages)
mask = intersect_masks(maskImages, None, threshold=0.5, cc=True)
t = []
for s in range(nsubj):
rbeta = load(statImages[s])
beta = rbeta.get_data()[mask>0]
t.append(beta)
t = np.array(t)
t[np.isnan(t)] = 0
t = t.mean(0)*np.sqrt(nsubj)
nim = load(statImages[0])
affine = nim.get_affine()
tmap = np.zeros(nim.get_shape())
tmap[mask>0] = t
tImage = Nifti1Image(tmap, affine)
if resultImage!=None:
save(tImage,resultImage)
return tmap
示例10: mask_parcellation
def mask_parcellation(mask_images, nb_parcel, output_image=None):
"""
Performs the parcellation of a certain mask
Parameters
----------
mask_images: list of strings,
paths of the mask images that define the common space.
nb_parcel: int,
number of desired parcels
output_image: string, optional
path of the output image
Returns
-------
wim: Nifti1Imagine instance, the resulting parcellation
"""
from ..mask import intersect_masks
# compute the group mask
affine = load(mask_images[0]).get_affine()
shape = load(mask_images[0]).get_shape()
mask = intersect_masks(mask_images, threshold=0)>0
ijk = np.where(mask)
ijk = np.array(ijk).T
nvox = ijk.shape[0]
# Get and cluster coordinates
ijk = np.hstack((ijk,np.ones((nvox,1))))
coord = np.dot(ijk, affine.T)[:,:3]
cent, tlabs, J = kmeans(coord, nb_parcel)
# Write the results
label = -np.ones(shape)
label[mask]= tlabs
wim = Nifti1Image(label, affine)
wim.get_header()['descrip'] = 'Label image in %d parcels'%nb_parcel
if output_image is not None:
save(wim, output_image)
return wim
示例11: save_volume
def save_volume(shape, path, affine, mask=None, data=None, descrip=None):
"""
volume saving utility for masked volumes
Parameters
----------
shape, tupe of dimensions of the data
path, string, output image path
affine, transformation of the grid to a coordinate system
mask=None, binary mask used to reduce the volume size
data=None data to be put in the volume
descrip=None, a string descibing what the image is
Fixme
-----
Handle the case where data is multi-dimensional
"""
volume = np.zeros(shape)
if mask== None:
print "Could not write the image: no mask"
return
if data == None:
print "Could not write the image: no data"
return
if np.size(data.shape) == 1:
volume[mask > 0] = data
else:
for i in range(data.shape[0]):
volume[i][mask[0] > 0] = data[i]
wim = Nifti1Image(volume, affine)
if descrip !=None:
wim.get_header()['descrip']=descrip
save(wim, path)
示例12: Parcellation_output
def Parcellation_output(Pa, mask_images, learning_images, coord, nbru,
verbose=1,swd = "/tmp"):
"""
Function that produces images that describe the spatial structure
of the parcellation. It mainly produces label images at the group
and subject level
Parameters
----------
Pa : Parcellation instance that describes the parcellation
mask_images: list of images paths that define the mask
learning_images: list of float images containing the input data
coord: array of shape (nvox,3) that contains(approximated)
MNI-coordinates of the brain mask voxels considered in the
parcellation process
nbru: list of subject ids
verbose=1 : verbosity level
swd = '/tmp': write directory
Results
-------
Pa: the updated Parcellation instance
"""
nsubj = Pa.nb_subj
Pa.set_subjects(nbru)
# write the template image
tlabs = Pa.group_labels
LabelImage = os.path.join(swd,"template_parcel.nii")
rmask = load(mask_images[0])
ref_dim = rmask.get_shape()
affine = rmask.get_affine()
Label = np.zeros(ref_dim)
Label[Pa.ijk[:,0],Pa.ijk[:,1],Pa.ijk[:,2]]=tlabs+1
wim = Nifti1Image (Label, affine)
hdr = wim.get_header()
hdr['descrip'] = 'group_level Label image obtained from a \
parcellation procedure'
save(wim, LabelImage)
# write subject-related stuff
Jac = []
if Pa.isfield('jacobian'):
Jac = Pa.get_feature('jacobian')
Jac = np.reshape(Jac,(Pa.k,nsubj))
for s in range(nsubj):
# write the images
labs = Pa.label[:,s]
LabelImage = os.path.join(swd,"parcel%s.nii" % nbru[s])
JacobImage = os.path.join(swd,"jacob%s.nii" % nbru[s])
Label = np.zeros(ref_dim).astype(np.int)
Label[Pa.ijk[:,0],Pa.ijk[:,1],Pa.ijk[:,2]]=labs+1
wim = Nifti1Image (Label, affine)
hdr = wim.get_header()
hdr['descrip'] = 'individual Label image obtained \
from a parcellation procedure'
save(wim, LabelImage)
if ((verbose)&(np.size(Jac)>0)):
Label = np.zeros(ref_dim)
Label[Pa.ijk[:,0],Pa.ijk[:,1],Pa.ijk[:,2]]=Jac[labs,s]
wim = Nifti1Image (Label, affine)
hdr = wim.get_header()
hdr['descrip'] = 'image of the jacobian of the deformation \
associated with the parcellation'
save(wim, JacobImage)
return Pa
示例13: Nifti1Image
grp_mask = Nifti1Image(mask, load(mask_images[0]).get_affine())
ijk = np.array(np.where(mask)).T
nvox = np.sum(mask)
# output dir
b_smooth = True
if b_smooth:
print "smoothed data"
threshold_path = 'volume_threshold_smooth.con'
swd = '/data/home/virgile/virgile_internship/group_analysis/smoothed_FWHM5'
else:
print "unsmoothed data"
threshold_path = 'volume_threshold.con'
swd = '/data/home/virgile/virgile_internship/group_analysis/smoothed_FWHM0'
save(grp_mask, op.join(swd,'grp_mask.nii'))
################################################################
# Load the effects and variance
################################################################
def load_images(con_images, var_images):
"""
"""
nsubj = len(con_images)
beta = []
varbeta = []
tiny = 1.e-15
for s in range(nsubj):
rbeta = load(con_images[s])
temp = (rbeta.get_data())[mask]
示例14: surrogate_4d_dataset
########################################
paradigm = dm.EventRelatedParadigm(conditions, onsets)
X, names = dm.dmtx_light(frametimes, drift_model='Cosine', hfcut=128,
hrf_model=hrf_model, paradigm=paradigm, add_regs=motion, add_reg_names=add_reg_names)
#######################################
# Get the FMRI data
#######################################
fmri_data = surrogate_4d_dataset(shape=shape, n_scans=n_scans)[0]
# if you want to save it as an image
data_file = op.join(swd,'fmri_data.nii')
save(fmri_data, data_file)
########################################
# Perform a GLM analysis
########################################
# GLM fit
Y = fmri_data.get_data()
model = "ar1"
method = "kalman"
glm = GLM.glm()
mp.pcolor(X)
mp.show()
glm.fit(Y.T, X, method=method, model=model)
#explained = np.dot(X,glm.beta.reshape(X.shape[1],-1)).reshape(Y.T.shape).T
#residuals = Y - explained
示例15: range
label = -np.ones(F.V)
nroi = hroi.NROI_from_field(F, affine, shape, xyz, 0, threshold, smin)
bmap = -np.zeros(F.V)
if nroi!=None:
idx = nroi.discrete_features['index']
for k in range(nroi.k):
label[idx[k]] = k
# saving the blob image,i. e. a label image
wlabel = -2*np.ones(shape)
wlabel[data!=0] = label
blobPath = os.path.join(swd,"blob.nii")
wim = Nifti1Image(wlabel, affine)
wim.get_header()['descrip'] = 'blob image extracted from %s'%InputImage
save(wim, blobPath)
# --- 2.b take blob labelled "1" as an ROI
roi = DiscreteROI( affine=affine, shape=shape)
roi.from_labelled_image(blobPath, 1)
roiPath2 = os.path.join(swd, "roi_blob_1.nii")
roi.make_image(roiPath2)
# --- 2.c take the blob closest to 'position as an ROI'
roiPath3 = os.path.join(swd, "blob_closest_to_%d_%d_%d.nii")%\
(position[0], position[1], position[2])
roi.from_position_and_image(blobPath, np.array(position))
roi.make_image(roiPath3)
# --- 2.d make a set of ROIs from all the blobs
mroi = MultipleROI( affine=affine, shape=shape)