def create_mesh_and_save(cloud): filename = "object.stl" vtk_points = vtk.vtkPoints() np_cloud = np.asarray(cloud) for i in range(0, np_cloud.shape[0]): vtk_points.InsertPoint(i, np_cloud[i][0], np_cloud[i][1], np_cloud[i][2]) profile = vtk.vtkPolyData() profile.SetPoints(vtk_points) aCellArray = vtk.vtkCellArray() boundary = vtk.vtkPolyData() boundary.SetPoints(profile.GetPoints()) boundary.SetPolys(aCellArray) delny = vtk.vtkDelaunay2D() delny.SetInputData(profile) delny.SetSourceData(boundary) delny.SetTolerance(0.0001) delny.SetAlpha(4.0) delny.SetOffset(1.25) delny.BoundingTriangulationOff() delny.Update() stl_writer = vtk.vtkSTLWriter() stl_writer.SetFileName(filename) stl_writer.SetInputConnection(delny.GetOutputPort()) stl_writer.Write()
def __init__(self, pd, val, alpha=0): self.loc = vtk.vtkCellLocator() self.loc = vtk.vtkModifiedBSPTree() arr_crd_2d = pd.GetPointData().GetArray('2Dcrds') pts = vtk.vtkPoints() for kp in range(pd.GetNumberOfPoints()): p = pd.GetPoint(kp) crd_2D = arr_crd_2d.GetTuple(kp) pts.InsertNextPoint(crd_2D[0], crd_2D[1], 0) pd.SetPoints(pts) del2d = vtk.vtkDelaunay2D() del2d.SetInputData(pd) del2d.SetTolerance(0) if alpha > 0: del2d.SetAlpha(alpha) del2d.Update() self.pd2 = del2d.GetOutput() ## w = vtk.vtkXMLPolyDataWriter() ## w.SetFileName('del.vtp') ## w.SetInputData(self.pd2) ## w.Write() ## sys.exit(0) self.loc.SetDataSet(self.pd2) self.loc.BuildLocator() self.values = val
def render_image(pointset): delaunay = vtk.vtkDelaunay2D() delaunay.SetTolerance(0.001) delaunay.SetAlpha(18) delaunay.SetInput(pointset); delaunay.Update(); meshMapper = vtk.vtkPolyDataMapper() meshMapper.SetInput(delaunay.GetOutput()) meshMapper.SetScalarRange(0,255) meshActor = vtk.vtkActor() meshActor.SetMapper(meshMapper) boundaryMapper = vtk.vtkPolyDataMapper() boundaryMapper.SetInput(delaunay.GetOutput()) boundaryActor = vtk.vtkActor() boundaryActor.SetMapper(boundaryMapper); boundaryActor.GetProperty().SetColor(0,0.55,0); renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(meshActor) renderer.AddActor(boundaryActor) renderer.SetBackground(.5, .5, .5) renderWindow.SetSize(600, 600) renderWindow.Render() renderWindowInteractor.Start()
def update(self): delaunay = vtkDelaunay2D() delaunay.SetInput(self.input_) delaunay.SetTolerance(self.tolerance) delaunay.SetAlpha(self.alpha) delaunay.Update() self.output_ = delaunay.GetOutput()
def delaunay2D(self): print("start generate mesh") boundary = vtk.vtkPolyData() boundary.SetPoints(self.vtkPolyData.GetPoints()) aCellArray = vtk.vtkCellArray() boundary.SetPolys(aCellArray) delaunay = vtk.vtkDelaunay2D() delaunay.SetSourceData(boundary) delaunay.SetInputData(self.vtkPolyData) delaunay.Update() print("finish delaunay") meshMapper = vtk.vtkPolyDataMapper() meshMapper.SetInputConnection(delaunay.GetOutputPort()) meshMapper.SetLookupTable(self.lut) meshMapper.SetScalarVisibility(1) meshMapper.SetUseLookupTableScalarRange(True) self.vtkActor = vtk.vtkActor() self.vtkActor.SetMapper(meshMapper) self.vtkActor.GetProperty().SetEdgeColor(0, 0, 1) self.vtkActor.GetProperty().SetInterpolationToFlat() self.vtkActor.GetProperty().SetRepresentationToWireframe() boundaryMapper = vtk.vtkPolyDataMapper() boundaryMapper.SetInputData(boundary) boundaryActor = vtk.vtkActor() boundaryActor.SetMapper(boundaryMapper) boundaryActor.GetProperty().SetColor(1, 0, 0) self.boundaryActor = vtk.vtkActor()
def overlay_polygon_internal(self, coords, height, colour): """Add a polygon to the output of the visualiser. coords is a list of 2-tuples representing x and y coordinates. These are triangulated by vtkDelaunay2D. height is the z-value given to all points. colour is the colour of the polygon, as a 3-tuple representing r, g, b values between 0 and 1. This function should not be called from outside the visualiser thread. Use overlay_polygon instead. """ points = vtkPoints() for coord in coords: points.InsertNextPoint(coord[0], coord[1], height) profile = vtkPolyData() profile.SetPoints(points) delny = vtkDelaunay2D() delny.SetInput(profile) mesh = vtkPolyDataMapper() mesh.SetInput(delny.GetOutput()) actor = vtkActor() actor.SetMapper(mesh) actor.GetProperty().SetColor(colour) self.vtk_renderer.AddActor(actor)
def delauney(polydata): """Run a delauney filter on a dataset""" alg = vtk.vtkDelaunay2D() alg.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE) alg.SetInputDataObject(polydata) alg.Update() return vtki.wrap(alg.GetOutputDataObject(0))
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkDelaunay2D(), 'Processing.', ('vtkPointSet', 'vtkPolyData'), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def render_image(pointset): delaunay = vtk.vtkDelaunay2D() delaunay.SetTolerance(0.001) delaunay.SetAlpha(18) delaunay.SetInput(pointset) delaunay.Update() meshMapper = vtk.vtkPolyDataMapper() meshMapper.SetInput(delaunay.GetOutput()) meshMapper.SetScalarRange(0, 255) meshActor = vtk.vtkActor() meshActor.SetMapper(meshMapper) boundaryMapper = vtk.vtkPolyDataMapper() boundaryMapper.SetInput(delaunay.GetOutput()) boundaryActor = vtk.vtkActor() boundaryActor.SetMapper(boundaryMapper) boundaryActor.GetProperty().SetColor(0, 0.55, 0) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(meshActor) renderer.AddActor(boundaryActor) renderer.SetBackground(.5, .5, .5) renderWindow.SetSize(600, 600) renderWindow.Render() renderWindowInteractor.Start()
def update(self): delaunay = vtkDelaunay2D() delaunay.SetInputData(self.input_) delaunay.SetTolerance(self.tolerance) delaunay.SetAlpha(self.alpha) delaunay.Update() self.output_ = delaunay.GetOutput()
def main(): colors = vtk.vtkNamedColors() # Create points on an XY grid with random Z coordinate points = vtk.vtkPoints() gridSize = 10 seed = 0 randomSequence = vtk.vtkMinimalStandardRandomSequence() randomSequence.Initialize(seed) for x in range(0, gridSize): for y in range(0, gridSize): d = randomSequence.GetValue() randomSequence.Next() points.InsertNextPoint(x, y, d * 3) # Add the grid points to a polydata object polydata = vtk.vtkPolyData() polydata.SetPoints(points) glyphFilter = vtk.vtkVertexGlyphFilter() glyphFilter.SetInputData(polydata) glyphFilter.Update() # Create a mapper and actor pointsMapper = vtk.vtkPolyDataMapper() pointsMapper.SetInputConnection(glyphFilter.GetOutputPort()) pointsActor = vtk.vtkActor() pointsActor.SetMapper(pointsMapper) pointsActor.GetProperty().SetPointSize(3) pointsActor.GetProperty().SetColor(colors.GetColor3d("Red")) # Triangulate the grid points delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(polydata) delaunay.Update() # Create a mapper and actor triangulatedMapper = vtk.vtkPolyDataMapper() triangulatedMapper.SetInputConnection(delaunay.GetOutputPort()) triangulatedActor = vtk.vtkActor() triangulatedActor.SetMapper(triangulatedMapper) # Create a renderer, render window, and interactor renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) # Add the actor to the scene renderer.AddActor(pointsActor) renderer.AddActor(triangulatedActor) renderer.SetBackground(colors.GetColor3d("Green")) # Background color green # Render and interact renderWindow.SetWindowName('TriangulateTerrainMap') renderWindow.Render() renderWindowInteractor.Start()
def addArray2d(self,x,y,zz,mode='real'): if mode == 'square': xr=x.max()-x.min() yr=y.max()-y.min() xmul=1.0 ymul=1.0 if xr >= yr: ymul=xr/yr if xr <= yr: xmul=yr/xr x*=xmul y*=ymul points = vtk.vtkPoints(); for i in range(y.shape[0]): for j in range(x.shape[0]): points.InsertNextPoint(x[j], y[i], zz[i][j]*self.scalingFactor); inputPolyData = vtk.vtkPolyData(); inputPolyData.SetPoints(points); delaunay = vtk.vtkDelaunay2D() delaunay.SetTolerance(0.000001) delaunay.SetInput(inputPolyData); delaunay.Update(); outputPolyData = delaunay.GetOutput(); bounds=outputPolyData.GetBounds(); minz = bounds[4]; maxz = bounds[5]; self.lut=vtk.vtkLookupTable() self.lut.SetNumberOfTableValues(100) self.lut.SetTableRange(minz, maxz) self.lut.SetHueRange(0.667, 0.0) self.lut.Build() colors=vtk.vtkFloatArray() for i in range(0,outputPolyData.GetNumberOfPoints()): colors.InsertNextValue(outputPolyData.GetPoint(i)[2]) outputPolyData.GetPointData().SetScalars(colors); self.outputs.append(outputPolyData) mapper = vtk.vtkPolyDataMapper(); mapper.SetLookupTable(self.lut) mapper.InterpolateScalarsBeforeMappingOn() mapper.SetInputConnection(outputPolyData.GetProducerPort()) mapper.SetScalarModeToUsePointData() mapper.ScalarVisibilityOn(); mapper.SetScalarRange(colors.GetRange()) surfaceActor = vtk.vtkActor(); surfaceActor.SetMapper(mapper); self.boundBox=bounds self.ren.AddActor(surfaceActor);
def vtkPolySurface(Data=None, names=None): x_, y_, z_ = 0, 1, 2 # ------------------------------------------------- # # --- [1] Arguments Check --- # # ------------------------------------------------- # if (Data is None): sys.exit("[vtkPolySurface] Data == ???") nComponents = Data.shape[1] if (nComponents == 3): coordinates = np.copy(Data[:, x_:z_ + 1]) scholars = np.reshape(Data[:, z_], (Data.shape[0], 1)) if (nComponents >= 4): coordinates = np.copy(Data[:, x_:z_ + 1]) scholars = np.copy(Data[:, z_ + 1:]) nScholars = scholars.shape[1] if (names is None): names = ["Data{0:02}".format(ik + 1) for ik in range(nScholars)] if (len(names) != nScholars): print( "[convert__vtkPolySurface] unmatched names & Data size .... [ERROR] " ) print("[convert__vtkPolySurface] Data size :: {0} ".format(Data.shape)) print("[convert__vtkPolySurface] names :: {0} ".format(names)) # ------------------------------------------------- # # --- [2] Coordinates Points Settings --- # # ------------------------------------------------- # # -- [2-1] Coordinates Points -- # coordinates_ = vtknp.numpy_to_vtk(coordinates, deep=True) points = vtk.vtkPoints() points.SetData(coordinates_) # -- [2-2] define PolyData / CellDataArray -- # polyData = vtk.vtkPolyData() polyData.SetPoints(points) cellArray = vtk.vtkCellArray() # -- [2-3] assign pointData to polyData -- # for ik in range(nScholars): pointData_ = vtknp.numpy_to_vtk(scholars[:, ik], deep=True) pointData_.SetName(names[ik]) polyData.GetPointData().AddArray(pointData_) # -- [2-4] boundary for Delaunay2D -- # boundary = vtk.vtkPolyData() boundary.SetPoints(polyData.GetPoints()) boundary.SetPolys(cellArray) # ------------------------------------------------- # # --- [3] Delaunay triangulation --- # # ------------------------------------------------- # delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(polyData) delaunay.SetSourceData(boundary) delaunay.Update() # ------------------------------------------------- # # --- [4] return polyData --- # # ------------------------------------------------- # return (delaunay.GetOutput())
def createSectionPolygon(self, element): outer_points, inner_points = element.cross_section.get_cross_section_points( element.length) number_inner_points = len(inner_points) number_outer_points = len(outer_points) # definitions points = vtk.vtkPoints() outerData = vtk.vtkPolyData() innerPolygon = vtk.vtkPolygon() innerCell = vtk.vtkCellArray() innerData = vtk.vtkPolyData() delaunay = vtk.vtkDelaunay2D() outerPolygon = vtk.vtkPolygon() edges = vtk.vtkCellArray() data = vtk.vtkPolyData() source = vtk.vtkTriangleFilter() #TODO: create points - check the axis alignments - older version (0, y, z) for y, z in inner_points: points.InsertNextPoint(y, z, 0) for y, z in outer_points: points.InsertNextPoint(y, z, 0) # create external polygon outerData.SetPoints(points) delaunay.SetInputData(outerData) if number_inner_points >= 3: # remove inner area for holed sections for i in range(number_inner_points): innerPolygon.GetPointIds().InsertNextId(i) innerCell.InsertNextCell(innerPolygon) innerData.SetPoints(points) innerData.SetPolys(innerCell) delaunay.SetSourceData(innerData) delaunay.Update() return delaunay else: outerPolygon.GetPointIds().SetNumberOfIds(number_outer_points) for i in range(number_outer_points): outerPolygon.GetPointIds().SetId(i, i) edges.InsertNextCell(outerPolygon) data.SetPoints(points) data.SetPolys(edges) source.AddInputData(data) return source
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkDelaunay2D(), 'Processing.', ('vtkPointSet', 'vtkPolyData'), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def create_delaunay(poly_data): """create 2D delunay""" print("starting delaunay") delaunay = vtk.vtkDelaunay2D() print("ending delaunay") delaunay.SetInputData(poly_data) delaunay.Update() return delaunay
def delaunay2D(polydata): delny = vtk.vtkDelaunay2D() delny.SetInputData(polydata) delny.SetTolerance(0.1) delny.SetAlpha(0.0) delny.BoundingTriangulationOff() delny.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE) delny.Update() return delny.GetOutput()
def main(): colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor("BkgColor", [0.3, 0.6, 0.3, 1.0]) points = vtk.vtkPoints() for x in range(10): for y in range(10): points.InsertNextPoint(x + random.uniform(-.25, .25), y + random.uniform(-.25, .25), 0) aPolyData = vtk.vtkPolyData() aPolyData.SetPoints(points) aCellArray = vtk.vtkCellArray() boundary = vtk.vtkPolyData() boundary.SetPoints(aPolyData.GetPoints()) boundary.SetPolys(aCellArray) delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(aPolyData) delaunay.SetSourceData(boundary) delaunay.Update() meshMapper = vtk.vtkPolyDataMapper() meshMapper.SetInputConnection(delaunay.GetOutputPort()) meshActor = vtk.vtkActor() meshActor.SetMapper(meshMapper) meshActor.GetProperty().SetEdgeColor(colors.GetColor3d("Blue")) meshActor.GetProperty().SetInterpolationToFlat() meshActor.GetProperty().SetRepresentationToWireframe() boundaryMapper = vtk.vtkPolyDataMapper() boundaryMapper.SetInputData(boundary) boundaryActor = vtk.vtkActor() boundaryActor.SetMapper(boundaryMapper) boundaryActor.GetProperty().SetColor(colors.GetColor3d("Red")) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(meshActor) renderer.AddActor(boundaryActor) renderer.SetBackground(colors.GetColor3d("BkgColor")) renderWindowInteractor.Initialize() renderWindow.Render() renderWindowInteractor.Start()
def set_scalar_data(input_scalar, poly_data): """set the dalaunay as scalar data""" warp_delaunay = vtk.vtkDelaunay2D() warp_delaunay.SetInputConnection(input_scalar.GetOutputPort()) warp_delaunay.GetPolyDataInput(0).GetPointData().SetScalars( poly_data.GetPointData().GetScalars() ) # set the amplitude as scalar data warp_delaunay.Update() # gets elevation color+elevation surface return warp_delaunay
def applyDelaunay2D(mat): points = vtk.vtkPoints() i = 0 for x, y ,z in mat: points.InsertPoint(i, x, y ,z) i+=1 profile = vtk.vtkPolyData() profile.SetPoints(points) delny = vtk.vtkDelaunay2D() delny.SetInput(profile) delny.Update() return delny
def main(): colors = vtk.vtkNamedColors() # Create a set of heights on a grid. # This is often called a "terrain map". points = vtk.vtkPoints() gridSize = 10 for x in range(gridSize): for y in range(gridSize): points.InsertNextPoint(x, y, int((x + y) / (y + 1))) # Add the grid points to a polydata object polydata = vtk.vtkPolyData() polydata.SetPoints(points) delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(polydata) # Visualize meshMapper = vtk.vtkPolyDataMapper() meshMapper.SetInputConnection(delaunay.GetOutputPort()) meshActor = vtk.vtkActor() meshActor.SetMapper(meshMapper) meshActor.GetProperty().SetColor(colors.GetColor3d('Banana')) meshActor.GetProperty().EdgeVisibilityOn() glyphFilter = vtk.vtkVertexGlyphFilter() glyphFilter.SetInputData(polydata) pointMapper = vtk.vtkPolyDataMapper() pointMapper.SetInputConnection(glyphFilter.GetOutputPort()) pointActor = vtk.vtkActor() pointActor.GetProperty().SetColor(colors.GetColor3d('Tomato')) pointActor.GetProperty().SetPointSize(5) pointActor.SetMapper(pointMapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(meshActor) renderer.AddActor(pointActor) renderer.SetBackground(colors.GetColor3d('Mint')) renderWindowInteractor.Initialize() renderWindow.SetWindowName('Delaunay2D') renderWindow.Render() renderWindowInteractor.Start()
def delaunaytriang(points_xyz): vtk_points = vtkPoints() for point_xyz in points_xyz: x, y, z = point_xyz vtk_points.InsertNextPoint(x, y, z) inputPolyData = vtkPolyData() inputPolyData.SetPoints(vtk_points) delny = vtkDelaunay2D() delny.SetInputData(inputPolyData) delny.Update() return delny
def generate__surfacePolyData( self, tag=None ): # ------------------------------------------------- # # --- [1] Arguments Check --- # # ------------------------------------------------- # if ( tag is None ): sys.exit( "[convert__pointData2vtu -@vtkDataManager-] tag == ???" ) if ( self.Data[tag].fieldData is None ): self.Data[tag].generate__fieldData() if ( self.Data[tag].coordinateData is None ): self.Data[tag].generate__coordinateData() # ------------------------------------------------- # # --- [2] Coordinates Points Settings --- # # ------------------------------------------------- # # -- [2-1] Coordinates Points -- # coordinates_ = vtknp.numpy_to_vtk( self.Data[tag].coordinateData, deep=True ) points = vtk.vtkPoints() points.SetData( coordinates_ ) # -- [2-2] define PolyData / CellDataArray -- # self.pData = vtk.vtkPolyData() self.pData.SetPoints( points ) cellArray = vtk.vtkCellArray() # -- [2-3] assign pointData to polyData -- # for ik in range( self.Data[tag].nFields ): pointData_ = vtknp.numpy_to_vtk( self.Data[tag].fieldData[:,ik], deep=True ) pointData_.SetName( self.Data[tag].fieldLabel[ik] ) self.pData.GetPointData().AddArray( pointData_ ) # -- [2-4] boundary for Delaunay2D -- # boundary = vtk.vtkPolyData() boundary.SetPoints( self.pData.GetPoints() ) boundary.SetPolys ( cellArray ) # ------------------------------------------------- # # --- [3] Delaunay triangulation --- # # ------------------------------------------------- # delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData ( self.pData ) delaunay.SetSourceData( boundary ) delaunay.Update() # ------------------------------------------------- # # --- [4] save in vtu File --- # # ------------------------------------------------- # writer = vtk.vtkXMLPolyDataWriter() if ( self.DataFormat.lower() == "ascii" ): writer.SetDataModeToAscii() if ( self.DataFormat.lower() == "binary" ): writer.SetDataModeToBinary() writer.SetFileName( self.vtkFile ) writer.SetInputData( delaunay.GetOutput() ) writer.Write() print( "[vtkDataConverter] output :: {0} ".format( self.vtkFile ) )
def vtkpoints(points, color=None, radius=None): # Create a polydata with the points we just created. profile = vtk.vtkPolyData() profile.SetPoints(points) # Perform a 2D Delaunay triangulation on them. delny = vtk.vtkDelaunay2D() delny.SetInput(profile) delny.SetTolerance(0.001) mapMesh = vtk.vtkPolyDataMapper() mapMesh.SetInputConnection(delny.GetOutputPort()) meshActor = vtk.vtkActor() meshActor.SetMapper(mapMesh) meshActor.GetProperty().SetColor(0.1, 0.2, 0.1) # We will now create a nice looking mesh by wrapping the edges in tubes, # and putting fat spheres at the points. extract = vtk.vtkExtractEdges() extract.SetInputConnection(delny.GetOutputPort()) ball = vtk.vtkSphereSource() if radius == None: rad = 0.002 else: rad = radius print rad ball.SetRadius(rad) ball.SetThetaResolution(50) ball.SetPhiResolution(5) balls = vtk.vtkGlyph3D() balls.SetInputConnection(delny.GetOutputPort()) balls.SetSourceConnection(ball.GetOutputPort()) mapBalls = vtk.vtkPolyDataMapper() mapBalls.SetInputConnection(balls.GetOutputPort()) ballActor = vtk.vtkActor() ballActor.SetMapper(mapBalls) if color == None: ballcolor = red else: ballcolor = color print "setting ball color to...", ballcolor ballActor.GetProperty().SetColor(ballcolor) ballActor.GetProperty().SetSpecularColor(0, 0, 0) ballActor.GetProperty().SetSpecular(0.3) ballActor.GetProperty().SetSpecularPower(500) ballActor.GetProperty().SetAmbient(0.2) ballActor.GetProperty().SetDiffuse(0.8) return ballActor, profile
def createDEM_v1(): ds = xr.open_dataset('../data/output/Peru_20160601-20180530_comp4.nc') points = vtk.vtkPoints() numPoints = ds.south_north.size * ds.west_east.size print('Write points \n') for i, j in product(ds.south_north.values, ds.west_east.values): points.InsertNextPoint( ds.lat.isel(south_north=i, west_east=j), ds.lon.isel(south_north=i, west_east=j), ds.HGT.isel(south_north=i, west_east=j).values / 6370000.0) print('Create unstructured grid \n') polydata = vtk.vtkPolyData() polydata.SetPoints(points) delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(polydata) delaunay.Update() # subdivision = vtk.vtkButterflySubdivisionFilter() # subdivision.SetInputConnection(delaunay.GetOutputPort()) # subdivision.Update() #smoother = vtk.vtkWindowedSincPolyDataFilter() #smoother.SetInputConnection(delaunay.GetOutputPort()) #smoother.SetNumberOfIterations(5) #smoother.BoundarySmoothingOff() #smoother.FeatureEdgeSmoothingOff() #smoother.SetFeatureAngle(120.0) #smoother.SetPassBand(.001) #smoother.NonManifoldSmoothingOff() #smoother.NormalizeCoordinatesOff() #smoother.Update() appendFilter = vtk.vtkAppendFilter() appendFilter.AddInputData(delaunay.GetOutput()) appendFilter.Update() unstructuredGrid = vtk.vtkUnstructuredGrid() unstructuredGrid.ShallowCopy(appendFilter.GetOutput()) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName('cosipy.vtu') writer.SetInputData(unstructuredGrid) writer.Write()
def tessellation_callback(tessellation, size_of_cell1, tolerance1): input_data = tessellation.GetPolyDataInput() output_data = tessellation.GetPolyDataOutput() output_data.ShallowCopy(input_data) # Triangulate Surface. triangle_data = vtk.vtkTriangleFilter() triangle_data.SetInputData(output_data) triangle_data.Update() triangulated_model = triangle_data.GetOutput() number_of_polys = triangulated_model.GetNumberOfPolys() append_filter = vtk.vtkAppendPolyData() # Iterate over triangles. for i in range(0, 40): # Apply point generation filter. cell_index = i point_generation = vtk.vtkProgrammableFilter() point_generation.AddInputData(triangulated_model) point_generation.SetExecuteMethod( pointGenerationFilterBase.point_generation_callback( point_generation, cell_index, size_of_cell1)) current_polydata = point_generation.GetPolyDataOutput() # Append current triangulation polyData to total model polyData. append_filter.AddInputData(current_polydata) append_filter.Update() # Triangulate current cells generated points. delaunay2D = vtk.vtkDelaunay2D() delaunay2D.SetInputData(append_filter.GetOutput()) delaunay2D.SetSourceData(append_filter.GetOutput()) delaunay2D.SetTolerance(tolerance1) delaunay2D.Update() # Remove degenerate triangles and remove duplicate points. cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(delaunay2D.GetOutput()) cleaner.Update() polygonation = vtk.vtkProgrammableFilter() polygonation.AddInputData(cleaner.GetOutput()) polygonation.SetExecuteMethod( polygonation3DBase.polygonation_callback(polygonation)) output_data.SetPolys(polygonation.GetOutput().GetPolys()) output_data.SetPoints(polygonation.GetOutput().GetPoints())
def delaunay2D(plist, tol=None, c='gold', alpha=0.5, wire=False, bc=None, edges=False, legend=None, texture=None): ''' Create a mesh from points in the XY plane. ''' src = vtk.vtkPointSource() src.SetNumberOfPoints(len(plist)) src.Update() pd = src.GetOutput() for i,p in enumerate(plist): pd.GetPoints().SetPoint(i, p) delny = vtk.vtkDelaunay2D() vu.setInput(delny, pd) if tol: delny.SetTolerance(tol) delny.Update() return vu.makeActor(delny.GetOutput(), c, alpha, wire, bc, edges, legend, texture)
def convert_pts_to_mesh(polydata): # aCellArray = vtk.vtkCellArray() boundary = vtk.vtkPolyData() boundary.SetPoints(polydata.GetPoints()) # boundary.SetPolys(aCellArray) delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(polydata) delaunay.SetSourceData(boundary) delaunay.Update() result_polydata = delaunay.GetOutput() return result_polydata
def render_image(pointset): ''' square = 10 color_map = vtk.vtkLookupTable() color_map.SetNumberOfColors(square * square) color_map.SetTableRange(0, square * square - 1) for ii in range(0, square): for jj in range(0, square): color_map.SetTableValue(ii, jj / square, jj / square, ii /square) ''' color_map = vtk.vtkLookupTable() color_map.SetNumberOfColors(16) color_map.SetHueRange(0, 0.667) delaunay = vtk.vtkDelaunay2D() delaunay.SetTolerance(0.001) delaunay.SetAlpha(18) delaunay.SetInput(pointset); delaunay.Update(); elevation_thorax = vtk.vtkElevationFilter() elevation_thorax.SetInput(delaunay.GetOutput()) elevation_thorax.SetLowPoint(0, 0, -25) elevation_thorax.SetHighPoint(0, 0, 25) meshMapper = vtk.vtkPolyDataMapper2D() meshMapper.SetInput(elevation_thorax.GetOutput()) meshMapper.SetLookupTable(color_map) #meshMapper.SetScalarRange(0,255) meshActor = vtk.vtkActor2D() meshActor.SetMapper(meshMapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(meshActor) #renderer.AddActor(boundaryActor) renderer.SetBackground(.5, .5, .5) renderWindow.SetSize(600, 600) renderWindow.Render() renderWindowInteractor.Start()
def create_poly(): points = vtk.vtkPoints() GridSize = 20 z=0.0 for x in range(-GridSize,GridSize): for y in range(-GridSize,GridSize): z = 0.05*x*x+0.05*y*y+ random.uniform(-1,1) points.InsertNextPoint(x,y,z) # add the grid points to a polydata object inputPoly = vtk.vtkPolyData() inputPoly.SetPoints(points) delaunay = vtk.vtkDelaunay2D() delaunay.SetInputData(inputPoly) delaunay.Update() return delaunay.GetOutput()
def delaunay2D(plist, tol=None, c='gold', alpha=0.5, wire=False, bc=None, legend=None, texture=None): ''' Create a mesh from points in the XY plane. [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/delaunay2d.py) ''' pd = vtk.vtkPolyData() vpts = vtk.vtkPoints() vpts.SetData(numpy_to_vtk(plist, deep=True)) pd.SetPoints(vpts) delny = vtk.vtkDelaunay2D() delny.SetInputData(pd) if tol: delny.SetTolerance(tol) delny.Update() return Actor(delny.GetOutput(), c, alpha, wire, bc, legend, texture)
def __init__(self): self.dummyAdder = DummyPointIdsAdder() self.merger = vtkAppendPolyData() self.merger.AddInputConnection(self.dummyAdder.GetOutputPort()) self.transformer = vtkTransformPolyDataFilter() self.transformer.SetInputConnection(self.merger.GetOutputPort()) self.tesselator = vtkDelaunay2D() self.tesselator.SetInputConnection(self.transformer.GetOutputPort()) self.GetOutputPort = self.tesselator.GetOutputPort self.GetOutput = self.tesselator.GetOutput self.Update = self.tesselator.Update return
def render_image(pointset): ''' square = 10 color_map = vtk.vtkLookupTable() color_map.SetNumberOfColors(square * square) color_map.SetTableRange(0, square * square - 1) for ii in range(0, square): for jj in range(0, square): color_map.SetTableValue(ii, jj / square, jj / square, ii /square) ''' color_map = vtk.vtkLookupTable() color_map.SetNumberOfColors(16) color_map.SetHueRange(0, 0.667) delaunay = vtk.vtkDelaunay2D() delaunay.SetTolerance(0.001) delaunay.SetAlpha(18) delaunay.SetInput(pointset) delaunay.Update() elevation_thorax = vtk.vtkElevationFilter() elevation_thorax.SetInput(delaunay.GetOutput()) elevation_thorax.SetLowPoint(0, 0, -25) elevation_thorax.SetHighPoint(0, 0, 25) meshMapper = vtk.vtkPolyDataMapper2D() meshMapper.SetInput(elevation_thorax.GetOutput()) meshMapper.SetLookupTable(color_map) #meshMapper.SetScalarRange(0,255) meshActor = vtk.vtkActor2D() meshActor.SetMapper(meshMapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(meshActor) #renderer.AddActor(boundaryActor) renderer.SetBackground(.5, .5, .5) renderWindow.SetSize(600, 600) renderWindow.Render() renderWindowInteractor.Start()
def createTriangulation(pts): vPts = vtk.vtkPoints() numPoints = len(pts) vPts.SetNumberOfPoints(numPoints) for i in range(numPoints): vPts.SetPoint(i, pts[i]) poly = vtk.vtkPolyData() poly.SetPoints(vPts) delny = vtk.vtkDelaunay2D() delny.SetInputData(poly) delny.Update() # convert the output of delny to a vtkUnstructuredGrid appendFilter = vtk.vtkAppendFilter() appendFilter.AddInputData(delny.GetOutput()) appendFilter.Update() grid = vtk.vtkUnstructuredGrid() grid.ShallowCopy(appendFilter.GetOutput()) return grid
def create_actor_delaunay(pts, color, **kwargs): """ Creates a VTK actor for rendering triangulated plots using Delaunay triangulation. Keyword Arguments: * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False* :param pts: points :type pts: vtkFloatArray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) use_delaunay3d = kwargs.get("d3d", False) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create a PolyData object and add points polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Apply Delaunay triangulation on the poly data object triangulation = vtk.vtkDelaunay3D( ) if use_delaunay3d else vtk.vtkDelaunay2D() triangulation.SetInputData(polydata) # Map triangulated surface to the graphics primitives mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(triangulation.GetOutputPort()) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
def create_actor_delaunay(pts, color, **kwargs): """ Creates a VTK actor for rendering triangulated plots using Delaunay triangulation. Keyword Arguments: * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False* :param pts: points :type pts: vtkFloatArray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) use_delaunay3d = kwargs.get("d3d", False) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create a PolyData object and add points polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Apply Delaunay triangulation on the poly data object triangulation = vtk.vtkDelaunay3D() if use_delaunay3d else vtk.vtkDelaunay2D() triangulation.SetInputData(polydata) # Map triangulated surface to the graphics primitives mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(triangulation.GetOutputPort()) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
def delny2d(self): delny = vtk.vtkDelaunay2D() print("1") delny.SetInputData(self.pointCloud.vtkPolyData) print("1") delny.SetSourceData(self.pointCloud.vtkPolyData) print("1") delny.SetAlpha(1) #delny.SetTolerance(1) mapper = vtk.vtkPolyDataMapper() print("1") mapper.SetInputConnection(delny.GetOutputPort()) mapper.SetColorModeToDefault() print("1") actor = vtk.vtkActor() print("1") actor.SetMapper(mapper) print("1") self.mainActor = actor
def makeSurfaceVTP(locXYZ): # Load the file if type(locXYZ) == np.ndarray: loc = locXYZ elif type(locXYZ) == str: loc = np.genfromtxt(locXYZ) # Make the pts vtkPts = vtk.vtkPoints() vtkPts.SetData(npsup.numpy_to_vtk(loc,deep=1)) # Make the poly data polyPtsVTP = vtk.vtkPolyData() polyPtsVTP.SetPoints(vtkPts) # Triangulate del2Filt = vtk.vtkDelaunay2D() del2Filt.SetInputData(polyPtsVTP) del2Filt.Update() # Return return del2Filt.GetOutput()
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 plot_delaunay_2D(dataframe, renderer, r=0, g=0, b=0, **kwargs): """ """ points = vtk.vtkPoints() for x, y, z in zip(dataframe.X, dataframe.Y, dataframe.Z): points.InsertNextPoint(x, y, z) if points.GetNumberOfPoints() > 2: polydata = vtk.vtkPolyData() polydata.SetPoints(points) delaunay2D = vtk.vtkDelaunay2D() if vtk.VTK_MAJOR_VERSION <= 5: delaunay2D.SetInput(polydata) else: delaunay2D.SetInputData(polydata) delaunayMapper = vtk.vtkDataSetMapper() delaunayMapper.SetInputConnection(delaunay2D.GetOutputPort()) delaunayActor = vtk.vtkActor() delaunayActor.SetMapper(delaunayMapper) delaunayActor.GetProperty().SetColor(r,g,b) renderer.AddActor(delaunayActor) renderer.ResetCamera()
def loadafmasmesh(path, flatten=True, gaussianblursize=5): # load the image img = misc.imread(path) if flatten: #if we want to remove the parabolic/spherical background from AFM image #make a kernal to scan with; This should be tested with more images to choose the best shape and size; #Current kernel is a 20x20 square kernel = np.ones((20, 20), np.uint8) #Remove background artifact img = img - np.minimum(img, cv2.morphologyEx(img, cv2.MORPH_OPEN, kernel)) #Add optional gaussian blur to denoise if gaussianblursize>0: img = cv2.GaussianBlur(img, (0, 0), gaussianblursize) #img = cv2.bilateralFilter(img,9,80,80) if img.shape.__len__()>2: if img.shape[2] == 3: #if the image is a 3 channel rgb average the channels img = np.sum(img, axis=2) / 3.0 #make a grid array for x and y xx, yy = np.mgrid[0:img.shape[0], 0:img.shape[1]] #make the array of points, then reshape it to an Nx3 array points = np.array([xx, yy, img]) points = points.reshape((3, img.shape[0] * img.shape[1])).T pointsforvtk = vtk.vtkPoints() polygondata=vtk.vtkPolyData() cellarray=vtk.vtkCellArray() delaunay=vtk.vtkDelaunay2D() boundary=vtk.vtkPolyData() pointsarray = numpytovtk(points) #print type(pointsarray) pointsforvtk.SetData(pointsarray) polygondata.SetPoints(pointsforvtk) boundary.SetPoints(polygondata.GetPoints()) boundary.SetPolys(cellarray) delaunay.SetInputData(polygondata) delaunay.SetSourceData(boundary) #print(delaunay.GetOutput()) #meshpoly=delaunay.GetOutput() decimator = vtk.vtkDecimatePro() decimator.SetInputConnection(delaunay.GetOutputPort()) decimator.SetTargetReduction(0.999) decimator.PreserveTopologyOn() #decimator.BoundaryVertexDeletionOff() decimator.Update() plotvtk(decimator,boundary) print "mesh finished" points,triangles=polytopointstriangles(decimator.GetOutput()) print(triangles.__len__()) return points, triangles
def initialize(self): debug("In Delaunay2D::initialize()") self.fil = vtk.vtkDelaunay2D() self.fil.SetInput(self.prev_fil.GetOutput()) self.fil.Update()
def abs2asc(abs_file, tex_file,output): ftex = Image.open(tex_file) f = open(abs_file) rows = int(f.readline().split()[0]) cols = int(f.readline().split()[0]) values = [] # Reading the junk line f.readline() numbers = f.read().split() #flags fl = numbers[0: rows * cols] #X coordinates x = numbers[rows * cols: rows * cols * 2] # Y coordinates y = numbers[rows * cols * 2: rows * cols * 3] # Z coordinates z = numbers[rows * cols * 3: rows * cols * 4] for i in xrange(len(fl)): if fl[i] == '1': data.append([x[i], y[i], z[i]]) px = i%cols py = i/cols color_pixel = ftex.getpixel((px,py)) point_colors.append(color_pixel) pointSource.SetExecuteMethod(readPoints) pointSource.GetOutput().GetCellData().SetScalars(colors) pointSource.GetOutput().Update() delaunay = vtk.vtkDelaunay2D() #delaunay.SetTolerance(0.5) delaunay.SetAlpha(2.0) delaunay.SetInput(pointSource.GetOutput()) delaunay.Update() poly = delaunay.GetOutput() w = vtk.vtkPLYWriter() w.SetInput(poly) w.SetFileName(output + ".ply") w.SetFileTypeToASCII() w.SetDataByteOrderToLittleEndian() #w.SetColorModeToUniformPointColor() #w.SetScalarsName("aaa") w.Write() lnumber = 1 count = 0 max_points = len(point_colors) #print max_points for line in fileinput.input(output + ".ply", inplace=1): if lnumber > 11 and count <= max_points - 1: r, g, b = point_colors[count] new_line = line.replace("\n", "") print new_line, r, g, b count += 1 elif(lnumber == 8): print line, "property uchar red\n", "property uchar green\n", "property uchar blue" else: new_line = line.replace("\n", "") print new_line lnumber += 1 print "Terminou >> ", abs_file, ">>" , output + ".ply"
def main(argv): if len(argv) < 2: print "usage: ",argv[0]," <data>" exit(1) data_fn = argv[1] mapper = vtk.vtkPolyDataMapper() if data_fn.find('.vtk') != -1: reader = vtk.vtkPolyDataReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() trianglize = vtk.vtkDelaunay2D() trianglize.SetInput(data) trianglize.Update() mapper.SetInputConnection(trianglize.GetOutputPort()) elif data_fn.find('.pgm') != -1: reader = vtk.vtkPNMReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() trianglize = vtk.vtkImageDataGeometryFilter() trianglize.SetInput(data) trianglize.Update() warp = vtk.vtkWarpScalar() warp.SetScaleFactor(0.2) # arbitrary choice warp.SetInputConnection(trianglize.GetOutputPort()) warp.Update() mapper.SetInputConnection(warp.GetOutputPort()) elif data_fn.find('.dcm') != -1: reader =vtk.vtkDICOMImageReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() trianglize = vtk.vtkImageDataGeometryFilter() trianglize.SetInput(data) trianglize.Update() warp = vtk.vtkWarpScalar() #warp.SetScaleFactor(0.2) # arbitrary choice warp.SetInputConnection(trianglize.GetOutputPort()) warp.Update() mapper.SetInputConnection(warp.GetOutputPort()) else: print "unrecognized data file:",data_fn exit(1) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(700,700) renderWindow.AddRenderer(renderer) renderWindow.SetWindowName("heightfield") renderer.AddActor(actor) renderer.SetBackground(0.4,0.3,0.2) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
polys.InsertCellPoint(15) polys.InsertCellPoint(14) polys.InsertCellPoint(13) polys.InsertCellPoint(12) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetPolys(polys) # Notice this trick. The SetInput() method accepts a vtkPolyData that # is also the input to the Delaunay filter. The points of the # vtkPolyData are used to generate the triangulation; the polygons are # used to create a constraint region. The polygons are very carefully # created and ordered in the right direction to indicate inside and # outside of the polygon. delny = vtk.vtkDelaunay2D() delny.SetInputData(polyData) delny.SetSourceData(polyData) mapMesh = vtk.vtkPolyDataMapper() mapMesh.SetInputConnection(delny.GetOutputPort()) meshActor = vtk.vtkActor() meshActor.SetMapper(mapMesh) # Now we just pretty the mesh up with tubed edges and balls at the # vertices. extract = vtk.vtkExtractEdges() extract.SetInputConnection(delny.GetOutputPort()) tubes = vtk.vtkTubeFilter() tubes.SetInputConnection(extract.GetOutputPort()) tubes.SetRadius(0.1) tubes.SetNumberOfSides(6)
def prepareDelaunayData(dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs): local_nodeidx2global_nodeidx = {} no_of_aggnodes = len(agg_globalnodeidx) dim = len(global_nodecoords[0]) no_aggs = len(aggid2nodes) Points = vtk.vtkPoints() Vertices = vtk.vtkCellArray() for i in range(0, len(agg_globalnodeidx)): local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i] nodecoords = global_nodecoords[int(agg_globalnodeidx[i])] if dimension == 2: id = Points.InsertNextPoint(nodecoords[0], nodecoords[1], 0.0) elif dimension == 3: id = Points.InsertNextPoint( nodecoords[0] + 0.001 * random.random(), nodecoords[1] + 0.001 * random.random(), nodecoords[2] + 0.001 * random.random(), ) Vertices.InsertNextCell(1) Vertices.InsertCellPoint(id) # create polygon for current aggregate polydata = vtk.vtkPolyData() polydata.SetPoints(Points) polydata.SetVerts(Vertices) polydata.Modified() polydata.Update() polydata2 = vtk.vtkPolyData() if Points.GetNumberOfPoints() > 2: # todo: avoid error messages + add support for lines/surfaces # create delaunay object if dimension == 2: delaunay = vtk.vtkDelaunay2D() elif dimension == 3: delaunay = vtk.vtkDelaunay3D() # delaunay.SetAlpha(0.1) delaunay.SetInput(polydata) delaunay.Update() # create surfaceFilter surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) surfaceFilter.Update() polydata2 = surfaceFilter.GetOutput() lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(no_aggs) lookupTable.Build() Ids = vtk.vtkUnsignedIntArray() Ids.SetNumberOfComponents(1) Ids.SetName("Ids") for i in range(0, Points.GetNumberOfPoints()): Ids.InsertNextTuple1(int(aggid)) Ids.SetLookupTable(lookupTable) Procs = vtk.vtkUnsignedCharArray() Procs.SetNumberOfComponents(1) Procs.SetName("proc") for i in range(0, Points.GetNumberOfPoints()): Procs.InsertNextTuple1(aggid2procs[aggid]) polydata2.SetPoints(Points) polydata2.SetVerts(Vertices) polydata2.GetPointData().SetScalars(Ids) polydata2.GetPointData().AddArray(Procs) polydata2.Modified() polydata2.Update() aggpolygons.AddInput(polydata2)
def delaunay2d(points): """Construct a 2D Delaunay triangulation from a set of points.""" delaunay = vtk.vtkDelaunay2D() delaunay.SetInput(points) delaunay.Update() return delaunay.GetOutput()
def Delaunay(grand_nei, total, cluster_membership): itera=0 print("doing delaunay") i=0 for plane in grand_nei: Xp=plane.split(']') plane0=Xp[0] plane=plane0.split(",") color=cluster_membership[i] i=i+1 color0=[0.9*color+0.1, 0.75*color, 0.2*color] meshActor={} boundaryActor={} points=vtk.vtkPoints() for itom in plane: item=int(itom) xyz2=[total[item,0], total[item,1], total[item,2]] points.InsertNextPoint(xyz2) itera=itera+1 aPolyData = vtk.vtkPolyData() aPolyData.SetPoints(points) aCellArray = vtk.vtkCellArray() boundary = vtk.vtkPolyData() boundary.SetPoints(aPolyData.GetPoints()) boundary.SetPolys(aCellArray) delaunay = vtk.vtkDelaunay2D() if vtk.VTK_MAJOR_VERSION <= 5: delaunay.SetInput(aPolyData.GetOutput()) delaunay.SetSource(boundary) else: delaunay.SetInputData(aPolyData) delaunay.SetSourceData(boundary) delaunay.Update() meshMapper = vtk.vtkPolyDataMapper() meshMapper.SetInputConnection(delaunay.GetOutputPort()) meshActor["v{0}".format(i)] = vtk.vtkActor() meshActor["v{0}".format(i)].SetMapper(meshMapper) meshActor["v{0}".format(i)].GetProperty().SetEdgeColor(0, 0, 1) meshActor["v{0}".format(i)].GetProperty().SetColor(color0) meshActor["v{0}".format(i)].GetProperty().SetInterpolationToFlat() #meshActor["v{0}".format(i)].GetProperty().SetRepresentationToWireframe() boundaryMapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: boundaryMapper.SetInputConnection(boundary.GetProducerPort()) else: boundaryMapper.SetInputData(boundary) boundaryActor["v{0}".format(i)] = vtk.vtkActor() boundaryActor["v{0}".format(i)].SetMapper(boundaryMapper) boundaryActor["v{0}".format(i)].GetProperty().SetColor(1, 0, 0) renderer.AddActor(meshActor["v{0}".format(i)]) renderer.AddActor(boundaryActor["v{0}".format(i)]) print(itera)
# calculate the min and max of the z data _zMin = min(z.flat) _zMax = max(z.flat) # make a lookup table for the colour map and invert it (colours look # better when it's inverted) _lut = vtk.vtkLookupTable() _refLut = vtk.vtkLookupTable() _lut.Build() _refLut.Build() for i in range(256): _lut.SetTableValue(i, _refLut.GetTableValue(255-i)) # triangulate them _delaunay = vtk.vtkDelaunay2D() _delaunay.SetInput(_grid) _delaunay.SetTolerance(0.001) # warp the surface to generate the surface or "carpet" _warp = vtk.vtkWarpScalar() _warp.SetInput(_delaunay.GetOutput()) _warp.SetScaleFactor(1.0) # set up the mapper _mapper = vtk.vtkPolyDataMapper() _mapper.SetInput(_warp.GetOutput()) _mapper.SetLookupTable(_lut) _mapper.SetScalarRange(_zMin, _zMax) # set up the actor
def main(argv): if len(argv) < 2: print "usage: ",argv[0]," <data> [flat]" exit(1) data_fn = argv[1] flat = False if len(argv) > 2: flat = True mapper = vtk.vtkPolyDataMapper() if data_fn.find('.vtk') != -1: reader = vtk.vtkPolyDataReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() trianglize = vtk.vtkDelaunay2D() trianglize.SetInput(data) trianglize.Update() mapper.SetInputConnection(trianglize.GetOutputPort()) elif data_fn.find('.pgm') != -1: reader = vtk.vtkPNMReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() geometry = vtk.vtkImageDataGeometryFilter() geometry.SetInputConnection(reader.GetOutputPort()) geometry.Update() if flat: merge = vtk.vtkMergeFilter() merge.SetGeometry(geometry.GetOutput()) merge.SetScalars(data) mapper.SetInputConnection(merge.GetOutputPort()) else: warp = vtk.vtkWarpScalar() warp.SetInputConnection(geometry.GetOutputPort()) warp.SetScaleFactor(0.3) # looked good warp.Update() merge = vtk.vtkMergeFilter() merge.SetGeometry(warp.GetOutput()) merge.SetScalars(data) mapper.SetInputConnection(merge.GetOutputPort()) elif data_fn.find('.dcm') != -1: reader =vtk.vtkDICOMImageReader() reader.SetFileName(data_fn) reader.Update() data = reader.GetOutput() geometry = vtk.vtkImageDataGeometryFilter() geometry.SetInput(data) geometry.Update() if flat: mapper.SetInputConnection(geometry.GetOutputPort()) else: warp = vtk.vtkWarpScalar() warp.SetInputConnection(geometry.GetOutputPort()) warp.Update() mapper.SetInputConnection(warp.GetOutputPort()) else: print "unrecognized data file:",data_fn exit(1) lut = vtk.vtkLookupTable() lut.SetNumberOfColors(10) lut.SetHueRange(0.5,0.3) lut.SetSaturationRange(0.6,0.5) lut.SetValueRange(1.0,0.5) lut.Build() mapper.ImmediateModeRenderingOff() mapper.SetLookupTable(lut) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(700,700) renderWindow.AddRenderer(renderer) renderer.AddActor(actor) renderer.SetBackground(0.4,0.3,0.2) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
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.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Created a grid of points points = vtk.vtkPoints() gridSize = 10 for x in range(10): for y in range(10): points.InsertNextPoint(x, y, (x+y) / (y+1)) bounds = [1] * 6 points.GetBounds(bounds) # Add the grid points to a polydata object inputPolyData = vtk.vtkPolyData() inputPolyData.SetPoints(points) # Triangulate the grid points delaunay = vtk.vtkDelaunay2D() delaunay.SetInput(inputPolyData) delaunay.Update() elevationFilter = vtk.vtkElevationFilter() elevationFilter.SetInputConnection(delaunay.GetOutputPort()) elevationFilter.SetLowPoint(0, 0, bounds[4]) elevationFilter.SetHighPoint(0, 0, bounds[5]) elevationFilter.Update() output = vtk.vtkPolyData() output.ShallowCopy(vtk.vtkPolyData.SafeDownCast(elevationFilter.GetOutput())) elevation = vtk.vtkFloatArray.SafeDownCast(output.GetPointData().GetArray("Elevation")) # Create the color map colorLookupTable = vtk.vtkLookupTable() colorLookupTable.SetTableRange(bounds[4], bounds[5]) colorLookupTable.Build() # Generate the colors for each point based on the color map colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") for i in range(output.GetNumberOfPoints()): val = elevation.GetValue(i) dcolor = [1.0] * 3 colorLookupTable.GetColor(val, dcolor) color = [1] * 3 for j in range(3): color[j] = 255 * dcolor[j] colors.InsertNextTupleValue(color) output.GetPointData().AddArray(colors) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(output.GetProducerPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def vtksetup(points, color=None, radius=None): # Create a polydata with the points we just created. profile = vtk.vtkPolyData() profile.SetPoints(points) # Perform a 2D Delaunay triangulation on them. delny = vtk.vtkDelaunay2D() delny.SetInput(profile) delny.SetTolerance(0.001) mapMesh = vtk.vtkPolyDataMapper() mapMesh.SetInputConnection(delny.GetOutputPort()) meshActor = vtk.vtkActor() meshActor.SetMapper(mapMesh) meshActor.GetProperty().SetColor(.1, .2, .1) # Construct the surface and create isosurface. #surf = vtk.vtkSurfaceReconstructionFilter() #surf.SetInput(pointSource.GetPolyDataOutput()) cf = vtk.vtkPolyData() #cf = vtk.vtkContourFilter() cf.SetPoints(points) #cf.SetInput(surf.GetOutput()) #cf.SetValue(0, 0.0) ## map = vtk.vtkPolyDataMapper() ## map.SetInput(reverse.GetOutput()) ## map.ScalarVisibilityOff() surfaceActor = vtk.vtkActor() surfaceActor.SetMapper(map) surfaceActor.GetProperty().SetDiffuseColor(1.0000, 0.3882, 0.2784) surfaceActor.GetProperty().SetSpecularColor(1, 1, 1) surfaceActor.GetProperty().SetSpecular(.4) surfaceActor.GetProperty().SetSpecularPower(50) # We will now create a nice looking mesh by wrapping the edges in tubes, # and putting fat spheres at the points. extract = vtk.vtkExtractEdges() extract.SetInputConnection(delny.GetOutputPort()) ball = vtk.vtkSphereSource() if radius == None: rad = .002 else: rad = radius ball.SetRadius(rad) ball.SetThetaResolution(5) ball.SetPhiResolution(5) balls = vtk.vtkGlyph3D() balls.SetInputConnection(delny.GetOutputPort()) balls.SetSourceConnection(ball.GetOutputPort()) mapBalls = vtk.vtkPolyDataMapper() mapBalls.SetInputConnection(balls.GetOutputPort()) ballActor = vtk.vtkActor() ballActor.SetMapper(mapBalls) if color == None: ballcolor = red else: ballcolor = color ballActor.GetProperty().SetColor(ballcolor) ballActor.GetProperty().SetSpecularColor(0, 0, 0) ballActor.GetProperty().SetSpecular(0.3) ballActor.GetProperty().SetSpecularPower(100) ballActor.GetProperty().SetAmbient(0.2) ballActor.GetProperty().SetDiffuse(0.8) return ballActor
iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create some points # math = vtk.vtkMath() points = vtk.vtkPoints() i = 0 while i < 100: points.InsertPoint(i,math.Random(0,1),math.Random(0,1),0.0) i = i + 1 profile = vtk.vtkPolyData() profile.SetPoints(points) # triangulate them # del1 = vtk.vtkDelaunay2D() del1.SetInputData(profile) del1.SetTolerance(0.001) del1.SetAlpha(0.1) shrink = vtk.vtkShrinkPolyData() shrink.SetInputConnection(del1.GetOutputPort()) map = vtk.vtkPolyDataMapper() map.SetInputConnection(shrink.GetOutputPort()) triangulation = vtk.vtkActor() triangulation.SetMapper(map) triangulation.GetProperty().SetColor(1,0,0) # Add the actors to the renderer, set the background and size # ren1.AddActor(triangulation) ren1.SetBackground(1,1,1) renWin.SetSize(300,300)