def ExtractLargest(self, inplace=False): """ Extract largest connected set in mesh. Can be used to reduce residues obtained when generating an isosurface. Works only if residues are not connected (share at least one point with) the main component of the image. Parameters ---------- inplace : bool, optional Updates mesh in-place while returning nothing. Returns ------- mesh : vtkInterface.PolyData Largest connected set in mesh """ connect = vtk.vtkConnectivityFilter() connect.SetExtractionModeToLargestRegion() connect.SetInputData(self) connect.Update() geofilter = vtk.vtkGeometryFilter() geofilter.SetInputData(connect.GetOutput()) geofilter.Update() if inplace: self.Overwrite(geofilter.GetOutput()) else: return PolyData(geofilter.GetOutput())
def getConnectedVerticesWithinRadius(model, seedPt, radius): connectedPts_list = vtk.vtkIdList() x, y, z = model.GetPoint(seedPt) sphere = vtk.vtkSphere() sphere.SetRadius(radius) sphere.SetCenter(x, y, z) clipper = vtk.vtkClipPolyData() clipper.SetClipFunction(sphere) clipper.SetInputData(model) clipper.GenerateClippedOutputOn() clipper.Update() # slice_writer = vtk.vtkXMLPolyDataWriter() # slice_writer.SetInputData(clipper.GetClippedOutput()) # slice_writer.SetFileName('Region_cut' + '.vtp') # slice_writer.Write() connect = vtk.vtkConnectivityFilter() connect.SetInputData(clipper.GetClippedOutput()) connect.SetExtractionModeToClosestPointRegion() connect.SetClosestPoint(x, y, z) connect.Update() region = connect.GetOutput() for ptID in xrange(0, region.GetNumberOfPoints()): xp, yp, zp = region.GetPoint(ptID) modelpt = model.FindPoint(xp, yp, zp) connectedPts_list.InsertUniqueId(modelpt) return connectedPts_list
def getPatch(self, inputModel, inputCurve): # Clip model with curve loop = vtk.vtkSelectPolyData() loop.SetLoop(inputCurve) loop.GenerateSelectionScalarsOn() loop.SetInputData(inputModel) loop.SetSelectionModeToLargestRegion() clip = vtk.vtkClipPolyData() clip.InsideOutOn() clip.SetInputConnection(loop.GetOutputPort()) clip.GenerateClippedOutputOn() clip.Update() extractLargestPart = False clippedOutput = clip.GetOutput( ) if extractLargestPart else clip.GetClippedOutput() connectivity = vtk.vtkConnectivityFilter() connectivity.SetInputData(clippedOutput) connectivity.Update() clippedOutput2 = connectivity.GetOutput() # Remove unused points cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(clippedOutput2) cleaner.Update() return cleaner.GetOutput()
def Execute(self): if self.Mesh == None: self.PrintError('Error: No input mesh.') barycenter = [0.0,0.0,0.0] if self.Method == 'closest' and self.ClosestPoint == None: n = self.ReferenceMesh.GetNumberOfPoints() for i in range(n): point = self.ReferenceMesh.GetPoint(i) barycenter[0] += point[0] barycenter[1] += point[1] barycenter[2] += point[2] barycenter[0] /= n barycenter[1] /= n barycenter[2] /= n connectivityFilter = vtk.vtkConnectivityFilter() connectivityFilter.SetInputData(self.Mesh) connectivityFilter.ColorRegionsOff() if self.Method == 'largest': connectivityFilter.SetExtractionModeToLargestRegion() elif self.Method == 'closest': connectivityFilter.SetExtractionModeToClosestPointRegion() if self.ClosestPoint: connectivityFilter.SetClosestPoint(self.ClosestPoint) else: connectivityFilter.SetClosestPoint(barycenter) connectivityFilter.Update() self.Mesh = connectivityFilter.GetOutput()
def get_external_surface(_mesh, external=True): _center = np.zeros(3) _bounds = np.zeros(6) _ray_start = np.zeros(3) cell_id = vtk.mutable(-1) xyz = np.zeros(3) pcoords = np.zeros(3) t = vtk.mutable(0) sub_id = vtk.mutable(0) if external: surf = 1.1 else: surf = -1.1 _mesh.GetOutput().GetCenter(_center) _mesh.GetOutput().GetPoints().GetBounds(_bounds) for j in range(3): _ray_start[j] = _bounds[2 * j + 1] * surf cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(_mesh.GetOutput()) cell_locator.BuildLocator() cell_locator.IntersectWithLine(_ray_start, _center, 0.0001, t, xyz, pcoords, sub_id, cell_id) print('ID of the cell on the outer surface: {}'.format(cell_id)) connectivity_filter = vtk.vtkConnectivityFilter() connectivity_filter.SetInputConnection(_mesh.GetOutputPort()) connectivity_filter.SetExtractionModeToCellSeededRegions() connectivity_filter.InitializeSeedList() connectivity_filter.AddSeed(cell_id) connectivity_filter.Update() return connectivity_filter
def get_external_surface(self): print('getting external surface') _center = np.zeros(3) _bounds = np.zeros(6) _ray_start = np.zeros(3) cell_id = vtk.mutable(-1) xyz = np.zeros(3) pcoords = np.zeros(3) t = vtk.mutable(0) sub_id = vtk.mutable(0) _surf = 1.1 self.mesh.GetOutput().GetCenter(_center) self.mesh.GetOutput().GetPoints().GetBounds(_bounds) for j in range(3): _ray_start[j] = _bounds[2 * j + 1] * _surf cell_locator = vtk.vtkCellLocator() cell_locator.SetDataSet(self.mesh.GetOutput()) cell_locator.BuildLocator() cell_locator.IntersectWithLine(_ray_start, _center, 0.0001, t, xyz, pcoords, sub_id, cell_id) connectivity_filter = vtk.vtkConnectivityFilter() connectivity_filter.SetInputConnection(self.mesh.GetOutputPort()) connectivity_filter.SetExtractionModeToCellSeededRegions() connectivity_filter.InitializeSeedList() connectivity_filter.AddSeed(cell_id) connectivity_filter.Update() self.mesh = connectivity_filter # UnstructuredGrid
def getContour(self,value=0.5,arrName='',largestRegion=False): if arrName == '': arrName = self.waterArray[self.solver] contour=vtk.vtkContourFilter() contour.SetValue(0,value) self.pointData.SetActiveScalars(arrName) #contour.SetInputArrayToProcess(1, 0,0, vtkDataObject::FIELD_ASSOCIATION_POINTS , arrName); #something like this may also work contour.SetInputConnection(self.outputPort) contour.Update() if largestRegion: conn=vtk.vtkConnectivityFilter() conn.SetInputConnection(contour.GetOutputPort()) conn.SetExtractionModeToLargestRegion() conn.Update() connOutput = conn.GetOutput() IDs = [] for iC in range(connOutput.GetNumberOfCells()): #it has to be so complicated, no polylines are given cell = connOutput.GetCell(iC) for i in [0,1]: ID = cell.GetPointId(i) if not ID in IDs: IDs.append(ID) points=[connOutput.GetPoint(i) for i in IDs] else: cOutput = contour.GetOutput() points=[cOutput.GetPoint(i) for i in range(cOutput.GetNumberOfPoints())] if not points: sys.exit('vtkextract.py: No contours found - wrong initialization of water fraction?') points = np.array(points) return points
def Execute(self): if self.Mesh == None: self.PrintError('Error: No input mesh.') barycenter = [0.0, 0.0, 0.0] if self.Method == 'closest' and self.ClosestPoint == None: n = self.ReferenceMesh.GetNumberOfPoints() for i in range(n): point = self.ReferenceMesh.GetPoint(i) barycenter[0] += point[0] barycenter[1] += point[1] barycenter[2] += point[2] barycenter[0] /= n barycenter[1] /= n barycenter[2] /= n connectivityFilter = vtk.vtkConnectivityFilter() connectivityFilter.SetInputData(self.Mesh) connectivityFilter.ColorRegionsOff() if self.Method == 'largest': connectivityFilter.SetExtractionModeToLargestRegion() elif self.Method == 'closest': connectivityFilter.SetExtractionModeToClosestPointRegion() if self.ClosestPoint: connectivityFilter.SetClosestPoint(self.ClosestPoint) else: connectivityFilter.SetClosestPoint(barycenter) connectivityFilter.Update() self.Mesh = connectivityFilter.GetOutput()
def getBoundaryNodes(mesh, radius, used_nodes, vprint): numPts = mesh.GetNumberOfPoints() boundary_nodes = vtk.vtkIdList() #First get the points within a sphere on the boundaries using the boundary points as seed points for ptID in xrange(0, numPts): if (mesh.GetPointData().GetArray('GlobalBoundaryPoints').GetValue(ptID) > 0): x0, y0, z0 = mesh.GetPoint(ptID) neighbrs = vtk.vtkExtractGeometry() sphere = vtk.vtkSphere() sphere.SetCenter(x0, y0, z0) sphere.SetRadius(float(radius)) neighbrs.SetImplicitFunction(sphere) neighbrs.ExtractInsideOn() neighbrs.ExtractBoundaryCellsOn() neighbrs.SetInputData(mesh) neighbrs.Update() neighbors = vtk.vtkConnectivityFilter() neighbors.SetInputData(neighbrs.GetOutput()) neighbors.SetExtractionModeToClosestPointRegion() neighbors.SetClosestPoint(x0, y0, z0) neighbors.Update() neighbors = neighbors.GetOutput() for neighborID in xrange(0, neighbors.GetNumberOfPoints()): meshID = mesh.FindPoint(neighbors.GetPoint(neighborID)) if (used_nodes.IsId(meshID) < 0): boundary_nodes.InsertNextId(meshID) used_nodes.InsertNextId(meshID) writeVTU(neighbors, 'test_extraction.vtu', vprint) return [boundary_nodes, used_nodes]
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkConnectivityFilter(), 'Processing.', ('vtkDataSet',), ('vtkUnstructuredGrid',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def main(): colors = vtk.vtkNamedColors() sphereSource1 = vtk.vtkSphereSource() sphereSource1.Update() delaunay1 = vtk.vtkDelaunay3D() delaunay1.SetInputConnection(sphereSource1.GetOutputPort()) delaunay1.Update() sphereSource2 = vtk.vtkSphereSource() sphereSource2.SetCenter(5, 0, 0) sphereSource2.Update() delaunay2 = vtk.vtkDelaunay3D() delaunay2.SetInputConnection(sphereSource2.GetOutputPort()) delaunay2.Update() appendFilter = vtk.vtkAppendFilter() appendFilter.AddInputConnection(delaunay1.GetOutputPort()) appendFilter.AddInputConnection(delaunay2.GetOutputPort()) appendFilter.Update() connectivityFilter = vtk.vtkConnectivityFilter() connectivityFilter.SetInputConnection(appendFilter.GetOutputPort()) connectivityFilter.SetExtractionModeToAllRegions() connectivityFilter.ColorRegionsOn() connectivityFilter.Update() # Visualize mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(connectivityFilter.GetOutputPort()) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) # renWindow = vtk.vtkRenderWindow() # renWindow.AddRenderer(renderer) # iren = vtk.vtkRenderWindowInteractor() # iren.SetRenderWindow(renWindow) # iren.Initialize() # iren.Start() renWindow = vtk.vtkRenderWindow() renWindow.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWindow) iren.Initialize() renWindow.Render() renWindow.SetWindowName('ConnectivityFilter') renderer.SetBackground(colors.GetColor3d('deep_ochre')) renderer.GetActiveCamera().Zoom(0.9) renWindow.Render() iren.Start()
def LabelToSurface(label_path, surface_path, lcc=False, smoothIterations=15,relaxationFactor=0.1): tqdm.write("Converting segmentation label to surface file: {}".format(label_path)) # binary path if platform == "linux" or platform == "linux2": bin_path = "/home/jacky/Projects/CFD_intraranial/cxx/label_to_mesh/build_linux/LabelToMesh" elif platform == "darwin": return elif platform == "win32": bin_path = "D:/projects/CFD_intracranial/cxx/label_to_mesh/build/Release/LabelToMesh.exe" # convert to binary file command = bin_path + " " + label_path + " " + surface_path + " 1 1" # print(command) os.system(command) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(surface_path) reader.Update() surface = reader.GetOutput() transform = vtk.vtkTransform() transform.Scale(-1,-1,1) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(surface) transformFilter.SetTransform(transform) transformFilter.Update() surface = transformFilter.GetOutput() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(surface) smoothFilter.SetNumberOfIterations(smoothIterations); smoothFilter.SetRelaxationFactor(relaxationFactor); smoothFilter.FeatureEdgeSmoothingOff(); smoothFilter.BoundarySmoothingOn(); smoothFilter.Update(); surface = smoothFilter.GetOutput() if lcc: connectedFilter = vtk.vtkConnectivityFilter() connectedFilter.SetInputData(surface) connectedFilter.Update() surface = connectedFilter.GetOutput() if pathlib.Path(surface_path).suffix == ".vtk": writer = vtk.vtkGenericDataObjectWriter() elif pathlib.Path(surface_path).suffix == ".vtp": writer = vtk.vtkXMLPolyDataWriter() elif pathlib.Path(surface_path).suffix == ".stl": writer = vtk.vtkSTLWriter() writer.SetFileName(surface_path) writer.SetInputData(surface) writer.Update() tqdm.write("Convert segmentation label to surface file complete: {}".format(label_path))
def Connectivity(vtkdata): # Labelize all the objects connectivityFilter = vtk.vtkConnectivityFilter() connectivityFilter.SetInputData(vtkdata) connectivityFilter.SetExtractionModeToAllRegions() connectivityFilter.ColorRegionsOn() connectivityFilter.Update() vtkdata = connectivityFilter.GetOutput() label_label = vtkdata.GetPointData().GetArray('RegionId') return vtkdata, label_label
def get_connected_regions(dataset): if isinstance(dataset, vtk.vtkPolyData): connectivityFilter = vtk.vtkPolyDataConnectivityFilter() elif isinstance(dataset, vtk.vtkUnstructuredGrid): connectivityFilter = vtk.vtkConnectivityFilter() connectivityFilter.SetInputData(dataset) connectivityFilter.SetExtractionModeToAllRegions() connectivityFilter.ColorRegionsOn() connectivityFilter.Update() return connectivityFilter.GetOutput()
def filter_largest_cc(trimesh): poly = trimesh_to_vtk(trimesh.vertices, trimesh.faces, trimesh.graph_edges) connf = vtk.vtkConnectivityFilter() connf.SetInputData(poly) connf.SetExtractionModeToLargestRegion() connf.Update() clean = vtk.vtkCleanPolyData() clean.SetInputConnection(connf.GetOutputPort()) clean.PointMergingOff() clean.Update() return vtk_poly_to_mesh_components(clean.GetOutput())
def marching_cubes(image_data, contours, connectivity=False, path=None): """ """ if isinstance(image_data, VTKImage): info = image_data.information() importer = vtk.vtkImageImport() importer.SetDataScalarType(info.datatype) importer.SetNumberOfScalarComponents(1) importer.SetDataExtent(info.extent) importer.SetWholeExtent(info.extent) importer.SetDataOrigin(info.origin) importer.SetDataSpacing(info.spacing) size = len(image_data.flat) * image_data.dtype.itemsize array = image_data.flatten('F') vtk_array = numpy_support.numpy_to_vtk(array, 1, info.datatype) importer.CopyImportVoidPointer(vtk_array.GetVoidPointer(0), size) importer.Update() image_data = importer.GetOutput() if isinstance(contours, (int, float)): contours = (contours, ) contour = vtk.vtkMarchingContourFilter() contour.SetInputData(image_data) for i, value in enumerate(contours): contour.SetValue(0, value) contour.Update() poly_data = contour.GetOutput() if connectivity: connectivity = vtk.vtkConnectivityFilter() connectivity.SetInputData(poly_data) connectivity.SetExtractionModeToLargestRegion() connectivity.Update() mapper = vtk.vtkGeometryFilter() mapper.SetInputData(connectivity.GetOutput()) mapper.Update() poly_data = mapper.GetOutput() if isinstance(path, str): writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(path) writer.SetInputData(poly_data) writer.Write() return poly_data
def test_add_sphere(self): platter = vtk.vtkAppendPolyData() for obj in self.list_sphere: platter.AddInputData(obj.GetOutputDataObject(0)) platter.Update() poly_data = platter.GetOutput() split = vtk.vtkConnectivityFilter() split.SetInputData(poly_data) split.SetExtractionModeToAllRegions() split.Update() n_output = split.GetNumberOfExtractedRegions() self.assertEqual(n_output, self.n_sphere)
def connectivity_all(inp): """ Color regions according to connectivity Args: inp: InputConnection Returns: con: connectivity object """ con = vtk.vtkConnectivityFilter() con.SetInputData(inp) con.SetExtractionModeToAllRegions() con.ColorRegionsOn() con.Update() assert con.GetNumberOfExtractedRegions() > 0, 'empty geometry' return con
def connectivity(inp, origin): """ If there are more than one unconnected geometries, extract the closest one Args: inp: InputConnection origin: region closest to this point will be extracted Returns: con: connectivity object """ con = vtk.vtkConnectivityFilter() con.SetInputData(inp.GetOutput()) con.SetExtractionModeToClosestPointRegion() con.SetClosestPoint(origin[0], origin[1], origin[2]) con.Update() return con
def main(): sphereSource1 = vtk.vtkSphereSource() sphereSource1.Update() delaunay1 = vtk.vtkDelaunay3D() delaunay1.SetInputConnection(sphereSource1.GetOutputPort()) delaunay1.Update() sphereSource2 = vtk.vtkSphereSource() sphereSource2.SetCenter(5, 0, 0) sphereSource2.Update() delaunay2 = vtk.vtkDelaunay3D() delaunay2.SetInputConnection(sphereSource2.GetOutputPort()) delaunay2.Update() appendFilter = vtk.vtkAppendFilter() appendFilter.AddInputConnection(delaunay1.GetOutputPort()) appendFilter.AddInputConnection(delaunay2.GetOutputPort()) appendFilter.Update() connectivityFilter = vtk.vtkConnectivityFilter() connectivityFilter.SetInputConnection(appendFilter.GetOutputPort()) connectivityFilter.SetExtractionModeToAllRegions() connectivityFilter.ColorRegionsOn() connectivityFilter.Update() # Visualize mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(connectivityFilter.GetOutputPort()) mapper.Update() actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) renWindow = vtk.vtkRenderWindow() renWindow.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWindow) iren.Initialize() iren.Start()
def LabelToSurface(label_path, surface_path, lcc=False): print("Converting segmentation label to surface file:", label_path) # binary path bin_path = "D:/Dr_Simon_Yu/CFD_intracranial/code/cxx/label_to_mesh/build/Release/LabelToMesh.exe" # convert to binary file command = bin_path + " " + label_path + " " + surface_path + " 1 1" # print(command) os.system(command) reader = vtk.vtkGenericDataObjectReader() reader.SetFileName(surface_path) reader.Update() surface = reader.GetOutput() transform = vtk.vtkTransform() transform.Scale(-1, -1, 1) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(surface) transformFilter.SetTransform(transform) transformFilter.Update() surface = transformFilter.GetOutput() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputData(surface) smoothFilter.SetNumberOfIterations(15) smoothFilter.SetRelaxationFactor(0.1) smoothFilter.FeatureEdgeSmoothingOff() smoothFilter.BoundarySmoothingOn() smoothFilter.Update() surface = smoothFilter.GetOutput() if lcc: connectedFilter = vtk.vtkConnectivityFilter() connectedFilter.SetInputData(surface) connectedFilter.Update() surface = connectedFilter.GetOutput() writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(surface_path) writer.SetInputData(surface) writer.Update()
def extractLargestRegion(actor, legend=None): '''Keep only the largest connected part of a mesh and discard all the smaller pieces. [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/largestregion.py) ''' conn = vtk.vtkConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.ScalarConnectivityOff() poly = actor.polydata(True) conn.SetInputData(poly) conn.Update() epoly = conn.GetOutput() if legend is True: legend = actor.legend eact = Actor(epoly, legend) pr = vtk.vtkProperty() pr.DeepCopy(actor.GetProperty()) eact.SetProperty(pr) return eact
def check_centerline_region(self): """ Check if centerline is one connected region """ con = vtk.vtkConnectivityFilter() con.SetInputData(self.centerline) con.SetExtractionModeToAllRegions() con.ColorRegionsOn() con.Update() n_region = con.GetNumberOfExtractedRegions() if n_region == 0: self.logger.error('Centerline is empty') raise RuntimeError('Centerline is empty') if n_region > 1: self.logger.error('Centerline consist of more than one region') raise RuntimeError('Centerline consist of more than one region') return True
def connectivity(dataset, largest=False): """Find and label connected bodies/volumes. This adds an ID array to the point and cell data to distinguish seperate connected bodies. This applies a ``vtkConnectivityFilter`` filter which extracts cells that share common points and/or meet other connectivity criterion. (Cells that share vertices and meet other connectivity criterion such as scalar range are known as a region.) Parameters ---------- largest : bool Extract the largest connected part of the mesh. """ alg = vtk.vtkConnectivityFilter() alg.SetInputData(dataset) if largest: alg.SetExtractionModeToLargestRegion() else: alg.SetExtractionModeToAllRegions() alg.SetColorRegions(True) alg.Update() return _get_output(alg)
def interior_slice(interior_pt, norm_vec, all_results_vtu): # Use the centerline point & its normal vector to slice the .vtu model to return the perpendicular slice # at the centerline point. vtu_data = read_vtu(all_results_vtu) cutPlane = vtk.vtkPlane() cutPlane.SetOrigin(interior_pt) cutPlane.SetNormal(norm_vec) cutter = vtk.vtkCutter() cutter.SetCutFunction(cutPlane) cutter.SetInputData(vtu_data) cutter.Update() # Use the connectivity filter to extract only regions connected to the interior point # This prevents slicing into other branches connect = vtk.vtkConnectivityFilter() connect.SetInputData(cutter.GetOutput()) connect.SetExtractionModeToClosestPointRegion() connect.SetClosestPoint(interior_pt[0], interior_pt[1], interior_pt[2]) connect.Update() vtu_slice = connect.GetOutput() return vtu_slice
def getContour(self, value=0.5, arrName='', largestRegion=False): if arrName == '': arrName = self.waterArray[self.solver] contour = vtk.vtkContourFilter() contour.SetValue(0, value) self.pointData.SetActiveScalars(arrName) #contour.SetInputArrayToProcess(1, 0,0, vtkDataObject::FIELD_ASSOCIATION_POINTS , arrName); #something like this may also work contour.SetInputConnection(self.outputPort) contour.Update() if largestRegion: conn = vtk.vtkConnectivityFilter() conn.SetInputConnection(contour.GetOutputPort()) conn.SetExtractionModeToLargestRegion() conn.Update() connOutput = conn.GetOutput() IDs = [] for iC in range(connOutput.GetNumberOfCells( )): #it has to be so complicated, no polylines are given cell = connOutput.GetCell(iC) for i in [0, 1]: ID = cell.GetPointId(i) if not ID in IDs: IDs.append(ID) points = [connOutput.GetPoint(i) for i in IDs] else: cOutput = contour.GetOutput() points = [ cOutput.GetPoint(i) for i in range(cOutput.GetNumberOfPoints()) ] if not points: sys.exit( 'vtkextract.py: No contours found - wrong initialization of water fraction?' ) points = np.array(points) return points
import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create reader and warp data with vectors reader = vtk.vtkDataSetReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/blow.vtk") reader.SetScalarsName("thickness9") reader.SetVectorsName("displacement9") castToUnstructuredGrid = vtk.vtkCastToConcrete() castToUnstructuredGrid.SetInputConnection(reader.GetOutputPort()) castToUnstructuredGrid.Update() warp = vtk.vtkWarpVector() warp.SetInputData(castToUnstructuredGrid.GetUnstructuredGridOutput()) # extract mold from mesh using connectivity connect = vtk.vtkConnectivityFilter() connect.SetInputConnection(warp.GetOutputPort()) connect.SetExtractionModeToSpecifiedRegions() connect.AddSpecifiedRegion(0) connect.AddSpecifiedRegion(1) moldMapper = vtk.vtkDataSetMapper() moldMapper.SetInputConnection(reader.GetOutputPort()) moldMapper.ScalarVisibilityOff() moldActor = vtk.vtkActor() moldActor.SetMapper(moldMapper) moldActor.GetProperty().SetColor(.2,.2,.2) moldActor.GetProperty().SetRepresentationToWireframe() # extract parison from mesh using connectivity connect2 = vtk.vtkConnectivityFilter() connect2.SetInputConnection(warp.GetOutputPort()) connect2.SetExtractionModeToSpecifiedRegions()
sphere.SetRadius(1) sphere.SetPhiResolution(100) sphere.SetThetaResolution(100) selectionPoints = vtk.vtkPoints() selectionPoints.InsertPoint(0, 0.07325, 0.8417, 0.5612) selectionPoints.InsertPoint(1, 0.07244, 0.6568, 0.7450) selectionPoints.InsertPoint(2, 0.1727, 0.4597, 0.8850) selectionPoints.InsertPoint(3, 0.3265, 0.6054, 0.7309) selectionPoints.InsertPoint(4, 0.5722, 0.5848, 0.5927) selectionPoints.InsertPoint(5, 0.4305, 0.8138, 0.4189) loop = vtk.vtkImplicitSelectionLoop() loop.SetLoop(selectionPoints) extract = vtk.vtkExtractGeometry() extract.SetInputConnection(sphere.GetOutputPort()) extract.SetImplicitFunction(loop) connect = vtk.vtkConnectivityFilter() connect.SetInputConnection(extract.GetOutputPort()) connect.SetExtractionModeToClosestPointRegion() connect.SetClosestPoint(selectionPoints.GetPoint(0)) clipMapper = vtk.vtkDataSetMapper() clipMapper.SetInputConnection(connect.GetOutputPort()) backProp = vtk.vtkProperty() backProp.SetDiffuseColor(tomato) clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetColor(peacock) clipActor.SetBackfaceProperty(backProp) # Create graphics stuff # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow()
import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Quadric definition quadric = vtk.vtkQuadric() quadric.SetCoefficients([.5,1,.2,0,.1,0,0,.2,0,0]) sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(30,30,30) sample.SetImplicitFunction(quadric) sample.Update() #sample Print sample.ComputeNormalsOff() # Extract cells that contains isosurface of interest conn = vtk.vtkConnectivityFilter() conn.SetInputConnection(sample.GetOutputPort()) conn.ScalarConnectivityOn() conn.SetScalarRange(0.6,0.6) conn.SetExtractionModeToCellSeededRegions() conn.AddSeed(105) # Create a surface contours = vtk.vtkContourFilter() contours.SetInputConnection(conn.GetOutputPort()) # contours SetInputConnection [sample GetOutputPort] contours.GenerateValues(5,0.0,1.2) contMapper = vtk.vtkDataSetMapper() # contMapper SetInputConnection [contours GetOutputPort] contMapper.SetInputConnection(conn.GetOutputPort()) contMapper.SetScalarRange(0.0,1.2) contActor = vtk.vtkActor()
def fillCaps(self): # read the .obj and center it # polydata = Helpers.centerPolyData(Helpers.getObjData(modelFn)) # TODO: centering seems to glitch the tetgen somewhy polydata = Helpers.getObjData(modelFn) size = Helpers.getBounds(polydata) print "Model sizes:" + str(size) fillHolesFilter = vtk.vtkFillHolesFilter() fillHolesFilter.SetInputData(polydata) fillHolesFilter.SetHoleSize( 1000.0 ) # TODO: hole size: compute using model size (some factor of it) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(fillHolesFilter.GetOutputPort()) normals.ConsistencyOn() normals.SplittingOff() normals.Update() normals.GetOutput().GetPointData().SetNormals( polydata.GetPointData().GetNormals()) numOriginalCells = polydata.GetNumberOfCells() numNewCells = normals.GetOutput().GetNumberOfCells() it = normals.GetOutput().NewCellIterator() numCells = 0 it.InitTraversal() # Iterate over the original cells while (not it.IsDoneWithTraversal()) and numCells < numOriginalCells: it.GoToNextCell() numCells += 1 holePolyData = vtk.vtkPolyData() holePolyData.Allocate(normals.GetOutput(), numNewCells - numOriginalCells) holePolyData.SetPoints(normals.GetOutput().GetPoints()) cell = vtk.vtkGenericCell() # The remaining cells are the new ones from the hole filler while not it.IsDoneWithTraversal(): it.GetCell(cell) holePolyData.InsertNextCell(it.GetCellType(), cell.GetPointIds()) it.GoToNextCell() connectivity = vtk.vtkConnectivityFilter() connectivity.SetInputData(holePolyData) connectivity.SetExtractionModeToAllRegions() connectivity.ColorRegionsOn() connectivity.Update() capRegions = connectivity.GetOutput() outPD = vtk.vtkPolyData() outPD.Allocate(normals.GetOutput(), numNewCells) outPD.SetPoints(capRegions.GetPoints()) numOfCaps = connectivity.GetNumberOfExtractedRegions() print "Found " + str(numOfCaps) + " holes." # create the cap polydatas capPDs = [] for i in range(0, numOfCaps): capPD = vtk.vtkPolyData() capPD.Allocate(normals.GetOutput(), numNewCells) capPD.SetPoints(capRegions.GetPoints()) capPDs.append(capPD) capScalars = capRegions.GetCellData().GetScalars() cell = vtk.vtkGenericCell() it = capRegions.NewCellIterator() i = 0 while not it.IsDoneWithTraversal(): it.GetCell(cell) # outPD.InsertNextCell(it.GetCellType(), cell.GetPointIds()) capIdx = capScalars.GetValue(i) capPDs[capIdx].InsertNextCell(it.GetCellType(), cell.GetPointIds()) it.GoToNextCell() i = i + 1 sortedCaps = [] for i in range(0, len(capPDs)): capPD = capPDs[i] cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputData(capPD) cleanFilter.Update() cleanedPD = cleanFilter.GetOutput() area = Helpers.getArea(cleanedPD) radius = math.sqrt(area / math.pi) sortedCaps.append([cleanedPD, area, radius]) capPDs[i] = cleanedPD sortedCaps = sorted(sortedCaps, key=lambda x: x[1], reverse=True) [lastPd, area, radius] = sortedCaps[len(capPDs) - 1] print "Recommended edge size: " + str(radius / 2) scalarsName = "ModelFaceID" Helpers.appendScalars(polydata, 1, scalarsName) # 1 for the walls appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputData(outPD) appendFilter.AddInputData(polydata) scalarIdx = 2 for [capPD, area, radius] in sortedCaps: # if radius < 0.1: # Helpers.appendScalars(capPD, 1, scalarsName) # append the face ID idx # else: # Helpers.appendScalars(capPD, scalarIdx, scalarsName) # append the face ID idx Helpers.appendScalars(capPD, scalarIdx, scalarsName) # append the face ID idx appendFilter.AddInputData(capPD) print "Cap radius: " + str(radius) scalarIdx += 1 appendFilter.Update() cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputConnection(appendFilter.GetOutputPort()) cleanFilter.Update() joinedPD = cleanFilter.GetOutput() # joinedPD.GetCellData().SetScalars(scalars) # Write as VTP Helpers.writeVTP(meshFn, joinedPD) return [ polydata, [[capPD, radius] for [capPD, area, radius] in sortedCaps] ]
def _makeSTL(self): local_dir = self._gray_dir surface_dir = self._vol_dir+'_surfaces'+self._path_dlm try: os.mkdir(surface_dir) except: pass files = fnmatch.filter(sorted(os.listdir(local_dir)),'*.tif') counter = re.search("[0-9]*\.tif", files[0]).group() prefix = self._path_dlm+string.replace(files[0],counter,'') counter = str(len(counter)-4) prefixImageName = local_dir + prefix ### Create the renderer, the render window, and the interactor. The renderer # The following reader is used to read a series of 2D slices (images) # that compose the volume. The slice dimensions are set, and the # pixel spacing. The data Endianness must also be specified. The reader v16=vtk.vtkTIFFReader() v16.SetFilePrefix(prefixImageName) v16.SetDataExtent(0,100,0,100,1,len(files)) v16.SetFilePattern("%s%0"+counter+"d.tif") v16.Update() im = v16.GetOutput() im.SetSpacing(self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]) v = vte.vtkImageExportToArray() v.SetInputData(im) n = np.float32(v.GetArray()) idx = np.argwhere(n) (ystart,xstart,zstart), (ystop,xstop,zstop) = idx.min(0),idx.max(0)+1 I,J,K = n.shape if ystart > 5: ystart -= 5 else: ystart = 0 if ystop < I-5: ystop += 5 else: ystop = I if xstart > 5: xstart -= 5 else: xstart = 0 if xstop < J-5: xstop += 5 else: xstop = J if zstart > 5: zstart -= 5 else: zstart = 0 if zstop < K-5: zstop += 5 else: zstop = K a = n[ystart:ystop,xstart:xstop,zstart:zstop] itk_img = sitk.GetImageFromArray(a) itk_img.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]]) print "\n" print "-------------------------------------------------------" print "-- Applying Patch Based Denoising - this can be slow --" print "-------------------------------------------------------" print "\n" pb = sitk.PatchBasedDenoisingImageFilter() pb.KernelBandwidthEstimationOn() pb.SetNoiseModel(3) #use a Poisson noise model since this is confocal pb.SetNoiseModelFidelityWeight(1) pb.SetNumberOfSamplePatches(20) pb.SetPatchRadius(4) pb.SetNumberOfIterations(10) fimg = pb.Execute(itk_img) b = sitk.GetArrayFromImage(fimg) intensity = b.max() #grad = sitk.GradientMagnitudeRecursiveGaussianImageFilter() #grad.SetSigma(0.05) gf = sitk.GradientMagnitudeImageFilter() gf.UseImageSpacingOn() grad = gf.Execute(fimg) edge = sitk.Cast(sitk.BoundedReciprocal( grad ),sitk.sitkFloat32) print "\n" print "-------------------------------------------------------" print "---- Thresholding to deterimine initial level sets ----" print "-------------------------------------------------------" print "\n" t = 0.5 seed = sitk.BinaryThreshold(fimg,t*intensity) #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius) seed = sitk.BinaryMorphologicalOpening(seed,2) seed = sitk.BinaryFillhole(seed!=0) #Get connected regions r = sitk.ConnectedComponent(seed) labels = sitk.GetArrayFromImage(r) ids = sorted(np.unique(labels)) N = len(ids) if N > 2: i = np.copy(N) while i == N and (t-self._tratio)>-1e-7: t -= 0.01 seed = sitk.BinaryThreshold(fimg,t*intensity) #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius) seed = sitk.BinaryMorphologicalOpening(seed,2) seed = sitk.BinaryFillhole(seed!=0) #Get connected regions r = sitk.ConnectedComponent(seed) labels = sitk.GetArrayFromImage(r) i = len(np.unique(labels)) if i > N: N = np.copy(i) t+=0.01 else: t = np.copy(self._tratio) seed = sitk.BinaryThreshold(fimg,t*intensity) #Opening (Erosion/Dilation) step to remove islands smaller than 2 voxels in radius) seed = sitk.BinaryMorphologicalOpening(seed,2) seed = sitk.BinaryFillhole(seed!=0) #Get connected regions r = sitk.ConnectedComponent(seed) labels = sitk.GetArrayFromImage(r) labels = np.unique(labels)[1:] ''' labels[labels==0] = -1 labels = sitk.GetImageFromArray(labels) labels.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]]) #myshow3d(labels,zslices=range(20)) #plt.show() ls = sitk.ScalarChanAndVeseDenseLevelSetImageFilter() ls.UseImageSpacingOn() ls.SetLambda2(1.5) #ls.SetCurvatureWeight(1.0) ls.SetAreaWeight(1.0) #ls.SetReinitializationSmoothingWeight(1.0) ls.SetNumberOfIterations(100) seg = ls.Execute(sitk.Cast(labels,sitk.sitkFloat32),sitk.Cast(fimg,sitk.sitkFloat32)) seg = sitk.Cast(seg,sitk.sitkUInt8) seg = sitk.BinaryMorphologicalOpening(seg,1) seg = sitk.BinaryFillhole(seg!=0) #Get connected regions #r = sitk.ConnectedComponent(seg) contours = sitk.BinaryContour(seg) myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2])) plt.show() ''' segmentation = sitk.Image(r.GetSize(),sitk.sitkUInt8) segmentation.SetSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]]) for l in labels: d = sitk.SignedMaurerDistanceMap(r==l,insideIsPositive=False,squaredDistance=True,useImageSpacing=True) #d = sitk.BinaryThreshold(d,-1000,0) #d = sitk.Cast(d,edge.GetPixelIDValue() )*-1+0.5 #d = sitk.Cast(d,edge.GetPixelIDValue() ) seg = sitk.GeodesicActiveContourLevelSetImageFilter() seg.SetPropagationScaling(1.0) seg.SetAdvectionScaling(1.0) seg.SetCurvatureScaling(0.5) seg.SetMaximumRMSError(0.01) levelset = seg.Execute(d,edge) levelset = sitk.BinaryThreshold(levelset,-1000,0) segmentation = sitk.Add(segmentation,levelset) print ("RMS Change for Cell %d: "% l,seg.GetRMSChange()) print ("Elapsed Iterations for Cell %d: "% l, seg.GetElapsedIterations()) ''' contours = sitk.BinaryContour(segmentation) myshow3d(sitk.LabelOverlay(sitk.Cast(fimg,sitk.sitkUInt8),contours),zslices=range(fimg.GetSize()[2])) plt.show() ''' n[ystart:ystop,xstart:xstop,zstart:zstop] = sitk.GetArrayFromImage(segmentation)*100 i = vti.vtkImageImportFromArray() i.SetDataSpacing([self._pixel_dim[0],self._pixel_dim[1],self._pixel_dim[2]]) i.SetDataExtent([0,100,0,100,1,len(files)]) i.SetArray(n) i.Update() thres=vtk.vtkImageThreshold() thres.SetInputData(i.GetOutput()) thres.ThresholdByLower(0) thres.ThresholdByUpper(101) iso=vtk.vtkImageMarchingCubes() iso.SetInputConnection(thres.GetOutputPort()) iso.SetValue(0,1) regions = vtk.vtkConnectivityFilter() regions.SetInputConnection(iso.GetOutputPort()) regions.SetExtractionModeToAllRegions() regions.ColorRegionsOn() regions.Update() N = regions.GetNumberOfExtractedRegions() for i in xrange(N): r = vtk.vtkConnectivityFilter() r.SetInputConnection(iso.GetOutputPort()) r.SetExtractionModeToSpecifiedRegions() r.AddSpecifiedRegion(i) g = vtk.vtkExtractUnstructuredGrid() g.SetInputConnection(r.GetOutputPort()) geo = vtk.vtkGeometryFilter() geo.SetInputConnection(g.GetOutputPort()) geo.Update() t = vtk.vtkTriangleFilter() t.SetInputConnection(geo.GetOutputPort()) t.Update() cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(t.GetOutputPort()) s = vtk.vtkSmoothPolyDataFilter() s.SetInputConnection(cleaner.GetOutputPort()) s.SetNumberOfIterations(50) dl = vtk.vtkDelaunay3D() dl.SetInputConnection(s.GetOutputPort()) dl.Update() self.cells.append(dl) for i in xrange(N): g = vtk.vtkGeometryFilter() g.SetInputConnection(self.cells[i].GetOutputPort()) t = vtk.vtkTriangleFilter() t.SetInputConnection(g.GetOutputPort()) #get the surface points of the cells and save to points attribute v = t.GetOutput() points = [] for j in xrange(v.GetNumberOfPoints()): p = [0,0,0] v.GetPoint(j,p) points.append(p) self.points.append(points) #get the volume of the cell vo = vtk.vtkMassProperties() vo.SetInputConnection(t.GetOutputPort()) self.volumes.append(vo.GetVolume()) stl = vtk.vtkSTLWriter() stl.SetInputConnection(t.GetOutputPort()) stl.SetFileName(surface_dir+'cell%02d.stl' % (i+self._counter)) stl.Write() if self._display: skinMapper = vtk.vtkDataSetMapper() skinMapper.SetInputConnection(regions.GetOutputPort()) skinMapper.SetScalarRange(regions.GetOutput().GetPointData().GetArray("RegionId").GetRange()) skinMapper.SetColorModeToMapScalars() #skinMapper.ScalarVisibilityOff() skinMapper.Update() skin = vtk.vtkActor() skin.SetMapper(skinMapper) #skin.GetProperty().SetColor(0,0,255) # An outline provides context around the data. # outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(v16.GetOutputPort()) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outlineData.GetOutputPort()) outline = vtk.vtkActor() #outline.SetMapper(mapOutline) #outline.GetProperty().SetColor(0,0,0) colorbar = vtk.vtkScalarBarActor() colorbar.SetLookupTable(skinMapper.GetLookupTable()) colorbar.SetTitle("Cells") colorbar.SetNumberOfLabels(N) # Create the renderer, the render window, and the interactor. The renderer # draws into the render window, the interactor enables mouse- and # keyboard-based interaction with the data within the render window. # aRenderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aRenderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # It is convenient to create an initial view of the data. The FocalPoint # and Position form a vector direction. Later on (ResetCamera() method) # this vector is used to position the camera to look at the data in # this direction. aCamera = vtk.vtkCamera() aCamera.SetViewUp (0, 0, -1) aCamera.SetPosition (0, 1, 0) aCamera.SetFocalPoint (0, 0, 0) aCamera.ComputeViewPlaneNormal() # Actors are added to the renderer. An initial camera view is created. # The Dolly() method moves the camera towards the FocalPoint, # thereby enlarging the image. aRenderer.AddActor(outline) aRenderer.AddActor(skin) aRenderer.AddActor(colorbar) aRenderer.SetActiveCamera(aCamera) aRenderer.ResetCamera () aCamera.Dolly(1.5) # Set a background color for the renderer and set the size of the # render window (expressed in pixels). aRenderer.SetBackground(0.0,0.0,0.0) renWin.SetSize(800, 600) # Note that when camera movement occurs (as it does in the Dolly() # method), the clipping planes often need adjusting. Clipping planes # consist of two planes: near and far along the view direction. The # near plane clips out objects in front of the plane the far plane # clips out objects behind the plane. This way only what is drawn # between the planes is actually rendered. aRenderer.ResetCameraClippingRange() im=vtk.vtkWindowToImageFilter() im.SetInput(renWin) iren.Initialize(); iren.Start(); #remove gray directory shutil.rmtree(local_dir)
def main(): def NumberOfTriangles(pd): """ Count the number of triangles. :param pd: vtkPolyData. :return: The number of triangles. """ cells = pd.GetPolys() numOfTriangles = 0 idList = vtk.vtkIdList() for i in range(0, cells.GetNumberOfCells()): cells.GetNextCell(idList) # If a cell has three points it is a triangle. if idList.GetNumberOfIds() == 3: numOfTriangles += 1 return numOfTriangles colors = vtk.vtkNamedColors() fileName = get_program_parameters() # Create the pipeline. reader = vtk.vtkMCubesReader() reader.SetFileName(fileName) reader.FlipNormalsOff() reader.Update() print("Before Decimation.") print("There are: ", NumberOfTriangles(reader.GetOutput()), "triangles") deci = vtk.vtkDecimatePro() deci.SetInputConnection(reader.GetOutputPort()) deci.SetTargetReduction(0.9) deci.SetAbsoluteError(0.0005) deci.MaximumIterations = 6 deci.SetFeatureAngle(30) deci.SetErrorIsAbsolute(1) deci.AccumulateErrorOn() # deci.SplittingOff() deci.Update() print("After Decimation.") print("There are: ", NumberOfTriangles(deci.GetOutput()), "triangles") connect = vtk.vtkConnectivityFilter() connect.SetInputConnection(deci.GetOutputPort()) connect.SetExtractionModeToLargestRegion() connect.Update() print("After Connectivity.") print("There are: ", NumberOfTriangles(connect.GetOutput()), "triangles") isoMapper = vtk.vtkDataSetMapper() isoMapper.SetInputConnection(connect.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(colors.GetColor3d("raw_sienna")) # Get an outline of the data set for context. outline = vtk.vtkOutlineFilter() outline.SetInputConnection(reader.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(colors.GetColor3d("Black")) # Create the Renderer, RenderWindow and RenderWindowInteractor. ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size. ren.AddActor(outlineActor) ren.AddActor(isoActor) ren.SetBackground(1, 1, 1) # renWin.SetSize(750, 750) renWin.SetSize(512, 512) ren.SetBackground(colors.GetColor3d("SlateGray")) # render the image cam = ren.GetActiveCamera() cam.SetFocalPoint(40.6018, 37.2813, 50.1953) cam.SetPosition(40.6018, -280.533, 47.0172) cam.ComputeViewPlaneNormal() cam.SetClippingRange(26.1073, 1305.36) cam.SetViewAngle(20.9219) cam.SetViewUp(0.0, 0.0, 1.0) iren.Initialize() renWin.Render() iren.Start()
def translesional_result(centerline_file, wall_file,vtk_file_list, output_dir,minPoint=(0,0,0), prox_dist=5, dist_dist=5): # read centerline centerlineReader = vtk.vtkXMLPolyDataReader() centerlineReader.SetFileName(centerline_file) centerlineReader.Update() centerline = centerlineReader.GetOutput() # read vessel wall wallReader = vtk.vtkSTLReader() wallReader.SetFileName(wall_file) wallReader.Update() # read vtk files vtk_files = [] centerlines = [] if not os.path.exists(output_dir): os.makedirs(output_dir) if not os.path.exists(os.path.join(output_dir,"centerlines")): os.makedirs(os.path.join(output_dir,"centerlines")) # average filter averageFilter = vtk.vtkTemporalStatistics() for file_name in vtk_file_list: reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(file_name) reader.Update() geomFilter = vtk.vtkGeometryFilter() geomFilter.SetInputData(reader.GetOutput()) geomFilter.Update() # scale up the CFD result transform = vtk.vtkTransform() transform.Scale(1000,1000,1000) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputData(geomFilter.GetOutput()) transformFilter.SetTransform(transform) transformFilter.Update() vtk_files.append(transformFilter.GetOutput()) interpolator = vtk.vtkPointInterpolator() interpolator.SetSourceData(transformFilter.GetOutput()) interpolator.SetInputData(centerline) interpolator.Update() # convert to desired unit # get the first element pressure try: first_point_pressure = interpolator.GetOutput().GetPointData().GetArray("p").GetValue(0) except: first_point_pressure = 120 converter = vtk.vtkArrayCalculator() converter.SetInputData(interpolator.GetOutput()) converter.AddScalarArrayName("p") converter.SetFunction("120 + (p - {}) * 921 * 0.0075".format(first_point_pressure)) # 921 = mu/nu = density of blood, 0.0075 converts from Pascal to mmHg, offset 120mmHg at ica converter.SetResultArrayName("p(mmHg)") converter.Update() converter2 = vtk.vtkArrayCalculator() converter2.SetInputData(converter.GetOutput()) converter2.AddVectorArrayName("wallShearStress") converter2.SetFunction("wallShearStress * 921") # 921 = mu/nu = density of blood, 0.0075 converts from Pascal to mmHg, http://aboutcfd.blogspot.com/2017/05/wallshearstress-in-openfoam.html converter2.SetResultArrayName("wallShearStress(Pa)") converter2.Update() # output the probe centerline centerline_output_path = os.path.join( os.path.dirname(centerline_file), output_dir, "centerlines", "centerline_probe_{}.vtp".format(os.path.split(file_name)[1].split("_")[1].split(".")[0]) ) centerlines.append(converter2.GetOutput()) averageFilter.SetInputData(converter2.GetOutput()) averageFilter.Update() centerline = averageFilter.GetOutput() # extract lesion section # get the abscissas of min radius point # Create kd tree kDTree = vtk.vtkKdTreePointLocator() kDTree.SetDataSet(centerline) kDTree.BuildLocator() minIdx = kDTree.FindClosestPoint(minPoint) minPoint_absc = centerline.GetPointData().GetArray("Abscissas_average").GetTuple(minIdx)[0] thresholdFilter = vtk.vtkThreshold() thresholdFilter.ThresholdBetween(minPoint_absc-prox_dist,minPoint_absc+dist_dist) thresholdFilter.SetInputData(centerline) thresholdFilter.SetAllScalars(0) # important !!! thresholdFilter.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,"Abscissas_average"); thresholdFilter.Update() # to vtkpolydata geometryFilter = vtk.vtkGeometryFilter() geometryFilter.SetInputData(thresholdFilter.GetOutput()) geometryFilter.Update() # get closest line connectFilter = vtk.vtkConnectivityFilter() connectFilter.SetExtractionModeToClosestPointRegion() connectFilter.SetClosestPoint(minPoint) connectFilter.SetInputData(geometryFilter.GetOutput()) connectFilter.Update() # compute result values abscissas = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("Abscissas_average")) abscissas_unique, index = np.unique(sorted(abscissas), axis=0, return_index=True) pressure = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("p(mmHg)_average")) pressure = [x for _, x in sorted(zip(abscissas,pressure))] pressure = [pressure[x] for x in index] pressure_gradient = np.diff(pressure)/np.diff(abscissas_unique) velocity = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("U_average")) velocity = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in velocity] velocity = [x for _, x in sorted(zip(abscissas,velocity))] velocity = [velocity[x] for x in index] velocity_gradient = np.diff(velocity)/np.diff(abscissas_unique) vorticity = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("vorticity_average")) vorticity = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in vorticity] vorticity = [x for _, x in sorted(zip(abscissas,vorticity))] vorticity = [vorticity[x] for x in index] vorticity_gradient = np.diff(vorticity)/np.diff(abscissas_unique) wss = vtk_to_numpy(thresholdFilter.GetOutput().GetPointData().GetArray("wallShearStress(Pa)_average")) wss = [math.sqrt(value[0]**2 + value[1]**2 +value[2]**2 ) for value in wss] wss = [wss[x] for x in index] wss = [x for _, x in sorted(zip(abscissas,wss))] wss_gradient = np.diff(wss)/np.diff(abscissas_unique) epsilon = 0.00001 p_ratio = np.mean(pressure[-4:-1])/(np.mean(pressure[0:3])+epsilon) u_ratio = np.mean(velocity[-4:-1])/(np.mean(velocity[0:3])+epsilon) w_ratio = np.mean(vorticity[-4:-1])/(np.mean(vorticity[0:3])+epsilon) wss_ratio = np.mean(wss[-4:-1])/(np.mean(wss[0:3])+epsilon) dp_ratio = np.mean(pressure_gradient[-4:-1])/(np.mean(pressure_gradient[0:3])+epsilon) du_ratio = np.mean(velocity_gradient[-4:-1])/(np.mean(velocity_gradient[0:3])+epsilon) dw_ratio = np.mean(vorticity_gradient[-4:-1])/(np.mean(vorticity_gradient[0:3])+epsilon) dwss_ratio = np.mean(wss_gradient[-4:-1])/(np.mean(wss_gradient[0:3])+epsilon) return_value = { 'translesion peak presssure(mmHg)': np.mean(heapq.nlargest(1, pressure)), 'translesion presssure ratio': p_ratio, 'translesion peak pressure gradient(mmHgmm^-1)': np.mean(heapq.nlargest(1, pressure_gradient)), 'translesion pressure gradient ratio': dp_ratio, 'translesion peak velocity(ms^-1)': np.mean(heapq.nlargest(1, velocity)), 'translesion velocity ratio': u_ratio, 'translesion velocity gradient ratio': du_ratio, 'translesion peak velocity gradient(ms^-1mm^-1)': np.mean(heapq.nlargest(1, velocity_gradient)), 'translesion peak vorticity(ms^-1)': np.mean(heapq.nlargest(1, vorticity)), 'translesion vorticity ratio': w_ratio, 'translesion vorticity gradient ratio': dw_ratio, 'translesion peak vorticity gradient(Pamm^-1)':np.mean(heapq.nlargest(1, vorticity_gradient)), 'translesion peak wss(Pa)': np.mean(heapq.nlargest(1, wss)), 'translesion peak wss gradient(Pamm^-1)': np.mean(heapq.nlargest(1, wss_gradient)), 'translesion wss ratio': wss_ratio, 'translesion wss gradient ratio': dwss_ratio, } return return_value
def vtkExtractOuterSurface(filename): reader = vtk.vtkNIFTIImageReader() reader.SetFileName(filename) reader.Update() image1 = reader.GetOutput() dim = image1.GetDimensions() print dim for x in [0, dim[0] - 1]: for y in [0, dim[1] - 1]: image1.SetScalarComponentFromFloat(x, y, dim[2] - 1, 0, 0.0) image1.SetScalarComponentFromFloat(x, y, dim[2] - 2, 0, 0.0) image1.SetScalarComponentFromFloat(x, y, dim[2] - 3, 0, 0.0) image1.SetScalarComponentFromFloat(x, y, dim[2] - 4, 0, 0.0) image1.SetScalarComponentFromFloat(x, y, 0, 0, 0.0) image1.SetScalarComponentFromFloat(x, y, 1, 0, 0.0) image1.SetScalarComponentFromFloat(x, y, 2, 0, 0.0) image1.SetScalarComponentFromFloat(x, y, 3, 0, 0.0) for y in [0, dim[1] - 1]: for z in [0, dim[2] - 1]: image1.SetScalarComponentFromFloat(dim[0] - 1, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(dim[0] - 2, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(dim[0] - 3, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(dim[0] - 4, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(dim[0] - 5, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(0, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(1, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(2, y, z, 0, 0.0) image1.SetScalarComponentFromFloat(3, y, z, 0, 0.0) for x in [0, dim[0] - 1]: for z in [0, dim[2] - 1]: image1.SetScalarComponentFromFloat(x, 0, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, 1, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, 2, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, 3, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, 4, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, 5, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, dim[1] - 1, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, dim[1] - 2, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, dim[1] - 3, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, dim[1] - 4, z, 0, 0.0) image1.SetScalarComponentFromFloat(x, dim[1] - 5, z, 0, 0.0) # threshold threshold = vtk.vtkImageThreshold() threshold.SetInputData(image1) threshold.ThresholdBetween(15, 1000) threshold.ReplaceInOn() threshold.SetInValue(200) threshold.ReplaceOutOn() threshold.SetOutValue(0) threshold.Update() image = threshold.GetOutput() # write to image writer = vtk.vtkNIFTIImageWriter() writer.SetFileName("C:/Users/QIN Shuo/Desktop/test.nii") writer.SetInputData(image) writer.Update() # marching here marching = vtk.vtkMarchingCubes() marching.SetInputData(image) marching.SetValue(0, 8) marching.Update() skin = marching.GetOutput() connector = vtk.vtkConnectivityFilter() connector.SetInputData(skin) connector.SetExtractionModeToLargestRegion() connector.Update() geo = vtk.vtkGeometryFilter() geo.SetInputData(connector.GetOutput()) geo.Update() area = geo.GetOutput() ## fill holes # filler = vtk.vtkFillHolesFilter() # filler.SetInputData(area) # filler.SetHoleSize(1E6) # filler.Update() # area = filler.GetOutput() # filter = vtk.vtkPolyDataConnectivityFilter() # filter.SetInputData(area) # filter.SetExtractionModeToSpecifiedRegions() # filter.AddSpecifiedRegion(0) # filter.Update() # area = filter.GetOutput() # visualization print "visualizing..." mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(area) # mapper.ScalarVisibilityOn() actor = vtk.vtkActor() actor.SetMapper(mapper) # actor.GetProperty().SetOpacity(0.7) renderer = vtk.vtkRenderer() renderer.AddActor(actor) window = vtk.vtkRenderWindow() window.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() window.SetInteractor(interactor) window.Render() interactor.Start()
def Bridge (x, z = 1.316666): app = vtk.vtkAppendPolyData() plane = vtk.vtkPlane() plane.SetOrigin(x, 0, 0) plane.SetNormal(1, 0, 0) cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetInputConnection(merg.GetOutputPort()) cf = vtk.vtkConnectivityFilter() cf.SetInputConnection(cutter.GetOutputPort()) cf.SetExtractionModeToAllRegions() cf.Update() regs = cf.GetNumberOfExtractedRegions() cf.SetExtractionModeToSpecifiedRegions() ms = [] for i in range(regs): cf.InitializeSpecifiedRegionList() cf.AddSpecifiedRegion(i) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(cf.GetOutputPort()) clean = vtk.vtkCleanPolyData() clean.SetInputConnection(gf.GetOutputPort()) clean.Update() pd = clean.GetOutput() ys = [] for j in range(pd.GetNumberOfPoints()): pt = pd.GetPoint(j) if pt[2] > z-1e-5: ys.append(pt[1]) if len(ys) > 1: ys.sort() m = ys[-1]+(ys[0]-ys[-1])/2 cyl = vtk.vtkCylinderSource() cyl.SetCenter(0, 0, m) cyl.SetResolution(12) cyl.SetRadius(.4) app.AddInputConnection(cyl.GetOutputPort()) ms.append(m) ov = 2 ex = extrude([(0, 0), (2, 0), (2, .75), (0, .75)], 0, ms[-1]-ms[0]+2*ov) tr = vtk.vtkTransform() tr.Translate(-1, -1.25, ms[0]-ov) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(tr) tp.SetInputConnection(ex.GetOutputPort()) app.AddInputConnection(tp.GetOutputPort()) tr2 = vtk.vtkTransform() tr2.Translate(x, 0, z+.5) tr2.RotateX(270) tp2 = vtk.vtkTransformPolyDataFilter() tp2.SetTransform(tr2) tp2.SetInputConnection(app.GetOutputPort()) return tp2
def splitDomainBetweenEndoAndEpi(domain, verbose=True): if (verbose): print '*** splitDomainBetweenEndoAndEpi ***' connectivity0 = vtk.vtkConnectivityFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): connectivity0.SetInputData(domain) else: connectivity0.SetInput(domain) connectivity0.SetExtractionModeToSpecifiedRegions() connectivity0.AddSpecifiedRegion(0) connectivity0.Update() ugrid0_temp = connectivity0.GetOutput() geom0 = vtk.vtkGeometryFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): geom0.SetInputData(ugrid0_temp) else: geom0.SetInput(ugrid0_temp) geom0.Update() pdata0_temp = geom0.GetOutput() tfilter0 = vtk.vtkTriangleFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): tfilter0.SetInputData(pdata0_temp) else: tfilter0.SetInput(pdata0_temp) tfilter0.Update() connectivity1 = vtk.vtkConnectivityFilter() connectivity1.SetExtractionModeToSpecifiedRegions() connectivity1.AddSpecifiedRegion(1) if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): connectivity1.SetInputData(domain) else: connectivity1.SetInput(domain) connectivity1.Update() ugrid1_temp = connectivity1.GetOutput() geom1 = vtk.vtkGeometryFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): geom1.SetInputData(ugrid1_temp) else: geom1.SetInput(ugrid1_temp) geom1.Update() pdata1_temp = geom1.GetOutput() tfilter1 = vtk.vtkTriangleFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): tfilter1.SetInputData(pdata1_temp) else: tfilter1.SetInput(pdata1_temp) tfilter1.Update() pdata1 = tfilter1.GetOutput() pdata0 = tfilter0.GetOutput() p0bd = pdata0.GetBounds() p1bd = pdata1.GetBounds() if (abs(p1bd[0] - p1bd[1]) < abs(p0bd[0] - p0bd[1])): pdata_epi = pdata0 pdata_endo = pdata1 else: pdata_epi = pdata1 pdata_endo = pdata0 return pdata_epi, pdata_endo