def create_cell_picker(self): """creates the vtk picker objects""" self.cell_picker = vtk.vtkCellPicker() self.node_picker = vtk.vtkPointPicker() self.area_picker = vtk.vtkAreaPicker() # vtkRenderedAreaPicker? self.rubber_band_style = vtk.vtkInteractorStyleRubberBandPick() #vtk.vtkInteractorStyleRubberBand2D #vtk.vtkInteractorStyleRubberBand3D #vtk.vtkInteractorStyleRubberBandZoom #vtk.vtkInteractorStyleAreaSelectHover #vtk.vtkInteractorStyleDrawPolygon #vtk.vtkAngleWidget #vtk.vtkAngleRepresentation2D #vtk.vtkAngleRepresentation3D #vtk.vtkAnnotation #vtk.vtkArrowSource #vtk.vtkGlyph2D #vtk.vtkGlyph3D #vtk.vtkHedgeHog #vtk.vtkLegendBoxActor #vtk.vtkLegendScaleActor #vtk.vtkLabelPlacer self.cell_picker.SetTolerance(0.001) self.node_picker.SetTolerance(0.001)
def start_pick(self): #Required to change interactor style = vtk.vtkInteractorStyleRubberBandPick() self.iren.SetInteractorStyle(style) picker = vtk.vtkAreaPicker() self.iren.SetPicker(picker) picker.AddObserver("EndPickEvent", self.picker_callback)
def __init__(self, volume): super(VtkWindow, self).__init__() self._default_size = 800 self.resize(self._default_size, self._default_size) self._volume = numpy.ascontiguousarray(volume, dtype="float32") self._central_widget = QtWidgets.QWidget(self) self._vtk_widget = QVTKRenderWindowInteractor(self._central_widget) self._vtk_widget.SetInteractorStyle( vtk.vtkInteractorStyleRubberBandPick()) self._float_array = vtk.vtkFloatArray() self._float_array.SetNumberOfComponents(1) self._float_array.SetVoidArray(self._volume, numpy.product(self._volume.shape), 1) self._image_data = vtk.vtkImageData() self._image_data.SetDimensions(*self._volume.shape) self._image_data.GetPointData().SetScalars(self._float_array) self._renderer = vtk.vtkRenderer() self._renderer.SetBackground(0., 0., 0.) self._layout = QtWidgets.QVBoxLayout() self._layout.addWidget(self._vtk_widget) self._central_widget.setLayout(self._layout) self.setCentralWidget(self._central_widget)
def __init__(self, volume, spacing=(1., 1., 1.)): super(InteractiveIsosurface, self).__init__() self._default_size = (600, 600) self.resize(*self._default_size) self._surface_object = IsoSurface(volume, spacing=spacing) self._central_widget = QtWidgets.QWidget(self) self._vtk_widget = QVTKRenderWindowInteractor(self._central_widget) self._vtk_widget.SetInteractorStyle( _vtk.vtkInteractorStyleRubberBandPick()) self._renderer = _vtk.vtkRenderer() self._renderer.SetBackground(0., 0., 0.) self._surface_object.set_renderer(self._renderer) self._THRESHOLD_SLIDER_MAXIMUM = 1000 self._THRESHOLD_SLIDER_INIT = self._THRESHOLD_SLIDER_MAXIMUM/2 self._threshold_table = self._adaptive_slider_values( volume, self._THRESHOLD_SLIDER_MAXIMUM, volume.min(), volume.max()) self._threshold_slider = QtWidgets.QSlider(QtCore.Qt.Horizontal) self._threshold_slider.setMaximum(self._THRESHOLD_SLIDER_MAXIMUM) self._layout = QtWidgets.QVBoxLayout() self._layout.addWidget(self._vtk_widget) self._layout.addWidget(self._threshold_slider) self._central_widget.setLayout(self._layout) self.setCentralWidget(self._central_widget)
def __init__(self, prnt, controller=None): from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor from vtk import vtkRenderWindow, vtkRenderer import wx import sys self.prnt = prnt self.fullscreen_on = 0 self.controller = controller iren = wxVTKRenderWindowInteractor(prnt, -1, size=prnt.GetSize()) iren.SetPosition((0, 0)) renwin = iren.GetRenderWindow() renwin.StereoCapableWindowOn() renwin.StereoRenderOff() if (sys.platform == 'linux2'): iren.AddObserver("CharEvent", self.key_down) iren.Show(1) iren.Render() elif (sys.platform == 'win32'): from vtk import vtkInteractorStyleRubberBandPick style = vtkInteractorStyleRubberBandPick() iren.SetInteractorStyle(style) iren.SetDesiredUpdateRate(1) iren.Enable(1) else: print "Check OS behaviour to determine how renderer and fullscreen will work on data_viewer" self.iren = iren
def __init__(self, volume): super(VtkWindow, self).__init__() self._default_size = 600 self.resize(self._default_size, self._default_size) self._volume = numpy.ascontiguousarray(volume, dtype="float32") self._central_widget = QtGui.QWidget(self) self._vtk_widget = QVTKRenderWindowInteractor(self._central_widget) self._vtk_widget.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) self._float_array = vtk.vtkFloatArray() self._float_array.SetNumberOfComponents(1) self._float_array.SetVoidArray(self._volume, numpy.product(self._volume.shape), 1) self._image_data = vtk.vtkImageData() self._image_data.SetDimensions(*self._volume.shape) self._image_data.GetPointData().SetScalars(self._float_array) self._renderer = vtk.vtkRenderer() self._renderer.SetBackground(0., 0., 0.) self._layout = QtGui.QVBoxLayout() self._layout.addWidget(self._vtk_widget) self._central_widget.setLayout(self._layout) self.setCentralWidget(self._central_widget)
def start_pick(self): #Required to change interactor style=vtk.vtkInteractorStyleRubberBandPick() self.iren.SetInteractorStyle(style) picker = vtk.vtkAreaPicker() self.iren.SetPicker(picker) picker.AddObserver("EndPickEvent", self.picker_callback)
def __init__(self, data, parent): super(SliceViewer, self).__init__() self._data = data self._lut = None self._actors = {} self._camera = None #self._slice_generator = SliceGenerator(self._data.get_image_side(), self._data.get_curvature()) #self._workspace = QtGui.QWorkspace() self._widget = QtGui.QWidget(parent) self._vtk_widget = QVTKRenderWindowInteractor(self._widget) self._vtk_widget.SetInteractorStyle( vtk.vtkInteractorStyleRubberBandPick()) #self._vtk_widget = QtGui.QPushButton("Foo", parent=self._widget) layout = QtGui.QVBoxLayout() #layout.addWidget(self._workspace) layout.addWidget(self._vtk_widget) #self._workspace.addWindow(self._vtk_widget) self._widget.setLayout(layout) # self._vtk_widget.Initialize() # self._vtk_widget.Start() self._renderer = vtk.vtkRenderer() self._renderer.SetDraw(0) self._vtk_render_window = self._vtk_widget.GetRenderWindow() self._vtk_render_window.AddRenderer(self._renderer)
def __init__(self, volume): super(InteractiveIsosurface, self).__init__() self._default_size = (600, 600) self.resize(*self._default_size) #self._volume = numpy.ascontiguousarray(volume, dtype="float32") self._surface_object = IsoSurface(volume) self._central_widget = QtGui.QWidget(self) self._vtk_widget = QVTKRenderWindowInteractor(self._central_widget) self._vtk_widget.SetInteractorStyle(_vtk.vtkInteractorStyleRubberBandPick()) self._renderer = _vtk.vtkRenderer() self._renderer.SetBackground(0., 0., 0.) self._surface_object.set_renderer(self._renderer) self._THRESHOLD_SLIDER_MAXIMUM = 1000 self._THRESHOLD_SLIDER_INIT = self._THRESHOLD_SLIDER_MAXIMUM/2 self._threshold_table = self._adaptive_slider_values(volume, self._THRESHOLD_SLIDER_MAXIMUM, volume.min(), volume.max()) self._threshold_slider = QtGui.QSlider(QtCore.Qt.Horizontal) self._threshold_slider.setMaximum(self._THRESHOLD_SLIDER_MAXIMUM) self._layout = QtGui.QVBoxLayout() self._layout.addWidget(self._vtk_widget) self._layout.addWidget(self._threshold_slider) self._central_widget.setLayout(self._layout) self.setCentralWidget(self._central_widget)
def __init__(self, parent=None): super(ModelmapViewer, self).__init__(parent) self._surface_algorithm = None self._surface_actor = None self._volume_scalars = None self._volume = None self._surface_level = 0.5 self._color = (0.2, 0.8, 0.2) self._planes = [] self._volume_max = 0. self._volume_numpy = None self._vtk_widget = QVTKRenderWindowInteractor(self._widget) # _vtk_widget is actually the RenderWindowInteractor self._vtk_widget.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) layout = QtGui.QVBoxLayout() layout.addWidget(self._vtk_widget) self._widget.setLayout(layout) #self._vtk_widget.Initialize() #self._vtk_widget.Start() self._renderer = vtk.vtkRenderer() self._vtk_render_window = self._vtk_widget.GetRenderWindow() self._vtk_render_window.AddRenderer(self._renderer) #self._renderer = self._vtk_widget.GetRenderWindow().GetRenderer() self._lut = vtk_tools.get_lookup_table(0., 1., log=False, colorscale="jet") self._create_volume_map() white = (1., 1., 1.) self._renderer.SetBackground(white)
def start_pick(self): style = vtk.vtkInteractorStyleRubberBandPick() self.iren.SetInteractorStyle(style) picker = vtk.vtkAreaPicker() self.iren.SetPicker(picker) picker.AddObserver("EndPickEvent", self.picker_callback) self.ui.vtkWidget.setFocus()
def plot_planes(array_in, spacing=(1., 1., 1.), log=False, cmap=None): """Plot two interactive planes cutting the provided volume.""" array_in = _numpy.float64(array_in) renderer = _vtk.vtkRenderer() render_window = _vtk.vtkRenderWindow() render_window.AddRenderer(renderer) interactor = _vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) interactor.SetInteractorStyle(_vtk.vtkInteractorStyleRubberBandPick()) if cmap is None: import matplotlib as _matplotlib cmap = _matplotlib.rcParams["image.cmap"] lut = get_lookup_table(max(0., array_in.min()), array_in.max(), log=log, colorscale=cmap) picker = _vtk.vtkCellPicker() picker.SetTolerance(0.005) image_data = array_to_image_data(array_in) image_data.SetSpacing(spacing[2], spacing[1], spacing[0]) def setup_plane(): """Create and setup a singel plane.""" plane = _vtk.vtkImagePlaneWidget() if VTK_VERSION >= 6: plane.SetInputData(image_data) else: plane.SetInput(image_data) plane.UserControlledLookupTableOn() plane.SetLookupTable(lut) plane.DisplayTextOn() plane.SetPicker(picker) plane.SetLeftButtonAction(1) plane.SetMiddleButtonAction(2) plane.SetRightButtonAction(0) plane.SetInteractor(interactor) return plane plane_1 = setup_plane() plane_1.SetPlaneOrientationToYAxes() plane_1.SetSliceIndex(int(array_in.shape[0]*spacing[0]/2)) plane_1.SetEnabled(1) plane_2 = setup_plane() plane_2.SetPlaneOrientationToZAxes() plane_2.SetSliceIndex(int(array_in.shape[1]*spacing[1]/2)) plane_2.SetEnabled(1) renderer.SetBackground(0., 0., 0.) render_window.SetSize(800, 800) interactor.Initialize() render_window.Render() interactor.Start()
def main(fn): reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(fn) reader.Update() converter = vtk.vtkUnstructuredGridToExplicitStructuredGrid() converter.GlobalWarningDisplayOff() # hide VTK errors converter.SetInputConnection(reader.GetOutputPort()) converter.SetInputArrayToProcess(0, 0, 0, 1, 'BLOCK_I') converter.SetInputArrayToProcess(1, 0, 0, 1, 'BLOCK_J') converter.SetInputArrayToProcess(2, 0, 0, 1, 'BLOCK_K') converter.Update() grid = converter.GetOutput() grid.ComputeFacesConnectivityFlagsArray() grid.GetCellData().SetActiveScalars('ConnectivityFlags') scalars = grid.GetCellData().GetArray('ConnectivityFlags') mapper = vtk.vtkDataSetMapper() mapper.SetInputData(grid) mapper.SetColorModeToMapScalars() mapper.SetScalarRange(scalars.GetRange()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() colors = vtk.vtkNamedColors() renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('DimGray')) window = vtk.vtkRenderWindow() window.AddRenderer(renderer) window.SetWindowName('LoadESGrid') window.SetSize(1024, 768) window.Render() camera = renderer.GetActiveCamera() camera.SetPosition(312452.407650, 7474760.406373, 3507.364723) camera.SetFocalPoint(314388.388434, 7481520.509575, -2287.477388) camera.SetViewUp(0.089920, 0.633216, 0.768734) camera.SetDistance(9111.926908) camera.SetClippingRange(595.217338, 19595.429475) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(window) interactor.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) window.Render() interactor.Start()
def plot_planes(array_in, log=False, cmap=None): """Plot two interactive planes cutting the provided volume.""" array_in = _numpy.float64(array_in) renderer = _vtk.vtkRenderer() render_window = _vtk.vtkRenderWindow() render_window.AddRenderer(renderer) interactor = _vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) interactor.SetInteractorStyle(_vtk.vtkInteractorStyleRubberBandPick()) if cmap == None: import matplotlib as _matplotlib cmap = _matplotlib.rcParams["image.cmap"] lut = get_lookup_table(max(0., array_in.min()), array_in.max(), log=log, colorscale=cmap) picker = _vtk.vtkCellPicker() picker.SetTolerance(0.005) image_data = array_to_image_data(array_in) def setup_plane(): """Create and setup a singel plane.""" plane = _vtk.vtkImagePlaneWidget() if VTK_VERSION >= 6: plane.SetInputData(image_data) else: plane.SetInput(image_data) plane.UserControlledLookupTableOn() plane.SetLookupTable(lut) plane.DisplayTextOn() plane.SetPicker(picker) plane.SetLeftButtonAction(1) plane.SetMiddleButtonAction(2) plane.SetRightButtonAction(0) plane.SetInteractor(interactor) return plane plane_1 = setup_plane() plane_1.SetPlaneOrientationToXAxes() plane_1.SetSliceIndex(array_in.shape[0]//2) plane_1.SetEnabled(1) plane_2 = setup_plane() plane_2.SetPlaneOrientationToYAxes() plane_2.SetSliceIndex(array_in.shape[1]//2) plane_2.SetEnabled(1) renderer.SetBackground(0., 0., 0.) render_window.SetSize(800, 800) interactor.Initialize() render_window.Render() interactor.Start()
def setup_window(size=(400, 400), background=(1., 1., 1.)): renderer = _vtk.vtkRenderer() #renderer.SetUseDepthPeeling(True) render_window = _vtk.vtkRenderWindow() render_window.AddRenderer(renderer) interactor = _vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(_vtk.vtkInteractorStyleRubberBandPick()) interactor.SetRenderWindow(render_window) renderer.SetBackground(background[0], background[1], background[2]) render_window.SetSize(size[0], size[1]) interactor.Initialize() render_window.Render() return renderer, render_window, interactor
def setup_window(size=(800, 800), background=(1., 1., 1.)): """Returns (renderer, render_window, interactor)""" renderer = _vtk.vtkRenderer() render_window = _vtk.vtkRenderWindow() render_window.AddRenderer(renderer) interactor = _vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(_vtk.vtkInteractorStyleRubberBandPick()) interactor.SetRenderWindow(render_window) renderer.SetBackground(background[0], background[1], background[2]) render_window.SetSize(size[0], size[1]) interactor.Initialize() render_window.Render() return renderer, render_window, interactor
def vertex_select(self): if self.ui.choose_vertex_button.isChecked(): self.vertex_actor.SetVisibility(True) self.iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) picker = vtk.vtkAreaPicker() self.iren.SetPicker(picker) picker.AddObserver("EndPickEvent", self.picker_callback) self.ui.trans_origin_button.setEnabled(False) self.ui.vtkWidget.setFocus() self.ui.vtkWidget.update() else: self.ui.trans_origin_button.setEnabled(False) self.vertex_actor.SetVisibility(False) self.ui.trans_origin_button.setEnabled(True) self.iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) self.transform_origin() self.ui.vtkWidget.update()
def plot_isosurface(volume, level=None): """Plot isosurfaces of the provided module. Levels can be iterable or singel value.""" surface_object = IsoSurface(volume, level) renderer = _vtk.vtkRenderer() render_window = _vtk.vtkRenderWindow() render_window.AddRenderer(renderer) interactor = _vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) interactor.SetInteractorStyle(_vtk.vtkInteractorStyleRubberBandPick()) #renderer.AddActor(surface_object.get_actor()) surface_object.set_renderer(renderer) renderer.SetBackground(0., 0., 0.) render_window.SetSize(800, 800) interactor.Initialize() render_window.Render() interactor.Start()
def plot_isosurface(volume, level=None, spacing=(1., 1., 1.)): """Plot isosurfaces of the provided module. Levels can be iterable or singel value.""" surface_object = IsoSurface(volume, level, spacing) renderer = _vtk.vtkRenderer() render_window = _vtk.vtkRenderWindow() render_window.AddRenderer(renderer) interactor = _vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) interactor.SetInteractorStyle(_vtk.vtkInteractorStyleRubberBandPick()) surface_object.set_renderer(renderer) renderer.SetBackground(0., 0., 0.) render_window.SetSize(800, 800) interactor.Initialize() render_window.Render() interactor.Start()
def __init__(self, parent=None): super(RotationViewer, self).__init__() #self._widget = QtGui.QWidget(parent) self._vtk_widget = QVTKRenderWindowInteractor(self._widget) # _vtk_widget is actually the RenderWindowInteractor self._vtk_widget.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) #self._vtk_widget.Initialize() layout = QtGui.QVBoxLayout() layout.addWidget(self._vtk_widget) self._widget.setLayout(layout) self._renderer = vtk.vtkRenderer() self._vtk_widget.GetRenderWindow().AddRenderer(self._renderer) #self._mlab_widget = embedded_mayavi.MlabWidget() self._setup_done = False self._points = None self._default_sphere_n = 10 self._sphere = vtk_tools.SphereMap(self._default_sphere_n) self._renderer.AddViewProp(self._sphere.get_actor()) self._renderer.SetBackground(1., 1., 1.)
def __init__(self, parent=None): super(ModelmapViewer, self).__init__(parent) self._surface_algorithm = None self._surface_actor = None self._volume_scalars = None self._volume = None self._surface_level = 0.5 self._color = (0.2, 0.8, 0.2) self._planes = [] self._volume_max = 0. self._volume_numpy = None self._vtk_widget = QVTKRenderWindowInteractor( self._widget) # _vtk_widget is actually the RenderWindowInteractor self._vtk_widget.SetInteractorStyle( vtk.vtkInteractorStyleRubberBandPick()) layout = QtGui.QVBoxLayout() layout.addWidget(self._vtk_widget) self._widget.setLayout(layout) #self._vtk_widget.Initialize() #self._vtk_widget.Start() self._renderer = vtk.vtkRenderer() self._renderer.SetDraw(0) self._vtk_render_window = self._vtk_widget.GetRenderWindow() self._vtk_render_window.AddRenderer(self._renderer) #self._renderer = self._vtk_widget.GetRenderWindow().GetRenderer() self._lut = vtk_tools.get_lookup_table(0., 1., log=False, colorscale="jet") self._create_volume_map() #self._setup_slices() #self._setup_surface() white = (1., 1., 1.) self._renderer.SetBackground(white)
def main(): grid = create_explicit_structured_grid((5, 6, 7), (20, 10, 1)) grid = convert_to_unstructured_grid(grid) grid = convert_to_explicit_structured_grid(grid) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(grid) colors = vtk.vtkNamedColors() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().LightingOff() actor.GetProperty().SetColor(colors.GetColor3d('Seashell')) renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('DarkSlateGray')) window = vtk.vtkRenderWindow() window.AddRenderer(renderer) window.SetWindowName('CreateESGrid') window.SetSize(1024, 768) window.Render() camera = renderer.GetActiveCamera() camera.SetPosition(8.383354, -72.468670, 94.262605) camera.SetFocalPoint(42.295234, 21.111537, -0.863606) camera.SetViewUp(0.152863, 0.676710, 0.720206) camera.SetDistance(137.681759) camera.SetClippingRange(78.173985, 211.583658) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(window) interactor.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) window.Render() interactor.Start()
def __init__(self, data, parent): super(SliceViewer, self).__init__() self._data = data self._lut = None self._actors = None self._camera = None #self._slice_generator = SliceGenerator(self._data.get_image_side(), self._data.get_curvature()) #self._workspace = QtGui.QWorkspace() self._widget = QtGui.QWidget(parent) self._vtk_widget = QVTKRenderWindowInteractor(self._widget) self._vtk_widget.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) #self._vtk_widget = QtGui.QPushButton("Foo", parent=self._widget) layout = QtGui.QVBoxLayout() #layout.addWidget(self._workspace) layout.addWidget(self._vtk_widget) #self._workspace.addWindow(self._vtk_widget) self._widget.setLayout(layout) # self._vtk_widget.Initialize() # self._vtk_widget.Start() self._renderer = vtk.vtkRenderer() self._vtk_render_window = self._vtk_widget.GetRenderWindow() self._vtk_render_window.AddRenderer(self._renderer)
def test_vtkInteractorStyleRubberBandPick(): ren = vtk.vtkRenderer() ren.SetBackground(1.0, 1.0, 1.0) V, T = box_model(5, 10, 1.0, 1.0) poly_data = numpy_to_vtkPolyData(V, faces.faces_to_cell_array(T)) idFilter = vtk.vtkIdFilter() idFilter.SetInput(poly_data) idFilter.SetIdsArrayName('i') idFilter.Update() poly_data = idFilter.GetOutput() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(poly_data) mapper.SetScalarVisibility(False) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(0.0, 0.6, 0.3) ren.AddActor(actor) visible = vtk.vtkSelectVisiblePoints() visible.SetInput(poly_data) visible.SetRenderer(ren) # highlight sphere = vtk.vtkSphereSource() sphere.SetRadius(0.2) highlight_poly_data = vtk.vtkPolyData() highlight_glyph = vtk.vtkGlyph3D() highlight_glyph.SetInput(highlight_poly_data) highlight_glyph.SetSourceConnection(sphere.GetOutputPort()) highlight_mapper = vtk.vtkPolyDataMapper() highlight_mapper.SetInputConnection(highlight_glyph.GetOutputPort()) highlight_actor = vtk.vtkActor() highlight_actor.SetMapper(highlight_mapper) highlight_actor.GetProperty().SetColor(1.0, 0.0, 0.0) highlight_actor.VisibilityOff() highlight_actor.PickableOff() ren.AddActor(highlight_actor) # render window render_window = vtk.vtkRenderWindow() render_window.AddRenderer(ren) render_window.SetSize(400, 400) picker = vtk.vtkAreaPicker() def pickCallback(obj, event): props = obj.GetProp3Ds() if props.GetNumberOfItems() <= 0: return extract_geometry = vtk.vtkExtractGeometry() extract_geometry.SetImplicitFunction(picker.GetFrustum()) extract_geometry.SetInput(props.GetLastProp3D().GetMapper().GetInput()) extract_geometry.Update() unstructured_grid = extract_geometry.GetOutput() if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0: return visible.Update() if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0: return i = np.intersect1d( vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i')), vtk_to_numpy(visible.GetOutput().GetPointData().GetArray('i'))) if i.shape[0] <= 0: return vtk_points = vtk.vtkPoints() vtk_points.SetNumberOfPoints(i.shape[0]) vtk_points_data = vtk_to_numpy(vtk_points.GetData()) vtk_points_data.flat = np.require(V[i], np.float32, 'C') highlight_poly_data.SetPoints(vtk_points) highlight_actor.VisibilityOn() picker.AddObserver('EndPickEvent', pickCallback) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(render_window) iren.SetPicker(picker) ren.ResetCamera() render_window.Render() style = vtk.vtkInteractorStyleRubberBandPick() style.SetCurrentRenderer(ren) iren.SetInteractorStyle(style) iren.Initialize() iren.Start()
def _setup_pipeline(self): ren = vtk.vtkRenderer() ren.SetBackground(1.0, 1.0, 1.0) color_points = vtk.vtkProgrammableFilter() def callback_color_points(): input_ = color_points.GetInput() output = color_points.GetOutput() output.ShallowCopy(input_) lookup = vtk.vtkFloatArray() lookup.SetNumberOfValues(input_.GetNumberOfPoints()) npy_lookup = vtk_to_numpy(lookup) npy_lookup.flat = self._k.astype( np.float32) / (COLORMAP.shape[0] - 1) output.GetPointData().SetScalars(lookup) color_points.SetExecuteMethod(callback_color_points) source = vtk.vtkCubeSource() vertices_glyph = vtk.vtkGlyph3D() vertices_glyph.SetInputConnection(color_points.GetOutputPort()) vertices_glyph.SetSourceConnection(source.GetOutputPort()) vertices_glyph.SetScaleModeToDataScalingOff() vertices_glyph.SetColorModeToColorByScalar() vertices_mapper = vtk.vtkPolyDataMapper() vertices_mapper.SetInputConnection(vertices_glyph.GetOutputPort()) vertices_mapper.SetLookupTable(LUT) vertices_actor = vtk.vtkActor() vertices_actor.SetMapper(vertices_mapper) vertices_actor.GetProperty().SetColor(*COLORMAP[0, :3]) vertices_actor.PickableOff() vertices_actor.VisibilityOff() ren.AddActor(vertices_actor) color_faces = vtk.vtkProgrammableFilter() def callback_color_faces(): input_ = color_faces.GetInput() output = color_faces.GetOutput() output.ShallowCopy(input_) lookup = vtk.vtkFloatArray() lookup.SetNumberOfValues(input_.GetNumberOfPolys()) npy_lookup = vtk_to_numpy(lookup) labelled_T = self._k[self.T] for i in xrange(input_.GetNumberOfPolys()): l = np.argmax(np.bincount(labelled_T[i])) npy_lookup[i] = float(l) / (COLORMAP.shape[0] - 1) output.GetCellData().SetScalars(lookup) color_faces.SetExecuteMethod(callback_color_faces) model_mapper = vtk.vtkPolyDataMapper() model_mapper.SetInputConnection(color_faces.GetOutputPort()) model_mapper.SetLookupTable(LUT) model_actor = vtk.vtkActor() model_actor.SetMapper(model_mapper) model_actor.GetProperty().SetColor(*COLORMAP[0, :3]) model_actor.VisibilityOff() ren.AddActor(model_actor) render_window = vtk.vtkRenderWindow() render_window.AddRenderer(ren) render_window.SetSize(400, 400) self.SetRenderWindow(render_window) visible = vtk.vtkSelectVisiblePoints() visible.SetRenderer(ren) picker = vtk.vtkAreaPicker() def callback_picker(obj, event): props = obj.GetProp3Ds() if props.GetNumberOfItems() <= 0: return extract_geometry = vtk.vtkExtractGeometry() extract_geometry.SetImplicitFunction(picker.GetFrustum()) extract_geometry.SetInput(visible.GetInput()) extract_geometry.Update() unstructured_grid = extract_geometry.GetOutput() if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0: return i = vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i')) if self.select_only_visible: visible.Update() if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0: return i = np.intersect1d( i, vtk_to_numpy( visible.GetOutput().GetPointData().GetArray('i'))) if i.shape[0] <= 0: return self.set_labels(self.current_label, i) picker.AddObserver('EndPickEvent', callback_picker) iren = self.GetInteractor() iren.SetRenderWindow(render_window) iren.SetPicker(picker) style = vtk.vtkInteractorStyleRubberBandPick() style.SetCurrentRenderer(ren) iren.SetInteractorStyle(style) self.pipeline = locals() self.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
scalars.SetValue(i, numpy.random.random()) poly_data.GetPointData().SetScalars(scalars) poly_data.Modified() print "scalars done" mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(poly_data) print "mapper done" actor = vtk.vtkActor() actor.SetMapper(mapper) print "actor done" renderer = vtk.vtkRenderer() renderer.SetBackground(1., 1., 1.) print "renderer done" render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) print "render window done" interactor = vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) interactor.SetRenderWindow(render_window) print "interactor done" renderer.AddActor(actor) print "add actor" render_window.Render() print "render" #interactor.Start() print "start interactor"
def om_display_vtk(f,d = 0,n = 0): """ This function displays a VTK::vtk file generated with OpenMEEG. Such a file defines a polydata, containing points and triangles of a single mesh. Most often a EEG helmet mesh and associated leadfield. """ welcome = """Welcome\n\n Move the slider to see all sources (columns of the input matrix)\n Press 'r': To select points/cells.\n""" # This callback function does updates the mappers for where n is the slider value def CleanPickData(object, event): ren.RemoveActor(selactor) PickData(object, event, selactor, 0, view, text_init) def SelectSource(object, event): # object will be the slider2D slidervalue = int(round(object.GetRepresentation().GetValue())) mapper.GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue)) renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue)) UpdateColorBar(colorBar, mapper) # A window with an interactor renWin = vtk.vtkRenderWindow() renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) # A picker (to pick points/cells) picker = vtk.vtkRenderedAreaPicker() iren.SetPicker(picker) # Read the input file reader = vtk.vtkPolyDataReader() reader.SetFileName(f); reader.Update() poly = reader.GetOutput() renWin.SetWindowName(f+' Potentials-'+str(n)) # determine the number of sources nb_sources = 0 for i in range(poly.GetPointData().GetNumberOfArrays()): if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)): nb_sources += 1 if nb_sources == 0: #the file doesn't provide potentials if not d.__class__ == int: assert(d.shape[0] == poly.GetNumberOfPoints()) nb_sources = d.shape[1] pot = [vtk.vtkDoubleArray() for j in range(d.shape[1])] for j in range(d.shape[1]): pot[j].SetName('Potentials-'+str(j)) for i in range(d.shape[0]): pot[j].InsertNextValue(d[i,j]) poly.GetPointData().AddArray(pot[j]) poly.Update() if not poly.GetPointData().GetGlobalIds('Indices'): ind = vtk.vtkUnsignedIntArray() ind.SetName('Indices') for i in range(poly.GetNumberOfPoints()): ind.InsertNextValue(i) poly.GetPointData().AddArray(ind) poly.GetPointData().SetActiveScalars('Potentials-'+str(n)) mapper = vtk.vtkPolyDataMapper() colorBar = vtk.vtkScalarBarActor() actor = vtk.vtkActor() ren = vtk.vtkRenderer() mapper.SetInput(poly) mapper.SetScalarModeToUsePointData(); mapper.Update() actor.SetMapper(mapper) ren.AddActor(actor) if nb_sources: ren.AddActor2D(colorBar) UpdateColorBar(colorBar, mapper) renWin.AddRenderer(ren) renWin.Render() if nb_sources > 1: # Slider sliderWidget = vtk.vtkSliderWidget() slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1) slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f') slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources) slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint1Coordinate().SetValue(.0, 0.02) slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint2Coordinate().SetValue(1., 0.02); sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider); sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn(); sliderWidget.AddObserver("InteractionEvent", SelectSource); # Selection selactor = vtk.vtkActor() view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot') view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600) # Welcome text text_init = vtk.vtkTextActor() text_init.SetPosition(10, 300) text_init.SetInput(welcome) text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0) view.GetRenderer().AddActor2D(text_init) view.GetInteractor().Initialize() iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData) iren.Initialize() iren.Start()
def SetStyle(self, style=None): if style: self.style = style else: self.style = vtk.vtkInteractorStyleRubberBandPick()
def om_display_vtp(f, n = 0): """ This function displays a VTK::vtp file generated with OpenMEEG. Such a file defines a polydata, containing points and triangles of several meshes which are labelled through a vtkAbstractArray (Strings) associated to the cells (mesh names). Results of the forward problem (or a cortical mapping) can be seen thanks to arrays associated to points and cells (respectively potentials and normals currents). """ welcome = """Welcome\n\n Switch the button: To either see Potentials (on points) or Currents (on triangles)\n Move the slider to see all sources (columns of the input matrix)\n Press 'r': To select points/cells.\n""" # This callback function does updates the mappers for where n is the slider value def CleanPickData(object, event): for i in range(4): rens[i].RemoveActor(selactor) if buttonWidget.GetRepresentation().GetState(): PickData(object, event, selactor, 1, view, text_init) else: PickData(object, event, selactor, 0, view, text_init) def SelectSource(object, event): # object will be the slider2D slidervalue = int(round(object.GetRepresentation().GetValue())) for i in range(4): mappers[i].GetInput().GetPointData().SetActiveScalars("Potentials-"+str(slidervalue)) mappers[i].GetInput().GetCellData().SetActiveScalars("Currents-"+str(slidervalue)) renWin.SetWindowName(renWin.GetWindowName()[0:(renWin.GetWindowName().find('-')+1)]+str(slidervalue)) UpdateColorBar(colorBars[i], mappers[i]) # This callback function does updates the Scalar Mode To Use def SelectMode(object, event): # object will be the buttonWidget for i in range(4): if (object.GetRepresentation().GetState()): mappers[i].SetScalarModeToUseCellData() renWin.SetWindowName(renWin.GetWindowName().replace('Potentials','Currents')) else: mappers[i].SetScalarModeToUsePointData() renWin.SetWindowName(renWin.GetWindowName().replace('Currents','Potentials')) UpdateColorBar(colorBars[i], mappers[i]) # A window with an interactor renWin = vtk.vtkRenderWindow() renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) # A picker (to pick points/cells) picker = vtk.vtkRenderedAreaPicker() iren.SetPicker(picker) # Read the input file reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(f); reader.Update() poly = reader.GetOutput() renWin.SetWindowName(f+' Potentials-'+str(n)) # determine the number of sources nb_sources = 0 for i in range(poly.GetPointData().GetNumberOfArrays()): if poly.GetPointData().GetGlobalIds('Potentials-'+str(i)): nb_sources += 1 if n < nb_sources: poly.GetPointData().SetActiveScalars('Potentials-'+str(n)) poly.GetCellData().SetActiveScalars('Currents-'+str(n)) # Get the mesh names cell_labels = poly.GetCellData().GetAbstractArray(0) assert(cell_labels.GetName()=='Names') s = set(); nb_meshes = 0; cell_ids = list() for i in range(cell_labels.GetNumberOfValues()): s.add(cell_labels.GetValue(i)) if len(s)>nb_meshes: # if a label is added, store the ID for the connectivity filter cell_ids.append(i) nb_meshes += 1 # Number of meshes assert(nb_meshes<=4) # Multiple viewports: 4 xmins = [0,.5,0,.5]; xmaxs = [0.5,1,0.5,1]; ymins = [0,0,.5,.5]; ymaxs = [0.5,0.5,1,1] mappers = [vtk.vtkPolyDataMapper() for i in range(4)] colorBars = [vtk.vtkScalarBarActor() for i in range(4)] actors = [vtk.vtkActor() for i in range(4)] rens = [vtk.vtkRenderer() for i in range(4)] for i in range(4): rens[i].SetViewport(xmins[i],ymins[i],xmaxs[i],ymaxs[i]); # Display the meshes if (i < nb_meshes): # Create a connectivity filter based on cell seeded region (to display # only one mesh per viewport) conn = vtk.vtkPolyDataConnectivityFilter() conn.SetInput(poly) conn.SetExtractionModeToCellSeededRegions() conn.AddSeed(cell_ids[i]); conn.Update() actor_meshname = vtk.vtkTextActor(); actor_meshname.SetInput(cell_labels.GetValue(cell_ids[i])); actor_meshname.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport(); actor_meshname.SetPosition(0.5, 0.85); tprop = actor_meshname.GetTextProperty(); tprop.SetFontSize(30) tprop.SetFontFamilyToArial(); tprop.SetColor(1, 1, 1); tprop.SetJustificationToCentered() mappers[i].SetInputConnection(conn.GetOutputPort()) mappers[i].SetScalarModeToUsePointData(); mappers[i].Update() if nb_sources: rens[i].AddActor2D(colorBars[i]) actors[i].SetMapper(mappers[i]) rens[i].AddActor2D(actor_meshname) rens[i].AddActor(actors[i]) if (i == 0): cam = rens[i].GetActiveCamera() rens[i].ResetCamera() else: # Create a plane to cut plane = vtk.vtkPlane(); plane.SetOrigin(0,0,0); plane.SetNormal(1,0,0); # Create cutter extract = vtk.vtkExtractPolyDataGeometry(); extract.SetInput(poly) extract.SetImplicitFunction(plane); extract.ExtractBoundaryCellsOff() mappers[i].SetInputConnection(extract.GetOutputPort()) mappers[i].SetScalarModeToUsePointData(); mappers[i].Update() # Create plane actor actors[i].SetMapper(mappers[i]) rens[i].AddActor(actors[i]) rens[i].SetActiveCamera(cam) if nb_sources: UpdateColorBar(colorBars[i], mappers[i]) renWin.AddRenderer(rens[i]) renWin.Render(); if nb_sources > 1: # Slider sliderWidget = vtk.vtkSliderWidget() slider = vtk.vtkSliderRepresentation2D(); slider.SetMaximumValue(nb_sources-1) slider.SetValue(n); slider.SetEndCapLength(0.01); slider.SetLabelFormat('%1.0f') slider.SetSliderWidth(0.05); slider.SetSliderLength(1./nb_sources) slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint1Coordinate().SetValue(.0 ,0.02) slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedViewport() slider.GetPoint2Coordinate().SetValue(1. ,0.02); sliderWidget.SetInteractor(iren); sliderWidget.SetRepresentation(slider); sliderWidget.SetAnimationModeToAnimate(); sliderWidget.EnabledOn(); sliderWidget.AddObserver("InteractionEvent", SelectSource); if not nb_sources == 0: # The button for choosing Potentials/Currents buttonWidget = vtk.vtkButtonWidget() button = vtk.vtkTexturedButtonRepresentation2D(); button.SetNumberOfStates(2) tex1r = vtk.vtkImageData(); tex2r = vtk.vtkImageData(); prop = vtk.vtkTextProperty(); prop.SetFontSize(24); prop.SetColor(1,0,0); prop.SetBold(2); prop.SetShadow(2); str2im = vtk.vtkFreeTypeStringToImage() str2im.RenderString(prop,'Potentials',tex1r) str2im.RenderString(prop,'Currents',tex2r) button.SetButtonTexture(0, tex1r) button.SetButtonTexture(1, tex2r) buttonWidget.SetInteractor(iren); buttonWidget.SetRepresentation(button); button.SetPlaceFactor(1); button.PlaceWidget([0., 100, 50, 500, 0, 0]); buttonWidget.On() buttonWidget.AddObserver(vtk.vtkCommand.StateChangedEvent,SelectMode); # Selection selactor = vtk.vtkActor() view = vtk.vtkContextView(); view.GetRenderWindow().SetWindowName('Plot') view.GetRenderWindow().SetPosition(600, 0); view.GetRenderWindow().SetSize(600, 600) # Welcome text text_init = vtk.vtkTextActor() text_init.SetPosition(10, 300) text_init.SetInput(welcome) text_init.GetTextProperty().SetColor(1.0, 0.0, 0.0) view.GetRenderer().AddActor2D(text_init) view.GetInteractor().Initialize() iren.AddObserver(vtk.vtkCommand.EndPickEvent,CleanPickData) iren.Initialize() iren.Start()
scalars.SetValue(i, numpy.random.random()) poly_data.GetPointData().SetScalars(scalars) poly_data.Modified() print "scalars done" mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(poly_data) print "mapper done" actor = vtk.vtkActor() actor.SetMapper(mapper) print "actor done" renderer = vtk.vtkRenderer() renderer.SetBackground(1.0, 1.0, 1.0) print "renderer done" render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) print "render window done" interactor = vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(vtk.vtkInteractorStyleRubberBandPick()) interactor.SetRenderWindow(render_window) print "interactor done" renderer.AddActor(actor) print "add actor" render_window.Render() print "render" # interactor.Start() print "start interactor"