def __init__(self, parent = None, title=None): QtGui.QMainWindow.__init__(self, parent) if title: self.setWindowTitle(title) else: self.setWindowTitle('Visualization') self.vl = QtGui.QVBoxLayout() self.hl = QtGui.QHBoxLayout() self.frame = QtGui.QFrame() self.vtkWidget, self.ren, self.iren, self.intstyle = self.init_vtk_widget(self.frame) self.save_main_vizualization_button = self.init_save_vizualization_button( self.frame, self.vtkWidget.GetRenderWindow() ) self.vl.addWidget(self.vtkWidget) self.hl.insertLayout(-1, self.vl) self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.vtkWidget.GetRenderWindow().LineSmoothingOn() self.vtkWidget.GetRenderWindow().PolygonSmoothingOn() self.vtkWidget.GetRenderWindow().PointSmoothingOn() self.vtkWidget.GetRenderWindow().SetMultiSamples(8) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() self.ren.GetActiveCamera().ParallelProjectionOn() self.intstyle = vtk.vtkInteractorStyleRubberBand2D() self.iren.SetInteractorStyle(self.intstyle) self.ren.SetBackground(1.0, 1.0, 1.0) self.frame.setLayout(self.hl) self.setCentralWidget(self.frame)
def OpenAddBoundaryDlg(self): self.style = vtk.vtkInteractorStyleRubberBand2D() self.position=[0.0,0.0,0.0,0.0] self.statusbar.showMessage('Select Boundary Elements') self.style.area_picker = vtk.vtkRenderedAreaPicker() self.style.AddObserver("LeftButtonReleaseEvent", self.leftButtonReleaseEvent) self.style.SetDefaultRenderer(self.renderer) self.renWinInteract.SetInteractorStyle(self.style) self.renWinInteract.SetPicker(self.style.area_picker)
def set_interaction(self, interaction): if interaction == "rubber_band_2d": for renderer in self.plotter.renderers: renderer.enable_parallel_projection() if hasattr(self.plotter, 'enable_rubber_band_2d_style'): self.plotter.enable_rubber_band_2d_style() else: style = vtk.vtkInteractorStyleRubberBand2D() self.plotter.interactor.SetInteractorStyle(style) else: for renderer in self.plotter.renderers: renderer.disable_parallel_projection() getattr(self.plotter, f'enable_{interaction}_style')()
def show(self, render_window=None): if render_window is None: render_window = vtk.vtkRenderWindow() render_window.SetSize(700, 700) render_window.AddRenderer(self.renderer) render_interactor = vtk.vtkRenderWindowInteractor() if self.allow_rotation: render_interactor.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) else: render_interactor.SetInteractorStyle(vtk.vtkInteractorStyleRubberBand2D()) render_interactor.SetRenderWindow(render_window) render_interactor.Initialize() render_interactor.Start()
def _createwindow(self): ren1 = vtk.vtkRenderer() ren1.AddActor(self.actor) ren1.SetBackground(0.1, 0.2, 0.4) ren1.ResetCamera() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.SetSize(700, 700) iren = vtk.vtkRenderWindowInteractor() if self.rotation: iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) else: iren.SetInteractorStyle(vtk.vtkInteractorStyleRubberBand2D()) iren.SetRenderWindow(renWin) iren.Initialize() iren.Start()
def init_vtk_widget(self, widget): vtk_widget = QVTKRenderWindowInteractor(widget) renderer = vtk.vtkRenderer() vtk_widget.GetRenderWindow().AddRenderer(renderer) renderer.SetBackground(1.0, 1.0, 1.0) interactor = vtk_widget.GetRenderWindow().GetInteractor() interactor_style = vtk.vtkInteractorStyleRubberBand2D() interactor.SetInteractorStyle(interactor_style) vtk_widget.GetRenderWindow().LineSmoothingOn() vtk_widget.GetRenderWindow().PolygonSmoothingOn() vtk_widget.GetRenderWindow().PointSmoothingOn() vtk_widget.GetRenderWindow().SetMultiSamples(8) return vtk_widget, renderer, interactor, interactor_style
def show(self): self.renderer = vtk.vtkRenderer() self.renderer.SetBackground(0.1, 0.2, 0.4) # Blue self.renderer.ResetCamera() self.renderer.AddActor(self.actor) render_window = vtk.vtkRenderWindow() render_window.SetSize(700, 700) render_window.AddRenderer(self.renderer) render_interactor = vtk.vtkRenderWindowInteractor() if self.allow_rotation: render_interactor.SetInteractorStyle( vtk.vtkInteractorStyleTrackballCamera()) else: render_interactor.SetInteractorStyle( vtk.vtkInteractorStyleRubberBand2D()) render_interactor.SetRenderWindow(render_window) render_interactor.Initialize() render_interactor.Start()
def __init__(self, parent=None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() data_file = "/Users/emonson/Data/Fodava/EMoGWDataSets/mnist12_1k_20100521.mat" self.ds = DataSource(data_file) self.pc_class = PCoordsChart(self.ds) self.view = self.pc_class.GetView() self.ui.setupUi(self, self.view.GetRenderWindow()) style = vtk.vtkInteractorStyleRubberBand2D() self.view.SetInteractorStyle(style) # Need this additional command (plus above set style) for this class self.view.SetInteractionModeTo2D() self.view.ResetCamera() self.view.GetInteractor().Start()
def show(*graphics): allow_rotation = True render_window = vtk.vtkRenderWindow() render_window.SetSize(700, 700) render_interactor = vtk.vtkRenderWindowInteractor() if allow_rotation: render_interactor.SetInteractorStyle( vtk.vtkInteractorStyleTrackballCamera()) else: render_interactor.SetInteractorStyle( vtk.vtkInteractorStyleRubberBand2D()) renderer = vtk.vtkRenderer() renderer.SetBackground(0.1, 0.2, 0.4) # Blue renderer.ResetCamera() for g in graphics: g.redraw() renderer.AddActor(g.actor) render_interactor.SetRenderWindow(render_window) render_window.AddRenderer(renderer) render_interactor.Initialize() render_interactor.Start()
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.renWinList = [] # data_file = askopenfilename() data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/mnist1_5c_20100324.mat' # self.openFilesDefaultPath = QtCore.QDir.homePath() # data_file = QtGui.QFileDialog.getOpenFileName(self, # "Load Saved Matlab File", # self.openFilesDefaultPath, # "All Files (*);;Matlab Files (*.mat)") # DataSource loads .mat file and can generate data from it for other views self.ds = DataSource(str(data_file)) # All view classes have access to an instance of that data source for internal queries # Note that the only view which will pull and display data right away is the icicle view # the other views need to be able to initialize without any data and only pull and show # upon the first AnnotationChanged event... # View #0 -- Icicle View # Set up a 2D scene, add an XY chart to it self.chartView = vtk.vtkContextView() self.chartView.GetRenderer().SetBackground(1.0, 1.0, 1.0) self.renWinList.append(self.chartView.GetRenderWindow()) self.chart = vtkvtg.vtkMyChartXY() self.chartView.GetScene().AddItem(self.chart) # View #1 -- AxisImageView self.axisView = vtk.vtkContextView() self.axisView.GetRenderer().SetBackground(1.0, 1.0, 1.0) self.renWinList.append(self.axisView.GetRenderWindow()) self.ai = vtkvtg.vtkAxisImageItem() self.axisView.GetScene().AddItem(self.ai) # Set up all the render windows in the GUI self.ui.setupUi(self, self.renWinList) # Now need to get all the interactors working properly # XY style0 = vtk.vtkInteractorStyleRubberBand2D() self.chartView.GetInteractor().SetInteractorStyle(style0) self.chartView.GetScene().SetInteractorStyle(style0) # Axis images style1 = vtk.vtkInteractorStyleRubberBand2D() self.axisView.GetInteractor().SetInteractorStyle(style1) self.axisView.GetScene().SetInteractorStyle(style1) # Set sizes for veritcal splitters self.ui.splitter.setSizes([200,400]) # Connect signals and slots QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit) # CORE setting up chart and axis images test_id = 68 self.table = self.ds.GetNodeOneScaleCoeffTable(test_id) line1 = vtkvtg.vtkMyPlotPoints() # line1.DebugOn() self.chart.AddPlot(line1) # POINTS line1.SetInput(self.table, 0, 1) line1.SetMarkerStyle(2) line1.SetColor(0, 0, 0, 255) # Tooltip image stack will now be owned by the tooltip, so need to do that differently... id_list = self.ds.PIN[test_id] image_stack = self.ds.GetProjectedImages(id_list) self.chart.SetTooltipImageStack(image_stack) self.chart.SetTooltipShowImage(True) # self.chart.SetTooltipImageScalingFactor(2.0) self.chart.SetTooltipImageTargetSize(40) axis_images = self.ds.GetNodeBasisImages(test_id) center_image = self.ds.GetNodeCenterImage(test_id) self.ai.SetAxisImagesHorizontal() self.ai.SetChartXY(self.chart) self.ai.SetChartXYView(self.chartView) self.ai.SetAxisImageStack(axis_images) self.ai.SetCenterImage(center_image) # Set up annotation link which will carry indices to parallel coordinates chart # for highlighting outside selections (e.g. back from image_flow) # This needs to carry indices, while image_flow link outputs pedigree ids # so conversion happens in HighlightSelectionCallback # data_col_idxs = vtk.vtkAnnotationLink() # data_col_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point # data_col_idxs.GetCurrentSelection().GetNode(0).SetContentType(4) # 2 = PedigreeIds, 4 = Indices # self.chart.SetDataColumnsLink(data_col_idxs) # self.ai.SetDataColumnsLink(data_col_idxs) # Create a annotation link to access selection in XY chart annotationLink = vtk.vtkAnnotationLink() annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4) # Indices # Connect the annotation link to the parallel coordinates representation self.chart.SetAnnotationLink(annotationLink) self.chart.GetAnnotationLink().AddObserver("AnnotationChangedEvent", self.IcicleSelectionCallback) # Set up annotation link which will carry indices to parallel coordinates chart # for highlighting outside selections (e.g. back from image_flow) # This needs to carry indices, while image_flow link outputs pedigree ids # so conversion happens in HighlightSelectionCallback highlight_link_idxs = vtk.vtkAnnotationLink() highlight_link_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point highlight_link_idxs.GetCurrentSelection().GetNode(0).SetContentType(4) # 2 = PedigreeIds, 4 = Indices self.chart.SetHighlightLink(highlight_link_idxs) # Fill selection link with dummy IDs id_array = N.array([0],dtype='int64') id_list = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) highlight_link_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(id_list) highlight_link_idxs.InvokeEvent("AnnotationChangedEvent") # self.updater = vtk.vtkViewUpdater() # self.updater.AddAnnotationLink(data_col_idxs) # self.updater.AddView(self.axisView) # self.updater.AddView(self.chartView) # col_array = N.array([0,1],dtype='int64') # col_vtk = VN.numpy_to_vtkIdTypeArray(col_array, deep=True) # data_col_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(col_vtk) # data_col_idxs.InvokeEvent("AnnotationChangedEvent") self.chart.RecalculateBounds() # Only need to Start() interactor for one view # self.pc_class.GetView().GetInteractor().Start() # Shouldn't have to do this render... for rw in self.renWinList: rw.Render()
def SetStyle(self, style=None): if style: self.style = style else: self.style = vtk.vtkInteractorStyleRubberBand2D()
def __init__(self, parent = None): # Number of slider divisions per integer value self.divs = 10 # self.rot_method = 'alt_axis' self.rot_method = '111' # self.rot_method = 'simple' self.axis_rescale = False QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() # Set up a 2D scene, add an XY chart to it self.view = vtk.vtkContextView() self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0) self.ui.setupUi(self, self.view.GetRenderWindow()) if self.rot_method == 'alt_axis': self.ui.comboBox.setCurrentIndex(0) elif self.rot_method == '111': self.ui.comboBox.setCurrentIndex(1) else: self.ui.comboBox.setCurrentIndex(2) style = vtk.vtkInteractorStyleRubberBand2D() self.view.GetInteractor().SetInteractorStyle(style) self.view.GetScene().SetInteractorStyle(style) # Need this additional command (plus above set style) for this class # self.view.SetInteractionModeTo2D() self.chart = vtk.vtkChartXY() self.chart.SetShowLegend(False) # Create a annotation link to access selection in parallel coordinates view annotationLink = vtk.vtkAnnotationLink() # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010) # See vtkSelectionNode doc for field and content type enum values annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4) # Indices # Connect the annotation link to the parallel coordinates representation self.chart.SetAnnotationLink(annotationLink) self.view.GetScene().AddItem(self.chart) # Set up callback to update 3d render window when selections are changed in # parallel coordinates view annotationLink.AddObserver("AnnotationChangedEvent", self.selectionCallback) QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit) QtCore.QObject.connect(self.ui.actionOpen, QtCore.SIGNAL("triggered()"), self.LoadData) QtCore.QObject.connect(self.ui.horizontalSlider, QtCore.SIGNAL("valueChanged(int)"), self.columnUpdate) QtCore.QObject.connect(self.ui.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.rotMethodChanged) self.LoadData() self.view.ResetCamera() self.ui.vtkWidget.GetRenderWindow().Render() self.view.GetInteractor().Start()
def plot(self, struct): # creates self. data1, legend, filename, fieldname, dim, has_field, tracker, revision if not self.call_config(struct): return # creates self.src #if not self.call_src(): # return self.rens[0].SetBackground((1.0, 1.0, 1.0)) self.xyplot = vtk.vtkXYPlotActor() if self.tracker.is_void: return False elif self.tracker.type == "node_files": series_num = 0 labels = [] trackers = self.tracker.trackers self.dataname = [] for tracker in trackers: self.dataname.append(tracker.get_vtkfile()) for name in self.dataname: res = self.Gr2_File_to_Polydata(name) polydata = res.get('polydata') labels.extend(res.get('labels')[min(len(labels), 3):]) series_num = series_num + res.get('series_num') for pd in polydata: if vtk.vtkVersion.GetVTKMajorVersion() < 6: self.xyplot.AddInput(pd) else: self.xyplot.AddDataSetInput(pd) # return False else: self.dataname = self.tracker.get_vtkfile() #returns 'labels', 'series_num' and 'polydata' keys res = self.Gr2_File_to_Polydata(self.dataname) polydata = res.get('polydata') labels = res.get('labels') series_num = res.get('series_num') for pd in polydata: if vtk.vtkVersion.GetVTKMajorVersion() < 6: self.xyplot.AddInput(pd) else: self.xyplot.AddDataSetInput(pd) self.xyplot.GetPositionCoordinate().SetValue(self.pospi0) self.xyplot.GetPosition2Coordinate().SetValue(self.pospt0) # rel # relative to the ones avobe self.xyplot.SetLegendPosition(self.posli0) self.xyplot.SetLegendPosition2(self.poslt0) # rel # self.xyplot.SetXValuesToArcLength() self.xyplot.SetXValuesToValue() temp = labels[0] if temp is None: temp = '2D graph' self.xyplot.SetTitle(temp) temp = labels[1] if temp is None: temp = 'X axis' self.xyplot.SetXTitle(temp) temp = labels[2] if temp is None: temp = 'Y axis' self.xyplot.SetYTitle(temp) for t in range(series_num): temp = labels[3 + t] if temp is None: temp = 'Series ' + unicode(t) self.xyplot.SetPlotLabel(t, temp) self.xyplot.SetPlotColor(t, palette[t % len(palette)]) self.xyplot.LegendOn() self.xyplot.PlotPointsOn() self.xyplot.GetProperty().SetColor(0.0, 0.0, 0.0) self.xyplot.GetProperty().SetPointSize(3) # Set text prop color (same color for backward compat with test) # Assign same object to all text props tprop = self.xyplot.GetTitleTextProperty() tprop.SetColor(self.xyplot.GetProperty().GetColor()) self.xyplot.SetAxisTitleTextProperty(tprop) self.xyplot.SetAxisLabelTextProperty(tprop) self.copy_params(struct) self.set_iren() self.inter = vtk.vtkInteractorStyleRubberBand2D() #self.inter = vtk.vtkInteractorStyleRubberBandZoom() self.inter.SetInteractor(self.iren) self.widget.SetInteractorStyle(self.inter) self.rens[0].AddActor(self.xyplot) self.last = None self.inter.AddObserver("SelectionChangedEvent", self.selection) # meanwhile not enough with the above: self.inter.AddObserver("StartInteractionEvent", self.selectioni) self.inter.AddObserver("EndInteractionEvent", self.selectionf) self.done = True
import math import vtkvtg from data_source import DataSource data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/mnist1_5c_20100324.mat' # DataSource loads .mat file and can generate data from it for other views ds = DataSource(data_file) renwin = vtk.vtkRenderWindow() renwin.SetMultiSamples(0) renwin.SetSize(400, 600) iren = vtk.vtkRenderWindowInteractor() istyle = vtk.vtkInteractorStyleRubberBand2D() iren.SetInteractorStyle(istyle) iren.SetRenderWindow(renwin) # setup the 2 view ports viewports = [(0.0,0.0,1.0,0.5), (0.0,0.5,1.0,1.0)] # CHART chartRen = vtk.vtkRenderer() chartRen.SetBackground(1.0,1.0,1.0) chartRen.SetViewport(viewports[1]) renwin.AddRenderer(chartRen) # Testing my custom chart class which has image hover tooltips chart = vtkvtg.vtkMyChartXY() chartScene = vtk.vtkContextScene()
def loadGraph(): # ---------- # Load and construct whole graph and multi-resolution data from Matlab structure dataDir = '/Users/emonson/Programming/Matlab/EMonson/Fodava/DocumentAnalysis/Analysis/' filename = dataDir + 'X20_042709b.mat' # filename = '/Users/emonson/Programming/Python/VTK/X20_040609b.mat' X = scipy.io.loadmat(filename) # Get graph structure G out of matlab variables G = X['G'] # ---------- # Set multi-resolution level bounds in GUI sliders levelMax = G.Tree.shape[0]-1 ui_window.hSlider_level.setMinimum(1) ui_window.hSlider_level.setMaximum(levelMax) ui_window.spinBox_level.setMinimum(1) ui_window.spinBox_level.setMaximum(levelMax) # Start setting up basis function for display as subgraph ExtBasis = GTree[level,0]['ExtBasis'][0][0][0] basisMax = ExtBasis.shape[1]-1 # zero-based indices # Set particular level basis function bounds in GUI sliders ui_window.hSlider_basisIndex.setMinimum(0) ui_window.hSlider_basisIndex.setMaximum(basisMax) ui_window.spinBox_basisIndex.setMinimum(0) ui_window.spinBox_basisIndex.setMaximum(basisMax) # Build table which will become graph table = vtk.vtkTable() col0 = vtk.vtkIntArray() col0.SetName('index1') col1 = vtk.vtkIntArray() col1.SetName('index2') val = vtk.vtkDoubleArray() val.SetName('weight') Tmat = G.T # Tmat = G.W for ii in range(Tmat.nzmax): col0.InsertNextValue(Tmat.rowcol(ii)[0]) col1.InsertNextValue(Tmat.rowcol(ii)[1]) val.InsertNextValue(abs(Tmat.getdata(ii))) table.AddColumn(col0) table.AddColumn(col1) table.AddColumn(val) # Vertex links need to be done with index2 first or indexing won't be right... # TODO: Make this foolproof so that graph always ends up with correct ordering of indices... tgraph = vtk.vtkTableToGraph() tgraph.SetInput(table) tgraph.AddLinkVertex('index2', 'stuff', False) tgraph.AddLinkVertex('index1', 'stuff', False) tgraph.AddLinkEdge('index2', 'index1') rawGraph = tgraph.GetOutput() rawGraph.Update() # print graph # Load and assign whole graph pre-layout coordinates ptsFile = os.path.splitext(filename)[0] + '_pts.vtp' if os.path.exists(ptsFile): polyreader = vtk.vtkXMLPolyDataReader() polyreader.SetFileName(ptsFile) polyreader.Update() pts = polyreader.GetOutput().GetPoints() rawGraph.SetPoints(pts) # print pts strategy = vtk.vtkPassThroughLayoutStrategy() layout = vtk.vtkGraphLayout() layout.SetInput(rawGraph) layout.SetLayoutStrategy(strategy) edgeLayout = vtk.vtkEdgeLayout() edgeStrategy = vtk.vtkArcParallelEdgeStrategy() edgeStrategy.SetNumberOfSubdivisions(50) edgeLayout.SetInputConnection(layout.GetOutputPort()) edgeLayout.SetLayoutStrategy(edgeStrategy) graph = edgeLayout.GetOutput() graph.Update() # -------- # Add ExtBasis to graph data & Select particular basis function # print 'ExtBasis shape: ' + str(ExtBasis[:,basisNum].data.shape) + ' (level,basis) (' + str(level) + ',' + str(basisNum) + ')' # Indexing of ExtBasis is backwards from graph, so need to reverse with [::-1] # and array not "contiguous" if don't do .copy() Esub = ExtBasis[:,basisNum].data[::-1].copy() EsubSq = Esub**2 # Esub = N.random.random(ExtBasis[:,basisNum].data.shape[0]) # SubIdxs = (Esub > 0.001).nonzero() # SubIdxs = (Esub**2 > 0.8).nonzero() # Set ExtBasis vertex data from numpy array basisFunc = VN.numpy_to_vtk(Esub) basisFunc.SetName('ExtBasis') basisFuncSq = VN.numpy_to_vtk(EsubSq) basisFuncSq.SetName('ExtBasisSq') vertexData = graph.GetVertexData() vertexData.AddArray(basisFunc) vertexData.AddArray(basisFuncSq) selection = vtk.vtkSelectionSource() selection.SetContentType(7) # vtkSelection::THRESHOLDS # selection.SetContentType(2) # vtkSelection::PEDIGREE_IDS selection.SetFieldType(3) # vtkSelection::VERTEX selection.SetArrayName("ExtBasisSq") selection.AddThreshold(basisCutoff, 10) # TODO: There was something wrong with the indexing in the PEDIGREE_IDS selection... # for ii in SubIdxs[0]: # selection.AddID(0,ii) minmax = "(%3.2e, %3.2e)" % (EsubSq.min(), EsubSq.max()) ui_window.label_basisCutoff_minmax.setText(minmax) selection.Update() # ---------- # Back to pipeline degree = vtk.vtkVertexDegree() degree.SetInput(graph) subgraph = vtk.vtkExtractSelectedGraph() subgraph.SetRemoveIsolatedVertices(False) subgraph.SetInputConnection(degree.GetOutputPort()) subgraph.SetSelectionConnection(selection.GetOutputPort()) # +++++++++++++ graphToPoly = vtk.vtkGraphToPolyData() graphToPoly.SetInputConnection(subgraph.GetOutputPort()) edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(graphToPoly.GetOutputPort()) edgeMapper.SetScalarModeToUseCellData() edgeMapper.SetScalarVisibility(False) edgeMapper.SetImmediateModeRendering(True) edgeActor = vtk.vtkActor() edgeActor.SetMapper(edgeMapper) edgeActor.SetPosition(0, 0, -0.003); lut = vtk.vtkLookupTable() lutNum = 256 lut.SetNumberOfTableValues(lutNum) ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToDiverging() ctf.AddRGBPoint(0.0, 0, 0, 1.0) ctf.AddRGBPoint(1.0, 1.0, 0, 0) for ii,ss in enumerate([float(xx)/float(lutNum) for xx in range(lutNum)]): cc = ctf.GetColor(ss) lut.SetTableValue(ii,cc[0],cc[1],cc[2],1.0) vertGlyph = vtk.vtkVertexGlyphFilter() vertGlyph.SetInputConnection(subgraph.GetOutputPort()) vertMapper = vtk.vtkPolyDataMapper() vertMapper.SetInputConnection(vertGlyph.GetOutputPort()) vertMapper.SetImmediateModeRendering(True) vertMapper.SetScalarModeToUsePointFieldData() vertMapper.SetLookupTable(lut) vertMapper.SelectColorArray('ExtBasis') vertMapper.Update() vertRange = vertMapper.GetInput().GetPointData().GetArray(vertMapper.GetArrayName()).GetRange() vertMapper.SetScalarRange(-1.0*vertRange[1], vertRange[1]) vertActor = vtk.vtkActor() vertActor.SetMapper(vertMapper) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetScalarVisibility(False) outlineMapper.SetImmediateModeRendering(True) outlineMapper.SetInputConnection(vertGlyph.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.PickableOff() outlineActor.SetPosition(0, 0, -0.001) outlineActor.GetProperty().SetRepresentationToWireframe() outlineActor.SetMapper(outlineMapper) # Create an Actor Collection for applying visibility to group basisActorCollection = vtk.vtkActorCollection() basisActorCollection.AddItem(vertActor) # basisActorCollection.AddItem(edgeActor) basisActorCollection.AddItem(outlineActor) # Apply a theme to the views theme = vtk.vtkViewTheme.CreateMellowTheme() theme.SetLineWidth(3) theme.SetPointSize(5) theme.SetSelectedCellColor(1,1,1) theme.SetSelectedPointColor(1,1,1) theme.SetOutlineColor(0.8, 0.8, 0.8) # theme.SetPointColor(0.9, 0.7, 0.3) theme.SetCellColor(0.9, 0.7, 0.3) # theme.SetPointOpacity(0.5) # theme.SetPointHueRange(0.0, 0.15) # theme.SetPointSaturationRange(0.6, 0.8) # theme.SetPointValueRange(0.4,0.8) # theme.SetPointAlphaRange(0.2,0.8) # theme.SetPointAlphaRange(1.0,1.0) # Apply theme # vertActor.GetProperty().SetColor(theme.GetPointColor()) # vertActor.GetProperty().SetOpacity(theme.GetPointOpacity()) vertActor.GetProperty().SetPointSize(theme.GetPointSize()) outlineActor.GetProperty().SetPointSize(vertActor.GetProperty().GetPointSize()+2) outlineActor.GetProperty().SetColor(theme.GetOutlineColor()) outlineActor.GetProperty().SetOpacity(theme.GetPointOpacity()) edgeActor.GetProperty().SetColor(theme.GetCellColor()) edgeActor.GetProperty().SetOpacity(theme.GetCellOpacity()) edgeActor.GetProperty().SetLineWidth(theme.GetLineWidth()) # ---------- # Background graph skeleton graphMapper = vtk.vtkGraphMapper() graphMapper.SetInputConnection(0, degree.GetOutputPort(0)) # Apply a theme to the background graph gtheme = vtk.vtkViewTheme() gtheme.SetLineWidth(1) gtheme.SetPointSize(0) gtheme.SetCellColor(0.8, 0.8, 0.8) gtheme.SetCellOpacity(0.2) gtheme.SetOutlineColor(0.8, 0.8, 0.8) gtheme.SetPointColor(0.8, 0.8, 0.8) gtheme.SetPointOpacity(0.0) graphMapper.ApplyViewTheme(gtheme) graphActor = vtk.vtkActor() graphActor.SetMapper(graphMapper) graphActor.SetPosition(0,0,-0.005) # ---------- # Background vertices graphPoly = vtk.vtkGraphToPolyData() graphPoly.SetInputConnection(0, tgraph.GetOutputPort(0)) vertGlyph = vtk.vtkGlyph3D() vertGlyph.SetInputConnection(0, graphPoly.GetOutputPort()) glyphSource = vtk.vtkGlyphSource2D() glyphSource.SetGlyphTypeToVertex() # glyphSource.SetGlyphTypeToCircle() # glyphSource.SetScale(0.025) vertGlyph.SetInputConnection(1, glyphSource.GetOutputPort()) vertexMapper = vtk.vtkPolyDataMapper() vertexMapper.SetInputConnection(vertGlyph.GetOutputPort()) vertexActor = vtk.vtkActor() vertexActor.SetMapper(vertexMapper) vertexActor.GetProperty().SetPointSize(4) vertexActor.GetProperty().SetOpacity(0.5) vertexActor.GetProperty().SetColor(0.6, 0.6, 0.6) vertexActor.SetPosition(0, 0, -0.004) # ---------- # Vertex index labels labelMapper = vtk.vtkDynamic2DLabelMapper() labelMapper.SetInputConnection(0, graphPoly.GetOutputPort(0)) labelMapper.SetLabelModeToLabelFieldData() labelMapper.SetFieldDataName("label") labelMapper.SetLabelFormat("%s") labelMapper.GetLabelTextProperty().SetColor(0.0, 0.0, 0.0) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # ---------- # MultiScale Graph msGraph = buildSubGraph(level) msMapper = vtk.vtkGraphMapper() msMapper.SetInput(msGraph) msMapper.SetColorEdges(True) msMapper.SetEdgeColorArrayName('weight') # Apply a theme to the background graph mtheme = vtk.vtkViewTheme() mtheme.SetLineWidth(3) mtheme.SetPointSize(11) # mtheme.SetCellColor(0.5, 0.5, 0.7) # mtheme.SetCellOpacity(0.5) mtheme.SetOutlineColor(0.8, 0.8, 0.8) mtheme.SetPointColor(0.3, 0.3, 0.6) mtheme.SetPointOpacity(1.0) mtheme.SetCellHueRange(0.67, 0.67) mtheme.SetCellSaturationRange(0.6, 0.1) mtheme.SetCellValueRange(0.5,1.0) mtheme.SetCellAlphaRange(0.2,0.8) msMapper.ApplyViewTheme(mtheme) msActor = vtk.vtkActor() msActor.SetMapper(msMapper) msActor.SetPosition(0,0,-0.002) # ---------- # Set up window and add actors view.SetLayoutStrategyToPassThrough() # view.ApplyViewTheme(theme) # view.SetupRenderWindow(win) view.GetRenderer().SetBackground(theme.GetBackgroundColor()) view.GetRenderer().SetBackground2(theme.GetBackgroundColor2()) view.GetRenderer().SetGradientBackground(True) view.GetRenderer().AddActor(vertActor) view.GetRenderer().AddActor(outlineActor) view.GetRenderer().AddActor(edgeActor) view.GetRenderer().AddActor(graphActor) view.GetRenderer().AddActor(vertexActor) view.GetRenderer().AddActor(labelActor) view.GetRenderer().AddActor(msActor) # ---------- # General interactor isty = vtk.vtkInteractorStyleRubberBand2D() # RubberBand2D assumes/needs parallel projection ON view.GetRenderer().GetActiveCamera().ParallelProjectionOn() iren = view.GetRenderWindow().GetInteractor() iren.SetInteractorStyle(isty) # Interactor style must be set before scalar bar can be shown # view.SetVertexScalarBarVisibility(True) sbActor = vtk.vtkScalarBarActor() sbActor.SetLookupTable(vertMapper.GetLookupTable()) sbActor.SetTitle(vertMapper.GetArrayName()) sbActor.SetNumberOfLabels(3) vertexScalarBar = vtk.vtkScalarBarWidget() vertexScalarBar.SetScalarBarActor(sbActor) vertexScalarBar.SetInteractor(iren) vertexScalarBar.SetDefaultRenderer(view.GetRenderer()) vertexScalarBar.SetCurrentRenderer(view.GetRenderer()) vertexScalarBar.SetEnabled(True) scalarBarRep = vertexScalarBar.GetRepresentation() scalarBarRep.SetOrientation(1) # 0 = Horizontal, 1 = Vertical scalarBarRep.GetPositionCoordinate().SetValue(0.05,0.05) scalarBarRep.GetPosition2Coordinate().SetValue(0.15,0.25) # Adding it this way gets it to show up, but it's not interactive view.GetRenderer().AddActor(sbActor) view.ResetCamera() view.Render() # ---------- # Add Actors to QListWidget to allow check and uncheck for visibility listItem0 = QtGui.QListWidgetItem() listItem0.setText('Index Labels') listItem0.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) labelActor.SetVisibility(0) listItem0.setCheckState(QtCore.Qt.Unchecked) # Put actor it in as data in the list widget item listItem0.setData(QtCore.Qt.UserRole, QtCore.QVariant(labelActor)) ui_window.listWidget.insertItem(0,listItem0) # Test retrieval of actor from list widget item # tmpItem = ui_window.listWidget.item(0) # tmpQtActor = tmpItem.data(QtCore.Qt.UserRole) # tmpActor = tmpQtActor.toPyObject() # tmpActor.SetVisibility(0) # Shorter way to add item to list widget listItem1 = QtGui.QListWidgetItem('Vertices (background)', ui_window.listWidget) listItem1.setData(QtCore.Qt.UserRole, QtCore.QVariant(vertexActor)) listItem1.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem1.setCheckState(QtCore.Qt.Checked) listItem2 = QtGui.QListWidgetItem('Graph (background)', ui_window.listWidget) listItem2.setData(QtCore.Qt.UserRole, QtCore.QVariant(graphActor)) listItem2.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem2.setCheckState(QtCore.Qt.Checked) listItem3 = QtGui.QListWidgetItem() listItem3.setText('Basis Function Vertices') listItem3.setData(QtCore.Qt.UserRole, QtCore.QVariant(basisActorCollection)) listItem3.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem3.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(1,listItem3) listItem6 = QtGui.QListWidgetItem() listItem6.setText('Basis Function Edges') listItem6.setData(QtCore.Qt.UserRole, QtCore.QVariant(edgeActor)) listItem6.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem6.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(2,listItem6) listItem4 = QtGui.QListWidgetItem() listItem4.setText('MultiScale Graph') listItem4.setData(QtCore.Qt.UserRole, QtCore.QVariant(msActor)) listItem4.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem4.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(3,listItem4) listItem5 = QtGui.QListWidgetItem() listItem5.setText('Basis Function Scale Bar') listItem5.setData(QtCore.Qt.UserRole, QtCore.QVariant(sbActor)) listItem5.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable) listItem5.setCheckState(QtCore.Qt.Checked) ui_window.listWidget.insertItem(3,listItem5) iren.Initialize() iren.Start()
def main(): img_reader = ImageReaderFactory().GenerateImageReader("png") img_reader.SetFileName("./kitti/image_00/000000.png") img_actor = ImageActor(img_reader.GetOutputPort()) sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(4.0) sphereSource.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(sphereSource.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) borderWidget = vtk.vtkBorderWidget() borderWidget.SetInteractor(interactor) representation = vtk.vtkBorderRepresentation() representation.SetPosition(0, 0) representation.SetPosition2(0.1, 0.1) borderWidget.SetRepresentation(representation) # borderWidget.CreateDefaultRepresentation() borderWidget.SelectableOff() borderWidget.On() print(representation) style = vtk.vtkInteractorStyleRubberBand2D() def gen(style, event): size = renderWindow.GetSize() start = list(style.GetStartPosition()) end = list(style.GetEndPosition()) new_start = [start[0], end[1]] new_end = [end[0], start[1]] print("start,end: ", start, end) print("new_start,new_end: ", new_start, new_end) tmp = [new_start[0] / size[0], new_start[1] / size[1]] print("scaled bottom_left: ", tmp) print("scaled top_right: ", new_end[0] / size[0], new_end[1] / size[1]) representation = vtk.vtkBorderRepresentation() borderWidget = vtk.vtkBorderWidget() representation.SetPosition(tmp[0], tmp[1]) representation.SetPosition2(new_end[0] / size[0] - tmp[0], new_end[1] / size[1] - tmp[1]) representation.SetMoving(0) print("Moving status: ", representation.GetMoving()) borderWidget.SetRepresentation(representation) borderWidget.SetInteractor(interactor) borderWidget.ResizableOn() # borderWidget.CreateDefaultRepresentation() # borderWidget.SelectableO() borderWidget.On() renderWindow.Render() widgets.append(borderWidget) # def stylecallback(style, event): # size = renderWindow.GetSize() # start = list(style.GetStartPosition()) # end = list(style.GetEndPosition()) # new_start = [start[0], end[1]] # new_end = [end[0], start[1]] # print("start,end: ", start, end) # print("new_start,new_end: ", new_start, new_end) # tmp = [new_start[0] / size[0], new_start[1] / size[1]] # print("scaled bottom_left: ", tmp) # print("scaled top_right: ", new_end[0] / size[0], new_end[1] / size[1]) # r = vtk.vtkBorderRepresentation() # # representation.MovingOff() # borderWidget = vtk.vtkBorderWidget() # # representation.ResizableOff() # # representation = vtk.vtkBorderRepresentation() # # representation # borderWidget.SelectableOff() # # global Flag # # if Flag: # # borderWidget.SelectableOn() # # Flag = False # # else: # # borderWidget.SelectableOff() # # Flag = True # # representation.SetPosition(tmp[0], tmp[1]) # # representation.SetPosition2( # # new_end[0] / size[0] - tmp[0], new_end[1] / size[1] - tmp[1]) # # representation.SetMoving(1) # # print("Moving status: ", representation.GetMoving()) # # borderWidget.CreateDefaultRepresentation() # # r = borderWidget.GetBorderRepresentation() # r.MovingOff() # r.SetPosition(tmp[0], tmp[1]) # r.SetPosition2( # new_end[0] / size[0] - tmp[0], new_end[1] / size[1] - tmp[1]) # r.SetMoving(1) # r.BuildRepresentation() # borderWidget.SetRepresentation(r) # borderWidget.SetInteractor(interactor) # # borderWidget.ResizableOff() # # borderWidget.CreateDefaultRepresentation() # # borderWidget.SelectableOn() # borderWidget.On() # print(r) # renderWindow.Render() # widgets.append(borderWidget) # style.AddObserver("SelectionChangedEvent", stylecallback) interactor.SetInteractorStyle(style) renderer.AddActor(actor) renderer.AddActor(img_actor.actor) interactor.Initialize() renderWindow.Render() # borderWidget.On() interactor.Start()