def initArea(self): ''' Sets up the VTK simulation area :return:None ''' self.actors_dict = {} self.actorCollection=vtk.vtkActorCollection() self.borderActor = vtk.vtkActor() self.borderActorHex = vtk.vtkActor() self.clusterBorderActor = vtk.vtkActor() self.clusterBorderActorHex = vtk.vtkActor() self.cellGlyphsActor = vtk.vtkActor() self.FPPLinksActor = vtk.vtkActor() # used for both white and colored links self.outlineActor = vtk.vtkActor() # self.axesActor = vtk.vtkCubeAxesActor2D() self.axesActor = vtk.vtkCubeAxesActor() self.outlineDim=[0,0,0] self.cellsActor = vtk.vtkActor() self.cellsActor.GetProperty().SetInterpolationToFlat() # ensures that pixels are drawn exactly not with interpolations/antialiasing self.hexCellsActor = vtk.vtkActor() self.hexCellsActor.GetProperty().SetInterpolationToFlat() # ensures that pixels are drawn exactly not with interpolations/antialiasing self.conActor = vtk.vtkActor() self.conActor.GetProperty().SetInterpolationToFlat() self.hexConActor = vtk.vtkActor() self.hexConActor.GetProperty().SetInterpolationToFlat() self.contourActor = vtk.vtkActor() self.glyphsActor=vtk.vtkActor() #self.linksActor=vtk.vtkActor() # # Concentration lookup table self.clut = vtk.vtkLookupTable() self.clut.SetHueRange(0.67, 0.0) self.clut.SetSaturationRange(1.0,1.0) self.clut.SetValueRange(1.0,1.0) self.clut.SetAlphaRange(1.0,1.0) self.clut.SetNumberOfColors(1024) self.clut.Build() # Contour lookup table # Do I need lookup table? May be just one color? self.ctlut = vtk.vtkLookupTable() self.ctlut.SetHueRange(0.6, 0.6) self.ctlut.SetSaturationRange(0,1.0) self.ctlut.SetValueRange(1.0,1.0) self.ctlut.SetAlphaRange(1.0,1.0) self.ctlut.SetNumberOfColors(1024) self.ctlut.Build()
def main(): filename = get_program_parameters() colors = vtk.vtkNamedColors() renderer = vtk.vtkRenderer() render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window_interactor = vtk.vtkRenderWindowInteractor() render_window_interactor.SetRenderWindow(render_window) # VRML Import importer = vtk.vtkVRMLImporter() importer.SetFileName(filename) importer.SetRenderWindow(render_window) importer.Update() actors = vtk.vtkActorCollection() actors = renderer.GetActors() print("There are", actors.GetNumberOfItems(), "actors") renderer.SetBackground(colors.GetColor3d("Burlywood")) render_window.SetSize(512, 512) render_window.Render() render_window_interactor.Start()
def initArea(self): ''' Sets up the VTK simulation area :return:None ''' self.actors_dict = {} self.actorCollection = vtk.vtkActorCollection() self.borderActor = vtk.vtkActor() self.borderActorHex = vtk.vtkActor() self.clusterBorderActor = vtk.vtkActor() self.clusterBorderActorHex = vtk.vtkActor() self.cellGlyphsActor = vtk.vtkActor() self.FPPLinksActor = vtk.vtkActor( ) # used for both white and colored links self.outlineActor = vtk.vtkActor() # self.axesActor = vtk.vtkCubeAxesActor2D() self.axesActor = vtk.vtkCubeAxesActor() self.outlineDim = [0, 0, 0] self.cellsActor = vtk.vtkActor() self.cellsActor.GetProperty().SetInterpolationToFlat( ) # ensures that pixels are drawn exactly not with interpolations/antialiasing self.hexCellsActor = vtk.vtkActor() self.hexCellsActor.GetProperty().SetInterpolationToFlat( ) # ensures that pixels are drawn exactly not with interpolations/antialiasing self.conActor = vtk.vtkActor() self.conActor.GetProperty().SetInterpolationToFlat() self.hexConActor = vtk.vtkActor() self.hexConActor.GetProperty().SetInterpolationToFlat() self.contourActor = vtk.vtkActor() self.glyphsActor = vtk.vtkActor() #self.linksActor=vtk.vtkActor() # # Concentration lookup table self.clut = vtk.vtkLookupTable() self.clut.SetHueRange(0.67, 0.0) self.clut.SetSaturationRange(1.0, 1.0) self.clut.SetValueRange(1.0, 1.0) self.clut.SetAlphaRange(1.0, 1.0) self.clut.SetNumberOfColors(1024) self.clut.Build() # Contour lookup table # Do I need lookup table? May be just one color? self.ctlut = vtk.vtkLookupTable() self.ctlut.SetHueRange(0.6, 0.6) self.ctlut.SetSaturationRange(0, 1.0) self.ctlut.SetValueRange(1.0, 1.0) self.ctlut.SetAlphaRange(1.0, 1.0) self.ctlut.SetNumberOfColors(1024) self.ctlut.Build()
def main(): filename_obj, filename_mtl, texturepath = get_program_parameters() importer = vtk.vtkOBJImporter() importer.SetFileName(filename_obj) importer.SetFileNameMTL(filename_mtl) importer.SetTexturePath(texturepath) colors = vtk.vtkNamedColors() renderer = vtk.vtkRenderer() render_window = vtk.vtkRenderWindow() render_window_interactor = vtk.vtkRenderWindowInteractor() renderer.SetBackground2(colors.GetColor3d("Silver")) renderer.SetBackground(colors.GetColor3d("Gold")) renderer.GradientBackgroundOn() render_window.AddRenderer(renderer) renderer.UseHiddenLineRemovalOn() render_window.AddRenderer(renderer) render_window.SetSize(640, 480) render_window_interactor.SetRenderWindow(render_window) importer.SetRenderWindow(render_window) importer.Update() actors = vtk.vtkActorCollection() actors = renderer.GetActors() actors.InitTraversal() print("There are", actors.GetNumberOfItems(), "actors") for a in range(0, actors.GetNumberOfItems()): print(importer.GetOutputDescription(a)) actor = actors.GetNextActor() # OBJImporter turns texture interpolation off if actor.GetTexture(): print("Hastexture\n") actor.GetTexture().InterpolateOn() pd = actor.GetMapper().GetInput() clean = vtk.vtkCleanPolyData() clean.SetInputData(pd) clean.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputData(pd) normals.SplittingOff() normals.ConsistencyOn() normals.Update() mapper = actor.GetMapper() mapper.SetInputData(normals.GetOutput()) mapper.SetInputData(pd) render_window.Render() render_window_interactor.Start()
def __init__(self, element_id, position, no_pick=True): super().__init__() self.no_pick = no_pick self.cell_id = 0 self.points = vtk.vtkPoints() self.points.SetNumberOfPoints(1) self.points.SetPoint(0, position) actor = FakeActor(element_id) self.actors = vtk.vtkActorCollection() self.actors.AddItem(actor)
def event_type(self, clean_level, clean_dict=None): for tel_id in self.tel_ids: telescope = self.event.inst.subarray.tel[tel_id] # tel_coords = self.event.inst.subarray.tel_coords tel_x_pos = self.tel_coords[tel_id].x.to_value(u.m) tel_y_pos = self.tel_coords[tel_id].y.to_value(u.m) tel_z_pos = self.tel_coords[tel_id].z.to_value(u.m) camera_actor = camera_structure(self.event, tel_id, clean_level, clean_dict) camera_frame_actor = camera_frame(telescope.camera.cam_id) actorCollection = vtk.vtkActorCollection() actorCollection.AddItem(camera_actor) actorCollection.AddItem(camera_frame_actor) if telescope.optics.name == "LST": CSS_LST_actor = LST_tel_structure() mirror_plate_actor = LST_create_mirror_plane() actorCollection.AddItem(mirror_plate_actor) actorCollection.AddItem(CSS_LST_actor) elif telescope.optics.name == "MST": MST_mirror_plate_actor = MST_create_mirror_plane() MST_tel_structure_actor = MST_tel_structure() actorCollection.AddItem(MST_mirror_plate_actor) actorCollection.AddItem(MST_tel_structure_actor) elif telescope.optics.name == 'SST': SST_primary_mirror_plane_actor = SST_primary_mirror_plane() SST_tel_structure_actor = SST_tel_structure() actorCollection.AddItem(SST_primary_mirror_plane_actor) actorCollection.AddItem(SST_tel_structure_actor) actorCollection.InitTraversal() transform = vtk.vtkTransform() transform.PostMultiply() transform.RotateY(-self.pointing[tel_id]['alt']) transform.Translate(tel_x_pos, tel_y_pos, tel_z_pos) for a in range(actorCollection.GetNumberOfItems()): actor = actorCollection.GetNextActor() actor.SetUserTransform(transform) self.tel_id[tel_id].append(actor)
def iniVTK(self): self.last_added_sphere_ren1 = None self.newed_spheres = vtk.vtkCollection() self.sphere_radius_ren1 = 2.0 self.bouttons_spheres = [] self.slice_assembly = None self.image_roi = None self.im_importer = vtk.vtkImageImport() self.sphere = vtk.vtkSphereSource() self.sphere.SetRadius(2.0) self.sphere_mapper = vtk.vtkPolyDataMapper() self.sphere_mapper.SetInputConnection(self.sphere.GetOutputPort()) self.sphere_actor_ren2 = vtk.vtkActor() self.sphere.SetCenter(show_height / 2, show_width / 2, 0) self.sphere_actor_ren2.SetMapper(self.sphere_mapper) self.sphere_actor_ren2.GetProperty().SetColor(255.0, 0, 0) self.vtk_widget.GetRenderWindow().SetSize(800, 400) self.image_actor = vtk.vtkImageActor() self.ren1 = vtk.vtkRenderer() self.ren2 = vtk.vtkRenderer() self.interactorStyle = BouttonInteractorStyle() self.vtk_widget.SetInteractorStyle(self.interactorStyle) self.vtk_widget.GetRenderWindow().AddRenderer(self.ren1) self.vtk_widget.GetRenderWindow().AddRenderer(self.ren2) self.ren1.SetViewport(0.0, 0.0, 0.5, 1.0) self.ren2.SetViewport(0.5, 0.0, 1.0, 1.0) self.ren2.AddActor(self.sphere_actor_ren2) self.imageLevelFilter = vtk.vtkImageMapToWindowLevelColors() self.imageLevelFilter.SetLevel(400) self.imageLevelFilter.SetWindow(800) self.im_importer.SetNumberOfScalarComponents(1) self.im_importer.SetDataScalarTypeToUnsignedShort() self.im_importer.SetDataExtent(0, show_width - 1, 0, show_height - 1, 0, 0) self.im_importer.SetWholeExtent(0, show_width - 1, 0, show_height - 1, 0, 0) self.imageLevelFilter.SetInputConnection( self.im_importer.GetOutputPort()) self.image_actor.SetInput(self.imageLevelFilter.GetOutput()) self.ren1_sphere_actors = vtk.vtkActorCollection() self.pointPicker = vtk.vtkPointPicker() self.actorPicker = vtk.vtkPropPicker() self.pickedActor = None self.ren1.AddActor(self.image_actor) self.ren2.AddActor(self.image_actor)
def __GroupChannelAdd(self): """ Populate the electrode's actor collection with channel properties from list-dictionary """ # Reset the actor collection for adding the new actors. self.channelActors = vtk.vtkActorCollection() # Run through each channel and add a new actor for each loaded chan # Info was stored as strings, needs to be converted back to float for chan in self.channelInfo: nextLoadActor = self.AddChannelRepresentationActor(\ float(chan[self.channelProperties[1]]),\ float(chan[self.channelProperties[2]]),\ float(chan[self.channelProperties[3]]),\ float(chan[self.channelProperties[4]]),\ float(chan[self.channelProperties[5]]),\ float(chan[self.channelProperties[6]]))
def __init__(self, planeWidget, owner, orientation, imageData=None): print "PlaneWidgetObserver.__init__(): orientation=",orientation MarkerWindowInteractor.__init__(self) self.interactButtons = (1,2,3) self.pw = planeWidget self.owner = owner self.orientation = orientation self.observer = vtk.vtkImagePlaneWidget() self.camera = self.renderer.GetActiveCamera() self.ringActors = vtk.vtkActorCollection() self.defaultRingLine = 1 self.textActors = {} self.hasData = 0 self.set_image_data(imageData) self.lastTime = 0 self.set_mouse1_to_move()
def __init__(self, planeWidget, owner, orientation, imageData=None): print "PlaneWidgetObserver.__init__(): orientation=", orientation MarkerWindowInteractor.__init__(self) self.interactButtons = (1, 2, 3) self.pw = planeWidget self.owner = owner self.orientation = orientation self.observer = vtk.vtkImagePlaneWidget() self.camera = self.renderer.GetActiveCamera() self.ringActors = vtk.vtkActorCollection() self.defaultRingLine = 1 self.textActors = {} self.hasData = 0 self.set_image_data(imageData) self.lastTime = 0 self.set_mouse1_to_move()
def iniVTK(self): self.last_added_sphere_ren1 = None self.newed_spheres = vtk.vtkCollection() self.sphere_radius_ren1 = 2.0 self.bouttons_spheres = [] self.slice_assembly = None self.image_roi = None self.im_importer = vtk.vtkImageImport() self.sphere = vtk.vtkSphereSource() self.sphere.SetRadius(2.0) self.sphere_mapper = vtk.vtkPolyDataMapper() self.sphere_mapper.SetInputConnection(self.sphere.GetOutputPort()) self.sphere_actor_ren2 = vtk.vtkActor() self.sphere.SetCenter(show_height / 2, show_width / 2, 0) self.sphere_actor_ren2.SetMapper(self.sphere_mapper) self.sphere_actor_ren2.GetProperty().SetColor(255.0, 0, 0) self.vtk_widget.GetRenderWindow().SetSize(800, 400) self.image_actor = vtk.vtkImageActor() self.ren1 = vtk.vtkRenderer() self.ren2 = vtk.vtkRenderer() self.interactorStyle = BouttonInteractorStyle() self.vtk_widget.SetInteractorStyle(self.interactorStyle) self.vtk_widget.GetRenderWindow().AddRenderer(self.ren1) self.vtk_widget.GetRenderWindow().AddRenderer(self.ren2) self.ren1.SetViewport(0.0, 0.0, 0.5, 1.0) self.ren2.SetViewport(0.5, 0.0, 1.0, 1.0) self.ren2.AddActor(self.sphere_actor_ren2) self.imageLevelFilter = vtk.vtkImageMapToWindowLevelColors() self.imageLevelFilter.SetLevel(400) self.imageLevelFilter.SetWindow(800) self.im_importer.SetNumberOfScalarComponents(1) self.im_importer.SetDataScalarTypeToUnsignedShort() self.im_importer.SetDataExtent(0, show_width - 1, 0, show_height - 1, 0, 0) self.im_importer.SetWholeExtent(0, show_width - 1, 0, show_height - 1, 0, 0) self.imageLevelFilter.SetInputConnection(self.im_importer.GetOutputPort()) self.image_actor.SetInput(self.imageLevelFilter.GetOutput()) self.ren1_sphere_actors = vtk.vtkActorCollection() self.pointPicker = vtk.vtkPointPicker() self.actorPicker = vtk.vtkPropPicker() self.pickedActor = None self.ren1.AddActor(self.image_actor) self.ren2.AddActor(self.image_actor)
def __init__(self): """ Set a particular cursor for mapping channels for this electrode, and initialize actor collections and actor property lists """ # Set the electrode placement cursor self.channelCursor = self.__CreateChannelRepresentationActor() self.channelCursor.GetProperty().SetColor(0, 1, 0) self.channelCursor.PickableOff() # Instantiate an collection for positioned channel actors self.channelActors = vtk.vtkActorCollection() # Instantiate a dictionary list to hold information mapped channel info self.channelInfo = [] self.channelProperties = ['channelID',\ 'x_coor',\ 'y_coor',\ 'z_coor',\ 'red_px',\ 'grn_px',\ 'blu_px']
def __init__(self): ''' Constructor ''' self.__Type = self.VTK_META_UNKNOWN self.__pickedPointId = -1 #int self.__PickedCellId = -1 #int self.__DataSet = 0 #vtkDataSet self.__ActorList = vtk.vtkActorCollection() #vtkDataArrayCollection self.__Time = -1 #double self.__Property = 0 #vtkObject self.__ArrayCollection = vtk.vtkDataArrayCollection() #vtkDataArrayCollection self.__CurrentScalarArray = 0 #vtkDataArray self.__Name = "" #string self.__FilePath = "" #string self.__Tag = "" #string self.__Lock = 0 #int self.__MetaDataDictionary = None #itk.MetaDataDictionary self.__WirePolyData = None #vtkPolyData self.Initialize()
class EventHandler: __sharedState = {} markers = vtk.vtkActorCollection() defaultColor = (0,0,1) labelsOn = 1 observers = {} selected = {} __NiftiQForm=None __NiftiSpacings=(1.0,1.0,1.0) def __init__(self): self.__dict__ = self.__sharedState def add_selection(self, marker): self.selected[marker] = 1 self.notify('select marker', marker) def remove_selection(self, marker): if self.selected.has_key(marker): del self.selected[marker] self.notify('unselect marker', marker) def select_new(self, marker): for oldMarker in self.selected.keys(): self.remove_selection(oldMarker) self.add_selection(marker) def add_marker(self, marker): # break undo cycle func, args = UndoRegistry().get_last_pop() #print 'add', func, args if len(args)==0 or \ (func, args[0]) != (self.add_marker, marker): UndoRegistry().push_command(self.remove_marker, marker) self.markers.AddItem(marker) self.notify('add marker', marker) def remove_marker(self, marker): # break undo cycle func, args = UndoRegistry().get_last_pop() #print 'remove', func, args if len(args)==0 or \ (func, args[0]) != (self.remove_marker, marker): UndoRegistry().push_command(self.add_marker, marker) self.markers.RemoveItem(marker) self.notify('remove marker', marker) def get_markers(self): return self.markers def get_markers_as_seq(self): numMarkers = self.markers.GetNumberOfItems() self.markers.InitTraversal() return [self.markers.GetNextActor() for i in range(numMarkers)] def set_default_color(self, color): self.defaultColor = color def get_default_color(self): return self.defaultColor def save_markers_as(self, fname): self.markers.InitTraversal() numMarkers = self.markers.GetNumberOfItems() lines = []; conv_lines = [] #self.printTalairachResults() for i in range(numMarkers): marker = self.markers.GetNextActor() if marker is None: continue else: #XXX if self.__Nifti: if self.__NiftiQForm is not None: conv_marker=marker.convert_coordinates(self.__NiftiQForm,self.__NiftiSpacings) #XXX conv_marker=marker.convert_coordinates(QForm) center = conv_marker.get_center() request = "1,%i,%i,%i" % (int(center[0]),int(center[1]),int(center[2])) result=self.query_talairach(request) conv_lines.append("%.3f, %.3f, %.3f, %s"%(center[0],center[1],center[2],result)) lines.append(marker.to_string()) lines.sort() fh = file(fname, 'w') fh.write('\n'.join(lines) + '\n') if self.__NiftiQForm is not None: fn = file(fname+".conv", 'w') #only needed for nifti, but what the hell conv_lines.sort() fn.write('\n'.join(conv_lines) + '\n') def query_talairach(self, request): sock = socket.socket() sock.connect(("talairach.org",1600)) sock.settimeout(10.0) sock.send(request) res = sock.recv(1000) #print "res=", res return res def printTalairachResults(self): """For testing: query talairach-daemon and print results""" self.markers.InitTraversal() numMarkers = self.markers.GetNumberOfItems() for i in range(numMarkers): marker = self.markers.GetNextActor() if marker is None: continue if self.__NiftiQForm is not None: conv_marker=marker.convert_coordinates(self.__NiftiQForm,self.__NiftiSpacings) center = conv_marker.get_center() request = "1,%i,%i,%i" % (int(center[0]),int(center[1]),int(center[2])) if debug: print "Marker", center, ":", self.query_talairach(request) def setNifti(self,QForm,spacings): self.__NiftiQForm=QForm self.__NiftiSpacings=spacings def set_vtkactor(self, vtkactor): if debug: print "EventHandler.set_vtkactor()" self.vtkactor = vtkactor def save_registration_as(self, fname): if debug: print "EventHandler.save_registration_as(", fname,")" fh = file(fname, 'w') # XXX mcc: somehow get the transform for the VTK actor. aiieeee #xform = self.vtkactor.GetUserTransform() loc = self.vtkactor.GetOrigin() pos = self.vtkactor.GetPosition() scale = self.vtkactor.GetScale() mat = self.vtkactor.GetMatrix() orient = self.vtkactor.GetOrientation() if debug: print "EventHandler.save_registration_as(): vtkactor has origin, pos, scale, mat, orient=", loc, pos, scale, mat, orient, "!!" def vtkmatrix4x4_to_array(vtkmat): scipy_array = zeros((4,4), 'd') for i in range(0,4): for j in range(0,4): scipy_array[i][j] = mat.GetElement(i,j) return scipy_array scipy_mat = vtkmatrix4x4_to_array(mat) pickle.dump(scipy_mat, fh) fh.close() def load_markers_from(self, fname): self.notify('render off') for line in file(fname, 'r'): marker = Marker.from_string(line) self.add_marker(marker) self.notify('render on') UndoRegistry().flush() def attach(self, observer): self.observers[observer] = 1 def detach(self, observer): try: del self.observers[observer] except KeyError: pass def notify(self, event, *args): for observer in self.observers.keys(): if debug: print "EventHandler.notify(", event, "): calling update_viewer for ", observer observer.update_viewer(event, *args) def get_labels_on(self): return self.labelsOn def set_labels_on(self): self.labelsOn = 1 self.notify('labels on') def set_labels_off(self): self.labelsOn = 0 self.notify('labels off') def is_selected(self, marker): return self.selected.has_key(marker) def get_selected(self): return self.selected.keys() def get_num_selected(self): return len(self.selected)
def main(): filename = get_program_parameters() colors = vtk.vtkNamedColors() print("Reading " + filename) renderer = vtk.vtkRenderer() render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window_interactor = vtk.vtkRenderWindowInteractor() render_window_interactor.SetRenderWindow(render_window) # VRML Import importer = vtk.vtkVRMLImporter() importer.SetFileName(filename) importer.SetRenderWindow(render_window) importer.Update() actors = vtk.vtkActorCollection() actors = renderer.GetActors() print("There are", actors.GetNumberOfItems(), "actors") actors.InitTraversal() for a in range(0, actors.GetNumberOfItems()): actor = actors.GetNextActor() # The importer shininess parameter is between 0 and 1. VTK specular power is usually 10 - 100. # Also, the default for the specular factor for VRML is 1, while VTK's # is 0 specular_power = actor.GetProperty().GetSpecularPower() if specular_power <= 1.0: actor.GetProperty().SetSpecularPower(specular_power * 128.0) specular = actor.GetProperty().GetSpecular() if specular == 0.0: actor.GetProperty().SetSpecular(1.0) # if 0 # The VRML default ambient intensity is .2 ambient_intensity = actor.GetProperty().GetAmbient() if ambient_intensity == 0.0: actor.GetProperty().SetAmbient(.2) # endif mapper = actor.GetMapper() if (mapper): data_set = mapper.GetInput() if not data_set.GetPointData().GetNormals(): normals = vtk.vtkPolyDataNormals() normals.SetInputData(data_set) normals.SplittingOff() normals.Update() mapper.SetInputData(normals.GetOutput()) # If there is a lookup table, convert it to point data lut = mapper.GetLookupTable() if lut and mapper.GetScalarVisibility(): pc = vtk.vtkUnsignedCharArray() pc.SetNumberOfComponents(4) pc.SetNumberOfTuples(lut.GetNumberOfColors()) for t in range(0, lut.GetNumberOfColors()): lutc = lut.GetTableValue(t) lutuc = ['', '', '', ''] lut.GetColorAsUnsignedChars(lutc, lutuc) pc.SetTypedTuple(t, lutuc) mapper.SetLookupTable(None) mapper.GetInput().GetPointData().SetScalars(pc) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.GetActiveCamera().Dolly(1.4) renderer.ResetCameraClippingRange() renderer.SetBackground(colors.GetColor3d("PaleGreen")) render_window.SetSize(640, 480) render_window.Render() render_window_interactor.Start()
import vtk c = vtk.vtkActorCollection() a1 = vtk.vtkActor() a2 = vtk.vtkActor() c.AddItem(a1) c.AddItem(a2) print c.GetNumberOfItems() c.InitTraversal() for i in xrange(2): print c.GetNextActor()
ntheme.SetOutlineColor(0.2, 0.2, 0.2) ntheme.SetPointColor(0.1, 0.1, 0.1) ntheme.SetPointOpacity(1.0) nodeMapper = vtk.vtkGraphMapper() nodeMapper.SetInput(nodeGraph) nodeMapper.SetColorEdges(False) nodeMapper.ApplyViewTheme(ntheme) nodeActor = vtk.vtkActor() nodeActor.SetMapper(nodeMapper) nodeActor.SetPosition(0,0,-0.0025) # ---------- # Create an Actor Collection for applying visibility to group basisActorCollection = vtk.vtkActorCollection() basisActorCollection.AddItem(vertActor) basisActorCollection.AddItem(outlineActor) # ---------- # Background graph skeleton graphMapper = vtk.vtkGraphMapper() graphMapper.SetInputConnection(0, edgeLayout.GetOutputPort(0)) graphMapper.SetColorEdges(True) graphMapper.SetEdgeColorArrayName('weight') # Apply a theme to the background graph gtheme = vtk.vtkViewTheme() gtheme.SetLineWidth(1) gtheme.SetPointSize(0) gtheme.SetOutlineColor(0.8, 0.8, 0.8)
class EventHandler: __sharedState = {} markers = vtk.vtkActorCollection() defaultColor = (0, 0, 1) labelsOn = 1 observers = {} selected = {} def __init__(self): self.__dict__ = self.__sharedState def add_selection(self, marker): self.selected[marker] = 1 self.notify('select marker', marker) def remove_selection(self, marker): if self.selected.has_key(marker): del self.selected[marker] self.notify('unselect marker', marker) def select_new(self, marker): for oldMarker in self.selected.keys(): self.remove_selection(oldMarker) self.add_selection(marker) def add_marker(self, marker): # break undo cycle func, args = UndoRegistry().get_last_pop() #print 'add', func, args if len(args)==0 or \ (func, args[0]) != (self.add_marker, marker): UndoRegistry().push_command(self.remove_marker, marker) self.markers.AddItem(marker) self.notify('add marker', marker) def remove_marker(self, marker): # break undo cycle func, args = UndoRegistry().get_last_pop() #print 'remove', func, args if len(args)==0 or \ (func, args[0]) != (self.remove_marker, marker): UndoRegistry().push_command(self.add_marker, marker) self.markers.RemoveItem(marker) self.notify('remove marker', marker) def get_markers(self): return self.markers def get_markers_as_seq(self): numMarkers = self.markers.GetNumberOfItems() self.markers.InitTraversal() return [self.markers.GetNextActor() for i in range(numMarkers)] def set_default_color(self, color): self.defaultColor = color def get_default_color(self): return self.defaultColor def save_markers_as(self, fname): fh = file(fname, 'w') self.markers.InitTraversal() numMarkers = self.markers.GetNumberOfItems() lines = [] for i in range(numMarkers): marker = self.markers.GetNextActor() if marker is None: continue lines.append(marker.to_string()) lines.sort() fh.write('\n'.join(lines) + '\n') def set_vtkactor(self, vtkactor): print "EventHandler.set_vtkactor()" self.vtkactor = vtkactor def save_registration_as(self, fname): print "EventHandler.save_registration_as(", fname, ")" fh = file(fname, 'w') # XXX mcc: somehow get the transform for the VTK actor. aiieeee #xform = self.vtkactor.GetUserTransform() loc = self.vtkactor.GetOrigin() pos = self.vtkactor.GetPosition() scale = self.vtkactor.GetScale() mat = self.vtkactor.GetMatrix() orient = self.vtkactor.GetOrientation() print "EventHandler.save_registration_as(): vtkactor has origin, pos, scale, mat, orient=", loc, pos, scale, mat, orient, "!!" def vtkmatrix4x4_to_array(vtkmat): scipy_array = zeros((4, 4), 'd') for i in range(0, 4): for j in range(0, 4): scipy_array[i][j] = mat.GetElement(i, j) return scipy_array scipy_mat = vtkmatrix4x4_to_array(mat) pickle.dump(scipy_mat, fh) fh.close() def load_markers_from(self, fname): #this runs when you load markers from file. it loads a csv file line by line and adds each marker self.notify('render off') for line in file(fname, 'r'): marker = Marker.from_string(line) self.add_marker(marker) #adds the marker to a vtk actor collection self.notify('render on') UndoRegistry().flush() def attach(self, observer): self.observers[observer] = 1 def detach(self, observer): try: del self.observers[observer] except KeyError: pass def notify(self, event, *args): #this function maps events to function calls for observer in self.observers.keys(): #print "EventHandler.notify(", event, "): calling update_viewer for ", observer, "with args: ", args #DEBUG MODE ONLY observer.update_viewer(event, *args) def get_labels_on(self): return self.labelsOn def set_labels_on(self): self.labelsOn = 1 self.notify('labels on') def set_labels_off(self): self.labelsOn = 0 self.notify('labels off') def is_selected(self, marker): return self.selected.has_key(marker) def get_selected(self): return self.selected.keys() def get_num_selected(self): return len(self.selected)
def loadGraph(): # ---------- # Load and construct whole graph and multi-resolution data from Matlab structure dataDir = '/Users/emonson/Programming/Matlab/EMonson/Fodava/DocumentAnalysis/Analysis/' filename = dataDir + 'X20_042709b.mat' # filename = '/Users/emonson/Programming/Python/VTK/X20_040609b.mat' X = scipy.io.loadmat(filename) # Get graph structure G out of matlab variables G = X['G'] # ---------- # Set multi-resolution level bounds in GUI sliders levelMax = G.Tree.shape[0]-1 ui_window.hSlider_level.setMinimum(1) ui_window.hSlider_level.setMaximum(levelMax) ui_window.spinBox_level.setMinimum(1) ui_window.spinBox_level.setMaximum(levelMax) # Start setting up basis function for display as subgraph ExtBasis = GTree[level,0]['ExtBasis'][0][0][0] basisMax = ExtBasis.shape[1]-1 # zero-based indices # Set particular level basis function bounds in GUI sliders ui_window.hSlider_basisIndex.setMinimum(0) ui_window.hSlider_basisIndex.setMaximum(basisMax) ui_window.spinBox_basisIndex.setMinimum(0) ui_window.spinBox_basisIndex.setMaximum(basisMax) # Build table which will become graph table = vtk.vtkTable() col0 = vtk.vtkIntArray() col0.SetName('index1') col1 = vtk.vtkIntArray() col1.SetName('index2') val = vtk.vtkDoubleArray() val.SetName('weight') Tmat = G.T # Tmat = G.W for ii in range(Tmat.nzmax): col0.InsertNextValue(Tmat.rowcol(ii)[0]) col1.InsertNextValue(Tmat.rowcol(ii)[1]) val.InsertNextValue(abs(Tmat.getdata(ii))) table.AddColumn(col0) table.AddColumn(col1) table.AddColumn(val) # Vertex links need to be done with index2 first or indexing won't be right... # TODO: Make this foolproof so that graph always ends up with correct ordering of indices... tgraph = vtk.vtkTableToGraph() tgraph.SetInput(table) tgraph.AddLinkVertex('index2', 'stuff', False) tgraph.AddLinkVertex('index1', 'stuff', False) tgraph.AddLinkEdge('index2', 'index1') rawGraph = tgraph.GetOutput() rawGraph.Update() # print graph # Load and assign whole graph pre-layout coordinates ptsFile = os.path.splitext(filename)[0] + '_pts.vtp' if os.path.exists(ptsFile): polyreader = vtk.vtkXMLPolyDataReader() polyreader.SetFileName(ptsFile) polyreader.Update() pts = polyreader.GetOutput().GetPoints() rawGraph.SetPoints(pts) # print pts strategy = vtk.vtkPassThroughLayoutStrategy() layout = vtk.vtkGraphLayout() layout.SetInput(rawGraph) layout.SetLayoutStrategy(strategy) edgeLayout = vtk.vtkEdgeLayout() edgeStrategy = vtk.vtkArcParallelEdgeStrategy() edgeStrategy.SetNumberOfSubdivisions(50) edgeLayout.SetInputConnection(layout.GetOutputPort()) edgeLayout.SetLayoutStrategy(edgeStrategy) graph = edgeLayout.GetOutput() graph.Update() # -------- # Add ExtBasis to graph data & Select particular basis function # print 'ExtBasis shape: ' + str(ExtBasis[:,basisNum].data.shape) + ' (level,basis) (' + str(level) + ',' + str(basisNum) + ')' # Indexing of ExtBasis is backwards from graph, so need to reverse with [::-1] # and array not "contiguous" if don't do .copy() Esub = ExtBasis[:,basisNum].data[::-1].copy() EsubSq = Esub**2 # Esub = N.random.random(ExtBasis[:,basisNum].data.shape[0]) # SubIdxs = (Esub > 0.001).nonzero() # SubIdxs = (Esub**2 > 0.8).nonzero() # Set ExtBasis vertex data from numpy array basisFunc = VN.numpy_to_vtk(Esub) basisFunc.SetName('ExtBasis') basisFuncSq = VN.numpy_to_vtk(EsubSq) basisFuncSq.SetName('ExtBasisSq') vertexData = graph.GetVertexData() vertexData.AddArray(basisFunc) vertexData.AddArray(basisFuncSq) selection = vtk.vtkSelectionSource() selection.SetContentType(7) # vtkSelection::THRESHOLDS # selection.SetContentType(2) # vtkSelection::PEDIGREE_IDS selection.SetFieldType(3) # vtkSelection::VERTEX selection.SetArrayName("ExtBasisSq") selection.AddThreshold(basisCutoff, 10) # TODO: There was something wrong with the indexing in the PEDIGREE_IDS selection... # for ii in SubIdxs[0]: # selection.AddID(0,ii) minmax = "(%3.2e, %3.2e)" % (EsubSq.min(), EsubSq.max()) ui_window.label_basisCutoff_minmax.setText(minmax) selection.Update() # ---------- # Back to pipeline degree = vtk.vtkVertexDegree() degree.SetInput(graph) subgraph = vtk.vtkExtractSelectedGraph() subgraph.SetRemoveIsolatedVertices(False) subgraph.SetInputConnection(degree.GetOutputPort()) subgraph.SetSelectionConnection(selection.GetOutputPort()) # +++++++++++++ graphToPoly = vtk.vtkGraphToPolyData() graphToPoly.SetInputConnection(subgraph.GetOutputPort()) edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(graphToPoly.GetOutputPort()) edgeMapper.SetScalarModeToUseCellData() edgeMapper.SetScalarVisibility(False) edgeMapper.SetImmediateModeRendering(True) edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.SetPosition(0, 0, -0.003); lut = vtk.vtkLookupTable() lutNum = 256 lut.SetNumberOfTableValues(lutNum) ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToDiverging() ctf.AddRGBPoint(0.0, 0, 0, 1.0) ctf.AddRGBPoint(1.0, 1.0, 0, 0) for ii,ss in enumerate([float(xx)/float(lutNum) for xx in range(lutNum)]): cc = ctf.GetColor(ss) lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0) vertGlyph = vtk.vtkVertexGlyphFilter() vertGlyph.SetInputConnection(subgraph.GetOutputPort()) vertMapper = vtk.vtkPolyDataMapper() vertMapper.SetInputConnection(vertGlyph.GetOutputPort()) vertMapper.SetImmediateModeRendering(True) vertMapper.SetScalarModeToUsePointFieldData() vertMapper.SetLookupTable(lut) vertMapper.SelectColorArray('ExtBasis') vertMapper.Update() vertRange = vertMapper.GetInput().GetPointData().GetArray(vertMapper.GetArrayName()).GetRange() vertMapper.SetScalarRange(-1.0*vertRange[1], vertRange[1]) vertActor = vtk.vtkActor() vertActor.SetMapper(vertMapper) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetScalarVisibility(False) outlineMapper.SetImmediateModeRendering(True) outlineMapper.SetInputConnection(vertGlyph.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.PickableOff() outlineActor.SetPosition(0, 0, -0.001) outlineActor.GetProperty().SetRepresentationToWireframe() outlineActor.SetMapper(outlineMapper) # Create an Actor Collection for applying visibility to group basisActorCollection = vtk.vtkActorCollection() basisActorCollection.AddItem(vertActor) # basisActorCollection.AddItem(edgeActor) basisActorCollection.AddItem(outlineActor) # Apply a theme to the views theme = vtk.vtkViewTheme.CreateMellowTheme() theme.SetLineWidth(3) theme.SetPointSize(5) theme.SetSelectedCellColor(1,1,1) theme.SetSelectedPointColor(1,1,1) theme.SetOutlineColor(0.8, 0.8, 0.8) # theme.SetPointColor(0.9, 0.7, 0.3) theme.SetCellColor(0.9, 0.7, 0.3) # theme.SetPointOpacity(0.5) # theme.SetPointHueRange(0.0, 0.15) # theme.SetPointSaturationRange(0.6, 0.8) # theme.SetPointValueRange(0.4,0.8) # theme.SetPointAlphaRange(0.2,0.8) # theme.SetPointAlphaRange(1.0,1.0) # Apply theme # vertActor.GetProperty().SetColor(theme.GetPointColor()) # vertActor.GetProperty().SetOpacity(theme.GetPointOpacity()) vertActor.GetProperty().SetPointSize(theme.GetPointSize()) outlineActor.GetProperty().SetPointSize(vertActor.GetProperty().GetPointSize()+2) outlineActor.GetProperty().SetColor(theme.GetOutlineColor()) outlineActor.GetProperty().SetOpacity(theme.GetPointOpacity()) edgeActor.GetProperty().SetColor(theme.GetCellColor()) edgeActor.GetProperty().SetOpacity(theme.GetCellOpacity()) edgeActor.GetProperty().SetLineWidth(theme.GetLineWidth()) # ---------- # Background graph skeleton graphMapper = vtk.vtkGraphMapper() graphMapper.SetInputConnection(0, degree.GetOutputPort(0)) # Apply a theme to the background graph gtheme = vtk.vtkViewTheme() gtheme.SetLineWidth(1) gtheme.SetPointSize(0) gtheme.SetCellColor(0.8, 0.8, 0.8) gtheme.SetCellOpacity(0.2) gtheme.SetOutlineColor(0.8, 0.8, 0.8) gtheme.SetPointColor(0.8, 0.8, 0.8) gtheme.SetPointOpacity(0.0) graphMapper.ApplyViewTheme(gtheme) graphActor = vtk.vtkActor() graphActor.SetMapper(graphMapper) graphActor.SetPosition(0,0,-0.005) # ---------- # Background vertices graphPoly = vtk.vtkGraphToPolyData() graphPoly.SetInputConnection(0, tgraph.GetOutputPort(0)) vertGlyph = vtk.vtkGlyph3D() vertGlyph.SetInputConnection(0, graphPoly.GetOutputPort()) glyphSource = vtk.vtkGlyphSource2D() glyphSource.SetGlyphTypeToVertex() # glyphSource.SetGlyphTypeToCircle() # glyphSource.SetScale(0.025) vertGlyph.SetInputConnection(1, glyphSource.GetOutputPort()) vertexMapper = vtk.vtkPolyDataMapper() vertexMapper.SetInputConnection(vertGlyph.GetOutputPort()) vertexActor = vtk.vtkActor() vertexActor.SetMapper(vertexMapper) vertexActor.GetProperty().SetPointSize(4) vertexActor.GetProperty().SetOpacity(0.5) vertexActor.GetProperty().SetColor(0.6, 0.6, 0.6) vertexActor.SetPosition(0, 0, -0.004) # ---------- # Vertex index labels labelMapper = vtk.vtkDynamic2DLabelMapper() labelMapper.SetInputConnection(0, graphPoly.GetOutputPort(0)) labelMapper.SetLabelModeToLabelFieldData() labelMapper.SetFieldDataName("label") labelMapper.SetLabelFormat("%s") labelMapper.GetLabelTextProperty().SetColor(0.0, 0.0, 0.0) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # ---------- # MultiScale Graph msGraph = buildSubGraph(level) msMapper = vtk.vtkGraphMapper() msMapper.SetInput(msGraph) msMapper.SetColorEdges(True) msMapper.SetEdgeColorArrayName('weight') # Apply a theme to the background graph mtheme = vtk.vtkViewTheme() mtheme.SetLineWidth(3) mtheme.SetPointSize(11) # mtheme.SetCellColor(0.5, 0.5, 0.7) # mtheme.SetCellOpacity(0.5) mtheme.SetOutlineColor(0.8, 0.8, 0.8) mtheme.SetPointColor(0.3, 0.3, 0.6) mtheme.SetPointOpacity(1.0) mtheme.SetCellHueRange(0.67, 0.67) mtheme.SetCellSaturationRange(0.6, 0.1) mtheme.SetCellValueRange(0.5,1.0) mtheme.SetCellAlphaRange(0.2,0.8) msMapper.ApplyViewTheme(mtheme) msActor = vtk.vtkActor() msActor.SetMapper(msMapper) msActor.SetPosition(0,0,-0.002) # ---------- # Set up window and add actors view.SetLayoutStrategyToPassThrough() # view.ApplyViewTheme(theme) # view.SetupRenderWindow(win) view.GetRenderer().SetBackground(theme.GetBackgroundColor()) view.GetRenderer().SetBackground2(theme.GetBackgroundColor2()) view.GetRenderer().SetGradientBackground(True) view.GetRenderer().AddActor(vertActor) view.GetRenderer().AddActor(outlineActor) view.GetRenderer().AddActor(edgeActor) view.GetRenderer().AddActor(graphActor) view.GetRenderer().AddActor(vertexActor) view.GetRenderer().AddActor(labelActor) view.GetRenderer().AddActor(msActor) # ---------- # General interactor isty = vtk.vtkInteractorStyleRubberBand2D() # RubberBand2D assumes/needs parallel projection ON view.GetRenderer().GetActiveCamera().ParallelProjectionOn() iren = view.GetRenderWindow().GetInteractor() iren.SetInteractorStyle(isty) # Interactor style must be set before scalar bar can be shown # view.SetVertexScalarBarVisibility(True) sbActor = vtk.vtkScalarBarActor() sbActor.SetLookupTable(vertMapper.GetLookupTable()) sbActor.SetTitle(vertMapper.GetArrayName()) sbActor.SetNumberOfLabels(3) vertexScalarBar = vtk.vtkScalarBarWidget() vertexScalarBar.SetScalarBarActor(sbActor) vertexScalarBar.SetInteractor(iren) vertexScalarBar.SetDefaultRenderer(view.GetRenderer()) vertexScalarBar.SetCurrentRenderer(view.GetRenderer()) vertexScalarBar.SetEnabled(True) scalarBarRep = vertexScalarBar.GetRepresentation() scalarBarRep.SetOrientation(1) # 0 = Horizontal, 1 = Vertical scalarBarRep.GetPositionCoordinate().SetValue(0.05,0.05) scalarBarRep.GetPosition2Coordinate().SetValue(0.15,0.25) # Adding it this way gets it to show up, but it's not interactive view.GetRenderer().AddActor(sbActor) view.ResetCamera() view.Render() # ---------- # Add Actors to QListWidget to allow check and uncheck for visibility listItem0 = QtGui.QListWidgetItem() listItem0.setText('Index Labels') listItem0.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) labelActor.SetVisibility(0) listItem0.setCheckState(QtCore.Qt.Unchecked) # Put actor it in as data in the list widget item listItem0.setData(QtCore.Qt.UserRole, QtCore.QVariant(labelActor)) ui_window.listWidget.insertItem(0,listItem0) # Test retrieval of actor from list widget item # tmpItem = ui_window.listWidget.item(0) # tmpQtActor = tmpItem.data(QtCore.Qt.UserRole) # tmpActor = tmpQtActor.toPyObject() # tmpActor.SetVisibility(0) # Shorter way to add item to list widget listItem1 = QtGui.QListWidgetItem('Vertices (background)', ui_window.listWidget) listItem1.setData(QtCore.Qt.UserRole, QtCore.QVariant(vertexActor)) listItem1.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem1.setCheckState(QtCore.Qt.Checked) listItem2 = QtGui.QListWidgetItem('Graph (background)', ui_window.listWidget) listItem2.setData(QtCore.Qt.UserRole, QtCore.QVariant(graphActor)) listItem2.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem2.setCheckState(QtCore.Qt.Checked) listItem3 = QtGui.QListWidgetItem() listItem3.setText('Basis Function Vertices') listItem3.setData(QtCore.Qt.UserRole, QtCore.QVariant(basisActorCollection)) listItem3.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem3.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(1,listItem3) listItem6 = QtGui.QListWidgetItem() listItem6.setText('Basis Function Edges') listItem6.setData(QtCore.Qt.UserRole, QtCore.QVariant(edgeActor)) listItem6.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem6.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(2,listItem6) listItem4 = QtGui.QListWidgetItem() listItem4.setText('MultiScale Graph') listItem4.setData(QtCore.Qt.UserRole, QtCore.QVariant(msActor)) listItem4.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem4.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(3,listItem4) listItem5 = QtGui.QListWidgetItem() listItem5.setText('Basis Function Scale Bar') listItem5.setData(QtCore.Qt.UserRole, QtCore.QVariant(sbActor)) listItem5.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem5.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(3,listItem5) iren.Initialize() iren.Start()