• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python gifti.read函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nibabel.gifti.read函数的典型用法代码示例。如果您正苦于以下问题:Python read函数的具体用法?Python read怎么用?Python read使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了read函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:bthirion,项目名称:retinotopic_mapping,代码行数:29,代码来源:angular_analysis.py


示例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)
开发者ID:jarrodmillman,项目名称:nibabel,代码行数:7,代码来源:test_giftiio.py


示例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
开发者ID:juhuntenburg,项目名称:SurfacePlotting,代码行数:30,代码来源:SurfacePlotting.py


示例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)
开发者ID:unidesigner,项目名称:nibabel,代码行数:8,代码来源:test_giftiio.py


示例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))
开发者ID:unidesigner,项目名称:nibabel,代码行数:9,代码来源:test_giftiio.py


示例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)
开发者ID:aestrivex,项目名称:cvu,代码行数:13,代码来源:preprocessing.py


示例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)
开发者ID:bergtholdt,项目名称:nipy,代码行数:26,代码来源:discrete_domain.py


示例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
开发者ID:juhuntenburg,项目名称:SurfacePlotting,代码行数:29,代码来源:SurfacePlotting.py


示例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)
开发者ID:thomas-vincent,项目名称:pyhrf,代码行数:7,代码来源:io.py


示例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)
开发者ID:bthirion,项目名称:mathematicians,代码行数:33,代码来源:viz_activation.py


示例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
开发者ID:NPDL,项目名称:NPDL-scripts,代码行数:8,代码来源:npdl_utils.py


示例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, [])
开发者ID:unidesigner,项目名称:nibabel,代码行数:9,代码来源:test_giftiio.py


示例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)
开发者ID:bthirion,项目名称:retinotopic_mapping,代码行数:43,代码来源:mesh_processing.py


示例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")
开发者ID:unidesigner,项目名称:nibabel,代码行数:10,代码来源:test_giftiio.py


示例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)
开发者ID:jarrodmillman,项目名称:nibabel,代码行数:12,代码来源:test_giftiio.py


示例16: load_surf_data

def load_surf_data(surf_data):
    """Loading data to be represented on a surface mesh.

    Parameters
    ----------
    surf_data : str or numpy.ndarray
        Either a file containing surface data (valid format are .gii,
        .gii.gz, .mgz, .nii, .nii.gz, or Freesurfer specific files such as
        .thickness, .curv, .sulc, .annot, .label) or
        a Numpy array containing surface data.
    Returns
    -------
    data : numpy.ndarray
        An array containing surface data
    """
    # 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'):
            if LooseVersion(nibabel.__version__) >= LooseVersion('2.1.0'):
                gii = nibabel.load(surf_data)
            else:
                gii = gifti.read(surf_data)
            data = _gifti_img_to_data(gii)
        elif surf_data.endswith('gii.gz'):
            gii = _load_surf_files_gifti_gzip(surf_data)
            data = _gifti_img_to_data(gii)
        else:
            raise ValueError(('The input type is not recognized. %r was given '
                              'while valid inputs are a Numpy array or one of '
                              'the following file formats: .gii, .gii.gz, '
                              '.mgz, .nii, .nii.gz, Freesurfer specific files '
                              'such as .curv, .sulc, .thickness, .annot, '
                              '.label') % surf_data)
    # if the input is a numpy array
    elif isinstance(surf_data, np.ndarray):
        data = np.squeeze(surf_data)
    else:
        raise ValueError('The input type is not recognized. '
                         'Valid inputs are a Numpy array or one of the '
                         'following file formats: .gii, .gii.gz, .mgz, .nii, '
                         '.nii.gz, Freesurfer specific files such as .curv, '
                         '.sulc, .thickness, .annot, .label')
    return data
开发者ID:bthirion,项目名称:nilearn,代码行数:53,代码来源:surface.py


示例17: mesh_arrays

def mesh_arrays(mesh, nibabel=True):
   """ Returns the arrays associated with a mesh
   if len(output)==2, the arrays are coordiantes and triangle lists
   if len(output)==3, the arrays are  coordiantes, triangle lists
       and outer normal
   fixme: use intent !
   """
   if isinstance(mesh, basestring):
       mesh_ = read(mesh)
   else:
       mesh_ = mesh
   cor = mesh_.getArraysFromIntent("NIFTI_INTENT_POINTSET")[0].data
   tri = mesh_.getArraysFromIntent("NIFTI_INTENT_TRIANGLE")[0].data
   return cor, tri
开发者ID:bthirion,项目名称:retinotopic_mapping,代码行数:14,代码来源:mesh_processing.py


示例18: __init__

  def __init__(self, surf_path, max_neighbors=50):
    self.surf_path = surf_path
    try:
      surf = gifti.read(surf_path)
    except:
      raise NPDLError(('Surface: {} does not exist ' +
                       'or is not a valid Gifti file.').format(surf))

    self.coords, self.faces = [surf.darrays[i].data for i in 0, 1]
    self.coords = self.coords.astype(np.float64)
    self.faces = self.faces.astype(np.int32)

    self.num_verts = self.coords.shape[0]
    self.neighbors = self.construct_neighbors(max_neighbors)
    return
开发者ID:NPDL,项目名称:NPDL-scripts,代码行数:15,代码来源:npdl_utils.py


示例19: loadannot_gifti

def loadannot_gifti(parcname, subject, subjects_dir, labnam=None, surf_type='pial',
        surf_struct=None, quiet=False):

    import numpy as np
    from nibabel import gifti

    fname = os.path.join(subjects_dir, subject, 'label', 'lh.%s.%sgii'%(parcname,'%s'))
    fname = match_gifti_intent(fname, 'label')

    annot_lh = gifti.read(parse.hemineutral(fname)%'lh')
    annot_rh = gifti.read(parse.hemineutral(fname)%'rh')
    
    #unpack the annotation data
    labdict_lh=parse.appendhemis(annot_lh.labeltable.get_labels_as_dict(),"lh_")
    labv_lh=map(labdict_lh.get,annot_lh.darrays[0].data)

    labdict_rh=parse.appendhemis(annot_rh.labeltable.get_labels_as_dict(),"rh_")
    labv_rh=map(labdict_rh.get,annot_rh.darrays[0].data)

    labv=labv_lh+labv_rh

    #return labv
    #The objective is now to create MNE label files for these on the fly

    vertices = np.vstack((surf_struct.lh_verts, surf_struct.rh_verts))
    mne_labels = []

    for lab in labnam:
        cur_lab_verts = np.flatnonzero(np.array(labv)==lab)
        cur_lab_pos = vertices[cur_lab_verts]

        cur_lab = mne.Label(cur_lab_verts, pos=cur_lab_pos/1000, hemi=lab[:2],
            name = parse.demangle_hemi(lab))
        mne_labels.append(cur_lab)
        
    return mne_labels	
开发者ID:aestrivex,项目名称:cvu,代码行数:36,代码来源:preprocessing.py


示例20: test_dataarray1

def test_dataarray1():

    img = gi.read(DATA_FILE1)
    assert_array_almost_equal(img.darrays[0].data, DATA_FILE1_darr1)
    assert_array_almost_equal(img.darrays[1].data, DATA_FILE1_darr2)

    me = img.darrays[0].meta.get_metadata()

    assert_true("AnatomicalStructurePrimary" in me)
    assert_true("AnatomicalStructureSecondary" in me)
    assert_equal(me["AnatomicalStructurePrimary"], "CortexLeft")

    assert_array_almost_equal(img.darrays[0].coordsys.xform, np.eye(4, 4))
    assert_equal(gi.xform_codes.niistring[img.darrays[0].coordsys.dataspace], "NIFTI_XFORM_TALAIRACH")
    assert_equal(gi.xform_codes.niistring[img.darrays[0].coordsys.xformspace], "NIFTI_XFORM_TALAIRACH")
开发者ID:unidesigner,项目名称:nibabel,代码行数:15,代码来源:test_giftiio.py



注:本文中的nibabel.gifti.read函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python loadsave.load函数代码示例发布时间:2022-05-27
下一篇:
Python affines.from_matvec函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap