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 writePatches(rval, LoopCen, ParList, outname): print outname points = vtk.vtkPoints() polygons = vtk.vtkCellArray() v = 0 polygon = vtk.vtkPolygon() havePoly = [] for k in range(len(ParList)): nedge = len(ParList[k]) if nedge < 2: print nedge print k print ParList[k] else: havePoly.append(k) #for k in range(300): # Create the points of the polygon: the loop centers polygon = vtk.vtkPolygon() for l in ParList[k]: points.InsertNextPoint(LoopCen[l][0], LoopCen[l][1], LoopCen[l][2]) polygon.GetPointIds().SetNumberOfIds(nedge) for l in range(nedge): #print l polygon.GetPointIds().SetId(l, v + l) polygons.InsertNextCell(polygon) v += nedge # Create the matching polydata polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(polygons) # Add stresses ... eng, press, stress = compute_energy_and_pressure(rval, 1.0, 1.0) pressure = vtk.vtkDoubleArray() pressure.SetNumberOfComponents(1) pressure.SetName('Pressure') for k in havePoly: pressure.InsertNextValue(press[k]) polygonPolyData.GetCellData().AddArray(pressure) writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(outname) if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(polygonPolyData) else: writer.SetInputData(polygonPolyData) writer.SetDataModeToAscii() writer.Write()
def rectangle(size=(1, 1)): X, Y = size # Setup four points points = vtk.vtkPoints() points.InsertNextPoint(-X / 2, -Y / 2, 0) points.InsertNextPoint(-X / 2, Y / 2, 0) points.InsertNextPoint(X / 2, Y / 2, 0) points.InsertNextPoint(X / 2, -Y / 2, 0) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) # make a quad polygon.GetPointIds().SetId(0, 0) polygon.GetPointIds().SetId(1, 1) polygon.GetPointIds().SetId(2, 2) polygon.GetPointIds().SetId(3, 3) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) # Create a PolyData polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(polygons) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polygonPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def _caps(self, mesh): boundaries = mesh.clean().boundary().pyvista.split_bodies() caps = None for boundary in boundaries: boundary = mesh.load_mesh(boundary) points = self._order_points(boundary.cells) vtk_points = vtk.vtkPoints() polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(len(points)) for i, point in enumerate(points): vtk_points.InsertPoint(i, boundary.points.loc[point].values) polygon.GetPointIds().SetId(i, i) polygon_list = vtk.vtkCellArray() polygon_list.InsertNextCell(polygon) cap = vtk.vtkPolyData() cap.SetPoints(vtk_points) cap.SetPolys(polygon_list) cap = pyvista.wrap(cap).triangulate() if caps is None: caps = cap else: caps = caps.merge(cap) return caps
def generate_polydata(surface_mesh): vertices = surface_mesh.vertices polygons = surface_mesh.faces points = vtk.vtkPoints() for v in vertices: p = v.get_val() points.InsertNextPoint(p[0], p[1], p[2]) vtk_polygons = vtk.vtkCellArray() for p in polygons: vtk_polygon = vtk.vtkPolygon() vtk_polygon.GetPointIds().SetNumberOfIds(len(p.adj_vertices)) for i in range(len(p.adj_vertices)): vtk_polygon.GetPointIds().SetId(i, p.adj_vertices[i].id) vtk_polygons.InsertNextCell(vtk_polygon) polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(vtk_polygons) return polygonPolyData
def getCell2vtp(vtkObj, ind): """ Function gets a cell by ind and constructs a polydata from it. """ # Get the cell cE = vtkObj.GetCell(ind) # Make the polygon if cE.GetCellType() == 11: # Use a cubeSource, much faster cube = vtk.vtkCubeSource() cube.SetBounds(cE.GetBounds()) cube.Update() vtpObj = cube.GetOutput() else: polygons = vtk.vtkCellArray() for iF in range(cE.GetNumberOfFaces()): f = cE.GetFace(iF) poly = vtk.vtkPolygon() poly.GetPointIds().SetNumberOfIds(f.GetNumberOfPoints()) for nr in range(f.GetNumberOfPoints()): poly.GetPointIds().SetId(nr, f.GetPointId(nr)) polygons.InsertNextCell(poly) # Build the polydata vtpObj = vtk.vtkPolyData() vtpObj.SetPoints(obj.GetPoints()) vtpObj.SetPolys(polygons) return normFilter(triangulatePolyData(vtpObj))
def gocad2vtp(gcFile): """" Function to read gocad polystructure file and makes VTK Polydata object (vtp). Input: gcFile: gocadFile with polysturcture """ print "Reading GOCAD ts file..." vrtx, trgl = read_GOCAD_ts(gcFile) # Adjust the index trgl = trgl - 1 # Make vtk pts ptsvtk = vtk.vtkPoints() ptsvtk.SetData(npsup.numpy_to_vtk(vrtx,deep=1)) # Make the polygon connection polys = vtk.vtkCellArray() for face in trgl: poly = vtk.vtkPolygon() poly.GetPointIds().SetNumberOfIds(len(face)) for nrv, vert in enumerate(face): poly.GetPointIds().SetId(nrv,vert) polys.InsertNextCell(poly) # Make the polydata, structure of connections and vrtx polyData = vtk.vtkPolyData() polyData.SetPoints(ptsvtk) polyData.SetPolys(polys) return polyData
def ndarray2vtkMesh(inVertexArray, inFacesArray): ''' Code inspired by https://github.com/selaux/numpy2vtk ''' # Handle the points & vertices: z_index=0 vtk_points = vtkPoints() for p in inVertexArray: z_value = p[2] if inVertexArray.shape[1] == 3 else z_index vtk_points.InsertNextPoint([p[0], p[1], z_value]) number_of_points = vtk_points.GetNumberOfPoints() indices = np.array(range(number_of_points), dtype=np.int) vtk_vertices = vtkCellArray() for v in indices: vtk_vertices.InsertNextCell(1) vtk_vertices.InsertCellPoint(v) # Handle faces number_of_polygons = inFacesArray.shape[0] poly_shape = inFacesArray.shape[1] vtk_polygons = vtkCellArray() for j in range(0, number_of_polygons): polygon = vtkPolygon() polygon.GetPointIds().SetNumberOfIds(poly_shape) for i in range(0, poly_shape): polygon.GetPointIds().SetId(i, inFacesArray[j, i]) vtk_polygons.InsertNextCell(polygon) # Assemble the vtkPolyData from the points, vertices and faces poly_data = vtkPolyData() poly_data.SetPoints(vtk_points) poly_data.SetVerts(vtk_vertices) poly_data.SetPolys(vtk_polygons) return poly_data
def read_grid_from_nc(path): # read from netcdf (slow creation) x, y, z, cells = read_grid_parameters_from_nc(path) points = vtkPoints() points.SetNumberOfPoints(len(x)) for i in range(0, len(x)): points.InsertPoint(i, x[i], y[i], z[i]) grid = vtkUnstructuredGrid() grid.SetPoints(points) grid.Allocate(cells.shape[0], cells.shape[0]) cell_type = vtkPolygon().GetCellType() cell_sizes = (cells > 0).sum(1) for cell, cell_size in zip(cells, cell_sizes): if cell_size < 3: continue ids = vtkIdList() ids.SetNumberOfIds(cell_size) for i, pointid in enumerate(cell): ids.SetId(i, pointid - 1) grid.InsertNextCell(cell_type, ids) return grid
def gen_outline(pts,color,size): ''' Returns an outline actor with specified pts, color and size. Incoming pnts should be ordered. ''' if color[0]<=1 and color != None: color=(int(color[0]*255),int(color[1]*255),int(color[2]*255)) if color[0]>=1 and color != None: color=(color[0]/float(255),color[1]/float(255),color[2]/float(255)) points=vtk.vtkPoints() for i in pts: points.InsertNextPoint(i) lineseg=vtk.vtkPolygon() lineseg.GetPointIds().SetNumberOfIds(len(pts)) for i in range(len(pts)): lineseg.GetPointIds().SetId(i,i) linesegcells=vtk.vtkCellArray() linesegcells.InsertNextCell(lineseg) outline=vtk.vtkPolyData() outline.SetPoints(points) outline.SetVerts(linesegcells) outline.SetLines(linesegcells) Omapper=vtk.vtkPolyDataMapper() Omapper.SetInputData(outline) outlineActor=vtk.vtkActor() outlineActor.SetMapper(Omapper) outlineActor.GetProperty().SetColor(color) outlineActor.GetProperty().SetPointSize(size) return outlineActor,outline
def main(): # Create a square in the x-y plane. points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(1.0, 1.0, 0.0) points.InsertNextPoint(0.0, 1.0, 0.0) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPoints().DeepCopy(points) polygon.GetPointIds().SetNumberOfIds(4) # The 4 corners of the square for i in range(4): polygon.GetPointIds().SetId(i, i) # Inputs p1 = [0.1, 0, -1.0] p2 = [0.1, 0, 1.0] tolerance = 0.001 # Outputs t = vtk.mutable( 0 ) # Parametric coordinate of intersection (0 (corresponding to p1) to 1 (corresponding to p2)) x = [0.0, 0.0, 0.0] pcoords = [0.0, 0.0, 0.0] subId = vtk.mutable(0) iD = polygon.IntersectWithLine(p1, p2, tolerance, t, x, pcoords, subId) print('intersected? ', 'Yes' if iD == 1 else 'No') print('intersection: ', x)
def _update_vtk_objects(self): """When n is changed the thus the number of coordinates this function is needed to update the vtk objects with the new number of points. """ # self._vtk_points.SetNumberOfPoints(len(self._points)) # for i, c in enumerate(self._points): # self._vtk_points.InsertPoint(i, c[0], c[1], c[2]) self._vtk_points = _vtk.vtkPoints() for coordinates in self._points: self._vtk_points.InsertNextPoint(coordinates[0], coordinates[1], coordinates[2]) self._vtk_polygons = _vtk.vtkCellArray() for polygon in self._polygons: vtk_polygon = _vtk.vtkPolygon() vtk_polygon.GetPointIds().SetNumberOfIds(3) for local_index, global_index in enumerate(polygon): vtk_polygon.GetPointIds().SetId(local_index, global_index) self._vtk_polygons.InsertNextCell(vtk_polygon) self._vtk_poly_data.SetPoints(self._vtk_points) self._vtk_poly_data.SetPolys(self._vtk_polygons) self._vtk_scalars = _vtk.vtkFloatArray() self._vtk_scalars.SetNumberOfValues( self._vtk_poly_data.GetPoints().GetNumberOfPoints()) for i in range(self._vtk_scalars.GetNumberOfTuples()): self._vtk_scalars.SetValue(i, 0.) self._vtk_poly_data.GetPointData().SetScalars(self._vtk_scalars) self._vtk_poly_data.Modified()
def convert_face_3d(face: Face3D) -> PolyData: """Convert a ladybug_geometry.Face3D to vtkPolyData.""" # check if geometry has holes or is convex # mesh them and use convert_mesh if face.has_holes or not face.is_convex: return convert_mesh(face.triangulated_mesh3d) # create a PolyData from face points points = vtk.vtkPoints() polygon = vtk.vtkPolygon() cells = vtk.vtkCellArray() vertices_count = len(face.vertices) polygon.GetPointIds().SetNumberOfIds(vertices_count) for ver in face.vertices: points.InsertNextPoint(*ver) for count in range(vertices_count): polygon.GetPointIds().SetId(count, count) cells.InsertNextCell(polygon) face_vtk = PolyData() face_vtk.SetPoints(points) face_vtk.SetPolys(cells) return face_vtk
def polygons(indices): """ Maps a numpy ndarray to an vtkCellArray of vtkPolygons Args: indices (numpy.ndarray<int>): A numpy.ndarray of shape (n,m) of indices that define n polygons with m points each Returns: vtk_polygons (vtk.vtkCellArray): VTK representation of the polygons """ if not isinstance(indices, numpy.ndarray): raise Numpy2VtkFormatException( 'polygons needs numpy array as input' ) if len(indices.shape) != 2: raise Numpy2VtkFormatException( 'polygons needs a nxm ndarray as input' ) if indices.dtype != numpy.int: raise Numpy2VtkFormatException( 'polygons needs to be numpy array of type numpy.int' ) number_of_polygons = indices.shape[0] poly_shape = indices.shape[1] vtk_polygons = vtk.vtkCellArray() for j in range(0, number_of_polygons): polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(poly_shape) for i in range(0, poly_shape): polygon.GetPointIds().SetId(i, indices[j, i]) vtk_polygons.InsertNextCell(polygon) return vtk_polygons
def face_points2actor(fps_df): cell_array = vtk.vtkCellArray() points = vtk.vtkPoints() point_id = 0 for i in range(fps_df.shape[0]): polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(3) for n in range(3): points.InsertNextPoint(fps_df.iloc[i, 0 + 3 * n], fps_df.iloc[i, 1 + 3 * n], fps_df.iloc[i, 2 + 3 * n]) polygon.GetPointIds().SetId(n, point_id) point_id += 1 cell_array.InsertNextCell(polygon) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(cell_array) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(polydata) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) return actor, polydata
def _update_vtk_objects(self): """When n is changed the thus the number of coordinates this function is needed to update the vtk objects with the new number of points.""" # self._vtk_points.SetNumberOfPoints(len(self._points)) # for i, c in enumerate(self._points): # self._vtk_points.InsertPoint(i, c[0], c[1], c[2]) self._vtk_points = _vtk.vtkPoints() for coordinates in self._points: self._vtk_points.InsertNextPoint(coordinates[0], coordinates[1], coordinates[2]) self._vtk_polygons = _vtk.vtkCellArray() for polygon in self._polygons: vtk_polygon = _vtk.vtkPolygon() vtk_polygon.GetPointIds().SetNumberOfIds(3) for local_index, global_index in enumerate(polygon): vtk_polygon.GetPointIds().SetId(local_index, global_index) self._vtk_polygons.InsertNextCell(vtk_polygon) self._vtk_poly_data.SetPoints(self._vtk_points) self._vtk_poly_data.SetPolys(self._vtk_polygons) self._vtk_scalars = _vtk.vtkFloatArray() self._vtk_scalars.SetNumberOfValues(self._vtk_poly_data.GetPoints().GetNumberOfPoints()) for i in range(self._vtk_scalars.GetNumberOfTuples()): self._vtk_scalars.SetValue(i, 0.) self._vtk_poly_data.GetPointData().SetScalars(self._vtk_scalars) self._vtk_poly_data.Modified()
def gen_outline(pts,color,size): ''' Returns an outline actor with specified pts, color and size. Incoming pnts should be ordered. ''' if color[0]<=1 and color != None: color=(int(color[0]*255),int(color[1]*255),int(color[2]*255)) if color[0]>=1 and color != None: color=(color[0]/float(255),color[1]/float(255),color[2]/float(255)) points=vtk.vtkPoints() for i in pts: points.InsertNextPoint(i) lineseg=vtk.vtkPolygon() lineseg.GetPointIds().SetNumberOfIds(len(pts)) for i in range(len(pts)): lineseg.GetPointIds().SetId(i,i) linesegcells=vtk.vtkCellArray() linesegcells.InsertNextCell(lineseg) outline=vtk.vtkPolyData() outline.SetPoints(points) outline.SetVerts(linesegcells) outline.SetLines(linesegcells) Omapper=vtk.vtkPolyDataMapper() Omapper.SetInputData(outline) outlineActor=vtk.vtkActor() outlineActor.SetMapper(Omapper) outlineActor.GetProperty().SetColor(color) outlineActor.GetProperty().SetPointSize(size) return outlineActor,outline #actor/polydata
def _make_quad(self, ids): polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) for i in range(4): polygon.GetPointIds().SetId(i, ids[i]) return polygon
def getCell2vtp(vtkObj,ind): """ Function gets a cell by ind and constructs a polydata from it. """ # Get the cell cE = vtkObj.GetCell(ind) # Make the polygon if cE.GetCellType() == 11: # Use a cubeSource, much faster cube = vtk.vtkCubeSource() cube.SetBounds(cE.GetBounds()) cube.Update() vtpObj = cube.GetOutput() else: polygons = vtk.vtkCellArray() for iF in range(cE.GetNumberOfFaces()): f = cE.GetFace(iF) poly = vtk.vtkPolygon() poly.GetPointIds().SetNumberOfIds(f.GetNumberOfPoints()) for nr in range(f.GetNumberOfPoints()): poly.GetPointIds().SetId(nr,f.GetPointId(nr)) polygons.InsertNextCell(poly) # Build the polydata vtpObj = vtk.vtkPolyData() vtpObj.SetPoints(obj.GetPoints()) vtpObj.SetPolys(polygons) return polydata.normFilter(polydata.triangulatePolyData(vtpObj))
def sphere_poly_data(): rotations_n = 1 coordinates = numpy.array(icosahedral_sphere.sphere_sampling(rotations_n)) #create points object points = vtk.vtkPoints() for c in coordinates: points.InsertNextPoint(c[0], c[1], c[2]) #coordinates = icosahedral_sphere.icosahedron_vertices() base_coordinates = icosahedral_sphere.icosahedron_vertices() edges, edge_indices = icosahedron_edges() faces, face_indices = icosahedron_faces() edge_points = [] for e in edges: origin = e[0] base = e[1] - e[0] for i in range(1, rotations_n): edge_points.append(origin + i / float(rotations_n) * base) def get_index(i, j): return int((rotations_n + 1) * j + float(j) / 2. - float(j)**2 / 2. + i) face_points = [] print "start loop" print zip(faces, face_indices) for f, fi in zip(enumerate(faces), face_indices): base_index = f[0] * (((rotations_n + 1)**2 + rotations_n) / 2) print base_index for i in range(0, rotations_n): for j in range(0, rotations_n): if i + j < rotations_n: face_indices.append((base_index + get_index(i, j), base_index + get_index(i, j + 1), base_index + get_index(i + 1, j))) # full_list = [numpy.array(c) for c in coordinates] + edge_points + face_points # normalized_list =[l/numpy.linalg.norm(l) for l in full_list] points = vtk.vtkPoints() for c in coordinates: points.InsertNextPoint(c[0], c[1], c[2]) print "number of points = {0}".format(points.GetNumberOfPoints()) polygons = vtk.vtkCellArray() for p in face_indices: polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(3) for i, pi in enumerate(p): polygon.GetPointIds().SetId(i, pi) polygons.InsertNextCell(polygon) poly_data = vtk.vtkPolyData() poly_data.SetPoints(points) poly_data.SetPolys(polygons) return poly_data
def draw(self, graphics): cell, pointnums = super(Polygon, self).draw(graphics) polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(len(pointnums)) for i, p in enumerate(pointnums): polygon.GetPointIds().SetId(i, p) cell.InsertNextCell(polygon)
def start_pyvtkarea(self, name, attrs): self.pyvtkareaIndex += 1 if self.pyvtkareaIndex % 100 == 0: print "pyvtkareaIndex:%d" % self.pyvtkareaIndex self.ms = vtk.vtkFloatArray() self.mspts = vtk.vtkPoints() self.ms.SetNumberOfComponents(3) self.polygon = vtk.vtkPolygon()
def get_vtkActor(self, campos, dist_from_surf=0.08, return_mapper=False): points = vtk.vtkPoints() polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(len(self.vertex_coords)) dist_to_points = [] direction_to_points = [] for point in self.vertex_coords: dist_to_points.append( np.sqrt((point[0] - campos[0])**2 + (point[1] - campos[1])**2 + (point[2] - campos[2])**2)) direction_to_points.append([ (point[0] - campos[0]) / dist_to_points[-1], (point[1] - campos[1]) / dist_to_points[-1], (point[2] - campos[2]) / dist_to_points[-1] ]) dist_to_poly = min(dist_to_points) - dist_from_surf for n, direction in enumerate(direction_to_points): points.InsertNextPoint( (campos[0] + direction[0] * (dist_to_points[n] - dist_from_surf), campos[1] + direction[1] * (dist_to_points[n] - dist_from_surf), campos[2] + direction[2] * (dist_to_points[n] - dist_from_surf))) #points.InsertNextPoint( ( campos[0] + direction[0]*dist_to_poly, campos[1] + direction[1]*dist_to_poly, campos[2] + direction[2]*dist_to_poly ) ) polygon.GetPointIds().SetId(n, n) polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(polygons) triangulator = vtk.vtkTriangleFilter() triangulator.SetInputData(polydata) triangulator.Update() mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(triangulator.GetOutput()) else: mapper.SetInputData(triangulator.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().LightingOff() if return_mapper: return mapper, actor else: return actor
def draw(self, graphics): cell, pointnums = super(Polygon, self).draw(graphics) polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(len(pointnums)) for i, p in enumerate(pointnums): polygon.GetPointIds().SetId(i, p) cell.InsertNextCell(polygon) graphics.data.SetPolys(cell)
def prepFillarea(renWin, ren, farea, cmap=None): n = prepPrimitive(farea) if n == 0: return for i in range(n): x = farea.x[i] y = farea.y[i] c = farea.color[i] st = farea.style[i] idx = farea.index[i] N = max(len(x), len(y)) for a in [x, y]: while len(a) < n: a.append(a[-1]) #Create points pts = vtk.vtkPoints() for j in range(N): pts.InsertNextPoint(x[j], y[j], 0.) #Create polygon out of these points polygon = vtk.vtkPolygon() pid = polygon.GetPointIds() pid.SetNumberOfIds(N) for j in range(N): pid.SetId(j, j) polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) polygonPolyData = vtk.vtkPolyData() geo, pts = project(pts, farea.projection, farea.worldcoordinate) polygonPolyData.SetPoints(pts) polygonPolyData.SetPolys(polygons) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputData(polygonPolyData) a.SetMapper(m) p = a.GetProperty() if cmap is None: if farea.colormap is not None: cmap = farea.colormap else: cmap = 'default' if isinstance(cmap, str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C / 100. for C in color]) ren.AddActor(a) fitToViewport(a, ren, farea.viewport, wc=farea.worldcoordinate, geo=geo) return
def generateVolumetricLine(self): """ Generates volumetric lines. """ if self.centroid is None: return points = vtk.vtkPoints() poly_s = vtk.vtkPolygon() tangent_dir = self.calculateElectrodePolygon(points, poly_s) self.polygonActor = self.prepareActorWithShadersAndMapper(points, poly_s, tangent_dir)
def _createpolygon(self, pointnumbers): if depth(pointnumbers) >= 3: for p in pointnumbers: self._createpolygon(p) else: polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(len(pointnumbers)) i = 0 for p in pointnumbers: polygon.GetPointIds().SetId(i, p) i += 1 self.polygons.InsertNextCell(polygon)
def __init__(self): nverts = 10 # First build the cone portion cone = vtk.vtkConeSource() cone.SetResolution(nverts) cone.SetRadius(.08) cone.SetHeight(.2) cone.CappingOff() coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInput(cone.GetOutput()) # Now take care of the capping polygon pts = vtk.vtkPoints() pts.SetNumberOfPoints(nverts) for i in range(0, nverts): theta = 2 * i * pi / nverts + pi / 2 pts.InsertPoint(i, 0.8, .08 * sin(theta), .08 * cos(theta)) poly = vtk.vtkPolygon() poly.GetPointIds().SetNumberOfIds(nverts) for i in range(0, nverts): poly.GetPointIds().SetId(i, i) pdata = vtk.vtkPolyData() pdata.Allocate(1, 1) pdata.InsertNextCell(poly.GetCellType(), poly.GetPointIds()) pdata.SetPoints(pts) capmapper = vtk.vtkPolyDataMapper() capmapper.SetInput(pdata) self.el = 0.0 self.az = 0.0 self.coneActor = vtk.vtkActor() self.coneActor.SetMapper(coneMapper) self.coneActor.SetPosition(0.9, 0, 0) self.coneActor.SetOrigin(-0.9, 0, 0) self.coneActor.GetProperty().SetColor(0, 1, 1) self.coneActor.GetProperty().SetAmbient(.1) self.coneActor.RotateY(-90) self.capActor = vtk.vtkActor() self.capActor.SetMapper(capmapper) self.capActor.GetProperty().SetAmbientColor(1, 1, 0) self.capActor.GetProperty().SetAmbient(1) self.capActor.GetProperty().SetDiffuse(0) self.capActor.RotateY(-90)
def prepFillarea(renWin,ren,farea,cmap=None): n = prepPrimitive(farea) if n==0: return for i in range(n): x = farea.x[i] y = farea.y[i] c = farea.color[i] st = farea.style[i] idx = farea.index[i] N = max(len(x),len(y)) for a in [x,y]: while len(a)<n: a.append(a[-1]) #Create points pts = vtk.vtkPoints() for j in range(N): pts.InsertNextPoint(x[j],y[j],0.) #Create polygon out of these points polygon = vtk.vtkPolygon() pid = polygon.GetPointIds() pid.SetNumberOfIds(N) for j in range(N): pid.SetId(j,j) polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) polygonPolyData = vtk.vtkPolyData() geo,pts = project(pts,farea.projection,farea.worldcoordinate) polygonPolyData.SetPoints(pts) polygonPolyData.SetPolys(polygons) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputData(polygonPolyData) a.SetMapper(m) p = a.GetProperty() if cmap is None: if farea.colormap is not None: cmap = farea.colormap else: cmap = 'default' if isinstance(cmap,str): cmap = vcs.elements["colormap"][cmap] color = cmap.index[c] p.SetColor([C/100. for C in color]) ren.AddActor(a) fitToViewport(a,ren,farea.viewport,wc=farea.worldcoordinate,geo=geo) return
def main(): colors = vtk.vtkNamedColors() # Setup four points points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(1.0, 1.0, 0.0) points.InsertNextPoint(0.0, 1.0, 0.0) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) # make a quad polygon.GetPointIds().SetId(0, 0) polygon.GetPointIds().SetId(1, 1) polygon.GetPointIds().SetId(2, 2) polygon.GetPointIds().SetId(3, 3) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) # Create a PolyData polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(polygons) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(polygonPolyData) else: mapper.SetInputData(polygonPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d("Silver")) # Visualize renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.SetWindowName("Polygon") renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d("Salmon")) renderWindow.Render() renderWindowInteractor.Start()
def arrayToPolydata(verts, faces): pts = vtk.vtkPoints() tris = vtk.vtkCellArray() for v in verts: pts.InsertNextPoint( [v[0], v[1], v[2]] ) for f in faces: poly = vtk.vtkPolygon() poly.GetPointIds().InsertId(0,f[0]) poly.GetPointIds().InsertId(1,f[1]) poly.GetPointIds().InsertId(2,f[2]) tris.InsertNextCell(poly.GetPointIds()) return pts, tris
def buildPolyData(vertices, faces=None, indexOffset=0): ''' Build a ``vtkPolyData`` object from a list of vertices where faces represents the connectivity of the polygonal mesh. E.g. : - ``vertices=[[x1,y1,z1],[x2,y2,z2], ...]`` - ``faces=[[0,1,2], [1,2,3], ...]`` Use ``indexOffset=1`` if face numbering starts from 1 instead of 0. .. hint:: Example: `buildpolydata.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/buildpolydata.py>`_ .. image:: https://user-images.githubusercontent.com/32848391/51032546-bf4dac00-15a0-11e9-9e1e-035fff9c05eb.png ''' sourcePoints = vtk.vtkPoints() sourceVertices = vtk.vtkCellArray() sourcePolygons = vtk.vtkCellArray() for pt in vertices: if len(pt) > 2: aid = sourcePoints.InsertNextPoint(pt[0], pt[1], pt[2]) else: aid = sourcePoints.InsertNextPoint(pt[0], pt[1], 0) sourceVertices.InsertNextCell(1) sourceVertices.InsertCellPoint(aid) if faces: for f in faces: n = len(f) if n == 4: plg = vtk.vtkTetra() elif n == 3: plg = vtk.vtkTriangle() else: plg = vtk.vtkPolygon() plg.GetPointIds().SetNumberOfIds(n) for i in range(n): plg.GetPointIds().SetId(i, f[i] - indexOffset) sourcePolygons.InsertNextCell(plg) poly = vtk.vtkPolyData() poly.SetPoints(sourcePoints) poly.SetVerts(sourceVertices) if faces: poly.SetPolys(sourcePolygons) clp = vtk.vtkCleanPolyData() clp.SetInputData(poly) clp.PointMergingOn() clp.Update() return clp.GetOutput()
def FFD_trans(polygonPolyData): # 按照id顺序获取polydata的vertex坐标 coord = [] position = [0.0, 0.0, 0.0] for i in range(polygonPolyData.GetNumberOfPoints()): polygonPolyData.GetPoint(i, position) coord.append(copy(position)) # coord=[polygonPolyData.GetPoint(i, [0.0, 0.0, 0.0]) for i in range(polygonPolyData.GetNumberOfPoints())] # 按照cell的id顺序获取构成cell的vertex的id cell_ids = [] for i in range(polygonPolyData.GetNumberOfCells()): cell = polygonPolyData.GetCell(i) nPoints = cell.GetNumberOfPoints() vertex_ids = [] for j in range(nPoints): vertex_ids.append(cell.GetPointId(j)) cell_ids.append(vertex_ids) #new_coord = list(map(old2new, coord)) # get Bernstein matrix B and deform matrix P # set the new_coord as BP P = np.zeros((totalsphere, 3)) for i in range(totalsphere): x, y, z = spherelist[i].GetCenter() P[i] = [x, y, z] B = util.get_stu_deformation_matrix(coord, [xl, yl, zl]) new_coord = np.dot(B, P) # 重构polydata points = vtk.vtkPoints() for i in range(len(coord)): points.InsertNextPoint(new_coord[i]) # points.InsertNextPoint(coord[i]) cells = vtk.vtkCellArray() for vertex_ids in cell_ids: polygon = vtk.vtkPolygon() cell_num = len(vertex_ids) polygon.GetPointIds().SetNumberOfIds(cell_num) id0 = 0 for i in vertex_ids: polygon.GetPointIds().SetId(id0, i) id0 += 1 cells.InsertNextCell(polygon) polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(cells) return polygonPolyData
def Build_DFN(self): #Points self.points.SetNumberOfPoints(len(self.DFN_GeoData.Points)) for i in range(len(self.DFN_GeoData.Points)): self.points.SetPoint(i, self.DFN_GeoData.Points[i][0], self.DFN_GeoData.Points[i][1], self.DFN_GeoData.Points[i][2]) #Fractures Fractures = vtk.vtkCellArray() for i in range(self.DFN_GeoData.NumFracs): polygon = vtk.vtkPolygon() NumIDs = len(self.DFN_GeoData.Fractures[i]) polygon.GetPointIds().SetNumberOfIds(NumIDs) for j in range(NumIDs): polygon.GetPointIds().SetId(j, self.DFN_GeoData.Fractures[i][j]) Fractures.InsertNextCell(polygon) self.DFNData.SetPoints(self.points) self.DFNData.SetPolys(Fractures) #Append the Fracture ID into Output FracID = vtk.vtkIntArray() FracID.SetNumberOfValues(self.DFN_GeoData.NumFracs) #intArray->SetNumberOfComponents(1); FracID.SetName("FractureID") for i in range(self.DFN_GeoData.NumFracs): FracID.SetValue(i, i) self.DFNData.GetCellData().SetScalars(FracID) self.DFNData.Modified() #Append frac props if applicable if (len(self.DFN_GeoData.perm_array) > 0): Perm = vtk_np.numpy_to_vtk(num_array=self.DFN_GeoData.perm_array, deep=True, array_type=vtk.VTK_FLOAT) Perm.SetName('Permeability (m^2)') self.DFNData.GetCellData().AddArray(Perm) if (len(self.DFN_GeoData.aperature_array) > 0): Aperature = vtk_np.numpy_to_vtk( num_array=self.DFN_GeoData.aperature_array, deep=True, array_type=vtk.VTK_FLOAT) Aperature.SetName('Aperature (m)') self.DFNData.GetCellData().AddArray(Aperature)
def add_polygon(self): colors = vtk.vtkNamedColors() points = vtk.vtkPoints() points.InsertNextPoint(self.coords[0][0], self.coords[0][1], self.coords[0][2]) points.InsertNextPoint(self.coords[1][0], self.coords[1][1], self.coords[1][2]) points.InsertNextPoint(self.coords[2][0], self.coords[2][1], self.coords[2][2]) points.InsertNextPoint(self.coords[3][0], self.coords[3][1], self.coords[3][2]) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) # make a quad polygon.GetPointIds().SetId(0, 0) polygon.GetPointIds().SetId(1, 1) polygon.GetPointIds().SetId(2, 2) polygon.GetPointIds().SetId(3, 3) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) # Create a PolyData polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(polygons) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polygonPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) r = random.randint(200, 235) / 255.0 g = random.randint(200, 255) / 255.0 b = 19 / 255.0 actor.GetProperty().SetDiffuseColor(r, g, b) # actor.GetProperty().SetColor(colors.GetColor3d("Green")) actor.key = self.thisBlock + "_" + self.faceName + "_boundary" self.renderer.AddActor(actor) self.renderer.Render()
def genPoly(coords,pts,filled=True): N = pts.GetNumberOfPoints() if filled: poly = vtk.vtkPolygon() else: poly = vtk.vtkPolyLine() pid = poly.GetPointIds() n = len(coords) pid.SetNumberOfIds(n) for j in range(n): c = list(coords[j]) if len(c)==2: c.append(0) pts.InsertNextPoint(*c) pid.SetId(j,j+N) return poly
def genPoly(coords, pts, filled=True): N = pts.GetNumberOfPoints() if filled: poly = vtk.vtkPolygon() else: poly = vtk.vtkPolyLine() pid = poly.GetPointIds() n = len(coords) pid.SetNumberOfIds(n) for j in range(n): c = list(coords[j]) if len(c) == 2: c.append(0) pts.InsertNextPoint(*c) pid.SetId(j, j + N) return poly
def irregular_right_prism_to_polydata(prism): """References: - https://cmake.org/Wiki/VTK/Examples/Python/GeometricObjects/Display/Polygon """ sympy_polygon = prism.polygon_base surface_color = prism.surface_color base_p = prism.position vtk_polydata = vtk.vtkPolyData() # Setup four points points = vtk.vtkPoints() points_number = 0 for p in prism.get_point3d_list(): points_number = points_number + 1 points.InsertNextPoint(p.x, p.y, p.z) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() # Create the polygon for my_polygon in prism.get_polygon_list_by_index(): print(my_polygon) polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(len(prism.get_point3d_list())) polygon.GetPoints().DeepCopy(points) for my_point in my_polygon: print(my_point) polygon.GetPointIds().SetId(my_point, my_point) polygons.InsertNextCell(polygon) # Create a PolyData vtk_polydata.SetPoints(points) vtk_polydata.SetPolys(polygons) # setup colors (setting the name to "Colors" is nice but not necessary) vtk_colors = vtk.vtkUnsignedCharArray() vtk_colors.SetNumberOfComponents(3) vtk_colors.SetName("Colors") vtk_colors.InsertNextTuple3(surface_color.red, surface_color.green, surface_color.blue) vtk_polydata.GetCellData().SetScalars(vtk_colors) vtk_polydata.Modified() return vtk_polydata
def _generate_vtk_objects(self): """Generate vtk_points, vtk_polygons, vtk_poly_data, vtk_scalars, vtk_mapper and vtk_actor. This function must be called after _generate_points_and_polys()""" self._vtk_points = _vtk.vtkPoints() for coordinates in self._points: self._vtk_points.InsertNextPoint(coordinates[0], coordinates[1], coordinates[2]) self._vtk_polygons = _vtk.vtkCellArray() for polygon in self._polygons: vtk_polygon = _vtk.vtkPolygon() vtk_polygon.GetPointIds().SetNumberOfIds(3) for local_index, global_index in enumerate(polygon): vtk_polygon.GetPointIds().SetId(local_index, global_index) self._vtk_polygons.InsertNextCell(vtk_polygon) self._vtk_poly_data = _vtk.vtkPolyData() self._vtk_poly_data.SetPoints(self._vtk_points) self._vtk_poly_data.SetPolys(self._vtk_polygons) self._vtk_scalars = _vtk.vtkFloatArray() self._vtk_scalars.SetNumberOfValues( self._vtk_poly_data.GetPoints().GetNumberOfPoints()) for i in range(self._vtk_scalars.GetNumberOfTuples()): self._vtk_scalars.SetValue(i, 0.) self._vtk_poly_data.GetPointData().SetScalars(self._vtk_scalars) self._vtk_poly_data.Modified() self._vtk_mapper = _vtk.vtkPolyDataMapper() if VTK_VERSION < 6: self._vtk_mapper.SetInput(self._vtk_poly_data) else: self._vtk_mapper.SetInputData(self._vtk_poly_data) self._vtk_mapper.InterpolateScalarsBeforeMappingOn() self._vtk_mapper.UseLookupTableScalarRangeOn() self._vtk_actor = _vtk.vtkActor() self._vtk_actor.SetMapper(self._vtk_mapper) normals = _vtk.vtkFloatArray() normals.SetNumberOfComponents(3) for point in self._points: normals.InsertNextTuple(point) self._vtk_poly_data.GetPointData().SetNormals(normals)
def _square_slice(self): """Return a polydata of a square slice.""" polygons = vtk.vtkCellArray() for i in range(self._side-1): for j in range(self._side-1): corners = [(i, j), (i+1, j), (i+1, j+1), (i, j+1)] polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) for index, corner in enumerate(corners): polygon.GetPointIds().SetId(index, corner[0]*self._side+corner[1]) polygons.InsertNextCell(polygon) template_poly_data = vtk.vtkPolyData() template_poly_data.SetPoints(self._points) template_poly_data.GetPointData().SetScalars(self._image_values) template_poly_data.SetPolys(polygons) return template_poly_data
def irregular_right_prism_to_vtk_polydata(prism): """References: - https://cmake.org/Wiki/VTK/Examples/Python/GeometricObjects/Display/Polygon """ sympy_polygon = prism.polygon_base surface_color = prism.surface_color base_p = prism.position vtk_polydata = vtk.vtkPolyData() # Setup four points points = vtk.vtkPoints() points_number = 0 for p in sympy_polygon.vertices: points_number = points_number + 1 x = float(p.x) y = float(p.y) z = float(base_p.z) points.InsertNextPoint(x, y, z) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(points_number) # make a quad for i in range(0, points_number): polygon.GetPointIds().SetId(i, i) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) # Create a PolyData vtk_polydata.SetPoints(points) vtk_polydata.SetPolys(polygons) # setup colors (setting the name to "Colors" is nice but not necessary) vtk_colors = vtk.vtkUnsignedCharArray() vtk_colors.SetNumberOfComponents(3) vtk_colors.SetName("Colors") vtk_colors.InsertNextTuple3(surface_color.red, surface_color.green, surface_color.blue) vtk_polydata.GetCellData().SetScalars(vtk_colors) vtk_polydata.Modified() return vtk_polydata
def __init__(self): vtkCameraManipulator.__init__(self) self._start_position = [0, 0] self._end_position = [0, 0] self._pixel_array = vtk.vtkUnsignedCharArray() self._left_button_down = False self._ctrl_left_button_down = False self._right_button_down = False self._middle_button_down = False self._down_pos = None self._up_pos = None self._point_list = [] self.renderer = None self.iren = None #self.reset_polygon() self._points = 0 self.polygon = vtk.vtkPolygon() self.poly_data = vtk.vtkPolyData() self.poly_points = vtk.vtkPoints() self.poly_data.SetPoints(self.poly_points) self.cell_array = vtk.vtkCellArray() self.cell_array.InsertNextCell(self.polygon) self.cell_array.Squeeze() self.poly_data.SetPolys(self.cell_array) self.done_picking = MrSignal() self._picking_active = False self.poly_pick_filter = PolyPickFilter() self.poly_pick_filter.set_poly_pick_data(self.poly_data) self.vtk_graphics = VTKGraphics.instance() from .picking_manager import PickingManager self.picking_manager = PickingManager.instance()
def _square_slice(self): """Call in the beginning. Precalculates the polydata object without rotation.""" self._polygons.Initialize() for i in range(self._side-1): for j in range(self._side-1): corners = [(i, j), (i+1, j), (i+1, j+1), (i, j+1)] polygon = _vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) for index, corner in enumerate(corners): polygon.GetPointIds().SetId(index, corner[0]*self._side+corner[1]) self._polygons.InsertNextCell(polygon) self._template_poly_data = _vtk.vtkPolyData() self._template_poly_data.SetPoints(self._points) self._template_poly_data.GetPointData().SetScalars(self._image_values) self._template_poly_data.SetPolys(self._polygons)
def _generate_vtk_objects(self): """Generate vtk_points, vtk_polygons, vtk_poly_data, vtk_scalars, vtk_mapper and vtk_actor. This function must be called after _generate_points_and_polys()""" self._vtk_points = _vtk.vtkPoints() for coordinates in self._points: self._vtk_points.InsertNextPoint(coordinates[0], coordinates[1], coordinates[2]) self._vtk_polygons = _vtk.vtkCellArray() for polygon in self._polygons: vtk_polygon = _vtk.vtkPolygon() vtk_polygon.GetPointIds().SetNumberOfIds(3) for local_index, global_index in enumerate(polygon): vtk_polygon.GetPointIds().SetId(local_index, global_index) self._vtk_polygons.InsertNextCell(vtk_polygon) self._vtk_poly_data = _vtk.vtkPolyData() self._vtk_poly_data.SetPoints(self._vtk_points) self._vtk_poly_data.SetPolys(self._vtk_polygons) self._vtk_scalars = _vtk.vtkFloatArray() self._vtk_scalars.SetNumberOfValues(self._vtk_poly_data.GetPoints().GetNumberOfPoints()) for i in range(self._vtk_scalars.GetNumberOfTuples()): self._vtk_scalars.SetValue(i, 0.) self._vtk_poly_data.GetPointData().SetScalars(self._vtk_scalars) self._vtk_poly_data.Modified() self._vtk_mapper = _vtk.vtkPolyDataMapper() if VTK_VERSION < 6: self._vtk_mapper.SetInput(self._vtk_poly_data) else: self._vtk_mapper.SetInputData(self._vtk_poly_data) self._vtk_mapper.InterpolateScalarsBeforeMappingOn() self._vtk_mapper.UseLookupTableScalarRangeOn() self._vtk_actor = _vtk.vtkActor() self._vtk_actor.SetMapper(self._vtk_mapper) normals = _vtk.vtkFloatArray() normals.SetNumberOfComponents(3) for point in self._points: normals.InsertNextTuple(point) self._vtk_poly_data.GetPointData().SetNormals(normals)
def _circular_slice(self): """Return a cellarray of a square slice.""" polygons = vtk.vtkCellArray() for i in range(self._side-1): for j in range(self._side-1): corners = [(i, j), (i+1, j), (i+1, j+1), (i, j+1)] radius = max([numpy.sqrt((c[0] - self._side/2. + 0.5)**2 + (c[1] - self._side/2. + 0.5)**2) for c in corners]) if radius < self._side/2.: polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) for index, corner in enumerate(corners): polygon.GetPointIds().SetId(index, corner[0]*self._side+corner[1]) polygons.InsertNextCell(polygon) template_poly_data = vtk.vtkPolyData() template_poly_data.SetPoints(self._points) template_poly_data.GetPointData().SetScalars(self._image_values) template_poly_data.SetPolys(polygons) return template_poly_data
def createActor1(self): # Create source polyDataPoints = vtk.vtkPoints() polyDataPoints.InsertPoint(0, 1., 0., 0.) polyDataPoints.InsertPoint(1, 1., 0., 10.) polyDataPoints.InsertPoint(2, 3., 0., 10.) polyDataPoints.InsertPoint(3, 2., 0., 0.) polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) polygon.GetPointIds().SetId(0, 0) polygon.GetPointIds().SetId(1, 1) polygon.GetPointIds().SetId(2, 2) polygon.GetPointIds().SetId(3, 3) polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) polyData = vtk.vtkPolyData() polyData.SetPoints(polyDataPoints) #polyData.SetLines(polygons) polyData.SetPolys(polygons) rotationalExtrusionFilter = vtk.vtkRotationalExtrusionFilter() rotationalExtrusionFilter.SetInput(polyData) rotationalExtrusionFilter.SetResolution(10) rotationalExtrusionFilter.SetAngle(240) rotationalExtrusionFilter.SetTranslation(0) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(rotationalExtrusionFilter.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) #actor.GetProperty().SetColor(1.0, 0, 0) return actor
def getpolyactor(poly, h=0): points = vtk.vtkPoints() for p in poly: print 'getpolyactor', p if len(p) == 2: p = [p[0], p[1], h] points.InsertNextPoint(p) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(len(poly)-1) for i in range(len(poly)-1): polygon.GetPointIds().SetId(i, i) # polygon.GetPointIds().SetId(0, 0) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) # Create a PolyData polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(polygons) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(polygonPolyData) else: mapper.SetInputData(polygonPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def makePolygon(polygon,elevation=0,triangulate=False): """ Function to make a 2D vtk polygon PolyData from points making up a polygon. Inputs polygon - array list of vertices in clockwise order elevation - float, elevation of the polygon triangulate - boolean, triangulate the surface Output polyData - returns polydata of the surface polygon """ # Make a enclosed polygons nrBasepts = len(polygon) ptsArr = np.hstack((polygon,np.ones((polygon.shape[0],1))*elevation)) ppts = vtk.vtkPoints() ppts.SetData(npsup.numpy_to_vtk(ptsArr,deep=1)) # Make the cells array of polygons polys = vtk.vtkCellArray() poly = vtk.vtkPolygon() poly.GetPointIds().SetNumberOfIds(len(ptsArr)) for ind in np.arange(len(ptsArr)): poly.GetPointIds().SetId(ind,ind) polys.InsertNextCell(poly) polyPolyData = vtk.vtkPolyData() polyPolyData.SetPoints(ppts) polyPolyData.SetPolys(polys) if triangulate: triFilt = vtk.vtkTriangleFilter() triFilt.SetInputData(polyPolyData) triFilt.Update() return triFilt.GetOutput() else: return polyPolyData
def decimate(points, faces, reduction=0.5, smooth_steps=100, scalars=[], save_vtk=False, output_vtk=''): """ Decimate vtk triangular mesh with vtk.vtkDecimatePro. Parameters ---------- points : list of lists of floats each element is a list of 3-D coordinates of a vertex on a surface mesh faces : list of lists of integers each element is list of 3 indices of vertices that form a face on a surface mesh reduction : float fraction of mesh faces to remove smooth_steps : integer number of smoothing steps scalars : list of integers or floats optional scalars for output VTK file save_vtk : Boolean output decimated vtk file? output_vtk : string output decimated vtk file name Returns ------- points : list of lists of floats decimated points faces : list of lists of integers decimated faces scalars : list of integers or floats scalars for output VTK file output_vtk : string output decimated vtk file Examples -------- >>> import os >>> from mindboggle.utils.io_vtk import read_vtk, write_vtk >>> from mindboggle.utils.mesh import decimate >>> from mindboggle.utils.plots import plot_vtk >>> path = os.environ['MINDBOGGLE_DATA'] >>> input_vtk = os.path.join(path, 'arno', 'labels', 'label22.vtk') >>> reduction = 0.5 >>> smooth_steps = 100 >>> save_vtk = False >>> output_vtk = '' >>> faces, lines, indices, points, npoints, scalars, scalar_names, ... o2 = read_vtk(input_vtk) >>> points, faces, scalars, output_vtk = decimate(points, faces, reduction, >>> smooth_steps, scalars, >>> save_vtk, output_vtk) >>> len(points) == 2679 True >>> len(points) 2679 >>> # View: >>> output_vtk = 'decimated.vtk' >>> write_vtk(output_vtk, points, indices, lines, faces, scalars, >>> scalar_names) # doctest: +SKIP >>> plot_vtk(output_vtk) # doctest: +SKIP """ import os import vtk #------------------------------------------------------------------------- # vtk points: #------------------------------------------------------------------------- vtk_points = vtk.vtkPoints() [vtk_points.InsertPoint(i, x[0], x[1], x[2]) for i,x in enumerate(points)] #------------------------------------------------------------------------- # vtk faces: #------------------------------------------------------------------------- vtk_faces = vtk.vtkCellArray() for face in faces: vtk_face = vtk.vtkPolygon() vtk_face.GetPointIds().SetNumberOfIds(3) vtk_face.GetPointIds().SetId(0, face[0]) vtk_face.GetPointIds().SetId(1, face[1]) vtk_face.GetPointIds().SetId(2, face[2]) vtk_faces.InsertNextCell(vtk_face) #------------------------------------------------------------------------- # vtk scalars: #------------------------------------------------------------------------- if scalars: vtk_scalars = vtk.vtkFloatArray() vtk_scalars.SetName("scalars") for scalar in scalars: vtk_scalars.InsertNextValue(scalar) #------------------------------------------------------------------------- # vtkPolyData: #------------------------------------------------------------------------- polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.SetPolys(vtk_faces) if scalars: polydata.GetPointData().SetScalars(vtk_scalars) #------------------------------------------------------------------------- # Decimate: #------------------------------------------------------------------------- # We want to preserve topology (not let any cracks form). # This may limit the total reduction possible. decimate = vtk.vtkDecimatePro() decimate.SetInput(polydata) decimate.SetTargetReduction(reduction) decimate.PreserveTopologyOn() #------------------------------------------------------------------------- # Smooth: #------------------------------------------------------------------------- if save_vtk: if not output_vtk: output_vtk = os.path.join(os.getcwd(), 'decimated.vtk') exporter = vtk.vtkPolyDataWriter() if smooth_steps > 0: smoother = vtk.vtkSmoothPolyDataFilter() smoother.SetInput(decimate.GetOutput()) smoother.SetNumberOfIterations(smooth_steps) smoother.Update() out = smoother.GetOutput() if save_vtk: exporter.SetInput(smoother.GetOutput()) else: decimate.Update() out = decimate.GetOutput() if save_vtk: exporter.SetInput(decimate.GetOutput()) #------------------------------------------------------------------------- # Export output: #------------------------------------------------------------------------- if save_vtk: exporter.SetFileName(output_vtk) exporter.Write() if not os.path.exists(output_vtk): raise(IOError(output_vtk + " not found")) #------------------------------------------------------------------------- # Extract decimated points, faces, and scalars: #------------------------------------------------------------------------- points = [list(out.GetPoint(point_id)) for point_id in range(out.GetNumberOfPoints())] if out.GetNumberOfPolys() > 0: polys = out.GetPolys() pt_data = out.GetPointData() faces = [[int(polys.GetData().GetValue(j)) for j in range(i*4 + 1, i*4 + 4)] for i in range(polys.GetNumberOfCells())] if scalars: scalars = [pt_data.GetScalars().GetValue(i) for i in range(len(points))] else: faces = [] scalars = [] return points, faces, scalars, output_vtk
#!/usr/bin/env python import vtk # Setup four points points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(1.0, 1.0, 0.0) points.InsertNextPoint(0.0, 1.0, 0.0) # Create the polygon polygon = vtk.vtkPolygon() polygon.GetPointIds().SetNumberOfIds(4) #make a quad polygon.GetPointIds().SetId(0, 0) polygon.GetPointIds().SetId(1, 1) polygon.GetPointIds().SetId(2, 2) polygon.GetPointIds().SetId(3, 3) # Add the polygon to a list of polygons polygons = vtk.vtkCellArray() polygons.InsertNextCell(polygon) # Create a PolyData polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(points) polygonPolyData.SetPolys(polygons) # Create a mapper and actor mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5:
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(self.Surface) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.Loop == None: self.PrintError('Error: no Loop.') select = vtk.vtkImplicitSelectionLoop() select.SetLoop(self.Loop.GetPoints()) normal = [0.0,0.0,0.0] centroid = [0.0,0.0,0.0] vtk.vtkPolygon().ComputeNormal(self.Loop.GetPoints(),normal) #compute centroid and check normals p = [0.0,0.0,0.0] for i in range (self.Loop.GetNumberOfPoints()): p = self.Loop.GetPoint(i) centroid[0] += p[0] centroid[1] += p[1] centroid[2] += p[2] centroid[0] = centroid[0] / self.Loop.GetNumberOfPoints() centroid[1] = centroid[1] / self.Loop.GetNumberOfPoints() centroid[2] = centroid[2] / self.Loop.GetNumberOfPoints() print "loop centroid", centroid locator = vtk.vtkPointLocator() locator.SetDataSet(self.Surface) locator.AutomaticOn() locator.BuildLocator() idsurface = locator.FindClosestPoint(centroid) if (self.Surface.GetPointData().GetNormals() == None): normalsFilter = vmtkscripts.vmtkSurfaceNormals() normalsFilter.Surface = self.Surface normalsFilter.NormalsArrayName = 'Normals' normalsFilter.Execute() self.Surface = normalsFilter.Surface normalsurface = [0.0,0.0,0.0] self.Surface.GetPointData().GetNormals().GetTuple(idsurface,normalsurface) print "loop normal: ", normal print "surface normal inside the loop: ", normalsurface check = vtk.vtkMath.Dot(normalsurface,normal) if check < 0: normal[0] = - normal[0] normal[1] = - normal[1] normal[2] = - normal[2] #compute plane proj = float(vtk.vtkMath.Dot(self.Loop.GetPoint(0),normal)) point = [0.0,0.0,0.0] self.Loop.GetPoint(0,point) for i in range (self.Loop.GetNumberOfPoints()): tmp = vtk.vtkMath.Dot(self.Loop.GetPoint(i),normal) if tmp < proj: proj = tmp self.Loop.GetPoint(i,point) origin = [0.0,0.0,0.0] origin[0] = point[0] #- normal[0] origin[1] = point[1] #- normal[1] origin[2] = point[2] #- normal[2] plane=vtk.vtkPlane() plane.SetNormal(normal[0],normal[1],normal[2]) plane.SetOrigin(origin[0],origin[1],origin[2]) #set bool Bool = vtk.vtkImplicitBoolean() Bool.SetOperationTypeToDifference() Bool.AddFunction(select) Bool.AddFunction(plane) clipper=vtk.vtkClipPolyData() clipper.SetInput(self.Surface) clipper.SetClipFunction(Bool) clipper.GenerateClippedOutputOn() clipper.InsideOutOff() clipper.Update() self.Surface = clipper.GetOutput()
def decimate_file(input_vtk, reduction=0.5, smooth_steps=100, output_vtk=''): """ Decimate vtk triangular mesh file with vtk.vtkDecimatePro. Parameters ---------- input_vtk : string input vtk file with triangular surface mesh reduction : float fraction of mesh faces to remove do_smooth : Boolean smooth after decimation? output_vtk : string output decimated vtk file Returns ------- output_vtk : string output decimated vtk file Examples -------- >>> import os >>> from mindboggle.utils.mesh import decimate_file >>> path = os.environ['MINDBOGGLE_DATA'] >>> input_vtk = os.path.join(path, 'arno', 'labels', 'label22.vtk') >>> output_vtk = 'decimated_file.vtk' >>> reduction = 0.9 >>> smooth_steps = 0 >>> decimate_file(input_vtk, reduction=reduction, >>> smooth_steps=smooth_steps, output_vtk=output_vtk) >>> # View: >>> os.system('mayavi2 -d ' + output_vtk + ' -m Surface &') """ import os import vtk from mindboggle.utils.io_vtk import read_vtk # Read VTK surface mesh file: faces, u1, u2, points, u4, labels, u5, u6 = read_vtk(input_vtk) # vtk points: vtk_points = vtk.vtkPoints() [vtk_points.InsertPoint(i, x[0], x[1], x[2]) for i,x in enumerate(points)] # vtk faces: vtk_faces = vtk.vtkCellArray() for face in faces: vtk_face = vtk.vtkPolygon() vtk_face.GetPointIds().SetNumberOfIds(3) vtk_face.GetPointIds().SetId(0, face[0]) vtk_face.GetPointIds().SetId(1, face[1]) vtk_face.GetPointIds().SetId(2, face[2]) vtk_faces.InsertNextCell(vtk_face) # vtkPolyData: polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.SetPolys(vtk_faces) # We want to preserve topology (not let any cracks form). # This may limit the total reduction possible. decimate = vtk.vtkDecimatePro() decimate.SetInput(polydata) decimate.SetTargetReduction(reduction) decimate.PreserveTopologyOn() # Export output: if not output_vtk: output_vtk = os.path.join(os.getcwd(), 'decimated_file.vtk') exporter = vtk.vtkPolyDataWriter() if smooth_steps > 0: smoother = vtk.vtkSmoothPolyDataFilter() smoother.SetInputConnection(decimate.GetOutputPort()) smoother.SetNumberOfIterations(smooth_steps) exporter.SetInput(smoother.GetOutput()) else: exporter.SetInput(decimate.GetOutput()) exporter.SetFileName(output_vtk) exporter.Write() return output_vtk
def testCells(self): # Demonstrates all cell types # # NOTE: the use of NewInstance/DeepCopy is included to increase # regression coverage. It is not required in most applications. ren = vtk.vtkRenderer() # turn off all cullers ren.GetCullers().RemoveAllItems() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(300, 150) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) # create a scene with one of each cell type # Voxel voxelPoints = vtk.vtkPoints() voxelPoints.SetNumberOfPoints(8) voxelPoints.InsertPoint(0, 0, 0, 0) voxelPoints.InsertPoint(1, 1, 0, 0) voxelPoints.InsertPoint(2, 0, 1, 0) voxelPoints.InsertPoint(3, 1, 1, 0) voxelPoints.InsertPoint(4, 0, 0, 1) voxelPoints.InsertPoint(5, 1, 0, 1) voxelPoints.InsertPoint(6, 0, 1, 1) voxelPoints.InsertPoint(7, 1, 1, 1) aVoxel = vtk.vtkVoxel() aVoxel.GetPointIds().SetId(0, 0) aVoxel.GetPointIds().SetId(1, 1) aVoxel.GetPointIds().SetId(2, 2) aVoxel.GetPointIds().SetId(3, 3) aVoxel.GetPointIds().SetId(4, 4) aVoxel.GetPointIds().SetId(5, 5) aVoxel.GetPointIds().SetId(6, 6) aVoxel.GetPointIds().SetId(7, 7) bVoxel = aVoxel.NewInstance() bVoxel.DeepCopy(aVoxel) aVoxelGrid = vtk.vtkUnstructuredGrid() aVoxelGrid.Allocate(1, 1) aVoxelGrid.InsertNextCell(aVoxel.GetCellType(), aVoxel.GetPointIds()) aVoxelGrid.SetPoints(voxelPoints) aVoxelMapper = vtk.vtkDataSetMapper() aVoxelMapper.SetInputData(aVoxelGrid) aVoxelActor = vtk.vtkActor() aVoxelActor.SetMapper(aVoxelMapper) aVoxelActor.GetProperty().BackfaceCullingOn() # Hexahedron hexahedronPoints = vtk.vtkPoints() hexahedronPoints.SetNumberOfPoints(8) hexahedronPoints.InsertPoint(0, 0, 0, 0) hexahedronPoints.InsertPoint(1, 1, 0, 0) hexahedronPoints.InsertPoint(2, 1, 1, 0) hexahedronPoints.InsertPoint(3, 0, 1, 0) hexahedronPoints.InsertPoint(4, 0, 0, 1) hexahedronPoints.InsertPoint(5, 1, 0, 1) hexahedronPoints.InsertPoint(6, 1, 1, 1) hexahedronPoints.InsertPoint(7, 0, 1, 1) aHexahedron = vtk.vtkHexahedron() aHexahedron.GetPointIds().SetId(0, 0) aHexahedron.GetPointIds().SetId(1, 1) aHexahedron.GetPointIds().SetId(2, 2) aHexahedron.GetPointIds().SetId(3, 3) aHexahedron.GetPointIds().SetId(4, 4) aHexahedron.GetPointIds().SetId(5, 5) aHexahedron.GetPointIds().SetId(6, 6) aHexahedron.GetPointIds().SetId(7, 7) bHexahedron = aHexahedron.NewInstance() bHexahedron.DeepCopy(aHexahedron) aHexahedronGrid = vtk.vtkUnstructuredGrid() aHexahedronGrid.Allocate(1, 1) aHexahedronGrid.InsertNextCell(aHexahedron.GetCellType(), aHexahedron.GetPointIds()) aHexahedronGrid.SetPoints(hexahedronPoints) aHexahedronMapper = vtk.vtkDataSetMapper() aHexahedronMapper.SetInputData(aHexahedronGrid) aHexahedronActor = vtk.vtkActor() aHexahedronActor.SetMapper(aHexahedronMapper) aHexahedronActor.AddPosition(2, 0, 0) aHexahedronActor.GetProperty().BackfaceCullingOn() # Tetra tetraPoints = vtk.vtkPoints() tetraPoints.SetNumberOfPoints(4) tetraPoints.InsertPoint(0, 0, 0, 0) tetraPoints.InsertPoint(1, 1, 0, 0) tetraPoints.InsertPoint(2, 0.5, 1, 0) tetraPoints.InsertPoint(3, 0.5, 0.5, 1) aTetra = vtk.vtkTetra() aTetra.GetPointIds().SetId(0, 0) aTetra.GetPointIds().SetId(1, 1) aTetra.GetPointIds().SetId(2, 2) aTetra.GetPointIds().SetId(3, 3) bTetra = aTetra.NewInstance() bTetra.DeepCopy(aTetra) aTetraGrid = vtk.vtkUnstructuredGrid() aTetraGrid.Allocate(1, 1) aTetraGrid.InsertNextCell(aTetra.GetCellType(), aTetra.GetPointIds()) aTetraGrid.SetPoints(tetraPoints) aTetraCopy = vtk.vtkUnstructuredGrid() aTetraCopy.ShallowCopy(aTetraGrid) aTetraMapper = vtk.vtkDataSetMapper() aTetraMapper.SetInputData(aTetraCopy) aTetraActor = vtk.vtkActor() aTetraActor.SetMapper(aTetraMapper) aTetraActor.AddPosition(4, 0, 0) aTetraActor.GetProperty().BackfaceCullingOn() # Wedge wedgePoints = vtk.vtkPoints() wedgePoints.SetNumberOfPoints(6) wedgePoints.InsertPoint(0, 0, 1, 0) wedgePoints.InsertPoint(1, 0, 0, 0) wedgePoints.InsertPoint(2, 0, 0.5, 0.5) wedgePoints.InsertPoint(3, 1, 1, 0) wedgePoints.InsertPoint(4, 1, 0, 0) wedgePoints.InsertPoint(5, 1, 0.5, 0.5) aWedge = vtk.vtkWedge() aWedge.GetPointIds().SetId(0, 0) aWedge.GetPointIds().SetId(1, 1) aWedge.GetPointIds().SetId(2, 2) aWedge.GetPointIds().SetId(3, 3) aWedge.GetPointIds().SetId(4, 4) aWedge.GetPointIds().SetId(5, 5) bWedge = aWedge.NewInstance() bWedge.DeepCopy(aWedge) aWedgeGrid = vtk.vtkUnstructuredGrid() aWedgeGrid.Allocate(1, 1) aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds()) aWedgeGrid.SetPoints(wedgePoints) aWedgeCopy = vtk.vtkUnstructuredGrid() aWedgeCopy.DeepCopy(aWedgeGrid) aWedgeMapper = vtk.vtkDataSetMapper() aWedgeMapper.SetInputData(aWedgeCopy) aWedgeActor = vtk.vtkActor() aWedgeActor.SetMapper(aWedgeMapper) aWedgeActor.AddPosition(6, 0, 0) aWedgeActor.GetProperty().BackfaceCullingOn() # Pyramid pyramidPoints = vtk.vtkPoints() pyramidPoints.SetNumberOfPoints(5) pyramidPoints.InsertPoint(0, 0, 0, 0) pyramidPoints.InsertPoint(1, 1, 0, 0) pyramidPoints.InsertPoint(2, 1, 1, 0) pyramidPoints.InsertPoint(3, 0, 1, 0) pyramidPoints.InsertPoint(4, 0.5, 0.5, 1) aPyramid = vtk.vtkPyramid() aPyramid.GetPointIds().SetId(0, 0) aPyramid.GetPointIds().SetId(1, 1) aPyramid.GetPointIds().SetId(2, 2) aPyramid.GetPointIds().SetId(3, 3) aPyramid.GetPointIds().SetId(4, 4) bPyramid = aPyramid.NewInstance() bPyramid.DeepCopy(aPyramid) aPyramidGrid = vtk.vtkUnstructuredGrid() aPyramidGrid.Allocate(1, 1) aPyramidGrid.InsertNextCell(aPyramid.GetCellType(), aPyramid.GetPointIds()) aPyramidGrid.SetPoints(pyramidPoints) aPyramidMapper = vtk.vtkDataSetMapper() aPyramidMapper.SetInputData(aPyramidGrid) aPyramidActor = vtk.vtkActor() aPyramidActor.SetMapper(aPyramidMapper) aPyramidActor.AddPosition(8, 0, 0) aPyramidActor.GetProperty().BackfaceCullingOn() # Pixel pixelPoints = vtk.vtkPoints() pixelPoints.SetNumberOfPoints(4) pixelPoints.InsertPoint(0, 0, 0, 0) pixelPoints.InsertPoint(1, 1, 0, 0) pixelPoints.InsertPoint(2, 0, 1, 0) pixelPoints.InsertPoint(3, 1, 1, 0) aPixel = vtk.vtkPixel() aPixel.GetPointIds().SetId(0, 0) aPixel.GetPointIds().SetId(1, 1) aPixel.GetPointIds().SetId(2, 2) aPixel.GetPointIds().SetId(3, 3) bPixel = aPixel.NewInstance() bPixel.DeepCopy(aPixel) aPixelGrid = vtk.vtkUnstructuredGrid() aPixelGrid.Allocate(1, 1) aPixelGrid.InsertNextCell(aPixel.GetCellType(), aPixel.GetPointIds()) aPixelGrid.SetPoints(pixelPoints) aPixelMapper = vtk.vtkDataSetMapper() aPixelMapper.SetInputData(aPixelGrid) aPixelActor = vtk.vtkActor() aPixelActor.SetMapper(aPixelMapper) aPixelActor.AddPosition(0, 0, 2) aPixelActor.GetProperty().BackfaceCullingOn() # Quad quadPoints = vtk.vtkPoints() quadPoints.SetNumberOfPoints(4) quadPoints.InsertPoint(0, 0, 0, 0) quadPoints.InsertPoint(1, 1, 0, 0) quadPoints.InsertPoint(2, 1, 1, 0) quadPoints.InsertPoint(3, 0, 1, 0) aQuad = vtk.vtkQuad() aQuad.GetPointIds().SetId(0, 0) aQuad.GetPointIds().SetId(1, 1) aQuad.GetPointIds().SetId(2, 2) aQuad.GetPointIds().SetId(3, 3) bQuad = aQuad.NewInstance() bQuad.DeepCopy(aQuad) aQuadGrid = vtk.vtkUnstructuredGrid() aQuadGrid.Allocate(1, 1) aQuadGrid.InsertNextCell(aQuad.GetCellType(), aQuad.GetPointIds()) aQuadGrid.SetPoints(quadPoints) aQuadMapper = vtk.vtkDataSetMapper() aQuadMapper.SetInputData(aQuadGrid) aQuadActor = vtk.vtkActor() aQuadActor.SetMapper(aQuadMapper) aQuadActor.AddPosition(2, 0, 2) aQuadActor.GetProperty().BackfaceCullingOn() # Triangle trianglePoints = vtk.vtkPoints() trianglePoints.SetNumberOfPoints(3) trianglePoints.InsertPoint(0, 0, 0, 0) trianglePoints.InsertPoint(1, 1, 0, 0) trianglePoints.InsertPoint(2, 0.5, 0.5, 0) triangleTCoords = vtk.vtkFloatArray() triangleTCoords.SetNumberOfComponents(2) triangleTCoords.SetNumberOfTuples(3) triangleTCoords.InsertTuple2(0, 1, 1) triangleTCoords.InsertTuple2(1, 2, 2) triangleTCoords.InsertTuple2(2, 3, 3) aTriangle = vtk.vtkTriangle() aTriangle.GetPointIds().SetId(0, 0) aTriangle.GetPointIds().SetId(1, 1) aTriangle.GetPointIds().SetId(2, 2) bTriangle = aTriangle.NewInstance() bTriangle.DeepCopy(aTriangle) aTriangleGrid = vtk.vtkUnstructuredGrid() aTriangleGrid.Allocate(1, 1) aTriangleGrid.InsertNextCell(aTriangle.GetCellType(), aTriangle.GetPointIds()) aTriangleGrid.SetPoints(trianglePoints) aTriangleGrid.GetPointData().SetTCoords(triangleTCoords) aTriangleMapper = vtk.vtkDataSetMapper() aTriangleMapper.SetInputData(aTriangleGrid) aTriangleActor = vtk.vtkActor() aTriangleActor.SetMapper(aTriangleMapper) aTriangleActor.AddPosition(4, 0, 2) aTriangleActor.GetProperty().BackfaceCullingOn() # Polygon polygonPoints = vtk.vtkPoints() polygonPoints.SetNumberOfPoints(4) polygonPoints.InsertPoint(0, 0, 0, 0) polygonPoints.InsertPoint(1, 1, 0, 0) polygonPoints.InsertPoint(2, 1, 1, 0) polygonPoints.InsertPoint(3, 0, 1, 0) aPolygon = vtk.vtkPolygon() aPolygon.GetPointIds().SetNumberOfIds(4) aPolygon.GetPointIds().SetId(0, 0) aPolygon.GetPointIds().SetId(1, 1) aPolygon.GetPointIds().SetId(2, 2) aPolygon.GetPointIds().SetId(3, 3) bPolygon = aPolygon.NewInstance() bPolygon.DeepCopy(aPolygon) aPolygonGrid = vtk.vtkUnstructuredGrid() aPolygonGrid.Allocate(1, 1) aPolygonGrid.InsertNextCell(aPolygon.GetCellType(), aPolygon.GetPointIds()) aPolygonGrid.SetPoints(polygonPoints) aPolygonMapper = vtk.vtkDataSetMapper() aPolygonMapper.SetInputData(aPolygonGrid) aPolygonActor = vtk.vtkActor() aPolygonActor.SetMapper(aPolygonMapper) aPolygonActor.AddPosition(6, 0, 2) aPolygonActor.GetProperty().BackfaceCullingOn() # Triangle Strip triangleStripPoints = vtk.vtkPoints() triangleStripPoints.SetNumberOfPoints(5) triangleStripPoints.InsertPoint(0, 0, 1, 0) triangleStripPoints.InsertPoint(1, 0, 0, 0) triangleStripPoints.InsertPoint(2, 1, 1, 0) triangleStripPoints.InsertPoint(3, 1, 0, 0) triangleStripPoints.InsertPoint(4, 2, 1, 0) triangleStripTCoords = vtk.vtkFloatArray() triangleStripTCoords.SetNumberOfComponents(2) triangleStripTCoords.SetNumberOfTuples(3) triangleStripTCoords.InsertTuple2(0, 1, 1) triangleStripTCoords.InsertTuple2(1, 2, 2) triangleStripTCoords.InsertTuple2(2, 3, 3) triangleStripTCoords.InsertTuple2(3, 4, 4) triangleStripTCoords.InsertTuple2(4, 5, 5) aTriangleStrip = vtk.vtkTriangleStrip() aTriangleStrip.GetPointIds().SetNumberOfIds(5) aTriangleStrip.GetPointIds().SetId(0, 0) aTriangleStrip.GetPointIds().SetId(1, 1) aTriangleStrip.GetPointIds().SetId(2, 2) aTriangleStrip.GetPointIds().SetId(3, 3) aTriangleStrip.GetPointIds().SetId(4, 4) bTriangleStrip = aTriangleStrip.NewInstance() bTriangleStrip.DeepCopy(aTriangleStrip) aTriangleStripGrid = vtk.vtkUnstructuredGrid() aTriangleStripGrid.Allocate(1, 1) aTriangleStripGrid.InsertNextCell(aTriangleStrip.GetCellType(), aTriangleStrip.GetPointIds()) aTriangleStripGrid.SetPoints(triangleStripPoints) aTriangleStripGrid.GetPointData().SetTCoords(triangleStripTCoords) aTriangleStripMapper = vtk.vtkDataSetMapper() aTriangleStripMapper.SetInputData(aTriangleStripGrid) aTriangleStripActor = vtk.vtkActor() aTriangleStripActor.SetMapper(aTriangleStripMapper) aTriangleStripActor.AddPosition(8, 0, 2) aTriangleStripActor.GetProperty().BackfaceCullingOn() # Line linePoints = vtk.vtkPoints() linePoints.SetNumberOfPoints(2) linePoints.InsertPoint(0, 0, 0, 0) linePoints.InsertPoint(1, 1, 1, 0) aLine = vtk.vtkLine() aLine.GetPointIds().SetId(0, 0) aLine.GetPointIds().SetId(1, 1) bLine = aLine.NewInstance() bLine.DeepCopy(aLine) aLineGrid = vtk.vtkUnstructuredGrid() aLineGrid.Allocate(1, 1) aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()) aLineGrid.SetPoints(linePoints) aLineMapper = vtk.vtkDataSetMapper() aLineMapper.SetInputData(aLineGrid) aLineActor = vtk.vtkActor() aLineActor.SetMapper(aLineMapper) aLineActor.AddPosition(0, 0, 4) aLineActor.GetProperty().BackfaceCullingOn() # Poly line polyLinePoints = vtk.vtkPoints() polyLinePoints.SetNumberOfPoints(3) polyLinePoints.InsertPoint(0, 0, 0, 0) polyLinePoints.InsertPoint(1, 1, 1, 0) polyLinePoints.InsertPoint(2, 1, 0, 0) aPolyLine = vtk.vtkPolyLine() aPolyLine.GetPointIds().SetNumberOfIds(3) aPolyLine.GetPointIds().SetId(0, 0) aPolyLine.GetPointIds().SetId(1, 1) aPolyLine.GetPointIds().SetId(2, 2) bPolyLine = aPolyLine.NewInstance() bPolyLine.DeepCopy(aPolyLine) aPolyLineGrid = vtk.vtkUnstructuredGrid() aPolyLineGrid.Allocate(1, 1) aPolyLineGrid.InsertNextCell(aPolyLine.GetCellType(), aPolyLine.GetPointIds()) aPolyLineGrid.SetPoints(polyLinePoints) aPolyLineMapper = vtk.vtkDataSetMapper() aPolyLineMapper.SetInputData(aPolyLineGrid) aPolyLineActor = vtk.vtkActor() aPolyLineActor.SetMapper(aPolyLineMapper) aPolyLineActor.AddPosition(2, 0, 4) aPolyLineActor.GetProperty().BackfaceCullingOn() # Vertex vertexPoints = vtk.vtkPoints() vertexPoints.SetNumberOfPoints(1) vertexPoints.InsertPoint(0, 0, 0, 0) aVertex = vtk.vtkVertex() aVertex.GetPointIds().SetId(0, 0) bVertex = aVertex.NewInstance() bVertex.DeepCopy(aVertex) aVertexGrid = vtk.vtkUnstructuredGrid() aVertexGrid.Allocate(1, 1) aVertexGrid.InsertNextCell(aVertex.GetCellType(), aVertex.GetPointIds()) aVertexGrid.SetPoints(vertexPoints) aVertexMapper = vtk.vtkDataSetMapper() aVertexMapper.SetInputData(aVertexGrid) aVertexActor = vtk.vtkActor() aVertexActor.SetMapper(aVertexMapper) aVertexActor.AddPosition(0, 0, 6) aVertexActor.GetProperty().BackfaceCullingOn() # Poly Vertex polyVertexPoints = vtk.vtkPoints() polyVertexPoints.SetNumberOfPoints(3) polyVertexPoints.InsertPoint(0, 0, 0, 0) polyVertexPoints.InsertPoint(1, 1, 0, 0) polyVertexPoints.InsertPoint(2, 1, 1, 0) aPolyVertex = vtk.vtkPolyVertex() aPolyVertex.GetPointIds().SetNumberOfIds(3) aPolyVertex.GetPointIds().SetId(0, 0) aPolyVertex.GetPointIds().SetId(1, 1) aPolyVertex.GetPointIds().SetId(2, 2) bPolyVertex = aPolyVertex.NewInstance() bPolyVertex.DeepCopy(aPolyVertex) aPolyVertexGrid = vtk.vtkUnstructuredGrid() aPolyVertexGrid.Allocate(1, 1) aPolyVertexGrid.InsertNextCell(aPolyVertex.GetCellType(), aPolyVertex.GetPointIds()) aPolyVertexGrid.SetPoints(polyVertexPoints) aPolyVertexMapper = vtk.vtkDataSetMapper() aPolyVertexMapper.SetInputData(aPolyVertexGrid) aPolyVertexActor = vtk.vtkActor() aPolyVertexActor.SetMapper(aPolyVertexMapper) aPolyVertexActor.AddPosition(2, 0, 6) aPolyVertexActor.GetProperty().BackfaceCullingOn() # Pentagonal prism pentaPoints = vtk.vtkPoints() pentaPoints.SetNumberOfPoints(10) pentaPoints.InsertPoint(0, 0.25, 0.0, 0.0) pentaPoints.InsertPoint(1, 0.75, 0.0, 0.0) pentaPoints.InsertPoint(2, 1.0, 0.5, 0.0) pentaPoints.InsertPoint(3, 0.5, 1.0, 0.0) pentaPoints.InsertPoint(4, 0.0, 0.5, 0.0) pentaPoints.InsertPoint(5, 0.25, 0.0, 1.0) pentaPoints.InsertPoint(6, 0.75, 0.0, 1.0) pentaPoints.InsertPoint(7, 1.0, 0.5, 1.0) pentaPoints.InsertPoint(8, 0.5, 1.0, 1.0) pentaPoints.InsertPoint(9, 0.0, 0.5, 1.0) aPenta = vtk.vtkPentagonalPrism() aPenta.GetPointIds().SetId(0, 0) aPenta.GetPointIds().SetId(1, 1) aPenta.GetPointIds().SetId(2, 2) aPenta.GetPointIds().SetId(3, 3) aPenta.GetPointIds().SetId(4, 4) aPenta.GetPointIds().SetId(5, 5) aPenta.GetPointIds().SetId(6, 6) aPenta.GetPointIds().SetId(7, 7) aPenta.GetPointIds().SetId(8, 8) aPenta.GetPointIds().SetId(9, 9) bPenta = aPenta.NewInstance() bPenta.DeepCopy(aPenta) aPentaGrid = vtk.vtkUnstructuredGrid() aPentaGrid.Allocate(1, 1) aPentaGrid.InsertNextCell(aPenta.GetCellType(), aPenta.GetPointIds()) aPentaGrid.SetPoints(pentaPoints) aPentaCopy = vtk.vtkUnstructuredGrid() aPentaCopy.DeepCopy(aPentaGrid) aPentaMapper = vtk.vtkDataSetMapper() aPentaMapper.SetInputData(aPentaCopy) aPentaActor = vtk.vtkActor() aPentaActor.SetMapper(aPentaMapper) aPentaActor.AddPosition(10, 0, 0) aPentaActor.GetProperty().BackfaceCullingOn() # Hexagonal prism hexaPoints = vtk.vtkPoints() hexaPoints.SetNumberOfPoints(12) hexaPoints.InsertPoint(0, 0.0, 0.0, 0.0) hexaPoints.InsertPoint(1, 0.5, 0.0, 0.0) hexaPoints.InsertPoint(2, 1.0, 0.5, 0.0) hexaPoints.InsertPoint(3, 1.0, 1.0, 0.0) hexaPoints.InsertPoint(4, 0.5, 1.0, 0.0) hexaPoints.InsertPoint(5, 0.0, 0.5, 0.0) hexaPoints.InsertPoint(6, 0.0, 0.0, 1.0) hexaPoints.InsertPoint(7, 0.5, 0.0, 1.0) hexaPoints.InsertPoint(8, 1.0, 0.5, 1.0) hexaPoints.InsertPoint(9, 1.0, 1.0, 1.0) hexaPoints.InsertPoint(10, 0.5, 1.0, 1.0) hexaPoints.InsertPoint(11, 0.0, 0.5, 1.0) aHexa = vtk.vtkHexagonalPrism() aHexa.GetPointIds().SetId(0, 0) aHexa.GetPointIds().SetId(1, 1) aHexa.GetPointIds().SetId(2, 2) aHexa.GetPointIds().SetId(3, 3) aHexa.GetPointIds().SetId(4, 4) aHexa.GetPointIds().SetId(5, 5) aHexa.GetPointIds().SetId(6, 6) aHexa.GetPointIds().SetId(7, 7) aHexa.GetPointIds().SetId(8, 8) aHexa.GetPointIds().SetId(9, 9) aHexa.GetPointIds().SetId(10, 10) aHexa.GetPointIds().SetId(11, 11) bHexa = aHexa.NewInstance() bHexa.DeepCopy(aHexa) aHexaGrid = vtk.vtkUnstructuredGrid() aHexaGrid.Allocate(1, 1) aHexaGrid.InsertNextCell(aHexa.GetCellType(), aHexa.GetPointIds()) aHexaGrid.SetPoints(hexaPoints) aHexaCopy = vtk.vtkUnstructuredGrid() aHexaCopy.DeepCopy(aHexaGrid) aHexaMapper = vtk.vtkDataSetMapper() aHexaMapper.SetInputData(aHexaCopy) aHexaActor = vtk.vtkActor() aHexaActor.SetMapper(aHexaMapper) aHexaActor.AddPosition(12, 0, 0) aHexaActor.GetProperty().BackfaceCullingOn() # RIB property aRIBProperty = vtk.vtkRIBProperty() aRIBProperty.SetVariable("Km", "float") aRIBProperty.SetSurfaceShader("LGVeinedmarble") aRIBProperty.SetVariable("veinfreq", "float") aRIBProperty.AddVariable("warpfreq", "float") aRIBProperty.AddVariable("veincolor", "color") aRIBProperty.AddParameter("veinfreq", " 2") aRIBProperty.AddParameter("veincolor", "1.0000 1.0000 0.9412") bRIBProperty = vtk.vtkRIBProperty() bRIBProperty.SetVariable("Km", "float") bRIBProperty.SetParameter("Km", "1.0") bRIBProperty.SetDisplacementShader("dented") bRIBProperty.SetSurfaceShader("plastic") aProperty = vtk.vtkProperty() bProperty = vtk.vtkProperty() aTriangleActor.SetProperty(aProperty) aTriangleStripActor.SetProperty(bProperty) ren.SetBackground(0.1, 0.2, 0.4) ren.AddActor(aVoxelActor) aVoxelActor.GetProperty().SetDiffuseColor(1, 0, 0) ren.AddActor(aHexahedronActor) aHexahedronActor.GetProperty().SetDiffuseColor(1, 1, 0) ren.AddActor(aTetraActor) aTetraActor.GetProperty().SetDiffuseColor(0, 1, 0) ren.AddActor(aWedgeActor) aWedgeActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aPyramidActor) aPyramidActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aPixelActor) aPixelActor.GetProperty().SetDiffuseColor(0, 1, 1) ren.AddActor(aQuadActor) aQuadActor.GetProperty().SetDiffuseColor(1, 0, 1) ren.AddActor(aTriangleActor) aTriangleActor.GetProperty().SetDiffuseColor(0.3, 1, 0.5) ren.AddActor(aPolygonActor) aPolygonActor.GetProperty().SetDiffuseColor(1, 0.4, 0.5) ren.AddActor(aTriangleStripActor) aTriangleStripActor.GetProperty().SetDiffuseColor(0.3, 0.7, 1) ren.AddActor(aLineActor) aLineActor.GetProperty().SetDiffuseColor(0.2, 1, 1) ren.AddActor(aPolyLineActor) aPolyLineActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aVertexActor) aVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPolyVertexActor) aPolyVertexActor.GetProperty().SetDiffuseColor(1, 1, 1) ren.AddActor(aPentaActor) aPentaActor.GetProperty().SetDiffuseColor(0.2, 0.4, 0.7) ren.AddActor(aHexaActor) aHexaActor.GetProperty().SetDiffuseColor(0.7, 0.5, 1) aRIBLight = vtk.vtkRIBLight() aRIBLight.ShadowsOn() aLight = vtk.vtkLight() aLight.PositionalOn() aLight.SetConeAngle(25) ren.AddLight(aLight) ren.ResetCamera() ren.GetActiveCamera().Azimuth(30) ren.GetActiveCamera().Elevation(20) ren.GetActiveCamera().Dolly(2.8) ren.ResetCameraClippingRange() aLight.SetFocalPoint(ren.GetActiveCamera().GetFocalPoint()) aLight.SetPosition(ren.GetActiveCamera().GetPosition()) # write to the temp directory if possible, otherwise use . dir = tempfile.gettempdir() atext = vtk.vtkTexture() pnmReader = vtk.vtkBMPReader() pnmReader.SetFileName(VTK_DATA_ROOT + "/Data/masonry.bmp") atext.SetInputConnection(pnmReader.GetOutputPort()) atext.InterpolateOff() aTriangleActor.SetTexture(atext) rib = vtk.vtkRIBExporter() rib.SetInput(renWin) rib.SetFilePrefix(dir + "/cells") rib.SetTexturePrefix(dir + "/cells") rib.Write() os.remove(dir + "/cells.rib") iv = vtk.vtkIVExporter() iv.SetInput(renWin) iv.SetFileName(dir + "/cells.iv") iv.Write() os.remove(dir + "/cells.iv") obj = vtk.vtkOBJExporter() obj.SetInput(renWin) obj.SetFilePrefix(dir + "/cells") obj.Write() os.remove(dir + "/cells.obj") os.remove(dir + "/cells.mtl") vrml = vtk.vtkVRMLExporter() vrml.SetInput(renWin) # vrml.SetStartWrite(vrml.SetFileName(dir + "/cells.wrl")) # vrml.SetEndWrite(vrml.SetFileName("/a/acells.wrl")) vrml.SetFileName(dir + "/cells.wrl") vrml.SetSpeed(5.5) vrml.Write() os.remove(dir + "/cells.wrl") oogl = vtk.vtkOOGLExporter() oogl.SetInput(renWin) oogl.SetFileName(dir + "/cells.oogl") oogl.Write() os.remove(dir + "/cells.oogl") # the UnRegister calls are because make object is the same as New, # and causes memory leaks. (Python does not treat NewInstance the same as New). def DeleteCopies(): bVoxel.UnRegister(None) bHexahedron.UnRegister(None) bTetra.UnRegister(None) bWedge.UnRegister(None) bPyramid.UnRegister(None) bPixel.UnRegister(None) bQuad.UnRegister(None) bTriangle.UnRegister(None) bPolygon.UnRegister(None) bTriangleStrip.UnRegister(None) bLine.UnRegister(None) bPolyLine.UnRegister(None) bVertex.UnRegister(None) bPolyVertex.UnRegister(None) bPenta.UnRegister(None) bHexa.UnRegister(None) DeleteCopies() # render and interact with data renWin.Render() img_file = "cells.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
path = os.environ['MINDBOGGLE_DATA'] input_vtk = os.path.join(path, 'arno', 'labels', 'label22.vtk') reduction = 0.5 smooth_steps = 100 faces, lines, indices, points, npoints, labels, o1, o2 = read_vtk(input_vtk) import vtk # vtk points: vtk_points = vtk.vtkPoints() [vtk_points.InsertPoint(i, x[0], x[1], x[2]) for i,x in enumerate(points)] # vtk faces: vtk_faces = vtk.vtkCellArray() for face in faces: vtk_face = vtk.vtkPolygon() vtk_face.GetPointIds().SetNumberOfIds(3) vtk_face.GetPointIds().SetId(0, face[0]) vtk_face.GetPointIds().SetId(1, face[1]) vtk_face.GetPointIds().SetId(2, face[2]) vtk_faces.InsertNextCell(vtk_face) # vtkPolyData: polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.SetPolys(vtk_faces) # We want to preserve topology (not let any cracks form). # This may limit the total reduction possible. decimate = vtk.vtkDecimatePro() decimate.SetInput(polydata)
def decimate(points, faces, reduction=0.5, smooth_steps=100, output_vtk=''): """ Decimate vtk triangular mesh with vtk.vtkDecimatePro. Parameters ---------- points : list of lists of floats each element is a list of 3-D coordinates of a vertex on a surface mesh faces : list of lists of integers each element is list of 3 indices of vertices that form a face on a surface mesh reduction : float fraction of mesh faces to remove smooth_steps : integer number of smoothing steps output_vtk : string output decimated vtk file Returns ------- points : list of lists of floats decimated points faces : list of lists of integers decimated faces output_vtk : string output decimated vtk file Examples -------- >>> import os >>> from mindboggle.utils.io_vtk import read_vtk, write_vtk >>> from mindboggle.utils.mesh import decimate >>> path = os.environ['MINDBOGGLE_DATA'] >>> input_vtk = os.path.join(path, 'arno', 'labels', 'label22.vtk') >>> reduction = 0.5 >>> smooth_steps = 100 >>> output_vtk = '' >>> faces, lines, indices, points, npoints, scalars, scalar_names, ... o2 = read_vtk(input_vtk) >>> points, faces, output_vtk = decimate(points, faces, reduction, >>> smooth_steps, output_vtk) >>> len(points) == 4567 True >>> len(points) 4567 >>> # View: >>> write_vtk('decimated.vtk', points, indices, lines, faces, scalars, >>> scalar_names) # doctest: +SKIP >>> os.system('mayavi2 -d decimated.vtk -m Surface &') # doctest: +SKIP """ import os import vtk from mindboggle.utils.io_vtk import read_vtk # vtk points: vtk_points = vtk.vtkPoints() [vtk_points.InsertPoint(i, x[0], x[1], x[2]) for i,x in enumerate(points)] # vtk faces: vtk_faces = vtk.vtkCellArray() for face in faces: vtk_face = vtk.vtkPolygon() vtk_face.GetPointIds().SetNumberOfIds(3) vtk_face.GetPointIds().SetId(0, face[0]) vtk_face.GetPointIds().SetId(1, face[1]) vtk_face.GetPointIds().SetId(2, face[2]) vtk_faces.InsertNextCell(vtk_face) # vtkPolyData: polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.SetPolys(vtk_faces) # We want to preserve topology (not let any cracks form). # This may limit the total reduction possible. decimate = vtk.vtkDecimatePro() decimate.SetInput(polydata) decimate.SetTargetReduction(reduction) decimate.PreserveTopologyOn() # Export output: if not output_vtk: output_vtk = os.path.join(os.getcwd(), 'decimated_file.vtk') #exporter = vtk.vtkPolyDataWriter() if smooth_steps > 0: smoother = vtk.vtkSmoothPolyDataFilter() smoother.SetInput(decimate.GetOutput()) smoother.SetNumberOfIterations(smooth_steps) smoother.Update() out = smoother.GetOutput() #exporter.SetInput(smoother.GetOutput()) else: decimate.Update() out = decimate.GetOutput() #exporter.SetInput(decimate.GetOutput()) #exporter.SetFileName(output_vtk) #exporter.Write() ## Extract points and faces: #faces, u1, u2, points, u4, u5, u6, u7 = read_vtk(output_vtk) points = [list(out.GetPoint(point_id)) for point_id in range(out.GetNumberOfPoints())] if out.GetNumberOfPolys() > 0: polys = out.GetPolys() faces = [[int(polys.GetData().GetValue(j)) for j in range(i*4 + 1, i*4 + 4)] for i in range(polys.GetNumberOfCells())] else: faces = [] return points, faces, output_vtk
def surface2inds(vrtx, trgl, mesh, boundaries=True, internal=True): """" Function to read gocad polystructure file and output indexes of mesh with in the structure. """ import vtk import vtk.util.numpy_support as npsup # Adjust the index trgl = trgl - 1 # Make vtk pts ptsvtk = vtk.vtkPoints() ptsvtk.SetData(npsup.numpy_to_vtk(vrtx, deep=1)) # Make the polygon connection polys = vtk.vtkCellArray() for face in trgl: poly = vtk.vtkPolygon() poly.GetPointIds().SetNumberOfIds(len(face)) for nrv, vert in enumerate(face): poly.GetPointIds().SetId(nrv, vert) polys.InsertNextCell(poly) # Make the polydata, structure of connections and vrtx polyData = vtk.vtkPolyData() polyData.SetPoints(ptsvtk) polyData.SetPolys(polys) # Make implicit func ImpDistFunc = vtk.vtkImplicitPolyDataDistance() ImpDistFunc.SetInput(polyData) # Convert the mesh vtkMesh = vtk.vtkRectilinearGrid() vtkMesh.SetDimensions(mesh.nNx, mesh.nNy, mesh.nNz) vtkMesh.SetXCoordinates(npsup.numpy_to_vtk(mesh.vectorNx, deep=1)) vtkMesh.SetYCoordinates(npsup.numpy_to_vtk(mesh.vectorNy, deep=1)) vtkMesh.SetZCoordinates(npsup.numpy_to_vtk(mesh.vectorNz, deep=1)) # Add indexes vtkInd = npsup.numpy_to_vtk(np.arange(mesh.nC), deep=1) vtkInd.SetName('Index') vtkMesh.GetCellData().AddArray(vtkInd) extractImpDistRectGridFilt = vtk.vtkExtractGeometry() # Object constructor extractImpDistRectGridFilt.SetImplicitFunction(ImpDistFunc) # extractImpDistRectGridFilt.SetInputData(vtkMesh) if boundaries is True: extractImpDistRectGridFilt.ExtractBoundaryCellsOn() else: extractImpDistRectGridFilt.ExtractBoundaryCellsOff() if internal is True: extractImpDistRectGridFilt.ExtractInsideOn() else: extractImpDistRectGridFilt.ExtractInsideOff() print("Extracting indices from grid...") # Executing the pipe extractImpDistRectGridFilt.Update() # Get index inside insideGrid = extractImpDistRectGridFilt.GetOutput() insideGrid = npsup.vtk_to_numpy(insideGrid.GetCellData().GetArray('Index')) # Return the indexes inside return insideGrid
if(len(segmentVertices[i]) > 0): pts[i].InsertNextPoint( basePoints.GetPoint(vIdx)) #for v in vertices: # for i in range(1, len(segmentVertices)): # pts[i].InsertNextPoint(v) i = 0 for v in segmentVertices: print "Len of %d is %d" % (i, len(v)) if len(v) > 0: for f in range(len(v)): if (f % 3 == 0): poly = vtk.vtkPolygon() poly.GetPointIds().InsertId(0,v[f]) poly.GetPointIds().InsertId(1,v[f + 1]) poly.GetPointIds().InsertId(2,v[f + 2]) #print "(%d, %d, %d)" % (v[f], v[f+1], v[f+2]) #exit(0) tris[i].InsertNextCell(poly.GetPointIds()) i += 1 for k in range(len(segmentVertices)): polys[k].SetPoints(pts[k]) polys[k].SetPolys(tris[k]) polys[k].Update() for k in range(len(segmentVertices)): print "%d: %d - %d" % (k, polys[k].GetNumberOfPoints(), polys[k].GetNumberOfPolys(), )
def prepGlyph(g, marker, index=0): t, s = marker.type[index], marker.size[index] * .5 gs = vtk.vtkGlyphSource2D() pd = None if t=='dot': gs.SetGlyphTypeToCircle() gs.FilledOn() elif t=='circle': gs.SetGlyphTypeToCircle() gs.FilledOff() elif t=='plus': gs.SetGlyphTypeToCross() gs.FilledOff() elif t=='cross': gs.SetGlyphTypeToCross() gs.SetRotationAngle(45) gs.FilledOff() elif t[:6]=='square': gs.SetGlyphTypeToSquare() gs.FilledOff() elif t[:7]=='diamond': gs.SetGlyphTypeToDiamond() gs.FilledOff() elif t[:8]=='triangle': gs.SetGlyphTypeToTriangle() gs.FilledOff() if t[9]=="d": gs.SetRotationAngle(180) elif t[9]=="l": gs.SetRotationAngle(90) elif t[9]=="r": gs.SetRotationAngle(-90) elif t[9]=="u": gs.SetRotationAngle(0) elif t == "hurricane": s =s/5. ds = vtk.vtkDiskSource() ds.SetInnerRadius(.55*s) ds.SetOuterRadius(1.01*s) ds.SetCircumferentialResolution(90) ds.SetRadialResolution(30) gf = vtk.vtkGeometryFilter() gf.SetInputConnection(ds.GetOutputPort()) gf.Update() pd1 = gf.GetOutput() apd = vtk.vtkAppendPolyData() apd.AddInputData(pd1) pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polygons = vtk.vtkCellArray() add_angle = numpy.pi/360. coords = [] angle1 = .6*numpy.pi angle2 = .88*numpy.pi while angle1<=angle2: coords.append([s*2+2*s*numpy.cos(angle1),2*s*numpy.sin(angle1)]) angle1+=add_angle angle1=.79*numpy.pi angle2=.6*numpy.pi while angle1>=angle2: coords.append([s*2.25+s*4*numpy.cos(angle1),-s*2+s*4*numpy.sin(angle1)]) angle1-=add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) coords=[] angle1 = 1.6*numpy.pi angle2 = 1.9*numpy.pi while angle1 <= angle2: coords.append( [- s*2 + s*2*numpy.cos(angle1),s*2*numpy.sin(angle1)]) angle1 += add_angle angle1 = 1.8*numpy.pi angle2 = 1.6*numpy.pi while angle1 >= angle2: coords.append( [- s*2.27 + s*4*numpy.cos(angle1), s*2 + s*4*numpy.sin(angle1)]) angle1 -= add_angle poly = genPoly(coords,pts,filled=True) polygons.InsertNextCell(poly) pd.SetPoints(pts) pd.SetPolys(polygons) apd.AddInputData(pd) apd.Update() g.SetSourceData(apd.GetOutput()) elif t[:4] == "star": np = 5 points = starPoints(.001 * s, 0, 0, np) pts = vtk.vtkPoints() # Add all perimeter points for point in points: pts.InsertNextPoint((point[0], point[1], 0)) center_id = len(points) # Add center point pts.InsertNextPoint((0,0,0)) polygons = vtk.vtkCellArray() for ind in range(0, np*2, 2): poly = vtk.vtkPolygon() pid = poly.GetPointIds() pid.SetNumberOfIds(4) pid.SetId(0, ind) pid.SetId(1, (ind - 1) % len(points)) pid.SetId(2, center_id) pid.SetId(3, (ind + 1) % len(points)) polygons.InsertNextCell(poly) pd = vtk.vtkPolyData() pd.SetPoints(pts) pd.SetPolys(polygons) g.SetSourceData(pd) elif t in ["w%.2i" % x for x in range(203)]: ## WMO marker params = wmo[t] pts = vtk.vtkPoints() pd = vtk.vtkPolyData() polys = vtk.vtkCellArray() lines = vtk.vtkCellArray() s*=3 #Lines first for l in params["line"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=False) lines.InsertNextCell(line) for l in params["poly"]: coords = numpy.array(zip(*l))*s/30. line = genPoly(coords.tolist(),pts,filled=True) polys.InsertNextCell(line) geo,pts = project(pts,marker.projection,marker.worldcoordinate) pd.SetPoints(pts) pd.SetPolys(polys) pd.SetLines(lines) g.SetSourceData(pd) else: warnings.warn("unknown marker type: %s, using dot" % t) gs.SetGlyphTypeToCircle() gs.FilledOn() if t[-5:]=="_fill": gs.FilledOn() if pd is None: # Use the difference in x to scale the point, as later we'll use the # x range to correct the aspect ratio: dx = marker.worldcoordinate[1] - marker.worldcoordinate[0] s *= abs(float(dx))/500. gs.SetScale(s) gs.Update() g.SetSourceConnection(gs.GetOutputPort()) return gs, pd
def prepFillarea(renWin,farea,cmap=None): n = prepPrimitive(farea) if n==0: return [] actors =[] # Find color map: if cmap is None: if farea.colormap is not None: cmap = farea.colormap else: cmap = 'default' if isinstance(cmap,str): cmap = vcs.elements["colormap"][cmap] # Create data structures: pts = vtk.vtkPoints() polygons = vtk.vtkCellArray() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetNumberOfTuples(n) polygonPolyData = vtk.vtkPolyData() polygonPolyData.SetPoints(pts) polygonPolyData.SetPolys(polygons) polygonPolyData.GetCellData().SetScalars(colors) # Reuse this temporary container to avoid reallocating repeatedly: polygon = vtk.vtkPolygon() # Iterate through polygons: for i in range(n): x = farea.x[i] y = farea.y[i] c = farea.color[i] st = farea.style[i] idx = farea.index[i] N = max(len(x),len(y)) for a in [x,y]: assert(len(a) == N) # Add current polygon pid = polygon.GetPointIds() pid.SetNumberOfIds(N) for j in range(N): pid.SetId(j, pts.InsertNextPoint(x[j],y[j],0.)) cellId = polygons.InsertNextCell(polygon) # Add the color to the color array: color = cmap.index[c] colors.SetTupleValue(cellId, [int((C/100.) * 255) for C in color]) # Transform points: geo,pts = project(pts,farea.projection,farea.worldcoordinate) # Setup rendering m = vtk.vtkPolyDataMapper() m.SetInputData(polygonPolyData) a = vtk.vtkActor() a.SetMapper(m) actors.append((a,geo)) return actors
def render(self, inputState, visibleAtoms, scalarsArray, lut, voro, voronoiOptions, colouringOptions): """ Render Voronoi cells for visible atoms """ self._logger.debug("Rendering Voronoi cells (%d visible atoms)", len(visibleAtoms)) # object for combining poly datas appendPolyData = vtk.vtkAppendPolyData() # loop over the visible atoms for visIndex, index in enumerate(visibleAtoms): # check we are working with the same atom! inp_pos = inputState.atomPos(index) out_pos = voro.getInputAtomPos(index) sep = vectors.separation(inp_pos, out_pos, inputState.cellDims, np.ones(3, np.int32)) if sep > 1e-4: raise RuntimeError("Voronoi ordering is different") # faces faces = voro.atomFaces(index) if faces is None: continue # scalar value for this atom scalar = scalarsArray[visIndex] # points (vertices) points = vtk.vtkPoints() scalars = vtk.vtkFloatArray() for point in voro.atomVertices(index): points.InsertNextPoint(point) scalars.InsertNextValue(scalar) # make polygons facePolygons = vtk.vtkCellArray() for face in faces: polygon = vtk.vtkPolygon() # set number of vertices polygon.GetPointIds().SetNumberOfIds(len(face)) # add vertices (indexes) for i, index in enumerate(face): polygon.GetPointIds().SetId(i, index) # add the polygon to the set facePolygons.InsertNextCell(polygon) # polydata object regionPolyData = vtk.vtkPolyData() regionPolyData.SetPoints(points) regionPolyData.SetPolys(facePolygons) regionPolyData.GetPointData().SetScalars(scalars) # append the poly data if vtk.vtkVersion.GetVTKMajorVersion() <= 5: appendPolyData.AddInputConnection(regionPolyData.GetProducerPort()) else: appendPolyData.AddInputData(regionPolyData) appendPolyData.Update() # remove any duplicate points cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputConnection(appendPolyData.GetOutputPort()) cleanFilter.Update() # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cleanFilter.GetOutputPort()) mapper.SetLookupTable(lut) utils.setMapperScalarRange(mapper, colouringOptions, len(inputState.specieList)) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(voronoiOptions.opacity) # store data self._actor = utils.ActorObject(actor) self._data["LUT"] = lut self._data["Voronoi"] = voro self._data["Scalars"] = scalarsArray self._data["Visible atoms"] = visibleAtoms self._data["Lattice"] = inputState self._data["Opacity"] = voronoiOptions.opacity