def wrapOpImp(self): smooth = vtk.vtkLoopSubdivisionFilter(); smooth.SetInputData(self.data); smooth.SetNumberOfSubdivisions(self.subdivision_count); smooth.Update(); result = smooth.GetOutput(); return result;
def Subdivide(self, nsub, subfilter='linear'): """ Increase the number of triangles in a single, connected triangular mesh. Uses one of the following vtk subdivision filters to subdivide a mesh. vtkButterflySubdivisionFilter vtkLoopSubdivisionFilter vtkLinearSubdivisionFilter Linear subdivision results in the fastest mesh subdivision, but it does not smooth mesh edges, but rather splits each triangle into 4 smaller triangles. Butterfly and loop subdivision perform smoothing when dividing, and may introduce artifacts into the mesh when dividing. Subdivision filter appears to fail for multiple part meshes. Should be one single mesh. Parameters ---------- nsub : int Number of subdivisions. Each subdivision creates 4 new triangles, so the number of resulting triangles is nface*4**nsub where nface is the current number of faces. subfilter : string, optional Can be one of the following: 'butterfly', 'loop', 'linear' Returns ------- mesh : Polydata object vtkInterface polydata object. Examples -------- >>> from vtkInterface import examples >>> import vtkInterface >>> mesh = vtkInterface.LoadMesh(examples.planefile) >>> submesh = mesh.Subdivide(1, 'loop') """ subfilter = subfilter.lower() if subfilter == 'linear': sfilter = vtk.vtkLinearSubdivisionFilter() elif subfilter == 'butterfly': sfilter = vtk.vtkButterflySubdivisionFilter() elif subfilter == 'loop': sfilter = vtk.vtkLoopSubdivisionFilter() else: raise Exception( "Subdivision filter must be one of the following: " + "'butterfly', 'loop', or 'linear'") # Subdivide sfilter.SetNumberOfSubdivisions(nsub) sfilter.SetInputData(self) sfilter.Update() return PolyData(sfilter.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkLoopSubdivisionFilter(), 'Processing.', ('vtkPolyData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def get_topography_actor(x, y, topography, super_elevation, decimation, smoothing=False): topography = topography.T topography *= super_elevation points, triangles, colors = setup_topography(x, y, topography, decimation=decimation) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(points) trianglePolyData.GetPointData().SetScalars(colors) trianglePolyData.SetPolys(triangles) # Clean the polydata so that the edges are shared ! cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInput(trianglePolyData) # Use a filter to smooth the data (will add triangles and smooth) # Use two different filters to show the difference mapper = vtk.vtkPolyDataMapper() if smoothing: smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(2) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort()) mapper.SetInputConnection(smooth_loop.GetOutputPort()) else: mapper.SetInput(trianglePolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
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 __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkLoopSubdivisionFilter(), 'Processing.', ('vtkPolyData', ), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def surface(vertices, faces=None, colors=None, smooth=None, subdivision=3): points = vtk.vtkPoints() points.SetData(numpy_support.numpy_to_vtk(vertices)) triangle_poly_data = vtk.vtkPolyData() triangle_poly_data.SetPoints(points) if colors is not None: triangle_poly_data.GetPointData().SetScalars( numpy_support.numpy_to_vtk(colors)) if faces is None: tri = Delaunay(vertices[:, [0, 1]]) faces = np.array(tri.simplices, dtype='i8') if faces.shape[1] == 3: triangles = np.empty((faces.shape[0], 4), dtype=np.int64) triangles[:, -3:] = faces triangles[:, 0] = 3 else: triangles = faces if not triangles.flags['C_CONTIGUOUS'] or triangles.dtype != 'int64': triangles = np.ascontiguousarray(triangles, 'int64') cells = vtk.vtkCellArray() cells.SetCells(triangles.shape[0], numpy_support.numpy_to_vtkIdTypeArray(triangles, deep=True)) triangle_poly_data.SetPolys(cells) clean_poly_data = vtk.vtkCleanPolyData() clean_poly_data.SetInputData(triangle_poly_data) mapper = vtk.vtkPolyDataMapper() surface_actor = vtk.vtkActor() if smooth is None: mapper.SetInputData(triangle_poly_data) surface_actor.SetMapper(mapper) elif smooth == "loop": smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(subdivision) smooth_loop.SetInputConnection(clean_poly_data.GetOutputPort()) mapper.SetInputConnection(smooth_loop.GetOutputPort()) surface_actor.SetMapper(mapper) elif smooth == "butterfly": smooth_butterfly = vtk.vtkButterflySubdivisionFilter() smooth_butterfly.SetNumberOfSubdivisions(subdivision) smooth_butterfly.SetInputConnection(clean_poly_data.GetOutputPort()) mapper.SetInputConnection(smooth_butterfly.GetOutputPort()) surface_actor.SetMapper(mapper) return surface_actor
def vtk_ellipsoid_topomesh(ellipsoid_radius=50.0, ellipsoid_scales=[1,1,1], ellipsoid_axes=np.diag(np.ones(3)), ellipsoid_center=np.zeros(3)): """ """ import vtk from openalea.cellcomplex.property_topomesh.utils.image_tools import vtk_polydata_to_triangular_mesh ico = vtk.vtkPlatonicSolidSource() ico.SetSolidTypeToIcosahedron() ico.Update() subdivide = vtk.vtkLoopSubdivisionFilter() subdivide.SetNumberOfSubdivisions(3) subdivide.SetInputConnection(ico.GetOutputPort()) subdivide.Update() scale_transform = vtk.vtkTransform() scale_factor = ellipsoid_radius/(np.sqrt(2)/2.) scale_transform.Scale(scale_factor,scale_factor,scale_factor) ellipsoid_sphere = vtk.vtkTransformPolyDataFilter() ellipsoid_sphere.SetInput(subdivide.GetOutput()) ellipsoid_sphere.SetTransform(scale_transform) ellipsoid_sphere.Update() ellipsoid_transform = vtk.vtkTransform() axes_transform = vtk.vtkLandmarkTransform() source_points = vtk.vtkPoints() source_points.InsertNextPoint([1,0,0]) source_points.InsertNextPoint([0,1,0]) source_points.InsertNextPoint([0,0,1]) target_points = vtk.vtkPoints() target_points.InsertNextPoint(ellipsoid_axes[0]) target_points.InsertNextPoint(ellipsoid_axes[1]) target_points.InsertNextPoint(ellipsoid_axes[2]) axes_transform.SetSourceLandmarks(source_points) axes_transform.SetTargetLandmarks(target_points) axes_transform.SetModeToRigidBody() axes_transform.Update() ellipsoid_transform.SetMatrix(axes_transform.GetMatrix()) ellipsoid_transform.Scale(ellipsoid_scales[0],ellipsoid_scales[1],ellipsoid_scales[2]) center_transform = vtk.vtkTransform() center_transform.Translate(ellipsoid_center[0],ellipsoid_center[1],ellipsoid_center[2]) center_transform.Concatenate(ellipsoid_transform) ellipsoid_ellipsoid = vtk.vtkTransformPolyDataFilter() ellipsoid_ellipsoid.SetInput(ellipsoid_sphere.GetOutput()) ellipsoid_ellipsoid.SetTransform(center_transform) ellipsoid_ellipsoid.Update() ellipsoid_mesh = vtk_polydata_to_triangular_mesh(ellipsoid_ellipsoid.GetOutput()) topomesh = triangle_topomesh(ellipsoid_mesh.triangles.values(),ellipsoid_mesh.points) return topomesh
def SubdivideMesh(mesh, nsub): """ Subdivides a VTK mesh """ if nsub > 3: subdivide = vtk.vtkLinearSubdivisionFilter() else: subdivide = vtk.vtkLoopSubdivisionFilter() # slower, but appears to be smoother subdivide.SetNumberOfSubdivisions(nsub) if vtk.vtkVersion().GetVTKMajorVersion() > 5: subdivide.SetInputData(mesh) else: subdivide.SetInput(mesh) subdivide.Update() return subdivide.GetOutput()
def SubdivideMesh(mesh, nsub): """ Subdivides a VTK mesh """ if nsub > 3: subdivide = vtk.vtkLinearSubdivisionFilter() else: subdivide = vtk.vtkLoopSubdivisionFilter( ) # slower, but appears to be smoother subdivide.SetNumberOfSubdivisions(nsub) if vtk.vtkVersion().GetVTKMajorVersion() > 5: subdivide.SetInputData(mesh) else: subdivide.SetInput(mesh) subdivide.Update() return subdivide.GetOutput()
def subdivision(poly, num, option='linear'): if option == 'linear': divide = vtk.vtkLinearSubdivisionFilter() elif option == 'loop': divide = vtk.vtkLoopSubdivisionFilter() elif option == 'butterfly': divide = vtk.vtkButterflySubdivisionFilter() else: print("subdivision option: linear, loop or butterfly") raise divide.SetInputData(poly) divide.SetNumberOfSubdivisions(num) divide.Update() return divide.GetOutput()
def __init__(self, **kwargs): self.poly_data = vtk.vtkPolyData() self.subdivider = vtk.vtkLoopSubdivisionFilter() self.subdivider.SetInput(self.poly_data) self.subdivider.SetNumberOfSubdivisions(2) self.mapper = vtk.vtkDataSetMapper() self.mapper.SetInputConnection(self.subdivider.GetOutputPort()) self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self._process_kwargs(**kwargs)
def vtkCreateFilterIsoContour(self): """ Fonction pour le filtrage du contour""" #----------------------------------------- # Application d'un filtre de subdivision #----------------------------------------- self.subdiviseAneurysm = vtk.vtkLoopSubdivisionFilter() self.subdiviseAneurysm.SetNumberOfSubdivisions(self.valFilter) self.subdiviseAneurysm.SetInputConnection(self.aneurysmNormals.GetOutputPort()) #----------------------------------------- # Application d'un filtre decimate et smooth #----------------------------------------- self.aneurysmDecimator = vtk.vtkDecimatePro() self.aneurysmDecimator.SetInputConnection(self.subdiviseAneurysm.GetOutputPort()) self.aneurysmDecimator.SetTargetReduction(self.valDecimate) self.aneurysmDecimator.PreserveTopologyOn() self.smoothAneurysm = vtk.vtkSmoothPolyDataFilter() self.smoothAneurysm.SetInputConnection(self.aneurysmDecimator.GetOutputPort()) self.smoothAneurysm.SetNumberOfIterations(self.valSmoothIter) self.smoothAneurysm.SetRelaxationFactor(0.07) self.smoothAneurysm.SetFeatureAngle(90) self.smoothAneurysm.FeatureEdgeSmoothingOn() #----------------------------------------- # Sauvegarde des datas pour le calcul des centerlines #----------------------------------------- surface_filter = vtk.vtkDataSetSurfaceFilter() surface_filter.SetInputConnection(self.smoothAneurysm.GetOutputPort()) meshNormals = vtk.vtkPolyDataNormals() meshNormals.SetInputConnection(surface_filter.GetOutputPort()) meshNormals.Update() self.surfNode = vtk_to_np(self.smoothAneurysm.GetOutput().GetPoints().GetData()) self.surfTable = vtk_to_np(self.smoothAneurysm.GetOutput().GetPolys().GetData()) #----------------------------------------- # Realisation du mapper ppour affichage #----------------------------------------- self.aneurysmStripper = vtk.vtkStripper() self.aneurysmStripper.SetInputConnection(self.smoothAneurysm.GetOutputPort()) self.aneurysmMapper = vtk.vtkPolyDataMapper() self.aneurysmMapper.SetInputConnection(self.aneurysmStripper.GetOutputPort()) self.aneurysmMapper.ScalarVisibilityOff() self.aneurysmMapper.SetScalarRange(self.min_pixel_value, self.max_pixel_value) self.aneurysmMapper.SetScalarModeToUsePointData() self.aneurysmMapper.SetLookupTable(self.bwLut)
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 sphereSource = vtk.vtkSphereSource() sphereSource.Update() originalMesh = sphereSource.GetOutput() numberOfViewports = 3 self.vtkWidget.GetRenderWindow().SetSize(200 * numberOfViewports, 200) numberOfSubdivisions = 2 for i in range(numberOfViewports): if i == 0: subdivisionFilter = vtk.vtkLinearSubdivisionFilter() elif i == 1: subdivisionFilter = vtk.vtkLoopSubdivisionFilter() else: subdivisionFilter = vtk.vtkButterflySubdivisionFilter() subdivisionFilter.SetNumberOfSubdivisions(numberOfSubdivisions) subdivisionFilter.SetInputConnection( originalMesh.GetProducerPort()) subdivisionFilter.Update() renderer = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(renderer) renderer.SetViewport( float(i) / numberOfViewports, 0, (i + 1.0) / numberOfViewports, 1) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(subdivisionFilter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor) renderer.ResetCamera() self._initialized = False
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 sphereSource = vtk.vtkSphereSource() sphereSource.Update() originalMesh = sphereSource.GetOutput() numberOfViewports = 3 self.vtkWidget.GetRenderWindow().SetSize(200*numberOfViewports, 200) numberOfSubdivisions = 2 for i in range(numberOfViewports): if i == 0: subdivisionFilter = vtk.vtkLinearSubdivisionFilter() elif i == 1: subdivisionFilter = vtk.vtkLoopSubdivisionFilter() else: subdivisionFilter = vtk.vtkButterflySubdivisionFilter() subdivisionFilter.SetNumberOfSubdivisions(numberOfSubdivisions) subdivisionFilter.SetInputConnection(originalMesh.GetProducerPort()) subdivisionFilter.Update() renderer = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(renderer) renderer.SetViewport(float(i)/numberOfViewports, 0, (i+1.0)/numberOfViewports, 1) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(subdivisionFilter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor) renderer.ResetCamera() self._initialized = False
def dem_to_vtk(self, dem): # %% points = vtk.vtkPoints() [points.InsertNextPoint(c) for c in dem] aPolyData = vtk.vtkPolyData() aPolyData.SetPoints(points) aCellArray = vtk.vtkCellArray() # Start triangulation - define boundary boundary = vtk.vtkPolyData() boundary.SetPoints(aPolyData.GetPoints()) boundary.SetPolys(aCellArray) # Perform Delaunay 2D delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(aPolyData) delaunay.SetSourceData(boundary) delaunay.Update() # Extract the polydata object from the triangulation = all the triangles trianglePolyData = delaunay.GetOutput() # Clean the polydata so that the edges are shared ! cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInputData(trianglePolyData) # Use a filter to smooth the data (will add triangles and smooth) - default parameters smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(3) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort()) smooth_loop.Update() # Save Polydata to XML format. Use smooth_loop.GetOutput() to obtain filtered polydata writer = vtk.vtkPolyDataWriter() writer.SetInputData(smooth_loop.GetOutput()) writer.SetFileTypeToBinary() writer.SetFileName(os.path.join(self.output_dir, 'dem.vtk')) writer.Update() return 0
def Execute(self): if self.Surface == None: self.PrintError('Error: No input surface.') subdivisionFilter = None if self.Method == 'linear': subdivisionFilter = vtk.vtkLinearSubdivisionFilter() elif self.Method == 'butterfly': subdivisionFilter = vtk.vtkButterflySubdivisionFilter() elif self.Method == 'loop': subdivisionFilter = vtk.vtkLoopSubdivisionFilter() else: self.PrintError('Error: Unsupported subdivision method.') subdivisionFilter.SetInputData(self.Surface) subdivisionFilter.SetNumberOfSubdivisions(self.NumberOfSubdivisions) subdivisionFilter.Update() self.Surface = subdivisionFilter.GetOutput()
def mesh_subdivision(self, num_subdivisions, method='loop'): if method == 'loop': subdivision_reader = vtk.vtkLoopSubdivisionFilter() elif method == 'butterfly': subdivision_reader = vtk.vtkButterflySubdivisionFilter() else: if self.warning: print('Not a valid subdivision method') subdivision_reader.SetInputData(self.vtkPolyData) subdivision_reader.SetNumberOfSubdivisions(num_subdivisions) subdivision_reader.Update() self.vtkPolyData = subdivision_reader.GetOutput() self.get_mesh_data_from_vtkPolyData() if self.warning: print( 'Warning! self.cell_attributes are reset and need to be updated!' ) self.cell_attributes = dict() #reset self.point_attributes = dict() #reset
def sphere2points( params, min_radius ): #input [X,Y,Z,Radius],min #output array[[0..#points],[x,y,z,nx,ny,nz]] vtk.vtkMultiThreader.SetGlobalMaximumNumberOfThreads( 1) # parallelized otherwise resolution = 1 + int(math.ceil(params[3] / min_radius)**0.5) ico = vtk.vtkPlatonicSolidSource() ico.SetSolidTypeToIcosahedron() subdivide = vtk.vtkLoopSubdivisionFilter() subdivide.SetNumberOfSubdivisions(resolution) subdivide.SetInputConnection(ico.GetOutputPort()) subdivide.Update() points = np.asarray(subdivide.GetOutput().GetPoints().GetData()) x = points[:, 0] y = points[:, 1] z = points[:, 2] r = ne.evaluate("sqrt(x**2 + y**2 + z**2)") points = np.divide(points[:, :], r[:, None]) normals = points points = points * params[3] + params[0:3] # scale and translation result = np.concatenate((points, normals), axis=1) return result
def get_surface_actor(width, resolution, y_offset, path_directory): # data = np.loadtxt(path_directory + 'Ground_Rock2Dlight.txt', delimiter = ',') data = np.loadtxt(path_directory, delimiter = ',') x_coords = data[:,0] y_coords = np.linspace(y_offset - width/2, y_offset + width/2, num=resolution) z_coords = data[:,1] z_coords -= 0.05 #fix ground clipping m = x_coords.shape[0] n = y_coords.shape[0] # Define points, triangles and colors points = vtkPoints() triangles = vtkCellArray() # Build the meshgrid manually count = 0 for i in range(m-1): for j in range(n-1): z1 = z_coords[i] z2 = z_coords[i] z3 = z_coords[i+1] # Triangle 1 points.InsertNextPoint(x_coords[i], y_coords[j], z1) points.InsertNextPoint(x_coords[i], y_coords[j+1], z2) points.InsertNextPoint(x_coords[i+1], y_coords[j], z3) triangle = vtkTriangle() triangle.GetPointIds().SetId(0, count) triangle.GetPointIds().SetId(1, count + 1) triangle.GetPointIds().SetId(2, count + 2) triangles.InsertNextCell(triangle) z1 = z_coords[i] z2 = z_coords[i+1] z3 = z_coords[i+1] # Triangle 2 points.InsertNextPoint(x_coords[i], y_coords[j+1], z1) points.InsertNextPoint(x_coords[i+1], y_coords[j+1], z2) points.InsertNextPoint(x_coords[i+1], y_coords[j], z3) triangle = vtkTriangle() triangle.GetPointIds().SetId(0, count + 3) triangle.GetPointIds().SetId(1, count + 4) triangle.GetPointIds().SetId(2, count + 5) count += 6 triangles.InsertNextCell(triangle) # Create a polydata object PolyData = vtkPolyData() # Add the geometry and topology to the polydata PolyData.SetPoints(points) #PolyData.GetPointData().SetScalars(colors) PolyData.SetPolys(triangles) if color_map: bounds = PolyData.GetBounds() minz = bounds[4] maxz = bounds[5] lut = vtkLookupTable() lut.SetTableRange(minz, maxz) lut.Build() colors = vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName('Colors') for i in range(PolyData.GetNumberOfPoints()): point = PolyData.GetPoint(i) dcolor = 3*[0.0] lut.GetColor(point[2], dcolor) #assign color to z value color = [i*255.0 for i in dcolor] colors.InsertNextTuple3(*color) PolyData.GetPointData().SetScalars(colors) # Clean the polydata so that the edges are shared ! cleanPolyData = vtkCleanPolyData() cleanPolyData.SetInputData(PolyData) # Use a filter to smooth the data (will add triangles and smooth) smoothPolyData = vtkLoopSubdivisionFilter() smoothPolyData.SetNumberOfSubdivisions(3) smoothPolyData.SetInputConnection(cleanPolyData.GetOutputPort()) # Create a mapper and actor for smoothed dataset mapper = vtkPolyDataMapper() mapper.SetInputConnection(smoothPolyData.GetOutputPort()) actor_loop = vtkActor() actor_loop.SetMapper(mapper) actor_loop.GetProperty().SetColor(0.929, 0.788, 0.686) actor_loop.GetProperty().SetAmbient(0.1) actor_loop.GetProperty().SetAmbientColor(0.3,0.3,0.3) # actor_loop.GetProperty().SetDiffuse(0.1) # actor_loop.GetProperty().SetDiffuseColor(0.396, 0.263, 0.129) # actor_loop.GetProperty().SetInterpolationToPhong() # actor_loop.GetProperty().SetSpecular(0.6) # actor_loop.GetProperty().SetSpecularPower(10) # actor_loop.GetProperty().EdgeVisibilityOn() actor_loop.GetProperty().SetLineWidth(0.2) return actor_loop
parser.add_argument('-r','--range',type=float , help = 'Set the scalar range for visualization to [-RANGE,+RANGE].') parser.add_argument('-c', '--color',type=str, help = 'The name of the color scheme.\ The default value is BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_3 .\ For more information visit:\ http://www.vtk.org/doc/nightly/html/classvtkColorSeries.html',\ default='BREWER_SEQUENTIAL_YELLOW_ORANGE_BROWN_3') args = parser.parse_args() vtp_file = args.input reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(vtp_file) reader.Update() polydata = reader.GetOutput() subdivisionFilter = vtk.vtkLoopSubdivisionFilter() subdivisionFilter.SetNumberOfSubdivisions(2) #set the order subdivisionFilter.SetInputData(polydata) subdivisionFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(subdivisionFilter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) ##### visualizations ### ## color lookup table ## lut = vtk.vtkColorTransferFunction() lut.SetColorSpaceToHSV() color_series = vtk.vtkColorSeries()
def main(): nc = vtk.vtkNamedColors() # Make a 32 x 32 grid size = 32 rn = vtk.vtkMinimalStandardRandomSequence() rn.SetSeed(1) # Define z values for the topography (random height) topography = numpy.zeros([size, size]) for i in range(size): for j in range(size): topography[i][j] = rn.GetRangeValue(0, 5) rn.Next() # Define points, triangles and colors colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) points = vtk.vtkPoints() triangles = vtk.vtkCellArray() # Build the meshgrid manually count = 0 for i in range(size - 1): for j in range(size - 1): z1 = topography[i][j] z2 = topography[i][j + 1] z3 = topography[i + 1][j] # Triangle 1 points.InsertNextPoint(i, j, z1) points.InsertNextPoint(i, (j + 1), z2) points.InsertNextPoint((i + 1), j, z3) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count) triangle.GetPointIds().SetId(1, count + 1) triangle.GetPointIds().SetId(2, count + 2) triangles.InsertNextCell(triangle) z1 = topography[i][j + 1] z2 = topography[i + 1][j + 1] z3 = topography[i + 1][j] # Triangle 2 points.InsertNextPoint(i, (j + 1), z1) points.InsertNextPoint((i + 1), (j + 1), z2) points.InsertNextPoint((i + 1), j, z3) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count + 3) triangle.GetPointIds().SetId(1, count + 4) triangle.GetPointIds().SetId(2, count + 5) count += 6 triangles.InsertNextCell(triangle) # Add some color r = [int(i / float(size) * 255), int(j / float(size) * 255), 0] colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(points) trianglePolyData.GetPointData().SetScalars(colors) trianglePolyData.SetPolys(triangles) # Clean the polydata so that the edges are shared ! cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInputData(trianglePolyData) # Use a filter to smooth the data (will add triangles and smooth) # Use two different filters to show the difference smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(3) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort()) smooth_butterfly = vtk.vtkButterflySubdivisionFilter() smooth_butterfly.SetNumberOfSubdivisions(3) smooth_butterfly.SetInputConnection(cleanPolyData.GetOutputPort()) # Create a mapper and actor for initial dataset mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(trianglePolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) # Create a mapper and actor for smoothed dataset (vtkLoopSubdivisionFilter) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(smooth_loop.GetOutputPort()) actor_loop = vtk.vtkActor() actor_loop.SetMapper(mapper) actor_loop.SetPosition(32, 0, 0) # Create a mapper and actor for smoothed dataset (vtkButterflySubdivisionFilter) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(smooth_butterfly.GetOutputPort()) actor_butterfly = vtk.vtkActor() actor_butterfly.SetMapper(mapper) actor_butterfly.SetPosition(64, 0, 0) # Visualise renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add actors and render renderer.AddActor(actor) renderer.AddActor(actor_loop) renderer.AddActor(actor_butterfly) renderer.SetBackground(nc.GetColor3d('AliceBlue')) renderWindow.SetSize(900, 300) renderWindow.Render() renderer.GetActiveCamera().Elevation(-45) renderer.GetActiveCamera().Zoom(3) renderWindow.Render() renderWindowInteractor.Start()
def main(): named_colors = vtk.vtkNamedColors() # Make a 32 x 32 grid. size = 32 # Define z values for the topography. # Comment out the following line if you want a different random # distribution each time the script is run. np.random.seed(3) topography = np.random.randint(0, 5, (size, size)) # Define points, triangles and colors colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) points = vtk.vtkPoints() triangles = vtk.vtkCellArray() # Build the meshgrid manually. count = 0 for i in range(size - 1): for j in range(size - 1): z1 = topography[i][j] z2 = topography[i][j + 1] z3 = topography[i + 1][j] # Triangle 1 points.InsertNextPoint(i, j, z1) points.InsertNextPoint(i, (j + 1), z2) points.InsertNextPoint((i + 1), j, z3) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count) triangle.GetPointIds().SetId(1, count + 1) triangle.GetPointIds().SetId(2, count + 2) triangles.InsertNextCell(triangle) z1 = topography[i][j + 1] z2 = topography[i + 1][j + 1] z3 = topography[i + 1][j] # Triangle 2 points.InsertNextPoint(i, (j + 1), z1) points.InsertNextPoint((i + 1), (j + 1), z2) points.InsertNextPoint((i + 1), j, z3) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count + 3) triangle.GetPointIds().SetId(1, count + 4) triangle.GetPointIds().SetId(2, count + 5) count += 6 triangles.InsertNextCell(triangle) # Add some color. r = [int(i / float(size) * 255), int(j / float(size) * 255), 0] colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) colors.InsertNextTypedTuple(r) # Create a polydata object. trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata. trianglePolyData.SetPoints(points) trianglePolyData.GetPointData().SetScalars(colors) trianglePolyData.SetPolys(triangles) # Clean the polydata so that the edges are shared! cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInputData(trianglePolyData) # Use a filter to smooth the data (will add triangles and smooth). smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(3) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort()) # Create a mapper and actor for smoothed dataset. mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(smooth_loop.GetOutputPort()) actor_loop = vtk.vtkActor() actor_loop.SetMapper(mapper) actor_loop.GetProperty().SetInterpolationToFlat() # Update the pipeline so that vtkCellLocator finds cells! smooth_loop.Update() # Define a cellLocator to be able to compute intersections between lines. # and the surface locator = vtk.vtkCellLocator() locator.SetDataSet(smooth_loop.GetOutput()) locator.BuildLocator() maxloop = 1000 dist = 20.0 / maxloop tolerance = 0.001 # Make a list of points. Each point is the intersection of a vertical line # defined by p1 and p2 and the surface. points = vtk.vtkPoints() for i in range(maxloop): p1 = [2 + i * dist, 16, -1] p2 = [2 + i * dist, 16, 6] # Outputs (we need only pos which is the x, y, z position # of the intersection) t = vtk.mutable(0) pos = [0.0, 0.0, 0.0] pcoords = [0.0, 0.0, 0.0] subId = vtk.mutable(0) locator.IntersectWithLine(p1, p2, tolerance, t, pos, pcoords, subId) # Add a slight offset in z. pos[2] += 0.01 # Add the x, y, z position of the intersection. points.InsertNextPoint(pos) # Create a spline and add the points spline = vtk.vtkParametricSpline() spline.SetPoints(points) functionSource = vtk.vtkParametricFunctionSource() functionSource.SetUResolution(maxloop) functionSource.SetParametricFunction(spline) # Map the spline mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(functionSource.GetOutputPort()) # Define the line actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(named_colors.GetColor3d("Red")) actor.GetProperty().SetLineWidth(3) # Visualize renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add actors and render renderer.AddActor(actor) renderer.AddActor(actor_loop) renderer.SetBackground(named_colors.GetColor3d("Cornsilk")) renderWindow.SetSize(800, 800) renderWindow.Render() renderer.GetActiveCamera().SetPosition(-32.471276, 53.258788, 61.209332) renderer.GetActiveCamera().SetFocalPoint(15.500000, 15.500000, 2.000000) renderer.GetActiveCamera().SetViewUp(0.348057, -0.636740, 0.688055) renderer.ResetCameraClippingRange() renderWindow.Render() renderWindowInteractor.Start()
colors.InsertNextTupleValue(r) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(points) trianglePolyData.GetPointData().SetScalars(colors) trianglePolyData.SetPolys(triangles) # Clean the polydata so that the edges are shared ! cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInputData(trianglePolyData) # Use a filter to smooth the data (will add triangles and smooth) smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(3) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort()) # Create a mapper and actor for smoothed dataset mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(smooth_loop.GetOutputPort()) actor_loop = vtk.vtkActor() actor_loop.SetMapper(mapper) actor_loop.GetProperty().SetInterpolationToFlat() # Update the pipeline so that vtkCellLocator finds cells ! smooth_loop.Update() # Define a cellLocator to be able to compute intersections between lines # and the surface
faces.InsertNextCell(3) faces.InsertCellPoint(31) faces.InsertCellPoint(19) faces.InsertCellPoint(29) model = vtk.vtkPolyData() model.SetPolys(faces) model.SetPoints(points) # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) #vtkButterflySubdivisionFilter subdivide subdivide = vtk.vtkLoopSubdivisionFilter() subdivide.SetInputData(model) subdivide.SetNumberOfSubdivisions(4) mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(subdivide.GetOutputPort()) rose = vtk.vtkLODActor() rose.SetMapper(mapper) fe = vtk.vtkFeatureEdges() fe.SetInputConnection(subdivide.GetOutputPort()) fe.SetFeatureAngle(100) feMapper = vtk.vtkPolyDataMapper() feMapper.SetInputConnection(fe.GetOutputPort()) edges = vtk.vtkActor() edges.SetMapper(feMapper) # Add the actors to the renderer, set the background and size #
def createWallMesh(self, edgePolyData): numpy_coordinates = numpy_support.vtk_to_numpy( edgePolyData.GetPoints().GetData()) print('size=', numpy_coordinates.shape, numpy_coordinates.size) # print(numpy_coordinates) originPointCount = int(numpy_coordinates.shape[0]) edgePolyData.GetLines().InitTraversal() pointIdLink = [-1] * edgePolyData.GetNumberOfLines() idList = vtk.vtkIdList() while edgePolyData.GetLines().GetNextCell(idList): if pointIdLink[idList.GetId(0)] != -1: print("line from id {} already assign!!".format( idList.GetId(0))) else: pointIdLink[idList.GetId(0)] = idList.GetId(1) pointIdList = [0] while pointIdLink[pointIdList[-1]] != 0 and pointIdLink[ pointIdList[-1]] != 1: next = pointIdLink[pointIdList[-1]] pointIdList.append(next) print(len(pointIdList)) t = 1000 polyPoints = vtk.vtkPoints() polyPoints.DeepCopy(edgePolyData.GetPoints()) points = list(range(originPointCount)) appear = [] for i in range(t): while True: random.shuffle(points) avgp = (numpy_coordinates[points[0]] + numpy_coordinates[points[1]] + numpy_coordinates[points[2]]) / 3 h = hash(str(avgp)) if h not in appear: polyPoints.InsertPoint(originPointCount + i, avgp) appear.append(h) break originData = vtk.vtkPolyData() originData.SetPoints(polyPoints) constrain = vtk.vtkPolyData() constrain.SetPoints(polyPoints) constrain.SetPolys(vtk.vtkCellArray()) delaunayFilter = vtk.vtkDelaunay2D() delaunayFilter.SetInputData(originData) delaunayFilter.SetSourceData(constrain) delaunayFilter.SetTolerance(0.01) delaunayFilter.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE) delaunayFilter.Update() cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputConnection(delaunayFilter.GetOutputPort()) cleanFilter.Update() smoothFilter = vtk.vtkSmoothPolyDataFilter() smoothFilter.SetInputConnection(cleanFilter.GetOutputPort()) smoothFilter.SetNumberOfIterations(200) smoothFilter.SetRelaxationFactor(0.05) smoothFilter.BoundarySmoothingOff() smoothFilter.Update() subdivisionFilter = vtk.vtkLoopSubdivisionFilter() subdivisionFilter.SetNumberOfSubdivisions(2) subdivisionFilter.SetInputConnection(smoothFilter.GetOutputPort()) subdivisionFilter.Update() return subdivisionFilter.GetOutput()
def vtk_mesh_subdivision(): """Subdivide a mesh into more triangles The subdivisions are increasing the faces by 4^# subdivisions """ # get the polydata for a mesh v, f = wavefront.ellipsoid_mesh(1, 2, 3, density=20) polydata = wavefront.meshtopolydata(v, f) # subdivide using appropriate filter smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(1) # can define the number of subdivisions smooth_loop.SetInputData(polydata) smooth_loop.Update() poly_loop = vtk.vtkPolyData() poly_loop.ShallowCopy(smooth_loop.GetOutput()) smooth_butterfly = vtk.vtkButterflySubdivisionFilter() smooth_butterfly.SetNumberOfSubdivisions(3) smooth_butterfly.SetInputData(polydata) smooth_butterfly.Update() poly_butterfly = vtk.vtkPolyData() poly_butterfly.ShallowCopy(smooth_butterfly.GetOutput()) # Create a mapper and actor for initial dataset mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polydata) actor = vtk.vtkActor() actor.SetMapper(mapper) # Create a mapper and actor for smoothed dataset (vtkLoopSubdivisionFilter) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(smooth_loop.GetOutputPort()) actor_loop = vtk.vtkActor() actor_loop.SetMapper(mapper) actor_loop.SetPosition(3, 0, 0) # Create a mapper and actor for smoothed dataset (vtkButterflySubdivisionFilter) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(smooth_butterfly.GetOutputPort()) actor_butterfly = vtk.vtkActor() actor_butterfly.SetMapper(mapper) actor_butterfly.SetPosition(6, 0, 0) # Visualise renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add actors and render renderer.AddActor(actor) renderer.AddActor(actor_loop) renderer.AddActor(actor_butterfly) renderer.SetBackground(1, 1, 1) # Background color white renderWindow.SetSize(800, 800) renderWindow.Render() renderWindowInteractor.Start() # output to a new v, f array # convert polydata to numpy v_loop, f_loop = wavefront.polydatatomesh(poly_loop) v_butterfly, f_butterfly = wavefront.polydatatomesh(poly_butterfly) print('Original #V : {} #F : {}'.format(v.shape[0], f.shape[0])) print('Loop #V : {} #F : {}'.format(v_loop.shape[0], f_loop.shape[0])) print('BFly #V : {} #F : {}'.format(v_butterfly.shape[0], f_butterfly.shape[0]))
def extract_slice_thickness(nsubdivision, domain, LVctr, RVctr, Epictr, verbose=True): refinedmesh = vtk.vtkLoopSubdivisionFilter() refinedmesh.SetNumberOfSubdivisions(nsubdivision) refinedmesh.SetInput(domain) refinedmesh.Update() featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInput(refinedmesh.GetOutput()) featureEdges.BoundaryEdgesOn() featureEdges.FeatureEdgesOff() featureEdges.ManifoldEdgesOff() featureEdges.NonManifoldEdgesOff() featureEdges.Update() connectfilter = vtk.vtkPolyDataConnectivityFilter() connectfilter.SetInput(featureEdges.GetOutput()) connectfilter.SetExtractionModeToSpecifiedRegions() connectfilter.Update() epi = vtk.vtkPolyData() LVendo = vtk.vtkPolyData() RVendo = vtk.vtkPolyData() #connectfilter.DeleteSpecifiedRegion(0) #connectfilter.DeleteSpecifiedRegion(1) #connectfilter.DeleteSpecifiedRegion(2) #connectfilter.AddSpecifiedRegion(0) connectfilter.SetExtractionModeToClosestPointRegion() connectfilter.SetClosestPoint(Epictr[0], Epictr[1], Epictr[2]) connectfilter.Update() epi.DeepCopy(connectfilter.GetOutput()) epi = clean_pdata(epi) #connectfilter.SetExtractionModeToSpecifiedRegions() #connectfilter.DeleteSpecifiedRegion(0) #connectfilter.AddSpecifiedRegion(1) connectfilter.SetClosestPoint(RVctr[0], RVctr[1], RVctr[2]) connectfilter.Update() RVendo.DeepCopy(connectfilter.GetOutput()) RVendo = clean_pdata(RVendo) #connectfilter.DeleteSpecifiedRegion(1) #connectfilter.AddSpecifiedRegion(2) connectfilter.SetClosestPoint(LVctr[0], LVctr[1], LVctr[2]) connectfilter.Update() LVendo.DeepCopy(connectfilter.GetOutput()) LVendo = clean_pdata(LVendo) epipointlocator = vtk.vtkPointLocator() epipointlocator.SetDataSet(epi) epipointlocator.BuildLocator() LVendopointlocator = vtk.vtkPointLocator() LVendopointlocator.SetDataSet(LVendo) LVendopointlocator.BuildLocator() RVendopointlocator = vtk.vtkPointLocator() RVendopointlocator.SetDataSet(RVendo) RVendopointlocator.BuildLocator() epidistance = vtk.vtkFloatArray() epidistance.SetName("Thickness") for p in range(0, epi.GetNumberOfPoints()): pt = epi.GetPoints().GetPoint(p) RVendoid = RVendopointlocator.FindClosestPoint(pt) RVendopt = RVendo.GetPoints().GetPoint(RVendoid) LVendoid = LVendopointlocator.FindClosestPoint(pt) LVendopt = LVendo.GetPoints().GetPoint(LVendoid) disttoRVendo = math.sqrt( vtk.vtkMath.Distance2BetweenPoints(pt, RVendopt)) disttoLVendo = math.sqrt( vtk.vtkMath.Distance2BetweenPoints(pt, LVendopt)) epidistance.InsertNextValue(min(disttoRVendo, disttoLVendo)) epi.GetPointData().SetActiveScalars("Thickness") epi.GetPointData().SetScalars(epidistance) return epi
def GenerateApex(input_filename, output_filename, sampling): """ Generate apex for the mesh. Assumes that the apex is in the end of the point list of the mesh input_filename string: vtk mesh to add apex to output_filename string: vtk file to store the result sampling int: number of vertices per layer Return nothing """ #input_filename = 'endo_mesh.vtk' #output_filename = 'endo_mesh_capped.vtk' #sampling = sampling_epi #read the mesh rdr = vtk.vtkPolyDataReader() rdr.SetFileName(input_filename) rdr.Update() mesh = rdr.GetOutput() meshpts = mytools.ExtractVTKPoints(mesh) meshfaces = mytools.ExtractVTKTriFaces(mesh) m, n = meshpts.shape #get the last 4 layers (after resampling they do not coincide with the MRI) pts = meshpts[-4 * sampling:, :] #mlab.points3d(pts[:,0],pts[:,1],pts[:,2], scale_mode='none', scale_factor=0.2 ) #assuming slices are along X axis #project points into YZ plane and use griddata to interpolate the third coordinate miny = pts[:, 1].min() maxy = pts[:, 1].max() minz = pts[:, 2].min() maxz = pts[:, 2].max() gx, gy = np.mgrid[miny:maxy:10j, minz:maxz:10j] grid = griddata(pts[:, 1:3], pts[:, 0], (gx, gy), method='cubic') #finished interpolating #get just the last slice for triangulation. We will add these to the new points and run triangulation pts_last = meshpts[-sampling:, :] #we also need to know if the coordinate is increasing or decreasing to keep only #those new points, that lie beyond the original mesh. Don't want any overlaps slice_coord_first = meshpts[0, 0] slice_coord_last = pts_last[0, 0] slices_increase = False if slice_coord_last > slice_coord_first: slices_increase = True #create a Nx3 array of grid points where we interpolated the x coordinate gridpts = np.column_stack((grid.flatten(), gx.flatten(), gy.flatten())) #leave only points beyond the current mesh if slices_increase: cover_pts = gridpts[gridpts[:, 0] > slice_coord_last + mindist, :] else: cover_pts = gridpts[gridpts[:, 0] < slice_coord_last - mindist, :] #combine generated points with the last slice and tirangulate tri = Delaunay(np.concatenate((pts_last[:, 1:3], cover_pts[:, 1:3]))) mergedpts = np.concatenate((meshpts, cover_pts)) capfaces = tri.simplices.copy() #eliminate faces that have only boundary points 0:sampling #sometimes the edges in the slice are curvy and there are triangles connecting #just the boundary points. We don't want to have them in the mesh, they will ruin everything. n1 = capfaces < sampling n2 = n1.all(axis=1) capfaces1 = capfaces[n2 == False, :] #the new points will be added to the end of the mesh points #so we need to update the faces to account for the new point ids. #Also we need to take into account that the first "sampling" points of the #generated apex are the last points of the mesh capfaces1 = capfaces1 + m - sampling allfaces = np.concatenate((meshfaces, capfaces1)) #concatenate faces #create polydata and save it pd = mytools.CreatePolyData(mergedpts, allfaces) if make_beautiful: ls = vtk.vtkLoopSubdivisionFilter() ls.SetInput(pd) ls.SetNumberOfSubdivisions(1) ls.Update() mytools.SaveVTKPolyData(ls.GetOutput(), output_filename) else: mytools.SaveVTKPolyData(pd, output_filename)
def extract_slice_thickness_LVonly(nsubdivision, domain, verbose=True): refinedmesh = vtk.vtkLoopSubdivisionFilter() refinedmesh.SetNumberOfSubdivisions(nsubdivision) refinedmesh.SetInput(domain) refinedmesh.Update() bds = domain.GetBounds() ctr = [0, 0, 0] ctr[0] = 0.5 * (bds[0] + bds[1]) ctr[1] = 0.5 * (bds[2] + bds[3]) ctr[2] = 0.5 * (bds[4] + bds[5]) featureEdges = vtk.vtkFeatureEdges() featureEdges.SetInput(refinedmesh.GetOutput()) featureEdges.BoundaryEdgesOn() featureEdges.FeatureEdgesOff() featureEdges.ManifoldEdgesOff() featureEdges.NonManifoldEdgesOff() featureEdges.Update() connectfilter = vtk.vtkPolyDataConnectivityFilter() connectfilter.SetInput(featureEdges.GetOutput()) connectfilter.SetExtractionModeToSpecifiedRegions() connectfilter.Update() epi = vtk.vtkPolyData() LVendo = vtk.vtkPolyData() connectfilter.SetExtractionModeToClosestPointRegion() connectfilter.SetClosestPoint(ctr[0], ctr[1] + 1000, ctr[2] + 1000) connectfilter.Update() epi.DeepCopy(connectfilter.GetOutput()) epi = clean_pdata(epi) connectfilter.SetClosestPoint(ctr[0], ctr[1], ctr[2]) connectfilter.Update() LVendo.DeepCopy(connectfilter.GetOutput()) LVendo = clean_pdata(LVendo) epipointlocator = vtk.vtkPointLocator() epipointlocator.SetDataSet(epi) epipointlocator.BuildLocator() LVendopointlocator = vtk.vtkPointLocator() LVendopointlocator.SetDataSet(LVendo) LVendopointlocator.BuildLocator() epidistance = vtk.vtkFloatArray() epidistance.SetName("Thickness") for p in range(0, epi.GetNumberOfPoints()): pt = epi.GetPoints().GetPoint(p) LVendoid = LVendopointlocator.FindClosestPoint(pt) LVendopt = LVendo.GetPoints().GetPoint(LVendoid) disttoLVendo = math.sqrt( vtk.vtkMath.Distance2BetweenPoints(pt, LVendopt)) epidistance.InsertNextValue(disttoLVendo) epi.GetPointData().SetActiveScalars("Thickness") epi.GetPointData().SetScalars(epidistance) return epi
def create_surface(): path_directory = 'PATH2D/' #elevation_data = np.loadtxt(path_directory + 'Ground_Rock2D.txt', delimiter = ',') topography = np.loadtxt(path_directory + 'Ground_Rock2D_2.txt') # topography *= 10 #elevation_data = elevation_data[:,1] #elevation_data *= 100 #width = elevation_data.shape[0] #width = 30 #topography = np.repeat(elevation_data, width).reshape((width, elevation_data.shape[0])) m = topography.shape[0] n = topography.shape[1] # Define points, triangles and colors points = vtk.vtkPoints() triangles = vtk.vtkCellArray() # Build the meshgrid manually count = 0 for i in range(m-1): for j in range(n-1): z1 = topography[i][j] z2 = topography[i][j+1] z3 = topography[i+1][j] # Triangle 1 points.InsertNextPoint(i, j, z1) points.InsertNextPoint(i, (j+1), z2) points.InsertNextPoint((i+1), j, z3) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count) triangle.GetPointIds().SetId(1, count + 1) triangle.GetPointIds().SetId(2, count + 2) triangles.InsertNextCell(triangle) z1 = topography[i][j+1] z2 = topography[i+1][j+1] z3 = topography[i+1][j] # Triangle 2 points.InsertNextPoint(i, (j+1), z1) points.InsertNextPoint((i+1), (j+1), z2) points.InsertNextPoint((i+1), j, z3) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count + 3) triangle.GetPointIds().SetId(1, count + 4) triangle.GetPointIds().SetId(2, count + 5) count += 6 triangles.InsertNextCell(triangle) # Create a polydata object trianglePolyData = vtk.vtkPolyData() # Add the geometry and topology to the polydata trianglePolyData.SetPoints(points) #trianglePolyData.GetPointData().SetScalars(colors) trianglePolyData.SetPolys(triangles) # Clean the polydata so that the edges are shared ! cleanPolyData = vtk.vtkCleanPolyData() cleanPolyData.SetInputData(trianglePolyData) # Use a filter to smooth the data (will add triangles and smooth) smooth_loop = vtk.vtkLoopSubdivisionFilter() smooth_loop.SetNumberOfSubdivisions(3) smooth_loop.SetInputConnection(cleanPolyData.GetOutputPort()) # Create a mapper and actor for smoothed dataset mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(smooth_loop.GetOutputPort()) actor_loop = vtk.vtkActor() actor_loop.SetMapper(mapper) actor_loop.GetProperty().SetInterpolationToFlat() # Update the pipeline so that vtkCellLocator finds cells ! smooth_loop.Update() # Define a cellLocator to be able to compute intersections between lines # and the surface locator = vtk.vtkCellLocator() locator.SetDataSet(smooth_loop.GetOutput()) locator.BuildLocator() transform = vtk.vtkTransform() transform.Scale((0.06, 1, 1)) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetTransform(transform) actor_loop.SetUserTransform(transform) # Visualize # renderer = vtk.vtkRenderer() # renderWindow = vtk.vtkRenderWindow() # renderWindow.AddRenderer(renderer) # renderWindowInteractor = vtk.vtkRenderWindowInteractor() # renderWindowInteractor.SetRenderWindow(renderWindow) return actor_loop # Add actors and render # renderer.AddActor(actor_loop) # # renderer.SetBackground(1, 1, 1) # Background color white # renderWindow.SetSize(800, 800) # renderWindow.Render() # renderWindowInteractor.Start()
def GenerateApex(input_filename, output_filename, sampling): """ Generate apex for the mesh. Assumes that the apex is in the end of the point list of the mesh input_filename string: vtk mesh to add apex to output_filename string: vtk file to store the result sampling int: number of vertices per layer Return nothing """ #input_filename = 'endo_mesh.vtk' #output_filename = 'endo_mesh_capped.vtk' #sampling = sampling_epi #read the mesh rdr = vtk.vtkPolyDataReader() rdr.SetFileName(input_filename) rdr.Update() mesh = rdr.GetOutput() meshpts = mytools.ExtractVTKPoints(mesh) meshfaces = mytools.ExtractVTKTriFaces(mesh) m, n = meshpts.shape #get the last 4 layers (after resampling they do not coincide with the MRI) pts = meshpts[-4*sampling:,:] #mlab.points3d(pts[:,0],pts[:,1],pts[:,2], scale_mode='none', scale_factor=0.2 ) #assuming slices are along X axis #project points into YZ plane and use griddata to interpolate the third coordinate miny = pts[:,1].min() maxy = pts[:,1].max() minz = pts[:,2].min() maxz = pts[:,2].max() gx, gy = np.mgrid[miny:maxy:10j, minz:maxz:10j] grid = griddata(pts[:,1:3],pts[:,0],(gx,gy),method = 'cubic') #finished interpolating #get just the last slice for triangulation. We will add these to the new points and run triangulation pts_last = meshpts[-sampling:,:] #we also need to know if the coordinate is increasing or decreasing to keep only #those new points, that lie beyond the original mesh. Don't want any overlaps slice_coord_first = meshpts[0,0] slice_coord_last = pts_last[0,0] slices_increase = False if slice_coord_last > slice_coord_first: slices_increase = True #create a Nx3 array of grid points where we interpolated the x coordinate gridpts = np.column_stack( (grid.flatten(),gx.flatten(),gy.flatten()) ) #leave only points beyond the current mesh if slices_increase: cover_pts = gridpts[gridpts[:,0]>slice_coord_last+mindist,:] else : cover_pts = gridpts[gridpts[:,0]<slice_coord_last-mindist,:] #combine generated points with the last slice and tirangulate tri = Delaunay( np.concatenate( (pts_last[:,1:3], cover_pts[:,1:3]) ) ) mergedpts = np.concatenate( (meshpts, cover_pts) ) capfaces = tri.simplices.copy() #eliminate faces that have only boundary points 0:sampling #sometimes the edges in the slice are curvy and there are triangles connecting #just the boundary points. We don't want to have them in the mesh, they will ruin everything. n1 = capfaces<sampling n2 = n1.all(axis=1) capfaces1 = capfaces[ n2==False, : ] #the new points will be added to the end of the mesh points #so we need to update the faces to account for the new point ids. #Also we need to take into account that the first "sampling" points of the #generated apex are the last points of the mesh capfaces1 = capfaces1 + m - sampling allfaces = np.concatenate( (meshfaces, capfaces1)) #concatenate faces #create polydata and save it pd = mytools.CreatePolyData(mergedpts,allfaces) if make_beautiful: ls = vtk.vtkLoopSubdivisionFilter() ls.SetInput(pd) ls.SetNumberOfSubdivisions(1) ls.Update() mytools.SaveVTKPolyData(ls.GetOutput(),output_filename) else: mytools.SaveVTKPolyData(pd,output_filename)