def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') # feature edges are used to find any holes in the surface. fedges = vtk.vtkFeatureEdges() fedges.BoundaryEdgesOn() fedges.FeatureEdgesOff() fedges.ManifoldEdgesOff() fedges.SetInputData(self.Surface) fedges.Update() ofedges = fedges.GetOutput() # if numEdges is not 0, then there are holes which need to be capped numEdges = ofedges.GetNumberOfPoints() if numEdges != 0: tempcapper = vmtksurfacecapper.vmtkSurfaceCapper() tempcapper.Surface = self.Surface tempcapper.Interactive = 0 tempcapper.Execute() networkSurface = tempcapper.Surface else: networkSurface = self.Surface # randomly select one cell to delete so that there is an opening for # vmtkNetworkExtraction to use. numCells = self.Surface.GetNumberOfCells() cellToDelete = random.randrange(0, numCells-1) networkSurface.BuildLinks() networkSurface.DeleteCell(cellToDelete) networkSurface.RemoveDeletedCells() # extract the network of approximated centerlines net = vmtknetworkextraction.vmtkNetworkExtraction() net.Surface = networkSurface net.AdvancementRatio = 1.001 net.Execute() network = net.Network convert = vmtkcenterlinestonumpy.vmtkCenterlinesToNumpy() convert.Centerlines = network convert.LogOn = False convert.Execute() ad = convert.ArrayDict cellDataTopology = ad['CellData']['Topology'] # the network topology identifies an the input segment with the "0" id. # since we artificially created this segment, we don't want to use the # ends of the segment as source/target points of the centerline calculation nodeIndexToIgnore = np.where(cellDataTopology[:,0] == 0)[0][0] keepCellConnectivityList = [] pointIdxToKeep = np.array([]) # we remove the cell, points, and point data which are associated with the # segment we want to ignore for loopIdx, cellConnectivityList in enumerate(ad['CellData']['CellPointIds']): if loopIdx == nodeIndexToIgnore: removeCellStartIdx = cellConnectivityList[0] removeCellEndIdx = cellConnectivityList[-1] removeCellLength = cellConnectivityList.size if (removeCellEndIdx + 1) - removeCellStartIdx != removeCellLength: raise(ValueError) continue else: rescaledCellConnectivity = np.subtract(cellConnectivityList, removeCellLength, where=cellConnectivityList >= removeCellLength) keepCellConnectivityList.append(rescaledCellConnectivity) pointIdxToKeep = np.concatenate((pointIdxToKeep, cellConnectivityList)).astype(np.int) newPoints = ad['Points'][pointIdxToKeep] newRadius = ad['PointData']['Radius'][pointIdxToKeep] # precompute the delaunay tessellation for the whole surface. tessalation = vmtkdelaunayvoronoi.vmtkDelaunayVoronoi() tessalation.Surface = networkSurface tessalation.Execute() self.DelaunayTessellation = tessalation.DelaunayTessellation self.VoronoiDiagram = tessalation.VoronoiDiagram self.PoleIds = tessalation.PoleIds # vtk objects cannot be serialized in python. Instead of converting the inputs to numpy arrays and having # to reconstruct the vtk object each time the loop executes (a slow process), we can just pass in the # memory address of the data objects as a string, and use the vtk python bindings to create a python name # referring to the data residing at that memory address. This works because joblib executes each loop # iteration in a fork of the original process, providing access to the original memory space. # However, the process does not work for return arguments, since the original process will not have access to # the memory space of the fork. To return results we use the vmtkCenterlinesToNumpy converter. networkSurfaceMemoryAddress = networkSurface.__this__ delaunayMemoryAddress = tessalation.DelaunayTessellation.__this__ voronoiMemoryAddress = tessalation.VoronoiDiagram.__this__ poleIdsMemoryAddress = tessalation.PoleIds.__this__ # When using Joblib Under Windows, it is important to protect the main loop of code to avoid recursive spawning # of subprocesses. Since we cannot guarantee no code will run outside of “if __name__ == ‘__main__’” blocks # (only imports and definitions), we make Joblib execute each loop iteration serially on windows. # On unix-like os's (linux, Mac) we execute each loop iteration independently on as many cores as the system has. if (sys.platform == 'win32') or (sys.platform == 'win64') or (sys.platform == 'cygwin'): self.PrintLog('Centerlines extraction on windows computer will execute serially.') self.PrintLog('To speed up execution, please run vmtk on unix-like operating system') numParallelJobs = 1 else: numParallelJobs = -1 self.PrintLog('Computing Centerlines ...') # note about the verbose function: while Joblib can print a progress bar output (set verbose = 20), # it does not implement a callback function as of version 0.11, so we cannot report progress to the user # if we are redirecting standard out with the self.PrintLog method. outlist = Parallel(n_jobs=numParallelJobs, backend='multiprocessing', verbose=0)( delayed(_compute_centerlines_network)(networkSurfaceMemoryAddress, delaunayMemoryAddress, voronoiMemoryAddress, poleIdsMemoryAddress, cell, newPoints) for cell in keepCellConnectivityList) out = [] for item in outlist: npConvert = vmtknumpytocenterlines.vmtkNumpyToCenterlines() npConvert.ArrayDict = item npConvert.LogOn = 0 npConvert.Execute() out.append(npConvert.Centerlines) # Append each segment's polydata into a single polydata object centerlineAppender = vtk.vtkAppendPolyData() for data in out: centerlineAppender.AddInputData(data) centerlineAppender.Update() # clean and strip the output centerlines so that redundant points are merged and tracts are combined centerlineCleaner = vtk.vtkCleanPolyData() centerlineCleaner.SetInputData(centerlineAppender.GetOutput()) centerlineCleaner.Update() centerlineStripper = vtk.vtkStripper() centerlineStripper.SetInputData(centerlineCleaner.GetOutput()) centerlineStripper.JoinContiguousSegmentsOn() centerlineStripper.Update() self.Centerlines = centerlineStripper.GetOutput()
def __init__(self, target_mesh): self.point_locator = vtk.vtkPointLocator() self.point_locator.SetDataSet(target_mesh) self.point_locator.BuildLocator() self.cell_locator = vtk.vtkCellLocator() self.cell_locator.SetDataSet(target_mesh) self.cell_locator.SetTolerance(0.0001) self.cell_locator.BuildLocator() edge_filter = vtk.vtkFeatureEdges() edge_filter.SetInputData(target_mesh) edge_filter.BoundaryEdgesOn() edge_filter.FeatureEdgesOn() edge_filter.SetFeatureAngle(90) edge_filter.ManifoldEdgesOff() edge_filter.NonManifoldEdgesOff() edge_filter.Update() edge_points = edge_filter.GetOutput().GetPoints() self.edge_point_ids = [] for i in range(edge_points.GetNumberOfPoints()): point_id = self.point_locator.FindClosestPoint( edge_points.GetPoint(i)) self.edge_point_ids.append(point_id)
def GetEdgeMask(self, angle): """ Returns a mask of the points of a surface mesh that have a surface angle greater than angle Parameters ---------- angle : float Angle to consider an edge. """ featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInputData(self) featureEdges.FeatureEdgesOn() featureEdges.BoundaryEdgesOff() featureEdges.NonManifoldEdgesOff() featureEdges.ManifoldEdgesOff() featureEdges.SetFeatureAngle(angle) featureEdges.Update() edges = featureEdges.GetOutput() origID = vtkInterface.GetPointScalars(edges, 'vtkOriginalPointIds') return np.in1d(self.GetPointScalars('vtkOriginalPointIds'), origID, assume_unique=True)
def extractboundaryedge(polydata): edge = vtk.vtkFeatureEdges() edge.SetInputData(polydata) edge.FeatureEdgesOff() edge.NonManifoldEdgesOff() edge.Update() return edge.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkFeatureEdges(), 'Processing.', ('vtkPolyData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def vtk_extract_feature_edges(polydata, compute_feature_edges=False, compute_boundary_edges=True, compute_non_manifold_edges=False): """Wrapper for vtkFeatureedges. Extracts the edges of the cells that are open. Args: compute_non_manifold_edges (bool): Turn on/off the extraction of non-manifold edges. compute_boundary_edges (bool): Turn on/off the extraction of boundary edges. compute_feature_edges (bool): Turn on/off the extraction of feature edges. polydata (vtkPolyData): surface to extract the openings from. Returns: feature_edges (vtkPolyData): The boundary edges of the surface. """ feature_edges = vtk.vtkFeatureEdges() if compute_feature_edges: feature_edges.FeatureEdgesOn() else: feature_edges.FeatureEdgesOff() if compute_boundary_edges: feature_edges.BoundaryEdgesOn() else: feature_edges.BoundaryEdgesOff() if compute_non_manifold_edges: feature_edges.NonManifoldEdgesOn() else: feature_edges.NonManifoldEdgesOff() feature_edges.SetInputData(polydata) feature_edges.Update() return feature_edges.GetOutput()
def PlotBoundaries(mesh): """ Plots boundaries of a mesh """ featureEdges = vtk.vtkFeatureEdges() vtkInterface.SetVTKInput(featureEdges, mesh) featureEdges.FeatureEdgesOff() featureEdges.BoundaryEdgesOn() featureEdges.NonManifoldEdgesOn() featureEdges.ManifoldEdgesOff() edgeMapper = vtk.vtkPolyDataMapper(); edgeMapper.SetInputConnection(featureEdges.GetOutputPort()); edgeActor = vtk.vtkActor(); edgeActor.GetProperty().SetLineWidth(5); edgeActor.SetMapper(edgeMapper) mapper = vtk.vtkDataSetMapper() vtkInterface.SetVTKInput(mapper, mesh) # Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().LightingOff() # Render pobj = PlotClass() pobj.AddActor(actor) pobj.AddActor(edgeActor) pobj.Plot(); del pobj
def _SliceModel(self, plane): """cuts surface and returns polydata of the clipped surface and the clipped face""" cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetInputData(self.Surface) cutter.Update() FeatureEdges = vtk.vtkFeatureEdges() FeatureEdges.SetInputConnection(cutter.GetOutputPort()) FeatureEdges.BoundaryEdgesOn() FeatureEdges.FeatureEdgesOff() FeatureEdges.NonManifoldEdgesOff() FeatureEdges.ManifoldEdgesOff() FeatureEdges.Update() cutStrips = vtk.vtkStripper( ) # Forms loops (closed polylines) from cutter cutStrips.SetInputConnection(cutter.GetOutputPort()) cutStrips.Update() cutPoly = vtk.vtkPolyData( ) # This trick defines polygons as polyline loop cutPoly.SetPoints((cutStrips.GetOutput()).GetPoints()) cutPoly.SetPolys((cutStrips.GetOutput()).GetLines()) return cutter.GetOutput(), cutPoly
def __init__(self, args): self.Surface = None self.InputFile = args.surface self.OutputFile = args.file_out self.FeatureAngle = 50.0 #args.feature_angle self.NumberOfRegions = 0 self.RegionIdsArrayName = "RegionsId" self.boundaries = vtk.vtkFeatureEdges() self.NewScalars = vtk.vtkIntArray() self.RegionAreas = vtk.vtkDoubleArray() self.mesh = vtk.vtkPolyData() self.BoundaryLines = vtk.vtkPolyData() self.BoundaryPointArray = vtk.vtkIntArray() self.BoundaryCellArray = vtk.vtkIntArray() self.CheckCells = vtk.vtkIdList() self.CheckCells2 = vtk.vtkIdList() self.CheckCellsCareful = vtk.vtkIdList() self.CheckCellsCareful2 = vtk.vtkIdList() # dynamic alloated arrays self.checked = None self.checkedcarefully = None self.pointMapper = None #Feature edges options self.BoundaryEdges = 0 self.ManifoldEdges = 0 self.NonManifoldEdges = 0 self.FeatureEdges = 1 self.ExtractLargestregion = 0
def Edges(self, opacity=1): """Create edges of polytopes.""" domain = vtk.vtkGeometryFilter() domain.SetInput(self.vtkgrid[self.dim]) domain.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput(domain.GetOutput()) edges = vtk.vtkFeatureEdges() edges.SetInput(normals.GetOutput()) edges.ManifoldEdgesOff() edges.BoundaryEdgesOn() edges.NonManifoldEdgesOff() edges.FeatureEdgesOff() edges.SetFeatureAngle(1) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(edges.GetOutput()) # if self.mesh.topology().dim()==3: mapper.ScalarVisibilityOff() # else: # mapper.SetLookupTable(self.lut) # mapper.SetScalarRange(self.vmin, self.vmax) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) return actor
def PlotBoundaries(mesh): """ Plots boundaries of a mesh """ # Determine boundary edges featureEdges = vtk.vtkFeatureEdges() SetVTKInput(featureEdges, mesh) featureEdges.FeatureEdgesOff() featureEdges.BoundaryEdgesOn() featureEdges.NonManifoldEdgesOff() featureEdges.ManifoldEdgesOff() edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(featureEdges.GetOutputPort()) # Create edge actor edgeActor = vtk.vtkActor() edgeActor.GetProperty().SetLineWidth(5) edgeActor.SetMapper(edgeMapper) # Render plobj = PlotClass() plobj.AddMesh(mesh) plobj.AddActor(edgeActor) # plobj.AddLegend([ # ['Mesh', [1, 1, 1]], # ['Holes', [1, 0, 0]] # ]) plobj.Plot('Plotting Degenerates Features') del plobj
def vtk_read(path): reader = vtk.vtkOBJReader() reader.SetFileName(path) reader.Update() pdata = reader.GetOutput() # check if the stl file is closed featureEdge = vtk.vtkFeatureEdges() featureEdge.FeatureEdgesOff() featureEdge.BoundaryEdgesOn() featureEdge.NonManifoldEdgesOn() featureEdge.SetInputData(pdata) featureEdge.Update() # pass pdata through a triangle filter tr = vtk.vtkTriangleFilter() tr.SetInputData(pdata) tr.PassVertsOff() tr.PassLinesOff() tr.Update() # normals filter pnormal = vtk.vtkPolyDataNormals() pnormal.SetInputData(tr.GetOutput()) pnormal.AutoOrientNormalsOff() pnormal.ComputePointNormalsOn() pnormal.ComputeCellNormalsOff() pnormal.SplittingOff() pnormal.ConsistencyOn() pnormal.FlipNormalsOn() pnormal.Update() pdata = pnormal.GetOutput() # create a vtkSelectEnclosedPoints filter filter = vtk.vtkSelectEnclosedPoints() filter.SetSurfaceData(pdata) print(pdata.GetNumberOfPoints()) print(pdata.GetPointData().GetNumberOfTuples()) # print(pdata) obj_points = np.zeros([pdata.GetNumberOfPoints(), 3]) obj_normals = np.zeros([pdata.GetNumberOfPoints(), 3]) polydata = vtk.vtkPolyData() polydata.ShallowCopy(pdata) for i in range(pdata.GetNumberOfPoints()): obj_points[i, :] = pdata.GetPoint(i) obj_normals[i, :] = pdata.GetPointData().GetNormals().GetTuple(i) obj_polygons = numpy.zeros([pdata.GetNumberOfCells(), 3]).astype(np.int) for i in range(pdata.GetNumberOfCells()): cell = vtk.vtkIdList() pdata.GetCellPoints(i, cell) for j in range(3): obj_polygons[i, j] = cell.GetId(j) # print(cell.GetId(j) ) return (obj_points, obj_normals, obj_polygons)
def extractboundaryedge(surface, feature_edges=False): """Extract boundary edges of a surface mesh.""" edge = vtk.vtkFeatureEdges() edge.SetInput(surface) if not feature_edges: edge.FeatureEdgesOff() edge.Update() return edge.GetOutput()
def extractboundaryedge(polydata): """Extract boundary edges of a surface mesh.""" edge = vtk.vtkFeatureEdges() edge.SetInput(polydata) edge.FeatureEdgesOff() edge.NonManifoldEdgesOff() edge.Update() return edge.GetOutput()
def get_vtk_actors(self): if not self.enabled: return [] else: if self.solid_actor is None: mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(self.get_polydata()) self.solid_actor = vtk.vtkActor() self.solid_actor.SetMapper(mapper) # Make the edge actor if it doesn't already exist and is needed if self.parent.edges and self.edge_actor is None: if self.parent.status_callback is not None: self.parent.status_callback('Detecting mesh edges...') edge_finder = vtk.vtkFeatureEdges() edge_finder.SetInputData(self.get_polydata()) edge_finder.ManifoldEdgesOff() edge_finder.BoundaryEdgesOff() edge_finder.NonManifoldEdgesOff() edge_finder.SetFeatureAngle(20) edge_finder.ColoringOff() edge_finder.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(edge_finder.GetOutputPort()) self.edge_actor = vtk.vtkActor() self.edge_actor.SetMapper(mapper) self.edge_actor.GetProperty().SetLineWidth(self.linewidth) if self.parent.status_callback is not None: self.parent.status_callback(None) # Make sure the colour and lighing are set appropriately if self.parent.edges: self.solid_actor.GetProperty().SetColor((0, 0, 0)) self.edge_actor.GetProperty().SetColor(self.colour) else: self.solid_actor.GetProperty().SetColor(self.colour) if self.parent.flat_shading: self.solid_actor.GetProperty().LightingOff() if self.parent.edges: return [self.solid_actor, self.edge_actor] else: return [self.solid_actor]
def getEdges(polydata): featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInputData(polydata) featureEdges.BoundaryEdgesOn() featureEdges.FeatureEdgesOn() featureEdges.ManifoldEdgesOn() featureEdges.NonManifoldEdgesOn() featureEdges.Update() return featureEdges.GetOutput()
def n_open_edges(self): """Return the number of open edges on this mesh.""" alg = vtk.vtkFeatureEdges() alg.FeatureEdgesOff() alg.BoundaryEdgesOn() alg.NonManifoldEdgesOn() alg.SetInputDataObject(self) alg.Update() return alg.GetOutput().GetNumberOfCells()
def extractboundaryedge(polydata): edge = vtk.vtkFeatureEdges() if vtk.vtkVersion.GetVTKMajorVersion() > 5: edge.SetInputData(polydata) else: edge.SetInput(polydata) edge.FeatureEdgesOff() edge.NonManifoldEdgesOff() edge.Update() return edge.GetOutput()
def _extract_boundary_data(self, internalData): patchFeatureEdgesFilter = vtk.vtkFeatureEdges() patchFeatureEdgesFilter.FeatureEdgesOff() patchFeatureEdgesFilter.NonManifoldEdgesOff() patchFeatureEdgesFilter.ManifoldEdgesOff() patchFeatureEdgesFilter.SetInputData(internalData) patchFeatureEdgesFilter.Update() return patchFeatureEdgesFilter.GetOutput()
def PlotEdges(mesh, angle): featureEdges = vtk.vtkFeatureEdges() if vtk.vtkVersion().GetVTKMajorVersion() >5: featureEdges.SetInputData(mesh) else: featureEdges.SetInput(mesh) featureEdges.FeatureEdgesOn() featureEdges.BoundaryEdgesOff() featureEdges.NonManifoldEdgesOff() featureEdges.ManifoldEdgesOff() featureEdges.SetFeatureAngle(angle) edgeMapper = vtk.vtkPolyDataMapper(); edgeMapper.SetInputConnection(featureEdges.GetOutputPort()); edgeActor = vtk.vtkActor(); edgeActor.GetProperty().SetLineWidth(5); edgeActor.SetMapper(edgeMapper) mapper = vtk.vtkDataSetMapper() if vtk.vtkVersion().GetVTKMajorVersion() >5: mapper.SetInputData(mesh) else: mapper.SetInput(mesh) # Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().LightingOff() ############################### # Display ############################### # Render ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Allow user to interact istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) ren.AddActor(actor) ren.AddActor(edgeActor) iren.Initialize() renWin.Render() iren.Start()
def extractfeatureedges(surface, boundary_edges=True, feature_edges=False, feature_angle=30): """Extract feature edges of a surface mesh. Defaults to extracting boundary edges.""" edge = vtk.vtkFeatureEdges() edge.SetInput(surface) edge.BoundaryEdgesOn() if boundary_edges else edge.BoundaryEdgesOff() edge.FeatureEdgesOn() if feature_edges else edge.FeatureEdgesOff() edge.SetFeatureAngle(feature_angle) edge.Update() return edge.GetOutput()
def extractfeatureedges(surface, boundary_edges=True, feature_edges=False, feature_angle=30): """Extract feature edges of a surface mesh. Defaults to extracting boundary edges.""" edge = vtk.vtkFeatureEdges() edge.SetInputData(surface) edge.BoundaryEdgesOn() if boundary_edges else edge.BoundaryEdgesOff() edge.FeatureEdgesOn() if feature_edges else edge.FeatureEdgesOff() edge.SetFeatureAngle(feature_angle) edge.Update() return edge.GetOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: No Input Surface.') # Step 0: Check if the surface has any unfilled holes in it. if it does, cap them. fedges = vtk.vtkFeatureEdges() fedges.BoundaryEdgesOn() fedges.FeatureEdgesOff() fedges.ManifoldEdgesOff() fedges.SetInputData(self.Surface) fedges.Update() ofedges = fedges.GetOutput() # if the following is not == 0, then the surface contains unfilled holes. numEdges = ofedges.GetNumberOfPoints() if numEdges >= 1: self.PrintLog('Capping unclosed holes in surface.') tempcapper = vmtksurfacecapper.vmtkSurfaceCapper() tempcapper.Surface = self.Surface tempcapper.LogOn = 0 tempcapper.Interactive = 0 tempcapper.Execute() self.Surface = tempcapper.Surface # Step 1: Convert the input surface into an image mask of unsigned char type and spacing = PolyDataToImageDataSpacing # Where voxels lying inside the surface are set to 255 and voxels outside the image are set to value 0. # since we are creating a new image container from nothing, calculate the origin, extent, and dimensions for the # vtkImageDataObject from the surface parameters. self.PrintLog('Converting Surface to Image Mask') binaryImageFilter = vmtksurfacetobinaryimage.vmtkSurfaceToBinaryImage() binaryImageFilter.Surface = self.Surface binaryImageFilter.InsideValue = 255 binaryImageFilter.LogOn = 0 binaryImageFilter.OutsideValue = 0 binaryImageFilter.PolyDataToImageDataSpacing = self.PolyDataToImageDataSpacing binaryImageFilter.Execute() # Step 2: Feed into the vtkvmtkMedialCurveFilter # This takes the binary image and computes the average outward flux of the image. This is then # used to compute the skeleton image. It returns a binary image where values of 1 are skeleton points # and values of 0 are outside the skeleton. The execution speed of this algorithm is fairly sensetive to # the extent of the input image. self.PrintLog('Extracting Centerline Skeleton from Image Mask...') medialCurveFilter = vtkvmtk.vtkvmtkMedialCurveFilter() medialCurveFilter.SetInputData(binaryImageFilter.Image) medialCurveFilter.SetThreshold(self.Threshold) medialCurveFilter.SetSigma(self.Sigma) medialCurveFilter.Update() self.Image = medialCurveFilter.GetOutput()
def boundaries(actor, c='p', lw=5, legend=None): '''Build a copy of actor that shows the boundary lines of its surface.''' fe = vtk.vtkFeatureEdges() vu.setInput(fe, vu.polydata(actor)) fe.BoundaryEdgesOn() fe.FeatureEdgesOn() fe.ManifoldEdgesOn() fe.NonManifoldEdgesOn() fe.ColoringOff() fe.Update() bactor = vu.makeActor(fe.GetOutput(), c=c, alpha=1, legend=legend) bactor.GetProperty().SetLineWidth(lw) return bactor
def getSurfaceData(a_FileName, a_InputLegacyDataType = 'none'): #------------------ # Get geometry data #------------------ geoFilter = vtk.vtkGeometryFilter() geoFilter.SetInputData(a_Data) geoFilter.Update() #-------------------------- # Extract domain boundaries #-------------------------- featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInputConnection(geo_filter.GetOutputPort()) featureEdges.BoundaryEdgesOn() featureEdges.FeatureEdgesOff() featureEdges.Update() edgeData = featureEdges.GetOutput() numCells = edgeData.GetNumberOfCells() numNodes = edgeData.GetNumberOfPoints() #------------------------------------------------------------------- # Get connectivity data # # NOTE: Turning on ScalarConnectivity (not shown) will exclude holes # in the mesh #------------------------------------------------------------------- connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetInputConnection(featureEdges.GetOutputPort()) connectivity.Update() connectivityData = connectivity.GetOutput() #---------------------------------------------- # VTK List object for storing boundary node IDs #---------------------------------------------- nodeList = vtk.vtkIdList() connectivityArray = np.zeros((numCells, 2), dtype=np.int32, order='F') for cellID in range(numCells): connectivityData.GetCellPoints(cellID, nodeList) connectivityArray[cellID,0] = nodeList.GetId(0) connectivityArray[cellID,1] = nodeList.GetId(1) coordinatesArray = np.zeros((numNodes, 3), dtype=np.float64, order='F') for nodeID in range(numNodes): coordinatesArray[p,:] = connectivityData.GetPoint(p)[0], connectivityData.GetPoint(p)[1], \ connectivityData.GetPoint(p)[2] return coordinatesArray, connectivityArray
def PlotEdges(mesh, angle): featureEdges = vtk.vtkFeatureEdges() if vtk.vtkVersion().GetVTKMajorVersion() > 5: featureEdges.SetInputData(mesh) else: featureEdges.SetInput(mesh) featureEdges.FeatureEdgesOn() featureEdges.BoundaryEdgesOff() featureEdges.NonManifoldEdgesOff() featureEdges.ManifoldEdgesOff() featureEdges.SetFeatureAngle(angle) edgeMapper = vtk.vtkPolyDataMapper() edgeMapper.SetInputConnection(featureEdges.GetOutputPort()) edgeActor = vtk.vtkActor() edgeActor.GetProperty().SetLineWidth(5) edgeActor.SetMapper(edgeMapper) mapper = vtk.vtkDataSetMapper() if vtk.vtkVersion().GetVTKMajorVersion() > 5: mapper.SetInputData(mesh) else: mapper.SetInput(mesh) # Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().LightingOff() ############################### # Display ############################### # Render ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Allow user to interact istyle = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(istyle) ren.AddActor(actor) ren.AddActor(edgeActor) iren.Initialize() renWin.Render() iren.Start()
def extractBoundaryEdges(inputModel, outputModel, boundary=False, feature=False, nonManifold=False, manifold=False, featureAngle=20): """Extract edges of a model. """ boundaryEdges = vtk.vtkFeatureEdges() boundaryEdges.SetInputData(inputModel.GetPolyData()) boundaryEdges.ExtractAllEdgeTypesOff() boundaryEdges.SetBoundaryEdges(boundary) boundaryEdges.SetFeatureEdges(feature) if feature: boundaryEdges.SetFeatureAngle(featureAngle) boundaryEdges.SetNonManifoldEdges(nonManifold) boundaryEdges.SetManifoldEdges(manifold) boundaryEdges.Update() outputModel.SetAndObservePolyData(boundaryEdges.GetOutput())
def ExtractEdges(self, feature_angle=30, boundary_edges=True, non_manifold_edges=True, feature_edges=True, manifold_edges=True): """ Extracts edges from a surface. From vtk documentation, the edges are one of the following 1) boundary (used by one polygon) or a line cell 2) non-manifold (used by three or more polygons) 3) feature edges (edges used by two triangles and whose dihedral angle > feature_angle) 4) manifold edges (edges used by exactly two polygons). Parameters ---------- feature_angle : float, optional Defaults to 30 degrees. boundary_edges : bool, optional Defaults to True non_manifold_edges : bool, optional Defaults to True feature_edges : bool, optional Defaults to True manifold_edges : bool, optional Defaults to True Returns ------- edges : vtkInterface.vtkPolyData Extracted edges """ featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInputData(self) featureEdges.SetFeatureAngle(feature_angle) featureEdges.SetManifoldEdges(manifold_edges) featureEdges.SetNonManifoldEdges(non_manifold_edges) featureEdges.SetBoundaryEdges(non_manifold_edges) featureEdges.SetFeatureEdges(feature_edges) featureEdges.SetColoring(False) featureEdges.Update() return PolyData(featureEdges.GetOutput())
def PlotBoundaries(mesh, **args): """ Plots boundaries of a mesh """ featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInputData(mesh) featureEdges.FeatureEdgesOff() featureEdges.BoundaryEdgesOn() featureEdges.NonManifoldEdgesOn() featureEdges.ManifoldEdgesOff() featureEdges.Update() edges = vtkInterface.PolyData(featureEdges.GetOutput()) plobj = PlotClass() plobj.AddMesh(edges, 'r', style='wireframe') plobj.AddMesh(mesh) plobj.Plot()
def GetWholeConnectedRegions(poly, coord): # for each of the connected regions, make a (likely non-convex) # whole polygon, divided at the self intersections. # for small image, reduces by 4.975 # big image improves by 3.918 numCells = poly.GetNumberOfCells() #print "numcells before", numCells connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetInput(poly) connectivity.SetExtractionModeToAllRegions() connectivity.Update() numRegions = connectivity.GetNumberOfExtractedRegions() connectivity.SetExtractionModeToSpecifiedRegions() featureEdges = vtk.vtkFeatureEdges() featureEdges.BoundaryEdgesOn() numResult = 0 for r in range(numRegions): numResult += 1 connectivity.InitializeSpecifiedRegionList() connectivity.AddSpecifiedRegion(r) region = connectivity.GetOutput() region.Update() #print "region has ", region.GetNumberOfCells(), " cells" featureEdges.SetInput(region) edges = featureEdges.GetOutput() edges.Update() edges.BuildLinks(0) #print "edges has", edges.GetNumberOfCells(), " cells" numCells = edges.GetNumberOfCells() # for i in xrange(numCells): # print edges.GetCell(i).GetPoints().GetPoint(0), edges.GetCell(i).GetPoints().GetPoint(1) # edges not given in order, we need to traverse # first look for self intersections points = edges.GetPoints() selfIntersections = [] cellIds = vtk.vtkIdList() for p in range(points.GetNumberOfPoints()): edges.GetPointCells(p,cellIds) if cellIds.GetNumberOfIds() == 4: selfIntersections.append(p) numResult += 1 #print selfIntersections ## if not selfIntersections: ## selfIntersections.append(edges.GetCell(0).GetPointIds().GetId(0)) # for now just return number of cells in result return numResult
def GetWholeConnectedRegions(poly, coord): # for each of the connected regions, make a (likely non-convex) # whole polygon, divided at the self intersections. # for small image, reduces by 4.975 # big image improves by 3.918 numCells = poly.GetNumberOfCells() #print "numcells before", numCells connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetInput(poly) connectivity.SetExtractionModeToAllRegions() connectivity.Update() numRegions = connectivity.GetNumberOfExtractedRegions() connectivity.SetExtractionModeToSpecifiedRegions() featureEdges = vtk.vtkFeatureEdges() featureEdges.BoundaryEdgesOn() numResult = 0 for r in range(numRegions): numResult += 1 connectivity.InitializeSpecifiedRegionList() connectivity.AddSpecifiedRegion(r) region = connectivity.GetOutput() region.Update() #print "region has ", region.GetNumberOfCells(), " cells" featureEdges.SetInput(region) edges = featureEdges.GetOutput() edges.Update() edges.BuildLinks(0) #print "edges has", edges.GetNumberOfCells(), " cells" numCells = edges.GetNumberOfCells() # for i in xrange(numCells): # print edges.GetCell(i).GetPoints().GetPoint(0), edges.GetCell(i).GetPoints().GetPoint(1) # edges not given in order, we need to traverse # first look for self intersections points = edges.GetPoints() selfIntersections = [] cellIds = vtk.vtkIdList() for p in range(points.GetNumberOfPoints()): edges.GetPointCells(p, cellIds) if cellIds.GetNumberOfIds() == 4: selfIntersections.append(p) numResult += 1 #print selfIntersections ## if not selfIntersections: ## selfIntersections.append(edges.GetCell(0).GetPointIds().GetId(0)) # for now just return number of cells in result return numResult
def identify_caps(model): #print("========== identify_caps ==========") face_caps = [] face_ids = model.get_face_ids() for face_id in face_ids: #print("----- face {0:d} -----".format(face_id)) face_polydata = model.get_face_polydata(face_id=face_id) feature_edges = vtk.vtkFeatureEdges() feature_edges.SetInputData(face_polydata) feature_edges.BoundaryEdgesOn() feature_edges.ManifoldEdgesOff() feature_edges.NonManifoldEdgesOff() feature_edges.FeatureEdgesOff() feature_edges.ColoringOn() #feature_edges.SetFeatureAngle(self.params.angle); feature_edges.Update() boundary_edges = feature_edges.GetOutput() clean_filter = vtk.vtkCleanPolyData() boundary_edges_clean = clean_filter.SetInputData(boundary_edges) clean_filter.Update() cleaned_edges = clean_filter.GetOutput() conn_filter = vtk.vtkPolyDataConnectivityFilter() conn_filter.SetInputData(cleaned_edges) conn_filter.SetExtractionModeToSpecifiedRegions() boundary_edge_components = list() rid = 0 while True: conn_filter.AddSpecifiedRegion(rid) conn_filter.Update() component = vtk.vtkPolyData() component.DeepCopy(conn_filter.GetOutput()) if component.GetNumberOfCells() <= 0: break #print("{0:d}: Number of boundary lines: {1:d}".format(rid, component.GetNumberOfCells())) boundary_edge_components.append(component) conn_filter.DeleteSpecifiedRegion(rid) rid += 1 if rid == 1: face_caps.append(True) else: face_caps.append(False) print("Done.") return face_caps
def preprocess_mesh(mesh, num_patches=10): """ This function... :param mesh: :param num_patches: :return: """ # run patching for i in range(num_patches): mesh = patch(mesh) edges2 = vtk.vtkFeatureEdges() edges2.SetInputData(mesh) edges2.FeatureEdgesOff() edges2.NonManifoldEdgesOn() edges2.ManifoldEdgesOff() edges2.BoundaryEdgesOn() edges2.Update() edgesPd = edges2.GetOutput() print( "{0} cells and {1} points".format( edgesPd.GetNumberOfCells(), edgesPd.GetNumberOfPoints() ) ) toDelete = vtk.vtkFloatArray() toDelete.SetNumberOfComponents(1) toDelete.SetNumberOfValues(mesh.GetNumberOfPoints()) for i in range(mesh.GetNumberOfPoints()): toDelete.SetValue(i, 0) for i in range(edgesPd.GetNumberOfPoints()): edgePnt = edgesPd.GetPoint(i) meshVertId = mesh.FindPoint(edgePnt) toDelete.SetValue(meshVertId, 1) mesh.GetPointData().SetScalars(toDelete) clipper = vtk.vtkClipPolyData() clipper.SetValue(0.5) clipper.SetInputData(mesh) clipper.InsideOutOn() clipper.Update() return clipper.GetOutput()
def main(): fn = get_program_parameters() polyData = ReadPolyData(fn) featureEdges = vtk.vtkFeatureEdges() featureEdges.FeatureEdgesOff() featureEdges.BoundaryEdgesOn() featureEdges.NonManifoldEdgesOn() featureEdges.SetInputData(polyData) featureEdges.Update() numberOfOpenEdges = featureEdges.GetOutput().GetNumberOfCells() if numberOfOpenEdges > 0: print(fn, ': Surface is not closed') else: print(fn, ': Surface is closed')
def boundaries(actor, c='p', lw=5, legend=None): '''Build a copy of actor that shows the boundary lines of its surface. [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/tutorial.py) ''' fe = vtk.vtkFeatureEdges() fe.SetInputData(actor.polydata()) fe.BoundaryEdgesOn() fe.FeatureEdgesOn() fe.ManifoldEdgesOn() fe.NonManifoldEdgesOn() fe.ColoringOff() fe.Update() bactor = Actor(fe.GetOutput(), c=c, alpha=1, legend=legend) bactor.GetProperty().SetLineWidth(lw) return bactor
def featureEdgeView(self): if not self.featureEdge: feature_edge = vtk.vtkFeatureEdges() feature_edge.SetInputConnection(self.filter.GetOutputPort()) self.mapper.SetInputConnection(feature_edge.GetOutputPort()) self.featureEdge = True prop = self.actor.GetProperty() prop.SetColor(0, 0, 0) prop.SetLineWidth(2) prop.SetRepresentationToSurface() self.interRender.ReInitialize() else: self.mapper.SetInputConnection(self.filter.GetOutputPort()) self.mapper.SetScalarModeToUseCellFieldData() self.vtkWindow.interRender() self.featureEdge = False
def CloseSurface( shape, output ): """ Closes holes in a surface with a flat cover shape vtkPolyData: input shape output vtkPolyData: output shape Return nothing. """ fe = vtk.vtkFeatureEdges() fe.SetInputData( shape ) fe.BoundaryEdgesOn() fe.NonManifoldEdgesOff() fe.FeatureEdgesOff() fe.ManifoldEdgesOff() fe.Update() connect = vtk.vtkPolyDataConnectivityFilter() connect.SetInputData(fe.GetOutput()) connect.Update() ncontours = connect.GetNumberOfExtractedRegions() append = vtk.vtkAppendPolyData() append.AddInput(shape) for i in range(ncontours): connect.AddSpecifiedRegion(i) connect.SetExtractionModeToSpecifiedRegions() connect.Update() edges = connect.GetOutput() cover = vtk.vtkPolyData() GenerateHoleCover(edges, cover) append.AddInput(cover) connect.DeleteSpecifiedRegion(i) append.Update() cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(append.GetOutput()) cleaner.Update() output.DeepCopy(cleaner.GetOutput())
def patch(mesh): """ This function... :param mesh: :return: """ edges = vtk.vtkFeatureEdges() edges.SetInputData(mesh) edges.FeatureEdgesOff() edges.NonManifoldEdgesOn() edges.ManifoldEdgesOff() edges.BoundaryEdgesOn() edges.Update() print( "{0} cells and {1} points".format( edges.GetOutput().GetNumberOfCells(), edges.GetOutput().GetNumberOfPoints() ) ) if edges.GetOutput().GetNumberOfPoints() == 0: print("No defects") return mesh patchSkel = vtk.vtkStripper() patchSkel.SetInputData(edges.GetOutput()) patchSkel.Update() patchPoly = vtk.vtkPolyData() patchPoly.Initialize() patchPoly.SetPoints(patchSkel.GetOutput().GetPoints()) patchPoly.SetPolys(patchSkel.GetOutput().GetLines()) patchTri = vtk.vtkTriangleFilter() patchTri.SetInputData(patchPoly) patchTri.Update() meshAppend = vtk.vtkAppendPolyData() meshAppend.AddInputData(patchTri.GetOutput()) meshAppend.AddInputData(mesh) meshAppend.Update() poly = vtk.vtkCleanPolyData() poly.SetInputData(meshAppend.GetOutput()) poly.Update() return poly.GetOutput()
def conditionImp(self): featureEdges = vtk.vtkFeatureEdges(); featureEdges.FeatureEdgesOff(); featureEdges.BoundaryEdgesOn(); featureEdges.NonManifoldEdgesOn(); featureEdges.SetInputData(self.data); featureEdges.Update(); numberOfOpenEdges = featureEdges.GetOutput().GetNumberOfCells(); if numberOfOpenEdges > 0: if not self.failed: self.failed = True; return False; else: return False; else: self.failed = False; return True;
def makeBorderPD(ipw): # setup source ps = vtk.vtkPlaneSource() ps.SetOrigin(ipw.GetOrigin()) ps.SetPoint1(ipw.GetPoint1()) ps.SetPoint2(ipw.GetPoint2()) fe = vtk.vtkFeatureEdges() fe.SetInput(ps.GetOutput()) tubef = vtk.vtkTubeFilter() tubef.SetNumberOfSides(12) tubef.SetRadius(0.5) tubef.SetInput(fe.GetOutput()) return tubef.GetOutput()
def Domain(self, opacity=1, mesh=False): domain = vtk.vtkGeometryFilter() domain.SetInput(self.vtkgrid) domain.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput(domain.GetOutput()) # edges edges = vtk.vtkFeatureEdges() edges.SetInput(normals.GetOutput()) edges.ManifoldEdgesOff() if mesh: edges.ManifoldEdgesOn() edges.BoundaryEdgesOn() edges.NonManifoldEdgesOff() edges.FeatureEdgesOff() edges.SetFeatureAngle(1) # mapper for domain mapper = vtk.vtkPolyDataMapper() mapper.SetInput(normals.GetOutput()) mapper.SetLookupTable(self.lut) mapper.SetScalarRange(self.vmin, self.vmax) # actor for domain actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) # mapper for edges mapper = vtk.vtkPolyDataMapper() mapper.SetInput(edges.GetOutput()) if self.mesh.topology().dim() == 3: mapper.ScalarVisibilityOff() else: mapper.SetLookupTable(self.lut) mapper.SetScalarRange(self.vmin, self.vmax) # actor for domain actor2 = vtk.vtkActor() actor2.SetMapper(mapper) actor2.GetProperty().SetOpacity((1 + opacity) / 2) if mesh: actor2.GetProperty().SetOpacity(opacity) return [actor, actor2]
def _Execute(self, *args): input = self.GetPolyDataInput() # Gets any edges of the mesh edger = vtkFeatureEdges() edger.BoundaryEdgesOn() edger.FeatureEdgesOff() edger.NonManifoldEdgesOff() edger.ManifoldEdgesOff() edger.SetInputData(input) # Converts the edges to a polyline stripper = vtkStripper() stripper.SetInputConnection(edger.GetOutputPort()) stripper.Update() # Change the polylines into polygons boundaryPoly = vtkPolyData() boundaryPoly.SetPoints(stripper.GetOutput().GetPoints()) boundaryPoly.SetPolys(stripper.GetOutput().GetLines()) # Triangulate tri = vtkTriangleFilter() tri.SetInputData(boundaryPoly) tri.Update() # Join to the input merger = vtkAppendPolyData() merger.AddInputData(input) merger.AddInputData(tri.GetOutput()) # Clean up by merging duplicate points cleaner = vtkCleanPolyData() cleaner.SetInputConnection(merger.GetOutputPort()) cleaner.Update() # Set output output = self.GetPolyDataOutput() output.ShallowCopy(cleaner.GetOutput()) return
def boundaries_create(clean,arg_boundaries_color,arg_boundaries_width): boundariespolydata = vtk.vtkFeatureEdges() boundariespolydata.SetInputConnection(clean.GetOutputPort()) boundariespolydata.SetBoundaryEdges(1) boundariespolydata.SetFeatureEdges(0) boundariespolydata.SetNonManifoldEdges(0) boundariespolydata.SetColoring(1) boundariesmapper = vtk.vtkPolyDataMapper() boundariesmapper.SetInputConnection(boundariespolydata.GetOutputPort()) boundariesmapper.SetScalarVisibility(0) boundariesactor = vtk.vtkActor() boundariesactor.SetMapper(boundariesmapper) boundariesactor.GetProperty().SetLineWidth(arg_boundaries_width) boundariesactor.GetProperty().SetColor(arg_boundaries_color) boundariesactor.GetProperty().SetAmbient(1) boundariesactor.GetProperty().SetDiffuse(0) boundariesactor.PickableOff() return(boundariesactor,boundariespolydata)
input_file = 'spatial_data_%03d.d' % int(options.frame) #input_file = 'v6brivers.14_fort.74_%03d.vtu' % int(frame) #input_file = 'v6brivers.14_fort.74.pvd' #input_file = 'femar3_irene30_maxwvel.vtu' meshReader.SetFileName(input_file) meshReader.SetScalarsName("WindSpeed") meshReader.SetVectorsName("WindVelocity") #meshReader.SetPointArrayStatus("WindVelocity",1) ##meshReader.SetPointArrayStatus("MaximumWindSpeed",1) meshReader.Update() # create actor for unstructured grid outline #outlineMesh = vtk.vtkOutlineFilter() meshGeometryFilter = vtk.vtkGeometryFilter() meshGeometryFilter.SetInput(meshReader.GetOutput()) outlineMesh = vtk.vtkFeatureEdges() outlineMesh.SetInputConnection(meshGeometryFilter.GetOutputPort()) outlineMesh.BoundaryEdgesOn() outlineMeshMapper = vtk.vtkPolyDataMapper() outlineMeshMapper.SetInputConnection(outlineMesh.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMeshMapper) outlineActor.GetProperty().SetColor(1,1,1) # create a color scale (color lookup table) refLut = vtk.vtkLookupTable() lut = vtk.vtkLookupTable() refLut.SetNumberOfColors(256) lut.SetNumberOfColors(256) refLut.SetHueRange(0.0, 0.667) refLut.Build()
def renderthis(self,warunek): # open a window and create a renderer self.widget.GetRenderWindow().AddRenderer(self.ren) # open file openFileDialog = wx.FileDialog(self, "Open STL file", "", self.filename, "*.stl", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return self.filename = openFileDialog.GetPath() # render the data reader = vtk.vtkSTLReader() reader.SetFileName(self.filename) reader.Update() mesh = reader.GetOutput() # To take the polygonal data from the vtkConeSource and # create a rendering for the renderer. coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInput(reader.GetOutput()) # create an actor for our scene if self.isploted: coneActor=self.ren.GetActors().GetLastActor() self.ren.RemoveActor(coneActor) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) # Add actor self.ren.AddActor(coneActor) # print self.ren.GetActors().GetNumberOfItems() #addPoint(self.ren, pSource, color=[1.0,0.0,0.0]) #addPoint(self.ren, pTarget, color=[1.0,0.0,1.0]) addLine(self.ren, pp1, pp2) addLine(self.ren, pp3, pp4) addLine(self.ren, pp5, pp6) addLine(self.ren, pp7, pp8) addLine(self.ren, pp1, pp7) addLine(self.ren, pp3, pp5) addLine(self.ren, pp4, pp6) addLine(self.ren, pp2, pp8) addLine(self.ren, pp1, pp3) addLine(self.ren, pp7, pp5) addLine(self.ren, pp4, pp2) addLine(self.ren, pp6, pp8) if warunek==1: addEdges(self.ren) ##################################################################################### featureEdge=vtk.vtkFeatureEdges() featureEdge.FeatureEdgesOff() featureEdge.BoundaryEdgesOn() featureEdge.NonManifoldEdgesOn() featureEdge.SetInput(mesh) featureEdge.Update() openEdges = featureEdge.GetOutput().GetNumberOfCells() if openEdges != 0: print "the stl file is not closed" select = vtk.vtkSelectEnclosedPoints() select.SetSurface(mesh) inside_polydat = vtk.vtkPolyData() forcing_polydat = vtk.vtkPolyData() interpolation_polydat = vtk.vtkPolyData() inside_points = vtk.vtkPoints() forcing_points = vtk.vtkPoints() interpolation_points = vtk.vtkPoints() # for i in range(11): #IsInside(i-5,0.1,0.1,mesh) global licz global licz2 global licznik for j in range(1,lwY+1): for i in range(1,lwX+1): licz += 1 print (licz/float(stoProcent))*100.0 for k in range(1,lwZ+1): sprawdzenie = 0 siatkaX[1]=xmin+0.001 siatkaX[lwX]=xmax-0.001 siatkaY[1]=ymin+0.001 siatkaY[lwY]=ymax-0.001 siatkaZ[1]=zmin+0.001 siatkaZ[lwZ]=zmax-0.001 sprawdzenie = IsInsideCheck(siatkaX[i],siatkaY[j],siatkaZ[k],mesh) siatkaX[1]=xmin siatkaX[lwX]=xmax siatkaY[1]=ymin siatkaY[lwY]=ymax siatkaZ[1]=zmin siatkaZ[lwZ]=zmax mesh_point_inside = [siatkaX[i],siatkaY[j],siatkaZ[k]] #mesh_point_forcing = [siatkaX[i]+1.0,siatkaY[j],siatkaZ[k]] maska[licznik] = sprawdzenie licznik=licznik+1 if sprawdzenie == 1: inside_points.InsertNextPoint(mesh_point_inside) #forcing_points.InsertNextPoint(mesh_point_forcing) licznik=0 licznik_forcing=0 for j in range(0,lwY): for i in range(0,lwX): for k in range(0,lwZ): #print j,i,k maska3D[j][i][k]=maska[licznik] licznik=licznik+1 #print maska3D find_forcing_points(lwY,lwX,lwZ,maska3D,forcing_points,siatkaX,siatkaY,siatkaZ,boundary_points,mesh,intersection,maska3D_forcing,interpolation_points,fnix,fniy,fniz,fncx,fncy,fncz) for j in range(0,lwY): for i in range(0,lwX): for k in range(0,lwZ): if maska3D_forcing[j][i][k] > 0: licznik_forcing = licznik_forcing+maska3D_forcing[j][i][k] for i in range(0,licznik_forcing): print i,fnix[i],fniy[i],fniz[i],fncx[i],fncy[i],fncz[i] odczyt_STL(self.filename,normals,licznik_forcing,fnix,fniy,fniz,fncx,fncy,fncz) zp = [0,0,0] for i in range(0,licznik_forcing): if fncx[i]>0 and normals[i][0]<0: normals[i][0]=normals[i][0]*(-1.0) if fncx[i]<0 and normals[i][0]>0: normals[i][0]=normals[i][0]*(-1.0) if fncy[i]>0 and normals[i][1]<0: normals[i][1]=normals[i][1]*(-1.0) if fncy[i]<0 and normals[i][1]>0: normals[i][1]=normals[i][1]*(-1.0) if fncz[i]>0 and normals[i][2]<0: normals[i][2]=normals[i][2]*(-1.0) if fncz[i]<0 and normals[i][2]>0: normals[i][2]=normals[i][2]*(-1.0) for i in range(0,licznik_forcing): zp1 = [fncx[i],fncy[i],fncz[i]] zp2 = [normals[i][0]+fncx[i],normals[i][1]+fncy[i],normals[i][2]+fncz[i]] #normals[i][0]=normals[i][0]+fncx[i] #normals[i][1]=normals[i][1]+fncy[i] #normals[i][2]=normals[i][2]+fncz[i] addLine(self.ren, zp1, zp2) print i,normals[i],zp1,zp2 #print intersection #print "+++++++++++++++++++=" #print maska3D_forcing """ licznik=0 for j in range(0,lwY): for i in range(0,lwX-1): for k in range(0,lwZ): mesh_point_forcing = [siatkaX[i+1],siatkaY[j+1],siatkaZ[k+1]] if (maska3D[j][i][k] == 0) and (maska3D[j][i+1][k] == 1): forcing_points.InsertNextPoint(mesh_point_forcing) licznik=licznik+1 """ zapis = open('Maska.txt', 'w') for i in range(0,lwX*lwY*lwZ): zapis.write(str(maska[i])) zapis.write('\n') zapis.close() print "zapisano Maske" inside_polydat.SetPoints(inside_points) inside = vtk.vtkSphereSource() inside.SetRadius(0.02) inside.SetPhiResolution(8) inside.SetThetaResolution(8) ballGlyph = vtkGlyph3D() ballGlyph.SetColorModeToColorByScalar() ballGlyph.SetSourceConnection(inside.GetOutputPort()) ballGlyph.SetInput(inside_polydat) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(ballGlyph.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor([1.0,0.0,0.0]) self.ren.AddActor(actor) ###################################################################################### forcing_polydat.SetPoints(forcing_points) forcing = vtk.vtkSphereSource() #point.SetCenter(pS) forcing.SetRadius(0.02) forcing.SetPhiResolution(8) forcing.SetThetaResolution(8) forcingGlyph = vtkGlyph3D() forcingGlyph.SetColorModeToColorByScalar() forcingGlyph.SetSourceConnection(forcing.GetOutputPort()) forcingGlyph.SetInput(forcing_polydat) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(forcingGlyph.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor([0.0,1.0,0.0]) self.ren.AddActor(actor) ##################################################################################### """ interpolation_polydat.SetPoints(interpolation_points) interpolation = vtk.vtkSphereSource() #point.SetCenter(pS) interpolation.SetRadius(0.02) interpolation.SetPhiResolution(8) interpolation.SetThetaResolution(8) interpolationGlyph = vtkGlyph3D() interpolationGlyph.SetColorModeToColorByScalar() interpolationGlyph.SetSourceConnection(interpolation.GetOutputPort()) interpolationGlyph.SetInput(interpolation_polydat) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(interpolationGlyph.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor([0.0,0.0,1.0]) self.ren.AddActor(actor) """ ##################################################################################### obbTree = vtk.vtkOBBTree() obbTree.SetDataSet(mesh) obbTree.BuildLocator() pointsVTKintersection = vtk.vtkPoints() obbTree.IntersectWithLine(pSource, pTarget, pointsVTKintersection, None) pointsVTKIntersectionData = pointsVTKintersection.GetData() noPointsVTKIntersection = pointsVTKIntersectionData.GetNumberOfTuples() pointsIntersection = [] for idx in range(noPointsVTKIntersection): _tup = pointsVTKIntersectionData.GetTuple3(idx) pointsIntersection.append(_tup) print pointsIntersection if not self.isploted: axes = vtk.vtkAxesActor() self.marker = vtk.vtkOrientationMarkerWidget() self.marker.SetInteractor( self.widget._Iren ) self.marker.SetOrientationMarker( axes ) self.marker.SetViewport(0.75,0,1,0.25) self.marker.SetEnabled(1) self.ren.ResetCamera() self.ren.ResetCameraClippingRange() #cam = self.ren.GetActiveCamera() self.cam.Elevation(50) self.cam.Azimuth(40) #cam.SetPosition(0,0,1) #cam.SetFocalPoint(0,0,-50) self.isploted = True self.ren.Render()
clipper.SetValue(0) clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputConnection(clipper.GetOutputPort()) clipMapper.ScalarVisibilityOff() backProp = vtk.vtkProperty() backProp.SetDiffuseColor(GetRGBColor('tomato')) clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetColor(GetRGBColor('peacock')) clipActor.SetBackfaceProperty(backProp) # now extract feature edges boundaryEdges = vtk.vtkFeatureEdges() boundaryEdges.SetInputConnection(clipper.GetOutputPort()) boundaryEdges.BoundaryEdgesOn() boundaryEdges.FeatureEdgesOff() boundaryEdges.NonManifoldEdgesOff() boundaryClean = vtk.vtkCleanPolyData() boundaryClean.SetInputConnection(boundaryEdges.GetOutputPort()) boundaryStrips = vtk.vtkStripper() boundaryStrips.SetInputConnection(boundaryClean.GetOutputPort()) boundaryStrips.Update() boundaryPoly = vtk.vtkPolyData() boundaryPoly.SetPoints(boundaryStrips.GetOutput().GetPoints()) boundaryPoly.SetPolys(boundaryStrips.GetOutput().GetLines())
foldingNormals.SetInputData(folding) else: foldingNormals.SetInput(folding) foldingNormals.SplittingOff() foldingMapper.SetInputConnection(foldingNormals.GetOutputPort()) foldingMapper.SetScalarRange(0, 24) foldingMapper.SetLookupTable(lut) foldingMapper.SetScalarModeToUseCellData() foldingActor.SetMapper(foldingMapper) # foldingActor.GetProperty().EdgeVisibilityOn() # foldingActor.GetProperty().SetOpacity(0.7) ren.AddActor(foldingActor) kq_to_folding = [[a for a in folding_to_kq if folding_to_kq[a] == i] for i in range(surface.GetNumberOfPoints())] boundary_extractor = vtk.vtkFeatureEdges() boundary_extractor.FeatureEdgesOff() if vtk.vtkVersion.GetVTKMajorVersion() >= 6: boundary_extractor.SetInputData(folding) else: boundary_extractor.SetInput(folding) boundary_extractor.Update() boundary_scalars = vtk.vtkIntArray() for iEdge in range(boundary_extractor.GetOutput().GetNumberOfCells()): boundary_scalars.InsertNextValue(iEdge) boundary_extractor.GetOutput().GetCellData().SetScalars(boundary_scalars) show_boundary = True boundary = vtk.vtkPolyData() if show_boundary:
cutter = vtk.vtkCutter() cutter.SetCutFunction(p) cutter.SetInput(data) cutter.Update() out = cutter.GetOutput() # Save cut data to file # Comment this if you dont want the cut-plane data cfile = "cut" + str(int(ncut)) + ".vtp" w = vtk.vtkXMLPolyDataWriter() w.SetFileName(cfile) w.SetInput(out) w.Write() # Extract boundary, includes outer boundary bd = vtk.vtkFeatureEdges() bd.BoundaryEdgesOn() bd.ColoringOff() bd.FeatureEdgesOff() bd.ManifoldEdgesOff() bd.AddInput(out) bd.Update() shape = bd.GetOutput() if shape.GetNumberOfPoints() == 0: print "No points found, something wrong !!!" # Now extract only the shape not the outer boundary g = vtk.vtkGeometryFilter() g.ExtentClippingOn() g.SetExtent(xmin, xmax, ymin, ymax, zmin, zmax) g.SetInput(shape)
def testICPTransform(self): renWin = vtk.vtkRenderWindow() #iren = vtk.vtkRenderWindowInteractor() #iren.SetRenderWindow(renWin) # Create objects sscale = {2:[0.7, 0.7, 0.7], 3:[0.5, 0.5, 0.5]} scenter = {2:[-0.25, 0.25, 0.0], 3:[ 0.4, -0.3, 0.0]} scolors = {2:[0.2, 0.6, 0.1], 3:[0.1, 0.2, 0.6]} s = dict() # The super quadric sources for sidx in range(1, 4): s.update({sidx:vtk.vtkSuperquadricSource()}) s[sidx].ToroidalOff() s[sidx].SetThetaResolution(20) s[sidx].SetPhiResolution(20) s[sidx].SetPhiRoundness(0.7 + (sidx - 2) * 0.4) s[sidx].SetThetaRoundness(0.85 + (sidx - 1) * 0.4) if sidx in sscale: s[sidx].SetScale(sscale[sidx]) if sidx in scenter: s[sidx].SetCenter(scenter[sidx]) s[sidx].Update() ren = dict() # Renderers sm = dict() # Mappers for the super quadric source sa = dict() # Actors for the super quadric source fe = dict() # Feature edges fem = dict() # Feature edges mappers fea = dict() # Feature edges actors icp = dict() # Iterated closest point transforms # Create the renderers for ridx in range(1, 4): ren.update({ridx: vtk.vtkRenderer()}) ren[ridx].SetViewport((ridx - 1) / 3.0, 0.0, ridx / 3.0, 1.0) ren[ridx].SetBackground(0.7, 0.8, 1.0) cam = ren[ridx].GetActiveCamera() cam.SetPosition(1.7, 1.4, 1.7) renWin.AddRenderer(ren[ridx]) # renderer 1 has all 3 objects, render i has object 1 and i (i=2, 3) # add actors (corresponding to the objects) to each renderer # and ICP transforms from objects i or to 1. # object 1 has feature edges too. for sidx in range(1, 4): if ridx == 1 or sidx == 1 or ridx == sidx: sm.update({ridx:{sidx:vtk.vtkPolyDataMapper()}}) sm[ridx][sidx].SetInputConnection(s[sidx].GetOutputPort()) sa.update({ridx:{sidx:vtk.vtkActor()}}) sa[ridx][sidx].SetMapper(sm[ridx][sidx]) prop = sa[ridx][sidx].GetProperty() if sidx in scolors: prop.SetColor(scolors[sidx]) if sidx == 1: prop.SetOpacity(0.2) fe.update({ridx:{sidx:vtk.vtkFeatureEdges()}}) src = s[sidx] fe[ridx][sidx].SetInputConnection(src.GetOutputPort()) fe[ridx][sidx].BoundaryEdgesOn() fe[ridx][sidx].ColoringOff() fe[ridx][sidx].ManifoldEdgesOff() fem.update({ridx:{sidx:vtk.vtkPolyDataMapper()}}) fem[ridx][sidx].SetInputConnection(fe[ridx][sidx].GetOutputPort()) fem[ridx][sidx].SetResolveCoincidentTopologyToPolygonOffset() fea.update({ridx:{sidx:vtk.vtkActor()}}) fea[ridx][sidx].SetMapper(fem[ridx][sidx]) ren[ridx].AddActor(fea[ridx][sidx]) ren[ridx].AddActor(sa[ridx][sidx]) if ridx > 1 and ridx == sidx: icp.update({ridx:{sidx:vtk.vtkIterativeClosestPointTransform()}}) icp[ridx][sidx].SetSource(s[sidx].GetOutput()) icp[ridx][sidx].SetTarget(s[1].GetOutput()) icp[ridx][sidx].SetCheckMeanDistance(1) icp[ridx][sidx].SetMaximumMeanDistance(0.001) icp[ridx][sidx].SetMaximumNumberOfIterations(30) icp[ridx][sidx].SetMaximumNumberOfLandmarks(50) sa[ridx][sidx].SetUserTransform(icp[ridx][sidx]) icp[3][3].StartByMatchingCentroidsOn() renWin.SetSize(400, 100) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "TestICPTransform.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()