本文整理汇总了Python中nibabel.gifti.read函数的典型用法代码示例。如果您正苦于以下问题:Python read函数的具体用法?Python read怎么用?Python read使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: load_texture
def load_texture(path):
"""Return an array from texture data stored in a gifti file
Parameters
----------
path string or list of strings
path of the texture files
Returns
-------
data array of shape (nnode) or (nnode, len(path))
the corresponding data
"""
from nibabel.gifti import read
# use alternative libraries than nibabel if necessary
if hasattr(path, '__iter__'):
tex_data = []
for f in path:
ftex = read(f).getArraysFromIntent('NIFTI_INTENT_TIME_SERIES')
tex = np.array([f.data for f in ftex])
tex_data.append(tex)
tex_data = np.array(tex_data)
if len(tex_data.shape) > 2:
tex_data = np.squeeze(tex_data)
else:
tex_ = read(path)
tex_data = np.array([darray.data for darray in tex_.darrays])
return tex_data
示例2: test_readwritedata
def test_readwritedata():
img = gi.read(DATA_FILE2)
with InTemporaryDirectory():
gi.write(img, "test.gii")
img2 = gi.read("test.gii")
assert_equal(img.numDA, img2.numDA)
assert_array_almost_equal(img.darrays[0].data, img2.darrays[0].data)
示例3: check_surf_mesh
def check_surf_mesh(self, index):
from nilearn._utils.compat import _basestring
import nibabel
# if input is a filename, try to load it
surf_mesh = self.meshes[index]
if isinstance(surf_mesh, _basestring):
if (surf_mesh.endswith('orig') or surf_mesh.endswith('pial') or
surf_mesh.endswith('white') or surf_mesh.endswith('sphere') or
surf_mesh.endswith('inflated')):
coords, faces = nibabel.freesurfer.io.read_geometry(surf_mesh)
elif surf_mesh.endswith('gii'):
coords, faces = gifti.read(surf_mesh).darrays[0].data, \
gifti.read(surf_mesh).darrays[1].data
else:
raise ValueError('Format of mesh file not recognized.')
# if a dictionary is given, check it contains entries for coords and faces
elif isinstance(surf_mesh, dict):
if ('faces' in surf_mesh and 'coords' in surf_mesh):
coords, faces = surf_mesh['coords'], surf_mesh['faces']
else:
raise ValueError('If surf_mesh is given as a dictionary it must '
'contain items with keys "coords" and "faces"')
else:
raise ValueError('surf_mesh must be a either filename or a dictionary '
'containing items with keys "coords" and "faces"')
return coords, faces
示例4: test_readwritedata
def test_readwritedata():
img = gi.read(DATA_FILE2)
newp = pjoin(tempfile.gettempdir(), "test.gii")
gi.write(img, newp)
img2 = gi.read(newp)
assert_equal(img.numDA, img2.numDA)
assert_array_almost_equal(img.darrays[0].data, img2.darrays[0].data)
示例5: test_read_ordering
def test_read_ordering():
# DATA_FILE1 has an expected darray[0].data shape of (3,3). However if we
# read another image first (DATA_FILE2) then the shape is wrong
# Read an image
img2 = gi.read(DATA_FILE2)
assert_equal(img2.darrays[0].data.shape, (143479, 1))
# Read image for which we know output shape
img = gi.read(DATA_FILE1)
assert_equal(img.darrays[0].data.shape, (3, 3))
示例6: loadsurf_gifti
def loadsurf_gifti(fname,surftype,quiet=True):
from nibabel import gifti
from dataset import SurfData
fname = '%s.%sgii'%(fname,'%s')
fname = match_gifti_intent(fname, 'surface')
surf_lh = gifti.read(parse.hemineutral(fname)%'lh')
surf_rh = gifti.read(parse.hemineutral(fname)%'rh')
sverts_lh,sfaces_lh = surf_lh.darrays[0].data, surf_lh.darrays[1].data
sverts_rh,sfaces_rh = surf_rh.darrays[0].data, surf_rh.darrays[1].data
return SurfData(sverts_lh,sfaces_lh,sverts_rh,sfaces_rh,surftype)
示例7: domain_from_mesh
def domain_from_mesh(mesh):
"""Instantiate a StructuredDomain from a gifti mesh
Parameters
----------
mesh: nibabel gifti mesh instance, or path to such a mesh
"""
if isinstance(mesh, basestring):
from nibabel.gifti import read
mesh_ = read(mesh)
else:
mesh_ = mesh
if len(mesh_.darrays) == 2:
cor, tri = mesh_.darrays
elif len(mesh_.darrays) == 3:
cor, nor, tri = mesh_.darrays
else:
raise Exception("%d arrays in gifti file (case not handled)" \
% len(mesh_.darrays))
mesh_dom = MeshDomain(cor.data, tri.data)
vol = mesh_dom.area()
topology = mesh_dom.topology()
dim = 2
return StructuredDomain(dim, mesh_dom.coord, vol, topology)
示例8: check_surf_data
def check_surf_data(self, index, gii_darray=0):
from nilearn._utils.compat import _basestring
import nibabel
surf_data = self.backgrounds[index]
# if the input is a filename, load it
if isinstance(surf_data, _basestring):
if (surf_data.endswith('nii') or surf_data.endswith('nii.gz') or
surf_data.endswith('mgz')):
data = np.squeeze(nibabel.load(surf_data).get_data())
elif (surf_data.endswith('curv') or surf_data.endswith('sulc') or
surf_data.endswith('thickness')):
data = nibabel.freesurfer.io.read_morph_data(surf_data)
elif surf_data.endswith('annot'):
data = nibabel.freesurfer.io.read_annot(surf_data)[0]
elif surf_data.endswith('label'):
data = nibabel.freesurfer.io.read_label(surf_data)
elif surf_data.endswith('gii'):
data = gifti.read(surf_data).darrays[gii_darray].data
else:
raise ValueError('Format of data file not recognized.')
# if the input is an array, it should have a single dimension
elif isinstance(surf_data, np.ndarray):
data = np.squeeze(surf_data)
if len(data.shape) is not 1:
raise ValueError('Data array cannot have more than one dimension.')
return data
示例9: read_mesh
def read_mesh(filename):
if has_ext_gzsafe(filename, 'gii'):
mesh_gii = gifti.read(filename)
cor,tri = (mesh_gii.darrays[0].data, mesh_gii.darrays[1].data)
return cor,tri,mesh_gii.darrays[0].coordsys
else:
raise Exception('Unsupported file format (%s)' %filename)
示例10: display
def display(fun_dir, fs_dir, contrast):
mlab.figure(bgcolor=(1, 1, 1))
left_mesh = freesurfer.read_geometry(os.path.join(fs_dir, 'lh.inflated'))
right_mesh = freesurfer.read_geometry(os.path.join(fs_dir, 'rh.inflated'))
left_curv = os.path.join(fs_dir, 'lh.curv')
right_curv = os.path.join(fs_dir, 'rh.curv')
meshes = [left_mesh, right_mesh]
curves = [left_curv, right_curv]
for hemisphere, mesh_file, curv_file in zip(['lh', 'rh'], meshes, curves):
fun_file = os.path.join(fun_dir, '%s_z_map_%s.gii' % (
contrast, hemisphere))
coords, triangles = mesh_file
x, y, z = coords.T
if hemisphere == 'lh':
x -= 50
else:
x += 50
curv = freesurfer.read_morph_data(curv_file).astype(np.float)
tex = np.array([darrays.data for darrays in
read(fun_file).darrays]).ravel()
print fun_file, tex.min(), tex.max()
name = ''
cmin = -1
cmax = 1
mlab.triangular_mesh(x, y, z, triangles, transparent=True, opacity=1.,
name=name, scalars=curv, colormap="bone",
vmin=cmin, vmax=cmax)
func_mesh = mlab.pipeline.triangular_mesh_source(
x, y, z, triangles, scalars=tex)
thresh = mlab.pipeline.threshold(func_mesh, low=THRESHOLD)
mlab.pipeline.surface(thresh, colormap="hot", vmin=THRESHOLD, vmax=7)
示例11: load_gii
def load_gii(img_path):
"""Load Gifti."""
try:
img = gifti.read(img_path)
except:
raise NPDLError('Image file ({}) could not be loaded'.format(img))
img = np.array(map(lambda d: d.data, img.darrays))
return img
示例12: test_getbyintent
def test_getbyintent():
img = gi.read(DATA_FILE1)
da = img.getArraysFromIntent("NIFTI_INTENT_POINTSET")
assert_equal(len(da), 1)
da = img.getArraysFromIntent("NIFTI_INTENT_TRIANGLE")
assert_equal(len(da), 1)
da = img.getArraysFromIntent("NIFTI_INTENT_CORREL")
assert_equal(len(da), 0)
assert_equal(da, [])
示例13: texture_gradient
def texture_gradient(mesh, texture, mask=None):
""" Compute the gradient of a given texture at each point of the mesh
Parameters
---------
mesh: string, a path to a mesh file
texture: string, a path to a texture file
mask: string, optional, a path to mask texture for that mesh/subject,
so that only part of the vertices are conssidered.
Returns
-------
gradient: array of shape (mesh.n_vertices, 3)
the gradient vector at each mesh node.
fixme
-----
Put in mesh_processing
Note
----
the gradient is expressedn in 3D space, note on surface coordinates
"""
# get coordinates and triangles
coord, triangles = mesh_arrays(mesh)
if mask == None:
mask = np.ones(coord.shape[0]).astype(np.bool)
else:
mask = read(mask).darrays[0].data.astype(np.bool)
# compute the neighborhood system
neighb = mesh_to_graph(mesh).to_coo_matrix().tolil().rows
# read the texture
y = read(texture).darrays[0].data
# compute the gradient
gradient = []
for i in np.where(mask)[0]:
yi = y[neighb[i]]
yi[mask[neighb[i]] == False] = y[i]
grad = np.linalg.lstsq(coord[neighb[i]], yi)[0]
gradient.append(grad)
return np.array(gradient)
示例14: test_metadata
def test_metadata():
for i, dat in enumerate(datafiles):
img = gi.read(dat)
me = img.get_metadata()
medat = me.get_metadata()
assert_equal(numda[i], img.numDA)
assert_equal(img.version, "1.0")
示例15: test_labeltable
def test_labeltable():
img = gi.read(DATA_FILE6)
assert_array_almost_equal(img.darrays[0].data[:3], DATA_FILE6_darr1)
assert_equal(len(img.labeltable.labels), 36)
labeldict = img.labeltable.get_labels_as_dict()
assert_true(labeldict.has_key(660700))
assert_equal(labeldict[660700], u"entorhinal")
assert_equal(img.labeltable.labels[1].key, 2647065)
assert_equal(img.labeltable.labels[1].red, 0.0980392)
assert_equal(img.labeltable.labels[1].green, 0.392157)
assert_equal(img.labeltable.labels[1].blue, 0.156863)
assert_equal(img.labeltable.labels[1].alpha, 1)