def __init__(self): # POINTS self.points = vtk.vtkPoints() self.cell = vtk.vtkCellArray() self.poly = vtk.vtkPolyData() self.poly.SetPoints(self.points) self.poly.SetVerts(self.cell) # mapper = vtk.vtkPolyDataMapper() # mapper.SetInputData(self.poly) # self.actor = vtk.vtkActor() # self.actor.SetMapper(mapper) # CLIP box = vtk.vtkBox() box.SetBounds(0, 1, 0, 1, 0, 1) self.clipper = vtk.vtkClipPolyData() self.clipper.SetInputData(self.poly) self.clipper.SetClipFunction(box) self.clipper.Update() mapper_in = vtk.vtkPolyDataMapper() mapper_in.SetInputConnection(self.clipper.GetOutputPort(1)) actor_in = vtk.vtkActor() actor_in.SetMapper(mapper_in) actor_in.GetProperty().SetColor(1, 0, 0) mapper_out = vtk.vtkPolyDataMapper() mapper_out.SetInputConnection(self.clipper.GetOutputPort(0)) actor_out = vtk.vtkActor() actor_out.SetMapper(mapper_out) actor_out.GetProperty().SetColor(0, 1, 0) self.actor = vtk.vtkAssembly() self.actor.AddPart(actor_in) self.actor.AddPart(actor_out) for i in range(10000): self.points_grown_up()
def _createLocator(self): bounds = self.widget.imageData.GetBounds() sizes = [bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]] smallest = min(sizes) multiplier = smallest / 30 halfSize = 4 * multiplier gapSize = 2 * multiplier upLine = CreateLine([0, gapSize, 0], [0, gapSize+halfSize, 0]) downLine = CreateLine([0, -gapSize, 0], [0, -(gapSize+halfSize), 0]) rightLine = CreateLine([gapSize, 0, 0], [gapSize+halfSize, 0, 0]) leftLine = CreateLine([-gapSize, 0, 0], [-(gapSize+halfSize), 0, 0]) assembly = vtkAssembly() assembly.AddPart(upLine) assembly.AddPart(downLine) assembly.AddPart(leftLine) assembly.AddPart(rightLine) self.assemblyFollower = vtkProp3DFollower() self.assemblyFollower.SetProp3D(assembly) self.assemblyFollower.SetCamera(self.widget.renderer.GetActiveCamera()) self._addToOverlay(self.assemblyFollower) self.widget.render()
def __init__ (self, jid): self.jid = jid self.posTimeStamp = time.time() self.velocity = numpy.array([0.0, 0.0, 0.0]) self.axisOfRotation = "z" self.omega = 0.0 self.microAnimation = 'nothing' self.basedir = jvDataDir + '/Avatars/CompassRosie' # Load the stuff: filename = jvDataDir + 'Avatars/CompassRosie/index.xml' fd = open(filename, 'r') XMLstring = fd.read() fd.close() logging.debug("CompassRosie: Attempting to transform XML string") try: topElement = ET.fromstring(XMLstring) except: logging.error("CompassRosie: Failed to transform XML string") xmlConverter = XML2VTK(topElement, basedir=self.basedir) self.actors = xmlConverter.actors self.assemblies = xmlConverter.assemblies # Bind everything into a single object for the viewer: self.assembly = vtk.vtkAssembly() for i in self.actors: self.actors[i].SetPickable(1) self.assembly.AddPart(self.actors[i]) for i in self.assemblies: self.assembly.AddPart(self.assemblies[i])
def __init__(self): # Central dot self.dot = vtk.vtkSphereSource() self.dot.SetThetaResolution(20) self.dot.SetRadius(.5) self.dotMapper = vtk.vtkPolyDataMapper() self.dotMapper.SetInputConnection(self.dot.GetOutputPort()) self.dotActor = vtk.vtkActor() self.dotActor.SetMapper(self.dotMapper) # Circular halo around dot self.halo = vtk.vtkSphereSource() self.halo.SetThetaResolution(20) self.halo.SetRadius(2) self.haloMapper = vtk.vtkPolyDataMapper() self.haloMapper.SetInputConnection(self.halo.GetOutputPort()) self.haloActor = vtk.vtkActor() self.haloActor.SetMapper(self.haloMapper) self.dotActor.GetProperty().SetColor(red) self.haloActor.GetProperty().SetColor(white) self.haloActor.GetProperty().SetOpacity(0.1) self.haloActor.GetProperty().SetSpecular(0.6) self.actor = vtk.vtkAssembly() self.actor.AddPart(self.dotActor) self.actor.AddPart(self.haloActor)
def addModel(self, reader): self.maper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: self.mapper.SetInput(reader.GetOutput()) else: self.mapper.SetInputConnection(reader.GetOutputPort()) #Check if assembly has been made yet if (not self.assemblyMade): self.assembly = vtk.vtkAssembly() self.assemblyMade = True self.assembly = vtk.vtkAssembly() #Add the main actor(plane model) to the assembly then call render and reset the camera self.assembly.AddPart(self.actor) self.render.AddActor(self.assembly) self.render.ResetCamera() self.interactor.Render()
def gen_assembly(color): #return an assembly of SGV actors pnt_assembly = vtk.vtkAssembly() for pnt in a: pnt_assembly.AddPart(generate_sphere(pnt,1,color)) pnt_assembly.SetOrigin(0,0,0) return pnt_assembly
def __init__(self, altitude=0, extent=None, position=None, mode="full", color=None, hole_size=1): self._altitude = None self._extent = None self._position = None self._mode = None self._color = None self._hole_size = None # TODO : color self._sources = {} self._actor = vtkAssembly() self.altitude = altitude self.extent = extent or [[-1, -1], [1, 1]] self.position = position or [0, 0] self.mode = mode self.color = color or (1, 0, 0) self.hole_size = hole_size
def draw_directions(w, t, trans): ''' Return a vtkAssembly of arrows showing entry and exit of beam from sgv ''' arrow_length = w / np.sin(t) t = np.absolute((np.pi - t) / 2) # rotate by 2 theta exit_direction = np.array([w * np.sin(t), w * np.cos(t), 0]) enter_direction = np.array([-w * np.sin(t), w * np.cos(t), 0]) strain_direction_ref = np.array([0, w, 0]) #transform directions based on trans enter_direction = np.dot(enter_direction, trans[0:3, 0:3]) exit_direction = np.dot(exit_direction, trans[0:3, 0:3]) strain_direction_ref = np.dot(strain_direction_ref, trans[0:3, 0:3]) exit_norm = exit_direction / (np.linalg.norm(exit_direction)) enter_norm = enter_direction / (np.linalg.norm(enter_direction)) strain_ref_norm = strain_direction_ref / ( np.linalg.norm(strain_direction_ref)) exit_arrow_actor = arrow(np.array([0, 0, 0]), arrow_length, exit_norm, False, (1, 0, 0)) enter_arrow_actor = arrow(np.array([0, 0, 0]), arrow_length, enter_norm, True, (1, 0, 0)) strain_arrow_actor = arrow(np.array([0, 0, 0]), arrow_length, strain_ref_norm, False, (0, 0, 1)) arrows = vtk.vtkAssembly() arrows.AddPart(enter_arrow_actor) arrows.AddPart(exit_arrow_actor) arrows.AddPart(strain_arrow_actor) return arrows
def _createLocator(self): bounds = self.widget.imageData.GetBounds() sizes = [ bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4] ] smallest = min(sizes) multiplier = smallest / 30 halfSize = 4 * multiplier gapSize = 2 * multiplier upLine = CreateLine([0, gapSize, 0], [0, gapSize + halfSize, 0]) downLine = CreateLine([0, -gapSize, 0], [0, -(gapSize + halfSize), 0]) rightLine = CreateLine([gapSize, 0, 0], [gapSize + halfSize, 0, 0]) leftLine = CreateLine([-gapSize, 0, 0], [-(gapSize + halfSize), 0, 0]) assembly = vtkAssembly() assembly.AddPart(upLine) assembly.AddPart(downLine) assembly.AddPart(leftLine) assembly.AddPart(rightLine) self.assemblyFollower = vtkProp3DFollower() self.assemblyFollower.SetProp3D(assembly) self.assemblyFollower.SetCamera(self.widget.renderer.GetActiveCamera()) self._addToOverlay(self.assemblyFollower) self.widget.render()
def set_objects(self, object_labels, colour_scheme=None, show_orientations=True): """ Parses a list of ObjectLabel to set boxes and their colours :param object_labels: list of ObjectLabel to visualize :param colour_scheme: colours for each class (e.g. COLOUR_SCHEME_KITTI) :param show_orientations: (optional) if True, show box orientations """ box_corners = [] box_colours = [] pyramid_tips = None if show_orientations: pyramid_tips = [] for obj in object_labels: # Ignore DontCare boxes since they are at (-1000, -1000, -1000) if obj.type == 'DontCare': continue # Get box corners corners = np.array(obj_utils.compute_box_corners_3d(obj)) if corners.size != 0: box_corners.append(corners.transpose()) # Get colours if colour_scheme is not None: if obj.type in colour_scheme: box_colours.append(colour_scheme[obj.type]) else: # Default (White) box_colours.append((255, 255, 255)) if show_orientations: # Overwrite self.vtk_actor to contain both actors vtk_boxes_actor = self.vtk_actor self.vtk_actor = vtk.vtkAssembly() self.vtk_actor.AddPart(vtk_boxes_actor) self.vtk_actor.AddPart(self.vtk_pyramid_actor) # Distance off the ground arrow_height = obj.h / 2.0 pyramid_tip_length = obj.l * 0.2 half_obj_l = obj.l / 2.0 # Distance from centroid pyramid_tip_dist = half_obj_l + pyramid_tip_length # Start and end points # arrow_start = np.add(obj.t, [0, -arrow_height, 0]) pyramid_tip =\ np.add(obj.t, [pyramid_tip_dist * np.cos(obj.ry), -arrow_height, pyramid_tip_dist * -np.sin(obj.ry)]) pyramid_tips.append(pyramid_tip) self._set_boxes(box_corners, box_colours, pyramid_tips)
def tube(reader, mcBone, mcSkin): """ Create the tube visualisation of the skin. The distance between each tube is 1cm. Args: reader: vtkSLCReader used to read the raw scanner data mcBone: vtkMarchingCubes used to create the bone mcSkin: vtkMarchingCubes used to create the skin Returns: vtkAssembly """ bounds = mcSkin.GetOutput().GetBounds() # Plan plane = vtk.vtkPlane() plane.SetNormal(0, 0, 1) plane.SetOrigin((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[4]) high = plane.EvaluateFunction((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[5]) # Get the number and size of voxel (Axis:z) nbVoxelZ = reader.GetDataExtent()[5] sizeVoxelZ = reader.GetDataSpacing()[2] # Create the tubes with vtkCutter and vtkTubeFilter cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetInputConnection(mcSkin.GetOutputPort()) cutter.GenerateValues(math.floor(nbVoxelZ * sizeVoxelZ / 10) + 1, 0, high) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetInputConnection(cutter.GetOutputPort()) tubeFilter.SetRadius(.5) tubeFilter.SetNumberOfSides(50) # Skin mapper and actor mapperSkin = vtk.vtkDataSetMapper() mapperSkin.SetInputConnection(tubeFilter.GetOutputPort()) mapperSkin.ScalarVisibilityOff() actorSkin = vtk.vtkActor() actorSkin.SetMapper(mapperSkin) actorSkin.GetProperty().SetColor(0.95, 0.64, 0.64) # Bone mapper and actor mapperBone = vtk.vtkDataSetMapper() mapperBone.SetInputConnection(mcBone.GetOutputPort()) mapperBone.ScalarVisibilityOff() actorBone = vtk.vtkActor() actorBone.SetMapper(mapperBone) actorBone.GetProperty().SetColor(0.9, 0.9, 0.9) # Group the actors assembly = vtk.vtkAssembly() assembly.AddPart(actorSkin) assembly.AddPart(actorBone) return assembly
def set_objects(self, object_labels, colour_scheme=None, show_orientations=False): """Parses a list of boxes_3d and sets their colours Args: object_labels: list of ObjectLabels colour_scheme: colours for each class (e.g. COLOUR_SCHEME_KITTI) show_orientations: (optional) if True, self.vtk_lines_actor can be used to display the orientations of each box """ box_corners = [] box_colours = [] orientation_vectors = None if show_orientations: orientation_vectors = [] for obj in object_labels: # Ignore DontCare boxes since they are at (-1000, -1000, -1000) if obj.type == 'DontCare': continue box_3d = box_3d_encoder.object_label_to_box_3d(obj) # Get box corners corners = np.array(box_3d_encoder.compute_box_3d_corners(box_3d)) if corners.size != 0: box_corners.append(corners.transpose()) # Get colours if colour_scheme is not None: if obj.type in colour_scheme: box_colours.append(colour_scheme[obj.type]) else: # Default (White) box_colours.append((255, 255, 255)) if show_orientations: # Overwrite self.vtk_actor to contain both actors vtk_boxes_actor = self.vtk_actor self.vtk_actor = vtk.vtkAssembly() self.vtk_actor.AddPart(vtk_boxes_actor) self.vtk_actor.AddPart(self.vtk_lines_actor) # Distance off the ground arrow_height = obj.h / 2.0 # Start and end points arrow_start = np.add(obj.t, [0, -arrow_height, 0]) arrow_end = np.add(obj.t, [ obj.l * np.cos(obj.ry), -arrow_height, obj.l * -np.sin(obj.ry) ]) orientation_vectors.append([arrow_start, arrow_end]) self._set_boxes(box_corners, box_colours, orientation_vectors)
def semiTransparent(mcBone, mcSkin): """ Create the semi-transparent visualisation of the skin. A sphere is clipping the skin near the articulation and the front face (as seen from the camera) of the skin is semi-transparent. Args: mcBone: vtkMarchingCubes used to create the bone mcSkin: vtkMarchingCubes used to create the skin Returns: vtkAssembly """ # Create a sphere for clipping sphere = vtk.vtkSphere() sphere.SetCenter(80, 20, 120) sphere.SetRadius(60) # Clip skin with a sphere clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(mcSkin.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.SetValue(1) clipper.Update() # Skin mapper mapperSkin = vtk.vtkDataSetMapper() mapperSkin.SetInputConnection(clipper.GetOutputPort()) mapperSkin.ScalarVisibilityOff() # Opaque back skin actorSkinBack = vtk.vtkActor() actorSkinBack.SetMapper(mapperSkin) actorSkinBack.GetProperty().SetColor(0.95, 0.64, 0.64) actorSkinBack.GetProperty().SetFrontfaceCulling(True) # Transparent front skin actorSkinFront = vtk.vtkActor() actorSkinFront.SetMapper(mapperSkin) actorSkinFront.GetProperty().SetColor(0.95, 0.64, 0.64) actorSkinFront.GetProperty().SetBackfaceCulling(True) actorSkinFront.GetProperty().SetOpacity(0.5) # Bone mapper and actor mapperBone = vtk.vtkDataSetMapper() mapperBone.SetInputConnection(mcBone.GetOutputPort()) mapperBone.ScalarVisibilityOff() actorBone = vtk.vtkActor() actorBone.SetMapper(mapperBone) actorBone.GetProperty().SetColor(0.9, 0.9, 0.9) # Group the actors assembly = vtk.vtkAssembly() assembly.AddPart(actorSkinBack) assembly.AddPart(actorSkinFront) assembly.AddPart(actorBone) return assembly
def axesCubeFloor(ren): axes = axesCube(ren) flr = floor() flr.RotateX(90) flr.SetPosition(0, -1.5, 0) flr.SetScale(3) assembly = vtk.vtkAssembly() assembly.AddPart(flr) assembly.AddPart(axes) return assembly
def setup_pipeline_objs(colors, robot_id, points=False): """ Internal function to initialise vtk objects. :return: reader_list, actor_list, mapper_list """ if points: sphereSource = vtk.vtkSphereSource() sphereSource.SetCenter(0, 0, 0) sphereSource.SetRadius(0.3) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(uniform(0.0, 1.0), uniform(0.0, 1.0), uniform(0.0, 1.0)) text = vtk.vtkVectorText() text.SetText(robot_id) text_mapper = vtk.vtkPolyDataMapper() text_mapper.SetInputConnection(text.GetOutputPort()) text_actor = vtk.vtkActor() text_actor.SetMapper(text_mapper) text_actor.GetProperty().SetColor(uniform(0.0, 1.0), uniform(0.0, 1.0), uniform(0.0, 1.0)) text_actor.AddPosition(0, 0, 1) text_actor.RotateX(60) text_actor.SetScale(0.5) assembly = vtk.vtkAssembly() assembly.AddPart(actor) assembly.AddPart(text_actor) return [], [assembly], [] stl_files = setup_file_names(4) print("STL FILES: {}".format(stl_files)) reader_list = [0] * len(stl_files) actor_list = [0] * len(stl_files) # print("Actor List: {}".format(actor_list)) mapper_list = [0] * len(stl_files) for i in range(len(stl_files)): reader_list[i] = vtk.vtkSTLReader() loc = pkg_resources.resource_filename("components", '/'.join(('simulator','media', stl_files[i]))) # print(loc) reader_list[i].SetFileName(loc) mapper_list[i] = vtk.vtkPolyDataMapper() mapper_list[i].SetInputConnection(reader_list[i].GetOutputPort()) actor_list[i] = vtk.vtkActor() actor_list[i].SetMapper(mapper_list[i]) actor_list[i].GetProperty().SetColor(colors[i]) # (R,G,B) actor_list[i].SetScale(0.013) return reader_list, actor_list, mapper_list
def _createFilament(self, markers): filament = vtk.vtkAssembly() filament.AddPart(markers[0]) for i, marker in enumerate(markers[1:]): prevMarker = markers[i] cylActor = self._createCylinder(Vec3f(prevMarker.GetCenter()), Vec3f(marker.GetCenter())) filament.AddPart(cylActor) filament.AddPart(marker) return filament
def makeAssembly(actors, legend=None): '''Group many actors as a single new actor''' assembly = vtk.vtkAssembly() for a in actors: assembly.AddPart(a) setattr(assembly, 'legend', legend) assignPhysicsMethods(assembly) assignConvenienceMethods(assembly, legend) if hasattr(actors[0], 'base'): setattr(assembly, 'base', actors[0].base) setattr(assembly, 'top', actors[0].top) return assembly
def axesCubeFloor(ren, x_bound=np.matrix([[-1.5, 1.5]]), y_bound=np.matrix([[-1.5, 1.5]]), z_bound=np.matrix([[-1.5, 1.5]]), position=np.matrix([[0, -1.5, 0]])): axes = axesCube(ren, x_bound=x_bound, y_bound=y_bound, z_bound=z_bound) flr = floor() flr.RotateX(90) flr.SetPosition(position[0, 0], position[0, 1], position[0, 2]) flr.SetScale(3) assembly = vtk.vtkAssembly() assembly.AddPart(flr) assembly.AddPart(axes) return assembly
def CreateAssembly9076(): if CreateAssembly9076.output is not None: return CreateAssembly9076.output outline = CreateOutline9076() # Works - convert lines to polygons cutPoly = vtk.vtkPolyData() cutPoly.SetPoints(outline.GetPoints()) cutPoly.SetPolys(outline.GetLines()) # Triangle filter is robust enough to ignore the duplicate point at # the beginning and end of the polygons and triangulate them. cutTriangles = vtk.vtkTriangleFilter() cutTriangles.SetInputData(cutPoly) cutMapper = vtk.vtkPolyDataMapper() cutMapper.SetInputConnection(cutTriangles.GetOutputPort()) cutActor = vtk.vtkActor() cutActor.SetMapper(cutMapper) cutActor.GetProperty().SetColor(peacock) # Intersecting plane cutActor.GetProperty().SetOpacity(.3) probeSurface = CreateSurface9076() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(probeSurface) probeActor = vtk.vtkActor() probeActor.SetMapper(mapper) if vtk.VTK_VERSION > '9.0.0': prop = probeActor.GetProperty() prop.SetInterpolationToPBR() prop.SetMetallic(0.5) prop.SetRoughness(0.4) mapper0 = vtk.vtkPolyDataMapper() mapper0.SetInputData(outline) outLineActor = vtk.vtkActor() outLineActor.SetMapper(mapper0) outLineActor.GetProperty().SetLineWidth(4) assemblyActor = vtk.vtkAssembly() assemblyActor.AddPart(cutActor) assemblyActor.AddPart(probeActor) assemblyActor.AddPart(outLineActor) CreateAssembly9076.output = assemblyActor return CreateAssembly9076.output
def get_assembly(self): actor = list() # the list of links ur_assembly = [vtk.vtkAssembly()] for id, file in enumerate(self.filenames): actor.append(self.get_polydata_actor(file, self.pose[id][0:3])) self.set_actor_property(actor[id], id) # 装配体添加零件 ur_assembly[id].AddPart(actor[id]) if id < len(self.filenames): assembly = vtk.vtkAssembly() ur_assembly.append(assembly) ur_assembly[id].AddPart(ur_assembly[id + 1]) ur_assembly[id].SetOrigin(self.pose[id][0], self.pose[id][1], self.pose[id][2]) # for id, assembe in enumerate(ur_assembly): # ur_assembly[id].Rotate() # initialize_pose = [45, 45, 45, 45, 45, 30] initialize_pose = [0, 0, 0, 0, 0, 0] ur_assembly[1].SetOrientation(0, 0, initialize_pose[0]) ur_assembly[2].SetOrientation(0, 90 + initialize_pose[1], 0) ur_assembly[3].SetOrientation(0, initialize_pose[2], 0) ur_assembly[4].SetOrientation(0, 90 + initialize_pose[3], 0) ur_assembly[5].SetOrientation(0, 0, initialize_pose[4]) ur_assembly[6].SetOrientation(0, initialize_pose[5], 0) # ur_assembly[1].RotateZ(initialize_pose[0]) # ur_assembly[2].RotateY(initialize_pose[1]) # ur_assembly[3].RotateY(initialize_pose[2]) # ur_assembly[4].RotateY(initialize_pose[3]) # ur_assembly[5].RotateZ(initialize_pose[4]) # ur_assembly[6].RotateY(initialize_pose[5]) # ur_assembly[0].RotateX(180) ur_assembly[0].RotateZ(-90) return ur_assembly
def __init__(self, data, directory_prefix=None): """ Loads surface models and (optionally) assemblies from dictionary loaded by sksurgerycore.ConfigurationManager. :param data: data from sksurgerycore.ConfigurationManager :param prefix: directory name prefix as string """ self.named_assemblies = {} self.named_surfaces = {} self.directory_prefix = directory_prefix if 'surfaces' in data.keys(): surfaces = data['surfaces'] else: raise KeyError("No 'surfaces' section defined in config") # Load surfaces for surface_name in surfaces: config = surfaces[surface_name] surface = self.__load_surface(config) surface.set_name(surface_name) self.named_surfaces[surface_name] = surface if 'assemblies' in data.keys(): assemblies = data['assemblies'] self.__check_assembly_duplicates(assemblies) # Iterate over assemblies for assembly in assemblies: logging.info("Adding assembly: %s", assembly) new_assembly = vtk.vtkAssembly() # Iterate over surfaces in this assembly for surface_name in assemblies[assembly]: logging.info("Adding surface: %s to assembly: %s", surface_name, assembly) # Check surface exists and add to assembly if surface_name in self.named_surfaces.keys(): surface = self.named_surfaces[surface_name] new_assembly.AddPart(surface.actor) else: raise KeyError("Trying to add {} to vtkAssembly, \ but it is not a valid surface.".\ format(surface_name)) self.named_assemblies[assembly] = new_assembly
def __init__(self, raysect_node): if not isinstance(raysect_node, Node): raise TypeError( "A VTKNode can only be constructed from a Raysect Node object." ) assembly = vtk.vtkAssembly() assembly.SetUserTransform( convert_to_vtk_transform(raysect_node.transform)) for child in raysect_node.children: vtk_part = map_raysect_element_to_vtk(child) assembly.AddPart(vtk_part.actor) self.assembly = assembly
def colorizeSTL(output): polys = output.GetPolys() allpoints = output.GetPoints() tocolor = [] with open(params.ColorizeResult, "rb") as f: content = f.read() for b in content: if b == 1: tocolor.append(True) else: tocolor.append(False) triangles = vtk.vtkCellArray() triangles2 = vtk.vtkCellArray() for i in range(polys.GetSize()): idList = vtk.vtkIdList() polys.GetNextCell(idList) num = idList.GetNumberOfIds() if num != 3: break triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, idList.GetId(0)) triangle.GetPointIds().SetId(1, idList.GetId(1)) triangle.GetPointIds().SetId(2, idList.GetId(2)) if tocolor[i]: triangles.InsertNextCell(triangle) else: triangles2.InsertNextCell(triangle) trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(allpoints) trianglePolyData.SetPolys(triangles) trianglePolyData2 = vtk.vtkPolyData() trianglePolyData2.SetPoints(allpoints) trianglePolyData2.SetPolys(triangles2) actor = build_actor(trianglePolyData, True) actor.GetProperty().SetColor(params.ColorizeColor) actor2 = build_actor(trianglePolyData2, True) assembly = vtk.vtkAssembly() assembly.AddPart(actor) assembly.AddPart(actor2) return assembly
def readCSV(self, antennas): xyz = [] with open(antennas, 'rb') as csvfile: coordinates = csv.reader(csvfile, delimiter=',') for row in coordinates: # convert list of strings to float row = map(float, row) xyz.append(row) global antennaLocs antennaLocs = xyz if (not self.assemblyMade): self.assembly = vtk.vtkAssembly() self.assemblyMade = True for antenna in antennaLocs: self.convertDimensions(antenna[0], antenna[1], antenna[2], antenna[3])
def CreateBounds(bounds): """ Creates a boundary object to display around a volume. :rtype: list of actors """ originX = bounds[0] originY = bounds[2] originZ = bounds[4] boundX = bounds[1] boundY = bounds[3] boundZ = bounds[5] linePartLength = 0.2 lineActors = [] lineActors += CreateLineBeginAndEnd([originX, originY, originZ], [boundX, originY, originZ], linePartLength) lineActors += CreateLineBeginAndEnd([originX, originY, originZ], [originX, boundY, originZ], linePartLength) lineActors += CreateLineBeginAndEnd([originX, originY, originZ], [originX, originY, boundZ], linePartLength) ColorActor(lineActors[0], [1, 0, 0]) ColorActor(lineActors[2], [0, 1, 0]) ColorActor(lineActors[4], [0, 0, 1]) lineActors += CreateLineBeginAndEnd([boundX, boundY, boundZ], [boundX, boundY, originZ], linePartLength) lineActors += CreateLineBeginAndEnd([boundX, boundY, boundZ], [originX, boundY, boundZ], linePartLength) lineActors += CreateLineBeginAndEnd([boundX, boundY, boundZ], [boundX, originY, boundZ], linePartLength) lineActors += CreateLineBeginAndEnd([boundX, originY, originZ], [boundX, originY, boundZ], linePartLength) lineActors += CreateLineBeginAndEnd([boundX, originY, originZ], [boundX, boundY, originZ], linePartLength) lineActors += CreateLineBeginAndEnd([originX, boundY, originZ], [originX, boundY, boundZ], linePartLength) lineActors += CreateLineBeginAndEnd([originX, boundY, originZ], [boundX, boundY, originZ], linePartLength) lineActors += CreateLineBeginAndEnd([originX, originY, boundZ], [originX, boundY, boundZ], linePartLength) lineActors += CreateLineBeginAndEnd([originX, originY, boundZ], [boundX, originY, boundZ], linePartLength) for lineActor in lineActors: ColorActor(lineActor, color=None, opacity=0.5) mean = reduce(lambda x, y: x + y, bounds) / 3.0 sphereActor = CreateSphere(mean / 25.0) sphereActor.SetPosition(originX, originY, originZ) dataGrid = vtkAssembly() for lineActor in lineActors: dataGrid.AddPart(lineActor) return [dataGrid, sphereActor]
def axes(scale=(1,1,1),colorx=(1,0,0),colory=(0,1,0),colorz=(0,0,1),opacity=1): ''' Create an actor with the coordinate system axes where red = x, green = y, blue =z. ''' arrowx=_arrow(color=colorx,scale=scale,opacity=opacity) arrowy=_arrow(color=colory,scale=scale,opacity=opacity) arrowz=_arrow(color=colorz,scale=scale,opacity=opacity) arrowy.RotateZ(90) arrowz.RotateY(-90) ass=vtk.vtkAssembly() ass.AddPart(arrowx) ass.AddPart(arrowy) ass.AddPart(arrowz) return ass
def doWrap(Mapper,Act): act_left = vtk.vtkActor() act_left.SetMapper(Mapper) act_left.SetProperty(Act.GetProperty()) T = vtk.vtkTransform() T.Translate(-360,0,0) act_left.SetUserTransform(T) act_right = vtk.vtkActor() act_right.SetMapper(Mapper) T = vtk.vtkTransform() T.Translate(360,0,0) act_right.SetUserTransform(T) act_right.SetProperty(Act.GetProperty()) A = vtk.vtkAssembly() A.AddPart(act_left) A.AddPart(Act) A.AddPart(act_right) return A
def gen_meas_point_assembly(color): sgv_assembly = vtk.vtkAssembly() w = self.ui.sgv.width.value() d = self.ui.sgv.depth.value() t = np.radians(self.ui.sgv.theta.value()) trans = self.ui.sgv.trans for pnt in a: local_trans = trans local_trans[0:3,3] = pnt local_ugrid = draw_sgv(w, d, t, local_trans) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(local_ugrid) local_actor = vtk.vtkActor() local_actor.SetMapper(mapper) local_actor.GetProperty().SetColor(color) # local_actor.GetProperty().SetOpacity(0.5) sgv_assembly.AddPart(local_actor) return sgv_assembly
def __init__(self, pos, colour): depth = 0.2 height = 300 width = 600 breadth = 200 self.colour = np.array(colour) self.pos = np.array(pos) self.size = np.array((width, breadth)) dims = ((pos[0], pos[0] + width, 0, height, pos[1], pos[1] + depth), (pos[0], pos[0] + width, 0, depth, pos[1], pos[1] + breadth)) self.assembly = vtk.vtkAssembly() for d in dims: cube = vtk.vtkCubeSource() # noinspection PyArgumentList cube.SetBounds(d) actor = make_actor(cube) actor.GetProperty().SetColor(self.colour / 255) self.assembly.AddPart(actor)
def __init__(self, world_to_slice, tensor_image, display_coordinates="physical", colormap=None, opacity=1.0, display_mode="principal_direction_voxel"): self._display_mode = None self.display_coordinates_ = display_coordinates medipy.gui.image.Layer.__init__(self, world_to_slice, tensor_image, display_coordinates, colormap, opacity) self.add_allowed_event("display_mode") ###################### # Initialize members # ###################### self._pipelines = { "principal_direction_voxel": PrincipalDirectionVoxelPipeline(), "principal_direction_line": PrincipalDirectionLinePipeline(), "ellipsoid": EllipsoidPipeline() } ############################ # Property-related members # ############################ self._actor = vtkAssembly() for pipeline in self._pipelines.values(): self._actor.AddPart(pipeline.actor) ################### # Private members # ################### self._set_display_mode(display_mode) self.add_observer("any", self._on_any_event) # Update once so that the VTK pipeline is executed (and the extents of # the objects updated) before displaying. self._update()
def __init__(self, canvas, position, numInputs, numOutputs, labelList, module_instance): # parent constructor DeVIDECanvasObject.__init__(self, canvas, position) # we'll fill this out later self._size = (0, 0) self._numInputs = numInputs self.inputLines = [None] * self._numInputs self._numOutputs = numOutputs # be careful with list concatenation! self.outputLines = [[] for i in range(self._numOutputs)] self._labelList = labelList self.module_instance = module_instance # usually 2-element list. elem0 is 0 for input port and 1 for # output port. elem1 is the index. self.draggedPort = None self.enteredPort = None self.selected = False self.blocked = False # we'll collect the glyph and its ports in this assembly self.prop1 = vtk.vtkAssembly() # the main body glyph self._beb = BeveledEdgeBlock() self._selection_block = FilledBlock() self._blocked_block = FilledBlock() self._rbsa = vtk.vtkActor() # and of course the label self._tsa = vtk.vtkTextActor3D() self._iportssa = \ [(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in range(self._numInputs)] self._oportssa = \ [(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in range(self._numOutputs)] self._create_geometry() self.update_geometry()
def __init__(self, canvas, position, numInputs, numOutputs, labelList, module_instance): # parent constructor DeVIDECanvasObject.__init__(self, canvas, position) # we'll fill this out later self._size = (0,0) self._numInputs = numInputs self.inputLines = [None] * self._numInputs self._numOutputs = numOutputs # be careful with list concatenation! self.outputLines = [[] for i in range(self._numOutputs)] self._labelList = labelList self.module_instance = module_instance # usually 2-element list. elem0 is 0 for input port and 1 for # output port. elem1 is the index. self.draggedPort = None self.enteredPort = None self.selected = False self.blocked = False # we'll collect the glyph and its ports in this assembly self.prop1 = vtk.vtkAssembly() # the main body glyph self._beb = BeveledEdgeBlock() self._selection_block = FilledBlock() self._blocked_block = FilledBlock() self._rbsa = vtk.vtkActor() # and of course the label self._tsa = vtk.vtkTextActor3D() self._iportssa = \ [(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in range(self._numInputs)] self._oportssa = \ [(vtk.vtkCubeSource(),vtk.vtkActor()) for _ in range(self._numOutputs)] self._create_geometry() self.update_geometry()
def _createFilamentSpline(self, markers): profileData = vtk.vtkPolyData() points, scalars, t, sList = generateSpline(markers) fradius = self.actor_radius * 1.5 # Create the polyline. lines = vtk.vtkCellArray() lines.InsertNextCell(len(sList)) for i in range(len(sList)): lines.InsertCellPoint(i) profileData.SetPoints(points) profileData.SetLines(lines) profileData.GetPointData().SetScalars(scalars) # Add thickness to the resulting line. profileTubes = vtk.vtkTubeFilter() profileTubes.SetNumberOfSides(20) profileTubes.SetInput(profileData) profileTubes.SetRadius(fradius) profileMapper = vtk.vtkPolyDataMapper() profileMapper.SetInput(profileTubes.GetOutput()) profileMapper.SetScalarRange(0,t) profileMapper.ScalarVisibilityOff() profile = vtk.vtkActor() profile.SetMapper(profileMapper) profile.GetProperty().SetDiffuseColor(self.color.r, self.color.g, self.color.b) # profile.GetProperty().SetSpecular(.3) # profile.GetProperty().SetSpecularPower(30) markers[0].GetProperty().SetDiffuseColor(self.color.r, self.color.g, self.color.b) markers[-1].GetProperty().SetDiffuseColor(self.color.r, self.color.g, self.color.b) # Add capping spheres filament = vtk.vtkAssembly() filament.AddPart(self.CreateMarker(Vec3f(markers[0].GetCenter()), fradius)) filament.AddPart(profile) filament.AddPart(self.CreateMarker(Vec3f(markers[-1].GetCenter()), fradius)) return filament
def __init__(self, a, b): self.a = a self.b = b width = self.b[0] - self.a[0] length = self.b[1] - self.a[1] height = 300 depth = 10 dims = ((-depth, width + depth, 0, height, length, length + depth), (-depth, width + depth, 0, height, -depth, 0), (-depth, 0, 0, height, -depth, length + depth), (width, width + depth, 0, height, -depth, length + depth), (-depth, width + depth, -depth, 0, -depth, length + depth)) self.assembly = vtk.vtkAssembly() for d in dims: cube = vtk.vtkCubeSource() cube.SetBounds(d) actor = make_actor(cube) actor.GetProperty().SetColor(0.1, 0.1, 0.1) self.assembly.AddPart(actor)
def create_waypoint_object(renderer, waypoints, snapshots, waypoint_id): """ Creates a VTK object representing a waypoint and its point cloud. :param renderer: The VTK renderer. :param waypoints: dict of waypoint ID to waypoint. :param snapshots: dict of snapshot ID to snapshot. :param waypoint_id: the waypoint id of the waypoint object we wish to create. :return: A vtkAssembly representing the waypoint (an axis) and its point cloud. """ assembly = vtk.vtkAssembly() actor = vtk.vtkAxesActor() actor.SetXAxisLabelText("") actor.SetYAxisLabelText("") actor.SetZAxisLabelText("") actor.SetTotalLength(0.2, 0.2, 0.2) point_cloud_actor = create_point_cloud_object(waypoints, snapshots, waypoint_id) assembly.AddPart(actor) assembly.AddPart(point_cloud_actor) renderer.AddActor(assembly) return assembly
def createPieces(ids): # A dictionary giving the pieces index in the list by Id indexDict = {} # List of pieces pieces = [] # Current index index = 0 # We parse the Id from x to y to z in order to have the most enjoyable # piece order when rendering. Back pieces first and front pieces last for x in range(0, 3): for y in range(0, 3): for z in range(0, 3): # Position in the array stageNumber = z cubeNumber = x + (3 * y) # Figure ID from the array pieceId = ids[z][cubeNumber] # Complete the dictionary of ids indexes if pieceId not in indexDict: indexDict[pieceId] = index # Create the vtlAssembly of the current cube pieces.append(vtk.vtkAssembly()) index += 1 # The index of the current shape pieceIndex = indexDict[pieceId] # Create the cube, set its color, and add it to the list of # pieces cube = createCubeActor(cubeNumber % 3, cubeNumber // 3, stageNumber) cube.GetProperty().SetColor(COLORS[pieceIndex][0], COLORS[pieceIndex][1], COLORS[pieceIndex][2]) pieces[pieceIndex].AddPart(cube) return pieces
def Assembly(self, currentElement): self.logger.debug(' inside an <Assembly> element: "%s"' % currentElement.get('name')) assembly = vtk.vtkAssembly() if 'SetPosition' in currentElement.keys(): try: assembly.SetPosition(coordsFromString(currentElement.get('SetPosition'))) except: self.logger.error(' .. <Assembly> failed to SetPosition') if 'SetOrientation' in currentElement.keys(): try: assembly.SetOrientation(coordsFromString(currentElement.get('SetOrientation'))) except: self.logger.error(' .. <Assembly> failed to SetOrientation') for childElement in currentElement.getchildren(): if childElement.tag in vtkTypes['Prop3D']: actor = self.namesToFunctions[childElement.tag](childElement) try: assembly.AddPart(actor) except: self.logger.error(' .. <Assembly> failed to AddPart (ie, probably failed to add a childElement <Actor>)') return assembly
def axes(scale=(1, 1, 1), colorx=(1, 0, 0), colory=(0, 1, 0), colorz=(0, 0, 1), opacity=1): """ Create an actor with the coordinate's system axes where red = x, green = y, blue = z. Parameters ---------- scale : tuple (3,) Axes size e.g. (100, 100, 100). Default is (1, 1, 1). colorx : tuple (3,) x-axis color. Default red (1, 0, 0). colory : tuple (3,) y-axis color. Default green (0, 1, 0). colorz : tuple (3,) z-axis color. Default blue (0, 0, 1). opacity : float, optional Takes values from 0 (fully transparent) to 1 (opaque). Default is 1. Returns ------- vtkAssembly """ arrowx = _arrow(color=colorx, scale=scale, opacity=opacity) arrowy = _arrow(color=colory, scale=scale, opacity=opacity) arrowz = _arrow(color=colorz, scale=scale, opacity=opacity) arrowy.RotateZ(90) arrowz.RotateY(-90) ass = vtk.vtkAssembly() ass.AddPart(arrowx) ass.AddPart(arrowy) ass.AddPart(arrowz) return ass
def _createBacillus(self, markers): """ A bacillus-form bacterium is marked by two markers, so this method replaces those markers with a sphere-cylinder-sphere vtkAssembly that well-approximates the bacillus shape. The spheres are identical to the input markers and the cylinder's endpoints are at their respective centers. """ c1 = Vec3f(markers[0].GetCenter()) c2 = Vec3f(markers[1].GetCenter()) cylActor = self._createCylinder(c1, c2) markers[0].GetProperty().SetDiffuseColor(self.color.r, self.color.g, self.color.b) cylActor.GetProperty().SetDiffuseColor(self.color.r, self.color.g, self.color.b) markers[1].GetProperty().SetDiffuseColor(self.color.r, self.color.g, self.color.b) # join separate pieces into a vtkAssembly bacillus = vtk.vtkAssembly() bacillus.AddPart(markers[0]) bacillus.AddPart(cylActor) bacillus.AddPart(markers[1]) return bacillus
def display_tube(self,gfx,caller): if gfx.ps != None: gfx.renderer.RemoveActor(gfx.ps.acteur) if self.c!='' and self.T!='' and self.U!='' and self.henttype=='cTU':#CTU CASE ptype='delta' self.enttype='cTU' deltaz = (self.c/self.U) deltaphi = (self.T * 360.0)/self.U self.dphi = deltaphi self.dz = deltaz elif self.dphi!='' and self.dz!='' and self.henttype=='Elm-Hel':#DELTA CASE ptype = 'delta' self.enttype='Elm-Hel' deltaphi = self.dphi deltaz =self.dz else : MB.showwarning('Info','Configure symmetry setting') return try: zmax = gfx.map[0].box.GetBounds()[5] zmin = gfx.map[0].box.GetBounds()[4] z = zmax - zmin except: z= 4*360*abs(self.dz/self.dphi) #ici exeption 'fit' calcule de dz avec ratio !!! if 'fit' in caller: self.c = self.c * gfx.map[0].ratio self.dz = self.dz * gfx.map[0].ratio deltaz =self.dz numPts = int(z/deltaz) self.numpts = numPts#definition du nombre de sm self.cptsymops_tube(ptype,numPts) #ptype est tjs = a delta on calcule toujours de la même maniere dans symmetry #parameter definition : shifta = radians(deltaphi) phizero = radians(self.phizero) ###definition des boules selon les parametres pdo = vtk.vtkPolyData() newPts = vtk.vtkPoints() #This will store the points for the Helix vals = vtk.vtkDoubleArray() for i in range(0, numPts): try : x = self.radius * gfx.map[0].scale * cos(i*shifta + phizero) y = self.radius * gfx.map[0].scale * sin(i*shifta + phizero) z = zmin + i*deltaz except : x = self.radius * cos(i*shifta + phizero) y = self.radius * sin(i*shifta + phizero) z = i*deltaz newPts.InsertPoint(i, x,y,z) vals.InsertNextValue(i) pdo.SetPoints(newPts) pdo.GetPointData().SetScalars(vals) sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) try : sphere.SetRadius(self.radius*gfx.map[0].scale/5.0) except: sphere.SetRadius(self.radius*(1/5.)) sphere.SetThetaResolution(8) sphere.SetStartTheta(0) sphere.SetEndTheta(360) sphere.SetPhiResolution(8) sphere.SetStartPhi(0) sphere.SetEndPhi(180) glyph = vtk.vtkGlyph3D() glyph.SetInput(pdo) glyph.SetColorMode(1) glyph.ScalingOn() glyph.SetScaleMode(2) glyph.SetScaleFactor(0.25) glyph.SetSource(sphere.GetOutput()) self.spheremapper = vtk.vtkPolyDataMapper() self.spheremapper.SetInputConnection(glyph.GetOutputPort()) self.spheremapper.UseLookupTableScalarRangeOff() self.spheremapper.SetScalarVisibility(0) self.sphact = vtk.vtkActor() self.sphact.PickableOff() self.sphact.DragableOff() self.sphact.SetMapper(self.spheremapper) self.sphact.GetProperty().SetRepresentationToSurface() self.sphact.GetProperty().SetInterpolationToGouraud() self.sphact.GetProperty().SetAmbient(0.15) self.sphact.GetProperty().SetDiffuse(0.85) self.sphact.GetProperty().SetSpecular(0.1) self.sphact.GetProperty().SetSpecularPower(100) self.sphact.GetProperty().SetSpecularColor(1, 1, 1) self.sphact.GetProperty().SetColor(1,1,1) ###definition de l helice continue enhance=100 hlxpdo = vtk.vtkPolyData() hlxnewPts = vtk.vtkPoints() #This will store the points for the Helix hlxvals = vtk.vtkDoubleArray() hlxnumPts = int(numPts*enhance) for i in range(0, hlxnumPts): try : x = self.radius * gfx.map[0].scale * cos(i*shifta/enhance + phizero) y = self.radius * gfx.map[0].scale * sin(i*shifta/enhance + phizero) z = zmin + i*deltaz/enhance except : x = self.radius * cos(i*shifta/enhance + phizero) y = self.radius * sin(i*shifta/enhance + phizero) z = i*deltaz/enhance hlxnewPts.InsertPoint(i, x,y,z) hlxvals.InsertNextValue(i) hlxpdo.SetPoints(hlxnewPts) hlxpdo.GetPointData().SetScalars(hlxvals) aPolyLine = vtk.vtkPolyLine() aPolyLine.GetPointIds().SetNumberOfIds(hlxnumPts) for i in range(0,hlxnumPts): aPolyLine.GetPointIds().SetId(i, i) hlxpdo.Allocate(1, 1) hlxpdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetScalarVisibility(0) self.mapper.SetInput(hlxpdo) self.helact = vtk.vtkActor() self.helact.PickableOff() self.helact.DragableOff() self.helact.GetProperty().SetColor(1,1,1) self.helact.GetProperty().SetRepresentationToWireframe() self.helact.GetProperty().SetLineWidth(5) self.helact.GetProperty().SetLineWidth(1) self.helact.GetProperty().SetSpecular(.4) self.helact.GetProperty().SetSpecularPower(10) self.helact.SetMapper(self.mapper) assembly = vtk.vtkAssembly() assembly.AddPart(self.sphact) assembly.AddPart(self.helact) helcol = [(1,1,1),(1,0,0.3),(0.3,0,1),(0,1,0.3)] for i in range(1,self.s+1): if i == 1: continue else : tmp_sphact= vtk.vtkActor() tmp_helact= vtk.vtkActor() tmp_sphact.ShallowCopy(self.sphact) tmp_helact.ShallowCopy(self.helact) ps=vtk.vtkProperty() ph=vtk.vtkProperty() ps.SetColor(helcol[(i-1)%4]) ph.SetColor(helcol[(i-1)%4]) tmp_sphact.SetProperty(ps) tmp_helact.SetProperty(ph) tmp_sphact.RotateWXYZ((360/self.s)*(i-1),0,0,1) tmp_helact.RotateWXYZ((360/self.s)*(i-1),0,0,1) assembly.AddPart(tmp_sphact) assembly.AddPart(tmp_helact) self.acteur=assembly gfx.renderer.AddActor(self.acteur) gfx.renwin.Render() gfx.ps = self return ptype
def display_Xn(self,gfx): if gfx.ps != None: gfx.renderer.RemoveActor(gfx.ps.acteur) try: zmax = gfx.map[0].box.GetBounds()[5] zmin = gfx.map[0].box.GetBounds()[4] ymax = gfx.map[0].box.GetBounds()[3] ymin = gfx.map[0].box.GetBounds()[2] c = (zmax - zmin)/2. b = (ymax - ymin)/2. except: b = c = self.radius dist = self.radius phizero = radians(self.phizero) if self.solidtype=='Cn': numPts = self.cnn shifta = radians(360./numPts) pdo = vtk.vtkPolyData() cirpdo = vtk.vtkPolyData() newPts = vtk.vtkPoints() vals = vtk.vtkDoubleArray() for i in range(0, numPts): try : if self.axe=='Z': x = dist * gfx.map[0].scale * cos(i*shifta + phizero) y = dist * gfx.map[0].scale * sin(i*shifta + phizero) z = 0 elif self.axe == 'Y': x = dist * gfx.map[0].scale * cos(i*shifta + phizero) y = 0 z = dist * gfx.map[0].scale * sin(i*shifta + phizero) elif self.axe == 'X': x = 0 y = dist * gfx.map[0].scale * cos(i*shifta + phizero) z = dist * gfx.map[0].scale * sin(i*shifta + phizero) except : if self.axe=='Z': x = dist * cos(i*shifta + phizero) y = dist * sin(i*shifta + phizero) z = 0 elif self.axe == 'Y': x = dist * cos(i*shifta + phizero) y = 0 z = dist * sin(i*shifta + phizero) elif self.axe == 'X': x = 0 y = dist * cos(i*shifta + phizero) z = dist * sin(i*shifta + phizero) newPts.InsertPoint(i, x,y,z) vals.InsertNextValue(i) pdo.SetPoints(newPts) pdo.GetPointData().SetScalars(vals) cirpdo.SetPoints(newPts) cirpdo.GetPointData().SetScalars(vals) aPolyLine = vtk.vtkPolyLine() aPolyLine.GetPointIds().SetNumberOfIds(numPts+1) for i in range(0,numPts): aPolyLine.GetPointIds().SetId(i, i) aPolyLine.GetPointIds().SetId(numPts, 0) cirpdo.Allocate(1, 1) cirpdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) try : sphere.SetRadius(self.radius*gfx.map[0].scale/5.0) except: sphere.SetRadius(self.radius/5.0) sphere.SetThetaResolution(8) sphere.SetStartTheta(0) sphere.SetEndTheta(360) sphere.SetPhiResolution(8) sphere.SetStartPhi(0) sphere.SetEndPhi(180) glyph = vtk.vtkGlyph3D() glyph.SetInput(pdo) glyph.SetColorMode(1) glyph.ScalingOn() glyph.SetScaleMode(2) glyph.SetScaleFactor(0.25) glyph.SetSource(sphere.GetOutput()) self.spheremapper = vtk.vtkPolyDataMapper() self.spheremapper.SetInputConnection(glyph.GetOutputPort()) self.spheremapper.UseLookupTableScalarRangeOff() self.spheremapper.SetScalarVisibility(0) self.sphact = vtk.vtkActor() self.sphact.PickableOff() self.sphact.DragableOff() self.sphact.SetMapper(self.spheremapper) self.sphact.GetProperty().SetRepresentationToSurface() self.sphact.GetProperty().SetInterpolationToGouraud() self.sphact.GetProperty().SetAmbient(0.15) self.sphact.GetProperty().SetDiffuse(0.85) self.sphact.GetProperty().SetSpecular(0.1) self.sphact.GetProperty().SetSpecularPower(100) self.sphact.GetProperty().SetSpecularColor(1, 1, 1) self.sphact.GetProperty().SetColor(1,1,1) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetScalarVisibility(0) self.mapper.SetInput(cirpdo) self.helact = vtk.vtkActor() self.helact.PickableOff() self.helact.DragableOff() self.helact.GetProperty().SetColor(1,1,1) self.helact.GetProperty().SetRepresentationToWireframe() self.helact.GetProperty().SetLineWidth(5) self.helact.GetProperty().SetLineWidth(1) self.helact.GetProperty().SetSpecular(.4) self.helact.GetProperty().SetSpecularPower(10) self.helact.SetMapper(self.mapper) assembly = vtk.vtkAssembly() assembly.AddPart(self.sphact) assembly.AddPart(self.helact) self.acteur=assembly gfx.renderer.AddActor(self.acteur) gfx.renwin.Render() gfx.ps = self elif self.solidtype=='Dn': numPts = self.dnn shifta = radians(360./numPts) cirpdo = vtk.vtkPolyData() pdo = vtk.vtkPolyData() newPts = vtk.vtkPoints() vals = vtk.vtkDoubleArray() for i in range(0, numPts): try: x = dist * gfx.map[0].scale * cos(i*shifta) y = dist * gfx.map[0].scale * sin(i*shifta) z = 0 except: x = dist * cos(i*shifta) y = dist * sin(i*shifta) z = 0 newPts.InsertPoint(i, x,y,z) vals.InsertNextValue(i) pdo.SetPoints(newPts) pdo.GetPointData().SetScalars(vals) cirpdo.SetPoints(newPts) cirpdo.GetPointData().SetScalars(vals) aPolyLine = vtk.vtkPolyLine() aPolyLine.GetPointIds().SetNumberOfIds(numPts+1) for i in range(0,numPts): aPolyLine.GetPointIds().SetId(i, i) aPolyLine.GetPointIds().SetId(numPts, 0) cirpdo.Allocate(1, 1) cirpdo.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) try: sphere.SetRadius(self.radius*gfx.map[0].scale/5.0) except: sphere.SetRadius(self.radius/5.0) sphere.SetThetaResolution(8) sphere.SetStartTheta(0) sphere.SetEndTheta(360) sphere.SetPhiResolution(8) sphere.SetStartPhi(0) sphere.SetEndPhi(180) glyph = vtk.vtkGlyph3D() glyph.SetInput(pdo) glyph.SetColorMode(1) glyph.ScalingOn() glyph.SetScaleMode(2) glyph.SetScaleFactor(0.25) glyph.SetSource(sphere.GetOutput()) self.spheremapper = vtk.vtkPolyDataMapper() self.spheremapper.SetInputConnection(glyph.GetOutputPort()) self.spheremapper.UseLookupTableScalarRangeOff() self.spheremapper.SetScalarVisibility(0) self.sphact = vtk.vtkActor() self.sphact.PickableOff() self.sphact.DragableOff() self.sphact.SetMapper(self.spheremapper) self.sphact.GetProperty().SetRepresentationToSurface() self.sphact.GetProperty().SetInterpolationToGouraud() self.sphact.GetProperty().SetAmbient(0.15) self.sphact.GetProperty().SetDiffuse(0.85) self.sphact.GetProperty().SetSpecular(0.1) self.sphact.GetProperty().SetSpecularPower(100) self.sphact.GetProperty().SetSpecularColor(1, 1, 1) self.sphact.GetProperty().SetColor(1,1,1) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetScalarVisibility(0) self.mapper.SetInput(cirpdo) self.helact = vtk.vtkActor() self.helact.PickableOff() self.helact.DragableOff() self.helact.GetProperty().SetColor(1,1,1) self.helact.GetProperty().SetRepresentationToWireframe() self.helact.GetProperty().SetLineWidth(5) self.helact.GetProperty().SetLineWidth(1) self.helact.GetProperty().SetSpecular(.4) self.helact.GetProperty().SetSpecularPower(10) self.helact.SetMapper(self.mapper) sphact2 = vtk.vtkActor() helact2 = vtk.vtkActor() sphact2.ShallowCopy(self.sphact) helact2.ShallowCopy(self.helact) self.sphact.AddPosition(0,0,dist*c/b) self.helact.AddPosition(0,0,dist*c/b) sphact2.AddPosition(0,0,-dist*c/b) helact2.AddPosition(0,0,-dist*c/b) assembly = vtk.vtkAssembly() assembly.AddPart(self.sphact) assembly.AddPart(self.helact) assembly.AddPart(sphact2) assembly.AddPart(helact2) self.acteur=assembly gfx.renderer.AddActor(self.acteur) gfx.renwin.Render() gfx.ps = self
import vtk s1 = vtk.vtkSphereSource() m1 = vtk.vtkPolyDataMapper() a1 = vtk.vtkActor() a1.SetMapper(m1) m1.SetInput(s1.GetOutput()) s2 = vtk.vtkConeSource() m2 = vtk.vtkPolyDataMapper() a2 = vtk.vtkActor() a2.SetMapper(m2) m2.SetInput(s2.GetOutput()) as1 = vtk.vtkAssembly() as1.AddPart(a1) as1.AddPart(a2) t1 = vtk.vtkTransform() t1.PostMultiply() t1.Translate(5.0, 0.0, 0.0) pc1 = vtk.vtkPropCollection() as1.GetActors(pc1) pc1.InitTraversal() for i in xrange(pc1.GetNumberOfItems()): pc1.GetNextProp().GetProperty().SetColor(255.0, 0.0, 0.0) ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor()
def __init__(self,axesOn = True): self.assembly = vtk.vtkAssembly() self.axes = vtk.vtkAxesActor() self.assembly.AddPart(self.axes) self.length = 20 self.setAxesOn(axesOn)
import vtk assembly1 = vtk.vtkAssembly() mappers = [] sources = [] def fun1(*args): global assembly1, ren print ren.GetNumberOfPropsRendered() ren.RemoveAllViewProps() ren.Modified() ren.Render() print ren.GetNumberOfPropsRendered() for i in xrange(6): x = vtk.vtkMath.Random(-5, 5) y = vtk.vtkMath.Random(-5, 5) z = vtk.vtkMath.Random(-5, 5) source_i = vtk.vtkConeSource() source_i.SetCenter(x, y, z) sources.append(source_i) mapper_i = vtk.vtkPolyDataMapper() mapper_i.SetInput(source_i.GetOutput()) actor_i = vtk.vtkActor() actor_i.SetMapper(mapper_i) c_r = (vtk.vtkMath.Random(0, 1)) c_g = (vtk.vtkMath.Random(0, 1)) c_b = (vtk.vtkMath.Random(0, 1)) print c_r, c_g, c_b actor_i.GetProperty().SetColor(c_r, c_g, c_b)
def __init__(self): self._parts = [] self._actor = vtk.vtkAssembly() self.setup()
def build_polydata(self): ''' build a vtkPolyData object for a given frame of the trajectory ''' self._polydata = vtk.vtkPolyData() # Converts the numpy coordinates into a vtk array coords, self.vtkids = ndarray_to_vtkpoints(self.coords) self._polydata.SetPoints(coords) del coords scalars = ndarray_to_vtkarray(self.atomsColours, self._atomsScales, self._nAtoms) self._polydata.GetPointData().SetScalars(scalars) del scalars bonds = [] for at in self._atoms: for bat in at.bondedTo(): if set([at.index,bat.index]) not in bonds: bonds.append([at.index,bat.index]) bonds = ndarray_to_vtkcellarray(bonds) self._polydata.SetLines(bonds) del bonds rendmod = self._rendmod actor_list = [] line_acteur=None ball_acteur=None tube_acteur=None if rendmod in [0,4] : line_mapper = vtk.vtkPolyDataMapper() if vtk.vtkVersion.GetVTKMajorVersion()<6: line_mapper.SetInput(self._polydata) else: line_mapper.SetInputData(self._polydata) line_mapper.SetLookupTable(self._lut) line_mapper.ScalarVisibilityOn() line_mapper.ColorByArrayComponent("scalars", 1) line_acteur = vtk.vtkActor() line_acteur.GetProperty().SetLineWidth(3) line_acteur.SetMapper(line_mapper) actor_list.append(line_acteur) if rendmod in [1,3,4]: sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) sphere.SetRadius(0.2) glyph = vtk.vtkGlyph3D() if vtk.vtkVersion.GetVTKMajorVersion()<6: glyph.SetInput(self._polydata) else: glyph.SetInputData(self._polydata) glyph.SetScaleModeToScaleByScalar() glyph.SetColorModeToColorByScalar() glyph.SetScaleFactor(1) glyph.SetSourceConnection(sphere.GetOutputPort()) glyph.SetIndexModeToScalar() sphere_mapper = vtk.vtkPolyDataMapper() sphere_mapper.SetLookupTable(self._lut) sphere_mapper.SetScalarRange(self._polydata.GetScalarRange()) sphere_mapper.SetInputConnection(glyph.GetOutputPort()) sphere_mapper.ScalarVisibilityOn() sphere_mapper.ColorByArrayComponent("scalars", 1) ball_acteur = vtk.vtkActor() ball_acteur.SetMapper(sphere_mapper) ball_acteur.GetProperty().SetAmbient(0.2) ball_acteur.GetProperty().SetDiffuse(0.5) ball_acteur.GetProperty().SetSpecular(0.3) actor_list.append(ball_acteur) self.glyph = glyph if rendmod in [2,3] : tubes = vtk.vtkTubeFilter() if vtk.vtkVersion.GetVTKMajorVersion()<6: tubes.SetInput(self._polydata) else: tubes.SetInputData(self._polydata) tubes.SetNumberOfSides(6) if rendmod == 2: tubes.CappingOn() tubes.SetRadius(0.015) else: tubes.SetCapping(0) tubes.SetRadius(0.01) tube_mapper = vtk.vtkPolyDataMapper() tube_mapper.SetLookupTable(self._lut) tube_mapper.SetInputConnection(tubes.GetOutputPort()) tube_mapper.ScalarVisibilityOn() tube_mapper.ColorByArrayComponent("scalars", 1) tube_acteur = vtk.vtkActor() tube_acteur.SetMapper(tube_mapper) tube_acteur.GetProperty().SetAmbient(0.2) tube_acteur.GetProperty().SetDiffuse(0.5) tube_acteur.GetProperty().SetSpecular(0.3) actor_list.append(tube_acteur) self.tubes = tubes self.picking_domain = {0:line_acteur,1:ball_acteur,2:tube_acteur,3:ball_acteur,4:ball_acteur}[rendmod] basis_vector = self._trajectory.universe.basisVectors() if not basis_vector is None: self.bbox = self.build_bbox(basis_vector) if not self.display_bbox: self.bbox.VisibilityOff() actor_list.append(self.bbox) assembly = vtk.vtkAssembly() for actor in actor_list: assembly.AddPart(actor) #self.build_real_bbox(assembly) return assembly
def CreateOrientationGrid(bounds, camera): return [] originX = bounds[0] originY = bounds[2] originZ = bounds[4] boundX = bounds[1] * 1.2 boundY = bounds[3] * 1.2 boundZ = bounds[5] * 1.2 lineActorsX = [] lineActorsY = [] lineActorsZ = [] lineText = [] # Create the main axes lineActorsX.append(CreateLine([0, 0, 0], [boundX, 0, 0])) lineActorsX.append(CreateLine([0, 0, 0], [originX, 0, 0])) lineActorsY.append(CreateLine([0, 0, 0], [0, boundY, 0])) lineActorsY.append(CreateLine([0, 0, 0], [0, originY, 0])) lineActorsZ.append(CreateLine([0, 0, 0], [0, 0, boundZ])) lineActorsZ.append(CreateLine([0, 0, 0], [0, 0, originZ])) # Create the nudges on the X axis subdivSize = boundX / 10 subdivSize = ClosestToMeasurement(subdivSize) smallHandleSize = subdivSize / 5.0 bigHandleSize = 2 * smallHandleSize for index in range(1, int(boundX / subdivSize)): handleSize = smallHandleSize if index % 5 != 0 else bigHandleSize lineActorsX.append(CreateLine([index * subdivSize, 0, 0], [index * subdivSize, handleSize, 0])) lineActorsX.append(CreateLine([index * subdivSize, 0, 0], [index * subdivSize, 0, handleSize])) if index > 0 and index % 5 == 0: textItem = CreateTextItem(str(index * subdivSize), 0.4 * subdivSize, camera) textItem.SetPosition([index * subdivSize, -handleSize, -handleSize]) ColorActor(textItem, color=[0.6, 0.6, 0.6]) lineText.append(textItem) textItemX = CreateTextItem("X", 0.5 * subdivSize, camera) textItemX.SetPosition([boundX, 0, 0]) # Create the nudges on the Y axis subdivSize = boundY / 10 subdivSize = ClosestToMeasurement(subdivSize) smallHandleSize = subdivSize / 5.0 for index in range(1, int(boundY / subdivSize)): handleSize = smallHandleSize if index % 5 != 0 else bigHandleSize lineActorsY.append(CreateLine([0, index * subdivSize, 0], [handleSize, index * subdivSize, 0])) lineActorsY.append(CreateLine([0, index * subdivSize, 0], [0, index * subdivSize, handleSize])) if index > 0 and index % 5 == 0: textItem = CreateTextItem(str(index * subdivSize), 0.4 * subdivSize, camera) textItem.SetPosition([-smallHandleSize, index * subdivSize, -smallHandleSize]) ColorActor(textItem, color=[0.6, 0.6, 0.6]) lineText.append(textItem) textItemY = CreateTextItem("Y", 0.5 * subdivSize, camera) textItemY.SetPosition([0, boundY, 0]) # Create the nudges on the Z axis subdivSize = boundZ / 10 subdivSize = ClosestToMeasurement(subdivSize) smallHandleSize = subdivSize / 5.0 for index in range(1, int(boundZ / subdivSize)): handleSize = smallHandleSize if index % 5 != 0 else bigHandleSize lineActorsZ.append(CreateLine([0, 0, index * subdivSize], [handleSize, 0, index * subdivSize])) lineActorsZ.append(CreateLine([0, 0, index * subdivSize], [0, handleSize, index * subdivSize])) if index > 0 and index % 5 == 0: textItem = CreateTextItem(str(index * subdivSize), 0.4 * subdivSize, camera) textItem.SetPosition([-handleSize, -handleSize, index * subdivSize]) ColorActor(textItem, color=[0.6, 0.6, 0.6]) lineText.append(textItem) textItemZ = CreateTextItem("Z", 0.5 * subdivSize, camera) textItemZ.SetPosition([0, 0, boundZ]) # Color the axis: R, G and B for lineActor in lineActorsX: ColorActor(lineActor, [1, 0, 0]) for lineActor in lineActorsY: ColorActor(lineActor, [0, 1, 0]) for lineActor in lineActorsZ: ColorActor(lineActor, [0, 0, 1]) # Add the lines into one big assembly dataGrid = vtkAssembly() for lineActor in (lineActorsX + lineActorsY + lineActorsZ): dataGrid.AddPart(lineActor) return [dataGrid, textItemX, textItemY, textItemZ] + lineText
def __init__(self, electrode_data): def __pca(A): """ Principal Component Analaysis """ # Get Dimensions num_data, dim = A.shape # Center data mean_A = A.mean(axis=0) for i in range(num_data): A[i] -= mean_A u,s,v = np.linalg.svd(A) normPos = s.argmin() return v[:, normPos] """ Setup Surface Rendering """ # Apply a discrete marching cubes algorithm to extract segmented # surface contours with incremental values self.electrodeExtractor = vtk.vtkDiscreteMarchingCubes() self.electrodeExtractor.SetInput(electrode_data.GetOutput()) self.electrodeExtractor.GenerateValues(1,\ np.min(electrode_data.GetArray()),\ np.max(electrode_data.GetArray())) self.electrodeMapper = vtk.vtkPolyDataMapper() self.electrodeMapper.SetInputConnection(\ self.electrodeExtractor.GetOutputPort()) self.electrodeMapper.ScalarVisibilityOff() self.electrodeProperty = vtk.vtkProperty() self.electrodeProperty.SetColor(1.0, 0.5, 0.0) self.SetMapper(self.electrodeMapper) self.SetProperty(self.electrodeProperty) self.electrodeExtractor.Update() self.grid = vtk.vtkAssembly() self.electrodePolyData = vtk.vtkPolyData() electrodePoints = vtk.vtkPoints() ePointMat = np.mat(np.zeros(shape = (36, 3))) chanIdx = 0 for segLabel in np.unique(electrode_data.GetArray()): # This is hacked for MAYO34 in order to show just the 6x6 grid sphere = vtk.vtkSphereSource() sphere.SetRadius(2) sphereMap = vtk.vtkPolyDataMapper() sphereMap.SetInput(sphere.GetOutput()) if (segLabel > 0 and segLabel < 37): x,y,z = np.nonzero(electrode_data.GetArray() == segLabel) nx = 0.9375*np.mean(z) ny = 0.9375*np.mean(y) nz = 1.5*np.mean(x) ePointMat[chanIdx] = [nx, ny, nz] chanIdx = chanIdx + 1 normalVector = __pca(ePointMat.copy()) for chan in range(chanIdx): xx = ePointMat[chan, 0] yy = ePointMat[chan, 1] zz = ePointMat[chan, 2] sphereActor = vtk.vtkOpenGLActor() sphereActor.SetMapper(sphereMap) sphereActor.GetProperty().SetColor(1.0, 0.0, 1.0) sphereActor.SetPosition(xx - 0 * normalVector[0],\ yy - 0 * normalVector[1],\ zz - 0 * normalVector[2]) electrodePoints.InsertNextPoint(xx - 0 * normalVector[0],\ yy - 0 * normalVector[1],\ zz - 0 * normalVector[2]) self.grid.AddPart(sphereActor) self.electrodePolyData.SetPoints(electrodePoints) self.GridSurface()
def load_mols(mol,rendmod,gfx,atomcol): mol.reader = vtk.vtkPDBReader() mol.reader.SetFileName(mol.mod.dfn) mol.reader.Update() #by calling Update() we read the file mol.reader.SetHBScale(mol.hbdsl) mol.reader.SetBScale(mol.bdsl) Localmol=[] beg=0 if mol.acteur!=None: pos = mol.acteur.GetPosition() ori = mol.acteur.GetOrientation() gfx.renderer.RemoveActor(mol.acteur) beg=1 if rendmod in [0,4] : mol.mapper = vtk.vtkPolyDataMapper() mol.mapper.SetInputConnection(mol.reader.GetOutputPort()) if atomcol!=1: mol.mapper.UseLookupTableScalarRangeOff() mol.mapper.SetScalarVisibility(0) else: mol.mapper.SetScalarModeToDefault() lacteur = vtk.vtkActor() lacteur.GetProperty().SetColor(mol.col) if mol.mod.dspmodtype=='AA': lacteur.GetProperty().SetLineWidth(3) else : lacteur.GetProperty().SetLineWidth(4) lacteur.SetMapper(mol.mapper) Localmol+=[lacteur] if rendmod in [1,3,4]: sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) sphere.SetRadius(1) sphere.SetThetaResolution(8) sphere.SetStartTheta(0) sphere.SetEndTheta(360) sphere.SetPhiResolution(8) sphere.SetStartPhi(0) sphere.SetEndPhi(180) glyph = vtk.vtkGlyph3D() glyph.SetInputConnection(mol.reader.GetOutputPort()) glyph.SetColorMode(1) glyph.ScalingOn() glyph.SetScaleMode(2) glyph.SetScaleFactor(0.25) glyph.SetSource(sphere.GetOutput()) mol.mapper = vtk.vtkPolyDataMapper() mol.mapper.SetInputConnection(glyph.GetOutputPort()) if atomcol!=1: mol.mapper.UseLookupTableScalarRangeOff() mol.mapper.SetScalarVisibility(0) else: mol.mapper.SetScalarModeToDefault() bacteur = vtk.vtkActor() bacteur.SetMapper(mol.mapper) bacteur.GetProperty().SetRepresentationToSurface() bacteur.GetProperty().SetInterpolationToGouraud() bacteur.GetProperty().SetAmbient(0.15) bacteur.GetProperty().SetDiffuse(0.85) bacteur.GetProperty().SetSpecular(0.1) bacteur.GetProperty().SetSpecularPower(100) bacteur.GetProperty().SetSpecularColor(1, 1, 1) bacteur.GetProperty().SetColor(mol.col) Localmol+=[bacteur] if rendmod in [2,3] : tubes = vtk.vtkTubeFilter() tubes.SetInputConnection(mol.reader.GetOutputPort()) tubes.SetNumberOfSides(8) tubes.SetCapping(0) tubes.SetRadius(1) tubes.SetVaryRadius(0) tubes.SetRadiusFactor(10) mol.mapper = vtk.vtkPolyDataMapper() mol.mapper.SetInputConnection(tubes.GetOutputPort()) if atomcol!=1: mol.mapper.UseLookupTableScalarRangeOff() mol.mapper.SetScalarVisibility(0) else: mol.mapper.SetScalarModeToDefault() tacteur = vtk.vtkActor() tacteur.SetMapper(mol.mapper) tacteur.GetProperty().SetRepresentationToSurface() tacteur.GetProperty().SetInterpolationToGouraud() tacteur.GetProperty().SetAmbient(0.15) tacteur.GetProperty().SetDiffuse(0.85) tacteur.GetProperty().SetSpecular(0.1) tacteur.GetProperty().SetSpecularPower(100) tacteur.GetProperty().SetSpecularColor(1, 1, 1) tacteur.GetProperty().SetColor(mol.col) Localmol+=[tacteur] assembly = vtk.vtkAssembly() for act in Localmol: assembly.AddPart(act) del act mol.acteur=assembly if beg: mol.acteur.SetPosition(pos) mol.acteur.SetOrientation(ori) else : remember_rottra(mol) gfx.renderer.AddActor(mol.acteur) gfx.renwin.Render()
def build_polydata(self): ''' build a vtkPolyData object for a given frame of the trajectory ''' atom_polydata = vtk.vtkPolyData() coords, _ = ndarray_to_vtkpoints(self.coords) atom_polydata.SetPoints(coords) scalars = ndarray_to_vtkarray(self.atomColors, self.atomSizes, self._nAtoms) atom_polydata.GetPointData().SetScalars(scalars) bonds = ndarray_to_vtkcellarray(self.bonds) atom_polydata.SetLines(bonds) rendmod = self._rendmod self.actor_list = [] line_actor=None ball_actor=None tube_actor=None if rendmod in [LINES, BALLS_AND_LINES] : line_mapper = vtk.vtkPolyDataMapper() line_mapper.SetInput(atom_polydata) line_mapper.SetLookupTable(self._lut) line_mapper.ScalarVisibilityOn() line_mapper.ColorByArrayComponent("scalars", 1) line_actor = vtk.vtkActor() line_actor.GetProperty().SetLineWidth(3) line_actor.SetMapper(line_mapper) self.actor_list += [line_actor] if rendmod in [BALLS, BALLS_AND_STICKS, BALLS_AND_LINES]: sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) sphere.SetRadius(0.2) glyph = vtk.vtkGlyph3D() glyph.SetInput(atom_polydata) glyph.SetScaleModeToScaleByScalar() glyph.SetColorModeToColorByScalar() glyph.SetScaleFactor(1) glyph.SetSource(sphere.GetOutput()) glyph.SetIndexModeToScalar() sphere_mapper = vtk.vtkPolyDataMapper() sphere_mapper.SetLookupTable(self._lut) sphere_mapper.SetScalarRange(atom_polydata.GetScalarRange()) sphere_mapper.SetInputConnection(glyph.GetOutputPort()) sphere_mapper.ScalarVisibilityOn() sphere_mapper.ColorByArrayComponent("scalars", 1) ball_actor = vtk.vtkActor() ball_actor.SetMapper(sphere_mapper) ball_actor.GetProperty().SetAmbient(0.2) ball_actor.GetProperty().SetDiffuse(0.5) ball_actor.GetProperty().SetSpecular(0.3) self.actor_list+=[ball_actor] self.glyph = glyph if rendmod in [STICKS, BALLS_AND_STICKS] : tubes = vtk.vtkTubeFilter() tubes.SetInput(atom_polydata) tubes.SetNumberOfSides(6) if rendmod == 2: tubes.CappingOn() tubes.SetRadius(0.015) else: tubes.SetCapping(0) tubes.SetRadius(0.01) tube_mapper = vtk.vtkPolyDataMapper() tube_mapper.SetLookupTable(self._lut) tube_mapper.SetInputConnection(tubes.GetOutputPort()) tube_mapper.ScalarVisibilityOn() tube_mapper.ColorByArrayComponent("scalars", 1) tube_actor = vtk.vtkActor() tube_actor.SetMapper(tube_mapper) tube_actor.GetProperty().SetAmbient(0.2) tube_actor.GetProperty().SetDiffuse(0.5) tube_actor.GetProperty().SetSpecular(0.3) self.actor_list+=[tube_actor] self.tubes = tubes if len(self.site_links) > 0: link_polydata = vtk.vtkPolyData() link_polydata.SetPoints(coords) link_polydata.SetLines(ndarray_to_vtkcellarray(self.site_links)) link_mapper = vtk.vtkPolyDataMapper() link_mapper.SetInput(link_polydata) link_actor = vtk.vtkActor() link_actor.GetProperty().SetLineWidth(3) link_actor.GetProperty().SetLineStipplePattern(0xf0f0) link_actor.GetProperty().SetColor(0.3, 0.3, 0.3) link_actor.SetMapper(link_mapper) self.actor_list += [link_actor] if len(self.lattice) > 0: lattice_points = [np.zeros((3,), np.float)] for lv in self.lattice: lattice_points.append(lv) for i in range(3): for j in range(i+1, 3): lattice_points.append(self.lattice[i]+self.lattice[j]) lattice_points.append(sum(self.lattice)) lattice_points = np.array(lattice_points) if True: # Shift the box to put the origin at the center. # This should be made configurable through a menu. lattice_points -= 0.5*lattice_points[-1] box_points, _ = ndarray_to_vtkpoints(lattice_points) box_lines = np.array([[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 4], [2, 6], [3, 5], [3, 6], [4, 7], [5, 7], [6, 7]]) box_polydata = vtk.vtkPolyData() box_polydata.SetPoints(box_points) box_polydata.SetLines(ndarray_to_vtkcellarray(box_lines)) box_mapper = vtk.vtkPolyDataMapper() box_mapper.SetInput(box_polydata) box_actor = vtk.vtkActor() box_actor.GetProperty().SetLineWidth(3) box_actor.GetProperty().SetLineStipplePattern(0xaaaa) box_actor.GetProperty().SetColor(0.1, 0.1, 0.4) box_actor.SetMapper(box_mapper) self.actor_list += [box_actor] self.picking_domain = {LINES: line_actor, BALLS: ball_actor, STICKS: tube_actor, BALLS_AND_STICKS: ball_actor, BALLS_AND_LINES: ball_actor} \ [rendmod] assembly = vtk.vtkAssembly() for actor in self.actor_list: assembly.AddPart(actor) return assembly
def __init__(self, model, optim=None): self.model = model self.reset_pose_params() self._sequence = pose_sequence.PoseSequence() self.viewer = ezvtk.vis.Viewer() self.view_modes = [ EditBoneMode(self, model), EditGlobalMode(self, model), EditMarkerMode(self, model), BoxSelectMode(self, model), OptimizerMode(self, model, optim), ] # Add triangular mesh. self.mesh_troupe = ezvtk.troupe.MeshTroupe() self.surface_troupe = ezvtk.troupe.LoopSurfaceTroupe(color=SURFACE_COLOUR, opacity=SURFACE_OPACITY) self.surface_troupe.set_polygons(model.triangles) self.surface_troupe.set_visible(False) self.mesh_troupe.set_polygons(model.triangles) self.mesh_troupe.set_radius(3.0e-4) self.mesh_assembly = vtk.vtkAssembly() self.mesh_assembly.AddPart(self.mesh_troupe.actor) self.mesh_assembly.AddPart(self.surface_troupe.actor) # Also add points for easy picking with the mouse. self.vertices_troupe = ezvtk.troupe.SpheresTroupe(radius=1e-3) colors = np.empty((self.model.n_vertices, 3), dtype=np.uint8) colors[:, 0] = 51 colors[:, 1] = 128 colors[:, 2] = 179 for v in PALM_VERTICES: colors[v, :] = [255, 0, 0] # red vertices on palm self.vertices_troupe.set_sphere_colors(colors) self.mesh_assembly.AddPart(self.vertices_troupe.actor) # Markers self.markers_troupe = ezvtk.troupe.SpheresTroupe(radius=2e-3, color=MARKER_COLOUR, opacity=0.25) self.markers_troupe.set_pickable(False) self.mesh_assembly.AddPart(self.markers_troupe.actor) self.marker_targets_troupe = ezvtk.troupe.MultipleSphereActorsTroupe( color=MARKER_COLOUR, num_spheres=len(self.model.markers) ) self.marker_targets_troupe.set_pickable(False) self.marker_conn_troupe = ezvtk.troupe.TubesTroupe(color=MARKER_COLOUR) self.marker_conn_troupe.set_pickable(False) # Text troupes self.text_troupe = ezvtk.troupe.TextTroupe() self.global_pos_text_troupe = ezvtk.troupe.TextTroupe(relative_position=(1, 1), absolute_offset=(-10, -10)) self.global_pos_text_troupe.set_alignment("right") self.file_name_text_troupe = ezvtk.troupe.TextTroupe(relative_position=(0, 0), absolute_offset=(10, 20)) # Visualize box selection self.planes_troupe = ezvtk.troupe.PlanesTroupe(color=(1.0, 0.0, 0.0)) # Add these to the viewer. self.viewer.renderer.AddActor(self.mesh_assembly) self.viewer.add_troupes( self.marker_targets_troupe, self.marker_conn_troupe, self.planes_troupe, self.text_troupe, self.global_pos_text_troupe, self.file_name_text_troupe, ) self.point_cloud_troupe = None # Set up key callbacks ensure_mode = lambda m, f: f(self.view_modes[m]) if self.mode == m else self.change_mode(m) onlyif_mode = lambda m, f: f(self.view_modes[m]) if self.mode == m else None def jumpto_mode(m, f): if self.mode != m: self.change_mode(m) f(self.view_modes[m]) self.viewer.add_key_callback( "a", lambda: ensure_mode(ViewModes.EDIT_BONES, lambda m: EditBoneMode.change_i_bone_and_i_axis(m, -1, 0)) ) self.viewer.add_key_callback( "z", lambda: ensure_mode(ViewModes.EDIT_BONES, lambda m: EditBoneMode.change_i_bone_and_i_axis(m, 1, 0)) ) self.viewer.add_key_callback( "s", lambda: ensure_mode(ViewModes.EDIT_BONES, lambda m: EditBoneMode.change_i_bone_and_i_axis(m, 0, 1)) ) self.viewer.add_key_callback( "x", lambda: ensure_mode(ViewModes.EDIT_BONES, lambda m: EditBoneMode.change_i_bone_and_i_axis(m, 0, -1)) ) self.viewer.add_key_callback( "d", lambda: onlyif_mode(ViewModes.EDIT_BONES, lambda m: EditBoneMode.update_angle(m, DELTA)) ) self.viewer.add_key_callback( "e", lambda: onlyif_mode(ViewModes.EDIT_BONES, lambda m: EditBoneMode.update_angle(m, math.pi)) ) self.viewer.add_key_callback( "c", lambda: onlyif_mode(ViewModes.EDIT_BONES, lambda m: EditBoneMode.update_angle(m, -DELTA)) ) self.viewer.add_key_callback( "f", lambda: ensure_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.change_marker(m, -1)) ) self.viewer.add_key_callback( "v", lambda: ensure_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.change_marker(m, 1)) ) self.viewer.add_key_callback("h", lambda: self.change_marker_weight(10)) self.viewer.add_key_callback("n", lambda: self.change_marker_weight(0.1)) self.viewer.add_key_callback( "1", lambda: jumpto_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.jump_to_marker(m, "ThumbTip")) ) self.viewer.add_key_callback( "2", lambda: jumpto_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.jump_to_marker(m, "IndexTip")) ) self.viewer.add_key_callback( "3", lambda: jumpto_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.jump_to_marker(m, "MiddleTip")) ) self.viewer.add_key_callback( "4", lambda: jumpto_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.jump_to_marker(m, "RingTip")) ) self.viewer.add_key_callback( "5", lambda: jumpto_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.jump_to_marker(m, "PinkyTip")) ) self.viewer.add_key_callback( "r", lambda: onlyif_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.deactivate_marker(m)) ) self.viewer.add_key_callback( "u", lambda: onlyif_mode(ViewModes.EDIT_MARKER, lambda m: EditMarkerMode.set_marker_from_model(m)) ) self.viewer.add_key_callback("t", lambda: self.change_mode(ViewModes.EDIT_GLOBAL)) self.viewer.add_key_callback("o", self.start_optimizer) self.viewer.add_key_callback("m", self.toggle_meshview) self.viewer.add_key_callback( "b", lambda: None if self.point_cloud_troupe is None else self.change_mode(ViewModes.BOX_SELECT) ) self.viewer.add_key_callback("left", lambda: self.change_file(-1)) self.viewer.add_key_callback("right", lambda: self.change_file(1)) self.viewer.add_key_callback("i", lambda: self.viewer.pick(False)) self.viewer.add_key_callback("p", self.save_data) self.viewer.add_key_callback("f1", self.show_help) # Other callbacks self.viewer.add_pick_callback(self.pick) self.viewer.add_actor_move_callback(self.view_modes[ViewModes.EDIT_GLOBAL].global_transform_modified) self.viewer.add_box_select_callback(self.view_modes[ViewModes.BOX_SELECT].box_select_points) # Set initial state self.change_mode(ViewModes.EDIT_BONES) self.update_mesh()
def __init__ (self, jid): self.jid = jid self.height = 1.73 self.posTimeStamp = time.time() self.velocity = numpy.array([0.0, 0.0, 0.0]) self.axisOfRotation = "z" self.omega = 0.0 self.actors = {} self.joints = {} self.angles = {} self.bonelengths = {} self.microAnimation = 'breathing' # we don't want all the characters to be breathing exactly in sync, # so we need some random seeds that are unique per character self.seed1 = random.random() self.seed2 = random.random() self.seed3 = random.random() # How long are each of the bones? We need the distance from the fulcrum # of the parent joint to the fulcrum of the child joint. (The femur don't # make a straight line from hip to knee, but what we want here is the # straight line from the hip to the knee, for positioning and animation.) self.bonelengths['sternum'] = 0.22 self.bonelengths['left collarbone'] = 0.19 self.bonelengths['right collarbone'] = 0.19 self.bonelengths['left humerus'] = 0.28 self.bonelengths['right humerus'] = 0.28 self.bonelengths['left forearm'] = 0.26 self.bonelengths['right forearm'] = 0.26 self.bonelengths['left femur'] = 0.49 self.bonelengths['right femur'] = 0.49 self.bonelengths['left shin'] = 0.38 self.bonelengths['right shin'] = 0.38 # The positions of all the joints in the body (local coordinates): self.joints['heart'] = numpy.array([0.0, 0.0, 1.45]) self.joints['sternumTop'] = numpy.array([0.0, 0.03, 1.45]) self.joints['left sternCollar'] = numpy.array([-0.012, 0.03, 1.45]) self.joints['right sternCollar'] = numpy.array([0.012, 0.03, 1.45]) self.joints["left shoulder"] = numpy.array([-0.2, 0.0, 1.45]) self.joints["right shoulder"] = numpy.array([0.2, 0.0, 1.45]) self.joints['left elbow'] = numpy.array([0.0, 0.0, 0.0]) self.joints['right elbow'] = numpy.array([0.0, 0.0, 0.0]) self.joints['left wrist'] = numpy.array([0.0, 0.0, 0.0]) self.joints['right wrist'] = numpy.array([0.0, 0.0, 0.0]) self.joints['left hip'] = numpy.array([-0.12, 0.0, 0.96]) self.joints['right hip'] = numpy.array([0.12, 0.0, 0.96]) self.joints['left knee'] = numpy.array([0.0, 0.0, 0.0]) self.joints['right knee'] = numpy.array([0.0, 0.0, 0.0]) self.joints['left ankle'] = numpy.array([0.0, 0.0, 0.0]) self.joints['right ankle'] = numpy.array([0.0, 0.0, 0.0]) # Angles of joints. *These* angles are intended to be intuitive for # animators. It is the job of the programmer to translate these # angles into the local coordinates. # For knees and elbows: # 0.0 is fully extended # ~160 degrees is fully flexed (via the bicep, or hamstring) # negative numbers is hyper-extended self.angles['left elbow'] = 25.0 self.angles['right elbow'] = 17.0 self.angles['left knee'] = 0.0 self.angles['right knee'] = 32.0 # Create the "core" bones: filename = jvDataDir + 'Avatars/Human/index.xml' fd = open(filename, 'r') XMLstring = fd.read() fd.close() logging.debug("Human: Attempting to transform XML string") try: topElement = ET.fromstring(XMLstring) except: logging.error("MapReader: Failed to transform XML string") xmlConverter = XML2VTK(topElement, bonelengths = self.bonelengths) self.actors = xmlConverter.actors # Initial positions for the bones: self.actors["sternum"].SetPosition(self.joints['sternumTop']) self.actors["sternum"].SetOrientation(-90.0, 0.0, 0.0) self.actors["left collarbone"].SetPosition(self.joints['left sternCollar']) self.actors["left collarbone"].SetOrientation(0.0, 0.0, 95.0) self.actors["right collarbone"].SetPosition(self.joints['right sternCollar']) self.actors["right collarbone"].SetOrientation(0.0, 0.0, -95.0) #self.actors["left humerus"].SetPosition(self.joints['left shoulder']) #self.actors["left humerus"].SetOrientation(-75.0, 0.0, 0.0) #self.actors["right humerus"].SetPosition(self.joints['right shoulder']) #self.actors["right humerus"].SetOrientation(-110.0, 0.0, 0.0) self.actors['left femur'].SetPosition(self.joints['left hip']) self.actors['left femur'].SetOrientation(-90.0, 0.0, 0.0) self.actors['right femur'].SetPosition(self.joints['right hip']) self.actors['right femur'].SetOrientation(-90.0, 0.0, 0.0) # dynamic update self.UpdateAllJointsAndBones() # Bind everything into a single object for the viewer: self.assembly = vtk.vtkAssembly() for i in self.actors: self.actors[i].SetPickable(1) self.assembly.AddPart(self.actors[i])
def contour(vol,voxsz=(1.0,1.0,1.0),affine=None,levels=[50],colors=[np.array([1.0,0.0,0.0])],opacities=[0.5]): ''' Take a volume and draw surface contours for any any number of thresholds (levels) where every contour has its own color and opacity Parameters: ---------------- vol : array, shape (N, M, K) an array representing the volumetric dataset for which we will draw some beautiful contours . voxsz : sequence of 3 floats default (1., 1., 1.) affine : not used here levels : sequence of thresholds for the contours taken from image values needs to be same datatype as vol colors : array, shape (N,3) with the rgb values in where r,g,b belong to [0,1] opacities : sequence of floats [0,1] Returns: ----------- ass: assembly of actors representing the contour surfaces Examples: ------------- >>> import numpy as np >>> from dipy.viz import fos >>> A=np.zeros((10,10,10)) >>> A[3:-3,3:-3,3:-3]=1 >>> r=fos.ren() >>> fos.add(r,fos.contour(A,levels=[1])) >>> fos.show(r) ''' im = vtk.vtkImageData() im.SetScalarTypeToUnsignedChar() im.SetDimensions(vol.shape[0],vol.shape[1],vol.shape[2]) #im.SetOrigin(0,0,0) #im.SetSpacing(voxsz[2],voxsz[0],voxsz[1]) im.AllocateScalars() for i in range(vol.shape[0]): for j in range(vol.shape[1]): for k in range(vol.shape[2]): im.SetScalarComponentFromFloat(i,j,k,0,vol[i,j,k]) ass=vtk.vtkAssembly() #ass=[] for (i,l) in enumerate(levels): #print levels skinExtractor = vtk.vtkContourFilter() skinExtractor.SetInput(im) skinExtractor.SetValue(0, l) skinNormals = vtk.vtkPolyDataNormals() skinNormals.SetInputConnection(skinExtractor.GetOutputPort()) skinNormals.SetFeatureAngle(60.0) skinMapper = vtk.vtkPolyDataMapper() skinMapper.SetInputConnection(skinNormals.GetOutputPort()) skinMapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skinMapper) skin.GetProperty().SetOpacity(opacities[i]) print colors[i] skin.GetProperty().SetColor(colors[i][0],colors[i][1],colors[i][2]) #skin.Update() ass.AddPart(skin) del skin del skinMapper del skinExtractor #ass=ass+[skin] return ass
def make_pActor_with_quaternion(): pSource = vtk.vtkSphereSource() pSource.SetPhiResolution(20) pSource.SetThetaResolution(20) pGlyph = vtk.vtkGlyph3D() pGlyph.SetSource(pSource.GetOutput()) #pGlyph.ScalingOn() #pGlyph.SetScaleModeToScaleByScalar() pos = vtk.vtkPoints() pos.InsertNextPoint(0, 0, 0) pData = vtk.vtkPolyData() pData.SetPoints(pos) diameter = vtk.vtkDoubleArray() diameter.SetNumberOfComponents(1) diameter.InsertNextTuple1(2.0) pData.GetPointData().SetScalars(diameter) pGlyph.SetInput(pData) pNormals = vtk.vtkPolyDataNormals() pNormals.SetInput(pGlyph.GetOutput()) ########################################################################### # clip plane plane = vtk.vtkPlane() plane.SetOrigin(0, 0, 0) plane.SetNormal(0, 1, 0) # upper side clipper = vtk.vtkClipPolyData() clipper.SetInput(pNormals.GetOutput()) clipper.SetClipFunction(plane) clipper.GenerateClipScalarsOn() clipper.GenerateClippedOutputOn() clipper.SetValue(0) clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInput(clipper.GetOutput()) clipMapper.ScalarVisibilityOff() clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetColor(peacock) ########################################################################### # clipped part restMapper = vtk.vtkPolyDataMapper() restMapper.SetInput(clipper.GetClippedOutput()) restMapper.ScalarVisibilityOff() restActor = vtk.vtkActor() restActor.SetMapper(restMapper) restActor.GetProperty().SetColor(tomato) ########################################################################### # assembly assembly = vtk.vtkAssembly() assembly.AddPart(clipActor) assembly.AddPart(restActor) assembly.RotateX(90) return assembly
def InputSelectionCallback(self, caller, event): """This is the callback that tracks changes in the parallel coordinates chart selection (pedigree ids) and sets the input images for the image flow view accordingly. Note: The image_flow selection should always contain a selection node, but it will have no tuples in the selection list if the PC selection has been cleared. This new version for variable dimensionality inverts the image stacks so there is as list of stacks with one stack per scale.""" for prop in self.assemblyList: self.renderer.RemoveViewProp(prop) annSel = caller.GetCurrentSelection() # Note: When image_flow selection is cleared the current selection does NOT contain any tuples if annSel.GetNumberOfNodes() > 0: idxVtk = annSel.GetNode(0).GetSelectionList() if idxVtk.GetNumberOfTuples() > 0: # New selection list, so get new data idxArr = VN.vtk_to_numpy(idxVtk) print "Image Flow input to Nup Flow ", idxArr # Only allowing single index [0] # Returning a list of image stacks self.imStackList = self.ds.GetDetailImages(idxArr.tolist()[0]) self.imWeightArrList = self.ds.GetDetailWeights(idxArr.tolist()[0]) else: self.imStackList = self.blank_image_list self.imWeightArrList = self.blank_image_weights # Comment this out if we don't want the view resetting on empty selections # self.needToResetCamera = True # Check whether images in stack are RGB already self.RGB_images = False if self.imStackList[0].GetPointData().GetScalars().GetNumberOfComponents() > 1: self.RGB_images = True # Clear out scale ID map (I think this is just in case we need to reverse order...?) self.scale_dict = {} self.numScales = len(self.imStackList) # Directly accessing member variable for index in range(self.numScales): self.scale_dict[index] = index self.colorList = [] self.resliceList = [] self.assemblyList = [] self.numImagesList = [] # Here is where we have to do things in a new order since there is one # stack per scale, so can form assemblies directly instead of adding # to each assembly in order as we go through the stacks. for nn, imStack in enumerate(self.imStackList): imStack.UpdateInformation() (xMin, xMax, yMin, yMax, zMin, zMax) = imStack.GetWholeExtent() (xSpacing, ySpacing, zSpacing) = imStack.GetSpacing() (x0, y0, z0) = imStack.GetOrigin() center = [x0 + xSpacing * 0.5 * (xMin + xMax), y0 + ySpacing * 0.5 * (yMin + yMax), z0 + zSpacing * 0.5 * (zMin + zMax)] # Adjust a blue-white-red lookup table # NOTE: Only basing on single image stack for now... i_range = N.array(imStack.GetPointData().GetScalars().GetRange()) i_ext = abs(i_range.min()) if (abs(i_range.min()) > abs(i_range.max())) else abs(i_range.max()) if abs(i_range[1]-i_range[0]) < 1e-10: i_ext = 1024 self.lut.SetRange(-i_ext,i_ext) # self.lut.Build() # Map the image stack through the lookup table color = vtk.vtkImageMapToColors() if self.RGB_images: color.SetLookupTable(None) else: color.SetLookupTable(self.lut) color.SetInput(imStack) color.UpdateWholeExtent() # since extent of images might be changing color.Update() self.colorList.append(color) assembly = vtk.vtkAssembly() self.assemblyList.append(assembly) numImages = zMax-zMin+1 self.numImagesList.append(numImages) for ii in range(numImages): zpos = z0 + zSpacing*(zMin+ii) axial = vtk.vtkMatrix4x4() axial.DeepCopy((1, 0, 0, center[0], 0, 1, 0, center[1], 0, 0, 1, zpos, 0, 0, 0, 1)) # Extract a slice in the desired orientation reslice = vtk.vtkImageReslice() reslice.SetInputConnection(self.colorList[nn].GetOutputPort()) reslice.SetOutputDimensionality(2) reslice.SetResliceAxes(axial) reslice.SetInterpolationModeToNearestNeighbor() # NOTE: Only basing spacing on first stack if ii == 0 and nn == 0: reslice.Update() tmp = reslice.GetOutput().GetBounds() if self.FlowDirection == Direction.Horizontal: self.flowSpacing = float(tmp[1]-tmp[0])*1.1 self.nupSpacing = float(tmp[3]-tmp[2])*1.1 else: self.flowSpacing = float(tmp[3]-tmp[2])*1.1 self.nupSpacing = float(tmp[1]-tmp[0])*1.1 sliceSpacing = reslice.GetOutput().GetSpacing()[2] # Not going to access these later, just keeping around so they # won't be garbage collected self.resliceList.append(reslice) # Create a list of actors with each image already assigned actor = vtk.vtkImageActor() actor.SetInput(self.resliceList[sum(self.numImagesList[:nn]) + ii].GetOutput()) # NOTE: Fragile test for blank image if imStack.GetPointData().GetScalars().GetName() == 'PNGImage': actor.SetPickable(False) else: actor.SetPickable(True) # Set opacity according to relative magnitude of abs(wavelet coeff) actor.SetOpacity(self.imWeightArrList[nn][ii]) if self.FlowDirection == Direction.Horizontal: actor.SetPosition(0, ii*self.nupSpacing, 0) else: actor.SetPosition(ii*self.nupSpacing, 0, 0) self.assemblyList[nn].AddPart(actor) # Adding assemblies to renderer after all completed for ii in range(self.numScales): self.renderer.AddActor(self.assemblyList[ii]) # Seems to work best if I set a temporary bounds here and don't do it again self.highlightRect.SetBounds(self.assemblyList[0].GetBounds()) # Get the current scale, if there is one, from the output_link selection list # scaleSel = self.output_link.GetCurrentSelection() # Note: Empty selection should still contain a node, but no tuples # if (scaleSel.GetNumberOfNodes() > 0) and (scaleSel.GetNode(0).GetSelectionList().GetNumberOfTuples() > 0): # # This should only contain a single value or none # scaleVal = scaleSel.GetNode(0).GetSelectionList().GetValue(0) # else: # scaleVal = -1 # # if (scaleVal > 0) and (scaleVal < len(self.assemblyList)): # self.highlightRect.SetBounds(self.assemblyList[scaleVal].GetBounds()) # self.highlightActor.SetOrientation(self.assemblyList[scaleVal].GetOrientation()) # tmpPos = self.assemblyList[scaleVal].GetPosition() # usePos = (tmpPos[0],tmpPos[1],tmpPos[2]+0.01) # self.highlightActor.SetPosition(usePos) # self.highlightIndex = scaleVal # self.highlightActor.SetPickable(False) # self.highlightActor.SetVisibility(True) # else: # self.highlightRect.SetBounds(self.assemblyList[0].GetBounds()) # self.highlightActor.SetOrientation(self.assemblyList[0].GetOrientation()) # tmpPos = self.assemblyList[0].GetPosition() # usePos = (tmpPos[0],tmpPos[1],tmpPos[2]+0.01) # self.highlightActor.SetPosition(usePos) # self.highlightIndex = -1 # self.highlightActor.SetPickable(False) # self.highlightActor.SetVisibility(False) # Create the slider which will control the image positions self.sliderRep.SetMinimumValue(0) self.sliderRep.SetMaximumValue(self.numScales-1) # self.sliderRep.SetValue(0) # self.sliderRep.SetValue(self.prevSliderValue) # In case prev value was greater than max # self.prevSliderValue = int(self.sliderRep.GetValue()) # Now assign initial positions to the actors self.setImagesPosition(self.prevSliderValue) if self.needToResetCamera: # Camera reset based on height, not width... # (Xmin0,Xmax0,Ymin0,Ymax0,Zmin0,Zmax0) = self.assemblyList[0].GetBounds() (Xmin0,Xmax0,Ymin0,Ymax0,Zmin0,Zmax0) = self.assemblyList[self.prevSliderValue].GetBounds() (Xmin1,Xmax1,Ymin1,Ymax1,Zmin1,Zmax1) = self.assemblyList[-1].GetBounds() # eps = (Ymax0-Ymin1)*0.1 eps = (Ymax0-Ymin0)*2.0 # Scale for height of whole thing # self.renderer.ResetCamera(Xmin0,Xmax0,Ymin1-eps,Ymax0+eps,Zmin0,Zmax0) # Scale for width of one element # self.renderer.ResetCamera(self.assemblyList[self.prevSliderValue].GetBounds()) self.renderer.ResetCamera(Xmin0,Xmax0,Ymin0-eps,Ymax0+eps,Zmin0,Zmax0) # self.cam.Elevation(10) self.renderer.ResetCameraClippingRange() # NOTE: Fragile test for blank image if imStack.GetPointData().GetScalars().GetName() == 'PNGImage': self.needToResetCamera = False else: self.needToResetCamera = False # Use output_link callback to update highlight properly self.ScaleSelectionCallback() if event is not None: self.window.Render() else: # If there is no SelectionNode in PC selection -- shouldn't reach here... print "PC no selection node to image flow called"
cone = vtk.vtkConeSource() coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.SetPosition(0, 0, 0.25) coneActor.GetProperty().SetColor(0, 1, 0) cylinder = vtk.vtkCylinderSource() cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.GetProperty().SetColor(1, 0, 0) assembly = vtk.vtkAssembly() assembly.AddPart(cylinderActor) assembly.AddPart(sphereActor) assembly.AddPart(cubeActor) assembly.AddPart(coneActor) assembly.SetOrigin(5, 10, 15) assembly.AddPosition(5, 0, 0) assembly.RotateX(15) # Add the actors to the renderer, set the background and size ren1 = vtk.vtkRenderer() ren1.AddActor(assembly) ren1.AddActor(coneActor) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1)
def contour_smooth(vol, voxsz=(1.0, 1.0, 1.0), affine=None, levels=[50], colors=[np.array([1.0, 0.0, 0.0])], opacities=[0.5], smoothing=10): """ Take a volume and draw surface contours for any any number of thresholds (levels) where every contour has its own color and opacity Parameters ---------- vol : (N, M, K) ndarray An array representing the volumetric dataset for which we will draw some beautiful contours . voxsz : (3,) array_like Voxel size. affine : None Not used. levels : array_like Sequence of thresholds for the contours taken from image values needs to be same datatype as `vol`. colors : (N, 3) ndarray RGB values in [0,1]. opacities : array_like Opacities of contours. Returns ------- vtkAssembly Examples -------- >>> import numpy as np >>> from dipy.viz import fvtk >>> A=np.zeros((10,10,10)) >>> A[3:-3,3:-3,3:-3]=1 >>> r=fvtk.ren() >>> fvtk.add(r,fvtk.contour(A,levels=[1])) >>> #fvtk.show(r) """ major_version = vtk.vtkVersion.GetVTKMajorVersion() im = vtk.vtkImageData() if major_version <= 5: im.SetScalarTypeToUnsignedChar() im.SetDimensions(vol.shape[0], vol.shape[1], vol.shape[2]) # im.SetOrigin(0,0,0) # im.SetSpacing(voxsz[2],voxsz[0],voxsz[1]) if major_version <= 5: im.AllocateScalars() else: im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 3) for i in range(vol.shape[0]): for j in range(vol.shape[1]): for k in range(vol.shape[2]): im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k]) ass = vtk.vtkAssembly() # ass=[] for (i, l) in enumerate(levels): # print levels skinExtractor = vtk.vtkContourFilter() if major_version <= 5: skinExtractor.SetInput(im) else: skinExtractor.SetInputData(im) skinExtractor.SetValue(0, l) # # Smoothing # Taken from: https://lorensen.github.io/VTKExamples/site/Python/MeshLabelImageColor/ # smoother = vtk.vtkWindowedSincPolyDataFilter() if vtk.VTK_MAJOR_VERSION <= 5: smoother.SetInput(skinExtractor.GetOutput()) else: smoother.SetInputConnection(skinExtractor.GetOutputPort()) smoother.SetNumberOfIterations(smoothing) # 30 # this has little effect on the error! # smoother.BoundarySmoothingOff() # smoother.FeatureEdgeSmoothingOff() # smoother.SetFeatureAngle(120.0) # smoother.SetPassBand(.001) #this increases the error a lot! smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.GenerateErrorScalarsOn() # smoother.GenerateErrorVectorsOn() smoother.Update() skinNormals = vtk.vtkPolyDataNormals() skinNormals.SetInputConnection(smoother.GetOutputPort()) skinNormals.SetFeatureAngle(60.0) # No Smoothing # skinNormals = vtk.vtkPolyDataNormals() # skinNormals.SetInputConnection(skinExtractor.GetOutputPort()) # skinNormals.SetFeatureAngle(60.0) skinMapper = vtk.vtkPolyDataMapper() skinMapper.SetInputConnection(skinNormals.GetOutputPort()) skinMapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skinMapper) skin.GetProperty().SetOpacity(opacities[i]) # print colors[i] skin.GetProperty().SetColor(colors[i][0], colors[i][1], colors[i][2]) # skin.Update() ass.AddPart(skin) del skin del skinMapper del skinExtractor return ass
actor1 = vtk.vtkActor() actor1.SetMapper(mapper1) actor2 = vtk.vtkActor() actor2.SetMapper(mapper2) actor3 = vtk.vtkActor() actor3.SetMapper(mapper3) actor5 = vtk.vtkActor() actor5.SetMapper(mapper5) actor6 = vtk.vtkActor() actor6.SetMapper(mapper6) actor7 = vtk.vtkActor() actor7.SetMapper(mapper7) # assembly actor6 and actor7 assembly = vtk.vtkAssembly() assembly.AddPart(actor6) assembly.AddPart(actor7) assembly.SetOrigin(actor6.GetCenter()) # Setup a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) #Add the actor to the scene renderer.AddActor(actor1) renderer.AddActor(actor2) renderer.AddActor(actor3)
cubeActor.GetProperty().SetColor(0,0,1) cone = vtk.vtkConeSource() coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.SetPosition(0,0,.25) coneActor.GetProperty().SetColor(0,1,0) cylinder = vtk.vtkCylinderSource() #top part cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.GetProperty().SetColor(1,0,0) compositeAssembly = vtk.vtkAssembly() compositeAssembly.AddPart(cylinderActor) compositeAssembly.AddPart(sphereActor) compositeAssembly.AddPart(cubeActor) compositeAssembly.AddPart(coneActor) compositeAssembly.SetOrigin(5,10,15) compositeAssembly.AddPosition(5,0,0) compositeAssembly.RotateX(15) # Build the prop assembly out of a vtkActor and a vtkAssembly assembly = vtk.vtkPropAssembly() assembly.AddPart(compositeAssembly) assembly.AddPart(coneActor) # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow()