def __init__(self, x, y, z, warp=1, scale=[1.0, 1.0, 1.0], f_args=(), f_kwargs=None, **traits): super(SurfRegularC, self).__init__(**traits) if f_kwargs is None: f_kwargs = {} data, actor = make_surf_actor(x, y, z, warp, scale, *f_args, **f_kwargs) mapper = actor.mapper mapper.lookup_table = self.lut self.lut.table_range = mapper.scalar_range self.data = data dr = data.point_data.scalars.range cf = self.contour_filter configure_input_data(cf, data) cf.generate_values(self.number_of_contours, dr[0], dr[1]) mapper = tvtk.PolyDataMapper(input=cf.output, lookup_table=self.lut) cont_actor = _make_actor(mapper=mapper) self.actors.extend([actor, cont_actor])
def _widget_changed(self, value): # If we are being unpickled do nothing. if self._unpickling: return if value not in self.widget_list: classes = [o.__class__ for o in self.widget_list] vc = value.__class__ self._connect(value) if vc in classes: self.widget_list[classes.index(vc)] = value else: self.widget_list.append(value) recorder = self.recorder if recorder is not None: idx = self.widget_list.index(value) name = recorder.get_script_id(self) lhs = '%s.widget'%name rhs = '%s.widget_list[%d]'%(name, idx) recorder.record('%s = %s'%(lhs, rhs)) if len(self.inputs) > 0: configure_input_data(value, self.inputs[0].outputs[0]) value.place_widget() value.on_trait_change(self.render) self.widgets = [value]
def __init__(self, points, **traits): super(MLabBase, self).__init__(**traits) assert len(points[0]) == 3, "The points must be 3D" self.points = points np = len(points) - 1 lines = numpy.zeros((np, 2), 'l') lines[:, 0] = numpy.arange(0, np - 0.5, 1, 'l') lines[:, 1] = numpy.arange(1, np + 0.5, 1, 'l') pd = tvtk.PolyData(points=points, lines=lines) self.poly_data = pd mapper = tvtk.PolyDataMapper() self.mapper = mapper tf = self.tube_filter tf.radius = self.radius if self.use_tubes: configure_input_data(tf, pd) configure_input_data(mapper, tf.output) a = _make_actor(mapper=mapper) a.property.color = self.color self.actors.append(a)
def _widget_changed(self, value): # If we are being unpickled do nothing. if self._unpickling: return if value not in self.widget_list: classes = [o.__class__ for o in self.widget_list] vc = value.__class__ self._connect(value) if vc in classes: self.widget_list[classes.index(vc)] = value else: self.widget_list.append(value) recorder = self.recorder if recorder is not None: idx = self.widget_list.index(value) name = recorder.get_script_id(self) lhs = '%s.widget' % name rhs = '%s.widget_list[%d]' % (name, idx) recorder.record('%s = %s' % (lhs, rhs)) if len(self.inputs) > 0: configure_input_data(value, self.inputs[0].outputs[0]) value.place_widget() value.on_trait_change(self.render) self.widgets = [value]
def _configure(self): self.primitive = self._get_primitive() self.mapper = tvtk.PolyDataMapper() configure_input_data(self.mapper, self.primitive.output) self.primitive.update() self._set_actor()
def __init__(self): #-------------using the little girl model part =tvtk.OBJReader(file_name = ".\\Resources\\little_girl_matlab_smoothed.obj") part_mapper = tvtk.PolyDataMapper() configure_input_data(part_mapper, part.output) #use the input = part.output will get a error #-------------define the color p = tvtk.Property(opacity=1, color=(1, 0.8, 0.7), ambient = 0.06, diffuse = 0.75) # softer self.part_actor = tvtk.Actor( mapper = part_mapper, property = p ) part.update() #-------- timer to dispalay a flash point self.timer_nav = QtCore.QTimer() self.timer_nav_hide = QtCore.QTimer() #-- self.callback() #---- the points to show self.point_to_obtain = None self.obtain_turn = 1 self.sub_1020 = None self.sub_GheadR = None self.line_al_cz_ar = None self.line_nz_cz_iz = None self.his_ref_mesh = None self.his_plate_mesh = None self.sub_1020_mesh = None self.navigation_target_mesh = None
def __init__(self, x, y, z, scalars, **traits): """ Parameters ---------- - x : array A list of x coordinate values formed using numpy.mgrid. - y : array A list of y coordinate values formed using numpy.mgrid. - z : array A list of z coordinate values formed using numpy.mgrid. - scalars : array Scalars to associate with the points. """ super(Contour3, self).__init__(**traits) triangles, points = make_triangles_points(x, y, z, scalars) self.pd = make_triangle_polydata(triangles, points, scalars) dr = self.pd.point_data.scalars.range self.lut.table_range = dr cf = self.contour_filter configure_input_data(cf, self.pd) cf.generate_values(self.number_of_contours, dr[0], dr[1]) mapper = tvtk.PolyDataMapper(input=cf.output, lookup_table=self.lut, scalar_range=dr) cont_actor = _make_actor(mapper=mapper) self.actors.append(cont_actor)
def __init__(self, points, vectors=None, scalars=None, **traits): super(Glyphs, self).__init__(**traits) if vectors is not None: assert len(points) == len(vectors) if scalars is not None: assert len(points) == len(scalars) self.points = points self.vectors = vectors self.scalars = scalars polys = numpy.arange(0, len(points), 1, 'l') polys = numpy.reshape(polys, (len(points), 1)) pd = tvtk.PolyData(points=points, polys=polys) if self.vectors is not None: pd.point_data.vectors = vectors pd.point_data.vectors.name = 'vectors' if self.scalars is not None: pd.point_data.scalars = scalars pd.point_data.scalars.name = 'scalars' self.poly_data = pd configure_input_data(self.glyph, pd) if self.glyph_source: self.glyph.source = self.glyph_source.output mapper = tvtk.PolyDataMapper(input=self.glyph.output) actor = _make_actor(mapper=mapper) actor.property.color = self.color self.actors.append(actor)
def resample_data(netcdfs, img_size, t, variables): """ Resample data for timestep, variables in netcdf to given image size """ polydatas_by_name = {} mbd = tvtk.MultiBlockDataSet() mbd.number_of_blocks = len(netcdfs) masks_by_name = {} for i, f in enumerate(netcdfs): ds = netCDF4.Dataset(f) grid = gridded.pyugrid.ugrid.UGrid.from_nc_dataset(ds) polydata, mask = grid2poly(grid) mbd.set_block(i, polydata) masks_by_name[f.name] = mask polydatas_by_name[f.name] = polydata ds.close() mbm = tvtk.MultiBlockMergeFilter() configure_input_data(mbm, mbd) resample = setup_pipeline(mbm, width=img_size[0], height=img_size[1]) for path in netcdfs: polydata = polydatas_by_name[path.name] mask = masks_by_name[path.name] update_data(path, polydata, mask, variables, t) resample.update() mbm.update() return resample
def visualize_point_correspondences(source_pts, target_pts, ij_corr=None, scalars=None, point_size=10): if ij_corr is None: if source_pts.shape != target_pts.shape: raise ValueError( "must have same amount of source and target points, or specify ij_corr parameter" ) ij_corr = np.column_stack( (np.arange(len(source_pts)), np.arange(len(target_pts)))) p = source_pts[ij_corr[:, 0]] p2 = target_pts[ij_corr[:, 1]] pd = tvtk.PolyData(points=p, verts=np.r_[:len(p)].reshape((-1, 1))) actor = tvtk.Actor(mapper=tvtk.PolyDataMapper()) configure_input_data(actor.mapper, pd) actor.property.point_size = point_size if scalars is not None: pd.point_data.scalars = scalars actor.mapper.scalar_range = scalars.min(), scalars.max() mlab.gcf().scene.add_actor(actor) class Ctrl(ta.HasTraits): alpha = ta.Range(0., 1.) def _alpha_changed(self): pd.points = p + self.alpha * (p2 - p) mlab.gcf().scene.render() Ctrl().configure_traits()
def move_seeds(seeds, vfield, dt): """ Move a list of seeds based on a velocity field. .. warning:: WARNING: THIS IS HARD CODED FOR GRID SIZE! Parameters ---------- seeds: tvtk.PolyData Old seed points vfield: mayavi.sources.array_source.ArraySource object The velocity field dt: float The time step betweent the current and the previous step. Returns ------- seeds_arr: ndarray New Seed points """ v_seed = tvtk.ProbeFilter() tvtk_common.configure_input_data(v_seed, seeds) tvtk_common.configure_source_data(v_seed, vfield) v_seed.update() int_vels = np.array(v_seed.output.point_data.vectors)[:,:2]/(15.625*1e3) seed_arr = np.array(seeds.points) seed_arr[:,:2] += int_vels * dt #seeds.points = seed_arr return seed_arr
def __init__(self, renwin, **traits): super(Picker, self).__init__(**traits) self.renwin = renwin self.pointpicker = tvtk.PointPicker() self.cellpicker = tvtk.CellPicker() self.worldpicker = tvtk.WorldPointPicker() self.probe_data = tvtk.PolyData() self._tolerance_changed(self.tolerance) # Use a set of axis to show the picked point. self.p_source = tvtk.Axes() self.p_mapper = tvtk.PolyDataMapper() self.p_actor = tvtk.Actor () self.p_source.symmetric = 1 self.p_actor.pickable = 0 self.p_actor.visibility = 0 prop = self.p_actor.property prop.line_width = 2 prop.ambient = 1.0 prop.diffuse = 0.0 configure_input_data(self.p_mapper, self.p_source.output) self.p_actor.mapper = self.p_mapper self.probe_data.points = [[0.0, 0.0, 0.0]] self.ui = None
def main(hdf5_animation_file): weights = None with h5py.File(hdf5_animation_file, 'r') as f: verts = f['verts'].value tris = f['tris'].value if 'weights' in f: weights = f['weights'].value pd = tvtk.PolyData(points=verts[0], polys=tris) normals = tvtk.PolyDataNormals(splitting=False) configure_input_data(normals, pd) actor = tvtk.Actor(mapper=tvtk.PolyDataMapper()) configure_input(actor.mapper, normals) actor.property.set(edge_color=(0.5, 0.5, 0.5), ambient=0.0, specular=0.15, specular_power=128., shading=True, diffuse=0.8) fig = mlab.figure(bgcolor=(1,1,1)) fig.scene.add_actor(actor) @mlab.animate(delay=40, ui=False) def animation(): for i in count(): if weights is not None: w_str = ",".join(["%0.2f"] * weights.shape[1]) print ("Frame %d Weights = " + w_str) % tuple([i] + weights[i].tolist()) frame = i % len(verts) pd.points = verts[frame] fig.scene.render() yield a = animation() fig.scene.z_minus_view() mlab.show()
def __init__(self, renwin, **traits): super(Picker, self).__init__(**traits) self.renwin = renwin self.pointpicker = tvtk.PointPicker() self.cellpicker = tvtk.CellPicker() self.worldpicker = tvtk.WorldPointPicker() self.probe_data = tvtk.PolyData() self._tolerance_changed(self.tolerance) # Use a set of axis to show the picked point. self.p_source = tvtk.Axes() self.p_mapper = tvtk.PolyDataMapper() self.p_actor = tvtk.Actor() self.p_source.symmetric = 1 self.p_actor.pickable = 0 self.p_actor.visibility = 0 prop = self.p_actor.property prop.line_width = 2 prop.ambient = 1.0 prop.diffuse = 0.0 configure_input_data(self.p_mapper, self.p_source.output) self.p_actor.mapper = self.p_mapper self.probe_data.points = [[0.0, 0.0, 0.0]] self.ui = None
def convert_to_poly_data(data): """Given a VTK dataset object, this returns the data as PolyData. This is primarily used to convert the data suitably for filters that only work for PolyData. """ if data.is_a('vtkPolyData'): return data conv = {'vtkStructuredPoints': tvtk.ImageDataGeometryFilter, 'vtkImageData': tvtk.ImageDataGeometryFilter, 'vtkRectilinearGrid': tvtk.RectilinearGridGeometryFilter, 'vtkStructuredGrid': tvtk.StructuredGridGeometryFilter, 'vtkUnstructuredGrid':tvtk.GeometryFilter} fil = None for name, fil_class in conv.items(): if data.is_a(name): fil = fil_class() break if fil is not None: configure_input_data(fil, data) fil.update() return fil.output else: error('Given object is not a VTK dataset: %s'%data.__class__.__name__)
def write_dataset_to_string(data): """Given a dataset, convert the dataset to an ASCII string that can be stored for persistence. """ w = tvtk.DataSetWriter(write_to_output_string=1) warn = w.global_warning_display configure_input_data(w, data) w.global_warning_display = 0 w.update() if w.output_string_length == 0: # Some VTK versions (5.2) have a bug when writing structured # grid datasets and produce empty output. We work around this # by writing to a file and then reading that output. w.write_to_output_string = 0 fh, fname = tempfile.mkstemp('.vtk') os.close(fh) os.remove(fname) w.file_name = fname w.write() # Read the data and delete the file. sdata = open(fname).read() os.remove(fname) else: sdata = w.output_string w.global_warning_display = warn return sdata
def __init__(self, points, **traits): super(MLabBase, self).__init__(**traits) assert len(points[0]) == 3, "The points must be 3D" self.points = points np = len(points) - 1 lines = numpy.zeros((np, 2), 'l') lines[:,0] = numpy.arange(0, np-0.5, 1, 'l') lines[:,1] = numpy.arange(1, np+0.5, 1, 'l') pd = tvtk.PolyData(points=points, lines=lines) self.poly_data = pd mapper = tvtk.PolyDataMapper() self.mapper = mapper tf = self.tube_filter tf.radius = self.radius if self.use_tubes: configure_input_data(tf, pd) configure_input_data(mapper, tf.output) a = _make_actor(mapper=mapper) a.property.color = self.color self.actors.append(a)
def write_dataset_to_string(data): """Given a dataset, convert the dataset to an ASCII string that can be stored for persistence. """ w = tvtk.DataSetWriter(write_to_output_string=1) warn = w.global_warning_display configure_input_data(w, data) w.global_warning_display = 0 w.update() if w.output_string_length == 0: # Some VTK versions (5.2) have a bug when writing structured # grid datasets and produce empty output. We work around this # by writing to a file and then reading that output. w.write_to_output_string = 0 fh, fname = tempfile.mkstemp('.vtk') os.close(fh); os.remove(fname) w.file_name = fname w.write() # Read the data and delete the file. sdata = open(fname).read() os.remove(fname) else: sdata = w.output_string w.global_warning_display = warn return sdata
def test_parent_child_input(self): """Case where parent has GetInput and child SetInput.""" vm = tvtk.SmartVolumeMapper() # In this case if the wrapping is not done right, the input # trait is made read-only which is a bug. We set the input # below to test this. configure_input_data(vm, tvtk.ImageData()) spw = tvtk.StructuredPointsWriter() spw.input_connection = None
def update_interpolated_scalars(poly_data, surface_probe_filter): if poly_data: tvtk_common.configure_input_data(surface_probe_filter, poly_data) #surface_probe_filter.input = poly_data surface_probe_filter.update() # Calculate Vperp, Vpar, Vphi surface_scalars = np.array(surface_probe_filter.output.point_data.scalars) return surface_scalars
def earth_actor(radius=0.5, opacity=1.0): """ Creates an earth source and returns the actor. """ source = tvtk.EarthSource(radius=radius, on_ratio=16, outline=0) mapper = tvtk.PolyDataMapper() configure_input_data(mapper, source.output) prop = tvtk.Property(opacity=opacity) actor = tvtk.Actor(mapper=mapper, property=prop) source.update() return actor
def image_to_vtk_texture(img): imgdata = tvtk.ImageData() t = img[::-1].reshape(-1, 3).astype(np.uint8) imgdata.point_data.scalars = t imgdata.extent = (0, img.shape[0] - 1, 0, img.shape[1] - 1, 0, 0) imgdata.dimensions = (img.shape[1], img.shape[0], 1) vtk_texture = tvtk.Texture() configure_input_data(vtk_texture, imgdata) return vtk_texture
def arrow_actor(color=colors.peacock, opacity=1.0, resolution=24): """ Creates a 3D Arrow and returns an actor. """ source = tvtk.ArrowSource(tip_resolution=resolution, shaft_resolution=resolution) mapper = tvtk.PolyDataMapper() configure_input_data(mapper, source.output) prop = tvtk.Property(opacity=opacity, color=color) actor = tvtk.Actor(mapper=mapper, property=prop) source.update() return actor
def cube_actor(center=(0, 0, 0), color=colors.blue, opacity=1.0): """ Creates a cube and returns the tvtk.Actor. """ source = tvtk.CubeSource(center=center) mapper = tvtk.PolyDataMapper() configure_input_data(mapper, source.output) p = tvtk.Property(opacity=opacity, color=color) actor = tvtk.Actor(mapper=mapper, property=p) source.update() return actor
def interpolate_vectors(image_data, poly_data): """ Interpolate a imagedata vectors to a set points in polydata""" surface_probe_filter = tvtk.ProbeFilter() tvtk_common.configure_source_data(surface_probe_filter, image_data) tvtk_common.configure_input_data(surface_probe_filter, poly_data) surface_probe_filter.update() # Calculate Vperp, Vpar, Vphi surface_vectors = np.array(surface_probe_filter.output.point_data.vectors) return surface_probe_filter, surface_vectors
def polydata_actor(polydata, compute_normals=True): """ create a vtk actor with given polydata as input """ if compute_normals: normals = tvtk.PolyDataNormals(splitting=False) configure_input_data(normals, polydata) polydata = normals actor = tvtk.Actor(mapper=tvtk.PolyDataMapper()) configure_input(actor.mapper, polydata) actor.mapper.lookup_table.hue_range = (0.33, 0.) return actor
def cylinder_actor(center=(0, 0, 0), radius=0.5, resolution=64, color=colors.green, opacity=1.0): """ Creates a cylinder and returns a tvtk.Actor. """ source = tvtk.CylinderSource(center=center, radius=radius, resolution=resolution) mapper = tvtk.PolyDataMapper() configure_input_data(mapper, source.output) prop = tvtk.Property(opacity=opacity, color=color) actor = tvtk.Actor(mapper=mapper, property=prop) source.update() return actor
def __init__(self, verts1, verts2, tris=None, lines=None, as_points=False, scalars=None, scalars2=None, vmin=None, vmax=None, actor_property=dict(specular=0.1, specular_power=128., diffuse=0.5), ): if tris is None: if lines is None: rep = 'points' else: rep = 'wireframe' else: rep = 'surface' super(Morpher, self).__init__() self._verts1, self._verts2 = verts1, verts2 self._polydata = tvtk.PolyData(points=verts1) if rep == 'points': self._polydata.verts = np.r_[:len(verts1)].reshape(-1,1) if tris is not None: self._polydata.polys = tris if lines is not None: self._polydata.lines = lines n = tvtk.PolyDataNormals(splitting=False) configure_input_data(n, self._polydata) self._actor = tvtk.Actor(mapper=tvtk.PolyDataMapper()) configure_input(self._actor.mapper, n) self._actor.property.representation = rep if rep == 'points': self._actor.property.point_size = 5 if as_points and scalars is None: self._polydata.point_data.scalars = \ np.random.uniform(0, 255, (len(verts1), 3)).astype(np.uint8) self._scalars12 = None if scalars is not None: self._polydata.point_data.scalars = scalars # automatically determine minimum/maximum from scalars if not given by user if vmin is None: vmin = scalars.min() if scalars2 is not None: vmin = min(vmin, scalars2.min()) if vmax is None: vmax = scalars.max() if scalars2 is not None: vmax = max(vmax, scalars2.max()) if scalars.ndim == 1: self._actor.mapper.use_lookup_table_scalar_range = False self._actor.mapper.scalar_range = (vmin, vmax) self._actor.mapper.lookup_table.hue_range = (0.33, 0) # when scalars of second mesh given we need to store both scalars in order # to interpolate between them during rendering if scalars2 is not None: self._scalars12 = (scalars, scalars2) else: self._actor.property.set(**actor_property) mlab.gcf().scene.add_actor(self._actor)
def make_2_vert_tube(a, b): pd = tvtk.PolyData(points=[a, b], lines=[[0, 1]]) pt = tvtk.TubeFilter( radius=tube_radius, number_of_sides=20, vary_radius="vary_radius_off", ) configure_input_data(pt, pd) m = tvtk.PolyDataMapper(input_connection=pt.output_port) a = tvtk.Actor(mapper=m) a.property.color = 0, 0, 0 a.property.specular = 0.3 return a
def add_actors_to_scene(self, scene_model, volume_actor): # An outline of the bounds of the Volume actor's data outline = tvtk.OutlineFilter() self.outline = outline configure_input_data(outline, volume_actor.mapper.input) outline.update() outline_mapper = tvtk.PolyDataMapper() configure_input_data(outline_mapper, outline.output) outline_actor = tvtk.Actor(mapper=outline_mapper) outline_actor.property.opacity = 0.3 scene_model.renderer.add_actor(outline_actor)
def test_parent_child_input(self): """Case where parent has GetInput and child SetInput.""" vm = tvtk.VolumeTextureMapper2D() # In this case if the wrapping is not done right, the input # trait is made read-only which is a bug. We set the input # below to test this. configure_input_data(vm, tvtk.ImageData()) spw = tvtk.StructuredPointsWriter() if vtk_major_version < 6: spw.input = None else: spw.input_connection = None
def axes_actor(origin=(0, 0, 0), scale_factor=1.0, radius=0.02, sides=12): """Creates a simple axes actor and returns a tvtk.Actor object.""" axes = tvtk.Axes(origin=origin, scale_factor=scale_factor, symmetric=1) tube = tvtk.TubeFilter(radius=radius, number_of_sides=sides, vary_radius='vary_radius_off') configure_input_data(tube, axes.output) mapper = tvtk.PolyDataMapper() configure_input_data(mapper, tube.output) actor = tvtk.Actor(mapper=mapper) axes.update() return actor
def plotLetter(self, mlab): line = self.objList[0] v1 = [ line.x[1] - line.x[0], line.y[1] - line.y[0], line.z[1] - line.z[0] ] v2 = [ line.x[2] - line.x[1], line.y[2] - line.y[1], line.z[2] - line.z[1] ] v1 = numpy.array(v1) v2 = numpy.array(v2) v1 = v1 / numpy.linalg.norm(v1) v2 = v2 / numpy.linalg.norm(v2) vtext = tvtk.VectorText() vtext.text = self.letter text_mapper = tvtk.PolyDataMapper() configure_input_data(text_mapper, vtext.get_output()) vtext.update() p2 = tvtk.Property(color=(self.color[0], self.color[1], self.color[2])) text_actor = tvtk.Follower(mapper=text_mapper, property=p2) text_actor.position = (0, 0, 0) auxx = text_actor._get_x_range() auxy = text_actor._get_y_range() yc = (auxy[1] - auxy[0]) / 2 alpha = self.b / (2 * yc) xm = (auxx[1] + auxx[0]) * alpha / 2 y0 = auxy[0] vCorr = (self.a / 2 - xm) * v1 - y0 * v2 text_actor.orientation = self.orientation text_actor.scale = numpy.array([alpha, alpha, 1]) auxx = text_actor._get_x_range() auxy = text_actor._get_y_range() text_actor.position = (line.x[0] + vCorr[0], line.y[0] + vCorr[1], line.z[0] + vCorr[2]) fig = mlab.gcf() fig.scene.add_actor(text_actor) return mlab
def sphere_actor(center=(0, 0, 0), radius=0.5, resolution=32, color=colors.purple, opacity=1.0): """ Creates a sphere and returns the actor. """ source = tvtk.SphereSource(center=center, radius=radius, theta_resolution=resolution, phi_resolution=resolution) mapper = tvtk.PolyDataMapper() configure_input_data(mapper, source.output) prop = tvtk.Property(opacity=opacity, color=color) actor = tvtk.Actor(mapper=mapper, property=prop) source.update() return actor
def cone_actor(center=(0, 0, 0), height=1.0, radius=0.5, direction=(1, 0, 0), resolution=100, color=colors.red, opacity=1.0): """ Sets up a cone actor and returns the tvtk.Actor object.""" source = tvtk.ConeSource(center=center, height=height, radius=radius, direction=direction, resolution=resolution) mapper = tvtk.PolyDataMapper() configure_input_data(mapper, source.output) p = tvtk.Property(opacity=opacity, color=color) actor = tvtk.Actor(mapper=mapper, property=p) source.update() return actor
def get_the_line(bfield, surf_seeds, n): """Generate the vertical line on the surface""" the_line = tvtk.StreamTracer() source=tvtk.PolyData(points=np.array([surf_seeds.points.get_point(n),[0,0,0]])) tvtk_common.configure_input_data(the_line, bfield) tvtk_common.configure_source_data(the_line, source) the_line.integrator = tvtk.RungeKutta4() the_line.maximum_propagation = 1000 the_line.integration_direction = 'backward' the_line.update() return the_line
def vismesh(pts, tris, color=None, edge_visibility=False, shader=None, triangle_scalars=None, colors=None, nan_color=None, **kwargs): if 'scalars' in kwargs and np.asarray(kwargs['scalars']).ndim == 2: colors = kwargs['scalars'] del kwargs['scalars'] # VTK does not allow bool arrays as scalars normally, so convert to float if 'scalars' in kwargs and np.asarray(kwargs['scalars']).dtype == np.bool: kwargs['scalars'] = kwargs['scalars'].astype(np.float) tm = mlab.triangular_mesh(pts[:, 0], pts[:, 1], pts[:, 2], tris, color=color, **kwargs) if shader is not None: tm.actor.property.load_material(shader) tm.actor.actor.property.shading = True diffuse = 1.0 if colors is not None else 0.8 tm.actor.actor.property.set(edge_visibility=edge_visibility, line_width=1, specular=0.0, specular_power=128., diffuse=diffuse) if triangle_scalars is not None: tm.actor.mapper.input.cell_data.scalars = triangle_scalars tm.actor.mapper.set(scalar_mode='use_cell_data', use_lookup_table_scalar_range=False, scalar_visibility=True) if "vmin" in kwargs and "vmax" in kwargs: tm.actor.mapper.scalar_range = kwargs["vmin"], kwargs["vmax"] if colors is not None: # this basically is a hack which doesn't quite work, # we have to completely replace the polydata behind the hands of mayavi tm.mlab_source.dataset.point_data.scalars = colors.astype(np.uint8) normals = tvtk.PolyDataNormals(splitting=False) configure_input_data(normals, tm.mlab_source.dataset) configure_input(tm.actor.mapper, normals) if nan_color is not None: if len(nan_color) == 3: nan_color = list(nan_color) + [1] tm.module_manager.scalar_lut_manager.lut.nan_color = nan_color tm.update_pipeline() return tm
def test_parent_child_input(self): """Case where parent has GetInput and child SetInput.""" if vtk_major_version == 6 and vtk_minor_version > 1: vm = tvtk.SmartVolumeMapper() else: vm = tvtk.VolumeTextureMapper2D() # In this case if the wrapping is not done right, the input # trait is made read-only which is a bug. We set the input # below to test this. configure_input_data(vm, tvtk.ImageData()) spw = tvtk.StructuredPointsWriter() if vtk_major_version < 6: spw.input = None else: spw.input_connection = None
def display_3d_array(array_3d, color_map, figure): ''' Method displays 3d array. Param: array_3d - np.array attenmap - np.array ''' cm = color_map # Dislay 3D Array Rendering v = figure for j in range(len(array_3d)): c = tuple(cm[j]) # Coordinate Information xx, yy, zz = np.where(array_3d[j] > 0.0) xx *= 100 yy *= 100 zz *= 100 # Generate Voxels For Protein append_filter = vtk.vtkAppendPolyData() for i in range(len(xx)): input1 = vtk.vtkPolyData() voxel_source = vtk.vtkCubeSource() voxel_source.SetCenter(xx[i], yy[i], zz[i]) voxel_source.SetXLength(100) voxel_source.SetYLength(100) voxel_source.SetZLength(100) voxel_source.Update() input1.ShallowCopy(voxel_source.GetOutput()) append_filter.AddInputData(input1) append_filter.Update() # Remove Any Duplicate Points. clean_filter = vtk.vtkCleanPolyData() clean_filter.SetInputConnection(append_filter.GetOutputPort()) clean_filter.Update() # Render Voxels pd = tvtk.to_tvtk(clean_filter.GetOutput()) cube_mapper = tvtk.PolyDataMapper() configure_input_data(cube_mapper, pd) p = tvtk.Property(opacity=1.0, color=c) cube_actor = tvtk.Actor(mapper=cube_mapper, property=p) v.scene.add_actor(cube_actor)
def _resample_data(image_data): """ Resample data onto a uniform 256^3 grid. """ spacing = image_data.spacing dims = image_data.dimensions output_spacing = (spacing[0] * (dims[0] / 256), spacing[1] * (dims[1] / 256), spacing[2] * (dims[2] / 256)) reslicer = tvtk.ImageReslice(interpolation_mode='cubic', output_extent=(0, 255, 0, 255, 0, 255), output_spacing=output_spacing) configure_input_data(reslicer, image_data) reslicer.update() result = reslicer.output result.point_data.scalars.name = POINT_DATA_SCALARS_NAME return reslicer.output
def write_data(dataset, fname, **kwargs): """Given a TVTK `dataset` this writes the `dataset` to a VTK XML file having file name `fname`. If the given file name has no extension, one is automatically picked based on the dataset and an XML file is written out. If the filename has a '.vtk' extension an old style VTK file is written. If any other extension is specified, an XML file is written out with the given extension. Any additional keyword arguments are passed to the writer used. """ err_msg = "Can only write tvtk.DataSet instances "\ "'got %s instead"%(dataset.__class__.__name__) assert isinstance(dataset, tvtk.DataSet), err_msg # Mapping to determine appropriate extension and writer. d2r = { 'vtkImageData': ('.vti', tvtk.StructuredPointsWriter), 'vtkRectilinearGrid': ('.vtr', tvtk.RectilinearGridWriter), 'vtkStructuredGrid': ('.vts', tvtk.StructuredGridWriter), 'vtkPolyData': ('.vtp', tvtk.PolyDataWriter), 'vtkUnstructuredGrid': ('.vtu', tvtk.UnstructuredGridWriter) } for type in d2r: if dataset.is_a(type): datatype = d2r[type] break ext = splitext(fname)[1] if ext == '.vtk': file_name = fname writer = datatype[1] elif len(ext) == 0: file_name = fname + datatype[0] writer = tvtk.XMLDataSetWriter else: file_name = fname writer = tvtk.XMLDataSetWriter w = writer(file_name=file_name, **kwargs) configure_input_data(w, dataset) w.write()
def __init__(self, Xmean, tris, components): HasTraits.__init__(self) self._components = components self._max_component_index = len(components) self._Xmean = Xmean self.pd = tvtk.PolyData(points=Xmean, polys=tris) self.normals = tvtk.PolyDataNormals(splitting=False) configure_input_data(self.normals, self.pd) mapper = tvtk.PolyDataMapper(immediate_mode_rendering=True) self.actor = tvtk.Actor(mapper=mapper) configure_input(self.actor.mapper, self.normals) self.actor.mapper.lookup_table = tvtk.LookupTable( hue_range=(0.45, 0.6), saturation_range=(0., 0.8), value_range=(.6, 1.), ) self.scene.add_actor(self.actor) self.timer = Timer(40, self.animate().next)
def __init__(self, Xmean, tris, components): HasTraits.__init__(self) self._components = components self._max_component_index = len(components) self._Xmean = Xmean self.pd = tvtk.PolyData(points=Xmean, polys=tris) self.normals = tvtk.PolyDataNormals(splitting=False) configure_input_data(self.normals, self.pd) mapper = tvtk.PolyDataMapper(immediate_mode_rendering=True) self.actor = tvtk.Actor(mapper=mapper) configure_input(self.actor.mapper, self.normals) self.actor.mapper.lookup_table = tvtk.LookupTable( hue_range = (0.45, 0.6), saturation_range = (0., 0.8), value_range = (.6, 1.), ) self.scene.add_actor(self.actor) self.timer = Timer(40, self.animate().next)
def write_data(dataset, fname, **kwargs): """Given a TVTK `dataset` this writes the `dataset` to a VTK XML file having file name `fname`. If the given file name has no extension, one is automatically picked based on the dataset and an XML file is written out. If the filename has a '.vtk' extension an old style VTK file is written. If any other extension is specified, an XML file is written out with the given extension. Any additional keyword arguments are passed to the writer used. """ err_msg = "Can only write tvtk.DataSet instances "\ "'got %s instead"%(dataset.__class__.__name__) assert isinstance(dataset, tvtk.DataSet), err_msg # Mapping to determine appropriate extension and writer. d2r = {'vtkImageData': ('.vti', tvtk.StructuredPointsWriter), 'vtkRectilinearGrid': ('.vtr', tvtk.RectilinearGridWriter), 'vtkStructuredGrid': ('.vts', tvtk.StructuredGridWriter), 'vtkPolyData': ('.vtp', tvtk.PolyDataWriter), 'vtkUnstructuredGrid': ('.vtu', tvtk.UnstructuredGridWriter) } for type in d2r: if dataset.is_a(type): datatype = d2r[type] break ext = splitext(fname)[1] if ext == '.vtk': file_name = fname writer = datatype[1] elif len(ext) == 0: file_name = fname + datatype[0] writer = tvtk.XMLDataSetWriter else: file_name = fname writer = tvtk.XMLDataSetWriter w = writer(file_name=file_name, **kwargs) configure_input_data(w, dataset) w.write()
def make_poly_norms(poly_data): """ Extract the normal vectors from a PolyData instance (A surface). Parameters ---------- poly_data: tvtk.PolyData instance The poly data to extract normal vectors from Returns ------- poly_norms: tvtk.PolyDataNormals instance The normal vectors """ poly_norms = tvtk.PolyDataNormals() tvtk_common.configure_input_data(poly_norms, poly_data) # poly_norms.input = poly_data poly_norms.compute_point_normals = True poly_norms.flip_normals = False poly_norms.update() return poly_norms
def _use_tubes_changed(self, val): if val: tf = self.tube_filter configure_input_data(tf, self.poly_data) configure_input_data(self.mapper, tf.output) else: configure_input_data(self.mapper, self.poly_data) self.render()
def __init__(self): self.part_actor = None self.points_to_show = np.array([]) self.points_to_show.shape = (0,3) self.focus_enable = None #-------------using the example model #part =tvtk.STLReader(file_name = "C:\\Users\\xiaoxiang\\texturedknot.stl") #-------------using the little girl model #part =tvtk.OBJReader(file_name = "C:\\Users\\xiaoxiang\\Desktop\\little_girl_matlab_smoothed.obj") part =tvtk.OBJReader(file_name = ".\\Resources\\little_girl_matlab_smoothed.obj") part_mapper = tvtk.PolyDataMapper() configure_input_data(part_mapper, part.output) #use the input = part.output will get a error #-------------define the color p = tvtk.Property(opacity=1, color=(1, 0.8, 0.7), ambient = 0.06, diffuse = 0.75) # softer self.part_actor = tvtk.Actor( mapper = part_mapper, property = p ) part.update() #-------------focus_enable is initialized to be True self.focus_enable = True
def __init__(self): self.el = 0.0 self.az = 0.0 # Create an arrow. arrow = tvtk.ArrowSource() # Transform it suitably so it is oriented correctly. t = tvtk.Transform() tf = tvtk.TransformFilter() tf.transform = t t.rotate_y(90.0) t.translate((-2, 0, 0)) configure_input_data(tf, arrow.output) mapper = tvtk.PolyDataMapper() configure_input(mapper, tf) self.actor = actor = tvtk.Follower() actor.mapper = mapper prop = actor.property prop.color = 0, 1, 1 prop.ambient = 0.5 prop.diffuse = 0.5