def DecimatePolyData(pd, reduction=0.9, ntarget=None): """ reduction == 0.9 => réduction to 10% original size if ntarget is not None override reduction factor vtkDecimatePro only process triangles we use vtkTriangleFilter first """ n = pd.GetPoints().GetNumberOfPoints() if ntarget is not None: reduction = (n-ntarget)/n print("reduction: ", n, reduction) triangulate = vtk.vtkTriangleFilter() triangulate.SetInputData(pd) triangulate.Update() decimate = vtk.vtkDecimatePro() #decimate = vtk.vtkQuadricDecimation() decimate.SetInputData(triangulate.GetOutput()) decimate.SetTargetReduction(reduction) decimate.PreserveTopologyOn() decimate.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(decimate.GetOutput()) triangleFilter.Update() return triangleFilter.GetOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(self.Surface) triangleFilter.Update() decimationFilter = vtk.vtkDecimatePro() decimationFilter.SetInputConnection(triangleFilter.GetOutputPort()) decimationFilter.SetTargetReduction(self.TargetReduction) decimationFilter.SetBoundaryVertexDeletion(self.BoundaryVertexDeletion) decimationFilter.PreserveTopologyOn() decimationFilter.Update() cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(decimationFilter.GetOutputPort()) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(cleaner.GetOutputPort()) triangleFilter.Update() self.Surface = triangleFilter.GetOutput()
def run(self, inputModel1, inputModel2, outputModel, operationIndex): """ Run the actual algorithm """ if not self.isValidInputOutputData(inputModel1, inputModel2, outputModel): slicer.util.errorDisplay('Input volume is the same as output volume. Choose a different output volume.') return False logging.info('Processing started') triangleFilter1 = vtk.vtkTriangleFilter() triangleFilter1.SetInputData(inputModel1.GetPolyData()) triangleFilter1.Update() triangleFilter2 = vtk.vtkTriangleFilter() triangleFilter2.SetInputData(inputModel2.GetPolyData()) triangleFilter2.Update() booleanFilter = vtk.vtkBooleanOperationPolyDataFilter() if operationIndex == 0: booleanFilter.SetOperationToIntersection() elif operationIndex == 1: booleanFilter.SetOperationToDifference() elif operationIndex == 2: booleanFilter.SetOperationToUnion() booleanFilter.SetInputData(0, triangleFilter1.GetOutput()) booleanFilter.SetInputData(1, triangleFilter2.GetOutput()) booleanFilter.Update() outputModel.SetAndObservePolyData(booleanFilter.GetOutput()) outputModel.CreateDefaultDisplayNodes() logging.info('Processing completed') return True
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # we'll be playing around with some vtk objects, this could # be anything self._triangleFilter = vtk.vtkTriangleFilter() self._curvatures = vtk.vtkCurvatures() self._curvatures.SetCurvatureTypeToMaximum() self._curvatures.SetInput(self._triangleFilter.GetOutput()) # initialise any mixins we might have NoConfigModuleMixin.__init__( self, { 'Module (self)': self, 'vtkTriangleFilter': self._triangleFilter, 'vtkCurvatures': self._curvatures }) module_utils.setup_vtk_object_progress(self, self._triangleFilter, 'Triangle filtering...') module_utils.setup_vtk_object_progress(self, self._curvatures, 'Calculating curvatures...') self.sync_module_logic_with_config()
def vtk_poly_data(poly_data, color=_default_color, color_attribute=None, color_map=basic_color_maps.Rainbow, wireframe=False, opacity=1.0, name=None, compression_level=0, **kwargs): """Create a Mesh drawable from given vtkPolyData. This function requires the vtk module (from package VTK) to be installed. Arguments: poly_data: `vtkPolyData`. Native vtkPolyData geometry. color: `int`. Packed RGB color of the resulting mesh (0xff0000 is red, 0xff is blue) when not using color maps. color_attribute: `tuple` of (`str`, `float`, `float`). This determines which scalar should be taken as the attribute for the color_map, and the color_range for the mesh: (attribute_name, min_value, max_value). A VTK mesh can have multiple named attributes in the vertices. min_value is the value mapped to 0 in the color_map. max_value is the value mapped to 1 in the color_map. color_map: `list`. A list of float quadruplets (attribute value, R, G, B), sorted by attribute value. The first quadruplet should have value 0.0, the last 1.0; R, G, B are RGB color components in the range 0.0 to 1.0. wireframe: `bool`. Whether mesh should display as wireframe. opacity: `float`. Opacity of mesh. name: `string`. A name of a object kwargs: `dict`. Dictionary arguments to configure transform and model_matrix.""" if vtk is None: raise RuntimeError('vtk module is not available') if poly_data.GetPolys().GetMaxCellSize() > 3: cut_triangles = vtk.vtkTriangleFilter() cut_triangles.SetInputData(poly_data) cut_triangles.Update() poly_data = cut_triangles.GetOutput() if color_attribute is not None: attribute = numpy_support.vtk_to_numpy(poly_data.GetPointData().GetArray(color_attribute[0])) color_range = color_attribute[1:3] else: attribute = [] color_range = [] vertices = numpy_support.vtk_to_numpy(poly_data.GetPoints().GetData()) indices = numpy_support.vtk_to_numpy(poly_data.GetPolys().GetData()).reshape(-1, 4)[:, 1:4] return process_transform_arguments( Mesh(vertices=np.array(vertices, np.float32), indices=np.array(indices, np.uint32), color=color, opacity=opacity, attribute=np.array(attribute, np.float32), color_range=color_range, color_map=np.array(color_map, np.float32), wireframe=wireframe, name=name, compression_level=compression_level), **kwargs )
def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) # the decimator only works on triangle data, so we make sure # that it only gets triangle data self._triFilter = vtk.vtkTriangleFilter() self._decimate = vtk.vtkDecimatePro() self._decimate.PreserveTopologyOn() self._decimate.SetInput(self._triFilter.GetOutput()) module_utils.setup_vtk_object_progress(self, self._triFilter, 'Converting to triangles') module_utils.setup_vtk_object_progress(self, self._decimate, 'Decimating mesh') # now setup some defaults before our sync self._config.target_reduction = self._decimate.GetTargetReduction() \ * 100.0 config_list = [ ('Target reduction (%):', 'target_reduction', 'base:float', 'text', 'Decimate algorithm will attempt to reduce by this much.')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self, 'vtkDecimatePro' : self._decimate, 'vtkTriangleFilter' : self._triFilter}) self.sync_module_logic_with_config()
def createCutFromPoint(node, color, plane): #z=plane.GetOrigin()[2] #if not isCutting(node, z): # return None segment_source = createSourceFromPoint(node) segment_normal = vtk.vtkPolyDataNormals() segment_normal.SetInputConnection(segment_source.GetOutputPort()) cutEdges = vtk.vtkCutter() cutEdges.SetInputConnection(segment_normal.GetOutputPort()) cutEdges.SetCutFunction(plane) cutEdges.GenerateCutScalarsOn() cutEdges.SetValue(0, 0.5) cutStrips = vtk.vtkStripper() cutStrips.SetInputConnection(cutEdges.GetOutputPort()) cutStrips.Update() cutPoly = vtk.vtkPolyData() cutPoly.SetPoints(cutStrips.GetOutput().GetPoints()) cutPoly.SetPolys(cutStrips.GetOutput().GetLines()) cutTriangles = vtk.vtkTriangleFilter() cutTriangles.SetInput(cutPoly) cutMapper = vtk.vtkPolyDataMapper() cutMapper.SetInput(cutPoly) cutMapper.SetInputConnection(cutTriangles.GetOutputPort()) cutActor = vtk.vtkActor() cutActor.SetMapper(cutMapper) cutActor.GetProperty().SetColor(color[0], color[1], color[2]) return cutActor
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) # we'll be playing around with some vtk objects, this could # be anything self._triangleFilter = vtk.vtkTriangleFilter() self._curvatures = vtk.vtkCurvatures() self._curvatures.SetCurvatureTypeToMaximum() self._curvatures.SetInput(self._triangleFilter.GetOutput()) # initialise any mixins we might have NoConfigModuleMixin.__init__(self, {'Module (self)' : self, 'vtkTriangleFilter' : self._triangleFilter, 'vtkCurvatures' : self._curvatures}) module_utils.setup_vtk_object_progress(self, self._triangleFilter, 'Triangle filtering...') module_utils.setup_vtk_object_progress(self, self._curvatures, 'Calculating curvatures...') self.sync_module_logic_with_config()
def Execute(self): if self.Surface == None: if self.Input == None: self.PrintError('Error: no Surface.') self.Surface = self.Input # estimates surface area to estimate the point density cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(self.Surface) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(cleaner.GetOutputPort()) triangleFilter.Update() massProps = vtk.vtkMassProperties() massProps.SetInputConnection(triangleFilter.GetOutputPort()) massProps.Update() print(massProps.GetSurfaceArea()) area = massProps.GetSurfaceArea() target_area = 3.0**0.5/4.0*self.EdgeLength**2.0 print ("target number of cells: {0}".format(area / target_area)) # A_total = N*(area_equilateral_triangle) print ("target number of points: {0}".format(area / target_area / 2.0)) #in the limit of equilateral triangles ratio ,Ncells/Npoints = 2
def vtk_ensure_trilist(polydata): try: import vtk from vtk.util.numpy_support import vtk_to_numpy trilist = vtk_to_numpy(polydata.GetPolys().GetData()) # 5 is the triangle type - if we have another type we need to # use a vtkTriangleFilter c = vtk.vtkCellTypes() polydata.GetCellTypes(c) if c.GetNumberOfTypes() != 1 or polydata.GetCellType(0) != 5: warnings.warn('Non-triangular mesh connectivity was detected - ' 'this is currently unsupported and thus the ' 'connectivity is being coerced into a triangular ' 'mesh. This may have unintended consequences.') t_filter = vtk.vtkTriangleFilter() t_filter.SetInputData(polydata) t_filter.Update() trilist = vtk_to_numpy(t_filter.GetOutput().GetPolys().GetData()) return trilist.reshape([-1, 4])[:, 1:] except Exception as e: warnings.warn(str(e)) return None
def subdivide(actor, N=1, method=0, legend=None): ''' Increase the number of points in actor surface N = number of subdivisions method = 0, Loop method = 1, Linear method = 2, Adaptive method = 3, Butterfly ''' triangles = vtk.vtkTriangleFilter() setInput(triangles, polydata(actor)) triangles.Update() originalMesh = triangles.GetOutput() if method == 0: sdf = vtk.vtkLoopSubdivisionFilter() elif method == 1: sdf = vtk.vtkLinearSubdivisionFilter() elif method == 2: sdf = vtk.vtkAdaptiveSubdivisionFilter() elif method == 3: sdf = vtk.vtkButterflySubdivisionFilter() else: colors.printc('Error in subdivide: unknown method.', 'r') exit(1) if method != 2: sdf.SetNumberOfSubdivisions(N) setInput(sdf, originalMesh) sdf.Update() out = sdf.GetOutput() if legend is None and hasattr(actor, 'legend'): legend = actor.legend sactor = makeActor(out, legend=legend) sactor.GetProperty().SetOpacity(actor.GetProperty().GetOpacity()) sactor.GetProperty().SetColor(actor.GetProperty().GetColor()) sactor.GetProperty().SetRepresentation( actor.GetProperty().GetRepresentation()) return sactor
def MakeTorus(): ''' Make a torus as the source. :return: vtkPolyData with normal and scalar data. ''' source = vtk.vtkSuperquadricSource(); source.SetCenter(0.0, 0.0, 0.0) source.SetScale(1.0, 1.0, 1.0) source.SetPhiResolution(64) source.SetThetaResolution(64) source.SetThetaRoundness(1) source.SetThickness(0.5) source.SetSize(10) source.SetToroidal(1) # The quadric is made of strips, so pass it through a triangle filter as # the curvature filter only operates on polys tri = vtk.vtkTriangleFilter() tri.SetInputConnection(source.GetOutputPort()) # The quadric has nasty discontinuities from the way the edges are generated # so let's pass it though a CleanPolyDataFilter and merge any points which # are coincident, or very close cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(tri.GetOutputPort()) cleaner.SetTolerance(0.005) cleaner.Update() return CalculateCurvatures(MakeElevations(cleaner.GetOutput()))
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkTriangleFilter(), 'Processing.', ('vtkPolyData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def ExtractGeometryZ(pd, nx, ny, nz, z0): """ cut the mesh using z > z0 could try vtkClipPolyData too """ filter = vtk.vtkExtractPolyDataGeometry() function = vtk.vtkPlane() function.SetNormal(nx, ny, nz) function.SetOrigin(0, 0, z0) triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(pd) triangleFilter.Update() filter.SetImplicitFunction(function) filter.SetInputData(triangleFilter.GetOutput()) filter.Update() #geometryFilter = vtk.vtkGeometryFilter() #geometryFilter.SetInputData(filter.GetOutput()) #geometryFilter.Update() connectFilter = vtk.vtkPolyDataConnectivityFilter() connectFilter.SetExtractionModeToLargestRegion() connectFilter.SetInputData(filter.GetOutput()) connectFilter.Update() return connectFilter.GetOutput()
def Plane(pos=(0, 0, 0), normal=(0, 0, 1), sx=1, sy=None, c="g", alpha=1, texture=None): """ Draw a plane of size `sx` and `sy` oriented perpendicular to vector `normal` and so that it passes through point `pos`. |Plane| """ if sy is None: sy = sx ps = vtk.vtkPlaneSource() ps.SetResolution(1, 1) tri = vtk.vtkTriangleFilter() tri.SetInputConnection(ps.GetOutputPort()) tri.Update() poly = tri.GetOutput() axis = np.array(normal) / np.linalg.norm(normal) theta = np.arccos(axis[2]) phi = np.arctan2(axis[1], axis[0]) t = vtk.vtkTransform() t.PostMultiply() t.Scale(sx, sy, 1) t.RotateY(np.rad2deg(theta)) t.RotateZ(np.rad2deg(phi)) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(poly) tf.SetTransform(t) tf.Update() pd = tf.GetOutput() actor = Actor(pd, c, alpha, texture=texture) actor.SetPosition(pos) settings.collectable_actors.append(actor) return actor
def test_vtk_surface_and_volume(self): import teigen.geometry3d as g3 height = 1.0 radius = 1.0 input1 = teigen.tb_vtk.get_cylinder([0.25, 0, -.5], height=height, radius=radius, direction=[0.0, .0, .0], resolution=50) object1Tri = vtk.vtkTriangleFilter() object1Tri.SetInputData(input1) object1Tri.Update() mass = vtk.vtkMassProperties() mass.SetInputData(object1Tri.GetOutput()) surf = mass.GetSurfaceArea() vol = mass.GetVolume() surf_analytic = g3.cylinder_surface(radius, height) vol_analytic = g3.cylinder_volume(radius, height) err_surf = np.abs(surf_analytic - surf) / surf_analytic err_vol = np.abs(vol_analytic - vol) / vol_analytic # print surf, surf_analytic, err_surf # print vol, vol_analytic, err_vol max_error = 0.01 self.assertLess(err_surf, max_error) self.assertLess(err_vol, max_error)
def MakeTorus(): """ Make a torus as the source. :return: vtkPolyData with normal and scalar data. """ source = vtk.vtkSuperquadricSource() source.SetCenter(0.0, 0.0, 0.0) source.SetScale(1.0, 1.0, 1.0) source.SetPhiResolution(64) source.SetThetaResolution(64) source.SetThetaRoundness(1) source.SetThickness(0.5) source.SetSize(10) source.SetToroidal(1) # The quadric is made of strips, so pass it through a triangle filter as # the curvature filter only operates on polys tri = vtk.vtkTriangleFilter() tri.SetInputConnection(source.GetOutputPort()) # The quadric has nasty discontinuities from the way the edges are generated # so let's pass it though a CleanPolyDataFilter and merge any points which # are coincident, or very close cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(tri.GetOutputPort()) cleaner.SetTolerance(0.005) cleaner.Update() return CalculateCurvatures(MakeElevations(cleaner.GetOutput()))
def readMeshFile(filename, verbose=False): """Read mesh file. The input format is determined by file name extension. Degenerate data gets removed and polygons get split into triangles to support varios restrictive output formats.""" informat = path.splitext(options.infilename)[1].strip('.') # set reader based on filename extension if informat == 'stl': reader = vtk.vtkSTLReader() elif informat == 'vtk': reader = vtk.vtkPolyDataReader() elif informat == 'obj': reader = vtk.vtkMNIObjectReader() #elif informat=='tag': # reader = vtk.vtkMNITagPointReader() else: raise ValueError('cannot read input format' + informat) reader.SetFileName(filename) # merge duplicate points, and/or remove unused points and/or remove degenerate cells clean = vtk.vtkCleanPolyData() clean.SetInputConnection(reader.GetOutputPort()) # convert input polygons and strips to triangles triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(clean.GetOutputPort()) #triangles = reader.GetOutputPort() # skipping above 'cleaning' doesn't work if verbose: print "read", filename return triangles
def readMeshFile(filename, verbose=False): """Read mesh file. The input format is determined by file name extension. Degenerate data gets removed and polygons get split into triangles to support varios restrictive output formats.""" informat = path.splitext(options.infilename)[1].strip('.') # set reader based on filename extension if informat=='stl': reader = vtk.vtkSTLReader() elif informat=='vtk': reader = vtk.vtkPolyDataReader() elif informat=='obj': reader = vtk.vtkMNIObjectReader() #elif informat=='tag': # reader = vtk.vtkMNITagPointReader() else: raise ValueError('cannot read input format' + informat) reader.SetFileName(filename) # merge duplicate points, and/or remove unused points and/or remove degenerate cells clean = vtk.vtkCleanPolyData() clean.SetInputConnection(reader.GetOutputPort()) # convert input polygons and strips to triangles triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(clean.GetOutputPort()) #triangles = reader.GetOutputPort() # skipping above 'cleaning' doesn't work if verbose: print "read", filename return triangles
def CreateCylinder(center, axis, radius, height, resolution=8): source = vtk.vtkCylinderSource() source.SetCenter(0, 0, 0) source.SetRadius(radius) source.SetHeight(height) source.SetResolution(int(resolution)) source.Update() polydata = source.GetOutput() #polydata.Update() #Perform rotation to get the rigth axis oldAxis = (0, 1, 0) polydata = MeshRotate(polydata, oldAxis, axis) #Perform translation to get the rigth center translationVector = center polydata = MeshTranslate(polydata, translationVector) triFilter = vtk.vtkTriangleFilter() if vtk.vtkVersion.GetVTKMajorVersion() == 6: triFilter.SetInputData(polydata) else: triFilter.SetInput(polydata) triFilter.Update() polydata = triFilter.GetOutput() #polydata.Update() return polydata
def MakeText(primitive): tf.update({primitive: vtk.vtkTriangleFilter()}) tf[primitive].SetInputConnection(primitive.GetOutputPort()) mp.update({primitive: vtk.vtkMassProperties()}) mp[primitive].SetInputConnection(tf[primitive].GetOutputPort()) # here we capture stdout and write it to a variable for processing. summary = StringIO.StringIO() # save the original stdout old_stdout = sys.stdout sys.stdout = summary print mp[primitive] summary = summary.getvalue() startSum = summary.find(" VolumeX") endSum = len(summary) print summary[startSum:] # Restore stdout sys.stdout = old_stdout vt.update({primitive: vtk.vtkVectorText()}) vt[primitive].SetText(summary[startSum:]) pdm.update({primitive: vtk.vtkPolyDataMapper()}) pdm[primitive].SetInputConnection(vt[primitive].GetOutputPort()) ta.update({primitive: vtk.vtkActor()}) ta[primitive].SetMapper(pdm[primitive]) ta[primitive].SetScale(.2, .2, .2) return ta[primitive]
def from_shape(cls, shape, colour, args, transform, resolution=20, *args_, **kwargs_): """Initialiase a VTKMesh object from a sfftkrw.SFFShape :param shapes: an iterable of shapes :type shapes: ``sfftkrw.SFFShapePrimitiveList :param colour: the segment colour :type colour: ``sfftkrw.SFFRGBA`` :param args: parsed arguments :type args: ``argparse.Namespace`` :param transform: transform bearing this shape's translation from the origin :type transform: ``sfftkrw.SFFTransformationMatrix`` :param int resolution: mesh resolution :return vtkmesh: an VTKMesh object :rtype vtkmesh: ``VTKMesh`` """ assert resolution > 0 vtkmesh = cls(colour, args, *args_, **kwargs_) from sfftk.schema import SFFEllipsoid, SFFCuboid, SFFCylinder, SFFCone if isinstance(shape, SFFEllipsoid): vtk_shape = vtk.vtkSphereSource() vtk_shape.SetRadius(shape.x) """ :TODO: make this variable """ vtk_shape.SetPhiResolution(resolution) vtk_shape.SetThetaResolution(resolution) elif isinstance(shape, SFFCylinder): vtk_shape = vtk.vtkCylinderSource() vtk_shape.SetHeight(shape.height) vtk_shape.SetRadius(shape.diameter / 2) vtk_shape.SetResolution(resolution) elif isinstance(shape, SFFCone): vtk_shape = vtk.vtkConeSource() vtk_shape.SetHeight(shape.height) vtk_shape.SetRadius(shape.bottomRadius) vtk_shape.SetResolution(resolution) elif isinstance(shape, SFFCuboid): vtk_shape = vtk.vtkCubeSource() vtk_shape.SetXLength(shape.x) vtk_shape.SetYLength(shape.y) vtk_shape.SetZLength(shape.z) T = transform.data_array vtk_shape.SetCenter(float(T[0, 3]), float(T[1, 3]), float(T[2, 3])) vtk_shape.Update() _vtkmesh = vtk_shape.GetOutput() # triangle filter triangleMesh = vtk.vtkTriangleFilter() triangleMesh.SetInputData(_vtkmesh) triangleMesh.Update() triangleMeshOutput = triangleMesh.GetOutput() vtkmesh.vtk_obj.SetPoints(triangleMeshOutput.GetPoints()) vtkmesh.vtk_obj.SetPolys(triangleMeshOutput.GetPolys()) return vtkmesh
def get_mesh_data(self, poly_data, color_attribute=None): """Returns vertices, indices and color attribute of triangulation """ if poly_data.GetPolys().GetMaxCellSize() > 3: cut_triangles = vtk.vtkTriangleFilter() cut_triangles.SetInputData(poly_data) cut_triangles.Update() poly_data = cut_triangles.GetOutput() if color_attribute is not None: attribute = vtk.util.numpy_support.vtk_to_numpy( poly_data.GetPointData().GetArray(color_attribute[0])) color_range = color_attribute[1:3] else: attribute = [] color_range = [] vertices = vtk.util.numpy_support.vtk_to_numpy( poly_data.GetPoints().GetData()) indices = vtk.util.numpy_support.vtk_to_numpy( poly_data.GetPolys().GetData()).reshape(-1, 4)[:, 1:4] return np.array(vertices, np.float32), np.array(indices, np.uint32), np.array( attribute, np.float32)
def Execute(args): reader = vmtkscripts.vmtkSurfaceReader() reader.InputFileName = args.surface reader.Execute() Surface = reader.Surface # estimates surface area to estimate the point density cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(Surface) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(cleaner.GetOutputPort()) triangleFilter.Update() massProps = vtk.vtkMassProperties() massProps.SetInputConnection(triangleFilter.GetOutputPort()) massProps.Update() print(massProps.GetSurfaceArea()) area = massProps.GetSurfaceArea() target_area = 3.0**0.5 / 4.0 * args.edge_length**2.0 print("target number of cells: {0}".format( area / target_area)) # A_total = N*(area_equilateral_triangle) print("target number of points: {0}".format( area / target_area / 2.0)) #in the limit of equilateral triangles ratio ,Ncells/Npoints = 2
def vtkCreateIsoContour(self , config = 'MARCHINGCUBES'): """ Fonction pour la creation de l'isocontour pour une valeur de seuillage""" #----------------------------------------- # Creation de l isocontour #----------------------------------------- if config == 'CONTOUR' : self.aneurysmExtractor = vtk.vtkContourFilter() if config == 'MARCHINGCUBES' : self.aneurysmExtractor = vtk.vtkMarchingCubes() self.aneurysmExtractor.SetInputConnection(self.vtkVolumBlur.GetOutputPort()) self.aneurysmExtractor.SetValue(0, self.valSeuil) self.aneurysmExtractor.ComputeNormalsOn() self.aneurysmTriangleFilter = vtk.vtkTriangleFilter() self.aneurysmTriangleFilter.SetInputConnection(self.aneurysmExtractor.GetOutputPort()) self.aneurysmCleanFilter = vtk.vtkCleanPolyData() self.aneurysmCleanFilter.SetInputConnection(self.aneurysmTriangleFilter.GetOutputPort()) self.aneurysmConnectFilter = vtk.vtkPolyDataConnectivityFilter() self.aneurysmConnectFilter.SetExtractionModeToLargestRegion() self.aneurysmConnectFilter.ScalarConnectivityOff() self.aneurysmConnectFilter.SetInputConnection(self.aneurysmCleanFilter.GetOutputPort()) self.aneurysmNormals = vtk.vtkPolyDataNormals() self.aneurysmNormals.SetInputConnection(self.aneurysmConnectFilter.GetOutputPort()) self.aneurysmNormals.SetFeatureAngle(60.0) self.aneurysmNormals.ComputeCellNormalsOn() self.aneurysmNormals.ComputePointNormalsOn() self.aneurysmNormals.ConsistencyOn() self.aneurysmNormals.AutoOrientNormalsOn() self.aneurysmNormals.Update()
def _transform_to_k3d(timestep, poly_data, color_attribute_name): ''' this function mirrors the prepartion in k3d.vtk_poly_data :param timestep: attribute from vtk collection file :param poly_data: vtk reader Output for one single vtk file :param color_attribute_name: Determines mesh colorization, 3-Tuple of Vtk Dataset name, min value, max value :return: 5-Tuple to match necessary updates to mesh when advancing the timestep ''' if poly_data.GetPolys().GetMaxCellSize() > 3: cut_triangles = vtk.vtkTriangleFilter() cut_triangles.SetInputData(poly_data) cut_triangles.Update() poly_data = cut_triangles.GetOutput() if color_attribute_name is not None: attribute = numpy_support.vtk_to_numpy( poly_data.GetPointData().GetArray(color_attribute_name)) color_range = minmax(attribute) else: attribute = [] color_range = [ 0, -1, ] #[-np.inf, np.inf] vertices = numpy_support.vtk_to_numpy(poly_data.GetPoints().GetData()) indices = numpy_support.vtk_to_numpy( poly_data.GetPolys().GetData()).reshape(-1, 4)[:, 1:4] return timestep, np.array(attribute, np.float32), color_range[0], color_range[1], \ np.array(vertices, np.float32), np.array(indices, np.uint32)
def ugrid2pdata( ugrid, only_trianlges=False, verbose=0): mypy.my_print(verbose, "*** ugrid2pdata ***") filter_geometry = vtk.vtkGeometryFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): filter_geometry.SetInputData(ugrid) else: filter_geometry.SetInput(ugrid) filter_geometry.Update() pdata = filter_geometry.GetOutput() if (only_trianlges): filter_triangle = vtk.vtkTriangleFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): filter_triangle.SetInputData(pdata) else: filter_triangle.SetInput(pdata) filter_triangle.Update() pdata = filter_triangle.GetOutput() return pdata
def filter(self): triangle_filter = vtk.vtkTriangleFilter() triangle_filter.SetInputData(self.mesh.pyvista.extract_surface()) triangle_filter.Update() return self.mesh.mesh_class()(pyvista.wrap( triangle_filter.GetOutput()), parents=[self.mesh])
def MakeText(primitive): tf.update({primitive: vtk.vtkTriangleFilter()}) tf[primitive].SetInputConnection(primitive.GetOutputPort()) mp.update({primitive: vtk.vtkMassProperties()}) mp[primitive].SetInputConnection(tf[primitive].GetOutputPort()) # here we capture stdout and write it to a variable for processing. summary = StringIO.StringIO() # save the original stdout old_stdout = sys.stdout sys.stdout = summary print mp[primitive] summary = summary.getvalue() startSum = summary.find(" VolumeX") endSum = len(summary) print summary[startSum:] # Restore stdout sys.stdout = old_stdout vt.update({primitive: vtk.vtkVectorText()}) vt[primitive].SetText(summary[startSum:]) pdm.update({primitive: vtk.vtkPolyDataMapper()}) pdm[primitive].SetInputConnection(vt[primitive].GetOutputPort()) ta.update({primitive: vtk.vtkActor()}) ta[primitive].SetMapper(pdm[primitive]) ta[primitive].SetScale(0.2, 0.2, 0.2) return ta[primitive]
def generate_plane_surface(half_size=10, res=30): """ Generates a square plane surface with triangular cells. The plane has a center at (0, 0, 0) and normals (0, 0, 1), i.e. the plane is parallel to X and Y axes. Args: half_size (int): half size of the plane (from center to an edge) res (int): resolution (number of divisions) in X and Y axes Returns: a plane surface (vtk.vtkPolyData) """ print("Generating a plane with half size={} and resolution={}".format( half_size, res)) plane = vtk.vtkPlaneSource() # plane.SetCenter(0, 0, 0) plane.SetNormal(0, 0, 1) plane.SetOrigin(-half_size, -half_size, 0) plane.SetPoint1(half_size, -half_size, 0) plane.SetPoint2(-half_size, half_size, 0) plane.SetResolution(res, res) # The plane is made of strips, so pass it through a triangle filter # to get a triangle mesh tri = vtk.vtkTriangleFilter() tri.SetInputConnection(plane.GetOutputPort()) tri.Update() plane_surface = tri.GetOutput() print('{} cells'.format(plane_surface.GetNumberOfCells())) return plane_surface
def WriteTecplotSurfaceFile(self): if self.OutputFileName == "": self.PrintError("Error: no OutputFileName.") self.PrintLog("Writing Tecplot file.") triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(self.Surface) triangleFilter.PassVertsOff() triangleFilter.PassLinesOff() triangleFilter.Update() self.Surface = triangleFilter.GetOutput() f = open(self.OutputFileName, "w") line = "VARIABLES = X,Y,Z" arrayNames = [] for i in range(self.Surface.GetPointData().GetNumberOfArrays()): array = self.Surface.GetPointData().GetArray(i) arrayName = array.GetName() if arrayName == None: continue if arrayName[-1] == "_": continue arrayNames.append(arrayName) if array.GetNumberOfComponents() == 1: line = line + "," + arrayName else: for j in range(array.GetNumberOfComponents()): line = line + "," + arrayName + str(j) line = line + "\n" f.write(line) line = ( "ZONE " + "N=" + str(self.Surface.GetNumberOfPoints()) + "," + "E=" + str(self.Surface.GetNumberOfCells()) + "," + "F=FEPOINT" + "," + "ET=TRIANGLE" + "\n" ) f.write(line) for i in range(self.Surface.GetNumberOfPoints()): point = self.Surface.GetPoint(i) line = str(point[0]) + " " + str(point[1]) + " " + str(point[2]) for arrayName in arrayNames: array = self.Surface.GetPointData().GetArray(arrayName) for j in range(array.GetNumberOfComponents()): line = line + " " + str(array.GetComponent(i, j)) line = line + "\n" f.write(line) for i in range(self.Surface.GetNumberOfCells()): cellPointIds = self.Surface.GetCell(i).GetPointIds() line = "" for j in range(cellPointIds.GetNumberOfIds()): if j > 0: line = line + " " line = line + str(cellPointIds.GetId(j) + 1) line = line + "\n" f.write(line)
def TriFilter(self, inplace=False): """ Returns an all triangle mesh. More complex polygons will be broken down into triangles. Parameters ---------- inplace : bool, optional Updates mesh in-place while returning nothing. Returns ------- mesh : vtkInterface.PolyData Mesh containing only triangles. None when inplace=True """ trifilter = vtk.vtkTriangleFilter() trifilter.SetInputData(self) trifilter.PassVertsOff() trifilter.PassLinesOff() trifilter.Update() if inplace: self.Overwrite(trifilter.GetOutput()) else: return PolyData(trifilter.GetOutput())
def makeTexturedObjData(objPath, scale=1): """ Loads .obj into VTK polyData optimized for searching texture space. Args: objPath (string): File path to .obj file to load Returns: polyData (vtk.vtkPolyData): VTK polyData object optimized for finding mapping from 2D texture coordinates to 3D world coordinates """ meshReader = vtk.vtkOBJReader() meshReader.SetFileName(objPath) triFilter = vtk.vtkTriangleFilter() if vtk.VTK_MAJOR_VERSION <= 5: triFilter.SetInput(meshReader.GetOutput()) else: triFilter.SetInputConnection(meshReader.GetOutputPort()) transform = vtk.vtkTransform() transform.Scale(scale,scale,scale) transformFilter=vtk.vtkTransformPolyDataFilter() transformFilter.SetTransform(transform) if vtk.VTK_MAJOR_VERSION <= 5: triFilter.SetInput(meshReader.GetOutput()) else: transformFilter.SetInputConnection(triFilter.GetOutputPort()) normalGenerator = vtk.vtkPolyDataNormals() normalGenerator.ComputePointNormalsOn() normalGenerator.ComputeCellNormalsOn() if vtk.VTK_MAJOR_VERSION <= 5: normalGenerator.SetInput(transformFilter.GetOutput()) else: normalGenerator.SetInputConnection(transformFilter.GetOutputPort()) normalGenerator.Update() polyData = normalGenerator.GetOutput() return polyData
def SuperquadricSource(): """ Make a torus as the source. """ source = vtk.vtkSuperquadricSource() source.SetCenter(0.0, 0.0, 0.0) source.SetScale(1.0, 1.0, 1.0) source.SetPhiResolution(64) source.SetThetaResolution(64) source.SetThetaRoundness(1) source.SetThickness(0.5) source.SetSize(10) source.SetToroidal(1) # The quadric is made of strips, so pass it through a triangle filter as # the curvature filter only operates on polys tri = vtk.vtkTriangleFilter() tri.SetInputConnection(source.GetOutputPort()) # The quadric has nasty discontinuities from the way the edges are generated # so let's pass it though a CleanPolyDataFilter and merge any points which # are coincident, or very close cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(tri.GetOutputPort()) cleaner.SetTolerance(0.005) cleaner.Update() cleanerBounds = cleaner.GetOutput().GetBounds() elev = vtk.vtkElevationFilter() elev.SetInputConnection(cleaner.GetOutputPort()) elev.SetLowPoint(0, cleanerBounds[2], 0) elev.SetHighPoint(0, cleanerBounds[3], 0) elev.Update() return elev
def GetSurfaceArea(self,modelNode): massProperties = vtk.vtkMassProperties() triangleFilter = vtk.vtkTriangleFilter() massProperties.SetInputConnection(triangleFilter.GetOutputPort()) triangleFilter.SetInputData(modelNode.GetPolyData()) surfaceArea = massProperties.GetSurfaceArea() return surfaceArea
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 cleanerAndTriangleFilter(self, inputModel): cleanerPolydata = vtk.vtkCleanPolyData() cleanerPolydata.SetInputData(inputModel.GetPolyData()) cleanerPolydata.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(cleanerPolydata.GetOutput()) triangleFilter.Update() inputModel.SetAndObservePolyData(triangleFilter.GetOutput())
def convertToImplicitPolyDataDistance(polyData): triFilter = vtk.vtkTriangleFilter() # triFilter to clean the polydata triFilter.SetInputData(polyData) triFilter.Update() ImpDist = vtk.vtkImplicitPolyDataDistance() ImpDist.SetTolerance(1e-1) ImpDist.SetInput(triFilter.GetOutput()) return ImpDist
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(cleaner.GetOutput()) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.ElementSizeMode == 'edgelength': self.TargetArea = 0.25 * 3.0**0.5 * self.TargetEdgeLength**2 elif self.ElementSizeMode == 'edgelengtharray': calculator = vtk.vtkArrayCalculator() calculator.SetInput(self.Surface) calculator.AddScalarArrayName(self.TargetEdgeLengthArrayName,0) calculator.SetFunction("%f^2 * 0.25 * sqrt(3) * %s^2" % (self.TargetEdgeLengthFactor,self.TargetEdgeLengthArrayName)) calculator.SetResultArrayName(self.TargetAreaArrayName) calculator.Update() self.MaxArea = 0.25 * 3.0**0.5 * self.MaxEdgeLength**2 self.MinArea = 0.25 * 3.0**0.5 * self.MinEdgeLength**2 self.Surface = calculator.GetOutput() surfaceRemeshing = vtkvmtk.vtkvmtkPolyDataSurfaceRemeshing() surfaceRemeshing.SetInput(self.Surface) if self.CellEntityIdsArrayName: surfaceRemeshing.SetCellEntityIdsArrayName(self.CellEntityIdsArrayName) if self.ElementSizeMode in ['area','edgelength']: surfaceRemeshing.SetElementSizeModeToTargetArea() elif self.ElementSizeMode in ['areaarray','edgelengtharray']: surfaceRemeshing.SetElementSizeModeToTargetAreaArray() surfaceRemeshing.SetTargetAreaArrayName(self.TargetAreaArrayName) else: self.PrintError('Error: unsupported ElementSizeMode.') surfaceRemeshing.SetTargetArea(self.TargetArea) surfaceRemeshing.SetTargetAreaFactor(self.TargetAreaFactor) surfaceRemeshing.SetMaxArea(self.MaxArea) surfaceRemeshing.SetMinArea(self.MinArea) surfaceRemeshing.SetNumberOfIterations(self.NumberOfIterations) surfaceRemeshing.SetNumberOfConnectivityOptimizationIterations(self.NumberOfConnectivityOptimizationIterations) surfaceRemeshing.SetRelaxation(self.Relaxation) surfaceRemeshing.SetMinAreaFactor(self.MinAreaFactor) surfaceRemeshing.SetAspectRatioThreshold(self.AspectRatioThreshold) surfaceRemeshing.SetInternalAngleTolerance(self.InternalAngleTolerance) surfaceRemeshing.SetNormalAngleTolerance(self.NormalAngleTolerance) surfaceRemeshing.SetCollapseAngleThreshold(self.CollapseAngleThreshold) surfaceRemeshing.SetPreserveBoundaryEdges(self.PreserveBoundaryEdges) surfaceRemeshing.Update() self.Surface = surfaceRemeshing.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(self.Surface) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() contourScalars = vtk.vtkDoubleArray() contourScalars.SetNumberOfComponents(1) contourScalars.SetNumberOfTuples(self.Surface.GetNumberOfPoints()) contourScalars.SetName(self.ContourScalarsArrayName) contourScalars.FillComponent(0,self.OutsideValue) self.Surface.GetPointData().AddArray(contourScalars) self.Surface.GetPointData().SetActiveScalars(self.ContourScalarsArrayName) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(self.Surface) mapper.ScalarVisibilityOn() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.Actor.GetMapper().SetScalarRange(-1.0,0.0) self.vmtkRenderer.Renderer.AddActor(self.Actor) self.ContourWidget = vtk.vtkContourWidget() self.ContourWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) rep = vtk.vtkOrientedGlyphContourRepresentation.SafeDownCast(self.ContourWidget.GetRepresentation()) rep.GetLinesProperty().SetColor(1, 0.2, 0) rep.GetLinesProperty().SetLineWidth(3.0) pointPlacer = vtk.vtkPolygonalSurfacePointPlacer() pointPlacer.AddProp(self.Actor) pointPlacer.GetPolys().AddItem(self.Surface) rep.SetPointPlacer(pointPlacer) self.Interpolator = vtk.vtkPolygonalSurfaceContourLineInterpolator() self.Interpolator.GetPolys().AddItem(self.Surface) rep.SetLineInterpolator(self.Interpolator) self.vmtkRenderer.AddKeyBinding('space','Generate scalars',self.ScalarsCallback) self.vmtkRenderer.AddKeyBinding('d','Delete contour',self.DeleteContourCallback) self.vmtkRenderer.AddKeyBinding('i','Start interaction',self.InteractCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def _readstls(self): """ Reads in all STL files contained in directories indicated by **ref_dir** and **def_dir**. Also calls **_make3Dmesh()** to create 3-D tetrahedral meshes. Returns ------- rsurfs, dsurfs """ for fname in sorted(os.listdir(self._ref_dir)): if '.stl' in fname.lower(): reader = vtk.vtkSTLReader() reader.SetFileName( str(os.path.normpath(self._ref_dir + os.sep + fname))) reader.Update() triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(reader.GetOutputPort()) triangles.Update() self.rsurfs.append(triangles.GetOutput()) massProps = vtk.vtkMassProperties() massProps.SetInputData(self.rsurfs[-1]) massProps.Update() print(("Generating tetrahedral mesh from {:s}".format(fname))) self._make3Dmesh( str(os.path.normpath(self._ref_dir + os.sep + fname)), 'MATERIAL', massProps.GetVolume()) for fname in sorted(os.listdir(self._def_dir)): if '.stl' in fname.lower(): reader = vtk.vtkSTLReader() reader.SetFileName( str(os.path.normpath(self._def_dir + os.sep + fname))) reader.Update() triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(reader.GetOutputPort()) triangles.Update() self.dsurfs.append(triangles.GetOutput()) massProps = vtk.vtkMassProperties() massProps.SetInputData(self.dsurfs[-1]) massProps.Update() print(("Generating tetrahedral mesh from {:s}".format(fname))) self._make3Dmesh( str(os.path.normpath(self._def_dir + os.sep + fname)), 'SPATIAL', massProps.GetVolume())
def write_stl(ugrid, filename): surface_filter = vtk.vtkDataSetSurfaceFilter() surface_filter.SetInputData(ugrid) triangle_filter = vtk.vtkTriangleFilter() triangle_filter.SetInputConnection(surface_filter.GetOutputPort()) writer = vtk.vtkSTLWriter() writer.SetFileName(filename) writer.SetInputConnection(triangle_filter.GetOutputPort()) writer.Write()
def applyFilters(self, state): surface = None surface = state.inputModelNode.GetPolyDataConnection() if state.decimation: triangle = vtk.vtkTriangleFilter() triangle.SetInputConnection(surface) decimation = vtk.vtkDecimatePro() decimation.SetTargetReduction(state.reduction) decimation.SetBoundaryVertexDeletion(state.boundaryDeletion) decimation.PreserveTopologyOn() decimation.SetInputConnection(triangle.GetOutputPort()) surface = decimation.GetOutputPort() if state.smoothing: if state.smoothingMethod == "Laplace": smoothing = vtk.vtkSmoothPolyDataFilter() smoothing.SetBoundarySmoothing(state.boundarySmoothing) smoothing.SetNumberOfIterations(state.laplaceIterations) smoothing.SetRelaxationFactor(state.laplaceRelaxation) smoothing.SetInputConnection(surface) surface = smoothing.GetOutputPort() elif state.smoothingMethod == "Taubin": smoothing = vtk.vtkWindowedSincPolyDataFilter() smoothing.SetBoundarySmoothing(state.boundarySmoothing) smoothing.SetNumberOfIterations(state.taubinIterations) smoothing.SetPassBand(state.taubinPassBand) smoothing.SetInputConnection(surface) surface = smoothing.GetOutputPort() if state.normals: normals = vtk.vtkPolyDataNormals() normals.AutoOrientNormalsOn() normals.SetFlipNormals(state.flipNormals) normals.SetSplitting(state.splitting) normals.SetFeatureAngle(state.featureAngle) normals.ConsistencyOn() normals.SetInputConnection(surface) surface = normals.GetOutputPort() if state.cleaner: cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(surface) surface = cleaner.GetOutputPort() if state.connectivity: connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetExtractionModeToLargestRegion() connectivity.SetInputConnection(surface) surface = connectivity.GetOutputPort() state.outputModelNode.SetPolyDataConnection(surface) return True
def Execute(self): from vmtk import vmtkscripts if self.Surface == None: self.PrintError('Error: no Surface.') if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(self.Surface) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() self.tagviewer = vmtkscripts.vmtkSurfaceViewer() self.tagviewer.Surface = self.Surface self.tagviewer.vmtkRenderer = self.vmtkRenderer self.tagviewer.Representation = 'edges' self.tagviewer.Opacity = self.Opacity self.tagviewer.Execute() self.ContourWidget = vtk.vtkContourWidget() self.ContourWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) rep = vtk.vtkOrientedGlyphContourRepresentation.SafeDownCast(self.ContourWidget.GetRepresentation()) rep.GetLinesProperty().SetColor(1, 0, 0) rep.GetLinesProperty().SetLineWidth(4.0) pointPlacer = vtk.vtkPolygonalSurfacePointPlacer() pointPlacer.AddProp(self.tagviewer.Actor) pointPlacer.GetPolys().AddItem(self.Surface) rep.SetPointPlacer(pointPlacer) self.Interpolator = vtk.vtkPolygonalSurfaceContourLineInterpolator() self.Interpolator.GetPolys().AddItem(self.Surface) rep.SetLineInterpolator(self.Interpolator) self.InputInfo("Building loop ...\n") self.vmtkRenderer.AddKeyBinding('space','Generate loop',self.LoopCallback) self.vmtkRenderer.AddKeyBinding('d','Delete contour',self.DeleteContourCallback) self.vmtkRenderer.AddKeyBinding('i','Start/stop contour drawing',self.InteractCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
def prepareModel(self, polyData): ''' ''' # import the vmtk libraries try: import vtkvmtkComputationalGeometryPython as vtkvmtkComputationalGeometry import vtkvmtkMiscPython as vtkvmtkMisc except ImportError: logging.error("Unable to import the SlicerVmtk libraries") capDisplacement = 0.0 surfaceCleaner = vtk.vtkCleanPolyData() surfaceCleaner.SetInputData(polyData) surfaceCleaner.Update() surfaceTriangulator = vtk.vtkTriangleFilter() surfaceTriangulator.SetInputData(surfaceCleaner.GetOutput()) surfaceTriangulator.PassLinesOff() surfaceTriangulator.PassVertsOff() surfaceTriangulator.Update() # new steps for preparation to avoid problems because of slim models (f.e. at stenosis) subdiv = vtk.vtkLinearSubdivisionFilter() subdiv.SetInputData(surfaceTriangulator.GetOutput()) subdiv.SetNumberOfSubdivisions(1) subdiv.Update() smooth = vtk.vtkWindowedSincPolyDataFilter() smooth.SetInputData(subdiv.GetOutput()) smooth.SetNumberOfIterations(20) smooth.SetPassBand(0.1) smooth.SetBoundarySmoothing(1) smooth.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputData(smooth.GetOutput()) normals.SetAutoOrientNormals(1) normals.SetFlipNormals(0) normals.SetConsistency(1) normals.SplittingOff() normals.Update() surfaceCapper = vtkvmtkComputationalGeometry.vtkvmtkCapPolyData() surfaceCapper.SetInputData(normals.GetOutput()) surfaceCapper.SetDisplacement(capDisplacement) surfaceCapper.SetInPlaneDisplacement(capDisplacement) surfaceCapper.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy(surfaceCapper.GetOutput()) return outPolyData
def Merge(polydata_list): append = vtk.vtkAppendPolyData() for polydata in polydata_list: triangle = vtk.vtkTriangleFilter() triangle.SetInputData(polydata) append.AddInputData(triangle.GetOutput()) clean = vtk.vtkCleanPolyData() clean.SetInputData(append.GetOutput()) return append.GetOutput()
def _readstls(self): for fname in sorted(os.listdir(self._ref_dir)): if '.stl' in fname.lower(): reader = vtk.vtkSTLReader() reader.SetFileName(self._ref_dir+'/'+fname) reader.Update() triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(reader.GetOutputPort()) triangles.Update() self.rsurfs.append(triangles.GetOutput()) dl = vtk.vtkDelaunay3D() dl.SetInputConnection(triangles.GetOutputPort()) dl.Update() self.rmeshes.append(dl) vol, cent, axes = self._getMassProps(self.rmeshes[-1]) self.rvols.append(vol) self.rcentroids.append(cent) self.raxes.append(axes) for fname in sorted(os.listdir(self._def_dir)): if '.stl' in fname.lower(): reader = vtk.vtkSTLReader() reader.SetFileName(self._def_dir+'/'+fname) reader.Update() triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(reader.GetOutputPort()) triangles.Update() self.dsurfs.append(triangles.GetOutput()) dl = vtk.vtkDelaunay3D() dl.SetInputConnection(triangles.GetOutputPort()) dl.Update() self.dmeshes.append(dl) vol, cent, axes = self._getMassProps(self.dmeshes[-1]) self.dvols.append(vol) self.dcentroids.append(cent) self.daxes.append(axes)
def GenTorus(programArguments): ''' programArguments: ini file containing model parameters''' # Load relevant parameters from ini file conf = ConfigObj(programArguments) parameters = conf['Parameters'] majorCirc = parameters['surfaceLength'] minorCirc = parameters['surfaceWidth'] thetaMesh = parameters['xMesh'] # Minor and major radii r = float(minorCirc)/(2*np.pi) R = float(majorCirc)/(2*np.pi) # Mesh sizes thetaResolution = int(thetaMesh) phiResolution = int(thetaResolution*(R/r)) # Generate a torus torusSource = vtk.vtkSuperquadricSource() torusSource.SetCenter(0.0, 0.0, 0.0) torusSource.SetScale(1.0, 1.0, 1.0) torusSource.SetToroidal(1) torusSource.SetThetaRoundness(1) torusSource.SetPhiRoundness(1) # SuperquadricSource reverses phi and theta to be confusing - this is not an error torusSource.SetPhiResolution(thetaResolution) torusSource.SetThetaResolution(phiResolution) # Don't change these! torusSource.SetSize(R + r) torusSource.SetThickness(r/R) # The quadric has nasty discontinuities from the way the edges are generated # so let's pass it though a CleanPolyDataFilter and merge any points which # are coincident, or very close. First convert quads into triangles tri = vtk.vtkTriangleFilter() tri.SetInputConnection(torusSource.GetOutputPort()) cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(tri.GetOutputPort()) cleaner.SetTolerance(0.00005) cleaner.Update() outputFileName = "torus_R" + majorCirc + "_r" + minorCirc + "_mesh" + thetaMesh + ".vtp" writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(cleaner.GetOutput()) writer.SetFileName(outputFileName) writer.Update() print "Saving output to file", outputFileName
def select(connected): selector = vtk.vtkThresholdPoints() selector.SetInput(connected.GetOutput()) print n_regions for i in range(10,11):#change to n_regions selector.ThresholdBetween(48,48) selector.SetInputArrayToProcess(1, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, "RegionId" ) selector.Update() triangles = vtk.vtkTriangleFilter() triangles.SetInputConnection(selector.GetOutputPort()) [V, A] = getMassProperties(triangles) print ("The volume is: " + str(V) + "\n") return selector
def update(self): delaunay = vtkDelaunay3D() delaunay.SetInput(self.input_) delaunay.SetTolerance(self.tolerance) delaunay.SetAlpha(self.alpha) delaunay.Update() geom = vtkGeometryFilter() geom.SetInputConnection(delaunay.GetOutputPort() ) triangle = vtkTriangleFilter() triangle.SetInputConnection(geom.GetOutputPort()) triangle.Update() self.output_ = triangle.GetOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(self.Surface) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(cleaner.GetOutputPort()) triangleFilter.Update() self.Surface = triangleFilter.GetOutput()
def CreatePlanarCrossSectionPolyDataFromFile(file): with open(file, 'r') as f: read_data = f.read() tokens = string.split(read_data) offset = 2 planeAppender = vtk.vtkAppendPolyData() outlineAppender = vtk.vtkAppendPolyData() # Iterate over separate pieces in the file while True: if (offset >= len(tokens)): break pointsInPiece = int(tokens[offset]) newPoints = vtk.vtkPoints() newPoints.SetNumberOfPoints(pointsInPiece) for ptId in xrange(pointsInPiece): x = float(tokens[ptId*3 + 0 + offset + 1]) y = float(tokens[ptId*3 + 1 + offset + 1]) z = float(tokens[ptId*3 + 2 + offset + 1]) newPoints.SetPoint(ptId, x, y, z) offset = offset + 3*pointsInPiece + 1 polygon = vtk.vtkPolyData() polygon.SetPoints(newPoints) polygon.Allocate(pointsInPiece) polygon.InsertNextCell(vtk.VTK_POLYGON, pointsInPiece, range(pointsInPiece)) triFilter = vtk.vtkTriangleFilter() triFilter.SetInputData(polygon) planeAppender.AddInputConnection(triFilter.GetOutputPort()) outline = vtk.vtkPolyData() outline.SetPoints(newPoints) outline.Allocate(pointsInPiece) outline.InsertNextCell(vtk.VTK_POLY_LINE, pointsInPiece, range(pointsInPiece)) outlineAppender.AddInputData(outline) planeAppender.Update() outlineAppender.Update() return (planeAppender.GetOutput(), outlineAppender.GetOutput())
def surface_area_vtk(self): if self.VTK_installed is False: raise VTK_Exception('VTK must be installed to access the surface_area_vtk property') if self._surface_area_vtk is None: tri_converter = vtk.vtkTriangleFilter() tri_converter.SetInputDataObject(self.vtp_mesh) tri_converter.Update() tri_mesh = tri_converter.GetOutput() mass_props = vtk.vtkMassProperties() mass_props.SetInputDataObject(tri_mesh) self._surface_area_vtk = mass_props.GetSurfaceArea() print 'Calculated mesh surface area using VTK Python bindings' return self._surface_area_vtk
def __init__(self): self.Center = np.zeros(3) self.Height = 1. self.Radius = 0.5 self.Direction = np.array((0., 0., 1.)) # Line down the centre of the tube self.Centerline = vtk.vtkPolyData() # VTK filter to create a tube self.Tuber = vtk.vtkTubeFilter() # VTK filter to tidy up the output of Tuber self.Triangulator = vtk.vtkTriangleFilter() self.Triangulator.SetInputConnection(self.Tuber.GetOutputPort()) self.SetExecuteMethod(self._Execute) return
def volume_vtk(self): if self.VTK_installed is False: raise VTK_Exception('VTK must be installed to access the volume_vtk property') if self._volume_vtk is None: tri_converter = vtk.vtkTriangleFilter() tri_converter.SetInputDataObject(self.vtp_mesh) tri_converter.Update() tri_mesh = tri_converter.GetOutput() mass_props = vtk.vtkMassProperties() mass_props.SetInputDataObject(tri_mesh) self._volume_vtk = mass_props.GetVolume() print 'Calculated mesh volume using VTK library' return self._volume_vtk
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source polygonSource = vtk.vtkRegularPolygonSource() polygonSource.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(polygonSource.GetOutputPort()) triangleFilter.Update() inputMapper = vtk.vtkPolyDataMapper() inputMapper.SetInputConnection(polygonSource.GetOutputPort()) inputActor = vtk.vtkActor() inputActor.SetMapper(inputMapper) inputActor.GetProperty().SetRepresentationToWireframe() triangleMapper = vtk.vtkPolyDataMapper() triangleMapper.SetInputConnection(triangleFilter.GetOutputPort()) triangleActor = vtk.vtkActor() triangleActor.SetMapper(triangleMapper) triangleActor.GetProperty().SetRepresentationToWireframe() # Setup renderers leftRenderer = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(leftRenderer) leftRenderer.SetViewport(0, 0, 0.5, 1) leftRenderer.SetBackground(0.6, 0.5, 0.4) leftRenderer.AddActor(inputActor) rightRenderer = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(rightRenderer) rightRenderer.SetViewport(0.5, 0, 1, 1) rightRenderer.SetBackground(0.4, 0.5, 0.6) rightRenderer.AddActor(triangleActor) leftRenderer.ResetCamera() rightRenderer.ResetCamera() self._initialized = False
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(cleaner.GetOutput()) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(self.Surface) triangleFilter.Update() decimationFilter = vtk.vtkDecimatePro() decimationFilter.SetInput(triangleFilter.GetOutput()) decimationFilter.SetTargetReduction(self.TargetReduction) decimationFilter.SetBoundaryVertexDeletion(self.BoundaryVertexDeletion) decimationFilter.PreserveTopologyOn() decimationFilter.Update() cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(decimationFilter.GetOutput()) cleaner.Update() triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(cleaner.GetOutput()) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()