def create_labels(graph, label_nodes, labels=[], priorities=[]): label_points = vtk.vtkPoints() label_str = vtk.vtkStringArray() label_str.SetName('Labels') for ii, n in enumerate(label_nodes): label_points.InsertNextPoint( (graph.node[n]['x'], graph.node[n]['y'], graph.node[n]['z'])) if len(labels) == len(label_nodes): label = str(labels[ii]) else: label = str(n) label_str.InsertNextValue(label) label_polydata = vtk.vtkPolyData() label_polydata.SetPoints(label_points) label_polydata.GetPointData().AddArray(label_str) hierarchy = vtk.vtkPointSetToLabelHierarchy() hierarchy.SetLabelArrayName(label_str.GetName()) if (len(priorities) > 0) and (len(priorities) == len(label_nodes)): parray = vtk.vtkIntArray() parray.SetName('Priorities') for priority in priorities: parray.InsertNextValue(priority) hierarchy.SetPriorityArrayName(parray.GetName()) label_mapper = vtk.vtkLabelPlacementMapper() label_mapper.SetInputConnection(hierarchy.GetOutputPort()) if vtk.VTK_MAJOR_VERSION <= 5: hierarchy.SetInput(label_polydata) else: hierarchy.SetInputData(label_polydata) label_actor = vtk.vtkActor2D() label_actor.SetMapper(label_mapper) return label_actor
def __init__(self, renderer, output_path, start_frame_index, block_sets: List[TFrameBlockData]): self.start_frame_index = start_frame_index self.output_path = output_path self.renderer = renderer self.frame_count = len(block_sets) self.block_sets = block_sets colors = vtk.vtkNamedColors() self.block_locations = vtk.vtkPoints() self.block_labels = vtk.vtkStringArray() self.block_labels.SetName("label") self.verts = vtk.vtkCellArray() self.block_polydata = vtk.vtkPolyData() self.block_polydata.SetPoints(self.block_locations) self.block_polydata.SetVerts(self.verts) self.block_polydata.GetPointData().AddArray(self.block_labels) self.block_label_hierarchy = vtk.vtkPointSetToLabelHierarchy() self.block_label_hierarchy.SetInputData(self.block_polydata) self.block_label_hierarchy.SetLabelArrayName("label") self.block_label_placement_mapper = vtk.vtkLabelPlacementMapper() self.block_label_placement_mapper.SetInputConnection( self.block_label_hierarchy.GetOutputPort()) self.block_label_placement_mapper.SetRenderStrategy( vtk.vtkFreeTypeLabelRenderStrategy()) self.block_label_placement_mapper.SetShapeToRoundedRect() self.block_label_placement_mapper.SetBackgroundColor(1.0, 1.0, 0.7) self.block_label_placement_mapper.SetBackgroundOpacity(0.4) self.block_label_placement_mapper.SetMargin(3) self.block_mapper = vtk.vtkGlyph3DMapper() self.block_mapper.SetInputData(self.block_polydata) block = vtk.vtkCubeSource() block.SetXLength(VoxelVolumeParameters.BLOCK_SIZE) block.SetYLength(VoxelVolumeParameters.BLOCK_SIZE) block.SetZLength(VoxelVolumeParameters.BLOCK_SIZE) self.block_mapper.SetSourceConnection(block.GetOutputPort()) # block actor self.block_actor = vtk.vtkActor() self.block_actor.SetMapper(self.block_mapper) self.block_actor.GetProperty().SetColor( colors.GetColor3d("PowderBlue")) self.block_actor.GetProperty().SetLineWidth(0.1) self.block_actor.GetProperty().SetRepresentationToWireframe() # label actor self.block_label_actor = vtk.vtkActor2D() self.block_label_actor.SetMapper(self.block_label_placement_mapper) self.renderer.AddActor(self.block_actor) self.renderer.AddActor(self.block_label_actor)
def set_text_labels(self, positions_3d, text_labels, colour=None): """Set text labels for each 3D position :param positions_3d: list of 3D positions N x [x, y, z] :param text_labels: list of text strings for each 3D position :param colour: (optional) text colour tuple (r, g, b) """ # Create vtk data vtk_poly_data = vtk.vtkPolyData() vtk_points = vtk.vtkPoints() vtk_cell_array = vtk.vtkCellArray() label_array = vtk.vtkStringArray() label_array.SetName('label') for point_idx in range(len(positions_3d)): point = tuple(positions_3d[point_idx]) vtk_points.InsertNextPoint(*point) vtk_cell_array.InsertNextCell(1) vtk_cell_array.InsertCellPoint(point_idx) label_array.InsertNextValue(text_labels[point_idx]) vtk_poly_data.SetPoints(vtk_points) vtk_poly_data.SetVerts(vtk_cell_array) vtk_poly_data.GetPointData().AddArray(label_array) hierarchy = vtk.vtkPointSetToLabelHierarchy() hierarchy.SetInputData(vtk_poly_data) hierarchy.SetLabelArrayName('label') if colour is not None: hierarchy.GetTextProperty().SetColor(colour) else: # Default colour (almost white) hierarchy.GetTextProperty().SetColor((0.9, 0.9, 0.9)) hierarchy.GetTextProperty().SetFontSize(12) placement_mapper = vtk.vtkLabelPlacementMapper() placement_mapper.SetInputConnection(hierarchy.GetOutputPort()) placement_mapper.GeneratePerturbedLabelSpokesOn() # Add rounded rectangular background placement_mapper.SetShapeToRoundedRect() placement_mapper.SetBackgroundColor(0.2, 0.2, 0.2) placement_mapper.SetBackgroundOpacity(0.5) placement_mapper.SetMargin(5) self.vtk_actor.SetMapper(placement_mapper)
def Pick_point(self, loc): """ This receives coordinates in the GUI where user has picked, converts it to mesh coordinates using vtkCellPicker, and places a sphere at picked location as a visual aid. Also places a label at the point in the render window. TO-DO: Add functionality so user can type the label in, rather than have it read 'Mid Patella' every time """ x, y = loc renderer = self.rens[0] picker = vtk.vtkCellPicker() picker.SetTolerance(0.01) picker.Pick(x, y, 0, renderer) points = picker.GetPickedPositions() numPoints = points.GetNumberOfPoints() #if no points selected, exits function if numPoints<1: return # Calls function to create a sphere at selected point pnt = points.GetPoint(0) self.mark(pnt[0], pnt[1], pnt[2]) # Creating label at selected point label = vtk.vtkStringArray() label.SetName('label') label.InsertNextValue(" Mid Patella") lPoints = vtk.vtkPolyData() lPoints.SetPoints(points) lPoints.GetPointData().AddArray(label) hier = vtk.vtkPointSetToLabelHierarchy() hier.SetInputData(lPoints) hier.SetLabelArrayName('label') hier.GetTextProperty().SetColor(0,0,0) hier.GetTextProperty().SetFontSize(30) lMapper = vtk.vtkLabelPlacementMapper() lMapper.SetInputConnection(hier.GetOutputPort()) lMapper.SetBackgroundColor(0.3,0.3,0.3) lMapper.SetBackgroundOpacity(0.8) lMapper.SetMargin(10) lActor = vtk.vtkActor2D() lActor.SetMapper(lMapper) self.labels.append(lActor) # keep track of all label actors self.rens[0].AddActor(lActor) self.Render() return pnt
fname = "" + str(dir) + "/mni-tagtest.tag" writer = vtk.vtkMNITagPointWriter() writer.SetFileName("" + str(fname) + "") writer.SetInputConnection(sphere1.GetOutputPort()) writer.SetInputConnection(1, xformFilter.GetOutputPort()) writer.SetLabelText(labels) writer.SetWeights(weights) writer.SetComments("Volume 1: sphere points\nVolume 2: transformed points") writer.Write() reader = vtk.vtkMNITagPointReader() reader.CanReadFile("" + str(fname) + "") reader.SetFileName("" + str(fname) + "") textProp = vtk.vtkTextProperty() textProp.SetFontSize(12) textProp.SetColor(1.0, 1.0, 0.5) labelHier = vtk.vtkPointSetToLabelHierarchy() labelHier.SetInputConnection(reader.GetOutputPort()) labelHier.SetTextProperty(textProp) labelHier.SetLabelArrayName("LabelText") labelHier.SetMaximumDepth(15) labelHier.SetTargetLabelCount(12) labelMapper = vtk.vtkLabelPlacementMapper() labelMapper.SetInputConnection(labelHier.GetOutputPort()) labelMapper.UseDepthBufferOff() labelMapper.SetShapeToRect() labelMapper.SetStyleToOutline() labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) glyphSource = vtk.vtkSphereSource() glyphSource.SetRadius(0.01) glyph = vtk.vtkGlyph3D()
def place_label(self, pos, text, text_color=[1, 1, 1], text_font_size=12, label_box_color=[0, 0, 0], label_box=1, label_box_opacity=0.8): """Place a label in the scene. Parameters ---------- pos : tuple or np.ndarray Position in 3D space where to place the label. text : str Label text. text_color : list or np.ndarray, optional Color of the label text in RGB. text_font_size : int, optional Text size of the label. label_box_color : list or np.ndarray, optional Background color of the label box in RGB. label_box: int, optional 0=do not show the label box, 1=show the label box. label_box_opacity: float, optional Opacity value of the background box (1=no transparency). """ pd = vtk.vtkPolyData() pts = vtk.vtkPoints() #verts = vtk.vtkDoubleArray() orient = vtk.vtkDoubleArray() orient.SetName('orientation') label = vtk.vtkStringArray() label.SetName('label') pts.InsertNextPoint(pos[0], pos[1], pos[2]) orient.InsertNextValue(1) label.InsertNextValue(str(text)) pd.SetPoints(pts) pd.GetPointData().AddArray(label) pd.GetPointData().AddArray(orient) h = vtk.vtkPointSetToLabelHierarchy() self._set_input_data(h, pd) h.SetOrientationArrayName('orientation') h.SetLabelArrayName('label') h.GetTextProperty().SetColor(text_color[0], text_color[1], text_color[2]) h.GetTextProperty().SetFontSize(text_font_size) lmapper = vtk.vtkLabelPlacementMapper() self._set_input_connection(lmapper, h) if label_box: lmapper.SetShapeToRoundedRect() lmapper.SetBackgroundColor(label_box_color[0], label_box_color[1], label_box_color[2]) lmapper.SetBackgroundOpacity(label_box_opacity) lmapper.SetMargin(3) lactor = vtk.vtkActor2D() lactor.SetMapper(lmapper) mapper = vtk.vtkPolyDataMapper() self._set_input_data(mapper, pd) actor = vtk.vtkActor() actor.SetMapper(mapper) self.actors.append(lactor)
def addBSpline(self, path, degree, color, thick=False, thickness=_DEFAULT_BSPLINE_THICKNESS): self._addedBSpline = True tau, u, spline, splineD1, splineD2, splineD3, curv, tors, arcLength, polLength = path.splinePoints( ) self._textActor.SetInput("Length: " + str(arcLength)) numIntervals = len(tau) - 1 curvPlotActor = vtk.vtkXYPlotActor() curvPlotActor.SetTitle("Curvature") curvPlotActor.SetXTitle("") curvPlotActor.SetYTitle("") curvPlotActor.SetXValuesToIndex() torsPlotActor = vtk.vtkXYPlotActor() torsPlotActor.SetTitle("Torsion") torsPlotActor.SetXTitle("") torsPlotActor.SetYTitle("") torsPlotActor.SetXValuesToIndex() uArrays = [] curvArrays = [] torsArrays = [] for i in range(numIntervals): uArrays.append(vtk.vtkDoubleArray()) uArrays[i].SetName("t") curvArrays.append(vtk.vtkDoubleArray()) curvArrays[i].SetName("Curvature") torsArrays.append(vtk.vtkDoubleArray()) torsArrays[i].SetName("Torsion") curvTorsArray = vtk.vtkDoubleArray() #minCurv = minTors = minNd1Xd2 = float("inf") #maxCurv = maxTors = float("-inf") for i in range(len(u)): for j in range(numIntervals): if u[i] >= tau[j] and u[i] < tau[j + 1]: break uArrays[j].InsertNextValue(u[i]) curvArrays[j].InsertNextValue(curv[i]) torsArrays[j].InsertNextValue(tors[i]) curvTorsArray.InsertNextValue(curv[i]) # + abs(tors[i])) #print("minCurv: {:e}; maxCurv: {:e}; minTors: {:e}; maxTors: {:e}; minNd1Xd2: {:e}".format(minCurv, maxCurv, minTors, maxTors, minNd1Xd2)) for inter in range(numIntervals): plotTable = vtk.vtkTable() plotTable.AddColumn(uArrays[inter]) plotTable.AddColumn(curvArrays[inter]) plotTable.AddColumn(torsArrays[inter]) points = self._chartXYCurv.AddPlot(vtk.vtkChart.LINE) points.SetInputData(plotTable, 0, 1) points.SetColor(self.COLOR_PLOT_CURV[0], self.COLOR_PLOT_CURV[1], self.COLOR_PLOT_CURV[2]) points.SetWidth(1.0) if inter > 0: points.SetLegendVisibility(False) points = self._chartXYTors.AddPlot(vtk.vtkChart.LINE) points.SetInputData(plotTable, 0, 2) points.SetColor(self.COLOR_PLOT_TORS[0], self.COLOR_PLOT_TORS[1], self.COLOR_PLOT_TORS[2]) points.SetWidth(1.0) if inter > 0: points.SetLegendVisibility(False) vtkPoints = vtk.vtkPoints() for point in spline: vtkPoints.InsertNextPoint(point[0], point[1], point[2]) polyDataLabelP = vtk.vtkPolyData() polyDataLabelP.SetPoints(vtkPoints) labels = vtk.vtkStringArray() labels.SetNumberOfValues(len(spline)) labels.SetName("labels") for i in range(len(spline)): if i == 0: labels.SetValue(i, "S") elif i == len(spline) - 1: labels.SetValue(i, "E") else: labels.SetValue(i, "") polyDataLabelP.GetPointData().AddArray(labels) sizes = vtk.vtkIntArray() sizes.SetNumberOfValues(len(spline)) sizes.SetName("sizes") for i in range(len(spline)): if i == 0 or i == len(spline) - 1: sizes.SetValue(i, 10) else: sizes.SetValue(i, 1) polyDataLabelP.GetPointData().AddArray(sizes) pointMapper = vtk.vtkPolyDataMapper() pointMapper.SetInputData(polyDataLabelP) pointActor = vtk.vtkActor() pointActor.SetMapper(pointMapper) pointSetToLabelHierarchyFilter = vtk.vtkPointSetToLabelHierarchy() pointSetToLabelHierarchyFilter.SetInputData(polyDataLabelP) pointSetToLabelHierarchyFilter.SetLabelArrayName("labels") pointSetToLabelHierarchyFilter.SetPriorityArrayName("sizes") pointSetToLabelHierarchyFilter.GetTextProperty().SetColor( self.COLOR_LABELS) pointSetToLabelHierarchyFilter.GetTextProperty().SetFontSize(15) pointSetToLabelHierarchyFilter.GetTextProperty().SetBold(True) pointSetToLabelHierarchyFilter.Update() labelMapper = vtk.vtkLabelPlacementMapper() labelMapper.SetInputConnection( pointSetToLabelHierarchyFilter.GetOutputPort()) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) self._rendererScene.AddActor(labelActor) if thick: cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(len(spline)) for i in range(len(spline)): cellArray.InsertCellPoint(i) polyData = vtk.vtkPolyData() polyData.SetPoints(vtkPoints) polyData.SetLines(cellArray) polyData.GetPointData().SetScalars(curvTorsArray) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetNumberOfSides(8) tubeFilter.SetInputData(polyData) tubeFilter.SetRadius(thickness) tubeFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(tubeFilter.GetOutputPort()) else: unstructuredGrid = vtk.vtkUnstructuredGrid() unstructuredGrid.SetPoints(vtkPoints) for i in range(1, len(spline)): unstructuredGrid.InsertNextCell(vtk.VTK_LINE, 2, [i - 1, i]) unstructuredGrid.GetPointData().SetScalars(curvArray) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(unstructuredGrid) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) self._rendererScene.AddActor(actor)
writer.SetInputConnection(sphere1.GetOutputPort()) writer.SetInputConnection(1, xformFilter.GetOutputPort()) writer.SetLabelText(labels) writer.SetWeights(weights) writer.SetComments("Volume 1: sphere points\nVolume 2: transformed points") writer.Write() reader = vtk.vtkMNITagPointReader() reader.CanReadFile(fname) reader.SetFileName(fname) textProp = vtk.vtkTextProperty() textProp.SetFontSize(12) textProp.SetColor(1.0, 1.0, 0.5) labelHier = vtk.vtkPointSetToLabelHierarchy() labelHier.SetInputConnection(reader.GetOutputPort()) labelHier.SetTextProperty(textProp) labelHier.SetLabelArrayName("LabelText") labelHier.SetMaximumDepth(15) labelHier.SetTargetLabelCount(12) labelMapper = vtk.vtkLabelPlacementMapper() labelMapper.SetInputConnection(labelHier.GetOutputPort()) labelMapper.UseDepthBufferOff() labelMapper.SetShapeToRect() labelMapper.SetStyleToOutline() labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper)
def vtk_movie_popularity_by_releases_circular_chart(self): # Compute unit vectors for all 18 genre delimeter lines unit_vectors = [] i = 0 while i < 360: unit_vectors.append( [np.cos(i * np.pi / 180), np.sin(i * np.pi / 180)]) i += 360 / 19 # Remove the last unit vector added due to floating point rounding errors unit_vectors = unit_vectors[:-1] # Draw the delimeter lines lines = vtk.vtkCellArray() colors = vtk.vtkNamedColors() points = vtk.vtkPoints() # First point is origin points.InsertNextPoint(0, 0, 0) for index, unit_vector in enumerate(unit_vectors): z = 0 # Scale z axis up by 10 points.InsertNextPoint(unit_vector[0], unit_vector[1], 0) line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, index + 1) lines.InsertNextCell(line) # Add labels to the delimeter lines - each corresponds to a genre # Data structures for labels label_pd = vtk.vtkPolyData() label_points = vtk.vtkPoints() label_verts = vtk.vtkCellArray() label = vtk.vtkStringArray() label.SetName('label') for index, unit_vector in enumerate(unit_vectors): label_points.InsertNextPoint(unit_vector[0] * 1.1, unit_vector[1] * 1.1, 0) label_verts.InsertNextCell(1) label_verts.InsertCellPoint(index) label.InsertNextValue(self.genres[index]) label_pd.SetPoints(label_points) label_pd.SetVerts(label_verts) label_pd.GetPointData().AddArray(label) hier = vtk.vtkPointSetToLabelHierarchy() hier.SetInputData(label_pd) hier.SetLabelArrayName('label') hier.GetTextProperty().SetColor(0.0, 0.0, 0.0) label_mapper = vtk.vtkLabelPlacementMapper() label_mapper.SetInputConnection(hier.GetOutputPort()) label_mapper.SetPlaceAllLabels(True) # label_mapper.SetShapeToRoundedRect() # label_mapper.SetBackgroundColor(1.0, 1.0, 0.7) # label_mapper.SetBackgroundOpacity(0.8) # label_mapper.SetMargin(3) label_actor = vtk.vtkActor2D() label_actor.SetMapper(label_mapper) # Generate a point on each unit vector that corresponds to that unit vector's genre's popularity for a given time year = self.year_vis3 - 1930 # year 1930 = index 0 if year < 0: # Total was set, so get the overall data for all years year_popularity = { genre: sum([ self.genre_popularity_by_releases[y][genre] for y in range(len(self.genre_popularity_by_releases)) ]) for genre in self.genre_popularity_by_releases[0] } # Get the dict for this year year_popularity = list(sorted(year_popularity.items( ))) # Convert the dict into a list of [key, value] year_pop_sum = sum([ n[1] for n in year_popularity ]) # Compute the total number of ratings submitted for this year normalised_year_popularity = list( map( lambda n: [ n[0], (3 * n[1] / year_pop_sum if year_pop_sum > 0 else n[1]) ], year_popularity) ) # Normalised popularities (sum over genres = 1) print(max([n[1] for n in normalised_year_popularity])) # The maximum normalised_year_pop is <0.33 even when looking at all data combined, so multiply all pop values by 3 (to make the plot more readable) else: year_popularity = self.genre_popularity_by_releases[ year] # Get the dict for this year year_popularity = list(sorted(year_popularity.items( ))) # Convert the dict into a list of [key, value] year_pop_sum = sum([ n[1] for n in year_popularity ]) # Compute the total number of ratings submitted for this year normalised_year_popularity = list( map( lambda n: [ n[0], (3 * n[1] / year_pop_sum if year_pop_sum > 0 else n[1]) ], year_popularity) ) # Normalised popularities (sum over genres = 1) # The maximum normalised_year_pop ever is <0.33, so multiply all pop values by 3 (to make the plot more readable) # Create points on each unit vector proportionately distant from origin to this genre's popularity for that year pop_lines = vtk.vtkCellArray() pop_points = vtk.vtkPoints() for index, unit_vector in enumerate(unit_vectors): pop_points.InsertNextPoint( unit_vector[0] * normalised_year_popularity[index][1], unit_vector[1] * normalised_year_popularity[index][1], 0) if index > 0: line = vtk.vtkLine() line.GetPointIds().SetId(0, index - 1) line.GetPointIds().SetId(1, index) pop_lines.InsertNextCell(line) # Add the last line that joins the last pop_point to the first pop_point line = vtk.vtkLine() line.GetPointIds().SetId(0, index) line.GetPointIds().SetId(1, 0) pop_lines.InsertNextCell(line) # Create a Polydata to store all the lines in linesPolyData = vtk.vtkPolyData() popLinesPolyData = vtk.vtkPolyData() # Add the lines to the dataset linesPolyData.SetPoints(points) linesPolyData.SetLines(lines) popLinesPolyData.SetPoints(pop_points) popLinesPolyData.SetLines(pop_lines) # Create a mapper and actor for the lines line_mapper = vtk.vtkPolyDataMapper() line_mapper.SetInputData(linesPolyData) pop_line_mapper = vtk.vtkPolyDataMapper() pop_line_mapper.SetInputData(popLinesPolyData) line_actor = vtk.vtkActor() line_actor.SetMapper(line_mapper) line_actor.GetProperty().SetLineWidth(1) line_actor.GetProperty().SetColor(colors.GetColor3d("Black")) pop_line_actor = vtk.vtkActor() pop_line_actor.SetMapper(pop_line_mapper) pop_line_actor.GetProperty().SetLineWidth(3) pop_line_actor.GetProperty().SetColor(colors.GetColor3d("Red")) # Write the current year on the bottom-left of the frame txt = vtk.vtkTextActor() txt.SetInput(str(year + 1930) if year >= 0 else '1930-2018') txtprop = txt.GetTextProperty() txtprop.SetFontFamilyToArial() txtprop.SetFontSize(60) txtprop.SetColor(1, 1, 1) txt.SetDisplayPosition(40, 40) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene renderer.AddActor(label_actor) renderer.AddActor(txt) renderer.AddActor(line_actor) renderer.AddActor(pop_line_actor) renderer.SetBackground( colors.GetColor3d("SlateGray")) # Background color green # Render and interact renderWindow.Render() renderWindowInteractor.Initialize( ) # Initialize first, then create timer events # Only set up animation if year != -1 (i.e. don't animate 'Total' display) and if framerate > 0 if year >= 0 and self.framerate_vis3 != 0: cb = vtkTimerCallback_vis3(year) # Set all necessary data as fields in instance cb.line_actor = pop_line_actor cb.text_actor = txt cb.genre_popularity = self.genre_popularity_by_releases cb.unit_vectors = unit_vectors renderWindowInteractor.AddObserver('TimerEvent', cb.execute) if self.framerate_vis3 == -1: # Set framerate to display the entire loop in 1s framerate = 1000 // 90 else: framerate = 1000 // self.framerate_vis3 timerId = renderWindowInteractor.CreateRepeatingTimer(framerate) # Start the interaction and timer renderWindowInteractor.Start()
def vtk_ratings_by_genre(self): # Read which metric to use metric = self.metric genre_list = list(self.rating_stats_by_genre.keys()) genre_list.sort() # Set up labels for the X and Y axes width = len(genre_list) height = 9 # Data structures for labels label_pd = vtk.vtkPolyData() label_points = vtk.vtkPoints() label_verts = vtk.vtkCellArray() label = vtk.vtkStringArray() label.SetName('label') # Y axis labels for y in range(height): label_points.InsertNextPoint(-1, y, 0) label_verts.InsertNextCell(1) label_verts.InsertCellPoint(y) label.InsertNextValue( str((y + 1) * 0.5) + '-' + str( (y + 2) * 0.5)) # Construct labels as '0.5-1.0' # Add Y axis title label_points.InsertNextPoint(-2, (height - 1) / 2, 0) label_verts.InsertNextCell(1) label_verts.InsertCellPoint(height) label.InsertNextValue("Scores") # X axis labels for x in range(width): label_points.InsertNextPoint(x, -1, 0) label_verts.InsertNextCell(1) label_verts.InsertCellPoint(x) label.InsertNextValue(genre_list[x]) # Add X axis title label_points.InsertNextPoint((width - 1) / 2, -2, 0) label_verts.InsertNextCell(1) label_verts.InsertCellPoint(width) label.InsertNextValue("Genre") # Add chart title label_points.InsertNextPoint((width - 1) / 4, height + 2, 2) label_verts.InsertNextCell(1) label_verts.InsertCellPoint(width + height) label.InsertNextValue( "Distribution of {} (in ranges of 0.5) of Movies by Genre".format( self.vis1_rating_list.get())) label_pd.SetPoints(label_points) label_pd.SetVerts(label_verts) label_pd.GetPointData().AddArray(label) hier = vtk.vtkPointSetToLabelHierarchy() hier.SetInputData(label_pd) hier.SetLabelArrayName('label') hier.GetTextProperty().SetColor(0.0, 0.0, 0.0) label_mapper = vtk.vtkLabelPlacementMapper() label_mapper.SetInputConnection(hier.GetOutputPort()) label_mapper.SetPlaceAllLabels(True) # label_mapper.SetShapeToRoundedRect() # label_mapper.SetBackgroundColor(1.0, 1.0, 0.7) # label_mapper.SetBackgroundOpacity(0.8) # label_mapper.SetMargin(3) label_actor = vtk.vtkActor2D() label_actor.SetMapper(label_mapper) # Done preparing labels, now prepare the points and lines lines = vtk.vtkCellArray() colors = vtk.vtkNamedColors() # Create the points in the grid and lines joining them vertically points = vtk.vtkPoints() for x in range(width): for y in range(height): z = self.rating_stats_by_genre[ genre_list[x]][metric][y] * 10 # Scale z axis up by 10 points.InsertNextPoint(x, y, z) if (y < height - 1): line = vtk.vtkLine() line.GetPointIds().SetId(0, height * x + y) line.GetPointIds().SetId(1, height * x + y + 1) lines.InsertNextCell(line) # Add the grid points to a polydata object polydata = vtk.vtkPolyData() polydata.SetPoints(points) glyphFilter = vtk.vtkVertexGlyphFilter() glyphFilter.SetInputData(polydata) glyphFilter.Update() # Create a Polydata to store all the lines in linesPolyData = vtk.vtkPolyData() # Add the points and lines to the dataset linesPolyData.SetPoints(points) linesPolyData.SetLines(lines) # Create a mapper and actor for the lines line_mapper = vtk.vtkPolyDataMapper() line_mapper.SetInputData(linesPolyData) line_actor = vtk.vtkActor() line_actor.SetMapper(line_mapper) line_actor.GetProperty().SetLineWidth(1) line_actor.GetProperty().SetColor(colors.GetColor3d("Black")) # Create a mapper and actor for the points points_mapper = vtk.vtkPolyDataMapper() points_mapper.SetInputConnection(glyphFilter.GetOutputPort()) points_actor = vtk.vtkActor() points_actor.SetMapper(points_mapper) points_actor.GetProperty().SetPointSize(3) points_actor.GetProperty().SetColor(colors.GetColor3d("Black")) ##### Point triangulation ##### # Triangulate the grid points delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(polydata) delaunay.Update() outputPolyData = delaunay.GetOutput() ##### Colour mapping ##### # From VTK coloured elevation map example bounds = 6 * [0.0] outputPolyData.GetBounds(bounds) # Find min and max z minZ = bounds[4] maxZ = bounds[5] # Create the colour table # From https://stackoverflow.com/questions/51747494/how-to-visualize-2d-array-of-doubles-in-vtk colorSeries = vtk.vtkColorSeries() colorSeries.SetColorScheme(vtk.vtkColorSeries.CITRUS) colour_table = vtk.vtkColorTransferFunction() colour_table.SetColorSpaceToHSV() nColors = colorSeries.GetNumberOfColors() zMin = minZ zMax = maxZ for i in range(0, nColors): color = colorSeries.GetColor(i) color = [c / 255.0 for c in color] t = zMin + float(zMax - zMin) / (nColors - 1) * i colour_table.AddRGBPoint(t, color[0], color[1], color[2]) # Generate colours for each point based on the colour table colours = vtk.vtkUnsignedCharArray() colours.SetNumberOfComponents(3) colours.SetName("Colours") for i in range(0, outputPolyData.GetNumberOfPoints()): p = 3 * [0.0] outputPolyData.GetPoint(i, p) dcolour = 3 * [0.0] colour_table.GetColor(p[2], dcolour) colour = 3 * [0.0] for j in range(0, 3): colour[j] = int(255 * dcolour[j]) try: colours.InsertNextTupleValue(colour) except AttributeError: # For compatibility with new VTK generic data arrays. colours.InsertNextTypedTuple(colour) outputPolyData.GetPointData().SetScalars(colours) # Create a mapper and actor triangulated_mapper = vtk.vtkPolyDataMapper() triangulated_mapper.SetInputData(outputPolyData) triangulated_actor = vtk.vtkActor() triangulated_actor.SetMapper(triangulated_mapper) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actors to the scene renderer.AddActor(label_actor) renderer.AddActor(line_actor) renderer.AddActor(points_actor) renderer.AddActor(triangulated_actor) renderer.SetBackground( colors.GetColor3d("SlateGray")) # Background color green # Render and interact renderWindow.Render() renderWindowInteractor.Start()
def addBSpline(self, path, degree, color, thick=False, thickness=_DEFAULT_BSPLINE_THICKNESS): self._addedBSpline = True tau, u, spline, splineD1, splineD2, splineD3, curv, tors, arcLength, polLength = path.splinePoints() self._textActor.SetInput("Length: "+str(arcLength)) numIntervals = len(tau)-1 curvPlotActor = vtk.vtkXYPlotActor() curvPlotActor.SetTitle("Curvature") curvPlotActor.SetXTitle("") curvPlotActor.SetYTitle("") curvPlotActor.SetXValuesToIndex() torsPlotActor = vtk.vtkXYPlotActor() torsPlotActor.SetTitle("Torsion") torsPlotActor.SetXTitle("") torsPlotActor.SetYTitle("") torsPlotActor.SetXValuesToIndex() uArrays = [] curvArrays = [] torsArrays = [] for i in range(numIntervals): uArrays.append(vtk.vtkDoubleArray()) uArrays[i].SetName("t") curvArrays.append(vtk.vtkDoubleArray()) curvArrays[i].SetName("Curvature") torsArrays.append(vtk.vtkDoubleArray()) torsArrays[i].SetName("Torsion") curvTorsArray = vtk.vtkDoubleArray() #minCurv = minTors = minNd1Xd2 = float("inf") #maxCurv = maxTors = float("-inf") for i in range(len(u)): for j in range(numIntervals): if u[i] >= tau[j] and u[i] < tau[j+1]: break uArrays[j].InsertNextValue(u[i]) curvArrays[j].InsertNextValue(curv[i]) torsArrays[j].InsertNextValue(tors[i]) curvTorsArray.InsertNextValue(curv[i])# + abs(tors[i])) #print("minCurv: {:e}; maxCurv: {:e}; minTors: {:e}; maxTors: {:e}; minNd1Xd2: {:e}".format(minCurv, maxCurv, minTors, maxTors, minNd1Xd2)) for inter in range(numIntervals): plotTable = vtk.vtkTable() plotTable.AddColumn(uArrays[inter]) plotTable.AddColumn(curvArrays[inter]) plotTable.AddColumn(torsArrays[inter]) points = self._chartXYCurv.AddPlot(vtk.vtkChart.LINE) points.SetInputData(plotTable, 0, 1) points.SetColor(self.COLOR_PLOT_CURV[0], self.COLOR_PLOT_CURV[1], self.COLOR_PLOT_CURV[2]) points.SetWidth(1.0) if inter > 0: points.SetLegendVisibility(False) points = self._chartXYTors.AddPlot(vtk.vtkChart.LINE) points.SetInputData(plotTable, 0, 2) points.SetColor(self.COLOR_PLOT_TORS[0], self.COLOR_PLOT_TORS[1], self.COLOR_PLOT_TORS[2]) points.SetWidth(1.0) if inter > 0: points.SetLegendVisibility(False) vtkPoints = vtk.vtkPoints() for point in spline: vtkPoints.InsertNextPoint(point[0], point[1], point[2]) polyDataLabelP = vtk.vtkPolyData() polyDataLabelP.SetPoints(vtkPoints) labels = vtk.vtkStringArray() labels.SetNumberOfValues(len(spline)) labels.SetName("labels") for i in range(len(spline)): if i == 0: labels.SetValue(i, "S") elif i == len(spline)-1: labels.SetValue(i, "E") else: labels.SetValue(i, "") polyDataLabelP.GetPointData().AddArray(labels) sizes = vtk.vtkIntArray() sizes.SetNumberOfValues(len(spline)) sizes.SetName("sizes") for i in range(len(spline)): if i == 0 or i == len(spline)-1: sizes.SetValue(i, 10) else: sizes.SetValue(i,1) polyDataLabelP.GetPointData().AddArray(sizes) pointMapper = vtk.vtkPolyDataMapper() pointMapper.SetInputData(polyDataLabelP) pointActor = vtk.vtkActor() pointActor.SetMapper(pointMapper) pointSetToLabelHierarchyFilter = vtk.vtkPointSetToLabelHierarchy() pointSetToLabelHierarchyFilter.SetInputData(polyDataLabelP) pointSetToLabelHierarchyFilter.SetLabelArrayName("labels") pointSetToLabelHierarchyFilter.SetPriorityArrayName("sizes") pointSetToLabelHierarchyFilter.GetTextProperty().SetColor(self.COLOR_LABELS) pointSetToLabelHierarchyFilter.GetTextProperty().SetFontSize(15) pointSetToLabelHierarchyFilter.GetTextProperty().SetBold(True) pointSetToLabelHierarchyFilter.Update() labelMapper = vtk.vtkLabelPlacementMapper() labelMapper.SetInputConnection(pointSetToLabelHierarchyFilter.GetOutputPort()) labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) self._rendererScene.AddActor(labelActor) if thick: cellArray = vtk.vtkCellArray() cellArray.InsertNextCell(len(spline)) for i in range(len(spline)): cellArray.InsertCellPoint(i) polyData = vtk.vtkPolyData() polyData.SetPoints(vtkPoints) polyData.SetLines(cellArray) polyData.GetPointData().SetScalars(curvTorsArray) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetNumberOfSides(8) tubeFilter.SetInputData(polyData) tubeFilter.SetRadius(thickness) tubeFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(tubeFilter.GetOutputPort()) else: unstructuredGrid = vtk.vtkUnstructuredGrid() unstructuredGrid.SetPoints(vtkPoints) for i in range(1, len(spline)): unstructuredGrid.InsertNextCell(vtk.VTK_LINE, 2, [i-1, i]) unstructuredGrid.GetPointData().SetScalars(curvArray) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(unstructuredGrid) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) self._rendererScene.AddActor(actor)
def __init__(self, bones, do_triangulation, do_import): VTKWindow.__init__(self, title='Triangulation Helper') self.bones = bones self.do_triangulation = do_triangulation self.current = bones[0] self.last_step = None self.current_modified = False self.do_import = do_import self.ll = QtGui.QVBoxLayout() self.list_model = lm = BonesListModel(self.bones, self) self.list_view = QtGui.QListView() self.list_view.setModel(lm) self.list_view.selectionModel().select(lm.index(0), QtGui.QItemSelectionModel.SelectCurrent) self.list_view.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.MinimumExpanding) self.ll.addWidget(self.list_view) self.add_bone_button = self.get_new_button('Add new bone', 'list-add') self.ll.addWidget(self.add_bone_button) self.hl.insertLayout(0, self.ll) self.bl = QtGui.QHBoxLayout() self.toggle_triangulation_button = self.get_new_button('Toggle Triangulation', 'image-x-generic', checkable=True) self.bl.insertWidget(-1, self.toggle_triangulation_button) self.toggle_triangulation_button.setChecked(True) self.toggle_markers_button = self.get_new_button('Toggle Markers', 'text-x-generic', checkable=True) self.bl.insertWidget(-1, self.toggle_markers_button) self.toggle_area_effect_button = self.get_new_button('Toggle Area Effect', 'list-add', checkable=True) self.bl.insertWidget(-1, self.toggle_area_effect_button) self.undo_button = self.get_new_button('Undo Last Step', 'edit-undo') self.bl.insertWidget(-1, self.undo_button) self.show_outline_button = self.get_new_button('Show Outline', 'zoom-in', checkable=True) self.bl.insertWidget(-1, self.show_outline_button) self.mark_as_done_button = self.get_new_button('Mark as done', 'emblem-readonly', checkable=True) self.bl.insertWidget(-1, self.mark_as_done_button) self.mark_as_done_button.setChecked('done' in self.current and self.current['done']) self.save_button = self.get_new_button('Save triangulation', 'document-save') self.bl.insertWidget(-1, self.save_button) self.vl.insertLayout(-1, self.bl) self.image_import = vtk.vtkImageImport() self.image_actor = vtk.vtkImageActor() self.triangle_data = vtk.vtkPolyData() self.triangle_mapper = vtk.vtkPolyDataMapper() self.triangle_actor = vtk.vtkActor() self.marker_data = vtk.vtkPolyData() self.marker_mapper = vtk.vtkPolyDataMapper() self.marker_actor = vtk.vtkActor() self.marker_actor.VisibilityOff() self.marker_labels_filter = vtk.vtkPointSetToLabelHierarchy() self.marker_labels_mapper = vtk.vtkLabelPlacementMapper() self.marker_labels_actor = vtk.vtkActor2D() self.marker_labels_actor.VisibilityOff() self.initialize_actors() self.render_actors([ self.image_actor, self.triangle_actor, self.marker_actor, self.marker_labels_actor ]) self.update_current_data(including_image=True) self.vtkWidget.GetRenderWindow().Render() self.ren.ResetCamera() self.iren.RemoveObservers('CharEvent') self.iren.AddObserver('KeyPressEvent', self.on_key, 0.0) self.intstyle.AddObserver('SelectionChangedEvent', self.area_selected, 0.0) self.list_view.selectionModel().currentChanged.connect(self.on_bone_model_change) self.add_bone_button.clicked.connect(self.add_bone) self.toggle_triangulation_button.clicked.connect(self.toggle_triangulation) self.toggle_markers_button.clicked.connect(self.toggle_markers) self.mark_as_done_button.clicked.connect(self.mark_as_done) self.save_button.clicked.connect(self.save_current) self.undo_button.clicked.connect(self.undo) self.show_outline_button.clicked.connect(self.trigger_outline)