Пример #1
0
 def _glyph_type_changed(self, value):
     if self.glyph_type == 'vector':
         self.glyph = tvtk.Glyph3D(clamping=True)
     else:
         self.glyph = tvtk.TensorGlyph(scale_factor=0.1)
         self.show_scale_mode = False
     self.glyph.on_trait_change(self.render)
Пример #2
0
def convexhull(ch3d):
    poly = tvtk.PolyData()
    poly.points = ch3d.points
    poly.polys = ch3d.simplices
    sphere = tvtk.SphereSource(radius=0.02)
    points3d = tvtk.Glyph3D()
    points3d.set_source_connection(sphere.output_port)
    points3d.set_input_data(poly)
    # 绘制凸多面体的面,设置半透明度
    m1 = tvtk.PolyDataMapper()
    m1.set_input_data(poly)
    a1 = tvtk.Actor(mapper=m1)
    a1.property.opacity = 0.3
    # 绘制凸多面体的边,设置为红色
    m2 = tvtk.PolyDataMapper()
    m2.set_input_data(poly)
    a2 = tvtk.Actor(mapper=m2)
    a2.property.representation = "wireframe"
    a2.property.line_width = 2.0
    a2.property.color = (1.0, 0, 0)
    # 绘制凸多面体的顶点,设置为绿色
    m3 = tvtk.PolyDataMapper(input_connection=points3d.output_port)
    a3 = tvtk.Actor(mapper=m3)
    a3.property.color = (0.0, 1.0, 0.0)
    return [a1, a2, a3]
Пример #3
0
def vtk_convexhull(ch, radius=0.02):
    from tvtk.api import tvtk

    poly = tvtk.PolyData()
    poly.points = ch.points
    poly.polys = ch.simplices

    sphere = tvtk.SphereSource(radius=radius)
    points3d = tvtk.Glyph3D()
    points3d.set_source_connection(sphere.output_port)
    points3d.set_input_data(poly)

    m1 = tvtk.PolyDataMapper()
    m1.set_input_data(poly)
    a1 = tvtk.Actor(mapper=m1)
    a1.property.opacity = 0.3

    m2 = tvtk.PolyDataMapper()
    m2.set_input_data(poly)
    a2 = tvtk.Actor(mapper=m2)
    a2.property.representation = "wireframe"
    a2.property.line_width = 2.0
    a2.property.color = (1.0, 0, 0)

    m3 = tvtk.PolyDataMapper(input_connection=points3d.output_port)
    a3 = tvtk.Actor(mapper=m3)
    a3.property.color = (0.0, 1.0, 0.0)
    return [a1, a2, a3]
Пример #4
0
    def __init__(self, triangles, points, scalars=None, **traits):
        """
        Parameters
        ----------

        - triangles : array
          This contains a list of vertex indices forming the triangles.
        - points : array
          Contains the list of points referred to in the triangle list.
        - scalars : array (optional)
          Scalars to associate with the points.
        """
        super(FancyTriMesh, self).__init__(**traits)

        self.points = points
        self.pd = make_triangle_polydata(triangles, points, scalars)

        # Update the radii so the default is computed correctly.
        self._tube_radius_changed(self.tube_radius)
        self._sphere_radius_changed(self.sphere_radius)

        scalar_vis = self.scalar_visibility

        # Extract the edges and show the lines as tubes.
        self.extract_filter = tvtk.ExtractEdges(input=self.pd)
        extract_f = self.extract_filter
        self.tube_filter.trait_set(input=extract_f.output,
                                   radius=self.tube_radius)
        edge_mapper = tvtk.PolyDataMapper(input=self.tube_filter.output,
                                          lookup_table=self.lut,
                                          scalar_visibility=scalar_vis)
        edge_actor = _make_actor(mapper=edge_mapper)
        edge_actor.property.color = self.color

        # Create the spheres for the points.
        self.sphere_source.radius = self.sphere_radius
        spheres = tvtk.Glyph3D(scaling=0,
                               source=self.sphere_source.output,
                               input=extract_f.output)
        sphere_mapper = tvtk.PolyDataMapper(input=spheres.output,
                                            lookup_table=self.lut,
                                            scalar_visibility=scalar_vis)
        sphere_actor = _make_actor(mapper=sphere_mapper)
        sphere_actor.property.color = self.color

        if scalars is not None:
            rs = numpy.ravel(scalars)
            dr = min(rs), max(rs)
            self.lut.table_range = dr
            edge_mapper.scalar_range = dr
            sphere_mapper.scalar_range = dr

        self.actors.extend([edge_actor, sphere_actor])
Пример #5
0
def show_points(xyzs, colors=None, voxelize=False, res=0.05, polydata=None,
                vtkfiletag="visvtk", renderer=renderer):

    if polydata is None:
        polydata = tvtk.PolyData()
    #zMin = xyzs[:, 2].min()
    #zMax = xyzs[:, 2].max()
    #mapper.scalar_range = (zMin, zMax)
    #mapper.scalar_visibility = 1
    polydata.points = xyzs

    # http://www.vtk.org/Wiki/VTK/Tutorials/GeometryTopology
    # VTK strongly divides GEOMETRY from TOPOLOGY. What most users would
    # think of as "points" are actually "points + vertices" in VTK. The
    # geometry is ALWAYS simply a list of coordinates - the topology
    # represents the connectedness of these coordinates. If no topology at
    # all is specified, then, as far as VTK is aware, there is NOTHING to
    # show. If you want to see points, you must tell VTK that each point
    # is independent of the rest by creating a vertex (a 0-D topology) at
    # each point.
    verts = np.arange(0, xyzs.shape[0], 1, 'l') # point ids
    verts.shape = (xyzs.shape[0], 1) # make it a column vector
    polydata.verts = verts

    if voxelize:
        cubesrc = tvtk.CubeSource()
        cubesrc.x_length = res
        cubesrc.y_length = res
        cubesrc.z_length = res
        glyph3d = tvtk.Glyph3D()
        glyph3d.source = cubesrc.output
        glyph3d.input = polydata
        glyph3d.update()
        polydata = glyph3d.output
        normals = compute_polydata_normals(polydata)
        color_polydata_by_normals(polydata, normals)
    else:
        if colors is None:
            colors = np.abs(xyzs[:, 2]/ np.max(xyzs[:, 2]))

        polydata.point_data.scalars = colors
        polydata.point_data.scalars.name = 'scalars'

    return visualise(polydata, vtkfiletag=vtkfiletag, renderer=renderer)
Пример #6
0
    def test_glyph_pipeline(self):
        # Given
        rta = tvtk.RTAnalyticSource()
        cs = tvtk.ConeSource()
        g = tvtk.Glyph3D(input_connection=rta.output_port)
        g.set_source_connection(cs.output_port)
        m = tvtk.PolyDataMapper(input_connection=g.output_port)

        tg = self._make_tree_generator()

        # When/Then
        kids = tg.get_children(cs)
        self.assertEqual(len(kids), 0)
        kids = tg.get_children(rta)
        self.assertEqual(len(kids), 0)

        kids = tg.get_children(g)
        self.assertEqual(len(kids), 2)
        self.assertEqual(kids['input'], [rta, cs])

        kids = tg.get_children(m)
        self.assertEqual(len(kids), 3)
        self.assertEqual(kids['input'], [g])
        self.assertEqual(kids['lookup_table'], m.lookup_table)
Пример #7
0
# -*- coding: utf-8 -*-
from .example_cut_plane import read_data
import numpy as np
from tvtk.api import tvtk
from scpy2.tvtk.tvtkhelp import ivtk_scene, event_loop, make_outline

plot3d = read_data()
grid = plot3d.output.get_block(0)

mask = tvtk.MaskPoints(random_mode=True, on_ratio=50)
mask.set_input_data(grid)

arrow_source = tvtk.ArrowSource()
arrows = tvtk.Glyph3D(input_connection=mask.output_port,
                      scale_factor=2 /
                      np.max(grid.point_data.scalars.to_array()))
arrows.set_source_connection(arrow_source.output_port)

arrows_mapper = tvtk.PolyDataMapper(scalar_range=grid.point_data.scalars.range,
                                    input_connection=arrows.output_port)
arrows_actor = tvtk.Actor(mapper=arrows_mapper)

center = grid.center
sphere = tvtk.SphereSource(center=(2, center[1], center[2]),
                           radius=2,
                           phi_resolution=6,
                           theta_resolution=6)
sphere_mapper = tvtk.PolyDataMapper(input_connection=sphere.output_port)

sphere_actor = tvtk.Actor(mapper=sphere_mapper)
sphere_actor.property.set(representation="wireframe", color=(0, 0, 0))
Пример #8
0
# point_data.t_coords = <array>.
#
# In this case CubeSource already defines texture coords for us (as of
# VTK-4.4).
cs = tvtk.CubeSource(x_length=2, y_length=1.0, z_length=0.5)

# Create input for the glyph -- the sources are placed at these input
# points.
pts = [[1, 1, 1], [0, 0, 0], [-1, -1, -1]]
pd = tvtk.PolyData(points=pts, polys=[[0], [1], [2]])
# Orientation/scaling is as per the vector attribute.
vecs = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
pd.point_data.vectors = vecs

# Create the glyph3d and set up the pipeline.
g = tvtk.Glyph3D(scale_mode='data_scaling_off', vector_mode='use_vector')
configure_input_data(g, pd)

# Note that VTK's vtkGlyph.SetSource is special because it has two
# call signatures: SetSource(src) and SetSource(int N, src) (which
# sets the N'th source).  In tvtk it is represented as both a property
# and as a method.  Using the `source` property will work fine if all
# you want is the first `source`.  OTOH if you want the N'th `source`
# use get_source(N).
# g.source = cs.output
configure_source_data(g, cs.output)
cs.update()
g.update()

m = tvtk.PolyDataMapper()
configure_input_data(m, g.output)
from tvtk.api import tvtk
from CStvtkfunc import ivtk_scene, event_loop

#读入PLot3D数据
plot3d = tvtk.MultiBlockPLOT3DReader(xyz_file_name="Element\combxyz.bin",
                                     q_file_name="Element\combq.bin",
                                     scalar_function_number=100,
                                     vector_function_number=200)
plot3d.update()
grid = plot3d.output.get_block(0)

#对数据集中的数据进行随机选取,每50个点选择一个点
mask = tvtk.MaskPoints(random_mode=True, on_ratio=50)
mask.set_input_data(grid)
#创建表示箭头的PolyData数据集
glyph_source = tvtk.ConeSource()
#在Mask采样后的PolyData数据集每个点上放置一个箭头
#箭头的方向、长度和颜色由于点对应的矢量和标量数据决定
glyph = tvtk.Glyph3D(input_connection=mask.output_port, scale_factor=2)
glyph.set_source_connection(glyph_source.output_port)
m = tvtk.PolyDataMapper(scalar_range=grid.point_data.scalars.range,
                        input_connection=glyph.output_port)
a = tvtk.Actor(mapper=m)

#窗口绘制
win = ivtk_scene(a)
win.scene.isometric_view()
event_loop()
Пример #10
0
    def vtk_actors(self):
        if (self.actors is None):
            self.actors = []
            points = _getfem_to_tvtk_points(self.sl.pts())
            (triangles, cv2tr) = self.sl.splxs(2)
            triangles = numpy.array(triangles.transpose(), 'I')
            data = tvtk.PolyData(points=points, polys=triangles)
            if self.scalar_data is not None:
                data.point_data.scalars = numpy.array(self.scalar_data)
            if self.vector_data is not None:
                data.point_data.vectors = numpy.array(self.vector_data)
            if self.glyph_name is not None:
                mask = tvtk.MaskPoints()
                mask.maximum_number_of_points = self.glyph_nb_pts
                mask.random_mode = True
                mask.input = data

                if self.glyph_name == 'default':
                    if self.vector_data is not None:
                        self.glyph_name = 'arrow'
                    else:
                        self.glyph_name = 'ball'

                glyph = tvtk.Glyph3D()
                glyph.scale_mode = 'scale_by_vector'
                glyph.color_mode = 'color_by_scalar'
                #glyph.scale_mode = 'data_scaling_off'
                glyph.vector_mode = 'use_vector'  # or 'use_normal'
                glyph.input = mask.output
                if self.glyph_name == 'arrow':
                    glyph.source = tvtk.ArrowSource().output
                elif self.glyph_name == 'ball':
                    glyph.source = tvtk.SphereSource().output
                elif self.glyph_name == 'cone':
                    glyph.source = tvtk.ConeSource().output
                elif self.glyph_name == 'cylinder':
                    glyph.source = tvtk.CylinderSource().output
                elif self.glyph_name == 'cube':
                    glyph.source = tvtk.CubeSource().output
                else:
                    raise Exception("Unknown glyph name..")
                #glyph.scaling = 1
                #glyph.scale_factor = self.glyph_scale_factor
                data = glyph.output

            if self.show_faces:
                ##                if self.deform is not None:
                ##                    data.point_data.vectors = array(numarray.transpose(self.deform))
                ##                    warper = tvtk.WarpVector(input=data)
                ##                    data = warper.output
                ##                lut = tvtk.LookupTable()
                ##                lut.hue_range = 0.667,0
                ##                c=gf_colormap('tripod')
                ##                lut.number_of_table_values=c.shape[0]
                ##                for i in range(0,c.shape[0]):
                ##                    lut.set_table_value(i,c[i,0],c[i,1],c[i,2],1)

                self.mapper = tvtk.PolyDataMapper(input=data)
                self.mapper.scalar_range = self.scalar_data_range
                self.mapper.scalar_visibility = True
                # Create mesh actor for display
                self.actors += [tvtk.Actor(mapper=self.mapper)]
            if self.show_edges:
                (Pe, E1, E2) = self.sl.edges()
                if Pe.size:
                    E = numpy.array(
                        numpy.concatenate((E1.transpose(), E2.transpose()),
                                          axis=0), 'I')
                    edges = tvtk.PolyData(points=_getfem_to_tvtk_points(Pe),
                                          polys=E)
                    mapper_edges = tvtk.PolyDataMapper(input=edges)
                    actor_edges = tvtk.Actor(mapper=mapper_edges)
                    actor_edges.property.representation = 'wireframe'
                    #actor_edges.property.configure_traits()
                    actor_edges.property.color = self.edges_color
                    actor_edges.property.line_width = self.edges_width
                    actor_edges.property.ambient = 0.5
                    self.actors += [actor_edges]
            if self.sl.nbsplxs(1):
                # plot tubes
                (seg, cv2seg) = self.sl.splxs(1)
                seg = numpy.array(seg.transpose(), 'I')
                data = tvtk.Axes(origin=(0, 0, 0),
                                 scale_factor=0.5,
                                 symmetric=1)
                data = tvtk.PolyData(points=points, lines=seg)
                tube = tvtk.TubeFilter(radius=0.4,
                                       number_of_sides=10,
                                       vary_radius='vary_radius_off',
                                       input=data)
                mapper = tvtk.PolyDataMapper(input=tube.output)
                actor_tubes = tvtk.Actor(mapper=mapper)
                #actor_tubes.property.representation = 'wireframe'
                actor_tubes.property.color = self.tube_color
                #actor_tubes.property.line_width = 8
                #actor_tubes.property.ambient = 0.5

                self.actors += [actor_tubes]

            if self.use_scalar_bar:
                self.scalar_bar = tvtk.ScalarBarActor(
                    title=self.scalar_data_name,
                    orientation='horizontal',
                    width=0.8,
                    height=0.07)
                self.scalar_bar.position_coordinate.coordinate_system = 'normalized_viewport'
                self.scalar_bar.position_coordinate.value = 0.1, 0.01, 0.0
                self.actors += [self.scalar_bar]

            if (self.lookup_table is not None):
                self.set_colormap(self.lookup_table)

        return self.actors
Пример #11
0
def main(*anim_files):
    fig = mlab.figure(bgcolor=(1, 1, 1))
    all_verts = []
    pds = []
    actors = []
    datasets = []
    glyph_pds = []
    glyph_actors = []

    colors = cycle([(1, 1, 1), (1, 0, 0), (0, 1, 0), (0, 0, 1)])

    for i, (f, color) in enumerate(zip(anim_files, colors)):
        data = h5py.File(f, 'r')
        verts = data['verts'].value
        tris = data['tris'].value
        print f
        print "  Vertices: ", verts.shape
        print "  Triangles: ", tris.shape
        datasets.append(data)

        # setup mesh
        pd = tvtk.PolyData(points=verts[0], polys=tris)
        normals = tvtk.PolyDataNormals(compute_point_normals=True,
                                       splitting=False)
        configure_input_data(normals, pd)
        actor = tvtk.Actor(mapper=tvtk.PolyDataMapper())
        configure_input(actor.mapper, normals)
        actor.mapper.immediate_mode_rendering = True
        actor.visibility = False
        fig.scene.add_actor(actor)

        actors.append(actor)
        all_verts.append(verts)
        pds.append(normals)

        # setup arrows
        arrow = tvtk.ArrowSource(tip_length=0.25,
                                 shaft_radius=0.03,
                                 shaft_resolution=32,
                                 tip_resolution=4)
        glyph_pd = tvtk.PolyData()
        glyph = tvtk.Glyph3D()
        scale_factor = verts.reshape(-1, 3).ptp(0).max() * 0.1
        glyph.set(scale_factor=scale_factor,
                  scale_mode='scale_by_vector',
                  color_mode='color_by_scalar')
        configure_input_data(glyph, glyph_pd)
        configure_source_data(glyph, arrow)
        glyph_actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(),
                                 visibility=False)
        configure_input(glyph_actor.mapper, glyph)
        fig.scene.add_actor(glyph_actor)

        glyph_actors.append(glyph_actor)
        glyph_pds.append(glyph_pd)

    actors[0].visibility = True
    glyph_actors[0].visibility = True

    class Viewer(HasTraits):
        animator = Instance(Animator)
        visible = Enum(*range(len(pds)))
        normals = Bool(True)
        export_off = Button
        restpose = Bool(True)
        show_scalars = Bool(True)
        show_bones = Bool(True)
        show_actual_bone_centers = Bool(False)

        def _export_off_changed(self):
            fd = FileDialog(title='Export OFF',
                            action='save as',
                            wildcard='OFF Meshes|*.off')
            if fd.open() == OK:
                v = all_verts[self.visible][self.animator.current_frame]
                save_off(fd.path, v, tris)

        @on_trait_change('visible, normals, restpose, show_scalars, show_bones'
                         )
        def _changed(self):
            for a in actors + glyph_actors:
                a.visibility = False
            for d in pds:
                d.compute_point_normals = self.normals
            actors[self.visible].visibility = True
            actors[self.visible].mapper.scalar_visibility = self.show_scalars
            glyph_actors[self.visible].visibility = self.show_bones
            #for i, visible in enumerate(self.visibilities):
            #    actors[i].visibility = visible
            self.animator.render = True

        def show_frame(self, frame):
            v = all_verts[self.visible][frame]
            dataset = datasets[self.visible]
            if not self.restpose:
                rbms_frame = dataset['rbms'][frame]
                v = v * dataset.attrs['scale'] + dataset.attrs['verts_mean']
                v = blend_skinning(v,
                                   dataset['segments'].value,
                                   rbms_frame,
                                   method=dataset.attrs['skinning_method'])
            pds[self.visible].input.points = v
            if 'scalar' in dataset and self.show_scalars:
                if dataset['scalar'].shape[0] == all_verts[
                        self.visible].shape[0]:
                    scalar = dataset['scalar'][frame]
                else:
                    scalar = dataset['scalar'].value
                pds[self.visible].input.point_data.scalars = scalar
            else:
                pds[self.visible].input.point_data.scalars = None
            if 'bone_transformations' in dataset and self.show_bones:
                W = dataset['bone_blendweights'].value
                T = dataset['bone_transformations'].value
                gpd = glyph_pds[self.visible]
                if self.show_actual_bone_centers:
                    verts0 = dataset['verts_restpose'].value
                    mean_bonepoint = verts0[W.argmax(axis=1)]  # - T[0,:,:,3]
                    #mean_bonepoint = np.array([
                    #    np.average(verts0, weights=w, axis=0) for w in W])
                    #gpd.points = np.repeat(mean_bonepoint + T[frame,:,:,3], 3, 0)
                    #print np.tile(mean_bonepoint + T[frame,:,:,3], 3).reshape((-1, 3))
                    #gpd.points = np.tile(mean_bonepoint + T[frame,:,:,3], 3).reshape((-1, 3))
                    pts = []
                    for i in xrange(T.shape[1]):
                        #offset = V.transform(V.hom4(mean_bonepoint[i]), T[frame,i,:,:])
                        offset = np.dot(T[frame, i], V.hom4(mean_bonepoint[i]))
                        pts += [offset] * 3
                    gpd.points = np.array(pts)

                else:
                    bonepoint = np.array(
                        [np.average(v, weights=w, axis=0) for w in W])
                    gpd.points = np.repeat(bonepoint, 3, 0)
                gpd.point_data.vectors = \
                        np.array(map(np.linalg.inv, T[frame,:,:,:3])).reshape(-1, 3)
                # color vertices
                vert_colors = vertex_weights_to_colors(W)
                pds[self.visible].input.point_data.scalars = vert_colors
                bone_colors = hue_linspace_colors(W.shape[0],
                                                  sat=0.8,
                                                  light=0.7)
                gpd.point_data.scalars = np.repeat(bone_colors, 3, 0)

        view = View(
            Group(
                Group(Item('visible'),
                      Item('export_off'),
                      Item('normals'),
                      Item('restpose'),
                      Item('show_scalars'),
                      Item('show_bones'),
                      Item('show_actual_bone_centers'),
                      label="Viewer"),
                Item('animator', style='custom', show_label=False),
            ))

    app = Viewer()
    animator = Animator(verts.shape[0], app.show_frame)
    app.animator = animator
    app.edit_traits()
    mlab.show()