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 figure(grid=False): """ Creates a mayavi figure with the brain atlas mesh :return: mayavi figure """ fig = mlab.figure(bgcolor=(1, 1, 1)) # engine = mlab.get_engine() # Returns the running mayavi engine. obj_file = Path(__file__).parent.joinpath("root.obj") mapper, actor = add_mesh(fig, obj_file) if grid: # https://vtk.org/Wiki/VTK/Examples/Python/Visualization/CubeAxesActor cubeAxesActor = vtk.vtkCubeAxesActor() cubeAxesActor.SetMapper(mapper) cubeAxesActor.SetBounds(mapper.GetBounds()) cubeAxesActor.SetCamera(fig.scene.renderer._vtk_obj.GetActiveCamera()) cubeAxesActor.SetXTitle("AP (um)") cubeAxesActor.SetYTitle("DV (um)") cubeAxesActor.SetZTitle("ML (um)") cubeAxesActor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cubeAxesActor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cubeAxesActor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cubeAxesActor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cubeAxesActor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cubeAxesActor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) cubeAxesActor.DrawXGridlinesOn() cubeAxesActor.DrawYGridlinesOn() cubeAxesActor.DrawZGridlinesOn() fig.scene.add_actor(cubeAxesActor) mlab.view(azimuth=180, elevation=0) mlab.view(azimuth=210, elevation=210, reset_roll=False) return fig
def _setupCubeAxisActor(self): actor = vtk.vtkCubeAxesActor() actor.VisibilityOff() actor.SetCamera(self._vtk_renderer.GetActiveCamera()) actor.SetGridLineLocation(vtk.vtkCubeAxesActor.VTK_GRID_LINES_ALL) actor.SetFlyMode(vtk.vtkCubeAxesActor.VTK_FLY_OUTER_EDGES) color = [0, 0, 0] prop = vtk.vtkProperty() prop.SetColor(color) actor.SetXAxesLinesProperty(prop) actor.SetYAxesLinesProperty(prop) actor.SetZAxesLinesProperty(prop) actor.SetXAxesGridlinesProperty(prop) actor.SetYAxesGridlinesProperty(prop) actor.SetZAxesGridlinesProperty(prop) for axis in [0, 1, 2]: actor.GetTitleTextProperty(axis).SetColor(color) actor.GetLabelTextProperty(axis).SetColor(color) self._cube_axes_actor = actor
def generate_axis_actor(actor,ren): ''' Generate a 3D axis based on the bounds of incoming 'actor' or actor-like object that has a GetBounds() method and renderer ''' ax3D = vtk.vtkCubeAxesActor() ax3D.ZAxisTickVisibilityOn() ax3D.SetXTitle('X') ax3D.SetYTitle('Y') ax3D.SetZTitle('Z') ax3D.GetTitleTextProperty(0).SetColor(0,0,0) ax3D.GetLabelTextProperty(0).SetColor(0,0,0) ax3D.GetXAxesLinesProperty().SetColor(0,0,0) ax3D.GetTitleTextProperty(1).SetColor(0,0,0) ax3D.GetLabelTextProperty(1).SetColor(0,0,0) ax3D.GetYAxesLinesProperty().SetColor(0,0,0) ax3D.GetTitleTextProperty(2).SetColor(0,0,0) ax3D.GetLabelTextProperty(2).SetColor(0,0,0) ax3D.GetZAxesLinesProperty().SetColor(0,0,0) ax3D.SetBounds(actor.GetBounds()) ax3D.SetCamera(ren.GetActiveCamera()) return ax3D
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 __init__(self): # No cmd line time_index, use on screen rendering self.onScreen = len(sys.argv) == 1 self.SetBackground( 0, 0, 0) self.renWin = vtk.vtkRenderWindow() self.renWin.AddRenderer( self ) if self.onScreen: self.renWin.FullScreenOn() self.iren = vtk.vtkRenderWindowInteractor() self.iren.SetRenderWindow( self.renWin ) self.iren.AddObserver("KeyPressEvent", self.Keypress_ShiftTime) else: self.renWin.OffScreenRenderingOn() self.renWin.SetSize( 1280, 720 ) self.axesActor = vtk.vtkCubeAxesActor(); self.axesActor.SetFlyModeToStaticTriad() #actorAxes->SetCamera(camOrtho); #double b[6] = {2,16,2,16,3,8}; #actorAxes->SetBounds(b); self.axesCamera = vtk.vtkCamera() self.axesCamera.SetPosition( 7, 7, 7) self.axesCamera.SetFocalPoint( 0, 0, 0) self.axesActor.SetCamera( self.axesCamera ) self.AddActor( self.axesActor )
def setnumViewports(self, n): r""" Function to set multiple viewports within the vtkWindow Parameters ------------ n: int number of viewports required """ dif = n - len(self.rens) if dif == 0: return elif dif < 0: for ren in self.rens[n:]: self.RemoveRenderer(ren) self.rens = self.rens[:n] elif dif > 0: for i in range(dif): self.rens.append(vtk.vtkRenderer()) self.axes.append(vtk.vtkCubeAxesActor()) self.AddRenderer(self.rens[-1]) if len(self.cams) < len(self.rens): self.cams.append(vtk.vtkCamera()) self.rens[-1].SetActiveCamera(self.cams[len(self.rens)-1]) for i, ren in enumerate(self.rens): ren.SetViewport(float(i)/n, 0, float(i+1)/n, 1) self.setBackground()
def bounding_box(vtkRenderer, actors): volSource = actors[0] cubeAxesActor = vtk.vtkCubeAxesActor() cubeAxesActor.SetBounds(volSource.GetOutput().GetBounds()) cubeAxesActor.SetCamera(vtkRenderer.GetActiveCamera()) cubeAxesActor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cubeAxesActor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cubeAxesActor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cubeAxesActor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cubeAxesActor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cubeAxesActor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) cubeAxesActor.DrawXGridlinesOn() cubeAxesActor.DrawYGridlinesOn() cubeAxesActor.DrawZGridlinesOn() if vtk.VTK_MAJOR_VERSION > 5: cubeAxesActor.SetGridLineLocation(vtk.VTK_GRID_LINES_FURTHEST) cubeAxesActor.XAxisMinorTickVisibilityOff() cubeAxesActor.YAxisMinorTickVisibilityOff() cubeAxesActor.ZAxisMinorTickVisibilityOff() actors.append(cubeAxesActor) return actors
def addAxes(self, actors, viewport=0, color=[1.0, 1.0, 1.0], font=None): r""" Add 3D axes to the vtk window Parameters ---------- actors: list List of ampActors, this is used to determine the necessary limits of the axes viewport: int, default 0 The index of the viewport add the axes into color: array_like The RGB values as floats of the axes line and text colour between [0, 1] """ self.axes = vtk.vtkCubeAxesActor() lim = [] ax = self.axes for actor in actors: lim.append(actor.GetBounds()) lim = np.array(lim) ax.SetBounds(tuple(lim.max(axis=0))) ax.SetCamera(self.rens[viewport].GetActiveCamera()) ax.SetFlyModeToClosestTriad() for axes in range(3): ax.GetTitleTextProperty(axes).SetColor(color) ax.GetLabelTextProperty(axes).SetColor(color) ax.GetTitleTextProperty(axes).SetFontFamilyToCourier() ax.GetLabelTextProperty(axes).SetFontFamilyToCourier()
def _setupCubeAxesActor(self): self._cube_axes_actor = vtk.vtkCubeAxesActor() self._cube_axes_actor.VisibilityOff() self._cube_axes_actor.SetCamera(self._vtk_renderer.GetActiveCamera()) self._cube_axes_actor.SetGridLineLocation( vtk.vtkCubeAxesActor.VTK_GRID_LINES_ALL) self._cube_axes_actor.SetFlyMode( vtk.vtkCubeAxesActor.VTK_FLY_OUTER_EDGES)
def __init__(self, ws, parent=None): super().__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vti = self.md_to_vti(ws) self.mapper = vtk.vtkDataSetMapper() self.mapper.SetInputData(vti) self.mapper.ScalarVisibilityOn() self.mapper.SetScalarModeToUseCellData() self.mapper.SetColorModeToMapScalars() self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) scalarBar = vtk.vtkScalarBarActor() scalarBar.SetLookupTable(self.mapper.GetLookupTable()) scalarBar.SetNumberOfLabels(4) srange = vti.GetScalarRange() self.lut = vtk.vtkLookupTable() self.lut.SetTableRange(srange) self.lut.Build() self.mapper.UseLookupTableScalarRangeOn() self.mapper.SetLookupTable(self.lut) scalarBar.SetLookupTable(self.lut) self.renderer = vtk.vtkRenderer() self.renderer.GradientBackgroundOn() self.renderer.SetBackground(0.8, 0.8, 0.8) self.renderer.SetBackground2(0, 0, 0) axes = vtk.vtkCubeAxesActor() axes.SetUseTextActor3D(1) axes.SetBounds(vti.GetBounds()) axes.SetCamera(self.renderer.GetActiveCamera()) axes.DrawXGridlinesOn() axes.DrawYGridlinesOn() axes.DrawZGridlinesOn() axes.SetFlyModeToOuterEdges() self.renderer.AddActor(self.actor) self.renderer.AddActor(axes) self.renderer.AddActor2D(scalarBar) self.renderer.ResetCamera() self.vtkWidget.GetRenderWindow().AddRenderer(self.renderer) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() layout = QVBoxLayout() layout.addWidget(self.vtkWidget) self.setLayout(layout) self.iren.Initialize()
def __init__(self, renderer, path_actor): self.path_actor = path_actor """ for k, v in VTKBackPlot.__dict__.items(): if "function" in str(v): print(k) for attr_name in dir(VTKBackPlot): attr_value = getattr(VTKBackPlot, attr_name) print(attr_name, attr_value, callable(attr_value)) print(dir(VTKBackPlot)) testit = getattr(VTKBackPlot, '_enableProgramTicks') print('enableProgramTicks {}'.format(testit)) """ cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(self.path_actor.GetBounds()) cube_axes_actor.SetCamera(renderer.GetActiveCamera()) cube_axes_actor.SetXLabelFormat("%6.3f") cube_axes_actor.SetYLabelFormat("%6.3f") cube_axes_actor.SetZLabelFormat("%6.3f") cube_axes_actor.SetFlyModeToStaticEdges() cube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) if not IN_DESIGNER: programBoundry = INIFILE.find("VTK", "PROGRAM_BOUNDRY") or "" if programBoundry.lower() in ['false', 'off', 'no', '0']: cube_axes_actor.XAxisVisibilityOff() cube_axes_actor.YAxisVisibilityOff() cube_axes_actor.ZAxisVisibilityOff() programTicks = INIFILE.find("VTK", "PROGRAM_TICKS") or "" if programTicks.lower() in ['false', 'off', 'no', '0']: cube_axes_actor.XAxisTickVisibilityOff() cube_axes_actor.YAxisTickVisibilityOff() cube_axes_actor.ZAxisTickVisibilityOff() programLabel = INIFILE.find("VTK", "PROGRAM_LABELS") or "" if programTicks.lower() in ['false', 'off', 'no', '0']: cube_axes_actor.XAxisLabelVisibilityOff() cube_axes_actor.YAxisLabelVisibilityOff() cube_axes_actor.ZAxisLabelVisibilityOff() self.actor = cube_axes_actor
def __init__(self, axis): self.status = STATUS cube_axes_actor = vtk.vtkCubeAxesActor() x_max = axis[0]["max_position_limit"] x_min = axis[0]["min_position_limit"] y_max = axis[1]["max_position_limit"] y_min = axis[1]["min_position_limit"] z_max = axis[2]["max_position_limit"] z_min = axis[2]["min_position_limit"] cube_axes_actor.SetBounds(x_min, x_max, y_min, y_max, z_min, z_max) cube_axes_actor.SetXLabelFormat("%6.3f") cube_axes_actor.SetYLabelFormat("%6.3f") cube_axes_actor.SetZLabelFormat("%6.3f") cube_axes_actor.SetFlyModeToStaticEdges() cube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) if not IN_DESIGNER: machineBoundry = INIFILE.find("VTK", "MACHINE_BOUNDRY") or "" if machineBoundry.lower() in ['false', 'off', 'no', '0']: cube_axes_actor.XAxisVisibilityOff() cube_axes_actor.YAxisVisibilityOff() cube_axes_actor.ZAxisVisibilityOff() machineTicks = INIFILE.find("VTK", "MACHINE_TICKS") or "" if machineTicks.lower() in ['false', 'off', 'no', '0']: cube_axes_actor.XAxisTickVisibilityOff() cube_axes_actor.YAxisTickVisibilityOff() cube_axes_actor.ZAxisTickVisibilityOff() machineLabels = INIFILE.find("VTK", "MACHINE_LABELS") or "" if machineLabels.lower() in ['false', 'off', 'no', '0']: cube_axes_actor.XAxisLabelVisibilityOff() cube_axes_actor.YAxisLabelVisibilityOff() cube_axes_actor.ZAxisLabelVisibilityOff() units = str(self.status.program_units) cube_axes_actor.SetXUnits(units) cube_axes_actor.SetYUnits(units) cube_axes_actor.SetZUnits(units) self.actor = cube_axes_actor
def render(self): """Render to display""" # define the renderer ren = vtk.vtkOpenGLRenderer() ren.SetBackground(*self._vtk_args.background_colour) # populate the renderer with the meshes for segment in self.segments: ren = segment.render(ren) # render window renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) if self._vtk_args.full_screen: renWin.FullScreenOn() # render window interactor iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) # from vtkCubeAxesActor.h # define VTK_FLY_OUTER_EDGES 0 # define VTK_FLY_CLOSEST_TRIAD 1 # define VTK_FLY_FURTHEST_TRIAD 2 # define VTK_FLY_STATIC_TRIAD 3 # define VTK_FLY_STATIC_EDGES 4 if self._vtk_args.cube_axes is not None: cubeAxesActor = vtk.vtkCubeAxesActor() cubeAxesActor.SetBounds(ren.ComputeVisiblePropBounds()) cubeAxesActor.SetCamera(ren.GetActiveCamera()) cubeAxesActor.SetFlyMode(self._vtk_args.cube_axes) cubeAxesActor.SetFlyModeToStaticEdges( ) # how the cube axes will appear cubeAxesActor.GetTitleTextProperty(0).SetColor(1.0, 1.0, 1.0) cubeAxesActor.GetTitleTextProperty(1).SetColor(1.0, 1.0, 1.0) cubeAxesActor.GetTitleTextProperty(2).SetColor(1.0, 1.0, 1.0) cubeAxesActor.XAxisMinorTickVisibilityOff() cubeAxesActor.YAxisMinorTickVisibilityOff() cubeAxesActor.ZAxisMinorTickVisibilityOff() ren.AddActor(cubeAxesActor) # _actor_count += 1 # assert ren.VisibleActorCount() == _actor_count # axes: display axes by default if not self._vtk_args.no_orientation_axes: axesActor = vtk.vtkAxesActor() axesWidget = vtk.vtkOrientationMarkerWidget() axesWidget.SetOrientationMarker(axesActor) axesWidget.SetViewport(0, 0, 0.1, 0.1) axesWidget.SetInteractor(iren) axesWidget.SetEnabled(1) ren.ResetCamera() # hello... print_date("Initialising...") iren.Initialize() print_date("Launching VTK viewer...") iren.Start() print_date("3D view completed.")
def main(): colors = vtk.vtkNamedColors() # Create a superquadric superquadricSource = vtk.vtkSuperquadricSource() superquadricSource.SetPhiRoundness(3.1) superquadricSource.SetThetaRoundness(1.0) superquadricSource.Update() # needed to GetBounds later renderer = vtk.vtkRenderer() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(superquadricSource.GetOutputPort()) superquadricActor = vtk.vtkActor() superquadricActor.SetMapper(mapper) cubeAxesActor = vtk.vtkCubeAxesActor() cubeAxesActor.SetBounds(superquadricSource.GetOutput().GetBounds()) cubeAxesActor.SetCamera(renderer.GetActiveCamera()) cubeAxesActor.GetTitleTextProperty(0).SetColor(colors.GetColor3d('Red')) cubeAxesActor.GetLabelTextProperty(0).SetColor(colors.GetColor3d('Red')) cubeAxesActor.GetTitleTextProperty(1).SetColor(colors.GetColor3d('LimeGreen')) cubeAxesActor.GetLabelTextProperty(1).SetColor(colors.GetColor3d('LimeGreen')) cubeAxesActor.GetTitleTextProperty(2).SetColor(colors.GetColor3d('Blue')) cubeAxesActor.GetLabelTextProperty(2).SetColor(colors.GetColor3d('Blue')) cubeAxesActor.DrawXGridlinesOn() cubeAxesActor.DrawYGridlinesOn() cubeAxesActor.DrawZGridlinesOn() cubeAxesActor.SetGridLineLocation(cubeAxesActor.VTK_GRID_LINES_FURTHEST) cubeAxesActor.XAxisMinorTickVisibilityOff() cubeAxesActor.YAxisMinorTickVisibilityOff() cubeAxesActor.ZAxisMinorTickVisibilityOff() renderer.AddActor(cubeAxesActor) renderer.AddActor(superquadricActor) renderer.GetActiveCamera().Azimuth(30) renderer.GetActiveCamera().Elevation(30) renderer.ResetCamera() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindow.Render() renderWindowInteractor.Start()
def add_axis(ren, limits, scale): ax3D = vtk.vtkCubeAxesActor() ax3D.ZAxisTickVisibilityOn() ax3D.SetXTitle('X') ax3D.SetYTitle('Y') ax3D.SetZTitle('Z') ax3D.SetBounds(limits) ax3D.SetZAxisRange(limits[-2] * scale[-1], limits[-1] * scale[-1]) ren.AddActor(ax3D) ax3D.SetCamera(ren.GetActiveCamera()) return ax3D
def AddAxis(self,limits,scale): if hasattr(self,"ax3D"): self.ren.RemoveActor(self.ax3D) self.ax3D = vtk.vtkCubeAxesActor() self.ax3D.ZAxisTickVisibilityOn() self.ax3D.SetXTitle('X (11)') self.ax3D.SetYTitle('Y (22)') self.ax3D.SetZTitle('Z') self.ax3D.SetBounds(limits) self.ax3D.SetZAxisRange(limits[-2]*scale,limits[-1]*scale) self.ax3D.SetCamera(self.ren.GetActiveCamera()) self.ren.AddActor(self.ax3D) self.ax3D.SetFlyModeToOuterEdges()
def AddAxis(self, limits, scale): if hasattr(self, "ax3D"): self.ren.RemoveActor(self.ax3D) self.ax3D = vtk.vtkCubeAxesActor() self.ax3D.ZAxisTickVisibilityOn() self.ax3D.SetXTitle('X') self.ax3D.SetYTitle('Y') self.ax3D.SetZTitle('Z') self.ax3D.SetBounds(limits) self.ax3D.SetZAxisRange(limits[-2] * scale, limits[-1] * scale) self.ax3D.SetCamera(self.ren.GetActiveCamera()) self.ren.AddActor(self.ax3D) self.ax3D.SetFlyModeToOuterEdges()
def showRangeBounds(self, rangeBounds): ''' Display axes showing the range boundaries :params rangeBounds: min/max values for the axes to be shown. ''' axes = vtk.vtkCubeAxesActor() #rangeBounds = self.dataSource.getRangeBounds() axes.SetBounds((rangeBounds[XMIN_INDEX], rangeBounds[XMAX_INDEX], \ rangeBounds[YMIN_INDEX], rangeBounds[YMAX_INDEX], \ rangeBounds[ZMIN_INDEX], rangeBounds[ZMAX_INDEX])) axes.SetCamera(self.ren.GetActiveCamera()) self.ren.AddActor(axes) self.ren.ResetCamera() self.renWin.Render()
def makeAxes(self, outline, outlinefilter): """ create axes """ tprop = vtk.vtkTextProperty() tprop.SetColor(self.fgColor) tprop.ShadowOff() prop = vtk.vtkProperty2D() prop.SetColor(self.fgColor) zax = vtk.vtkCubeAxesActor() zax.SetBounds(outline.GetBounds()[0], outline.GetBounds()[1], outline.GetBounds()[2], outline.GetBounds()[3], outline.GetBounds()[4], outline.GetBounds()[4]) zax.SetDragable(False) zax.SetCamera(self.renderer.GetActiveCamera()) zax.SetFlyModeToOuterEdges() zax.DrawXGridlinesOn() zax.DrawYGridlinesOn() zax.DrawZGridlinesOn() zax.SetXTitle('') zax.SetYTitle('') zax.SetZTitle('') zax.SetXAxisMinorTickVisibility(0) zax.SetYAxisMinorTickVisibility(0) zax.SetZAxisMinorTickVisibility(0) zax.SetXAxisLabelVisibility(0) zax.SetYAxisLabelVisibility(0) zax.SetZAxisLabelVisibility(0) axes = vtk.vtkCubeAxesActor2D() axes.SetDragable(False) axes.SetInputConnection(outlinefilter.GetOutputPort()) axes.SetCamera(self.renderer.GetActiveCamera()) axes.SetLabelFormat(self.config.LabelFormat()) axes.SetFlyModeToOuterEdges() axes.SetFontFactor(self.fontFactor) axes.SetNumberOfLabels(self.config.NLabels()) axes.SetXLabel(self.config.XLabel()) axes.SetYLabel(self.config.YLabel()) axes.SetZLabel(self.config.ZLabel()) axes.SetRanges(self.out.GetBounds()) axes.SetUseRanges(True) axes.SetProperty(prop) axes.SetAxisTitleTextProperty(tprop) axes.SetAxisLabelTextProperty(tprop) return zax, axes
def _create_axes(self, camera, verbose=0, tick_vis=True): """ Create the axes boxes """ cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(self.geo_data.extent) cube_axes_actor.SetCamera(camera) if verbose == 1: print(cube_axes_actor.GetAxisOrigin()) # set axes and label colors cube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.DrawXGridlinesOn() cube_axes_actor.DrawYGridlinesOn() cube_axes_actor.DrawZGridlinesOn() if not tick_vis: cube_axes_actor.XAxisMinorTickVisibilityOff() cube_axes_actor.YAxisMinorTickVisibilityOff() cube_axes_actor.ZAxisMinorTickVisibilityOff() cube_axes_actor.SetXTitle("X") cube_axes_actor.SetYTitle("Y") cube_axes_actor.SetZTitle("Z") cube_axes_actor.SetXAxisLabelVisibility(1) cube_axes_actor.SetYAxisLabelVisibility(1) cube_axes_actor.SetZAxisLabelVisibility(1) # only plot grid lines furthest from viewpoint # ensure platform compatibility for the grid line options if sys.platform == "win32": cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST) else: # rather use elif == "linux" ? but what about other platforms try: # apparently this can also go wrong on linux, maybe depends on vtk version? cube_axes_actor.SetGridLineLocation(vtk.VTK_GRID_LINES_FURTHEST) except AttributeError: pass return cube_axes_actor
def add_axis(self, limits, scale): if hasattr(self, "ax3D"): self.ren.RemoveActor(self.ax3D) self.ax3D = vtk.vtkCubeAxesActor() self.ax3D.ZAxisTickVisibilityOn() self.ax3D.SetXTitle('X') self.ax3D.SetXUnits('mm') self.ax3D.SetYTitle('Y') self.ax3D.SetYUnits('mm') self.ax3D.SetZTitle('Z') self.ax3D.SetZUnits('mm') self.ax3D.SetBounds(limits) self.ax3D.SetZAxisRange(limits[-2] * scale[2], limits[-1] * scale[2]) self.ax3D.SetCamera(self.ren.GetActiveCamera()) self.ren.AddActor(self.ax3D) if not (self.ren.GetBackground() == (0.1, 0.2, 0.4)): flip_colors(self.ren, self.ax3D)
def __init__(self): self._renderer, self._render_window, self._interactor = setup_window() self._bounds = _numpy.array((0., 1., 0., 1., 0., 1.)) self._axes_actor = _vtk.vtkCubeAxesActor() self._axes_actor.SetBounds(self._bounds) self._axes_actor.SetCamera(self._renderer.GetActiveCamera()) self._axes_actor.SetFlyModeToStaticTriad() self._axes_actor.GetXAxesLinesProperty().SetColor(0., 0., 0.) self._axes_actor.GetYAxesLinesProperty().SetColor(0., 0., 0.) self._axes_actor.GetZAxesLinesProperty().SetColor(0., 0., 0.) for i in range(3): self._axes_actor.GetLabelTextProperty(i).SetColor(0., 0., 0.) self._axes_actor.GetTitleTextProperty(i).SetColor(0., 0., 0.) self._renderer.AddActor(self._axes_actor)
def add_axis(self,limits,scale): if hasattr(self,"ax3D"): self.ren.RemoveActor(self.ax3D) self.ax3D = vtk.vtkCubeAxesActor() self.ax3D.ZAxisTickVisibilityOn() self.ax3D.SetXTitle('X') self.ax3D.SetXUnits('mm') self.ax3D.SetYTitle('Y') self.ax3D.SetYUnits('mm') self.ax3D.SetZTitle('Z') self.ax3D.SetZUnits('mm') self.ax3D.SetBounds(limits) self.ax3D.SetZAxisRange(limits[-2]*scale[2],limits[-1]*scale[2]) self.ax3D.SetXAxisRange(limits[0]*scale[0],limits[1]*scale[0]) self.ax3D.SetYAxisRange(limits[2]*scale[1],limits[3]*scale[1]) self.ax3D.SetCamera(self.ren.GetActiveCamera()) self.ren.AddActor(self.ax3D) if not(self.ren.GetBackground()==(0.1, 0.2, 0.4)): flip_colors(self.ren,self.ax3D)
def _create_axes(self, camera, verbose=0): "Create and returnr cubeAxesActor, settings." cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(self.geo_data.extent) cube_axes_actor.SetCamera(camera) if verbose == 1: print(cube_axes_actor.GetAxisOrigin()) # set axes and label colors cube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) # font size doesn't work seem to work - maybe some override in place? # cubeAxesActor.GetLabelTextProperty(0).SetFontSize(10) cube_axes_actor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.DrawXGridlinesOn() cube_axes_actor.DrawYGridlinesOn() cube_axes_actor.DrawZGridlinesOn() # cube_axes_actor.XAxisMinorTickVisibilityOff() # cube_axes_actor.YAxisMinorTickVisibilityOff() # cube_axes_actor.ZAxisMinorTickVisibilityOff() cube_axes_actor.SetXTitle("X") cube_axes_actor.SetYTitle("Y") cube_axes_actor.SetZTitle("Z") cube_axes_actor.SetXAxisLabelVisibility(1) cube_axes_actor.SetYAxisLabelVisibility(1) cube_axes_actor.SetZAxisLabelVisibility(1) # only plot grid lines furthest from viewpoint # ensure platform compatibility for the grid line options if sys.platform == "win32": cube_axes_actor.SetGridLineLocation(cube_axes_actor.VTK_GRID_LINES_FURTHEST) else: # rather use elif == "linux" ? but what about other platforms cube_axes_actor.SetGridLineLocation(vtk.VTK_GRID_LINES_FURTHEST) return cube_axes_actor
def axesCube(ren): cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(-1.5, 1.5, -1.5, 1.5, -1.5, 1.5) cube_axes_actor.SetCamera(ren.GetActiveCamera()) cube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.XAxisMinorTickVisibilityOff() cube_axes_actor.YAxisMinorTickVisibilityOff() cube_axes_actor.ZAxisMinorTickVisibilityOff() cube_axes_actor.SetFlyModeToStaticTriad() return cube_axes_actor
def axesCube(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]])): cube_axes_actor = vtk.vtkCubeAxesActor() cube_axes_actor.SetBounds(x_bound[0, 0], x_bound[0, 1], y_bound[0, 0], y_bound[0, 1], z_bound[0, 0], z_bound[0, 1]) cube_axes_actor.SetCamera(ren.GetActiveCamera()) cube_axes_actor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cube_axes_actor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cube_axes_actor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) cube_axes_actor.XAxisMinorTickVisibilityOff() cube_axes_actor.YAxisMinorTickVisibilityOff() cube_axes_actor.ZAxisMinorTickVisibilityOff() cube_axes_actor.SetFlyModeToStaticTriad() return cube_axes_actor
def addCubeAxesActor(self, renderer): cubeAxesActor = vtk.vtkCubeAxesActor() #設定軸上下限 cubeAxesActor.SetBounds(self.pointCloud.getBounds()) #將RENDER CAMERA指定給軸 cubeAxesActor.SetCamera(renderer.GetActiveCamera()) #設定標題與標籤文字顏色 cubeAxesActor.GetTitleTextProperty(0).SetColor(0.5, 0.5, 0.5) cubeAxesActor.GetLabelTextProperty(0).SetColor(0.5, 0.5, 0.5) cubeAxesActor.GetTitleTextProperty(1).SetColor(0.5, 0.5, 0.5) cubeAxesActor.GetLabelTextProperty(1).SetColor(0.5, 0.5, 0.5) cubeAxesActor.GetTitleTextProperty(2).SetColor(0.5, 0.5, 0.5) cubeAxesActor.GetLabelTextProperty(2).SetColor(0.5, 0.5, 0.5) #設定坐標軸線寬 cubeAxesActor.GetXAxesLinesProperty().SetLineWidth(0.5) cubeAxesActor.GetYAxesLinesProperty().SetLineWidth(0.5) cubeAxesActor.GetZAxesLinesProperty().SetLineWidth(0.5) #開啟網格線 cubeAxesActor.DrawXGridlinesOn() cubeAxesActor.DrawYGridlinesOn() cubeAxesActor.DrawZGridlinesOn() #內部網格線不畫 cubeAxesActor.SetDrawXInnerGridlines(False) cubeAxesActor.SetDrawYInnerGridlines(False) cubeAxesActor.SetDrawZInnerGridlines(False) #網格線顏色 cubeAxesActor.GetXAxesGridlinesProperty().SetColor(0.5, 0.5, 0.5) cubeAxesActor.GetYAxesGridlinesProperty().SetColor(0.5, 0.5, 0.5) cubeAxesActor.GetZAxesGridlinesProperty().SetColor(0.5, 0.5, 0.5) #控制軸的繪製方式(外,最近,最遠,靜態最近,靜態外) cubeAxesActor.SetFlyMode(0) #設定刻度線的位置(內,外,兩側) cubeAxesActor.SetTickLocation(1) #網格線樣式(所有,最近,最遠) cubeAxesActor.SetGridLineLocation(2) cubeAxesActor.XAxisMinorTickVisibilityOff() cubeAxesActor.YAxisMinorTickVisibilityOff() cubeAxesActor.ZAxisMinorTickVisibilityOff() return cubeAxesActor
def scatterplot_3d(data, color=None, point_size=None, cmap="jet", point_shape=None): if len(data.shape) != 2 or data.shape[1] != 3: raise ValueError("data must have shape (n, 3) where n is the number of points.") if point_shape is None: if len(data) <= 1000: point_shape = "spheres" else: point_shape = "squares" data = _numpy.float32(data) data_vtk = array_to_float_array(data) point_data = _vtk.vtkPoints() point_data.SetData(data_vtk) points_poly_data = _vtk.vtkPolyData() points_poly_data.SetPoints(point_data) if not color is None: lut = get_lookup_table(color.min(), color.max()) color_scalars = array_to_vtk(_numpy.float32(color.copy())) color_scalars.SetLookupTable(lut) points_poly_data.GetPointData().SetScalars(color_scalars) if point_shape == "spheres": if point_size is None: point_size = _numpy.array(data).std() / len(data)**(1./3.) / 3. glyph_filter = _vtk.vtkGlyph3D() glyph_filter.SetInputData(points_poly_data) sphere_source = _vtk.vtkSphereSource() sphere_source.SetRadius(point_size) glyph_filter.SetSourceConnection(sphere_source.GetOutputPort()) glyph_filter.SetScaleModeToDataScalingOff() if not color is None: glyph_filter.SetColorModeToColorByScalar() else: glyph_filter.SetColorMode(0) glyph_filter.Update() elif point_shape == "squares": if point_size is None: point_size = 3 glyph_filter = _vtk.vtkVertexGlyphFilter() glyph_filter.SetInputData(points_poly_data) glyph_filter.Update() else: raise ValueError("{0} is not a valid entry for points".format(points)) poly_data = _vtk.vtkPolyData() poly_data.ShallowCopy(glyph_filter.GetOutput()) renderer, render_window, interactor = setup_window() mapper = _vtk.vtkPolyDataMapper() mapper.SetInputData(poly_data) if not color is None: mapper.SetLookupTable(lut) mapper.SetUseLookupTableScalarRange(True) points_actor = _vtk.vtkActor() points_actor.SetMapper(mapper) points_actor.GetProperty().SetPointSize(point_size) points_actor.GetProperty().SetColor(0., 0., 0.) axes_actor = _vtk.vtkCubeAxesActor() axes_actor.SetBounds(points_actor.GetBounds()) axes_actor.SetCamera(renderer.GetActiveCamera()) axes_actor.SetFlyModeToStaticTriad() #axes_actor.GetProperty().SetColor(0., 0., 0.) axes_actor.GetXAxesLinesProperty().SetColor(0., 0., 0.) axes_actor.GetYAxesLinesProperty().SetColor(0., 0., 0.) axes_actor.GetZAxesLinesProperty().SetColor(0., 0., 0.) for i in range(3): axes_actor.GetLabelTextProperty(i).SetColor(0., 0., 0.) axes_actor.GetTitleTextProperty(i).SetColor(0., 0., 0.) renderer.AddActor(points_actor) renderer.AddActor(axes_actor) render_window.Render() interactor.Start()
from pyvr.renderer import Renderer from pyvr.actors import LandmarkActor from pyvr.utils.video import write_video import vtk if __name__ == '__main__': axes = vtk.vtkCubeAxesActor() axes.SetTotalLength(50, 50, 50) axes.AxisLabelsOff() renderer = Renderer() renderer.set_camera(pos=(0,-1200,0)) renderer.add_actor(LandmarkActor((100,100,100), 10, rgb=(0,1,0))) renderer.add_actor(axes) proj = renderer.render(rotate_angles=list(range(0,360,1)), bg=(1,1,1)) write_video(proj, 'test.mp4')
def cutmesh(filename, ymin, ymax, step): # 1. setup pipeline # ----------------- # STL mesh stlmesh = vtk.vtkSTLReader() stlmesh.SetFileName(filename) stlmesh.Update() # clip plane = vtk.vtkPlane() plane.SetOrigin(0, 30, 0) plane.SetNormal(0, 1, 0) cutter = vtk.vtkClipPolyData() cutter.SetClipFunction(plane) cutter.SetInputConnection(stlmesh.GetOutputPort()) cutter.Update() massProps = vtk.vtkMassProperties() massProps.SetInputConnection(cutter.GetOutputPort()) massProps.Update() # 2. move the plane and calculate the area # ---------------------------------------- def drange(start, stop, step): r = start while r < stop: yield r r += step curve = [] for planey in drange(ymin, ymax, step): plane.SetOrigin(0, planey, 0) cutter.Update() srf = 0.0 cut = cutter.GetOutput() if cut.GetNumberOfPoints(): massProps.Update() srf = massProps.GetSurfaceArea() curve.append( (planey, srf) ) # store the result in a matlab file outname = 'area.txt' with open(outname,'w') as outfile: for c in curve: outfile.write('%f %f\n' % c) print 'curve written in %s' % outname # 3. display mesh + cut at y=ymin # ------------------------------- plane.SetOrigin(0, ymin, 0) # STL mesh mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stlmesh.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(0.5, 0.5, 1.0) actor.GetProperty().SetOpacity(0.1) # STL grid mapper2 = vtk.vtkPolyDataMapper() mapper2.SetResolveCoincidentTopologyToPolygonOffset() mapper2.SetInputConnection(stlmesh.GetOutputPort()) actor2 = vtk.vtkActor() actor2.SetMapper(mapper2) actor2.GetProperty().SetColor(0.5, 0.5, 1.0) actor2.GetProperty().SetAmbient(1.0) actor2.GetProperty().SetDiffuse(0.0) actor2.GetProperty().SetSpecular(0.0) actor2.GetProperty().SetRepresentationToWireframe() # clip clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputConnection(cutter.GetOutputPort()) clipActor = vtk.vtkActor() clipActor.GetProperty().SetColor(1.0, 1.0, 0.0) clipActor.SetMapper(clipMapper) # clip grid clipMapper2 = vtk.vtkPolyDataMapper() clipMapper2.SetResolveCoincidentTopologyToPolygonOffset() clipMapper2.SetInputConnection(cutter.GetOutputPort()) clipActor2 = vtk.vtkActor() clipActor2.GetProperty().SetColor(0.0, 0.0, 0.0) clipActor2.GetProperty().SetAmbient(1.0) clipActor2.GetProperty().SetDiffuse(0.0) clipActor2.GetProperty().SetSpecular(0.0) clipActor2.GetProperty().SetRepresentationToWireframe() clipActor2.SetMapper(clipMapper2) # display mesh view = BasicView() cubeAxesActor = vtk.vtkCubeAxesActor() cubeAxesActor.SetBounds(stlmesh.GetOutput().GetBounds()) cubeAxesActor.SetCamera(view.ren.GetActiveCamera()) view.add( [actor, actor2, cubeAxesActor, clipActor, clipActor2]) view.interact()
def AddBoundsAxes(self, mesh=None, bounds=None, show_xaxis=True, show_yaxis=True, show_zaxis=True, show_xlabels=True, show_ylabels=True, show_zlabels=True, italic=False, bold=True, shadow=False, fontsize=16, font_family='courier', color='w', xtitle='X Axis', ytitle='Y Axis', ztitle='Z Axis'): """ Adds bounds axes. Shows the bounds of the most recent input mesh unless mesh is specified. Parameters ---------- mesh : vtkPolydata or unstructured grid, optional Input mesh to draw bounds axes around bounds : list or tuple, optional Bounds to override mesh bounds. [xmin, xmax, ymin, ymax, zmin, zmax] show_xaxis : bool, optional Makes x axis visible. Default True. show_yaxis : bool, optional Makes y axis visible. Default True. show_zaxis : bool, optional Makes z axis visible. Default True. show_xlabels : bool, optional Shows x labels. Default True. show_ylabels : bool, optional Shows y labels. Default True. show_zlabels : bool, optional Shows z labels. Default True. italic : bool, optional Italicises axis labels and numbers. Default False. bold : bool, optional Bolds axis labels and numbers. Default True. shadow : bool, optional Adds a black shadow to the text. Default False. fontsize : float, optional Sets the size of the label font. Defaults to 16. font_family : string, optional Font family. Must be either courier, times, or arial. color : string or 3 item list, optional Color of all labels and axis titles. Default white. Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' xtitle : string, optional Title of the x axis. Default "X Axis" ytitle : string, optional Title of the y axis. Default "Y Axis" ztitle : string, optional Title of the z axis. Default "Z Axis" Returns ------- cubeAxesActor : vtk.vtkCubeAxesActor Bounds actor """ # Use last input mesh if availble if not mesh and not bounds: if not hasattr(self, 'mesh'): raise Exception('Specify bounds or first input a mesh') mesh = self.mesh # create actor cubeAxesActor = vtk.vtkCubeAxesActor() cubeAxesActor.SetUse2DMode(True) # set bounds if not bounds: bounds = mesh.GetBounds() cubeAxesActor.SetBounds(mesh.GetBounds()) # show or hide axes cubeAxesActor.SetXAxisVisibility(show_xaxis) cubeAxesActor.SetYAxisVisibility(show_yaxis) cubeAxesActor.SetZAxisVisibility(show_zaxis) # disable minor ticks cubeAxesActor.XAxisMinorTickVisibilityOff(); cubeAxesActor.YAxisMinorTickVisibilityOff(); cubeAxesActor.ZAxisMinorTickVisibilityOff(); cubeAxesActor.SetCamera(self.ren.GetActiveCamera()) # set color color = ParseColor(color) cubeAxesActor.GetXAxesLinesProperty().SetColor(color) cubeAxesActor.GetYAxesLinesProperty().SetColor(color) cubeAxesActor.GetZAxesLinesProperty().SetColor(color) # empty arr empty_str = vtk.vtkStringArray() empty_str.InsertNextValue('') # show lines if show_xaxis: cubeAxesActor.SetXTitle(xtitle) else: cubeAxesActor.SetXTitle('') cubeAxesActor.SetAxisLabels(0, empty_str) if show_yaxis: cubeAxesActor.SetYTitle(ytitle) else: cubeAxesActor.SetYTitle('') cubeAxesActor.SetAxisLabels(1, empty_str) if show_zaxis: cubeAxesActor.SetZTitle(ztitle) else: cubeAxesActor.SetZTitle('') cubeAxesActor.SetAxisLabels(2, empty_str) # show labels if not show_xlabels: cubeAxesActor.SetAxisLabels(0, empty_str) if not show_ylabels: cubeAxesActor.SetAxisLabels(1, empty_str) if not show_zlabels: cubeAxesActor.SetAxisLabels(2, empty_str) # set font font_family = ParseFontFamily(font_family) for i in range(3): cubeAxesActor.GetTitleTextProperty(i).SetFontSize(fontsize) cubeAxesActor.GetTitleTextProperty(i).SetColor(color) cubeAxesActor.GetTitleTextProperty(i).SetFontFamily(font_family) cubeAxesActor.GetTitleTextProperty(i).SetBold(bold) cubeAxesActor.GetLabelTextProperty(i).SetFontSize(fontsize) cubeAxesActor.GetLabelTextProperty(i).SetColor(color) cubeAxesActor.GetLabelTextProperty(i).SetFontFamily(font_family) cubeAxesActor.GetLabelTextProperty(i).SetBold(bold) self.AddActor(cubeAxesActor) self.cubeAxesActor = cubeAxesActor return cubeAxesActor
def addWidgets(self,opt=None): if opt is not None: if opt.has_key('caption'): self.caption=opt['caption'] if opt.has_key('showAxes'): self.showAxes=opt['showAxes'] if opt.has_key('showCompass'): self.showCompass=opt['showCompass'] if opt.has_key('showScalarBar'): self.showScalarBar=opt['showScalarBar'] if opt.has_key('showXYPlane'): self.showXYPlane=opt['showXYPlane'] if opt.has_key('showYZPlane'): self.showYZPlane=opt['showYZPlane'] if opt.has_key('showZXPlane'): self.showZXPlane=opt['showZXPlane'] if opt.has_key('xlabel'): self.xlabel=opt['xlabel'] if opt.has_key('ylabel'): self.ylabel=opt['ylabel'] if opt.has_key('ylabel'): self.zlabel=opt['zlabel'] if opt.has_key('xrange'): self.xrange=opt['xrange'] if opt.has_key('yrange'): self.yrange=opt['yrange'] if opt.has_key('zrange'): self.zrange=opt['zrange'] prn=1000. pc=-prn plXY = vtk.vtkPlaneSource() plXY.SetPoint1(prn,-prn,0) plXY.SetPoint2(-prn,prn,0) plXY.SetOrigin(pc,pc,0) plXY.SetCenter(0,0,0) plXYmap = vtk.vtkPolyDataMapper() plXYmap.SetInput(plXY.GetOutput()) plXYact = vtk.vtkActor() plXYact.SetMapper(plXYmap) plXYact.GetProperty().SetOpacity(0.1) plYZ = vtk.vtkPlaneSource() plYZ.SetCenter(0,pc,pc) plYZ.SetPoint1(0,prn,-prn) plYZ.SetPoint2(0,-prn,prn) plYZmap = vtk.vtkPolyDataMapper() plYZmap.SetInput(plYZ.GetOutput()) plYZact = vtk.vtkActor() plYZact.SetMapper(plYZmap) plYZact.GetProperty().SetOpacity(0.1) plZX = vtk.vtkPlaneSource() plZX.SetCenter(pc,0,pc) plZX.SetPoint1(prn,0,-prn) plZX.SetPoint2(-prn,0,prn) plZXmap = vtk.vtkPolyDataMapper() plZXmap.SetInput(plZX.GetOutput()) plZXact = vtk.vtkActor() plZXact.SetMapper(plZXmap) plZXact.GetProperty().SetOpacity(0.1) ax=vtk.vtkAxesActor() ax.GetXAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ax.GetYAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ax.GetZAxisCaptionActor2D().GetProperty().SetColor(0,0,0) xa=vtk.vtkAxisActor() xa.SetPoint1(0,0,0) xa.SetPoint2(1000,0,0) xa.SetRange((0,1000)) xa.SetBounds(-1.0, 1000.0, -1.0, 1.0, -1.0, 1.0) self.ow=vtk.vtkOrientationMarkerWidget() textActor = vtk.vtkTextActor() textActor.GetTextProperty().SetFontSize ( 22 ) textActor.SetPosition2( 100, 100 ) textActor.SetInput(r'DESICOS VIEWER: '+str(self.caption)+r' Scaling: '+str(self.scalingFactor)) textActor.GetTextProperty().SetColor ( 0.0,0.0,0.0 ) if self.showXYPlane: self.ren.AddActor(plXYact) if self.showYZPlane: self.ren.AddActor(plYZact) if self.showZXPlane: self.ren.AddActor(plZXact) if self.showCaption: self.ren.AddActor2D( textActor ) if self.showScalarBar: self.scalar_bar = vtk.vtkScalarBarActor() self.scalar_bar.SetOrientationToHorizontal() self.scalar_bar.SetLookupTable(self.lut) self.scalar_bar.SetTitle("Imperfection value"); self.scalar_bar.SetNumberOfLabels(11) self.scalar_bar.GetProperty().SetColor ( 0.0,0.0,0.0 ) self.scalar_bar_widget = vtk.vtkScalarBarWidget() self.scalar_bar_widget.SetInteractor(self.iren) self.scalar_bar_widget.SetScalarBarActor(self.scalar_bar) self.scalar_bar_widget.On() if self.showCompass: self.ow.SetOrientationMarker(ax) self.ow.SetInteractor(self.iren) # self.ow.SetViewport( 0.0, 0.0, 0.4, 0.4 ) self.ow.SetEnabled( 1 ) self.ow.InteractiveOn() if self.showAxes: c=vtk.vtkCubeAxesActor() c.SetBounds(self.boundBox) c.SetXTitle(self.xlabel) c.SetYTitle(self.ylabel) c.SetZTitle(self.zlabel) if self.xrange is not None: c.SetXAxisRange(self.xrange) if self.yrange is not None: c.SetYAxisRange(self.yrange) if self.zrange is not None: c.SetZAxisRange(self.zrange) c.GetProperty().SetColor(0., 0., 0.) c.SetCamera(self.ren.GetActiveCamera()) self.ren.AddActor(c)
def animate(self, pd, ind): """ Helper function called by **deformableRegistration** if **animate** is *True*. Spawns a window with an interactive 3-D rendering of the current analyzed object in its reference state. The displacements calculated from the deformable image registration can be applied to this object to animate the deformation by pressing the RIGHT-ARROW. Pressing the UP-ARROW will animate and also save the frames to disk. Parameters ---------- pd : vtkPolyData The current analyzed object's reference geometry. ind : int The index of the current polydata in **rsurfs**. Necessary for naming directory created if animation frames are saved. """ pd.GetPointData().SetActiveVectors("Displacement") class vtkTimerCallback(object): def __init__(self): self.timer_count = 0 def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append( getScalars.GetVzComponent()) scalars.append( vectorNorm.GetOutput()) scalars.append( getScalars.GetVxComponent()) scalars.append( getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction( "%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1 def Keypress(self, obj, event): self.key = obj.GetKeySym() if self.key == "Right" or self.key == "Up": for i in range(10): obj.CreateOneShotTimer(1) renwin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renwin) iren.Initialize() cb = vtkTimerCallback() xmins = (0, 0.5, 0, 0.5) xmaxs = (0.5, 1, 0.5, 1) ymins = (0, 0, 0.5, 0.5) ymaxs = (0.5, 0.5, 1, 1) titles = ('Z Displacement', 'Magnitude', 'X Displacement', 'Y Displacement') cb.actors = [] cb.scalar_bars = [] cb.directory = str(os.path.normpath( self._def_dir + os.sep + "animation{:0d}".format(ind + 1))) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append( getScalars.GetVzComponent()) scalars.append( vectorNorm.GetOutput()) scalars.append( getScalars.GetVxComponent()) scalars.append( getScalars.GetVyComponent()) bounds = np.zeros(6, np.float32) pd.GetBounds(bounds) length = np.min(bounds[1::2] - bounds[0:-1:2]) * 0.2 bounds[1] = bounds[0] + length bounds[3] = bounds[2] + length bounds[5] = bounds[4] + length for j in range(4): mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(scalars[j]) mapper.SetScalarRange(scalars[j].GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetLookupTable(mapper.GetLookupTable()) scalar_bar.SetTitle(titles[j]) scalar_bar.SetLabelFormat("%3.3f") cb.scalar_bars.append(scalar_bar) actor = vtk.vtkActor() actor.SetMapper(mapper) cb.actors.append(actor) renderer = vtk.vtkRenderer() renderer.SetBackground(0., 0., 0.) renwin.AddRenderer(renderer) if j == 0: camera = renderer.GetActiveCamera() else: renderer.SetActiveCamera(camera) triad = vtk.vtkCubeAxesActor() triad.SetCamera(camera) triad.SetFlyModeToStaticTriad() triad.SetBounds(bounds) triad.GetXAxesLinesProperty().SetColor(1.0, 0.0, 0.0) triad.GetYAxesLinesProperty().SetColor(0.0, 1.0, 0.0) triad.GetZAxesLinesProperty().SetColor(0.0, 0.0, 1.0) triad.GetXAxesLinesProperty().SetLineWidth(3.0) triad.GetYAxesLinesProperty().SetLineWidth(3.0) triad.GetZAxesLinesProperty().SetLineWidth(3.0) triad.XAxisLabelVisibilityOff() triad.YAxisLabelVisibilityOff() triad.ZAxisLabelVisibilityOff() triad.XAxisTickVisibilityOff() triad.YAxisTickVisibilityOff() triad.ZAxisTickVisibilityOff() triad.XAxisMinorTickVisibilityOff() triad.YAxisMinorTickVisibilityOff() triad.ZAxisMinorTickVisibilityOff() renderer.SetViewport(xmins[j], ymins[j], xmaxs[j], ymaxs[j]) renderer.AddActor(actor) renderer.AddActor2D(scalar_bar) renderer.AddActor(triad) renderer.ResetCamera() renwin.Render() iren.AddObserver('TimerEvent', cb.execute) iren.AddObserver('KeyPressEvent', cb.Keypress) iren.Start()
def show_bounds(self, mesh=None, bounds=None, show_xaxis=True, show_yaxis=True, show_zaxis=True, show_xlabels=True, show_ylabels=True, show_zlabels=True, italic=False, bold=True, shadow=False, font_size=None, font_family=None, color=None, xlabel='X Axis', ylabel='Y Axis', zlabel='Z Axis', use_2d=False, grid=None, location='closest', ticks=None, all_edges=False, corner_factor=0.5, loc=None, fmt=None, minor_ticks=False, padding=0.0): """Add bounds axes. Shows the bounds of the most recent input mesh unless mesh is specified. Parameters ---------- mesh : vtkPolydata or unstructured grid, optional Input mesh to draw bounds axes around bounds : list or tuple, optional Bounds to override mesh bounds. [xmin, xmax, ymin, ymax, zmin, zmax] show_xaxis : bool, optional Makes x axis visible. Default True. show_yaxis : bool, optional Makes y axis visible. Default True. show_zaxis : bool, optional Makes z axis visible. Default True. show_xlabels : bool, optional Shows x labels. Default True. show_ylabels : bool, optional Shows y labels. Default True. show_zlabels : bool, optional Shows z labels. Default True. italic : bool, optional Italicises axis labels and numbers. Default False. bold : bool, optional Bolds axis labels and numbers. Default True. shadow : bool, optional Adds a black shadow to the text. Default False. font_size : float, optional Sets the size of the label font. Defaults to 16. font_family : string, optional Font family. Must be either courier, times, or arial. color : string or 3 item list, optional Color of all labels and axis titles. Default white. Either a string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF' xlabel : string, optional Title of the x axis. Default "X Axis" ylabel : string, optional Title of the y axis. Default "Y Axis" zlabel : string, optional Title of the z axis. Default "Z Axis" use_2d : bool, optional A bug with vtk 6.3 in Windows seems to cause this function to crash this can be enabled for smoother plotting for other environments. grid : bool or str, optional Add grid lines to the backface (``True``, ``'back'``, or ``'backface'``) or to the frontface (``'front'``, ``'frontface'``) of the axes actor. location : str, optional Set how the axes are drawn: either static (``'all'``), closest triad (``front``), furthest triad (``'back'``), static closest to the origin (``'origin'``), or outer edges (``'outer'``) in relation to the camera position. Options include: ``'all', 'front', 'back', 'origin', 'outer'`` ticks : str, optional Set how the ticks are drawn on the axes grid. Options include: ``'inside', 'outside', 'both'`` all_edges : bool, optional Adds an unlabeled and unticked box at the boundaries of plot. Useful for when wanting to plot outer grids while still retaining all edges of the boundary. corner_factor : float, optional If ``all_edges````, this is the factor along each axis to draw the default box. Dafuault is 0.5 to show the full box. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. padding : float, optional An optional percent padding along each axial direction to cushion the datasets in the scene from the axes annotations. Defaults to have no padding Return ------ cube_axes_actor : vtk.vtkCubeAxesActor Bounds actor Examples -------- >>> import pyvista >>> from pyvista import examples >>> mesh = pyvista.Sphere() >>> plotter = pyvista.Plotter() >>> _ = plotter.add_mesh(mesh) >>> _ = plotter.show_bounds(grid='front', location='outer', all_edges=True) >>> plotter.show() # doctest:+SKIP """ self.remove_bounds_axes() if font_family is None: font_family = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if color is None: color = rcParams['font']['color'] if fmt is None: fmt = rcParams['font']['fmt'] color = parse_color(color) # Use the bounds of all data in the rendering window if mesh is None and bounds is None: bounds = self.bounds # create actor cube_axes_actor = vtk.vtkCubeAxesActor() if use_2d or not np.allclose(self.scale, [1.0, 1.0, 1.0]): cube_axes_actor.SetUse2DMode(True) else: cube_axes_actor.SetUse2DMode(False) if grid: if isinstance(grid, str) and grid.lower() in ('front', 'frontface'): cube_axes_actor.SetGridLineLocation( cube_axes_actor.VTK_GRID_LINES_CLOSEST) if isinstance(grid, str) and grid.lower() in ('both', 'all'): cube_axes_actor.SetGridLineLocation( cube_axes_actor.VTK_GRID_LINES_ALL) else: cube_axes_actor.SetGridLineLocation( cube_axes_actor.VTK_GRID_LINES_FURTHEST) # Only show user desired grid lines cube_axes_actor.SetDrawXGridlines(show_xaxis) cube_axes_actor.SetDrawYGridlines(show_yaxis) cube_axes_actor.SetDrawZGridlines(show_zaxis) # Set the colors cube_axes_actor.GetXAxesGridlinesProperty().SetColor(color) cube_axes_actor.GetYAxesGridlinesProperty().SetColor(color) cube_axes_actor.GetZAxesGridlinesProperty().SetColor(color) if isinstance(ticks, str): ticks = ticks.lower() if ticks in ('inside'): cube_axes_actor.SetTickLocationToInside() elif ticks in ('outside'): cube_axes_actor.SetTickLocationToOutside() elif ticks in ('both'): cube_axes_actor.SetTickLocationToBoth() else: raise ValueError( 'Value of ticks ({}) not understood.'.format(ticks)) if isinstance(location, str): location = location.lower() if location in ('all'): cube_axes_actor.SetFlyModeToStaticEdges() elif location in ('origin'): cube_axes_actor.SetFlyModeToStaticTriad() elif location in ('outer'): cube_axes_actor.SetFlyModeToOuterEdges() elif location in ('default', 'closest', 'front'): cube_axes_actor.SetFlyModeToClosestTriad() elif location in ('furthest', 'back'): cube_axes_actor.SetFlyModeToFurthestTriad() else: raise ValueError( 'Value of location ({}) not understood.'.format(location)) # set bounds if bounds is None: bounds = np.array(mesh.GetBounds()) if isinstance(padding, (int, float)) and 0.0 <= padding < 1.0: if not np.any(np.abs(bounds) == np.inf): cushion = np.array([ np.abs(bounds[1] - bounds[0]), np.abs(bounds[3] - bounds[2]), np.abs(bounds[5] - bounds[4]) ]) * padding bounds[::2] -= cushion bounds[1::2] += cushion else: raise ValueError( 'padding ({}) not understood. Must be float between 0 and 1'. format(padding)) cube_axes_actor.SetBounds(bounds) # show or hide axes cube_axes_actor.SetXAxisVisibility(show_xaxis) cube_axes_actor.SetYAxisVisibility(show_yaxis) cube_axes_actor.SetZAxisVisibility(show_zaxis) # disable minor ticks if not minor_ticks: cube_axes_actor.XAxisMinorTickVisibilityOff() cube_axes_actor.YAxisMinorTickVisibilityOff() cube_axes_actor.ZAxisMinorTickVisibilityOff() cube_axes_actor.SetCamera(self.camera) # set color cube_axes_actor.GetXAxesLinesProperty().SetColor(color) cube_axes_actor.GetYAxesLinesProperty().SetColor(color) cube_axes_actor.GetZAxesLinesProperty().SetColor(color) # empty arr empty_str = vtk.vtkStringArray() empty_str.InsertNextValue('') # show lines if show_xaxis: cube_axes_actor.SetXTitle(xlabel) else: cube_axes_actor.SetXTitle('') cube_axes_actor.SetAxisLabels(0, empty_str) if show_yaxis: cube_axes_actor.SetYTitle(ylabel) else: cube_axes_actor.SetYTitle('') cube_axes_actor.SetAxisLabels(1, empty_str) if show_zaxis: cube_axes_actor.SetZTitle(zlabel) else: cube_axes_actor.SetZTitle('') cube_axes_actor.SetAxisLabels(2, empty_str) # show labels if not show_xlabels: cube_axes_actor.SetAxisLabels(0, empty_str) if not show_ylabels: cube_axes_actor.SetAxisLabels(1, empty_str) if not show_zlabels: cube_axes_actor.SetAxisLabels(2, empty_str) # set font font_family = parse_font_family(font_family) for i in range(3): cube_axes_actor.GetTitleTextProperty(i).SetFontSize(font_size) cube_axes_actor.GetTitleTextProperty(i).SetColor(color) cube_axes_actor.GetTitleTextProperty(i).SetFontFamily(font_family) cube_axes_actor.GetTitleTextProperty(i).SetBold(bold) cube_axes_actor.GetLabelTextProperty(i).SetFontSize(font_size) cube_axes_actor.GetLabelTextProperty(i).SetColor(color) cube_axes_actor.GetLabelTextProperty(i).SetFontFamily(font_family) cube_axes_actor.GetLabelTextProperty(i).SetBold(bold) self.add_actor(cube_axes_actor, reset_camera=False, pickable=False) self.cube_axes_actor = cube_axes_actor if all_edges: self.add_bounding_box(color=color, corner_factor=corner_factor) if fmt is not None: cube_axes_actor.SetXLabelFormat(fmt) cube_axes_actor.SetYLabelFormat(fmt) cube_axes_actor.SetZLabelFormat(fmt) return cube_axes_actor
def __init__(self): self.fs = False self.render = True self.rechnungen = 1. self.setSterne() self.ren = vtk.vtkRenderer() self.ren.SetBackground(.1*.75, .2*.75, .3*.75) for stern in self.Sterne: self.ren.AddActor(stern) if LINES: for pfad in self.Pfade: self.ren.AddActor(pfad) axisactor = vtk.vtkCubeAxesActor() axisactor.SetBounds((0, 1., 0, 1., 0, 1.)) #axisactor.SetXTitle("AU") axisactor.YAxisVisibilityOn() axisactor.ZAxisVisibilityOn() axisactor.SetCamera(self.ren.GetActiveCamera()) #self.ren.AddActor(axisactor) self.osd = OSD(self, text="") self.osd.update() self.ren.AddActor2D(self.osd) #self.ren.GetActiveCamera().SetPosition(0., 0., 10. * MAX_X) #self.ren.GetActiveCamera().SetFocalPoint(0., 0., 0.) #self.ren.GetActiveCamera().SetClippingRange(000., -2000.) self.ren.ResetCamera() self.ren.ResetCameraClippingRange() self.renwin = vtk.vtkRenderWindow() self.renwin.AddRenderer(self.ren) self.renwin.SetSize(800, 600) self.renwin.LineSmoothingOn() self.renwin.PolygonSmoothingOn() self.renwin.SetStereoTypeToAnaglyph() if self.fs: self.renwin.FullScreenOn() inter = vtk.vtkRenderWindowInteractor() inter.SetRenderWindow(self.renwin) inter.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) inter.Initialize() self.renwin.Render() inter.AddObserver("TimerEvent", self.animate) inter.AddObserver("KeyPressEvent", self.keypress) self.timer = inter.CreateRepeatingTimer(20) self.renwin.SetWindowName("+/- = in/decrease dt, \ space = Runge-Kutta on/off, \ c = toggle cam mode, \ r = reset") inter.Start() inter.DestroyTimer(self.timer) time.sleep(.1) for stern in self.Sterne: stern.killme() for pfad in self.Pfade: pfad.killme() del inter del self.renwin del self.Sterne del self.Pfade del self.osd del axisactor del self.ren del self.timer
renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren2.AddViewProp(foheActor) ren2.AddViewProp(outlineActor) ren2.SetBackground(0.1, 0.2, 0.4) normals.Update() bounds = normals.GetOutput().GetBounds() axes2 = vtk.vtkCubeAxesActor() axes2.SetBounds( bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]) axes2.SetXAxisRange(20, 300) axes2.SetYAxisRange(-0.01, 0.01) axes2.SetCamera(ren2.GetActiveCamera()) axes2.SetXLabelFormat("%6.1f") axes2.SetYLabelFormat("%6.1f") axes2.SetZLabelFormat("%6.1f") axes2.SetFlyModeToClosestTriad() axes2.SetScreenSize(20.0) ren2.AddViewProp(axes2) renWin.Render() ren2.ResetCamera()
ren4.AddViewProp(foheActor) ren4.AddViewProp(outlineActor) ren5.AddViewProp(foheActor) ren1.SetBackground(0.1, 0.2, 0.4) ren2.SetBackground(0.1, 0.2, 0.4) ren3.SetBackground(0.1, 0.2, 0.4) ren4.SetBackground(0.1, 0.2, 0.4) ren5.SetBackground(0.1, 0.2, 0.4) normals.Update() bounds = normals.GetOutput().GetBounds() axes = vtk.vtkCubeAxesActor() axes.SetBounds( bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]) axes.SetCamera(ren1.GetActiveCamera()) axes.SetXLabelFormat("%6.1f") axes.SetYLabelFormat("%6.1f") axes.SetZLabelFormat("%6.1f") axes.SetFlyModeToOuterEdges() ren1.AddViewProp(axes) axes2 = vtk.vtkCubeAxesActor() axes2.SetBounds( bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]) axes2.SetCamera(ren2.GetActiveCamera()) axes2.SetXLabelFormat(axes.GetXLabelFormat())
def animate(self, pd, ind): """ Helper function called by **deformableRegistration** if **animate** is *True*. Spawns a window with an interactive 3-D rendering of the current analyzed object in its reference state. The displacements calculated from the deformable image registration can be applied to this object to animate the deformation by pressing the RIGHT-ARROW. Pressing the UP-ARROW will animate and also save the frames to disk. Parameters ---------- pd : vtkPolyData The current analyzed object's reference geometry. ind : int The index of the current polydata in **rsurfs**. Necessary for naming directory created if animation frames are saved. """ pd.GetPointData().SetActiveVectors("Displacement") class vtkTimerCallback(object): def __init__(self): self.timer_count = 0 def execute(self, obj, event): if self.timer_count == 10: self.timer_count = 0 warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.SetScaleFactor(0.1 * (self.timer_count + 1)) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append(getScalars.GetVzComponent()) scalars.append(vectorNorm.GetOutput()) scalars.append(getScalars.GetVxComponent()) scalars.append(getScalars.GetVyComponent()) names = ("Z", "Mag", "X", "Y") for k, a in enumerate(self.actors): calc = vtk.vtkArrayCalculator() scalars[k].GetPointData().GetScalars().SetName(names[k]) calc.SetInputData(scalars[k]) calc.AddScalarArrayName(names[k]) calc.SetResultArrayName(names[k]) calc.SetFunction("%s * 0.1 * %f" % (names[k], self.timer_count + 1)) calc.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(calc.GetOutput()) mapper.SetScalarRange(calc.GetOutput().GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() mapper.Update() a.SetMapper(mapper) cb.scalar_bars[k].SetLookupTable(mapper.GetLookupTable()) iren = obj iren.GetRenderWindow().Render() time.sleep(0.3) if self.key == "Up": try: os.mkdir(self.directory) except: pass w2i = vtk.vtkWindowToImageFilter() w2i.SetInput(obj.GetRenderWindow()) w2i.Update() png = vtk.vtkPNGWriter() png.SetInputConnection(w2i.GetOutputPort()) png.SetFileName(self.directory + os.sep + "frame{:d}.png".format(self.timer_count)) png.Update() png.Write() self.timer_count += 1 def Keypress(self, obj, event): self.key = obj.GetKeySym() if self.key == "Right" or self.key == "Up": for i in range(10): obj.CreateOneShotTimer(1) renwin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renwin) iren.Initialize() cb = vtkTimerCallback() xmins = (0, 0.5, 0, 0.5) xmaxs = (0.5, 1, 0.5, 1) ymins = (0, 0, 0.5, 0.5) ymaxs = (0.5, 0.5, 1, 1) titles = ('Z Displacement', 'Magnitude', 'X Displacement', 'Y Displacement') cb.actors = [] cb.scalar_bars = [] cb.directory = str( os.path.normpath(self._def_dir + os.sep + "animation{:0d}".format(ind + 1))) warpVector = vtk.vtkWarpVector() warpVector.SetInputData(pd) warpVector.Update() poly = warpVector.GetPolyDataOutput() getScalars = vtk.vtkExtractVectorComponents() getScalars.SetInputData(poly) getScalars.Update() vectorNorm = vtk.vtkVectorNorm() vectorNorm.SetInputData(poly) vectorNorm.Update() scalars = [] scalars.append(getScalars.GetVzComponent()) scalars.append(vectorNorm.GetOutput()) scalars.append(getScalars.GetVxComponent()) scalars.append(getScalars.GetVyComponent()) bounds = np.zeros(6, np.float32) pd.GetBounds(bounds) length = np.min(bounds[1::2] - bounds[0:-1:2]) * 0.2 bounds[1] = bounds[0] + length bounds[3] = bounds[2] + length bounds[5] = bounds[4] + length for j in range(4): mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(scalars[j]) mapper.SetScalarRange(scalars[j].GetScalarRange()) mapper.SetScalarModeToUsePointData() mapper.SetColorModeToMapScalars() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetLookupTable(mapper.GetLookupTable()) scalar_bar.SetTitle(titles[j]) scalar_bar.SetLabelFormat("%3.3f") cb.scalar_bars.append(scalar_bar) actor = vtk.vtkActor() actor.SetMapper(mapper) cb.actors.append(actor) renderer = vtk.vtkRenderer() renderer.SetBackground(0., 0., 0.) renwin.AddRenderer(renderer) if j == 0: camera = renderer.GetActiveCamera() else: renderer.SetActiveCamera(camera) triad = vtk.vtkCubeAxesActor() triad.SetCamera(camera) triad.SetFlyModeToStaticTriad() triad.SetBounds(bounds) triad.GetXAxesLinesProperty().SetColor(1.0, 0.0, 0.0) triad.GetYAxesLinesProperty().SetColor(0.0, 1.0, 0.0) triad.GetZAxesLinesProperty().SetColor(0.0, 0.0, 1.0) triad.GetXAxesLinesProperty().SetLineWidth(3.0) triad.GetYAxesLinesProperty().SetLineWidth(3.0) triad.GetZAxesLinesProperty().SetLineWidth(3.0) triad.XAxisLabelVisibilityOff() triad.YAxisLabelVisibilityOff() triad.ZAxisLabelVisibilityOff() triad.XAxisTickVisibilityOff() triad.YAxisTickVisibilityOff() triad.ZAxisTickVisibilityOff() triad.XAxisMinorTickVisibilityOff() triad.YAxisMinorTickVisibilityOff() triad.ZAxisMinorTickVisibilityOff() renderer.SetViewport(xmins[j], ymins[j], xmaxs[j], ymaxs[j]) renderer.AddActor(actor) renderer.AddActor2D(scalar_bar) renderer.AddActor(triad) renderer.ResetCamera() renwin.Render() iren.AddObserver('TimerEvent', cb.execute) iren.AddObserver('KeyPressEvent', cb.Keypress) iren.Start()
# Create a superquadric superquadricSource = vtk.vtkSuperquadricSource() superquadricSource.SetPhiRoundness(3.1) superquadricSource.SetThetaRoundness(1.0) superquadricSource.Update() # needed to GetBounds later renderer = vtk.vtkRenderer() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(superquadricSource.GetOutputPort()) superquadricActor = vtk.vtkActor() superquadricActor.SetMapper(mapper) cubeAxesActor = vtk.vtkCubeAxesActor() cubeAxesActor.SetBounds(superquadricSource.GetOutput().GetBounds()) cubeAxesActor.SetCamera(renderer.GetActiveCamera()) cubeAxesActor.GetTitleTextProperty(0).SetColor(1.0, 0.0, 0.0) cubeAxesActor.GetLabelTextProperty(0).SetColor(1.0, 0.0, 0.0) cubeAxesActor.GetTitleTextProperty(1).SetColor(0.0, 1.0, 0.0) cubeAxesActor.GetLabelTextProperty(1).SetColor(0.0, 1.0, 0.0) cubeAxesActor.GetTitleTextProperty(2).SetColor(0.0, 0.0, 1.0) cubeAxesActor.GetLabelTextProperty(2).SetColor(0.0, 0.0, 1.0) cubeAxesActor.DrawXGridlinesOn() cubeAxesActor.DrawYGridlinesOn() cubeAxesActor.DrawZGridlinesOn() if vtk.VTK_MAJOR_VERSION > 5:
def addAxes(screenSize,ren,xRange,yRange,zRange,axesBounds): axes2 = vtk.vtkCubeAxesActor() axes2.SetCamera(ren.GetActiveCamera()) axes2.SetScreenSize(screenSize) axes2.SetFlyModeToOuterEdges() axes2.SetEnableDistanceLOD(0) axes2.SetEnableViewAngleLOD(0) axes2.SetLabelScaling(0,0,0,0) axes2.SetXLabelFormat("%3.0f") axes2.SetXTitle('Easting [UTM km]') axes2.SetXAxisRange(xRange) axes2.GetTitleTextProperty(0).SetColor(0.0,0.0,0.0) axes2.GetLabelTextProperty(0).SetColor(0.0,0.0,0.0) axes2.GetLabelTextProperty(0).SetOrientation(0.0) axes2.GetLabelTextProperty(0).SetFontSize(50) axes2.GetLabelTextProperty(0).SetVerticalJustificationToCentered() axes2.GetXAxesGridlinesProperty().SetColor(0.0,0.0,0.0) axes2.GetXAxesLinesProperty().SetColor(0.0,0.0,0.0) axes2.DrawXGridlinesOff() axes2.DrawXInnerGridlinesOff() axes2.SetYLabelFormat("%3.0f") axes2.SetYTitle('Northing [UTM km]') axes2.SetYAxisRange(yRange) axes2.GetTitleTextProperty(1).SetColor(0.0,0.0,0.0) axes2.GetLabelTextProperty(1).SetColor(0.0,0.0,0.0) axes2.GetLabelTextProperty(1).SetOrientation(0.0) axes2.GetYAxesGridlinesProperty().SetColor(0.0,0.0,0.0) axes2.GetYAxesLinesProperty().SetColor(0.0,0.0,0.0) axes2.DrawYGridlinesOff() axes2.DrawYInnerGridlinesOff() axes2.SetZLabelFormat('%.0f') axes2.SetZTitle('Depth [km b.s.l.]') axes2.SetZAxisRange(zRange) axes2.GetTitleTextProperty(2).SetColor(0.0,0.0,0.0) axes2.GetLabelTextProperty(2).SetColor(0.0,0.0,0.0) axes2.GetLabelTextProperty(2).SetOrientation(0.0) axes2.GetZAxesGridlinesProperty().SetColor(0.0,0.0,0.0) axes2.GetZAxesLinesProperty().SetColor(0.0,0.0,0.0) axes2.DrawZGridlinesOff() axes2.DrawZInnerGridlinesOff() axes2.SetBounds(axesBounds) return axes2