コード例 #1
0
ファイル: libbasin.py プロジェクト: ccraddock/mindboggle
    def write_surface_with_LUTs(File, Points, Faces, Maps):
        """Like write_scalars in io_vtk but no writing of vertices
        """
        print "writing sulci into VTK file:", File

        Fp = open(File,'w')
        io_vtk.write_header(Fp)
        io_vtk.write_points(Fp, Points)
        io_vtk.write_faces(Fp, Faces)
        if len(Maps) > 0:
        # Make sure that LUTs is a list of lists
            Count = 0
            for LUT_name, LUT in Maps.iteritems():
                if Count == 0 :
                    io_vtk.write_scalars(Fp, LUT, LUT_name)
                else:
                    io_vtk.write_scalars(Fp, LUT, LUT_name, begin_scalars=False)
                Count += 1
        Fp.close()
        return None
コード例 #2
0
        fundus_indices = [x for i,x in enumerate(border_indices)
                          if np.unique(border_label_tuples[i]).tolist()
                              in label_pairs]

        # Store the points as sulcus IDs in the fundus IDs array
        label_boundary_fundi[fundus_indices] = isulcus + 1

    # Construct a distance matrix
    print('Construct a boundary-to-fundus distance matrix...')
    distances, distance_matrix = compute_fundus_distances(label_boundary_fundi,
        fundi, folds, points, n_fundi)

    # Compute mean distances for each fundus
    fundus_mean_distances = np.zeros(n_fundi)
    fundus_std_distances = np.zeros(n_fundi)
    for ifundus in range(n_fundi):
        fundus_distances = distance_matrix[:, ifundus]
        fundus_distances = [x for x in fundus_distances if x != -1]
        fundus_mean_distances[ifundus] = np.mean(fundus_distances)
        fundus_std_distances[ifundus] = np.std(fundus_distances)

    print('Fundus mean distances')
    print(fundus_mean_distances)
    print('Fundus standard deviations of distances')
    print(fundus_std_distances)

    # Write resulting fundus-label boundary distances to VTK file
    print('Write distances to a VTK file for visualization...')
    write_scalars('evaluate_fundi.vtk', points, range(npoints), faces,
                       [distances], ['fundus-label boundary distances'])
コード例 #3
0
ファイル: io_vtk.py プロジェクト: ccraddock/mindboggle
def rewrite_scalars(input_vtk, output_vtk, new_scalars,
                    new_scalar_names=['scalars'], filter_scalars=[],
                    background_value=-1):
    """
    Load VTK format file and save a subset of scalars into a new file.

    Parameters
    ----------
    input_vtk : string
        input VTK file name
    output_vtk : string
        output VTK file name
    new_scalars : list of lists of floats (or single list or array of floats)
        each list (lookup table) contains new values to assign to the vertices
    new_scalar_names : string or list of strings
        each element is the new name for a lookup table
    filter_scalars : list or numpy array (optional)
        scalar values used to filter faces (foreground values retained)
    background_value : integer
        background value

    Returns
    -------
    output_vtk : string
        output VTK file name

    Examples
    --------
    >>> # Write vtk file with curvature values on sulci
    >>> import os
    >>> from mindboggle.utils.io_vtk import read_scalars, rewrite_scalars
    >>> path = os.environ['MINDBOGGLE_DATA']
    >>> input_vtk = os.path.join(path, 'arno', 'shapes', 'lh.pial.mean_curvature.vtk')
    >>> sulci_file = os.path.join(path, 'arno', 'features', 'sulci.vtk')
    >>> output_vtk = 'rewrite_scalars.vtk'
    >>> curvs, name = read_scalars(input_vtk, True,True)
    >>> sulci, name = read_scalars(sulci_file)
    >>> new_scalars = [curvs, sulci]
    >>> new_scalar_names = ['curvs', 'sulci']
    >>> filter_scalars = sulci
    >>> background_value = -1
    >>> #
    >>> rewrite_scalars(input_vtk, output_vtk, new_scalars, new_scalar_names, filter_scalars, background_value)
    >>> #
    >>> # View:
    >>> from mindboggle.utils.plots import plot_surfaces
    >>> plot_surfaces('rewrite_scalars.vtk')

    """
    import os
    import numpy as np

    from mindboggle.utils.mesh import remove_faces
    from mindboggle.utils.io_vtk import write_header, write_points, \
        write_vertices, write_faces, write_scalars, read_vtk, scalars_checker

    # Convert numpy arrays to lists
    if isinstance(new_scalars, np.ndarray):
        new_scalars = new_scalars.tolist()
    if isinstance(filter_scalars, np.ndarray):
        filter_scalars = filter_scalars.tolist()

    # Output VTK file to current working directory
    output_vtk = os.path.join(os.getcwd(), output_vtk)

    # Load VTK file
    faces, lines, indices, points, npoints, scalars, name, \
        input_vtk = read_vtk(input_vtk)

    # Find indices to foreground values
    if filter_scalars:
        indices_keep = [i for i,x in enumerate(filter_scalars)
                        if x != background_value]
        indices_remove = [i for i,x in enumerate(filter_scalars)
                          if x == background_value]
        # Remove surface faces whose three vertices are not all in indices
        faces = remove_faces(faces, indices_keep)

    # Write VTK file
    Fp = open(output_vtk,'w')
    write_header(Fp)
    write_points(Fp, points)
    if indices:
        write_vertices(Fp, indices)
    if faces:
        write_faces(Fp, faces)
    if new_scalars:
        new_scalars, new_scalar_names = scalars_checker(new_scalars,
                                                        new_scalar_names)

        # scalars_checker() returns a list of lists for scalars:
        for i, new_scalar_list in enumerate(new_scalars):
            if filter_scalars:
                for iremove in indices_remove:
                    new_scalar_list[iremove] = background_value
            if np.ndim(new_scalar_list) == 1:
                scalar_type = type(new_scalar_list[0]).__name__
            elif np.ndim(new_scalar_list) == 2:
                scalar_type = type(new_scalar_list[0][0]).__name__
            else:
                print("Undefined scalar type!")
            if i == 0:
                new_scalar_name = new_scalar_names[0]
                write_scalars(Fp, new_scalar_list, new_scalar_name,
                              begin_scalars=True,
                              scalar_type=scalar_type)
            else:
                if len(new_scalar_names) < i + 1:
                    new_scalar_name = new_scalar_names[0]
                else:
                    new_scalar_name = new_scalar_names[i]
                write_scalars(Fp, new_scalar_list, new_scalar_name,
                              begin_scalars=False,
                              scalar_type=scalar_type)
    else:
        print('Error: new_scalars is empty')
        exit()

    Fp.close()

    if not os.path.exists(output_vtk):
        raise(IOError(output_vtk + " not found"))

    return output_vtk
コード例 #4
0
ファイル: io_vtk.py プロジェクト: ccraddock/mindboggle
def write_vtk(output_vtk, points, indices=[], lines=[], faces=[],
              scalars=[], scalar_names=['scalars'], scalar_type='float'):
    """
    Save lists of scalars into the lookup table of a VTK-format file.

    Scalar definition includes specification of a lookup table.
    The definition of a lookup table is optional. If not specified,
    the default VTK table will be used (and tableName should be "default").

    SCALARS dataName dataType numComp
    LOOKUP_TABLE tableName

    Parameters
    ----------
    output_vtk : string
        path of the output VTK file
    points :  list of 3-tuples of floats
        each element has 3 numbers representing the coordinates of the points
    indices : list of integers
        indices of vertices
    lines : list of 2-tuples of integers
        Each element is an edge on the mesh, consisting of 2 integers
        representing the 2 vertices of the edge
    faces : list of 3-tuples of integers
        indices to the three vertices of a face on the mesh
    scalars : list of floats, or list of lists of floats;
        each list (lookup table) contains values assigned to the vertices
    scalar_names : string or list of strings
        each element is the name of a scalar list (lookup table)
    scalar_type : string
        type of scalars ('float' or 'int')

    Examples
    --------
    >>> # Toy example
    >>> import random, os
    >>> from mindboggle.utils.io_vtk import write_vtk
    >>> from mindboggle.utils.plots import plot_surfaces
    >>> points = [[random.random() for i in [1,2,3]] for j in range(4)]
    >>> indices = [1,2,3,0]
    >>> lines = [[1,2],[3,4]]
    >>> faces = [[1,2,3],[0,1,3]]
    >>> scalars = [[random.random() for i in range(4)] for j in [1,2]]
    >>> scalar_names = ['curv','depth']
    >>> output_vtk = 'write_vtk.vtk'
    >>> scalar_type = 'float'
    >>> write_vtk(output_vtk, points, indices, lines, faces, scalars, scalar_names, scalar_type)
    >>> # View:
    >>> plot_surfaces(output_vtk)
    >>> #
    >>> # Write vtk file with curvature values and view:
    >>> import os
    >>> from mindboggle.utils.io_vtk import read_vtk, write_vtk
    >>> from mindboggle.utils.plots import plot_surfaces
    >>> path = os.environ['MINDBOGGLE_DATA']
    >>> input_vtk = os.path.join(path, 'arno', 'shapes', 'lh.pial.mean_curvature.vtk')
    >>> faces, lines, indices, points, npoints, scalars, scalar_names, input_vtk = read_vtk(input_vtk)
    >>> output_vtk = 'write_vtk.vtk'
    >>> scalar_type = 'float'
    >>> write_vtk(output_vtk, points, indices, lines, faces, scalars, scalar_names, scalar_type)
    >>> # View:
    >>> plot_surfaces(output_vtk)

    """
    import os
    import numpy as np

    from mindboggle.utils.io_vtk import write_header, write_points, \
        write_vertices, write_faces, write_scalars, scalars_checker

    # Convert numpy arrays to lists
    if isinstance(faces, np.ndarray):
        faces = faces.tolist()
    if isinstance(points, np.ndarray):
        points = points.tolist()

    output_vtk = os.path.join(os.getcwd(), output_vtk)

    Fp = open(output_vtk,'w')
    write_header(Fp)
    write_points(Fp, points)
    if indices:
        write_vertices(Fp, indices)
    if lines:
        for i in range(0,len(lines)):
            lines[i] = [lines[i][0], lines[i][1]]
        write_faces(Fp, lines) # write_faces can write either lines or faces
    if faces:
        write_faces(Fp, faces)
    scalars, scalar_names = scalars_checker(scalars, scalar_names)
    if len(scalars):

        for i, scalar_list in enumerate(scalars):
            if i == 0:
                scalar_name = scalar_names[i]
                write_scalars(Fp, scalar_list, scalar_name,
                              begin_scalars=True, scalar_type=scalar_type)
            else:
                if len(scalar_names) < i + 1:
                    scalar_name = scalar_names[0]
                else:
                    scalar_name = scalar_names[i]
                write_scalars(Fp, scalar_list, scalar_name,
                              begin_scalars=False, scalar_type=scalar_type)
    Fp.close()

    if not os.path.exists(output_vtk):
        raise(IOError(output_vtk + " not found"))

    return output_vtk
コード例 #5
0
ファイル: io_vtk.py プロジェクト: TankThinkLabs/mindboggle
def rewrite_scalars(input_vtk, output_vtk, new_scalars,
                    new_scalar_names=['scalars'], filter_scalars=[]):
    """
    Load VTK format file and save a subset of scalars into a new file.

    Parameters
    ----------
    input_vtk : string
        input VTK file name
    output_vtk : string
        output VTK file name
    new_scalars : list of lists of floats (or single list or array of floats)
        each list (lookup table) contains new values to assign to the vertices
    new_scalar_names : string or list of strings
        each element is the new name for a lookup table
    filter_scalars : list or numpy array (optional)
        scalar values used to filter faces (values > -1 retained)

    Returns
    -------
    output_vtk : string
        output VTK file name

    Examples
    --------
    >>> # Write vtk file with curvature values on sulci
    >>> import os
    >>> from mindboggle.utils.io_vtk import read_scalars, rewrite_scalars
    >>> path = os.environ['MINDBOGGLE_DATA']
    >>> curv_file = os.path.join(path, 'arno', 'shapes', 'lh.pial.mean_curvature.vtk')
    >>> curvs, name = read_scalars(curv_file, True,True)
    >>> sulci_file = os.path.join(path, 'arno', 'features', 'sulci.vtk')
    >>> sulci, name = read_scalars(sulci_file)
    >>> #
    >>> rewrite_scalars(curv_file, 'rewrite_scalars.vtk',
    >>>                 [curvs, sulci], ['curvs', 'sulci'], sulci)
    >>> #
    >>> # View:
    >>> from mindboggle.utils.plots import plot_vtk
    >>> plot_vtk('rewrite_scalars.vtk')

    """
    import os
    import numpy as np

    from mindboggle.utils.mesh import remove_faces
    from mindboggle.utils.io_vtk import write_header, write_points, \
         write_vertices, write_faces, write_scalars, read_vtk, \
         scalars_checker

    # Convert numpy arrays to lists
    if isinstance(new_scalars, np.ndarray):
        new_scalars = new_scalars.tolist()
    if isinstance(filter_scalars, np.ndarray):
        filter_scalars = filter_scalars.tolist()

    # Output VTK file to current working directory
    output_vtk = os.path.join(os.getcwd(), output_vtk)

    # Load VTK file
    faces, lines, indices, points, npoints, scalars, name, input_vtk = read_vtk(input_vtk)

    # Find indices to nonzero values
    indices = range(npoints)
    if filter_scalars:
        indices_filter = [i for i,x in enumerate(filter_scalars) if x > -1]
        indices_remove = [i for i,x in enumerate(filter_scalars) if x == -1]
        # Remove surface mesh faces whose three vertices are not all in indices
        faces = remove_faces(faces, indices_filter)

    # Write VTK file
    Fp = open(output_vtk,'w')
    write_header(Fp)
    write_points(Fp, points)
    if indices:
        write_vertices(Fp, indices)
    if faces:
        write_faces(Fp, faces)
    if new_scalars:
        new_scalars, new_scalar_names = scalars_checker(new_scalars, new_scalar_names)

        for i, new_scalar_list in enumerate(new_scalars):
            if filter_scalars:
                for iremove in indices_remove:
                    new_scalar_list[iremove] = -1
            if i == 0:
                new_scalar_name = new_scalar_names[0]
                write_scalars(Fp, new_scalar_list, new_scalar_name)
            else:
                if len(new_scalar_names) < i + 1:
                    new_scalar_name = new_scalar_names[0]
                else:
                    new_scalar_name  = new_scalar_names[i]
                write_scalars(Fp, new_scalar_list, new_scalar_name, begin_scalars=False)
    else:
        print('Error: new_scalars is empty')
        exit()

    Fp.close()

    return output_vtk
コード例 #6
0
ファイル: io_vtk.py プロジェクト: TankThinkLabs/mindboggle
def write_vtk(output_vtk, points, indices=[], lines=[], faces=[],
              scalars=[], scalar_names=['scalars']):
    """
    Save lists of scalars into the lookup table of a VTK-format file.

    Scalar definition includes specification of a lookup table.
    The definition of a lookup table is optional. If not specified,
    the default VTK table will be used (and tableName should be "default").

    SCALARS dataName dataType numComp
    LOOKUP_TABLE tableName

    Parameters
    ----------
    output_vtk : string
        path of the output VTK file
    points :  list of 3-tuples of floats
        each element has 3 numbers representing the coordinates of the points
    indices : list of integers
        indices of vertices, default=[]
    lines : list of 2-tuples of integers
        Each element is an edge on the mesh, consisting of 2 integers
        representing the 2 vertices of the edge
        default=[]
    faces : list of 3-tuples of integers
        indices to the three vertices of a face on the mesh, default=[]
    scalars : list of, or list of lists of, floats (or single list of floats)
        each list (lookup table) contains values assigned to the vertices, default=[]
    scalar_names : string or list of strings
        each element is the name of a lookup table, default=['scalars']
        if only one string is given for this field, the program will convert
        it into a list of only this string.

    Notes
    --------

    If you do not have all 7 parameters, it's safer to use syntax like
    ...``indices=indices, faces=faces``... (as in Toy example)
    than syntax like ...``indices, faces``... alone to
    ensure that your variables are aligned with their orders
    in parameter definition.

    Examples
    --------
    >>> # Toy example
    >>> import random, os
    >>> from mindboggle.utils.io_vtk import write_vtk
    >>> from mindboggle.utils.plots import plot_vtk
    >>> points = [[random.random() for i in [1,2,3]] for j in range(4)]
    >>> indices = [1,2,3,0]
    >>> lines = [[1,2],[3,4]]
    >>> faces = [[1,2,3],[0,1,3]]
    >>> scalar_names = ['curv','depth']
    >>> scalars = [[random.random() for i in range(4)] for j in [1,2]]
    >>> #
    >>> write_vtk('write_vtk.vtk', points,
    >>>          indices, lines, faces, scalars, scalar_names)
    >>> #
    >>> # View:
    >>> plot_vtk('write_vtk.vtk')
    >>> #
    >>> # Write vtk file with curvature values on sulci and view:
    >>> from mindboggle.utils.io_vtk import read_vtk, write_vtk
    >>> path = os.environ['MINDBOGGLE_DATA']
    >>> input_vtk = os.path.join(path, 'arno', 'shapes', 'lh.pial.mean_curvature.vtk')
    >>> faces, lines, indices, points, npoints, curvs, name, input_vtk = read_vtk(input_vtk)
    >>> write_vtk('write_vtk.vtk', points, [], [], faces, curvs, 'curvatures')
    >>> plot_vtk('write_vtk.vtk')

    """
    import os
    from mindboggle.utils.io_vtk import write_header, write_points, \
         write_vertices, write_faces, write_scalars, \
         scalars_checker

    output_vtk = os.path.join(os.getcwd(), output_vtk)

    Fp = open(output_vtk,'w')
    write_header(Fp)
    write_points(Fp, points)
    if indices:
        write_vertices(Fp, indices)
    if lines:
        for i in range(0,len(lines)):
            lines[i] = [lines[i][0], lines[i][1]]
        write_faces(Fp, lines) # write_faces can write either lines or faces
    if faces:
        write_faces(Fp, faces)
    scalars, scalar_names = scalars_checker(scalars, scalar_names)
    if len(scalars):

        for i, scalar_list in enumerate(scalars):
            if i == 0:
                scalar_name = scalar_names[i]
                write_scalars(Fp, scalar_list, scalar_name)
            else:
                if len(scalar_names) < i + 1:
                    scalar_name = scalar_names[0]
                else:
                    scalar_name  = scalar_names[i]
                write_scalars(Fp, scalar_list, scalar_name, begin_scalars=False)
    Fp.close()

    return output_vtk