Exemple #1
0
def make_test_table(lut=False):
    from ctf import ColorTransferFunction, PiecewiseFunction
    if lut:
        table = tvtk.LookupTable()
        table.table_range = (255, 355)
        return table, None, None
    else:
        table = tvtk.VolumeProperty()
        ctf = ColorTransferFunction()
        mins, maxs = 255, 355
        ds = (maxs-mins)/4.0
        try:
            ctf.range = (mins, maxs)
        except Exception:
            # VTK versions < 5.2 don't seem to need this.
            pass
        ctf.add_rgb_point(mins,      0.00, 0.0, 1.00)
        ctf.add_rgb_point(mins+ds,   0.25, 0.5, 0.75)
        ctf.add_rgb_point(mins+2*ds, 0.50, 1.0, 0.50)
        ctf.add_rgb_point(mins+3*ds, 0.75, 0.5, 0.25)
        ctf.add_rgb_point(maxs,      1.00, 0.0, 0.00)
        otf = PiecewiseFunction()
        otf.add_point(255, 0.0)
        otf.add_point(355, 0.2)
        table.set_color(ctf)
        table.set_scalar_opacity(otf)
        return table, ctf, otf
Exemple #2
0
def show(d):
    l = tvtk.LookupTable(table_range=(0, 1))
    m = tvtk.PolyDataMapper(input=d.output,
                            scalar_visibility=True,
                            scalar_mode="use_cell_data")
    p = tvtk.Property(representation="s")
    a = tvtk.Actor(mapper=m, property=p)

    ren = tvtk.Renderer(background=(.1, .2, .4))
    ren.add_actor(a)
    rw = tvtk.RenderWindow(size=(600, 600))
    rw.add_renderer(ren)
    rwi = tvtk.RenderWindowInteractor(render_window=rw)
    rwi.initialize()
    rwi.start()
Exemple #3
0
 def set_colormap(self, c):
     if isinstance(c, str):
         lut = tvtk.LookupTable()
         c = gf_colormap(c)
         lut.number_of_table_values = c.shape[0]
         for i in range(c.shape[0]):
             lut.set_table_value(i, c[i, 0], c[i, 1], c[i, 2], 1)
     elif isinstance(c, tvtk.LookupTable):
         lut = c
     else:
         raise Exception("expected a string or a tvtk.LookupTable")
     self.lookup_table = lut
     if (self.mapper is not None):
         self.mapper.lookup_table = self.lookup_table
     if (self.scalar_bar is not None):
         self.scalar_bar.lookup_table = self.lookup_table
 def _setup_scene(self):
     # scalar bar for strain
     lut_strain = tvtk.LookupTable(hue_range=(0.66, 0.0))
     lut_strain.build()
     self._scalar_bar_strain = tvtk.ScalarBarActor(
         lookup_table=lut_strain,
         orientation='horizontal',
         text_position='succeed_scalar_bar',
         maximum_number_of_colors=256,
         number_of_labels=9,
         position=(0.1, 0.01),
         position2=(0.8, 0.08),
         title='element strain (%)',
         visibility=False)
     self.scene.add_actor(self._scalar_bar_strain)
     # scalar bar for stress
     # lookup table from green to yellow, and last 2 values dark red
     lut_stress = tvtk.LookupTable(hue_range=(0.33, 0.1),
                                   number_of_table_values=256)
     lut_stress.build()
     lut_stress.set_table_value(254, (1.0, 0.4, 0.0, 1.0))
     lut_stress.set_table_value(255, (1.0, 0.0, 0.0, 1.0))
     self._scalar_bar_stress = tvtk.ScalarBarActor(
         lookup_table=lut_stress,
         orientation='horizontal',
         text_position='succeed_scalar_bar',
         maximum_number_of_colors=256,
         number_of_labels=9,
         position=(0.1, 0.01),
         position2=(0.8, 0.08),
         title='element stress',
         visibility=False)
     self.scene.add_actor(self._scalar_bar_stress)
     # setup elements visualization
     self._elements_polydata = tvtk.PolyData()
     self._tubes = tvtk.TubeFilter(
         input=self._elements_polydata,
         number_of_sides=6,
         vary_radius='vary_radius_by_absolute_scalar',
         radius_factor=1.5)
     mapper = tvtk.PolyDataMapper(input=self._tubes.output,
                                  lookup_table=lut_strain,
                                  interpolate_scalars_before_mapping=True,
                                  scalar_mode='use_cell_data')
     self._elements_actor = tvtk.Actor(mapper=mapper)
     self.scene.add_actor(self._elements_actor)
     # show elements in deformed state as wireframe
     self._deformed_elements_polydata = tvtk.PolyData()
     self._deformed_elements_actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(
         input=self._deformed_elements_polydata))
     self._deformed_elements_actor.property.set(opacity=0.2,
                                                representation='wireframe')
     self.scene.add_actor(self._deformed_elements_actor)
     # highlight one element via a ribbon outline
     self._hl_element_ribbons = tvtk.RibbonFilter(input=tvtk.PolyData(),
                                                  use_default_normal=True,
                                                  width=1.0)
     self._hl_element_actor = tvtk.Actor(
         mapper=tvtk.PolyDataMapper(input=self._hl_element_ribbons.output),
         visibility=False)
     self._hl_element_actor.property.set(ambient=1,
                                         ambient_color=(1, 1, 1),
                                         diffuse=0)
     self.scene.add_actor(self._hl_element_actor)
     # cross sectional radius labels
     self._elements_label_polydata = tvtk.PolyData()
     self._label_cellcenters = tvtk.CellCenters(
         input=self._elements_label_polydata)
     self._label_visps = tvtk.SelectVisiblePoints(
         renderer=self.scene.renderer,
         input=self._label_cellcenters.output,
         tolerance=10000)
     self._label_actor = tvtk.Actor2D(mapper=tvtk.Dynamic2DLabelMapper(
         input=self._label_visps.output, label_mode='label_scalars'))
     self._label_actor.mapper.label_text_property.set(
         bold=True, italic=False, justification='centered', font_size=14)
     #self.scene.add_actor(self._label_actor)
     # force glyphs (use arrows for that)
     self._force_glyphs = tvtk.Glyph3D(scale_mode='scale_by_vector',
                                       vector_mode='use_vector',
                                       color_mode='color_by_vector',
                                       scale_factor=1.)
     self._force_glyphs.set_source(
         0,
         tvtk.ArrowSource(shaft_radius=0.04,
                          tip_resolution=8,
                          tip_radius=0.2).output)
     self._force_polydata = tvtk.PolyData()
     self._force_glyphs.set_input(0, self._force_polydata)
     self._force_actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(
         input=self._force_glyphs.output, scalar_range=(0, 10)))
     self._force_actor.mapper.lookup_table.hue_range = (0.33, 0.0)
     self.scene.add_actor(self._force_actor)
     # current status display
     self._text_actor = tvtk.TextActor(position=(0.5, 0.95))
     self._text_actor.position_coordinate.coordinate_system = 'normalized_display'
     self._text_actor.text_property.set(font_size=14,
                                        justification='center')
     self.scene.add_actor(self._text_actor)
     # a nice gradient background
     self.scene.renderer.set(background2=(0.28, 0.28, 0.28),
                             background=(0.01, 0.01, 0.02),
                             gradient_background=True)
     # setup events
     self.interaction_mode = 'select'
     self.scene.interactor.add_observer('MouseMoveEvent', self._mouse_move)
     self.scene.interactor.add_observer('LeftButtonPressEvent',
                                        self._mouse_press)
     self.scene.renderer.add_observer('StartEvent', self._before_render)
     self._on_init = True
     self._reset_zoom_needed = True
Exemple #5
0
    def save(self, file_name):
        """Save control point set into a new file FileName. It is not checked
        whether the file already exists. Further writes out a VTK .lut file
        and a .jpg file showing the gradients."""

        # Ensure that if the input file name had one of the extensions
        # we'll be writing out ourselves, it gets stripped out first.
        path_base, ext = splitext(file_name)
        #print(file_name)
        if ext.lower() in ['.lut', '.jpg', '.jpeg', '.grad']:
            ext = ''
        file_name = path_base + ext

        # Create the three names for the files we'll be actually
        # writing out.
        file_name_grad = file_name + '.grad'
        file_name_lut = file_name + '.lut'
        file_name_jpg = file_name + '.jpg'

        # write control points set.
        file = open(file_name_grad, "w")
        file.write("V 2.0 Color Gradient File\n")
        file.write("ScalingFunction: %s\n" % (self.scaling_function_string))
        file.write("ScalingParameter: %s\n" %
                   (self.scaling_function_parameter))
        file.write("ControlPoints: (pos fixed bindings h s v a)\n")
        for control_point in self.control_points:
            file.write( "  %s %s %s %s %s %s %s\n" % ( \
                control_point.pos, control_point.fixed, control_point.active_channels,
                control_point.color.get_hsva()[0], control_point.color.get_hsva()[1],
                control_point.color.get_hsva()[2], control_point.color.get_hsva()[3] ) )
        file.close()

        # write vtk lookup table. Unfortunatelly these objects don't seem to
        # have any built in and exposed means of loading or saving them, so
        # we build the vtk file directly
        vtk_table = tvtk.LookupTable()
        self.store_to_vtk_lookup_table(vtk_table)
        file = open(file_name_lut, "w")
        num_colors = vtk_table.number_of_table_values
        file.write("LOOKUP_TABLE UnnamedTable %s\n" % (num_colors))
        for idx in range(num_colors):
            entry = vtk_table.get_table_value(idx)
            file.write("%.4f %.4f %.4f %.4f\n" %
                       (entry[0], entry[1], entry[2], entry[3]))
        file.close()

        # if the python image library is aviable, also generate a small .jpg
        # file showing how the gradient looks. Based on code from Arnd Baecker.
        try:
            import Image
        except ImportError:
            pass  # we're ready otherwise. no jpg output tho.
        else:
            Ny = 64  # vertical size of the jpeg
            im = Image.new("RGBA", (num_colors, Ny))
            for nx in range(num_colors):
                (r, g, b, a) = vtk_table.get_table_value(nx)
                for ny in range(Ny):
                    im.putpixel((nx, ny), (int(255 * r), int(
                        255 * g), int(255 * b), int(255 * a)))
            im.save(file_name_jpg, "JPEG")
Exemple #6
0
def read_data():
    # 读入数据
    plot3d = tvtk.PLOT3DReader(xyz_file_name=vtk_data("combxyz.bin"),
                               q_file_name=vtk_data("combq.bin"),
                               scalar_function_number=100,
                               vector_function_number=200)
    plot3d.update()
    return plot3d


if __name__ == "__main__":
    plot3d = read_data()

    # 创建颜色映射表
    lut = tvtk.LookupTable()
    import pylab as pl
    lut.table = pl.cm.cool(np.arange(0, 256)) * 255

    # 显示StructuredGrid中的一个网格面
    plane = tvtk.StructuredGridGeometryFilter(input=plot3d.output,
                                              extent=(0, 100, 0, 100, 6, 6))
    plane_mapper = tvtk.PolyDataMapper(lookup_table=lut, input=plane.output)
    plane_mapper.scalar_range = plot3d.output.scalar_range
    plane_actor = tvtk.Actor(mapper=plane_mapper)

    # 做一个平面切面
    cut_plane = tvtk.Plane(origin=plot3d.output.center,
                           normal=(-0.287, 0, 0.9579))
    cut = tvtk.Cutter(input=plot3d.output, cut_function=cut_plane)
    cut_mapper = tvtk.PolyDataMapper(input=cut.output, lookup_table=lut)