def AssignLabelToRoots(root_canal, surf, label_name): label_array = surf.GetPointData().GetArray(label_name) RC_BoundingBox = root_canal.GetPoints().GetBounds() x = (RC_BoundingBox[0] + RC_BoundingBox[1]) / 2 y = (RC_BoundingBox[2] + RC_BoundingBox[3]) / 2 z = (RC_BoundingBox[4] + RC_BoundingBox[5]) / 2 surfID = vtk.vtkOctreePointLocator() surfID.SetDataSet(surf) surfID.BuildLocator() labelID = vtk.vtkIntArray() labelID.SetNumberOfComponents(1) labelID.SetNumberOfTuples(root_canal.GetNumberOfPoints()) labelID.SetName(label_name) labelID.Fill(-1) for pid in range(labelID.GetNumberOfTuples()): ID = surfID.FindClosestPoint(x, y, z, vtk.reference(20)) labelID.SetTuple(pid, (int(label_array.GetTuple(ID)[0]), )) root_canal.GetPointData().AddArray(labelID) return root_canal
def CentreLinePointLocator(self): """A vtkAbstractPointLocator subclass that allows fast searching for points on the centreline. """ clPtLoc = vtk.vtkOctreePointLocator() clPtLoc.SetDataSet(self.CentreLinePolyData) clPtLoc.BuildLocator() return clPtLoc
def __point_locator__(VTU01, VTU02): #locator = vtk.vtkPointLocator() locator = vtk.vtkOctreePointLocator() locator.SetDataSet(VTU01) locator.BuildLocator() n_Pts = VTU02.GetNumberOfPoints() Pts = VTU02.GetPointData() Cell_idx = [] for i in range(n_Pts): Pt = VTU02.GetPoint(i) PtId = locator.FindClosestPoint(Pt) Cell_idx.append(PtId) print "[point_locator]", len(Cell_idx) return Cell_idx
def TagImageFromPolyDataSurface(surface, image, tag_value=1): # instantiate point locator in order to map data back to the image octree = vtk.vtkOctreePointLocator() octree.SetDataSet(image) octree.BuildLocator() # convert bounds of polydata to image extents extents = ConvertBoundsToExtents(image, surface.GetBounds()) # extract a smaller in order to iterate over less points voi = vtk.vtkExtractVOI() voi.SetInputData(image) voi.SetVOI(extents) voi.Update() # find which points are within the surface (polydata) provided selection = vtk.vtkSelectEnclosedPoints() selection.SetSurfaceData(surface) selection.SetInputData(voi.GetOutput()) selection.Update() # make sure to keep the same nomenclature for the vtk array to # not overwrite the current data scalars = ns.vtk_to_numpy(image.GetPointData().GetScalars()) scalars_name = image.GetPointData().GetScalars().GetName() # iterate and find which points are within the volume for i in range(selection.GetOutput().GetNumberOfPoints()): if selection.IsInside(i) == True: iD = octree.FindClosestPoint(selection.GetOutput().GetPoint(i)) scalars[iD] = tag_value # convert the numpy array to a vtk array s = ns.numpy_to_vtk(scalars) s.SetName(scalars_name) # update the image with the tagged values for the mapped volume image.GetPointData().SetScalars(s)
def _Execute(self): """Private method that actually does the reading. Called by the VTK API. """ input = self.GetUnstructuredGridInput() # Load the snapshot data snap = HemeLbSnapshot(self.FileName) # Get the centres as these should match the snapshot positions centers = vtk.vtkCellCenters() centers.SetInput(input) centers.Update() # Use this to find the cell ID for each point. locator = vtk.vtkOctreePointLocator() locator.SetDataSet(centers.GetOutput()) locator.BuildLocator() # Should be fine enough locator.SetTolerance(0.1 * snap.voxel_size) # Copy the structure to output. grid = self.GetUnstructuredGridOutput() grid.ShallowCopy(input) nCells = len(snap) # Basic sanity check that we probably have matching geometry and # snapshot. if grid.GetNumberOfCells() != nCells: raise ValueError('Geometry ({}) and snapshot ({}) have different ' 'cell counts'.format(grid.GetNumberOfCells(), len(snap))) # Velocity field velocity = vtk.vtkDoubleArray() velocity.SetNumberOfComponents(3) velocity.SetNumberOfTuples(nCells) velocity.SetName('velocity') # Pressure pressure = vtk.vtkDoubleArray() pressure.SetNumberOfComponents(1) pressure.SetNumberOfTuples(nCells) pressure.SetName('pressure') # Stress stress = vtk.vtkDoubleArray() stress.SetNumberOfComponents(1) stress.SetNumberOfTuples(nCells) stress.SetName('stress') # The hard work bit. for pt in snap: # Get cell in geometry corresponding to the point cellId = locator.FindClosestPoint(pt.position) if cellId == -1: raise ValueError("Can't find cell for point at " + str(pt.position)) # Copy the data into the VTK structure velocity.SetTuple3(cellId, *pt.velocity) pressure.SetTuple1(cellId, pt.pressure) stress.SetTuple1(cellId, pt.stress) continue # Add the arrays to the output grid.GetCellData().AddArray(velocity) grid.GetCellData().AddArray(pressure) grid.GetCellData().AddArray(stress) return
def _CreateSkeleton(self): """Create the structure of the output vtkUnstructuredGrid and a map from the index of a point in the extraction file to the corresponding cellId in the skeleton. This method should only be called if the extraction object this instance is working on has changed since the last time this method was called. """ input = self.GetUnstructuredGridInput() # Get the centres as these should match the extracted property positions centers = vtk.vtkCellCenters() if vtk.vtkVersion().GetVTKMajorVersion() <= 5: centers.SetInput(input) else: centers.SetInputData(input) #centers.SetInput(input) centers.Update() # Use this to find the cell ID for each point. locator = vtk.vtkOctreePointLocator() locator.SetDataSet(centers.GetOutput()) locator.BuildLocator() # Should be fine enough locator.SetTolerance(0.1 * self.Extracted.voxelSizeMetres) # Get the first set of extracted data from the file. We don't care # which as we only want to use the positions. extracted_positions = self.Extracted.GetByIndex(0).position nExtractedPoints = len(extracted_positions) # Make a list of the cell ids to keep; i.e. the cell in the input # (whole geometry) with ID cellIdsGmy[i] contains the point given by # extracted_positions[i] gmyCellIdsByInput = vtk.vtkIdTypeArray() gmyCellIdsByInput.SetNumberOfComponents(1) gmyCellIdsByInput.SetNumberOfTuples(nExtractedPoints) gmyCellIdsByInputNp = numpy_support.vtk_to_numpy(gmyCellIdsByInput) for i, point in enumerate(extracted_positions): # Get cell in geometry corresponding to the point cellId = locator.FindClosestPoint(point) if cellId == -1: raise ValueError("Can't find cell for point at " + str(point)) gmyCellIdsByInputNp[i] = cellId # Make an object to select only the cell ids we want selector = vtk.vtkSelectionNode() selector.SetFieldType(CELL) selector.SetContentType(INDICES) selector.SetSelectionList(gmyCellIdsByInput) # Make an object to hold the selector selectors = vtk.vtkSelection() selectors.AddNode(selector) # Perform the selection extractSelection = vtk.vtkExtractSelectedIds() if vtk.vtkVersion().GetVTKMajorVersion() <= 5: extractSelection.SetInput(0, input) extractSelection.SetInput(1, selectors) else: extractSelection.SetInputData(0, input) extractSelection.SetInputData(1, selectors) extractSelection.Update() gmyCellIdsByOutput = extractSelection.GetOutput().GetCellData( ).GetArray('vtkOriginalCellIds') gmyCellIdsByOutputNp = numpy_support.vtk_to_numpy(gmyCellIdsByOutput) self.OutputCellIdsByInputIndex = MatchCorresponding( gmyCellIdsByOutputNp, gmyCellIdsByInputNp) # Create the skeleton data object and only copy in the structure. self.Skeleton = vtk.vtkUnstructuredGrid() self.Skeleton.CopyStructure(extractSelection.GetOutput()) return
def OctreeVisualize(fileName): ''' fileName:文件路径 该函数显示PLY模型的空间八叉树划分 ''' # PLY模型的读取 colors = vtk.vtkNamedColors() plyReader = vtk.vtkPLYReader() plyReader.SetFileName(fileName) plyMapper = vtk.vtkPolyDataMapper() plyMapper.SetInputConnection(plyReader.GetOutputPort()) plyReader.Update() plyActor = vtk.vtkActor() plyActor.SetMapper(plyMapper) plyActor.GetProperty().SetInterpolationToFlat() plyActor.GetProperty().SetRepresentationToPoints() plyActor.GetProperty().SetColor(colors.GetColor3d("Yellow")) # 构建八叉树 octree = vtk.vtkOctreePointLocator() octree.SetMaximumPointsPerRegion(5) octree.SetDataSet(plyReader.GetOutput()) octree.BuildLocator() polydata = vtk.vtkPolyData() octree.GenerateRepresentation(0, polydata) octreeMapper = vtk.vtkPolyDataMapper() octreeMapper.SetInputData(polydata) octreeActor = vtk.vtkActor() octreeActor.SetMapper(octreeMapper) octreeActor.GetProperty().SetInterpolationToFlat() octreeActor.GetProperty().SetRepresentationToWireframe() octreeActor.GetProperty().SetColor(colors.GetColor3d("SpringGreen")) # 渲染器和窗口 renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) # 交互器 renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # 将模型加入场景中 renderer.AddActor(plyActor) renderer.AddActor(octreeActor) renderer.SetBackground(colors.GetColor3d("MidnightBlue")) # 渲染一副图像(光照和相机自动创建) renderWindow.SetWindowName("OctreeVisualize") renderWindow.SetSize(600, 600) renderWindow.Render() # 创建设定八叉树划分细度的滑动条 sliderRep = vtk.vtkSliderRepresentation2D() sliderRep.SetMinimumValue(0) sliderRep.SetMaximumValue(octree.GetLevel()) sliderRep.SetValue(0) sliderRep.SetTitleText("Level") sliderRep.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() sliderRep.GetPoint1Coordinate().SetValue(.2, .2) sliderRep.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() sliderRep.GetPoint2Coordinate().SetValue(.8, .2) sliderRep.SetSliderLength(0.075) sliderRep.SetSliderWidth(0.05) sliderRep.SetEndCapLength(0.05) sliderRep.GetTitleProperty().SetColor(colors.GetColor3d("Beige")) sliderRep.GetCapProperty().SetColor(colors.GetColor3d("MistyRose")) sliderRep.GetSliderProperty().SetColor(colors.GetColor3d("LightBlue")) sliderRep.GetSelectedProperty().SetColor(colors.GetColor3d("Violet")) sliderWidget = vtk.vtkSliderWidget() sliderWidget.SetInteractor(renderWindowInteractor) sliderWidget.SetRepresentation(sliderRep) sliderWidget.SetAnimationModeToAnimate() sliderWidget.EnabledOn() # 给滑动条添加观察者 callback = SliderObserver(octree, polydata, renderer) callback.Octree = octree callback.PolyData = polydata callback.Renderer = renderer sliderWidget.AddObserver('InteractionEvent', callback) renderWindowInteractor.Initialize() renderWindow.Render() renderWindowInteractor.Start()
def _CreateSkeleton(self): """Create the structure of the output vtkUnstructuredGrid and a map from the index of a point in the extraction file to the corresponding cellId in the skeleton. This method should only be called if the extraction object this instance is working on has changed since the last time this method was called. """ input = self.GetUnstructuredGridInput() # Get the centres as these should match the extracted property positions centers = vtk.vtkCellCenters() if vtk.vtkVersion().GetVTKMajorVersion() <= 5: centers.SetInput( input ); else: centers.SetInputData( input ); #centers.SetInput(input) centers.Update() # Use this to find the cell ID for each point. locator = vtk.vtkOctreePointLocator() locator.SetDataSet(centers.GetOutput()) locator.BuildLocator() # Should be fine enough locator.SetTolerance(0.1 * self.Extracted.voxelSizeMetres) # Get the first set of extracted data from the file. We don't care # which as we only want to use the positions. extracted_positions = self.Extracted.GetByIndex(0).position nExtractedPoints = len(extracted_positions) # Make a list of the cell ids to keep; i.e. the cell in the input # (whole geometry) with ID cellIdsGmy[i] contains the point given by # extracted_positions[i] gmyCellIdsByInput = vtk.vtkIdTypeArray() gmyCellIdsByInput.SetNumberOfComponents(1) gmyCellIdsByInput.SetNumberOfTuples(nExtractedPoints) gmyCellIdsByInputNp = numpy_support.vtk_to_numpy(gmyCellIdsByInput) for i, point in enumerate(extracted_positions): # Get cell in geometry corresponding to the point cellId = locator.FindClosestPoint(point) if cellId == -1: raise ValueError("Can't find cell for point at " + str(point)) gmyCellIdsByInputNp[i] = cellId # Make an object to select only the cell ids we want selector = vtk.vtkSelectionNode() selector.SetFieldType(CELL) selector.SetContentType(INDICES) selector.SetSelectionList(gmyCellIdsByInput) # Make an object to hold the selector selectors = vtk.vtkSelection() selectors.AddNode(selector) # Perform the selection extractSelection = vtk.vtkExtractSelectedIds() if vtk.vtkVersion().GetVTKMajorVersion() <= 5: extractSelection.SetInput(0, input) extractSelection.SetInput(1, selectors) else: extractSelection.SetInputData(0, input) extractSelection.SetInputData(1, selectors) extractSelection.Update() gmyCellIdsByOutput = extractSelection.GetOutput().GetCellData().GetArray('vtkOriginalCellIds') gmyCellIdsByOutputNp = numpy_support.vtk_to_numpy(gmyCellIdsByOutput) self.OutputCellIdsByInputIndex = MatchCorresponding(gmyCellIdsByOutputNp,gmyCellIdsByInputNp) # Create the skeleton data object and only copy in the structure. self.Skeleton = vtk.vtkUnstructuredGrid() self.Skeleton.CopyStructure(extractSelection.GetOutput()) return