def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkIdFilter(), 'Processing.', ('vtkDataSet',), ('vtkDataSet',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def getEdges(pd): """ Extracts edges from polydata with correct point ids. """ # Store the original point ids idf = v.vtkIdFilter() idf.PointIdsOn() idf.SetIdsArrayName('PointIds') idf.SetInputData(pd.VTKObject) # Extract the edges edgeFilter = v.vtkExtractEdges() edgeFilter.SetInputConnection(idf.GetOutputPort()) edgeFilter.Update() # Now make a new cell array mapping to the old ids edges = v.vtkCellArray() badEdges = edgeFilter.GetOutput().GetLines() badEdges.InitTraversal() origIds = edgeFilter.GetOutput().GetPointData().GetArray('PointIds') ptIds = v.vtkIdList() while (badEdges.GetNextCell(ptIds)): edges.InsertNextCell(2) edges.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(0)))) edges.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(1)))) # Convert the cell array into a numpy array conn = dsa.vtkDataArrayToVTKArray(edges.GetData()).reshape( (edges.GetNumberOfCells(), 3))[:, 1:] return conn
def VtkDibujaIdsCells(uGrid, setToDraw, entTypeName, renderer): ids= vtk.vtkIdFilter() ids.SetInput(uGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsCells(uGrid,setToDraw,entTypeName) # Dibuja las etiquetas de las líneas. cc= vtk.vtkCellCenters() cc.SetInputConnection(ids.GetOutputPort()) # Centroides de las celdas. visCells= vtk.vtkSelectVisiblePoints() visCells.SetInputConnection(cc.GetOutputPort()) visCells.SetRenderer(renderer) visCells.SelectionWindowOff() #Create the mapper to display the cell ids. Specify the format to # use for the labels. Also create the associated actor. cellMapper= vtk.vtkLabeledDataMapper() cellMapper.SetInputConnection(visCells.GetOutputPort()) cellMapper.GetLabelTextProperty().SetColor(0,0,0.9) cellLabels= vtk.vtkActor2D() cellLabels.SetMapper(cellMapper) renderer.AddActor2D(cellLabels)
def VtkDibujaIdsElementos(nmbUGrid, setName, renderer): # ****** Creamos las etiquetas para las celdas ******* ids= vtk.vtkIdFilter() ids.SetInput(nmbUGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsElem(nmbUGrid,setName)() # Dibuja las etiquetas de las líneas. cc= vtk.vtkCellCenters() cc.SetInput(ids) # Centroides de las celdas. visElems= vtk.vtkSelectVisiblePoints() visElems.SetInput(cc) visElems.SetRenderer(renderer) visElems.SelectionWindowOff() ''' Create the mapper to display the element ids. Specify the format to use for the labels. Also create the associated actor. ''' elemMapper= vtk.vtkLabeledShStrMapper() elemMapper.SetInput(visElems) elemMapper.LabelTextProperty.SetColor(0,0,0.9) elemLabels= vtk.vtkActor2D() elemLabels.SetMapper(elemMapper) renderer.AddActor2D(elemLabels)
def VtkDibujaIdsCells(uGrid, setToDraw, entTypeName, renderer): ids = vtk.vtkIdFilter() ids.SetInput(uGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsCells(uGrid, setToDraw, entTypeName) # Dibuja las etiquetas de las líneas. cc = vtk.vtkCellCenters() cc.SetInputConnection(ids.GetOutputPort()) # Centroides de las celdas. visCells = vtk.vtkSelectVisiblePoints() visCells.SetInputConnection(cc.GetOutputPort()) visCells.SetRenderer(renderer) visCells.SelectionWindowOff() #Create the mapper to display the cell ids. Specify the format to # use for the labels. Also create the associated actor. cellMapper = vtk.vtkLabeledDataMapper() cellMapper.SetInputConnection(visCells.GetOutputPort()) cellMapper.GetLabelTextProperty().SetColor(0, 0, 0.9) cellLabels = vtk.vtkActor2D() cellLabels.SetMapper(cellMapper) renderer.AddActor2D(cellLabels)
def VtkDibujaIdsKPts(uGrid, setToDraw, renderer): '''Draw the point labels.''' numKPtsDI= setToDraw.getPoints.size if(numKPtsDI>0): ids= vtk.vtkIdFilter() ids.SetInput(uGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsKPts(uGrid,setToDraw) visPts= vtk.vtkSelectVisiblePoints() visPts.SetInputConnection(ids.GetOutputPort()) visPts.SetRenderer(renderer) visPts.SelectionWindowOff() #Create the mapper to display the point ids. Specify the format to # use for the labels. Also create the associated actor. ldm= vtk.vtkLabeledDataMapper() ldm.SetInputConnection(visPts.GetOutputPort()) ldm.GetLabelTextProperty().SetColor(0.1,0.1,0.1) pointLabels= vtk.vtkActor2D() pointLabels.SetMapper(ldm) renderer.AddActor2D(pointLabels) else: print "El conjunto: '",setToDraw,"' no tiene KPts."
def Release(self, obj, event): if self.pega_pontos: iren =self.Interactor ren = self.renderer x, y = iren.GetEventPosition() self.x1 = x self.y1 = y xmin = min(self.x0, self.x1) xmax = max(self.x0, self.x1) ymin = min(self.y0, self.y1) ymax = max(self.y0, self.y1) # Generate ids for labeling ids = vtk.vtkIdFilter() ids.SetInputData(self.polydata) ids.PointIdsOn() ids.CellIdsOn() ids.FieldDataOn() ids.Update() s = vtk.vtkSelectVisiblePoints() s.SetRenderer(self.renderer) s.SetInputData(ids.GetOutput()) s.SelectionWindowOn() s.SetSelection(xmin, xmax, ymin, ymax) s.SelectInvisibleOff() s.Update() id_points = numpy_support.vtk_to_numpy(s.GetOutput().GetPointData().GetAbstractArray("vtkIdFilter_Ids")) print id_points self.id_points.update(id_points.tolist()) else: obj.EndRotate()
def VtkDibujaIdsElementos(nmbUGrid, setName, renderer): # ****** Creamos las etiquetas para las celdas ******* ids = vtk.vtkIdFilter() ids.SetInput(nmbUGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsElem(nmbUGrid, setName)() # Dibuja las etiquetas de las líneas. cc = vtk.vtkCellCenters() cc.SetInput(ids) # Centroides de las celdas. visElems = vtk.vtkSelectVisiblePoints() visElems.SetInput(cc) visElems.SetRenderer(renderer) visElems.SelectionWindowOff() ''' Create the mapper to display the element ids. Specify the format to use for the labels. Also create the associated actor. ''' elemMapper = vtk.vtkLabeledShStrMapper() elemMapper.SetInput(visElems) elemMapper.LabelTextProperty.SetColor(0, 0, 0.9) elemLabels = vtk.vtkActor2D() elemLabels.SetMapper(elemMapper) renderer.AddActor2D(elemLabels)
def VtkDibujaIdsKPts(uGrid, setToDraw, renderer): numKPtsDI = setToDraw.getPoints.size if (numKPtsDI > 0): ids = vtk.vtkIdFilter() ids.SetInput(uGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsKPts(uGrid, setToDraw) visPts = vtk.vtkSelectVisiblePoints() visPts.SetInputConnection(ids.GetOutputPort()) visPts.SetRenderer(renderer) visPts.SelectionWindowOff() #Create the mapper to display the point ids. Specify the format to # use for the labels. Also create the associated actor. ldm = vtk.vtkLabeledDataMapper() ldm.SetInputConnection(visPts.GetOutputPort()) ldm.GetLabelTextProperty().SetColor(0.1, 0.1, 0.1) pointLabels = vtk.vtkActor2D() pointLabels.SetMapper(ldm) renderer.AddActor2D(pointLabels) else: print "El conjunto: '", setToDraw, "' no tiene KPts."
def set_mesh(self, V, T, **kwargs): self.V = V self.T = T self._k = np.zeros(V.shape[0], dtype=np.int32) model_poly_data = numpy_to_vtkPolyData(V, faces.faces_to_cell_array(T)) idFilter = vtk.vtkIdFilter() idFilter.SetInput(model_poly_data) idFilter.SetIdsArrayName('i') idFilter.Update() labelled_poly_data = idFilter.GetOutput() self.pipeline['color_points'].SetInput(model_poly_data) self.pipeline['color_faces'].SetInput(model_poly_data) self.pipeline['visible'].SetInput(labelled_poly_data) enorm = lambda V: np.sqrt(np.sum(V * V, axis=-1)) edge_lengths = np.r_[enorm(V[T[:, 0]] - V[T[:, 1]]), enorm(V[T[:, 1]] - V[T[:, 2]]), enorm(V[T[:, 2]] - V[T[:, 0]])] length = 0.2 * np.mean(edge_lengths) self.pipeline['source'].SetXLength(length) self.pipeline['source'].SetYLength(length) self.pipeline['source'].SetZLength(length) self.pipeline['vertices_actor'].VisibilityOn() self.pipeline['model_actor'].VisibilityOn() self.pipeline['ren'].ResetCamera() self.update()
def get_ids_filter(grid: Union[vtk.vtkUnstructuredGrid, vtk.vtkPolyData], idsname: str = 'Ids', is_nids: bool = True, is_eids: bool = True) -> vtk.vtkIdFilter: """ get the vtkIdFilter associated with a grid and either nodes/elements or both """ ids = vtk.vtkIdFilter() if isinstance(grid, vtk.vtkUnstructuredGrid): # this is typically what's called in the gui ids.SetInputData(grid) elif isinstance(grid, vtk.vtkPolyData): # pragma: no cover # this doesn't work... ids.SetCellIds(grid.GetCellData()) ids.SetPointIds(grid.GetPointData()) else: raise NotImplementedError(ids) #self.is_eids = False ids.CellIdsOn() ids.PointIdsOn() #print('is_eids=%s is_nids=%s' % (is_eids, is_nids)) if not is_eids: ids.CellIdsOff() if not is_nids: ids.PointIdsOff() #ids.FieldDataOn() ids.SetIdsArrayName(idsname) return ids
def get_domain_with_node_ids(mesh_vtu, domain_id_list): # -- add copy of element point ids to mesh pointIdFilter = vtk.vtkIdFilter() pointIdFilter.SetInputData(mesh_vtu) pointIdFilter.SetPointIds(True) pointIdFilter.SetCellIds(False) pointIdFilter.SetIdsArrayName("originalPointIDs") pointIdFilter.Update() mesh = pointIdFilter.GetUnstructuredGridOutput() # -- NUMPY - VTK mesh_wrapped = dsa.WrapDataObject(mesh) # -- extract element block ids material_array_name = "ElementBlockIds" element_block_id_array = mesh_wrapped.CellData[material_array_name] # -- create empty array for selection element_selection_array_name = "ElementSelection" element_selection_array = np.zeros(algs.shape(element_block_id_array)[0]) # -- assign selection id = 1 for elements in domain_id_list for domain_id in domain_id_list: element_selection_array[element_block_id_array == domain_id] = 1 # -- add selection array to mesh mesh_wrapped.CellData.append(element_selection_array, element_selection_array_name) # -- extract parts of mesh that have been selected selector = vtk.vtkThreshold() selector.SetInputData(mesh) selector.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, element_selection_array_name) selector.ThresholdBetween(1, 1) selector.Update() subgrid = selector.GetOutput() return subgrid
def _pick_depth_ids(self, xmin, ymin, xmax, ymax): """ Does an area pick of all the ids inside the box, even the ones behind the front elements """ area_picker = self.parent.area_picker area_picker.Pick() area_picker.AreaPick(xmin, ymin, xmax, ymax, self.parent.rend) frustrum = area_picker.GetFrustum() # vtkPlanes grid = self.parent.grid #extract_ids = vtk.vtkExtractSelectedIds() #extract_ids.AddInputData(grid) idsname = "Ids" ids = vtk.vtkIdFilter() ids.SetInputData(grid) if self.is_eids: ids.CellIdsOn() if self.is_nids: ids.PointIdsOn() #ids.FieldDataOn() ids.SetIdsArrayName(idsname) selected_frustrum = vtk.vtkExtractSelectedFrustum() selected_frustrum.SetFrustum(frustrum) selected_frustrum.PreserveTopologyOff() selected_frustrum.SetInputConnection(ids.GetOutputPort()) # was grid? selected_frustrum.Update() ugrid = selected_frustrum.GetOutput() eids = None nids = None msg = '' if self.is_eids: cells = ugrid.GetCellData() if cells is not None: ids = cells.GetArray('Ids') if ids is not None: cell_ids = vtk_to_numpy(ids) assert len(cell_ids) == len(np.unique(cell_ids)) eids = self.parent.get_element_ids(cell_ids) if self.is_nids: points = ugrid.GetPointData() if points is not None: ids = points.GetArray('Ids') if ids is not None: point_ids = vtk_to_numpy(ids) nids = self.parent.get_node_ids(point_ids) if self.callback is not None: self.callback(eids, nids) self.area_pick_button.setChecked(False) self.parent.setup_mouse_buttons(mode='default')
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkIdFilter(), 'Processing.', ('vtkDataSet', ), ('vtkDataSet', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def build_tag(self, label): self.label = label tag = vtk.vtkIdFilter() tag.CellIdsOn() tag.PointIdsOff() tag.SetInputConnection(self.mesh.GetOutputPort()) tag.SetIdsArrayName('elemTag') tag.Update() self.mesh = tag
def flux_area(verbose, poly_data): """ Calculate cosflow flux area for both eles and nodes in a surface @type verbose: bool @param verbose: whether to print progress to screen @type poly_data: vtkPolyData @param poly_data: poly data describing the surface @rtype: tuple of vtkFloatArray @return: (nodal flux area, elemental flux area) """ num_pts = poly_data.GetNumberOfPoints() num_cells = poly_data.GetNumberOfCells() if verbose: print " Flux Area: Recording cell ids" cell_ids = vtk.vtkIdFilter() cell_ids.SetInputConnection(poly_data.GetProducerPort()) cell_ids.CellIdsOn() cell_ids.Update() cell_ids = cell_ids.GetOutput() # vtkPolyData if verbose: print " Flux Area: Triangulating" tri_os = vtk.vtkTriangleFilter() tri_os.SetInputConnection(cell_ids.GetProducerPort()) tri_os.Update() tri_os = tri_os.GetOutput() # vtkPolyData orig_cell_ids = tri_os.GetCellData().GetScalars("vtkIdFilter_Ids") if verbose: print " Flux Area: Calculating areas" cell_areas = [0.0 for cell in range(num_cells)] nodal_areas = [0.0 for nod in range(num_pts)] for cellid in range(tri_os.GetNumberOfCells()): the_cell = tri_os.GetCell(cellid) orig_cell_id = orig_cell_ids.GetValue(cellid) tri_area = the_cell.ComputeArea() for pt in range(3): ptid = the_cell.GetPointId(pt) # equally proportion triangle areas to the points nodal_areas[ptid] += tri_area/3.0 cell_areas[orig_cell_id] += tri_area if verbose: print " Flux Area: Building cell and point area vtk array" na = vtk.vtkFloatArray() na.SetNumberOfValues(num_pts) na.SetName("cosflow_nodal_flux_area") for ptid in range(num_pts): na.SetValue(ptid, nodal_areas[ptid]) ca = vtk.vtkFloatArray() ca.SetNumberOfValues(num_cells) ca.SetName("cosflow_ele_flux_area") for cellid in range(num_cells): ca.SetValue(cellid, cell_areas[cellid]) return (na, ca)
def addGlobalIds(dataset): ids = vtk.vtkIdFilter() ids.PointIdsOn() ids.CellIdsOn() ids.SetIdsArrayName("vtkGlobalIds") ids.SetInputDataObject(dataset) ids.Update() data2 = ids.GetOutput() dataset.GetCellData().SetGlobalIds(data2.GetCellData().GetArray("vtkGlobalIds")) dataset.GetPointData().SetGlobalIds(data2.GetPointData().GetArray("vtkGlobalIds"))
def addGlobalIds(dataset): ids = vtk.vtkIdFilter() ids.PointIdsOn() ids.CellIdsOn() ids.SetIdsArrayName("vtkGlobalIds") ids.SetInputDataObject(dataset) ids.Update() data2 = ids.GetOutput() dataset.GetCellData().SetGlobalIds( data2.GetCellData().GetArray("vtkGlobalIds")) dataset.GetPointData().SetGlobalIds( data2.GetPointData().GetArray("vtkGlobalIds"))
def main(): pointSource = vtk.vtkPointSource() pointSource.SetNumberOfPoints(20) pointSource.Update() idFilter = vtk.vtkIdFilter() idFilter.SetInputConnection(pointSource.GetOutputPort()) idFilter.SetIdsArrayName("OriginalIds") idFilter.Update() surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(idFilter.GetOutputPort()) surfaceFilter.Update() poly_input = surfaceFilter.GetOutput() # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInputConnection(poly_input.GetProducerPort()) else: mapper.SetInputData(poly_input) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) # Visualize renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) areaPicker = vtk.vtkAreaPicker() renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetPicker(areaPicker) renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) #renderer.SetBackground(1,1,1) # Background color white renderWindow.Render() style = vtk.vtkRenderWindowInteractor() #style = myInteractorStyle() #style = InteractorStyle() #style = QVTKRenderWindowInteractor() #style.SetPoints(poly_input) renderWindowInteractor.SetInteractorStyle(style) renderWindowInteractor.Start()
def pick_depth_ids(self, xmin, ymin, xmax, ymax): """ Does an area pick of all the ids inside the box, even the ones behind the front elements """ retval = self.area_picker.AreaPick(xmin, ymin, xmax, ymax, self.ren) # self.area_picker.Pick() frustum = self.area_picker.GetFrustum() # vtkPlanes ids = vtk.vtkIdFilter() ids.SetInputData(self.grid) # ids.CellIdsOn() ids.PointIdsOn() ids.SetIdsArrayName("Ids") # get the cells/points inside the frustum selected_frustum = vtk.vtkExtractSelectedFrustum() selected_frustum.SetFieldType(True) selected_frustum.SetFrustum(frustum) selected_frustum.SetInputConnection(ids.GetOutputPort()) selected_frustum.Update() picked_grid = selected_frustum.GetOutput() if picked_grid: point_ids = None points = picked_grid.GetPointData() if points is not None: ids = points.GetArray('Ids') if ids is not None: point_ids = vtk_to_numpy(ids) if len(point_ids) != 0: self.node_ids.extend(point_ids) points = self.grid.GetPoints() _grid = vtk.vtkUnstructuredGrid() _grid.SetPoints(points) for node_id in point_ids: vertex = vtk.vtkVertex() vertex.GetPointIds().SetId(0, node_id) _grid.InsertNextCell(vertex.GetCellType(), vertex.GetPointIds()) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(_grid) colors = vtk.vtkNamedColors() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor( colors.GetColor3d("Tomato")) # actor.GetProperty().SetOpacity(.5) actor.GetProperty().SetPointSize(10) self.actors.append(actor) self.ren.AddActor(actor) self.iren.Render()
def initPipeline(self): try: if self.pipelineInitialized: # default state self.style.LockAspectToViewportOff() self.style.CenterAtStartPositionOff() self.style.UseDollyForPerspectiveProjectionOn() # reset camera too self.renderer.ResetCamera() self.renderWindow.Render() except AttributeError: pass self.pipelineInitialized = True self.sphere = vtk.vtkSphereSource() self.idFilter = vtk.vtkIdFilter() self.mapper = vtk.vtkPolyDataMapper() self.actor = vtk.vtkActor() self.idFilter.PointIdsOff() self.idFilter.CellIdsOn() self.idFilter.SetInputConnection(self.sphere.GetOutputPort()) self.mapper.SetInputConnection(self.idFilter.GetOutputPort()) self.mapper.SetColorModeToMapScalars() self.mapper.SetScalarModeToUseCellFieldData() self.mapper.SelectColorArray("vtkIdFilter_Ids") self.mapper.UseLookupTableScalarRangeOff() self.mapper.SetScalarRange(0, 95) self.actor.SetMapper(self.mapper) self.renderer = vtk.vtkRenderer() self.renderer.AddActor(self.actor) self.renderWindow = vtk.vtkRenderWindow() self.renderWindow.AddRenderer(self.renderer) self.iren = vtk.vtkRenderWindowInteractor() self.iren.SetRenderWindow(self.renderWindow) self.style = vtk.vtkInteractorStyleRubberBandZoom() self.iren.SetInteractorStyle(self.style) self.renderer.GetActiveCamera().SetPosition(0, 0, -1) self.renderer.ResetCamera() self.renderWindow.Render()
def addIDs(self, asfield=False): """ Generate point and cell ids. :param bool asfield: flag to control whether to generate scalar or field data. """ ids = vtk.vtkIdFilter() ids.SetInputData(self._polydata) ids.PointIdsOn() ids.CellIdsOn() if asfield: ids.FieldDataOn() else: ids.FieldDataOff() ids.Update() return self._update(ids.GetOutput())
def generateMeshPolyData(points): pts = v.vtkPoints() for p in points: pts.InsertNextPoint(p) pd = v.vtkPolyData() pd.SetPoints(pts) # Create a IdFilter to preserve original point ids idf = v.vtkIdFilter() idf.SetIdsArrayName('origIds') idf.PointIdsOn() idf.SetInputData(pd) # Create a 2D Delaunay triangulation d2d = v.vtkDelaunay2D() d2d.SetInputConnection(idf.GetOutputPort()) # Create mesh quality cell data array to filter out # boundary triangles mq = v.vtkMeshQuality() mq.SetInputConnection(d2d.GetOutputPort()) mq.SetTriangleQualityMeasureToAspectRatio() mq.SaveCellQualityOn() mq.Update() # Generate the polydata with mesh plateTriPoly = mq.GetOutput() plateTri = plateTriPoly.GetPolys() # Map the connectivity to original point ids newTriangles = v.vtkCellArray() plateTri.InitTraversal() triIds = v.vtkIdList() origIds = plateTriPoly.GetPointData().GetArray('origIds') aspectRatioArray = plateTriPoly.GetCellData().GetArray('Quality') triangleIndex = 0 while plateTri.GetNextCell(triIds): # Keep only the equilateral triangles to get rid of boundary triangles aspectRatio = aspectRatioArray.GetTuple1(triangleIndex) triangleIndex += 1 if aspectRatio < 1.5: newTriangles.InsertNextCell(3) for i in range(3): newTriangles.InsertCellPoint( int(origIds.GetTuple1(triIds.GetId(i)))) pd.SetPolys(newTriangles) return pd
def triangulate(pd): """ Generates a triangle mesh for a spherical point cloud. It is assumed that 'pd' is an object of dsa.PolyData type. """ # Project on a sphere sphereXyz = alg.norm(pd.Points) * np.linalg.norm(pd.Points, axis=1).mean() sphereXyz = np.around(sphereXyz, decimals=2) sphereArr = dsa.numpyTovtkDataArray(sphereXyz, name='SpherePts') pts = v.vtkPoints() pts.SetData(sphereArr) sphere = v.vtkPolyData() sphere.SetPoints(pts) # Store the original point ids idf = v.vtkIdFilter() idf.SetIdsArrayName('PointIds') idf.PointIdsOn() idf.SetInputData(sphere) # Delaunay3D to make a convex hull d3d = v.vtkDelaunay3D() d3d.SetInputConnection(idf.GetOutputPort()) # Extract the surface surf = v.vtkDataSetSurfaceFilter() surf.SetInputConnection(d3d.GetOutputPort()) surf.Update() # Now make a new cell array mapping to the old ids polyCells = v.vtkCellArray() sphereCells = surf.GetOutput().GetPolys() sphereCells.InitTraversal() origIds = surf.GetOutput().GetPointData().GetArray('PointIds') ptIds = v.vtkIdList() while (sphereCells.GetNextCell(ptIds)): polyCells.InsertNextCell(3) polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(0)))) polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(1)))) polyCells.InsertCellPoint(int(origIds.GetTuple1(ptIds.GetId(2)))) return polyCells
def makeConnectivityList(poly): listOut = [] idf = v.vtkIdFilter() idf.SetInputData(poly) idf.SetIdsArrayName('OrigIds') idf.PointIdsOn() edgeExt = v.vtkExtractEdges() edgeExt.SetInputConnection(idf.GetOutputPort()) edgeExt.Update() edges = edgeExt.GetOutput() origIds = edges.GetPointData().GetArray('OrigIds') ids = v.vtkIdList() cells = edges.GetLines() cells.InitTraversal() while cells.GetNextCell(ids): connectivity = [] for i in range(ids.GetNumberOfIds()): connectivity.append(int(origIds.GetTuple1(ids.GetId(i)))) listOut.append(connectivity) return listOut
def extractBoundaryPoints(self, polyData, edgeName=""): idFilter = vtk.vtkIdFilter() idFilter.SetInputData(polyData) idFilter.SetIdsArrayName("ids") idFilter.PointIdsOn() idFilter.CellIdsOff() idFilter.Update() edgeFilter = vtk.vtkFeatureEdges() edgeFilter.SetInputConnection(idFilter.GetOutputPort()) edgeFilter.BoundaryEdgesOn() edgeFilter.FeatureEdgesOff() edgeFilter.ManifoldEdgesOff() edgeFilter.NonManifoldEdgesOff() edgeFilter.Update() if edgeName != "": self.createNewModelNode(edgeFilter.GetOutput(), edgeName) return edgeFilter.GetOutput(), vtk_to_numpy( edgeFilter.GetOutput().GetPointData().GetArray("ids"))
def VtkDibujaIdsNodes(recordGrid, renderer): '''Display node labels''' ids= vtk.vtkIdFilter() ids.SetInput(recordGrid.uGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsNodes(recordGrid) visPts= vtk.vtkSelectVisiblePoints() visPts.SetInput("ids") visPts.SetRenderer(renderer) visPts.SelectionWindowOff() #Create the mapper to display the point ids. Specify the format to # use for the labels. Also create the associated actor. ldm= vtk.vtkLabeledShStrMapper() ldm.SetInput("visPts") ldm.LabelTextProperty().SetColor(0.1,0.1,0.1) nodeLabels= vtk.vtkActor2D().SetMapper(ldm) renderer.AddActor2D(nodeLabels)
def VtkDibujaIdsNodes(recordGrid, renderer): '''Display node labels (not implemented yet)''' ids = vtk.vtkIdFilter() ids.SetInput(recordGrid.uGrid) ids.CellIdsOff() ids.PointIdsOff() VtkCargaIdsNodes(recordGrid) visPts = vtk.vtkSelectVisiblePoints() visPts.SetInput("ids") visPts.SetRenderer(renderer) visPts.SelectionWindowOff() #Create the mapper to display the point ids. Specify the format to # use for the labels. Also create the associated actor. ldm = vtk.vtkLabeledShStrMapper() ldm.SetInput("visPts") ldm.LabelTextProperty().SetColor(0.1, 0.1, 0.1) nodeLabels = vtk.vtkActor2D().SetMapper(ldm) renderer.AddActor2D(nodeLabels)
def Release(self, obj, event): if self.pega_pontos: iren = self.Interactor ren = self.renderer x, y = iren.GetEventPosition() self.x1 = x self.y1 = y xmin = min(self.x0, self.x1) xmax = max(self.x0, self.x1) ymin = min(self.y0, self.y1) ymax = max(self.y0, self.y1) # Generate ids for labeling ids = vtk.vtkIdFilter() ids.SetInputData(self.polydata) ids.PointIdsOn() ids.CellIdsOn() ids.FieldDataOn() ids.Update() s = vtk.vtkSelectVisiblePoints() s.SetRenderer(self.renderer) s.SetInputData(ids.GetOutput()) s.SelectionWindowOn() s.SetSelection(xmin, xmax, ymin, ymax) s.SelectInvisibleOff() s.Update() id_points = numpy_support.vtk_to_numpy( s.GetOutput().GetPointData().GetAbstractArray( "vtkIdFilter_Ids")) print id_points self.id_points.update(id_points.tolist()) else: obj.EndRotate()
def remove_non_visible_faces( polydata, positions=[[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]], remove_visible=False, ): polydata.BuildLinks() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polydata) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetSize(800, 800) render_window.OffScreenRenderingOn() camera = renderer.GetActiveCamera() renderer.ResetCamera() pos = np.array(camera.GetPosition()) fp = np.array(camera.GetFocalPoint()) v = pos - fp mag = np.linalg.norm(v) vn = v / mag id_filter = vtk.vtkIdFilter() id_filter.SetInputData(polydata) id_filter.PointIdsOn() id_filter.Update() set_points = None for position in positions: pos = fp + np.array(position) * mag camera.SetPosition(pos.tolist()) renderer.ResetCamera() render_window.Render() select_visible_points = vtk.vtkSelectVisiblePoints() select_visible_points.SetInputData(id_filter.GetOutput()) select_visible_points.SetRenderer(renderer) # select_visible_points.SelectInvisibleOn() select_visible_points.Update() output = select_visible_points.GetOutput() id_points = numpy_support.vtk_to_numpy( output.GetPointData().GetAbstractArray("vtkIdFilter_Ids") ) if set_points is None: set_points = set(id_points.tolist()) else: set_points.update(id_points.tolist()) # id_list = vtk.vtkIdList() # output.GetVerts().GetCell(1000, id_list) if remove_visible: set_points = set(range(polydata.GetNumberOfPoints())) - set_points cells_ids = set() for p_id in set_points: id_list = vtk.vtkIdList() polydata.GetPointCells(p_id, id_list) for i in range(id_list.GetNumberOfIds()): cells_ids.add(id_list.GetId(i)) try: id_list = numpy_support.numpy_to_vtkIdTypeArray(np.array(list(cells_ids), dtype=np.int64)) except ValueError: id_list = vtk.vtkIdTypeArray() selection_node = vtk.vtkSelectionNode() selection_node.SetFieldType(vtk.vtkSelectionNode.CELL) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection_node.SetSelectionList(id_list) selection = vtk.vtkSelection() selection.AddNode(selection_node) extract_selection = vtk.vtkExtractSelection() extract_selection.SetInputData(0, polydata) extract_selection.SetInputData(1, selection) extract_selection.Update() geometry_filter = vtk.vtkGeometryFilter() geometry_filter.SetInputData(extract_selection.GetOutput()) geometry_filter.Update() clean_polydata = vtk.vtkCleanPolyData() clean_polydata.SetInputData(geometry_filter.GetOutput()) clean_polydata.Update() return clean_polydata.GetOutput()
def display_annot(self, images, image_pos_pat, image_ori_pat, annots_dict_list, interact): '''Display list of annotations, put markers according to notes and color code according to sequence order''' # define image based on subtraction of postS -preS image = images[4] # Proceed to build reference frame for display objects based on DICOM coords [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat) # supports 56 annotations color_list = [ [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0], [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0], [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0], [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0] ] a_count = 1 annot_pts_lbl = vtk.vtkPoints() for annots_dict in annots_dict_list: try: float(annots_dict['SliceLocation']) print '\n=========#'+str(a_count) print annots_dict ###################### ## Display in graphics ###################### im_pt = [0,0,0] ijk = [0,0,0] pco = [0,0,0] pi_2display=[0,0,0] pf_2display=[0,0,0] # extract Slice locaton pixId_sliceloc = self.transformed_image.FindPoint(self.origin[0], self.origin[1], float(annots_dict['SliceLocation'])) self.transformed_image.GetPoint(pixId_sliceloc, im_pt) io = self.transformed_image.ComputeStructuredCoordinates( im_pt, ijk, pco) # mark initial print "Point init" ijk[0] = int(annots_dict['xi']) ijk[1] = int(annots_dict['yi']) print ijk annots_dict['pi_ijk']=ijk pixId = self.transformed_image.ComputePointId(ijk) pi_2display = self.transformed_image.GetPoint(pixId) annots_dict['pi_2display']=pi_2display print pi_2display # mark final print "Point final" ijk[0] = int(annots_dict['xf']) ijk[1] = int(annots_dict['yf']) print ijk annots_dict['pf_ijk']=ijk pixId = self.transformed_image.ComputePointId(ijk) pf_2display = self.transformed_image.GetPoint(pixId) annots_dict['pf_2display']=pf_2display print pf_2display # Create a graphial line between the two points annot_pts = vtk.vtkPoints() annot_pts.InsertNextPoint(pi_2display) annot_pts.InsertNextPoint(pf_2display) annot_ln = vtk.vtkLine() annot_ln.GetPointIds().SetId(0,0) annot_ln.GetPointIds().SetId(1,1) note_lines = vtk.vtkCellArray() note_lines.InsertNextCell(annot_ln) annot_poly = vtk.vtkPolyData() annot_poly.SetPoints(annot_pts) annot_poly.SetLines(note_lines) annot_poly.Update() # Create mappers and actors annot_mapper_mesh = vtk.vtkPolyDataMapper() annot_mapper_mesh.SetInputData( annot_poly ) self.annot_actor = vtk.vtkActor() self.annot_actor.SetMapper(annot_mapper_mesh) self.annot_actor.GetProperty().SetColor(color_list[a_count]) self.annot_actor.GetProperty().SetLineWidth(3) self.annot_actor.GetProperty().SetOpacity(0.6) self.annot_actor.GetProperty().SetPointSize(7.0) self.annot_actor.GetProperty().SetRepresentationToWireframe() ############ # Generate data arrays containing label ids annot_pts_lbl.InsertPoint(a_count, pi_2display) # add annotation to scene print annots_dict self.renderer1.AddActor(self.annot_actor) # Initizalize self.renWin1.Render() self.renderer1.Render() a_count +=1 except ValueError: a_count +=1 pass ############ print annot_pts_lbl.GetNumberOfPoints() annot_lbl_poly = vtk.vtkPolyData() annot_lbl_poly.SetPoints(annot_pts_lbl) annot_lbl_poly.Update() # Generate data arrays containing label ids ids = vtk.vtkIdFilter() ids.SetInput(annot_lbl_poly) ids.PointIdsOn() ids.CellIdsOff() # Create labels for points visPts = vtk.vtkSelectVisiblePoints() visPts.SetInput(ids.GetOutput()) visPts.SetRenderer(self.renderer1) visPts.SelectionWindowOff() # Create the mapper to display the point ids. Specify the format to # use for the labels. Also create the associated actor. ldm = vtk.vtkLabeledDataMapper() ldm.SetInput(visPts.GetOutput()) ldm.SetLabelModeToLabelFieldData() pointLabels = vtk.vtkActor2D() pointLabels.SetMapper(ldm) # initialize self.renderer1.AddActor2D(pointLabels) print "\n====== Color codes:\n " print '\033[1;31m 1) Red ' print '\033[1;34m 2) Blue ' print '\033[1;36m 3) Cyan ' print '\033[1;33m 4) Yellow ' print '\033[1;35m 5) Fushia ' print '\033[1;37m 6) White ' print '\033[1;30m 7) Gray ' print '\033[1;0m' ############ if(interact==True): interactor = self.renWin1.GetInteractor() interactor.Start() return
reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(fn) reader.Update() #want to keep track of cellIds ids_filter = vtk.vtkIdFilter() ids_filter.SetInputConnection(reader.GetOutputPort()) #ids_filter.PointIdsOn() ids_filter.CellIdsOn() ids_filter.FieldDataOn() ids_filter.SetIdsArrayName("Ids") ids_filter.Update() vtkMesh = ids_filter.GetOutput() numberOfCellArrays = vtkMesh.GetCellData().GetNumberOfArrays() cell_entity_id = 0 cell_id_id = 0 arrayNames = [] for i in range(numberOfCellArrays): arrayNames.append(vtkMesh.GetCellData().GetArrayName(i))
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()
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Create a pipeline: some skinny-ass triangles sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(6) sphere.SetPhiResolution(24) ids = vtk.vtkIdFilter() ids.SetInputConnection(sphere.GetOutputPort()) adapt = vtk.vtkAdaptiveSubdivisionFilter() adapt.SetInputConnection(ids.GetOutputPort()) adapt.SetMaximumEdgeLength(0.1) #adapt.SetMaximumTriangleArea(0.01) #adapt.SetMaximumNumberOfPasses(1) adapt.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(adapt.GetOutputPort()) mapper.SetScalarModeToUseCellFieldData() mapper.SelectColorArray("vtkIdFilter_Ids") mapper.SetScalarRange(adapt.GetOutput().GetCellData().GetScalars().GetRange()) edgeProp = vtk.vtkProperty() edgeProp.EdgeVisibilityOn() edgeProp.SetEdgeColor(0, 0, 0)
def display_annot(self, images, image_pos_pat, image_ori_pat, annots_dict_list, interact): '''Display list of annotations, put markers according to notes and color code according to sequence order''' # define image based on subtraction of postS -preS image = images[4] # Proceed to build reference frame for display objects based on DICOM coords [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat) # supports 56 annotations color_list = [ [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0], [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0], [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0], [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0] ] a_count = 1 annot_pts_lbl = vtk.vtkPoints() for annots_dict in annots_dict_list: try: float(annots_dict['SliceLocation']) print '\n=========#'+str(a_count) print annots_dict ###################### ## Display in graphics ###################### im_pt = [0,0,0] ijk = [0,0,0] pco = [0,0,0] pi_2display=[0,0,0] pf_2display=[0,0,0] # extract Slice locaton pixId_sliceloc = self.transformed_image.FindPoint(self.origin[0], self.origin[1], float(annots_dict['SliceLocation'])) self.transformed_image.GetPoint(pixId_sliceloc, im_pt) io = self.transformed_image.ComputeStructuredCoordinates( im_pt, ijk, pco) # mark initial print "Point init" ijk[0] = int(annots_dict['xi']) ijk[1] = int(annots_dict['yi']) print ijk annots_dict['pi_ijk']=ijk pixId = self.transformed_image.ComputePointId(ijk) pi_2display = self.transformed_image.GetPoint(pixId) annots_dict['pi_2display']=pi_2display print pi_2display # mark final print "Point final" ijk[0] = int(annots_dict['xf']) ijk[1] = int(annots_dict['yf']) print ijk annots_dict['pf_ijk']=ijk pixId = self.transformed_image.ComputePointId(ijk) pf_2display = self.transformed_image.GetPoint(pixId) annots_dict['pf_2display']=pf_2display print pf_2display # Create a graphial line between the two points annot_pts = vtk.vtkPoints() annot_pts.InsertNextPoint(pi_2display) annot_pts.InsertNextPoint(pf_2display) annot_ln = vtk.vtkLine() annot_ln.GetPointIds().SetId(0,0) annot_ln.GetPointIds().SetId(1,1) note_lines = vtk.vtkCellArray() note_lines.InsertNextCell(annot_ln) annot_poly = vtk.vtkPolyData() annot_poly.SetPoints(annot_pts) annot_poly.SetLines(note_lines) annot_poly.Update() # Create mappers and actors annot_mapper_mesh = vtk.vtkPolyDataMapper() annot_mapper_mesh.SetInput( annot_poly ) self.annot_actor = vtk.vtkActor() self.annot_actor.SetMapper(annot_mapper_mesh) self.annot_actor.GetProperty().SetColor(color_list[a_count]) self.annot_actor.GetProperty().SetLineWidth(3) self.annot_actor.GetProperty().SetOpacity(0.6) self.annot_actor.GetProperty().SetPointSize(7.0) self.annot_actor.GetProperty().SetRepresentationToWireframe() ############ # Generate data arrays containing label ids annot_pts_lbl.InsertPoint(a_count, pi_2display) # add annotation to scene print annots_dict self.renderer1.AddActor(self.annot_actor) # Initizalize self.renWin1.Render() self.renderer1.Render() a_count +=1 except ValueError: a_count +=1 pass ############ print annot_pts_lbl.GetNumberOfPoints() annot_lbl_poly = vtk.vtkPolyData() annot_lbl_poly.SetPoints(annot_pts_lbl) annot_lbl_poly.Update() # Generate data arrays containing label ids ids = vtk.vtkIdFilter() ids.SetInput(annot_lbl_poly) ids.PointIdsOn() ids.CellIdsOff() # Create labels for points visPts = vtk.vtkSelectVisiblePoints() visPts.SetInput(ids.GetOutput()) visPts.SetRenderer(self.renderer1) visPts.SelectionWindowOff() # Create the mapper to display the point ids. Specify the format to # use for the labels. Also create the associated actor. ldm = vtk.vtkLabeledDataMapper() ldm.SetInput(visPts.GetOutput()) ldm.SetLabelModeToLabelFieldData() pointLabels = vtk.vtkActor2D() pointLabels.SetMapper(ldm) # initialize self.renderer1.AddActor2D(pointLabels) print "\n====== Color codes:\n " print '\033[1;31m 1) Red ' print '\033[1;34m 2) Blue ' print '\033[1;36m 3) Cyan ' print '\033[1;33m 4) Yellow ' print '\033[1;35m 5) Fushia ' print '\033[1;37m 6) White ' print '\033[1;30m 7) Gray ' print '\033[1;0m' ############ if(interact==True): interactor = self.renWin1.GetInteractor() interactor.Start() return
#!/usr/bin/env python # Demonstrate how to use the vtkConvertIds class works with point & cell data import vtk import sys sys.path.append("/Users/emonson/Programming/VTK_git/vtkVTG/build/bin") import libvtkvtgRenderingPython as vtgR rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-3,3,-3,3,-3,3) ids = vtk.vtkIdFilter() # Ids filter destroys RTData attributes!!! :( ids.SetInputConnection(rt.GetOutputPort(0)) ids.SetIdsArrayName('filter_ids') ids.Update() data = ids.GetOutputDataObject(0) numPts = data.GetPointData().GetArray('filter_ids').GetNumberOfTuples() att = vtk.vtkIntArray() # att = vtk.vtkIdTypeArray() att.SetName('orig_id_values') att.SetNumberOfComponents(1) att.SetNumberOfValues(numPts) for ii in range(numPts): att.SetValue(ii,ii) data.GetPointData().AddArray(att) # data.GetPointData().SetActiveScalars('orig_id_values')
def cell_pick(self, _id): if _id != -1: if self.last_selection == 'Element %s' % str(_id): self.should_it_render = False self.did_it_render = True return True camera_pos = self.camera.GetPosition() self.last_selection = 'Element %s' % str(_id) cell = self.Data.GetCell(_id) points = cell.GetPoints() count = points.GetNumberOfPoints() ids = vtk.vtkIdTypeArray() ids.SetNumberOfComponents(1) ids.InsertNextValue(_id) self.picked_type = 'Element' self.picked_id = self.element_ids[_id] point_list = vtk.vtkPoints() cell_list = vtk.vtkCellArray() f = 0.05 if count == 4: xyz = points.GetPoint(0) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(1) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(2) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(3) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) cell = vtk.vtkQuad() point_ids = cell.GetPointIds() point_ids.SetId(0, 0) point_ids.SetId(1, 1) point_ids.SetId(2, 2) point_ids.SetId(3, 3) elif count == 3: xyz = points.GetPoint(0) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(1) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(2) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) cell = vtk.vtkTriangle() point_ids = cell.GetPointIds() point_ids.SetId(0, 0) point_ids.SetId(1, 1) point_ids.SetId(2, 2) elif count == 2: xyz = points.GetPoint(0) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) xyz = points.GetPoint(1) xyz = [camera_pos[0] + (xyz[0] - camera_pos[0])*f, camera_pos[1] + (xyz[1] - camera_pos[1])*f, camera_pos[2] + (xyz[2] - camera_pos[2])*f] point_list.InsertNextPoint(xyz) cell = vtk.vtkLine() point_ids = cell.GetPointIds() point_ids.SetId(0, 0) point_ids.SetId(1, 1) cell_list.InsertNextCell(cell) poly_data = vtk.vtkPolyData() poly_data.SetPoints(point_list) poly_data.SetPolys(cell_list) poly_data.SetLines(cell_list) idFilter = vtk.vtkIdFilter() idFilter.SetInputData(poly_data) idFilter.SetIdsArrayName("SelectedIds") idFilter.Update() surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(idFilter.GetOutputPort()) surfaceFilter.Update() input = surfaceFilter.GetOutput() self.selectedMapper.SetInputData(input) self.selectedMapper.ScalarVisibilityOff() self.selectedActor.SetMapper(self.selectedMapper) self.selectedActor.GetProperty().EdgeVisibilityOn() # this makes cells not blue? #self.selectedActor.GetProperty().SetColor(0, 0.5, 0) self.selectedActor.GetProperty().SetEdgeColor(0.5, 0.5, 0) self.selectedActor.GetProperty().SetLineWidth(3) self.selectedActor.GetProperty().SetOpacity(0.5) self.should_it_render = True return True else: return False
def __init__(self, filename, parent=None): QtGui.QMainWindow.__init__(self, parent) # Initiate the UI as defined by Qt Designer self.ui = Ui_MainWindow() self.ui.setupUi(self) self.poly_data = None self.node_ids = None self.element_ids = None self.node_count = 0 self.read_data(filename) self.ui.txt_msg.appendPlainText("Model Loaded.") # initialize colors self.eidcolor = (0, 0.5, 0.5) self.edgecolor = (0, 0, 0) self.bgcolor1 = (0, 0, 1) self.bgcolor2 = (0.8, 0.8, 1) self.perspective = 0 self.solid = 1 self.idFilter = vtk.vtkIdFilter() self.idFilter.SetInputData(self.poly_data) self.idFilter.SetIdsArrayName("OriginalIds") self.idFilter.Update() self.surfaceFilter = vtk.vtkDataSetSurfaceFilter() self.surfaceFilter.SetInputConnection(self.idFilter.GetOutputPort()) self.surfaceFilter.Update() self.input = self.surfaceFilter.GetOutput() self.renderer = vtk.vtkRenderer() #self.renderer2 = vtk_widget.vtkRenderer() viewport = [0.0,0.0,0.15,0.15] #self.renderer2.SetViewport(viewport) #self.renderer2.Transparent() self.renderWindowInteractor = QVTKRenderWindowInteractor(self.ui.frame) self.renderWindowInteractor.GetRenderWindow().AddRenderer(self.renderer) #self.renderWindowInteractor.GetRenderWindow().AddRenderer(self.renderer2) self.renderWindowInteractor.GetRenderWindow().SetAlphaBitPlanes(1) self.axes = CoordinateAxes(self.renderWindowInteractor) self.ui.vl.addWidget(self.renderWindowInteractor) self.iren = vtk.vtkRenderWindowInteractor() self.iren = self.renderWindowInteractor.GetRenderWindow().GetInteractor() self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputData(self.input) self.mapper.ScalarVisibilityOff() self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self.actor.GetProperty().SetPointSize(2) self.actor.GetProperty().EdgeVisibilityOn() self.actor.GetProperty().SetColor(self.eidcolor) self.actor.GetProperty().SetEdgeColor(self.edgecolor) self.camera = vtk.vtkCamera() #self.camera2 = vtk_widget.vtkCamera() # trial... add glyph pd = vtk.vtkPolyData() pts = vtk.vtkPoints() scalars = vtk.vtkFloatArray() vectors = vtk.vtkFloatArray() vectors.SetNumberOfComponents(3) pd.SetPoints(pts) pd.GetPointData().SetScalars(scalars) pd.GetPointData().SetVectors(vectors) pts.InsertNextPoint(30, 30, 0.0) scalars.InsertNextValue(1) vectors.InsertNextTuple3(1, 1, 0.0) # Create simple PolyData for glyph table cs = vtk.vtkCubeSource() cs.SetXLength(0.5) cs.SetYLength(1) cs.SetZLength(2) # Set up the glyph filter glyph = vtk.vtkGlyph3D() #glyph.SetInputConnection(elev.GetOutputPort()) point_list = vtk.vtkPoints() point_list.InsertNextPoint([30, 30, 0]) poly_data = vtk.vtkPolyData() poly_data.SetPoints(point_list) idFilter = vtk.vtkIdFilter() idFilter.SetInputData(poly_data) idFilter.SetIdsArrayName("OriginalIds") idFilter.Update() surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(idFilter.GetOutputPort()) surfaceFilter.Update() # Here is where we build the glyph table # that will be indexed into according to the IndexMode glyph.SetSourceData(0,cs.GetOutput()) #glyph.SetInputConnection(surfaceFilter.GetOutputPort()) glyph.SetInputData(pd) glyph.SetIndexModeToScalar() glyph.SetRange(0, 1) glyph.SetScaleModeToDataScalingOff() glyph.OrientOn() mapper3 = vtk.vtkPolyDataMapper() mapper3.SetInputConnection(glyph.GetOutputPort()) mapper3.SetScalarModeToUsePointFieldData() mapper3.SetColorModeToMapScalars() mapper3.ScalarVisibilityOn() mapper3.SetScalarRange(0, 1) actor3 = vtk.vtkActor() actor3.SetMapper(mapper3) #actor3.GetProperty().SetBackgroundOpacity(0.5) gs = vtk.vtkGlyphSource2D() gs.SetGlyphTypeToCircle() gs.SetScale(25) gs.FilledOff() #gs.CrossOn() gs.Update() # Create a table of glyphs glypher = vtk.vtkGlyph2D() glypher.SetInputData(pd) glypher.SetSourceData(0, gs.GetOutput()) glypher.SetIndexModeToScalar() glypher.SetRange(0, 1) glypher.SetScaleModeToDataScalingOff() mapper = vtk.vtkPolyDataMapper2D() mapper.SetInputConnection(glypher.GetOutputPort()) mapper.SetScalarRange(0, 1) actor2D = vtk.vtkActor2D() actor2D.SetMapper(mapper) self.renderer.AddActor(self.actor) #self.renderer.AddActor(mapper) #self.renderer2.AddActor(actor3) self.renderer.SetBackground(self.bgcolor1) self.renderer.SetBackground2(self.bgcolor2) self.renderer.GradientBackgroundOn() self.renderer.SetActiveCamera(self.camera) self.renderer.ResetCamera() #self.camera.ZoomOff() #self.renderer2.SetActiveCamera(self.camera) #self.renderer2.ResetCamera() #self.renderer2.SetBackground(0,0,0) #self.renderer2.GetProperty().SetBackgroundOpacity(0.5) #self.renderer2.SetLayer(1) #self.renderer2.Clear() self.areaPicker = vtk.vtkAreaPicker() self.renderWindowInteractor.SetPicker(self.areaPicker) self.style = MyInteractorStyle() self.style.SetPoints(self.input) self.style.SetDefaultRenderer(self.renderer) self.style.Data = self.idFilter.GetOutput() self.style.camera = self.camera self.style.node_ids = self.node_ids self.style.element_ids = self.element_ids self.style.node_count = self.node_count self.style.window = self self.style.print_message = self.ui.txt_msg.appendPlainText self.renderWindowInteractor.SetInteractorStyle(self.style) self.renderWindowInteractor.Start() # screenshot code:e #self.w2if = vtk_widget.vtkWindowToImageFilter() #self.w2if.SetInput(self.renWin) #self.w2if.Update() self.show() self.iren.Initialize() #self.iren.Start() # Setup Connections self.ui.btn_bgcolor1.clicked.connect(self.on_color1) self.ui.btn_bgcolor2.clicked.connect(self.on_color2) self.ui.btn_edgecolor.clicked.connect(self.on_edgecolor) self.ui.btn_elementcolor.clicked.connect(self.on_elementcolor) self.ui.btn_nofillededge.clicked.connect(self.on_nofillededge) self.ui.btn_switch.clicked.connect(self.on_switch) self.ui.btn_perspectivetoggle.clicked.connect(self.on_toggleperspective) self.ui.btn_saveimg.clicked.connect(self.on_saveimg) self.ui.btn_togglewire.clicked.connect(self.on_togglewire) # Setup a shortcuts self.setusrstyle = QtGui.QShortcut(self) self.setusrstyle.setKey(("CTRL+c")) self.setusrstyle.activated.connect(self.on_copyimg)
cells.InsertNextCell(hexa) hexa = vtk.vtkHexahedron() hexa.GetPointIds().SetId(0, 8) hexa.GetPointIds().SetId(1, 9) hexa.GetPointIds().SetId(2, 10) hexa.GetPointIds().SetId(3, 11) hexa.GetPointIds().SetId(4, 12) hexa.GetPointIds().SetId(5, 13) hexa.GetPointIds().SetId(6, 14) hexa.GetPointIds().SetId(7, 15) cells.InsertNextCell(hexa) grid.SetCells(vtk.VTK_HEXAHEDRON, cells) # filter id_filter = vtk.vtkIdFilter() id_filter.PointIdsOff() id_filter.CellIdsOn() id_filter.SetInputData(grid) # lookup table lut = vtk.vtkLookupTable() lut.SetHueRange(0.667, 0) lut.Build() # mapper mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(id_filter.GetOutputPort()) mapper.SelectColorArray(id_filter.GetIdsArrayName()) mapper.SetScalarRange(id_filter.GetOutput().GetScalarRange()) mapper.SetLookupTable(lut)
def _pick_depth_ids(self, xmin, ymin, xmax, ymax): """ Does an area pick of all the ids inside the box, even the ones behind the front elements """ area_picker = self.parent.area_picker #area_picker.Pick() # double pick? area_picker.AreaPick(xmin, ymin, xmax, ymax, self.parent.rend) frustum = area_picker.GetFrustum() # vtkPlanes grid = self.parent.get_grid(self.name) #extract_ids = vtk.vtkExtractSelectedIds() #extract_ids.AddInputData(grid) idsname = "Ids" ids = vtk.vtkIdFilter() if isinstance(grid, vtk.vtkUnstructuredGrid): # this is typically what's called in the gui ids.SetInputData(grid) elif isinstance(grid, vtk.vtkPolyData): # pragma: no cover # this doesn't work... ids.SetCellIds(grid.GetCellData()) ids.SetPointIds(grid.GetPointData()) else: raise NotImplementedError(ids) #self.is_eids = False ids.CellIdsOn() ids.PointIdsOn() #print('is_eids=%s is_nids=%s' % (self.is_eids, self.is_nids)) if not self.is_eids: ids.CellIdsOff() if not self.is_nids: ids.PointIdsOff() #ids.FieldDataOn() ids.SetIdsArrayName(idsname) if 1: selected_frustum = vtk.vtkExtractSelectedFrustum() #selected_frustum.ShowBoundsOn() #selected_frustum.SetInsideOut(1) selected_frustum.SetFrustum(frustum) # PreserveTopologyOn: return an insidedness array # PreserveTopologyOff: return a ugrid selected_frustum.PreserveTopologyOff() #selected_frustum.PreserveTopologyOn() selected_frustum.SetInputConnection( ids.GetOutputPort()) # was grid? selected_frustum.Update() ugrid = selected_frustum.GetOutput() # we make a second frustum to remove extra points selected_frustum_flipped = vtk.vtkExtractSelectedFrustum() selected_frustum_flipped.SetInsideOut(1) selected_frustum_flipped.SetFrustum(frustum) selected_frustum_flipped.PreserveTopologyOff() selected_frustum_flipped.SetInputConnection( ids.GetOutputPort()) # was grid? selected_frustum_flipped.Update() ugrid_flipped = selected_frustum_flipped.GetOutput() else: # pragma: no cover extract_points = vtk.vtkExtractPoints() selection_node = vtk.vtkSelectionNode() selection = vtk.vtkSelection() #selection_node.SetContainingCellsOn() selection_node.Initialize() selection_node.SetFieldType(vtk.vtkSelectionNode.POINT) selection_node.SetContentType(vtk.vtkSelectionNode.INDICES) selection.AddNode(selection_node) extract_selection = vtk.vtkExtractSelection() extract_selection.SetInputData(0, grid) extract_selection.SetInputData(1, selection) # vtk 6+ extract_selection.Update() ugrid = extract_selection.GetOutput() eids = None if self.is_eids: cells = ugrid.GetCellData() if cells is not None: ids = cells.GetArray('Ids') if ids is not None: cell_ids = vtk_to_numpy(ids) assert len(cell_ids) == len(np.unique(cell_ids)) eids = self.parent.get_element_ids(self.name, cell_ids) nids = None if self.is_nids: ugrid_points, nids = self.get_inside_point_ids( ugrid, ugrid_flipped) ugrid = ugrid_points actor = self.parent.create_highlighted_actor( ugrid, representation=self.representation) self.actor = actor if self.callback is not None: self.callback(eids, nids, self.name) self.area_pick_button.setChecked(False) # TODO: it would be nice if you could do a rotation without # destroying the highlighted actor self.cleanup_observer = self.parent.setup_mouse_buttons( mode='default', left_button_down_cleanup=self.cleanup_callback)
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() resolution = 10 sphere = vtk.vtkSphereSource() sphere.SetCenter(0.75, 0, 0) sphere.SetThetaResolution(resolution) sphere.SetPhiResolution(resolution) sphere.Update() # Add ids to the points and cells of the sphere cellIdFilter = vtk.vtkIdFilter() cellIdFilter.SetInputConnection(sphere.GetOutputPort()) cellIdFilter.SetCellIds(True) cellIdFilter.SetPointIds(False) cellIdFilter.SetIdsArrayName("CellIds") cellIdFilter.Update() pointIdFilter = vtk.vtkIdFilter() pointIdFilter.SetInputConnection(cellIdFilter.GetOutputPort()) pointIdFilter.SetCellIds(False) pointIdFilter.SetPointIds(True) pointIdFilter.SetIdsArrayName("PointIds") pointIdFilter.Update() sphereWithIds = pointIdFilter.GetOutput() cube = vtk.vtkCubeSource() cube.Update() implicitCube = vtk.vtkBox() implicitCube.SetBounds(cube.GetOutput().GetBounds()) clipper = vtk.vtkClipPolyData() clipper.SetClipFunction(implicitCube) clipper.SetInput(sphereWithIds) clipper.InsideOutOn() clipper.Update() # Create a mapper and actor for clipped sphere clippedMapper = vtk.vtkPolyDataMapper() clippedMapper.SetInputConnection(clipper.GetOutputPort()) clippedMapper.ScalarVisibilityOff() clippedActor = vtk.vtkActor() clippedActor.SetMapper(clippedMapper) clippedActor.GetProperty().SetRepresentationToWireframe() # Create a mapper and actor for the cube cubeMapper = vtk.vtkPolyDataMapper() cubeMapper.SetInputConnection(cube.GetOutputPort()) cubeActor = vtk.vtkActor() cubeActor.SetMapper(cubeMapper) cubeActor.GetProperty().SetRepresentationToWireframe() cubeActor.GetProperty().SetOpacity(0.5) #create renderers and add actors of plane and cube self.ren.AddActor(clippedActor) self.ren.AddActor(cubeActor) self.ren.SetBackground(0.2, 0.3, 0.4) self.ren.ResetCamera() self._initialized = False
# private: # vtkPolyData Points # vtkActor SelectedActor # vtkDataSetMapper Selected_mapper # vtkStandardNewMacro(InteractorStyle) # def main(): if 1: point_source = vtk.vtkPointSource() point_source.SetNumberOfPoints(20) point_source.Update() id_filter = vtk.vtkIdFilter() id_filter.SetInputConnection(point_source.GetOutputPort()) id_filter.SetIdsArrayName("OriginalIds") id_filter.Update() surface_filter = vtk.vtkDataSetSurfaceFilter() surface_filter.SetInputConnection(id_filter.GetOutputPort()) surface_filter.Update() poly_input = surface_filter.GetOutput() # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInputConnection(poly_input.GetProducerPort())