def Create_Topo(Slope,Plane): ugrid = vtk.vtkUnstructuredGrid() gridreader=vtk.vtkUnstructuredGridReader() gridreader.SetFileName(Slope) gridreader.Update() ugrid = gridreader.GetOutput() GeomFilt1 = vtk.vtkGeometryFilter() GeomFilt1.SetInput(ugrid) GeomFilt1.Update() x = GeomFilt1.GetOutput() u = vtk.vtkUnstructuredGrid() bgridreader=vtk.vtkXMLUnstructuredGridReader() bgridreader.SetFileName(Plane) bgridreader.Update() u = bgridreader.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(u) GeomFilt2.Update() y = GeomFilt2.GetOutput() append = vtk.vtkAppendPolyData() append.AddInput(x) append.AddInput(y) data = append.GetOutput() d = vtk.vtkDelaunay3D() d.SetInput(data) d.Update d.BoundingTriangulationOff() d.SetTolerance(0.00001) d.SetAlpha(0) d.Update() z = d.GetOutput() return z
def clip(inp, origin, normal, inside_out=False, take_cell=False): """ VTK operation: clip. A vtkGeometryFilter is used to convert the resulted vtkUnstructuredMesh object into a vtkPolyData object. @param inp: input VTK object. @type inp: vtk.vtkobject @param origin: a 3-tuple for cut origin. @type origin: tuple @param normal: a 3-tuple for cut normal. @type normal: tuple @keyword inside_out: make inside out. Default False. @type inside_out: bool @keyword take_cell: treat the input VTK object with values on cells. Default False. @type: take_cell: bool @return: output VTK object. @rtype: vtk.vtkobject """ import vtk pne = vtk.vtkPlane() pne.SetOrigin(origin) pne.SetNormal(normal) clip = vtk.vtkClipDataSet() if take_cell: clip.SetInput(inp) else: clip.SetInputConnection(inp.GetOutputPort()) clip.SetClipFunction(pne) if inside_out: clip.InsideOutOn() parison = vtk.vtkGeometryFilter() parison.SetInputConnection(clip.GetOutputPort()) return parison
def _set_input (self): """ This function tries its best to generate an appropriate input for the Normals. If one has an input StructuredGrid or StructuredPoints or even a RectilinearGrid the PolyDataNormals will not work. In order for it to work an appropriate intermediate filter is used to create the correct output.""" debug ("In PolyDataNormals::_set_input ()") out = self.prev_fil.GetOutput () f = None if out.IsA ('vtkStructuredGrid'): f = vtk.vtkStructuredGridGeometryFilter () elif out.IsA ('vtkRectilinearGrid'): f = vtk.vtkRectilinearGridGeometryFilter () elif out.IsA ('vtkStructuredPoints') or out.IsA('vtkImageData'): if hasattr (vtk, 'vtkImageDataGeometryFilter'): f = vtk.vtkImageDataGeometryFilter () else: f = vtk.vtkStructuredPointsGeometryFilter () elif out.IsA('vtkUnstructuredGrid'): f = vtk.vtkGeometryFilter() elif out.IsA('vtkPolyData'): f = None else: msg = "This module does not support the given "\ "output - %s "%(out.GetClassName ()) raise Base.Objects.ModuleException, msg if f: f.SetInput (out) self.fil.SetInput (f.GetOutput ()) else: self.fil.SetInput(out)
def findPointsInCell(points, cell, verbose=1): ugrid_cell = vtk.vtkUnstructuredGrid() ugrid_cell.SetPoints(cell.GetPoints()) cell = vtk.vtkHexahedron() for k_point in xrange(8): cell.GetPointIds().SetId(k_point, k_point) cell_array_cell = vtk.vtkCellArray() cell_array_cell.InsertNextCell(cell) ugrid_cell.SetCells(vtk.VTK_HEXAHEDRON, cell_array_cell) geometry_filter = vtk.vtkGeometryFilter() geometry_filter.SetInputData(ugrid_cell) geometry_filter.Update() cell_boundary = geometry_filter.GetOutput() pdata_points = vtk.vtkPolyData() pdata_points.SetPoints(points) enclosed_points_filter = vtk.vtkSelectEnclosedPoints() enclosed_points_filter.SetSurfaceData(cell_boundary) enclosed_points_filter.SetInputData(pdata_points) enclosed_points_filter.Update() points_in_cell = [k_point for k_point in xrange(points.GetNumberOfPoints()) if enclosed_points_filter.GetOutput().GetPointData().GetArray('SelectedPoints').GetTuple(k_point)[0]] return points_in_cell
def ugrid2pdata( ugrid, only_trianlges=False, verbose=0): mypy.my_print(verbose, "*** ugrid2pdata ***") filter_geometry = vtk.vtkGeometryFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): filter_geometry.SetInputData(ugrid) else: filter_geometry.SetInput(ugrid) filter_geometry.Update() pdata = filter_geometry.GetOutput() if (only_trianlges): filter_triangle = vtk.vtkTriangleFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): filter_triangle.SetInputData(pdata) else: filter_triangle.SetInput(pdata) filter_triangle.Update() pdata = filter_triangle.GetOutput() return pdata
def findLocalCsys(self, filename): poly = vtk.vtkGeometryFilter() poly.SetInputData(self.vtkMeshes[filename]) poly.Update() distanceFilter = vtk.vtkImplicitPolyDataDistance() distanceFilter.SetInput(poly.GetOutput()) gradients = vtk.vtkFloatArray() gradients.SetNumberOfComponents(3) gradients.SetName("LevelSet Normals") distances = vtk.vtkFloatArray() distances.SetNumberOfComponents(1) distances.SetName("Signed Distances") N = self.vtkMeshes[filename].GetCellData().GetArray( "Centroids").GetNumberOfTuples() for i in range(N): g = np.zeros(3, np.float32) p = self.vtkMeshes[filename].GetCellData().GetArray( "Centroids").GetTuple3(i) d = distanceFilter.EvaluateFunction(p) distanceFilter.EvaluateGradient(p, g) g = old_div(np.array(g), np.linalg.norm(np.array(g))) gradients.InsertNextTuple(g) distances.InsertNextValue(d) self.vtkMeshes[filename].GetCellData().AddArray(gradients) self.vtkMeshes[filename].GetCellData().AddArray(distances)
def create_mesh(M,P,T): n_naca_pts = 50 write_test_file(M,P,T,-5.,5.,nsections=5) wing=create_wing('current_wing','output') n_sections=len(wing) n_section_pts = 2*n_naca_pts-1 # build mesh vtk_model = vtk.vtkStructuredGrid() vtk_model.SetDimensions(n_section_pts,n_sections,1) # build points vtk_points = vtk.vtkPoints() for j in xrange(n_sections): upper_pts = numpy.array([wing[j][1],wing[j][3]]).T lower_pts = numpy.array([wing[j][2],wing[j][4]]).T section_pts = numpy.concatenate((lower_pts[::-1],upper_pts[1:])) for i in xrange(n_section_pts): vtk_points.InsertNextPoint(section_pts[i,0],wing[j][0],section_pts[i,1]) # set points vtk_model.SetPoints(vtk_points) # convert to poly data pdata_filter = vtk.vtkGeometryFilter() if vtk.VTK_MAJOR_VERSION <= 5: pdata_filter.SetInput(vtk_model) else: pdata_filter.SetInputData(vtk_model) pdata_filter.Update() poly_data = pdata_filter.GetOutput() # compute normals norms = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: norms.SetInput(poly_data) else: norms.SetInputData(poly_data) norms.ComputePointNormalsOff() norms.ComputeCellNormalsOn() norms.ConsistencyOn() norms.Update() # clean poly data clean_poly = vtk.vtkCleanPolyData() clean_poly.ToleranceIsAbsoluteOn() clean_poly.SetAbsoluteTolerance(1.e-6) if vtk.VTK_MAJOR_VERSION <= 5: clean_poly.SetInput(norms.GetOutput()) else: clean_poly.SetInputData(norms.GetOutput()) clean_poly.Update() # write output mesh writer = vtk.vtkXMLPolyDataWriter() if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(clean_poly.GetOutput()) else: writer.SetInputData(clean_poly.GetOutput()) writer.SetFileName('output.vtp') writer.Write()
def setVtkGeometryFilter(self): """ Set the vtk_geometry_filter. We coerce STRUCTURED_GRID and UNSTRUCTURED_GRID vtk_dataset_types to be POLYDATA, so we only need a vtk.vtkGeometryFilter(). """ self.vtk_geometry_filter = vtk.vtkGeometryFilter()
def CreateSurfaceCells(self,inMesh): #Remove the surface cells from the mesh cellDimFilter = vtkvmtkcontrib.vtkvmtkCellDimensionFilter() cellDimFilter.SetInput(inMesh) cellDimFilter.ThresholdByUpper(3) cellDimFilter.Update() volumetricMesh = cellDimFilter.GetOutput() #Get new surface cells geomFilter = vtk.vtkGeometryFilter() geomFilter.SetInput(cellDimFilter.GetOutput()) geomFilter.Update() newSurfaceCells = geomFilter.GetOutput() #If the celEntityIdArray exist, project the original entity ids cellEntityIdsArray = newSurfaceCells.GetCellData().GetArray(self.CellEntityIdsArrayName) if (cellEntityIdsArray != None): #Convert the surface cells to poly data surfaceCellsToSurface = vmtkscripts.vmtkMeshToSurface() surfaceCellsToSurface.Mesh = newSurfaceCells surfaceCellsToSurface.Execute() #Get the original surface cells meshThreshold = vtk.vtkThreshold() meshThreshold.SetInput(self.Mesh) meshThreshold.ThresholdByUpper(self.WallCellEntityId+0.5) meshThreshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) meshThreshold.Update() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = meshThreshold.GetOutput() meshToSurface.Execute() #Project the entity ids form the old surface cells to the new surface cells #TODO: This is hackish(need for a tolerance), find a beeter way projector = vtkvmtkcontrib.vtkvmtkSurfaceProjectCellArray() projector.SetInput(surfaceCellsToSurface.Surface) projector.SetReferenceSurface(meshToSurface.Surface) projector.SetProjectedArrayName(self.CellEntityIdsArrayName) projector.SetDefaultValue(self.WallCellEntityId) projector.SetDistanceTolerance(self.Tolerance) projector.Update() #Convert the surface cells back to unstructured grid surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = projector.GetOutput() surfaceToMesh.Execute() newSurfaceCells = surfaceToMesh.Mesh #append the new surface cells to the volumetric elements appendFilter = vtkvmtk.vtkvmtkAppendFilter() appendFilter.AddInput(volumetricMesh) appendFilter.AddInput(newSurfaceCells) appendFilter.Update() return appendFilter.GetOutput()
def vtk2stl(fn_in, fn_out): reader = vtk.vtkDataSetReader() reader.SetFileName(fn_in) reader.Update() gfilter = vtk.vtkGeometryFilter() gfilter.SetInput(reader.GetOutput()) writer = vtk.vtkSTLWriter() writer.SetFileName(fn_out) writer.SetInput(gfilter.GetOutput()) writer.Write()
def extractcells(polydata, idlist=[0, 1, 2]): """Extract cells from polydata whose cellid is in idlist.""" cellids = vtk.vtkIdList() # specify cellids cellids.Initialize() for i in idlist: cellids.InsertNextId(i) extract = vtk.vtkExtractCells() # extract cells with specified cellids extract.SetInput(polydata) extract.AddCellList(cellids) extraction = extract.GetOutput() geometry = vtk.vtkGeometryFilter() # unstructured grid to polydata geometry.SetInput(extraction) return geometry.GetOutput()
def Execute(self): if self.Mesh == None: self.PrintError('Error: No input mesh.') if self.GenerateCaps == 1: if not ((self.Mesh.IsHomogeneous() == 1) & (self.Mesh.GetCellType(0) == 5)): self.PrintError('Error: In order to generate caps, all input mesh elements must be triangles.') meshToSurfaceFilter = vtk.vtkGeometryFilter() meshToSurfaceFilter.SetInputData(self.Mesh) meshToSurfaceFilter.Update() cap = vtkvmtk.vtkvmtkSimpleCapPolyData() cap.SetInputConnection(meshToSurfaceFilter.GetOutputPort()) cap.SetCellMarkerArrayName(self.FacetMarkerArrayName) cap.Update() surfacetomesh = vtkvmtk.vtkvmtkPolyDataToUnstructuredGridFilter() surfacetomesh.SetInputConnection(cap.GetOutputPort()) surfacetomesh.Update() self.Mesh = surfacetomesh.GetOutput() tetgen = vtkvmtk.vtkvmtkTetGenWrapper() tetgen.SetInputData(self.Mesh) tetgen.SetPLC(self.PLC) tetgen.SetRefine(self.Refine) tetgen.SetCoarsen(self.Coarsen) tetgen.SetNoBoundarySplit(self.NoBoundarySplit) tetgen.SetQuality(self.Quality) tetgen.SetMinRatio(self.MinRatio) tetgen.SetMinDihedral(self.MinDihedral) tetgen.SetMaxDihedral(self.MaxDihedral) tetgen.SetVarVolume(self.VarVolume) tetgen.SetFixedVolume(self.FixedVolume) tetgen.SetMaxVolume(self.MaxVolume) tetgen.SetRemoveSliver(self.RemoveSliver) tetgen.SetRegionAttrib(self.RegionAttrib) tetgen.SetEpsilon(self.Epsilon) tetgen.SetNoMerge(self.NoMerge) tetgen.SetDetectInter(self.DetectInter) tetgen.SetCheckClosure(self.CheckClosure) tetgen.SetOrder(self.Order) tetgen.SetDoCheck(self.DoCheck) tetgen.SetVerbose(self.Verbose) tetgen.SetUseSizingFunction(self.UseSizingFunction) tetgen.SetCellEntityIdsArrayName(self.CellEntityIdsArrayName) tetgen.SetTetrahedronVolumeArrayName(self.TetrahedronVolumeArrayName) tetgen.SetSizingFunctionArrayName(self.SizingFunctionArrayName) tetgen.SetOutputSurfaceElements(self.OutputSurfaceElements) tetgen.SetOutputVolumeElements(self.OutputVolumeElements) tetgen.Update() self.Mesh = tetgen.GetOutput()
def update(self): delaunay = vtkDelaunay3D() delaunay.SetInput(self.input_) delaunay.SetTolerance(self.tolerance) delaunay.SetAlpha(self.alpha) delaunay.Update() geom = vtkGeometryFilter() geom.SetInputConnection(delaunay.GetOutputPort() ) triangle = vtkTriangleFilter() triangle.SetInputConnection(geom.GetOutputPort()) triangle.Update() self.output_ = triangle.GetOutput()
def removeEndCaps(self): self.PrintLog("Using thresholding to remove endcaps.") th = vtk.vtkThreshold() th.SetInputData(self.Surface) th.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) th.ThresholdBetween(self.EndcapsThresholdLow, self.EndcapsThresholdHigh) th.Update() gf = vtk.vtkGeometryFilter() gf.SetInputConnection(th.GetOutputPort()) gf.Update() self.DoubleSurface = gf.GetOutput()
def ExtractVtuGeometry(inputVtu): """ Extract the geometry of a vtu. In 3D, this extracts the surface mesh. """ filter = vtk.vtkGeometryFilter() filter.SetInput(inputVtu.ugrid) filter.Update() surfacePoly = filter.GetOutput() # Construct output result = vtu() result.ugrid = PolyDataToUnstructuredGrid(surfacePoly) return result
def Execute(self): if self.Mesh == None: self.PrintError('Error: No input mesh.') meshToSurfaceFilter = vtk.vtkGeometryFilter() meshToSurfaceFilter.SetInputData(self.Mesh) meshToSurfaceFilter.Update() self.Surface = meshToSurfaceFilter.GetOutput() if self.CleanOutput == 1: cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(meshToSurfaceFilter.GetOutputPort()) cleaner.Update() self.Surface = cleaner.GetOutput()
def do_contour (self, event=None): debug ("In BandedSurfaceMap::do_contour ()") Common.state.busy () if self.contour_on.get (): if not self.mod_m.get_scalar_data_name (): self.contour_on.set (0) msg = "Warning: No scalar data present to contour!" Common.print_err (msg) Common.state.idle () return out = self.mod_m.GetOutput () if out.IsA('vtkPolyData'): f = None elif out.IsA ('vtkStructuredGrid'): f = vtk.vtkStructuredGridGeometryFilter () elif out.IsA ('vtkRectilinearGrid'): f = vtk.vtkRectilinearGridGeometryFilter () elif out.IsA ('vtkStructuredPoints') or \ out.IsA('vtkImageData'): if hasattr (vtk, 'vtkImageDataGeometryFilter'): f = vtk.vtkImageDataGeometryFilter () else: f = vtk.vtkStructuredPointsGeometryFilter () elif out.IsA('vtkUnstructuredGrid'): f = vtk.vtkGeometryFilter() else: msg = "This module does not support the given "\ "output - %s "%(out.GetClassName ()) raise Base.Objects.ModuleException, msg if f: f.SetInput (out) self.cont_fil.SetInput (f.GetOutput()) else: self.cont_fil.SetInput (out) self.map.SetInput (self.cont_fil.GetOutput ()) self.map.SetScalarModeToUseCellData() else: self.map.SetInput (self.mod_m.GetOutput ()) self.map.SetScalarModeToDefault() self.change_contour () Common.state.idle ()
def Execute(self): if self.Mesh == None: self.PrintError('Error: No input mesh.') meshToSurfaceFilter = vtk.vtkGeometryFilter() meshToSurfaceFilter.SetInput(self.Mesh) meshToSurfaceFilter.Update() self.Surface = meshToSurfaceFilter.GetOutput() if self.CleanOutput == 1: cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(meshToSurfaceFilter.GetOutput()) cleaner.Update() self.Surface = cleaner.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def filterUGridIntoPData( ugrid, only_trianlges=False, verbose=1): myVTK.myPrint(verbose, "*** filterUGridIntoPData ***") filter_geometry = vtk.vtkGeometryFilter() filter_geometry.SetInputData(ugrid) filter_geometry.Update() pdata = filter_geometry.GetOutput() if (only_trianlges): filter_triangle = vtk.vtkTriangleFilter() filter_triangle.SetInputData(pdata) filter_triangle.Update() pdata = filter_triangle.GetOutput() return pdata
def GetOpenningLine(self): m_polyline = vtk.vtkPolyData() m_appendfilter = vtk.vtkAppendFilter() for i in xrange(len(self._openingList) - 1): l_linesource = vtk.vtkLineSource() l_linesource.SetPoint1(self._openingList[i]) l_linesource.SetPoint2(self._openingList[i + 1]) l_linesource.Update() m_appendfilter.AddInputData(m_polyline) m_appendfilter.AddInputData(l_linesource.GetOutput()) m_appendfilter.Update() m_polyline.DeepCopy(m_appendfilter.GetOutput()) m_geomfilter = vtk.vtkGeometryFilter() m_geomfilter.SetInputConnection(m_appendfilter.GetOutputPort()) m_cleanfilter = vtk.vtkCleanPolyData() m_cleanfilter.SetInputConnection(m_geomfilter.GetOutputPort()) m_cleanfilter.Update() m_polylineOut = m_cleanfilter.GetOutput() return m_polylineOut
def vtk2stl(fn_in, fn_out): reader = vtk.vtkDataSetReader() reader.SetFileName(fn_in) reader.Update() gfilter = vtk.vtkGeometryFilter() if vtk.VTK_MAJOR_VERSION <= 5: gfilter.SetInput(reader.GetOutput()) else: gfilter.SetInputData(reader.GetOutput()) gfilter.Update() writer = vtk.vtkSTLWriter() writer.SetFileName(fn_out) if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(gfilter.GetOutput()) else: writer.SetInputData(gfilter.GetOutput()) writer.Write()
def Domain(self, opacity=1, mesh=False): domain = vtk.vtkGeometryFilter() domain.SetInput(self.vtkgrid) domain.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput(domain.GetOutput()) # edges edges = vtk.vtkFeatureEdges() edges.SetInput(normals.GetOutput()) edges.ManifoldEdgesOff() if mesh: edges.ManifoldEdgesOn() edges.BoundaryEdgesOn() edges.NonManifoldEdgesOff() edges.FeatureEdgesOff() edges.SetFeatureAngle(1) # mapper for domain mapper = vtk.vtkPolyDataMapper() mapper.SetInput(normals.GetOutput()) mapper.SetLookupTable(self.lut) mapper.SetScalarRange(self.vmin, self.vmax) # actor for domain actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) # mapper for edges mapper = vtk.vtkPolyDataMapper() mapper.SetInput(edges.GetOutput()) if self.mesh.topology().dim() == 3: mapper.ScalarVisibilityOff() else: mapper.SetLookupTable(self.lut) mapper.SetScalarRange(self.vmin, self.vmax) # actor for domain actor2 = vtk.vtkActor() actor2.SetMapper(mapper) actor2.GetProperty().SetOpacity((1 + opacity) / 2) if mesh: actor2.GetProperty().SetOpacity(opacity) return [actor, actor2]
def Execute(self): if self.Surface == None and self.Mesh == None: self.PrintError('Error: No Surface or Mesh.') if self.Surface != None and self.Mesh != None: self.PrintError('Error: Both Surface and Mesh, expecting only one.') input = self.Surface or self.Mesh th = vtk.vtkThreshold() th.SetInputData(input) th.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) th.ThresholdBetween(self.LowThreshold, self.HighThreshold) th.Update() if self.Mesh != None: self.Mesh = th.GetOutput() else: assert self.Surface != None gf = vtk.vtkGeometryFilter() gf.SetInputConnection(th.GetOutputPort()) gf.Update() self.Surface = gf.GetOutput()
def __init__(self, filename=None,bnd=None,outlet_ids=[], inlets=[], dist=None): """Class containing the information about the boundary of the domain. Args: filename (str): Name of the file containing the vtkUnstructuredGrid denoting the boundary of the domain.""" self.reader = vtk.vtkXMLUnstructuredGridReader() self.bndl = vtk.vtkCellLocator() self.geom_filter = vtk.vtkGeometryFilter() self.outlet_ids=outlet_ids self.inlets=inlets self.dist = dist open_ids = [] + self.outlet_ids for inlet in self.inlets: open_ids+=inlet.surface_ids if filename is not None: self.update_boundary_file(filename, open_ids) else: self.bnd=bnd if self.dist: self.phys_bnd = IO.move_boundary_through_normal(self.bnd, ids = open_ids) else: self.phys_bnd = self.bnd if vtk.vtkVersion.GetVTKMajorVersion()<6: self.geom_filter.SetInput(self.phys_bnd) else: self.geom_filter.SetInputData(self.phys_bnd) self.geom_filter.Update() self.bndl.SetDataSet(self.geom_filter.GetOutput()) self.bndl.BuildLocator()
def update(self): """ """ appendFilter = vtkAppendFilter() appendFilter.AddInput(self.input_) appendFilter.Update() extractGrid = vtkExtractUnstructuredGrid() extractGrid.SetInput(appendFilter.GetOutput()) extractGrid.SetExtent(self.extent[0], self.extent[1], self.extent[2], self.extent[3], self.extent[4], self.extent[5]) geom = vtkGeometryFilter() geom.SetInputConnection(extractGrid.GetOutputPort() ) geom.Update() clean = vtkCleanPolyData() clean.PointMergingOn() clean.SetTolerance(0.01) clean.SetInput(geom.GetOutput()) clean.Update() self.output_ = clean.GetOutput()
def getPointsInCell( points, cell, verbose=0): mypy.my_print(verbose, "*** getPointsInCell ***") ugrid_cell = vtk.vtkUnstructuredGrid() ugrid_cell.SetPoints(cell.GetPoints()) cell = vtk.vtkHexahedron() for k_point in xrange(8): cell.GetPointIds().SetId(k_point, k_point) cell_array_cell = vtk.vtkCellArray() cell_array_cell.InsertNextCell(cell) ugrid_cell.SetCells(vtk.VTK_HEXAHEDRON, cell_array_cell) geometry_filter = vtk.vtkGeometryFilter() if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): geometry_filter.SetInputData(ugrid_cell) else: geometry_filter.SetInput(ugrid_cell) geometry_filter.Update() cell_boundary = geometry_filter.GetOutput() pdata_points = vtk.vtkPolyData() pdata_points.SetPoints(points) enclosed_points_filter = vtk.vtkSelectEnclosedPoints() enclosed_points_filter.SetSurfaceData(cell_boundary) if (vtk.vtkVersion.GetVTKMajorVersion() >= 6): enclosed_points_filter.SetInputData(pdata_points) else: enclosed_points_filter.SetInput(pdata_points) enclosed_points_filter.Update() points_in_cell = [k_point for k_point in xrange(points.GetNumberOfPoints()) if enclosed_points_filter.GetOutput().GetPointData().GetArray('SelectedPoints').GetTuple1(k_point)] return points_in_cell
def _surface_selection(surf, array, low=-np.inf, upp=np.inf, use_cell=False): """Selection of points or cells meeting some thresholding criteria. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. array : str or ndarray Array used to perform selection. low : float or -np.inf Lower threshold. Default is -np.inf. upp : float or np.inf Upper threshold. Default is +np.inf. use_cell : bool, optional If True, apply selection to cells. Otherwise, use points. Default is False. Returns ------- surf_selected : BSPolyData Surface after thresholding. """ if low > upp: raise ValueError('Threshold not valid: [{},{}]'.format(low, upp)) at = 'c' if use_cell else 'p' if isinstance(array, np.ndarray): drop_array = True array_name = surf.append_array(array, at=at) else: drop_array = False array_name = array array = surf.get_array(name=array, at=at, return_name=False) if array.ndim > 1: raise ValueError('Arrays has more than one dimension.') if low == -np.inf: low = array.min() if upp == np.inf: upp = array.max() tf = wrap_vtk(vtkThreshold, allScalars=True) tf.ThresholdBetween(low, upp) if use_cell: tf.SetInputArrayToProcess(0, 0, 0, ASSOC_CELLS, array_name) else: tf.SetInputArrayToProcess(0, 0, 0, ASSOC_POINTS, array_name) gf = wrap_vtk(vtkGeometryFilter(), merging=False) surf_sel = serial_connect(surf, tf, gf) # Check results n_exp = np.logical_and(array >= low, array <= upp).sum() n_sel = surf_sel.n_cells if use_cell else surf_sel.n_points if n_exp != n_sel: element = 'cells' if use_cell else 'points' warnings.warn('Number of selected {}={}. Expected {}.' 'This may be due to the topology after selection.'. format(element, n_exp, n_sel)) if drop_array: surf.remove_array(name=array_name, at=at) surf_sel.remove_array(name=array_name, at=at) return surf_sel
def createModelBaseOnVolume(self, holefilledImageNode, outputModelNode): if holefilledImageNode: holefilledImageData = holefilledImageNode.GetImageData() cast = vtk.vtkImageCast() cast.SetInputData(holefilledImageData) cast.SetOutputScalarTypeToUnsignedChar() cast.Update() labelVolumeNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLLabelMapVolumeNode") slicer.mrmlScene.AddNode(labelVolumeNode) labelVolumeNode.SetName("Threshold") labelVolumeNode.SetSpacing(holefilledImageData.GetSpacing()) labelVolumeNode.SetOrigin(holefilledImageData.GetOrigin()) matrix = vtk.vtkMatrix4x4() holefilledImageNode.GetIJKToRASMatrix(matrix) labelVolumeNode.SetIJKToRASMatrix(matrix) labelImage = cast.GetOutput() labelVolumeNode.SetAndObserveImageData(labelImage) transformIJKtoRAS = vtk.vtkTransform() matrix = vtk.vtkMatrix4x4() labelVolumeNode.GetRASToIJKMatrix(matrix) transformIJKtoRAS.SetMatrix(matrix) transformIJKtoRAS.Inverse() padder = vtk.vtkImageConstantPad() padder.SetInputData(labelImage) padder.SetConstant(0) extent = labelImage.GetExtent() padder.SetOutputWholeExtent(extent[0], extent[1] + 2, extent[2], extent[3] + 2, extent[4], extent[5] + 2) cubes = vtk.vtkDiscreteMarchingCubes() cubes.SetInputConnection(padder.GetOutputPort()) cubes.GenerateValues(1, 1, 1) cubes.Update() smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(cubes.GetOutputPort()) smoother.SetNumberOfIterations(10) smoother.BoundarySmoothingOn() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(120.0) smoother.SetPassBand(0.001) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() pthreshold = vtk.vtkThreshold() pthreshold.SetInputConnection(smoother.GetOutputPort()) pthreshold.ThresholdBetween(1, 1) ## Label 1 pthreshold.ReleaseDataFlagOn() geometryFilter = vtk.vtkGeometryFilter() geometryFilter.SetInputConnection(pthreshold.GetOutputPort()) geometryFilter.ReleaseDataFlagOn() decimator = vtk.vtkDecimatePro() decimator.SetInputConnection(geometryFilter.GetOutputPort()) decimator.SetFeatureAngle(60) decimator.SplittingOff() decimator.PreserveTopologyOn() decimator.SetMaximumError(1) decimator.SetTargetReduction(0.5) #0.001 only reduce the points by 0.1%, 0.5 is 50% off decimator.ReleaseDataFlagOff() decimator.Update() smootherPoly = vtk.vtkSmoothPolyDataFilter() smootherPoly.SetRelaxationFactor(0.33) smootherPoly.SetFeatureAngle(60) smootherPoly.SetConvergence(0) if transformIJKtoRAS.GetMatrix().Determinant() < 0: reverser = vtk.vtkReverseSense() reverser.SetInputConnection(decimator.GetOutputPort()) reverser.ReverseNormalsOn() reverser.ReleaseDataFlagOn() smootherPoly.SetInputConnection(reverser.GetOutputPort()) else: smootherPoly.SetInputConnection(decimator.GetOutputPort()) Smooth = 10 smootherPoly.SetNumberOfIterations(Smooth) smootherPoly.FeatureEdgeSmoothingOff() smootherPoly.BoundarySmoothingOff() smootherPoly.ReleaseDataFlagOn() smootherPoly.Update() transformer = vtk.vtkTransformPolyDataFilter() transformer.SetInputConnection(smootherPoly.GetOutputPort()) transformer.SetTransform(transformIJKtoRAS) transformer.ReleaseDataFlagOn() transformer.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(transformer.GetOutputPort()) normals.SetFeatureAngle(60) normals.SetSplitting(True) normals.ReleaseDataFlagOn() stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) stripper.ReleaseDataFlagOff() stripper.Update() outputModel = stripper.GetOutput() outputModelNode.SetAndObservePolyData(outputModel) outputModelNode.SetAttribute("vtkMRMLModelNode.modelCreated","True") outputModelNode.GetDisplayNode().SetVisibility(1) slicer.mrmlScene.RemoveNode(labelVolumeNode) pass
def geo(inp): poly = vtk.vtkGeometryFilter() poly.SetInputData(inp) poly.Update() return poly.GetOutput()
def smoothMultipleSegments(self, maskImage=None, maskExtent=None): import vtkSegmentationCorePython as vtkSegmentationCore # Generate merged labelmap of all visible segments segmentationNode = self.scriptedEffect.parameterSetNode( ).GetSegmentationNode() visibleSegmentIds = vtk.vtkStringArray() segmentationNode.GetDisplayNode().GetVisibleSegmentIDs( visibleSegmentIds) if visibleSegmentIds.GetNumberOfValues() == 0: logging.info( "Smoothing operation skipped: there are no visible segments") return mergedImage = slicer.vtkOrientedImageData() if not segmentationNode.GenerateMergedLabelmapForAllSegments( mergedImage, vtkSegmentationCore.vtkSegmentation. EXTENT_UNION_OF_SEGMENTS_PADDED, None, visibleSegmentIds): logging.error( 'Failed to apply smoothing: cannot get list of visible segments' ) return segmentLabelValues = [] # list of [segmentId, labelValue] for i in range(visibleSegmentIds.GetNumberOfValues()): segmentId = visibleSegmentIds.GetValue(i) segmentLabelValues.append([segmentId, i + 1]) # Perform smoothing in voxel space ici = vtk.vtkImageChangeInformation() ici.SetInputData(mergedImage) ici.SetOutputSpacing(1, 1, 1) ici.SetOutputOrigin(0, 0, 0) # Convert labelmap to combined polydata # vtkDiscreteFlyingEdges3D cannot be used here, as in the output of that filter, # each labeled region is completely disconnected from neighboring regions, and # for joint smoothing it is essential for the points to move together. convertToPolyData = vtk.vtkDiscreteMarchingCubes() convertToPolyData.SetInputConnection(ici.GetOutputPort()) convertToPolyData.SetNumberOfContours(len(segmentLabelValues)) contourIndex = 0 for segmentId, labelValue in segmentLabelValues: convertToPolyData.SetValue(contourIndex, labelValue) contourIndex += 1 # Low-pass filtering using Taubin's method smoothingFactor = self.scriptedEffect.doubleParameter( "JointTaubinSmoothingFactor") smoothingIterations = 100 # according to VTK documentation 10-20 iterations could be enough but we use a higher value to reduce chance of shrinking passBand = pow( 10.0, -4.0 * smoothingFactor ) # gives a nice range of 1-0.0001 from a user input of 0-1 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(convertToPolyData.GetOutputPort()) smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(90.0) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() # Extract a label threshold = vtk.vtkThreshold() threshold.SetInputConnection(smoother.GetOutputPort()) # Convert to polydata geometryFilter = vtk.vtkGeometryFilter() geometryFilter.SetInputConnection(threshold.GetOutputPort()) # Convert polydata to stencil polyDataToImageStencil = vtk.vtkPolyDataToImageStencil() polyDataToImageStencil.SetInputConnection( geometryFilter.GetOutputPort()) polyDataToImageStencil.SetOutputSpacing(1, 1, 1) polyDataToImageStencil.SetOutputOrigin(0, 0, 0) polyDataToImageStencil.SetOutputWholeExtent(mergedImage.GetExtent()) # Convert stencil to image stencil = vtk.vtkImageStencil() emptyBinaryLabelMap = vtk.vtkImageData() emptyBinaryLabelMap.SetExtent(mergedImage.GetExtent()) emptyBinaryLabelMap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) vtkSegmentationCore.vtkOrientedImageDataResample.FillImage( emptyBinaryLabelMap, 0) stencil.SetInputData(emptyBinaryLabelMap) stencil.SetStencilConnection(polyDataToImageStencil.GetOutputPort()) stencil.ReverseStencilOn() stencil.SetBackgroundValue( 1 ) # General foreground value is 1 (background value because of reverse stencil) imageToWorldMatrix = vtk.vtkMatrix4x4() mergedImage.GetImageToWorldMatrix(imageToWorldMatrix) # TODO: Temporarily setting the overwrite mode to OverwriteVisibleSegments is an approach that should be change once additional # layer control options have been implemented. Users may wish to keep segments on separate layers, and not allow them to be separated/merged automatically. # This effect could leverage those options once they have been implemented. oldOverwriteMode = self.scriptedEffect.parameterSetNode( ).GetOverwriteMode() self.scriptedEffect.parameterSetNode().SetOverwriteMode( slicer.vtkMRMLSegmentEditorNode.OverwriteVisibleSegments) for segmentId, labelValue in segmentLabelValues: threshold.ThresholdBetween(labelValue, labelValue) stencil.Update() smoothedBinaryLabelMap = slicer.vtkOrientedImageData() smoothedBinaryLabelMap.ShallowCopy(stencil.GetOutput()) smoothedBinaryLabelMap.SetImageToWorldMatrix(imageToWorldMatrix) self.scriptedEffect.modifySegmentByLabelmap( segmentationNode, segmentId, smoothedBinaryLabelMap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet, False) self.scriptedEffect.parameterSetNode().SetOverwriteMode( oldOverwriteMode)
def render_window_serializer(render_window): """ Function to convert a vtk render window in a list of 2-tuple where first value correspond to a relative file path in the `vtkjs` directory structure and values of the binary content of the corresponding file. """ render_window.OffScreenRenderingOn() # to not pop a vtk windows render_window.Render() renderers = render_window.GetRenderers() doCompressArrays = False objIds = [] scDirs = [] sceneComponents = [] textureToSave = {} for renderer in renderers: renProps = renderer.GetViewProps() for rpIdx in range(renProps.GetNumberOfItems()): renProp = renProps.GetItemAsObject(rpIdx) if not renProp.GetVisibility(): continue if hasattr(renProp, 'GetMapper'): mapper = renProp.GetMapper() if mapper is None: continue dataObject = mapper.GetInputDataObject(0, 0) dataset = None if dataObject.IsA('vtkCompositeDataSet'): if dataObject.GetNumberOfBlocks() == 1: dataset = dataObject.GetBlock(0) else: gf = vtk.vtkCompositeDataGeometryFilter() gf.SetInputData(dataObject) gf.Update() dataset = gf.GetOutput() elif dataObject.IsA('vtkUnstructuredGrid'): gf = vtk.vtkGeometryFilter() gf.SetInputData(dataObject) gf.Update() dataset = gf.GetOutput() else: dataset = mapper.GetInput() if dataset and not isinstance(dataset, (vtk.vtkPolyData)): # All data must be PolyData surfaces! gf = vtk.vtkGeometryFilter() gf.SetInputData(dataset) gf.Update() dataset = gf.GetOutputDataObject(0) if dataset and dataset.GetPoints(): componentName = str(id(renProp)) scalarVisibility = mapper.GetScalarVisibility() arrayAccessMode = mapper.GetArrayAccessMode() colorArrayName = mapper.GetArrayName( ) if arrayAccessMode == 1 else mapper.GetArrayId() colorMode = mapper.GetColorMode() scalarMode = mapper.GetScalarMode() lookupTable = mapper.GetLookupTable() dsAttrs = None arrayLocation = '' if scalarVisibility: if scalarMode == 0: # By default (ScalarModeToDefault), the filter will use point data, # and if no point data is available, then cell data is used # https://vtk.org/doc/nightly/html/classvtkMapper.html#af330900726eb1a5e18e5f7f557306e52 if dataset.GetPointData().GetNumberOfArrays() >= 1: dsAttrs = dataset.GetPointData() arrayLocation = 'pointData' else: dsAttrs = dataset.GetCellData() arrayLocation = 'cellData' if scalarMode == 3 or scalarMode == 1: # VTK_SCALAR_MODE_USE_POINT_FIELD_DATA or VTK_SCALAR_MODE_USE_POINT_DATA dsAttrs = dataset.GetPointData() arrayLocation = 'pointData' elif scalarMode == 4 or scalarMode == 2: # VTK_SCALAR_MODE_USE_CELL_FIELD_DATA or VTK_SCALAR_MODE_USE_CELL_DATA dsAttrs = dataset.GetCellData() arrayLocation = 'cellData' colorArray = None dataArray = None if dsAttrs: if colorArrayName >= 0: dataArray = dsAttrs.GetArray(colorArrayName) elif dsAttrs.GetNumberOfArrays() >= 1: dataArray = dsAttrs.GetArray(0) if dataArray: # component = -1 => let specific instance get scalar from vector before mapping colorArray = lookupTable.MapScalars( dataArray, colorMode, -1) colorArrayName = '__CustomRGBColorArray__' colorArray.SetName(colorArrayName) colorMode = 0 else: colorArrayName = '' colorArrayInfo = { 'colorArray': colorArray, 'location': arrayLocation } _write_data_set(scDirs, dataset, colorArrayInfo, newDSName=componentName, compress=doCompressArrays) # Handle texture if any textureName = None if renProp.GetTexture() and renProp.GetTexture().GetInput( ): textureData = renProp.GetTexture().GetInput() textureName = 'texture_%d' % _get_object_id( textureData, objIds) textureToSave[textureName] = textureData representation = renProp.GetProperty().GetRepresentation( ) if hasattr(renProp, 'GetProperty') else 2 if representation == 1: colorToUse = renProp.GetProperty().GetColor( ) if hasattr(renProp, 'GetProperty') else [1, 1, 1] else: colorToUse = renProp.GetProperty().GetDiffuseColor( ) if hasattr(renProp, 'GetProperty') else [1, 1, 1] pointSize = renProp.GetProperty().GetPointSize( ) if hasattr(renProp, 'GetProperty') else 1.0 opacity = renProp.GetProperty().GetOpacity() if hasattr( renProp, 'GetProperty') else 1.0 edgeVisibility = renProp.GetProperty().GetEdgeVisibility( ) if hasattr(renProp, 'GetProperty') else False p3dPosition = renProp.GetPosition() if renProp.IsA( 'vtkProp3D') else [0, 0, 0] p3dScale = renProp.GetScale() if renProp.IsA( 'vtkProp3D') else [1, 1, 1] p3dOrigin = renProp.GetOrigin() if renProp.IsA( 'vtkProp3D') else [0, 0, 0] p3dRotateWXYZ = renProp.GetOrientationWXYZ( ) if renProp.IsA('vtkProp3D') else [0, 0, 0, 0] sceneComponents.append({ "name": componentName, "type": "httpDataSetReader", "httpDataSetReader": { "url": componentName }, "actor": { "origin": p3dOrigin, "scale": p3dScale, "position": p3dPosition, }, "actorRotation": p3dRotateWXYZ, "mapper": { "colorByArrayName": colorArrayName, "colorMode": colorMode, "scalarMode": scalarMode }, "property": { "representation": representation, "edgeVisibility": edgeVisibility, "diffuseColor": colorToUse, "pointSize": pointSize, "opacity": opacity }, "lookupTable": { "tableRange": lookupTable.GetRange(), "hueRange": lookupTable.GetHueRange() if hasattr( lookupTable, 'GetHueRange') else [0.5, 0] } }) if textureName: sceneComponents[-1]['texture'] = textureName # Save texture data if any for key, val in textureToSave.items(): _write_data_set(scDirs, val, None, newDSName=key, compress=doCompressArrays) activeCamera = renderer.GetActiveCamera() background = renderer.GetBackground() sceneDescription = { "fetchGzip": doCompressArrays, "background": background, "camera": { "focalPoint": activeCamera.GetFocalPoint(), "position": activeCamera.GetPosition(), "viewUp": activeCamera.GetViewUp(), "clippingRange": activeCamera.GetClippingRange() }, "centerOfRotation": renderer.GetCenter(), "scene": sceneComponents, } scDirs.append(['index.json', json.dumps(sceneDescription, indent=4)]) # create binary stream of the vtkjs directory structure compression = zipfile.ZIP_DEFLATED in_memory = BytesIO() zf = zipfile.ZipFile(in_memory, mode="w") try: for dirPath, data in (scDirs): zf.writestr(dirPath, data, compress_type=compression) finally: zf.close() in_memory.seek(0) return in_memory
calc_filename = os.path.join('..', 'data', '%s.vtu' % calc_name) field = 'sig22' field_min = 0. field_max = 400. fmt = '%.1f' lut = jet_cmap(table_range=(field_min, field_max)) reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(calc_filename) reader.Update() calc = reader.GetOutput() # the vtkUnstructuredGrid object bounds = np.array(calc.GetBounds()) size = bounds[1::2] - bounds[0::2] # we need to convert the data to vtkPolyData poly_data = vtk.vtkGeometryFilter() poly_data.SetInputData(calc) poly_data.Update() poly_data.GetOutput().GetPointData().SetActiveVectors('U') # deform the mesh using the displacement field warp = vtk.vtkWarpVector() warp.SetInputConnection(poly_data.GetOutputPort()) #warp.SetInputArrayToProcess(1, 0, 0, 0, 'U') warp.SetScaleFactor(5) warp.Update() warp.GetOutput().GetCellData().SetActiveScalars( field) # must be after call to Update probe_mapper = vtk.vtkPolyDataMapper() probe_mapper.SetInputConnection(warp.GetOutputPort())
blobImage.DeepCopy(maxValue.GetOutput()) i += 1 discrete = vtk.vtkDiscreteMarchingCubes() discrete.SetInputData(blobImage) discrete.GenerateValues(n, 1, n) discrete.ComputeAdjacentScalarsOn() # creates PointScalars thr = vtk.vtkThreshold() thr.SetInputConnection(discrete.GetOutputPort()) thr.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.SCALARS) # act on PointScalars created by ComputeAdjacentScalarsOn thr.AllScalarsOn() # default, changes better visible thr.ThresholdBetween(0, 0) # remove cells between labels, i.e. keep cells neighbouring background (label 0) vtu2vtp = vtk.vtkGeometryFilter() vtu2vtp.SetInputConnection(thr.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(vtu2vtp.GetOutputPort()) mapper.SetLookupTable(lut) mapper.SetScalarModeToUseCellData() # default is to use PointScalars, which get created with ComputeAdjacentScalarsOn mapper.SetScalarRange(0, lut.GetNumberOfColors()) actor = vtk.vtkActor() actor.SetMapper(mapper) ren1.AddActor(actor) renWin.Render()
moldMapper.ScalarVisibilityOff() moldActor = vtk.vtkActor() moldActor.SetMapper(moldMapper) moldActor.GetProperty().SetColor(.2, .2, .2) moldActor.GetProperty().SetRepresentationToWireframe() # extract parison from mesh using connectivity connect2 = vtk.vtkConnectivityFilter() connect2.SetInputConnection(warp.GetOutputPort()) connect2.SetExtractionModeToSpecifiedRegions() connect2.AddSpecifiedRegion(2) extractGrid = vtk.vtkExtractUnstructuredGrid() extractGrid.SetInputConnection(connect2.GetOutputPort()) extractGrid.CellClippingOn() extractGrid.SetCellMinimum(0) extractGrid.SetCellMaximum(23) parison = vtk.vtkGeometryFilter() parison.SetInputConnection(extractGrid.GetOutputPort()) normals2 = vtk.vtkPolyDataNormals() normals2.SetInputConnection(parison.GetOutputPort()) normals2.SetFeatureAngle(60) lut = vtk.vtkLookupTable() lut.SetHueRange(0.0, 0.66667) parisonMapper = vtk.vtkPolyDataMapper() parisonMapper.SetInputConnection(normals2.GetOutputPort()) parisonMapper.SetLookupTable(lut) parisonMapper.SetScalarRange(0.12, 1.0) parisonActor = vtk.vtkActor() parisonActor.SetMapper(parisonMapper) # graphics stuff ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow()
def main(): fileName, dataPoint = get_program_parameters() colors = vtk.vtkNamedColors() thickness = list() displacement = list() for i in range(0, 10): thickness.append('thickness' + str(i)) displacement.append('displacement' + str(i)) reader = list() warp = list() connect = list() mold = list() moldMapper = list() moldActor = list() connect2 = list() parison = list() normals2 = list() parisonMapper = list() parisonActor = list() cf = list() contourMapper = list() contours = list() ren = list() lut = vtk.vtkLookupTable() lut.SetHueRange(0.0, 0.66667) for i in range(0, 10): # Create the reader and warp the data vith vectors. reader.append(vtk.vtkDataSetReader()) reader[i].SetFileName(fileName) reader[i].SetScalarsName(thickness[i]) reader[i].SetVectorsName(displacement[i]) reader[i].Update() warp.append(vtk.vtkWarpVector()) warp[i].SetInputData(reader[i].GetUnstructuredGridOutput()) # Extract the mold from the mesh using connectivity. connect.append(vtk.vtkConnectivityFilter()) connect[i].SetInputConnection(warp[i].GetOutputPort()) connect[i].SetExtractionModeToSpecifiedRegions() connect[i].AddSpecifiedRegion(0) connect[i].AddSpecifiedRegion(1) mold.append(vtk.vtkGeometryFilter()) mold[i].SetInputConnection(connect[i].GetOutputPort()) moldMapper.append(vtk.vtkDataSetMapper()) moldMapper[i].SetInputConnection(mold[i].GetOutputPort()) moldMapper[i].ScalarVisibilityOff() moldActor.append(vtk.vtkActor()) moldActor[i].SetMapper(moldMapper[i]) moldActor[i].GetProperty().SetColor(colors.GetColor3d("ivory_black")) moldActor[i].GetProperty().SetRepresentationToWireframe() # Extract the parison from the mesh using connectivity. connect2.append(vtk.vtkConnectivityFilter()) connect2[i].SetInputConnection(warp[i].GetOutputPort()) connect2[i].SetExtractionModeToSpecifiedRegions() connect2[i].AddSpecifiedRegion(2) parison.append(vtk.vtkGeometryFilter()) parison[i].SetInputConnection(connect2[i].GetOutputPort()) normals2.append(vtk.vtkPolyDataNormals()) normals2[i].SetInputConnection(parison[i].GetOutputPort()) normals2[i].SetFeatureAngle(60) parisonMapper.append(vtk.vtkPolyDataMapper()) parisonMapper[i].SetInputConnection(normals2[i].GetOutputPort()) parisonMapper[i].SetLookupTable(lut) parisonMapper[i].SetScalarRange(0.12, 1.0) parisonActor.append(vtk.vtkActor()) parisonActor[i].SetMapper(parisonMapper[i]) cf.append(vtk.vtkContourFilter()) cf[i].SetInputConnection(connect2[i].GetOutputPort()) cf[i].SetValue(0, 0.5) contourMapper.append(vtk.vtkPolyDataMapper()) contourMapper[i].SetInputConnection(cf[i].GetOutputPort()) contours.append(vtk.vtkActor()) contours[i].SetMapper(contourMapper[i]) ren.append(vtk.vtkRenderer()) ren[i].AddActor(moldActor[i]) ren[i].AddActor(parisonActor[i]) ren[i].AddActor(contours[i]) ren[i].SetBackground(colors.GetColor3d("AliceBlue")) ren[i].GetActiveCamera().SetPosition(50.973277, 12.298821, 29.102547) ren[i].GetActiveCamera().SetFocalPoint(0.141547, 12.298821, -0.245166) ren[i].GetActiveCamera().SetViewUp(-0.500000, 0.000000, 0.866025) ren[i].GetActiveCamera().SetClippingRange(36.640827, 78.614680) # Create the RenderWindow and RenderWindowInteractor. renWin = vtk.vtkRenderWindow() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) rendererSizeX = 750 rendererSizeY = 400 renWinScale = 0.5 renWin.SetWindowName("Blow") if 0 <= dataPoint < 10: renWin.AddRenderer(ren[dataPoint]) renWin.SetSize(rendererSizeX, rendererSizeY) else: gridDimensionsX = 2 gridDimensionsY = 5 renWin.SetSize(int(rendererSizeX * gridDimensionsX * renWinScale), int(rendererSizeY * gridDimensionsY * renWinScale)) # Add and position the renders to the render window. viewPort = list() for row in range(0, gridDimensionsY): for col in range(0, gridDimensionsX): idx = row * gridDimensionsX + col x0 = float(col) / gridDimensionsX y0 = float(gridDimensionsY - row - 1) / gridDimensionsY x1 = float(col + 1) / gridDimensionsX y1 = float(gridDimensionsY - row) / gridDimensionsY viewPort[:] = [] viewPort.append(x0) viewPort.append(y0) viewPort.append(x1) viewPort.append(y1) renWin.AddRenderer(ren[idx]) ren[idx].SetViewport(viewPort) iren.Initialize() iren.Start()
def __init__(self, inputobj=None, ): vtk.vtkActor.__init__(self) BaseGrid.__init__(self) inputtype = str(type(inputobj)) self._data = None self._polydata = None ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() # elif utils.isSequence(inputobj):pass # TODO elif "UnstructuredGrid" in inputtype: self._data = inputobj elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj, verbose=False) self._data = loadUnStructuredGrid(inputobj) else: colors.printc("UGrid(): cannot understand input type:\n", inputtype, c='r') return self._mapper = vtk.vtkPolyDataMapper() self._mapper.SetInterpolateScalarsBeforeMapping(settings.interpolateScalarsBeforeMapping) if settings.usePolygonOffset: self._mapper.SetResolveCoincidentTopologyToPolygonOffset() pof, pou = settings.polygonOffsetFactor, settings.polygonOffsetUnits self._mapper.SetResolveCoincidentTopologyPolygonOffsetParameters(pof, pou) self.GetProperty().SetInterpolationToFlat() if not self._data: return sf = vtk.vtkShrinkFilter() sf.SetInputData(self._data) sf.SetShrinkFactor(1.0) sf.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(sf.GetOutput()) gf.Update() self._polydata = gf.GetOutput() self._mapper.SetInputData(self._polydata) sc = None if self.useCells: sc = self._polydata.GetCellData().GetScalars() else: sc = self._polydata.GetPointData().GetScalars() if sc: self._mapper.SetScalarRange(sc.GetRange()) self.SetMapper(self._mapper)
def scan(wannabeacts): scannedacts = [] if not utils.isSequence(wannabeacts): wannabeacts = [wannabeacts] for a in wannabeacts: # scan content of list if isinstance(a, vtk.vtkActor): scannedacts.append(a) if hasattr(a, 'trail' ) and a.trail and not a.trail in self.actors: scannedacts.append(a.trail) elif isinstance(a, vtk.vtkAssembly): scannedacts.append(a) if a.trail and not a.trail in self.actors: scannedacts.append(a.trail) elif isinstance(a, vtk.vtkActor2D): scannedacts.append(a) elif isinstance(a, vtk.vtkImageActor): scannedacts.append(a) elif isinstance(a, vtk.vtkVolume): scannedacts.append(a) elif isinstance(a, vtk.vtkImageData): scannedacts.append(Volume(a)) elif isinstance(a, vtk.vtkPolyData): scannedacts.append(Actor(a, c, alpha, wire, bc)) elif isinstance(a, str): # assume a filepath was given out = vtkio.load(a, c, alpha, wire, bc) if isinstance(out, str): colors.printc("~times File not found:", out, c=1) scannedacts.append(None) else: scannedacts.append(out) elif "dolfin" in str(type(a)): # assume a dolfin.Mesh object from vtkplotter.dolfin import MeshActor out = MeshActor(a, c=c, alpha=alpha, wire=True, bc=bc) scannedacts.append(out) elif a is None: pass elif isinstance(a, vtk.vtkUnstructuredGrid): gf = vtk.vtkGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkStructuredGrid): gf = vtk.vtkGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkRectilinearGrid): gf = vtk.vtkRectilinearGridGeometryFilter() gf.SetInputData(a) gf.Update() scannedacts.append( Actor(gf.GetOutput(), c, alpha, wire, bc)) elif isinstance(a, vtk.vtkMultiBlockDataSet): for i in range(a.GetNumberOfBlocks()): b = a.GetBlock(i) if isinstance(b, vtk.vtkPolyData): scannedacts.append(Actor(b, c, alpha, wire, bc)) elif isinstance(b, vtk.vtkImageData): scannedacts.append(Volume(b)) else: colors.printc("~!? Cannot understand input in show():", type(a), c=1) scannedacts.append(None) return scannedacts
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create pipeline - structured grid # pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName("" + str(VTK_DATA_ROOT) + "/Data/combxyz.bin") pl3d.SetQFileName("" + str(VTK_DATA_ROOT) + "/Data/combq.bin") pl3d.SetScalarFunctionNumber(100) pl3d.SetVectorFunctionNumber(202) pl3d.Update() output = pl3d.GetOutput().GetBlock(0) gf = vtk.vtkGeometryFilter() gf.SetInputData(output) gMapper = vtk.vtkPolyDataMapper() gMapper.SetInputConnection(gf.GetOutputPort()) gMapper.SetScalarRange(output.GetScalarRange()) gActor = vtk.vtkActor() gActor.SetMapper(gMapper) gf2 = vtk.vtkGeometryFilter() gf2.SetInputData(output) gf2.ExtentClippingOn() gf2.SetExtent(10,17,-6,6,23,37) gf2.PointClippingOn() gf2.SetPointMinimum(0) gf2.SetPointMaximum(10000) gf2.CellClippingOn() gf2.SetCellMinimum(0)
def main(): filename, startLabel, endLabel = get_program_parameters() # Create all of the classes we will need reader = vtk.vtkMetaImageReader() histogram = vtk.vtkImageAccumulate() discreteCubes = vtk.vtkDiscreteMarchingCubes() smoother = vtk.vtkWindowedSincPolyDataFilter() selector = vtk.vtkThreshold() scalarsOff = vtk.vtkMaskFields() geometry = vtk.vtkGeometryFilter() writer = vtk.vtkXMLPolyDataWriter() # Define all of the variables filePrefix = "Label" smoothingIterations = 15 passBand = 0.001 featureAngle = 120.0 # Generate models from labels # 1) Read the meta file # 2) Generate a histogram of the labels # 3) Generate models from the labeled volume # 4) Smooth the models # 5) Output each model into a separate file reader.SetFileName(filename) histogram.SetInputConnection(reader.GetOutputPort()) histogram.SetComponentExtent(0, endLabel, 0, 0, 0, 0) histogram.SetComponentOrigin(0, 0, 0) histogram.SetComponentSpacing(1, 1, 1) histogram.Update() discreteCubes.SetInputConnection(reader.GetOutputPort()) discreteCubes.GenerateValues(endLabel - startLabel + 1, startLabel, endLabel) smoother.SetInputConnection(discreteCubes.GetOutputPort()) smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(featureAngle) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() selector.SetInputConnection(smoother.GetOutputPort()) selector.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_CELLS, vtk.vtkDataSetAttributes.SCALARS) # Strip the scalars from the output scalarsOff.SetInputConnection(selector.GetOutputPort()) scalarsOff.CopyAttributeOff(vtk.vtkMaskFields.POINT_DATA, vtk.vtkDataSetAttributes.SCALARS) scalarsOff.CopyAttributeOff(vtk.vtkMaskFields.CELL_DATA, vtk.vtkDataSetAttributes.SCALARS) geometry.SetInputConnection(scalarsOff.GetOutputPort()) writer.SetInputConnection(geometry.GetOutputPort()) for i in range(startLabel, endLabel): # see if the label exists, if not skip it frequency = histogram.GetOutput().GetPointData().GetScalars( ).GetTuple1(i) if frequency == 0.0: continue # select the cells for a given label selector.ThresholdBetween(i, i) # output the polydata ss = "%s%d.vtp" % (filePrefix, i) writer.SetFileName(ss) writer.Write()
def apply_filters(fname, df, sf, surf_type): """Apply the decimation and smoothing filters using the VTK library and the user specified refinement factors. Decimation uses the vtkDecimatePro method. Smoothing uses the vtkWindowSincPolyDataFilter method. Both refinement processes maintain boundary vertices and topology. If both filters are applied, smoothing will be applied first. Input: ------ fname: string, name of the surface vtk file that will be refined df: float or None, factor for target reduction in the decimation process. Must be between 0 and 1. If set to None, no decimation will be applied. A higher value indicates a greater reduction in the number of surface triangles. sf: float or None, smoothing factor for the smoothing process. Must be between 0 and 1. If set to None, no smoothing will be applied. A higher value indicates more smoothing. surf_type: str, 'interior' or 'exterior', used to indicate if the surface being refined is an interior or exterior surface. Only interior surfaces will have smoothing applied if smoothing is requested. Return: ------- outfile: string, name of the output file from VTK after refinement """ # read in surface w/ vtk as an unstructured grid usg = vtk.vtkUnstructuredGridReader() usg.SetFileName(fname) usg.Update() usgport = usg.GetOutputPort() # convert USG to polydata gf = vtk.vtkGeometryFilter() gf.SetInputConnection(usgport) gf.Update() pdport = gf.GetOutputPort() # only apply smoothing filter to interior surfaces to avoid smoothing # the corners of the geometry if sf is not None and surf_type == 'interior': smoothfilter = vtk.vtkWindowedSincPolyDataFilter() smoothfilter.SetInputConnection(pdport) smoothfilter.SetNumberOfIterations(20) smoothfilter.BoundarySmoothingOff # don't apply to boundaries smoothfilter.NonManifoldSmoothingOff() # don't collapse topology/vols smoothfilter.Update() pdport = smoothfilter.GetOutputPort() if df is not None: # setup decimate operator decifilter = vtk.vtkDecimatePro() decifilter.SetInputConnection(pdport) # set decimate options decifilter.SetTargetReduction(df) # target reduction # preserve topology (splitting or hole elimination not allowed) decifilter.SetPreserveTopology(True) decifilter.SetSplitting(False) # no mesh splitting allowed # no boundary vertex (edge/curve) deletion allowed decifilter.SetBoundaryVertexDeletion(False) decifilter.Update() pdport = decifilter.GetOutputPort() # convert polydata back to USG appendfilter = vtk.vtkAppendFilter() appendfilter.SetInputConnection(pdport) appendfilter.Update() usg_new = vtk.vtkUnstructuredGrid() usg_new.ShallowCopy(appendfilter.GetOutput()) outfile = fname.split('.')[0] + '_refined.vtk' writer1 = vtk.vtkGenericDataObjectWriter() writer1.SetFileName(outfile) writer1.SetInputData(usg_new) writer1.Update() writer1.Write() return outfile
def setupPipeline(): #read file global reader reader = vtk.vtkOBJReader() reader.SetFileName(filename) #map 3d model global mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(reader.GetOutputPort()) #set actor global actor actor = vtk.vtkActor() actor.SetMapper(mapper) # Create a rendering window and renderer global ren ren = vtk.vtkRenderer() ren.SetBackground(0, 0, 0) ren.AddActor(actor) global intermediateWindow intermediateWindow = vtk.vtkRenderWindow() intermediateWindow.AddRenderer(ren) #render image global renImage renImage = vtk.vtkRenderLargeImage() renImage.SetInput(ren) renImage.SetMagnification(magnificationFactor) #Canny edge detector inspired by #https://vtk.org/Wiki/VTK/Examples/Cxx/Images/CannyEdgeDetector #to grayscale global lumImage lumImage = vtk.vtkImageLuminance() lumImage.SetInputConnection(renImage.GetOutputPort()) #to float global floatImage floatImage = vtk.vtkImageCast() floatImage.SetOutputScalarTypeToFloat() floatImage.SetInputConnection(lumImage.GetOutputPort()) #gaussian convolution global smoothImage smoothImage = vtk.vtkImageGaussianSmooth() smoothImage.SetInputConnection(floatImage.GetOutputPort()) smoothImage.SetDimensionality(2) smoothImage.SetRadiusFactors(1, 1, 0) #gradient global gradientImage gradientImage = vtk.vtkImageGradient() gradientImage.SetInputConnection(smoothImage.GetOutputPort()) gradientImage.SetDimensionality(2) #gradient magnitude global magnitudeImage magnitudeImage = vtk.vtkImageMagnitude() magnitudeImage.SetInputConnection(gradientImage.GetOutputPort()) #non max suppression global nonmaxSuppr nonmaxSuppr = vtk.vtkImageNonMaximumSuppression() nonmaxSuppr.SetDimensionality(2) #padding global padImage padImage = vtk.vtkImageConstantPad() padImage.SetInputConnection(gradientImage.GetOutputPort()) padImage.SetOutputNumberOfScalarComponents(3) padImage.SetConstant(0) #to structured points global i2sp1 i2sp1 = vtk.vtkImageToStructuredPoints() i2sp1.SetInputConnection(nonmaxSuppr.GetOutputPort()) #link edges global linkImage linkImage = vtk.vtkLinkEdgels() linkImage.SetInputConnection(i2sp1.GetOutputPort()) linkImage.SetGradientThreshold(2) #thresholds links global thresholdEdgels thresholdEdgels = vtk.vtkThreshold() thresholdEdgels.SetInputConnection(linkImage.GetOutputPort()) thresholdEdgels.ThresholdByUpper(10) thresholdEdgels.AllScalarsOff() #filter global gf gf = vtk.vtkGeometryFilter() gf.SetInputConnection(thresholdEdgels.GetOutputPort()) #to structured points global i2sp i2sp = vtk.vtkImageToStructuredPoints() i2sp.SetInputConnection(magnitudeImage.GetOutputPort()) #subpixel global spe spe = vtk.vtkSubPixelPositionEdgels() spe.SetInputConnection(gf.GetOutputPort()) #stripper global strip strip = vtk.vtkStripper() strip.SetInputConnection(spe.GetOutputPort()) global dsm dsm = vtk.vtkPolyDataMapper() dsm.SetInputConnection(strip.GetOutputPort()) dsm.ScalarVisibilityOff() global planeActor planeActor = vtk.vtkActor() planeActor.SetMapper(dsm) planeActor.GetProperty().SetAmbient(1.0) planeActor.GetProperty().SetDiffuse(0.0) global edgeRender edgeRender = vtk.vtkRenderer() edgeRender.AddActor(planeActor) global renderWindow renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(edgeRender) global finalImage finalImage = vtk.vtkRenderLargeImage() finalImage.SetMagnification(magnificationFactor) finalImage.SetInput(edgeRender) global revImage revImage = vtk.vtkImageThreshold() revImage.SetInputConnection(finalImage.GetOutputPort()) revImage.ThresholdByUpper(127) revImage.ReplaceInOn() revImage.ReplaceOutOn() revImage.SetOutValue(255) revImage.SetInValue(0) #write image global imgWriter imgWriter = vtk.vtkPNGWriter() imgWriter.SetInputConnection(revImage.GetOutputPort()) imgWriter.SetFileName("test.png")
def export_plotter_vtkjs(plotter, filename, compress_arrays=False): """Export a plotter's rendering window to the VTKjs format. """ sceneName = os.path.split(filename)[1] doCompressArrays = compress_arrays # Generate timestamp and use it to make subdirectory within the top level output dir timeStamp = time.strftime("%a-%d-%b-%Y-%H-%M-%S") root_output_directory = os.path.split(filename)[0] output_dir = os.path.join(root_output_directory, timeStamp) mkdir_p(output_dir) renderers = plotter.ren_win.GetRenderers() scDirs = [] sceneComponents = [] textureToSave = {} for rIdx in range(renderers.GetNumberOfItems()): renderer = renderers.GetItemAsObject(rIdx) renProps = renderer.GetViewProps() for rpIdx in range(renProps.GetNumberOfItems()): renProp = renProps.GetItemAsObject(rpIdx) if not renProp.GetVisibility(): continue if hasattr(renProp, 'GetMapper') and renProp.GetMapper() is not None: mapper = renProp.GetMapper() dataObject = mapper.GetInputDataObject(0, 0) dataset = None if dataObject is None: continue if dataObject.IsA('vtkCompositeDataSet'): if dataObject.GetNumberOfBlocks() == 1: dataset = dataObject.GetBlock(0) else: gf = vtk.vtkCompositeDataGeometryFilter() gf.SetInputData(dataObject) gf.Update() dataset = gf.GetOutput() else: dataset = mapper.GetInput() if dataset and not isinstance( dataset, (vtk.vtkPolyData, vtk.vtkImageData)): # All data must be PolyData surfaces gf = vtk.vtkGeometryFilter() gf.SetInputData(dataset) gf.Update() dataset = gf.GetOutputDataObject(0) if dataset: # and dataset.GetPoints(): # NOTE: vtkImageData does not have points componentName = 'data_%d_%d' % ( rIdx, rpIdx) # getComponentName(renProp) scalarVisibility = mapper.GetScalarVisibility() #arrayAccessMode = mapper.GetArrayAccessMode() #colorArrayName = mapper.GetArrayName() #TODO: if arrayAccessMode == 1 else mapper.GetArrayId() colorMode = mapper.GetColorMode() scalarMode = mapper.GetScalarMode() lookupTable = mapper.GetLookupTable() dsAttrs = None arrayLocation = '' if scalarVisibility: if scalarMode == 3 or scalarMode == 1: # VTK_SCALAR_MODE_USE_POINT_FIELD_DATA or VTK_SCALAR_MODE_USE_POINT_DATA dsAttrs = dataset.GetPointData() arrayLocation = 'pointData' # VTK_SCALAR_MODE_USE_CELL_FIELD_DATA or VTK_SCALAR_MODE_USE_CELL_DATA elif scalarMode == 4 or scalarMode == 2: dsAttrs = dataset.GetCellData() arrayLocation = 'cellData' colorArray = None dataArray = None if dsAttrs: dataArray = dsAttrs.GetArray( 0) # Force getting the active array if dataArray: # component = -1 => let specific instance get scalar from vector before mapping colorArray = lookupTable.MapScalars( dataArray, colorMode, -1) colorArrayName = '__CustomRGBColorArray__' colorArray.SetName(colorArrayName) colorMode = 0 else: colorArrayName = '' color_array_info = { 'colorArray': colorArray, 'location': arrayLocation } scDirs.append( write_data_set('', dataset, output_dir, color_array_info, new_name=componentName, compress=doCompressArrays)) # Handle texture if any textureName = None if renProp.GetTexture() and renProp.GetTexture().GetInput( ): textureData = renProp.GetTexture().GetInput() textureName = 'texture_%d' % get_object_id(textureData) textureToSave[textureName] = textureData representation = renProp.GetProperty().GetRepresentation( ) if hasattr(renProp, 'GetProperty') else 2 colorToUse = renProp.GetProperty().GetDiffuseColor( ) if hasattr(renProp, 'GetProperty') else [1, 1, 1] if representation == 1: colorToUse = renProp.GetProperty().GetColor( ) if hasattr(renProp, 'GetProperty') else [1, 1, 1] pointSize = renProp.GetProperty().GetPointSize( ) if hasattr(renProp, 'GetProperty') else 1.0 opacity = renProp.GetProperty().GetOpacity() if hasattr( renProp, 'GetProperty') else 1.0 edgeVisibility = renProp.GetProperty().GetEdgeVisibility( ) if hasattr(renProp, 'GetProperty') else False p3dPosition = renProp.GetPosition() if renProp.IsA( 'vtkProp3D') else [0, 0, 0] p3dScale = renProp.GetScale() if renProp.IsA( 'vtkProp3D') else [1, 1, 1] p3dOrigin = renProp.GetOrigin() if renProp.IsA( 'vtkProp3D') else [0, 0, 0] p3dRotateWXYZ = renProp.GetOrientationWXYZ( ) if renProp.IsA('vtkProp3D') else [0, 0, 0, 0] sceneComponents.append({ "name": componentName, "type": "httpDataSetReader", "httpDataSetReader": { "url": componentName }, "actor": { "origin": p3dOrigin, "scale": p3dScale, "position": p3dPosition, }, "actorRotation": p3dRotateWXYZ, "mapper": { "colorByArrayName": colorArrayName, "colorMode": colorMode, "scalarMode": scalarMode }, "property": { "representation": representation, "edgeVisibility": edgeVisibility, "diffuseColor": colorToUse, "pointSize": pointSize, "opacity": opacity }, "lookupTable": { "tableRange": lookupTable.GetRange(), "hueRange": lookupTable.GetHueRange() if hasattr( lookupTable, 'GetHueRange') else [0.5, 0] } }) if textureName: sceneComponents[-1]['texture'] = textureName # Save texture data if any for key, val in textureToSave.items(): write_data_set('', val, output_dir, None, new_name=key, compress=doCompressArrays) cameraClippingRange = plotter.camera.GetClippingRange() sceneDescription = { "fetchGzip": doCompressArrays, "background": plotter.background_color, "camera": { "focalPoint": plotter.camera.GetFocalPoint(), "position": plotter.camera.GetPosition(), "viewUp": plotter.camera.GetViewUp(), "clippingRange": [elt for elt in cameraClippingRange], }, "centerOfRotation": plotter.camera.GetFocalPoint(), "scene": sceneComponents } indexFilePath = os.path.join(output_dir, 'index.json') with open(indexFilePath, 'w') as outfile: json.dump(sceneDescription, outfile, indent=4) # ----------------------------------------------------------------------------- # Now zip up the results and get rid of the temp directory sceneFileName = os.path.join(root_output_directory, '%s%s' % (sceneName, FILENAME_EXTENSION)) try: import zlib compression = zipfile.ZIP_DEFLATED except: compression = zipfile.ZIP_STORED zf = zipfile.ZipFile(sceneFileName, mode='w') try: for dirName, subdirList, fileList in os.walk(output_dir): for fname in fileList: fullPath = os.path.join(dirName, fname) relPath = '%s/%s' % (sceneName, os.path.relpath(fullPath, output_dir)) zf.write(fullPath, arcname=relPath, compress_type=compression) finally: zf.close() shutil.rmtree(output_dir) print('Finished exporting dataset to: ', sceneFileName)
def get_section_vol(mesh, plane, loc_syst, celldata=False, array='DISP_TRA', component=-1, mesh0=0, matlist=[], EFlist=[], LFlist=[]): cut = vtk.vtkCutter() cut.SetInputData(mesh) cut.SetCutFunction(plane) cut.Update() if celldata: output0 = cut.GetOutput() cdata = output0.GetCellData() mat = cdata.GetArray('mat') EF = cdata.GetArray('EF') LF = cdata.GetArray('LF') extract = vtk.vtkExtractCells() extract.SetInputData(output0) eleList = vtk.vtkIdList() for ke in range(output0.GetNumberOfCells()): if len(matlist) == 0 or mat.GetTuple1(ke) in matlist: if len(EFlist) == 0 or EF.GetTuple1(ke) in EFlist: if len(LFlist) == 0 or LF.GetTuple1(ke) in LFlist: a = eleList.InsertNextId(ke) extract.SetCellList(eleList) output1 = extract.GetOutputPort() geom = vtk.vtkGeometryFilter() geom.SetInputConnection(output1) geom.Update() output = geom.GetOutput() c2p = vtk.vtkCellDataToPointData() c2p.SetInputData(output) c2p.Update() pdata = c2p.GetOutput().GetPointData() else: output = cut.GetOutput() pdata = output.GetPointData() anArray = pdata.GetArray(array) if anArray is None: print('Array ' + array + ' is not found.') val = [] inel = [] crd = [[], []] orig = plane.GetOrigin() for kp in range(output.GetNumberOfPoints()): p = output.GetPoint(kp) crd_2D = project_on_plane(loc_syst, orig, p) crd[0].append(crd_2D[0]) crd[1].append(crd_2D[1]) if component == -1: val.append(anArray.GetTuple(kp)) else: val.append(anArray.GetTuple(kp)[component]) for kp in range(output.GetNumberOfPolys()): p = output.GetCell(kp) if p.GetNumberOfPoints() == 3: inel.append([p.GetPointId(kk) for kk in range(3)]) return val, crd, output
def Execute(self): if not self.Mesh: self.PrintError('Error: No input mesh.') return if not self.CellEntityIdsArrayName: self.PrintError('Error: No input CellEntityIdsArrayName.') return if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) threshold = vtk.vtkThreshold() threshold.SetInput(self.Mesh) threshold.ThresholdByUpper(self.VolumeCellEntityId + 0.5) threshold.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) threshold.Update() boundaryMesh = threshold.GetOutput() boundaryMesh.GetCellData().SetActiveScalars( self.CellEntityIdsArrayName) boundaryMapper = vtk.vtkDataSetMapper() boundaryMapper.SetInput(boundaryMesh) boundaryMapper.ScalarVisibilityOn() boundaryMapper.SetScalarModeToUseCellData() boundaryMapper.SetScalarRange( boundaryMesh.GetCellData().GetScalars().GetRange()) boundaryActor = vtk.vtkActor() boundaryActor.SetMapper(boundaryMapper) self.vmtkRenderer.Renderer.AddActor(boundaryActor) wallThreshold = vtk.vtkThreshold() wallThreshold.SetInput(boundaryMesh) wallThreshold.ThresholdByLower(self.WallCellEntityId + 0.5) wallThreshold.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) wallThreshold.Update() wallMeshToSurface = vtk.vtkGeometryFilter() wallMeshToSurface.SetInput(wallThreshold.GetOutput()) wallMeshToSurface.Update() boundaryReferenceSystems = vtkvmtk.vtkvmtkBoundaryReferenceSystems() boundaryReferenceSystems.SetInput(wallMeshToSurface.GetOutput()) boundaryReferenceSystems.SetBoundaryRadiusArrayName("BoundaryRadius") boundaryReferenceSystems.SetBoundaryNormalsArrayName("BoundaryNormals") boundaryReferenceSystems.SetPoint1ArrayName("Point1Array") boundaryReferenceSystems.SetPoint2ArrayName("Point2Array") boundaryReferenceSystems.Update() self.ReferenceSystems = boundaryReferenceSystems.GetOutput() cellEntityIdsArray = vtk.vtkIntArray() cellEntityIdsArray.SetName(self.CellEntityIdsArrayName) cellEntityIdsArray.SetNumberOfTuples( self.ReferenceSystems.GetNumberOfPoints()) self.ReferenceSystems.GetPointData().AddArray(cellEntityIdsArray) boundaryThreshold = vtk.vtkThreshold() boundaryThreshold.SetInput(boundaryMesh) boundaryThreshold.ThresholdByUpper(self.WallCellEntityId + 0.5) boundaryThreshold.SetInputArrayToProcess(0, 0, 0, 1, self.CellEntityIdsArrayName) boundaryThreshold.Update() boundaryMeshToSurface = vtk.vtkGeometryFilter() boundaryMeshToSurface.SetInput(boundaryThreshold.GetOutput()) boundaryMeshToSurface.Update() boundarySurface = boundaryMeshToSurface.GetOutput() pointCells = vtk.vtkIdList() surfaceCellEntityIdsArray = vtk.vtkIntArray() surfaceCellEntityIdsArray.DeepCopy( boundarySurface.GetCellData().GetArray( self.CellEntityIdsArrayName)) self.PrintLog('') for i in range(self.ReferenceSystems.GetNumberOfPoints()): pointId = boundarySurface.FindPoint( self.ReferenceSystems.GetPoint(i)) boundarySurface.GetPointCells(pointId, pointCells) cellId = pointCells.GetId(0) cellEntityId = surfaceCellEntityIdsArray.GetValue(cellId) cellEntityIdsArray.SetValue(i, cellEntityId) origin = self.ReferenceSystems.GetPoint(i) normal = self.ReferenceSystems.GetPointData().GetArray( "BoundaryNormals").GetTuple3(i) radius = self.ReferenceSystems.GetPointData().GetArray( "BoundaryRadius").GetTuple1(i) logLine = 'CellEntityId: %d\n' % cellEntityId logLine += ' Origin: %f, %f, %f\n' % (origin[0], origin[1], origin[2]) logLine += ' Normal: %f, %f, %f\n' % (normal[0], normal[1], normal[2]) logLine += ' Radius: %f\n' % radius self.PrintLog(logLine) self.ReferenceSystems.GetPointData().SetActiveScalars( self.CellEntityIdsArrayName) labelsMapper = vtk.vtkLabeledDataMapper() labelsMapper.SetInput(self.ReferenceSystems) labelsMapper.SetLabelModeToLabelScalars() labelsActor = vtk.vtkActor2D() labelsActor.SetMapper(labelsMapper) self.vmtkRenderer.Renderer.AddActor(labelsActor) self.vmtkRenderer.Render() if self.OwnRenderer: self.vmtkRenderer.Deallocate()
pad.SetOutputNumberOfScalarComponents(3) pad.SetConstant(0) pad.Update() i2sp1 = vtk.vtkImageToStructuredPoints() i2sp1.SetInputConnection(nonMax.GetOutputPort()) i2sp1.SetVectorInputData(pad.GetOutput()) # link edgles imgLink = vtk.vtkLinkEdgels() imgLink.SetInputConnection(i2sp1.GetOutputPort()) imgLink.SetGradientThreshold(2) # threshold links thresholdEdgels = vtk.vtkThreshold() thresholdEdgels.SetInputConnection(imgLink.GetOutputPort()) thresholdEdgels.ThresholdByUpper(10) thresholdEdgels.AllScalarsOff() gf = vtk.vtkGeometryFilter() gf.SetInputConnection(thresholdEdgels.GetOutputPort()) i2sp = vtk.vtkImageToStructuredPoints() i2sp.SetInputConnection(imgMagnitude.GetOutputPort()) i2sp.SetVectorInputData(pad.GetOutput()) i2sp.Update() # subpixel them spe = vtk.vtkSubPixelPositionEdgels() spe.SetInputConnection(gf.GetOutputPort()) spe.SetGradMapsData(i2sp.GetOutput()) strip = vtk.vtkStripper() strip.SetInputConnection(spe.GetOutputPort()) dsm = vtk.vtkPolyDataMapper() dsm.SetInputConnection(strip.GetOutputPort()) dsm.ScalarVisibilityOff() planeActor = vtk.vtkActor()
import vtk def Create_Topo(Slope,Plane) ugrid = vtk.vtkUnstructuredGrid() gridreader=vtk.vtkUnstructuredGridReader() gridreader.SetFileName(Slope) gridreader.Update() ugrid = gridreader.GetOutput() GeomFilt1 = vtk.vtkGeometryFilter() GeomFilt1.SetInput(ugrid) GeomFilt1.Update() x = GeomFilt1.GetOutput() u = vtk.vtkUnstructuredGrid() bgridreader=vtk.vtkXMLUnstructuredGridReader() bgridreader.SetFileName(Plane) bgridreader.Update() u = bgridreader.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(u) GeomFilt2.Update() y = GeomFilt2.GetOutput() append = vtk.vtkAppendPolyData() append.AddInput(x) append.AddInput(y) data = append.GetOutput() d = vtk.vtkDelaunay3D() d.SetInput(data) d.Update d.BoundingTriangulationOff()
def GenerateTetrInFile(self): self.PrintLog('Generating Tetr .in file.') f=open(self.OutputFileName, 'w') line = '$title' + '\n' f.write(line) line = self.OutputFileName + '\n' f.write(line) line = '\n' f.write(line) line = '$compress' + '\n' f.write(line) line = 'gzip -f' + '\n' f.write(line) line = '\n' f.write(line) self.NormalizationTransform.Identity() if (self.NormalizationEntity != ''): sectionBoundaryPointIds = self.GetSectionBoundaryPointIds(self.NormalizationEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds sectionProperties.Execute() self.NormalizationRadius = sectionProperties.Radius if (self.NormalizationRadius != 0.0) & (self.NormalizationRadius != 1.0): self.NormalizationTransform.Scale(1.0/self.NormalizationRadius,1.0/self.NormalizationRadius,1.0/self.NormalizationRadius) line = '$radius' + '\n' f.write(line) line = str(self.NormalizationRadius) + '\n' f.write(line) line = '\n' f.write(line) line = '$viscosity' + '\n' f.write(line) line = str(0.035) + '\n' f.write(line) line = '\n' f.write(line) line = '$density' + '\n' f.write(line) line = str(1.06) + '\n' f.write(line) line = '\n' f.write(line) line = '$red' + '\n' f.write(line) line = str(0) + '\n' f.write(line) line = '\n' f.write(line) line = '$alpha' + '\n' f.write(line) line = str(0) + '\n' f.write(line) line = '\n' f.write(line) line = '$nsolve' + '\n' f.write(line) line = '22' + '\n' f.write(line) line = '\n' f.write(line) line = '$Uzawa_PC' + '\n' f.write(line) line = '1' + '\n' f.write(line) line = '\n' f.write(line) line = '$node' + '\n' f.write(line) line = str(self.Mesh.GetNumberOfPoints()) + '\n' f.write(line) for i in range(self.Mesh.GetNumberOfPoints()): point = [0.0,0.0,0.0] self.NormalizationTransform.TransformPoint(self.Mesh.GetPoint(i),point) line = str(i+1) + ' ' + str(point[0]) + ' ' + str(point[1]) + ' ' + str(point[2]) + '\n' f.write(line) line = '\n' f.write(line) line = '$elem' + '\n' f.write(line) quadratidTetraCellType = 24 quadraticTetraCellIds = vtk.vtkIdTypeArray() self.Mesh.GetIdsOfCellsOfType(quadratidTetraCellType,quadraticTetraCellIds) line = str(quadraticTetraCellIds.GetNumberOfTuples()) + '\n' f.write(line) for i in range(quadraticTetraCellIds.GetNumberOfTuples()): line = str(i+1) + ' ' cell = self.Mesh.GetCell(quadraticTetraCellIds.GetValue(i)) line += str(cell.GetPointId(0)+1) + ' ' line += str(cell.GetPointId(4)+1) + ' ' line += str(cell.GetPointId(1)+1) + ' ' line += str(cell.GetPointId(5)+1) + ' ' line += str(cell.GetPointId(2)+1) + ' ' line += str(cell.GetPointId(6)+1) + ' ' line += str(cell.GetPointId(7)+1) + ' ' line += str(cell.GetPointId(8)+1) + ' ' line += str(cell.GetPointId(9)+1) + ' ' line += str(cell.GetPointId(3)+1) + ' ' line += '\n' f.write(line) # inletEntities = self.InletEntities # reversedInlets = self.ReverseInlets # inletEntitiesReversed = zip(inletEntities,reversedInlets) # for inletEntityReversed in inletEntitiesReversed: # inletEntity = inletEntityReversed[0] # reversedInlet = inletEntityReversed[1] # if (inletEntity == ''): # continue for inletEntity in self.InletEntities: reversedInlet = inletEntity in self.ReverseInletEntities line = '\n' f.write(line) line = '$binlet' + ' (' + inletEntity + ') ' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(inletEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) sectionBoundaryPointIds = self.GetSectionBoundaryPointIds(inletEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds if not reversedInlet: sectionProperties.FlipOutwardNormal = 1 else: sectionProperties.FlipOutwardNormal = 0 sectionProperties.Execute() line = str(sectionProperties.Radius) + '\n' f.write(line) line = str(sectionProperties.Origin[0]) + ' ' + str(sectionProperties.Origin[1]) + ' ' + str(sectionProperties.Origin[2]) + '\n' f.write(line) line = str(sectionProperties.Normal[0]) + ' ' + str(sectionProperties.Normal[1]) + ' ' + str(sectionProperties.Normal[2]) + '\n' f.write(line) #TODO: for every inlet insert fourier coefficients given points of waveform (spline-interpolate points beforehands to get them equispaced). if (self.OutletEntity != ''): line = '\n' f.write(line) line = '$boutlet' + ' (' + self.OutletEntity + ') ' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.OutletEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) sectionBoundaryPointIds = self.GetSectionBoundaryPointIds(self.OutletEntity) sectionProperties = SectionProperties() sectionProperties.Mesh = self.Mesh sectionProperties.NormalizationTransform = self.NormalizationTransform sectionProperties.SectionBoundaryPointIds = sectionBoundaryPointIds sectionProperties.FlipOutwardNormal = 0 sectionProperties.Execute() line = str(sectionProperties.Radius) + '\n' f.write(line) line = str(sectionProperties.Origin[0]) + ' ' + str(sectionProperties.Origin[1]) + ' ' + str(sectionProperties.Origin[2]) + '\n' f.write(line) line = str(sectionProperties.Normal[0]) + ' ' + str(sectionProperties.Normal[1]) + ' ' + str(sectionProperties.Normal[2]) + '\n' f.write(line) if (self.WallEntity != ''): line = '\n' f.write(line) line = '$bwall' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.WallEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) wallPointIdsMap = vtk.vtkIdList() if (self.WriteWNodeSection == 1): line = '\n' f.write(line) line = '$wnode' + '\n' f.write(line) line = str(numberOfEntityNodes) + '\n' f.write(line) count = 0 wallPointIdsMap.SetNumberOfIds(entityArray.GetNumberOfTuples()) extractSurface = vtk.vtkGeometryFilter() extractSurface.SetInput(self.Mesh) extractSurface.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInput(extractSurface.GetOutput()) normalsFilter.AutoOrientNormalsOn() normalsFilter.ConsistencyOn() normalsFilter.Update() normalsSurface = normalsFilter.GetOutput() locator = vtk.vtkMergePoints() locator.SetDataSet(normalsSurface) locator.BuildLocator() for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): wallPointIdsMap.SetId(i,-1) continue wallPointIdsMap.SetId(i,count) point = self.Mesh.GetPoint(i) surfacePointId = locator.FindClosestPoint(point) normal = normalsSurface.GetPointData().GetNormals().GetTuple3(surfacePointId) line = str(count+1) + ' ' + str(i+1) + ' ' + str(normal[0]) + ' ' + str(normal[1]) + ' ' + str(normal[2]) + '\n' f.write(line) count += 1 if (self.WriteWElemSection == 1): line = '\n' f.write(line) line = '$welem' + '\n' f.write(line) dataArray = vtk.vtkIntArray() dataArray.SetNumberOfComponents(8) for i in range(self.Mesh.GetNumberOfCells()): qtetra = self.Mesh.GetCell(i) for j in range(qtetra.GetNumberOfFaces()): face = qtetra.GetFace(j) isBoundaryFace = 1 for k in range(face.GetNumberOfPoints()): if (entityArray.GetComponent(face.GetPointId(k),0) != 1.0): isBoundaryFace = 0 break if (isBoundaryFace == 0): continue dataArray.InsertNextValue(i) dataArray.InsertNextValue(j) for k in range(face.GetNumberOfPoints()): dataArray.InsertNextValue(face.GetPointId(k)) line = str(dataArray.GetNumberOfTuples()) + '\n' f.write(line) for i in range(dataArray.GetNumberOfTuples()): line = str(i+1) + ' ' line += str(int(dataArray.GetComponent(i,0))+1) + ' ' faceId = int(dataArray.GetComponent(i,1)) newTetrFaceIdsMap = [2, 4, 3, 1] line += str(newTetrFaceIdsMap[faceId]) + ' ' for j in range(2,dataArray.GetNumberOfComponents()): line += str(wallPointIdsMap.GetId(int(dataArray.GetComponent(i,j)))+1) + ' ' line += '\n' f.write(line) if (self.HistoryEntity != ''): line = '\n' f.write(line) line = '$history' + '\n' f.write(line) entityArray = self.Mesh.GetPointData().GetArray(self.HistoryEntity) numberOfEntityNodes = 0 for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue numberOfEntityNodes += 1 line = str(numberOfEntityNodes) + '\n' f.write(line) for i in range(entityArray.GetNumberOfTuples()): if (entityArray.GetComponent(i,0) != 1.0): continue line = str(i+1) + '\n' f.write(line) self.WriteTimeSteps(f)
moldMapper.ScalarVisibilityOff() moldActor = vtk.vtkActor() moldActor.SetMapper(moldMapper) moldActor.GetProperty().SetColor(.2,.2,.2) moldActor.GetProperty().SetRepresentationToWireframe() # extract parison from mesh using connectivity connect2 = vtk.vtkConnectivityFilter() connect2.SetInputConnection(warp.GetOutputPort()) connect2.SetExtractionModeToSpecifiedRegions() connect2.AddSpecifiedRegion(2) extractGrid = vtk.vtkExtractUnstructuredGrid() extractGrid.SetInputConnection(connect2.GetOutputPort()) extractGrid.CellClippingOn() extractGrid.SetCellMinimum(0) extractGrid.SetCellMaximum(23) parison = vtk.vtkGeometryFilter() parison.SetInputConnection(extractGrid.GetOutputPort()) normals2 = vtk.vtkPolyDataNormals() normals2.SetInputConnection(parison.GetOutputPort()) normals2.SetFeatureAngle(60) lut = vtk.vtkLookupTable() lut.SetHueRange(0.0,0.66667) parisonMapper = vtk.vtkPolyDataMapper() parisonMapper.SetInputConnection(normals2.GetOutputPort()) parisonMapper.SetLookupTable(lut) parisonMapper.SetScalarRange(0.12,1.0) parisonActor = vtk.vtkActor() parisonActor.SetMapper(parisonMapper) # graphics stuff ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow()
def smoothMultipleSegments(self): import vtkSegmentationCorePython as vtkSegmentationCore # Generate merged labelmap of all visible segments segmentationNode = self.scriptedEffect.parameterSetNode( ).GetSegmentationNode() visibleSegmentIds = vtk.vtkStringArray() segmentationNode.GetDisplayNode().GetVisibleSegmentIDs( visibleSegmentIds) if visibleSegmentIds.GetNumberOfValues() == 0: logging.info( "Smoothing operation skipped: there are no visible segments") return mergedImage = vtkSegmentationCore.vtkOrientedImageData() if not segmentationNode.GenerateMergedLabelmapForAllSegments( mergedImage, vtkSegmentationCore.vtkSegmentation. EXTENT_UNION_OF_SEGMENTS_PADDED, None, visibleSegmentIds): logging.error( 'Failed to apply smoothing: cannot get list of visible segments' ) return # Perform smoothing in voxel space ici = vtk.vtkImageChangeInformation() ici.SetInputData(mergedImage) ici.SetOutputSpacing(1, 1, 1) ici.SetOutputOrigin(0, 0, 0) # Convert labelmap to combined polydata convertToPolyData = vtk.vtkDiscreteMarchingCubes() convertToPolyData.SetInputConnection(ici.GetOutputPort()) startLabel = 1 endLabel = visibleSegmentIds.GetNumberOfValues() convertToPolyData.GenerateValues(endLabel - startLabel + 1, startLabel, endLabel) # Low-pass filtering using Taubin's method smoothingFactor = self.scriptedEffect.doubleParameter( "JointTaubinSmoothingFactor") smoothingIterations = 100 # according to VTK documentation 10-20 iterations could be enough but we use a higher value to reduce chance of shrinking passBand = pow( 10.0, -4.0 * smoothingFactor ) # gives a nice range of 1-0.0001 from a user input of 0-1 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(convertToPolyData.GetOutputPort()) smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(90.0) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() # Extract a label threshold = vtk.vtkThreshold() threshold.SetInputConnection(smoother.GetOutputPort()) # Convert to polydata geometryFilter = vtk.vtkGeometryFilter() geometryFilter.SetInputConnection(threshold.GetOutputPort()) # Convert polydata to stencil polyDataToImageStencil = vtk.vtkPolyDataToImageStencil() polyDataToImageStencil.SetInputConnection( geometryFilter.GetOutputPort()) polyDataToImageStencil.SetOutputSpacing(1, 1, 1) polyDataToImageStencil.SetOutputOrigin(0, 0, 0) polyDataToImageStencil.SetOutputWholeExtent(mergedImage.GetExtent()) # Convert stencil to image stencil = vtk.vtkImageStencil() emptyBinaryLabelMap = vtk.vtkImageData() emptyBinaryLabelMap.SetExtent(mergedImage.GetExtent()) emptyBinaryLabelMap.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) vtkSegmentationCore.vtkOrientedImageDataResample.FillImage( emptyBinaryLabelMap, 0) stencil.SetInputData(emptyBinaryLabelMap) stencil.SetStencilConnection(polyDataToImageStencil.GetOutputPort()) stencil.ReverseStencilOn() stencil.SetBackgroundValue( 1 ) # General foreground value is 1 (background value because of reverse stencil) imageToWorldMatrix = vtk.vtkMatrix4x4() mergedImage.GetImageToWorldMatrix(imageToWorldMatrix) for i in range(visibleSegmentIds.GetNumberOfValues()): threshold.ThresholdBetween(i + 1, i + 1) stencil.Update() smoothedBinaryLabelMap = vtkSegmentationCore.vtkOrientedImageData() smoothedBinaryLabelMap.ShallowCopy(stencil.GetOutput()) smoothedBinaryLabelMap.SetImageToWorldMatrix(imageToWorldMatrix) # Write results to segments directly, bypassing masking slicer.vtkSlicerSegmentationsModuleLogic.SetBinaryLabelmapToSegment( smoothedBinaryLabelMap, segmentationNode, visibleSegmentIds.GetValue(i), slicer.vtkSlicerSegmentationsModuleLogic.MODE_REPLACE, smoothedBinaryLabelMap.GetExtent())
def geometryFilt(vtkObject): geoFilt = vtk.vtkGeometryFilter() geoFilt.SetInputData(vtkObject) geoFilt.Update() return geoFilt.GetOutput()
lut.SetTableValue(1,0,1,0,1) lut.SetTableValue(2,0,1,1,1) lut.SetTableValue(3,1,0,0,1) lut.SetTableValue(4,1,0,1,1) masks = "0 1 2 3 4 5 6 7 10 11 14 15 16 18 20 22 26 30" i = 0 j = 0 k = 0 types = "strip triangle" for type in types.split(): for mask in masks.split(): locals()[get_variable_name("grid", i, "")] = vtk.vtkUnstructuredGrid() locals()[get_variable_name("grid", i, "")].Allocate(1,1) locals()[get_variable_name("grid", i, "")].InsertNextCell(aTriangleStrip.GetCellType(),aTriangleStrip.GetPointIds()) locals()[get_variable_name("grid", i, "")].SetPoints(triangleStripPoints) locals()[get_variable_name("geometry", i, "")] = vtk.vtkGeometryFilter() locals()[get_variable_name("geometry", i, "")].SetInputData(locals()[get_variable_name("grid", i, "")]) locals()[get_variable_name("triangles", i, "")] = vtk.vtkTriangleFilter() locals()[get_variable_name("triangles", i, "")].SetInputConnection(locals()[get_variable_name("geometry", i, "")].GetOutputPort()) locals()[get_variable_name("mapper", i, "")] = vtk.vtkPolyDataMapper() if (type == "strip"): locals()[get_variable_name("mapper", i, "")].SetInputConnection(locals()[get_variable_name("geometry", i, "")].GetOutputPort()) pass if (type == "triangle"): locals()[get_variable_name("mapper", i, "")].SetInputConnection(locals()[get_variable_name("triangles", i, "")].GetOutputPort()) pass locals()[get_variable_name("mapper", i, "")].SetLookupTable(lut) locals()[get_variable_name("mapper", i, "")].SetScalarRange(0,4) locals()[get_variable_name("actor", i, "")] = vtk.vtkActor() locals()[get_variable_name("actor", i, "")].SetMapper(locals()[get_variable_name("mapper", i, "")]) if (expr.expr(globals(), locals(),["mask","&","1"]) != 0):
from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # create a rendering window and renderer ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) renWin.StereoCapableWindowOn() iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) reader = vtk.vtkGenericEnSightReader() # Make sure all algorithms use the composite data pipeline cdp = vtk.vtkCompositeDataPipeline() reader.SetDefaultExecutivePrototype(cdp) reader.SetCaseFileName("" + str(VTK_DATA_ROOT) + "/Data/EnSight/elements.case") geom0 = vtk.vtkGeometryFilter() geom0.SetInputConnection(reader.GetOutputPort()) mapper0 = vtk.vtkHierarchicalPolyDataMapper() mapper0.SetInputConnection(geom0.GetOutputPort()) mapper0.SetColorModeToMapScalars() mapper0.SetScalarModeToUsePointFieldData() mapper0.ColorByArrayComponent("pointScalars",0) mapper0.SetScalarRange(0,112) actor0 = vtk.vtkActor() actor0.SetMapper(mapper0) # assign our actor to the renderer ren1.AddActor(actor0) # enable user interface interactor iren.Initialize() # prevent the tk window from showing up then start the event loop reader.SetDefaultExecutivePrototype(None)
def __init__(self, inputobj=None): vtk.vtkActor.__init__(self) BaseGrid.__init__(self) inputtype = str(type(inputobj)) self._data = None self._polydata = None self.name = "UGrid" ################### if inputobj is None: self._data = vtk.vtkUnstructuredGrid() elif utils.isSequence(inputobj): pts, cells, celltypes = inputobj self._data = vtk.vtkUnstructuredGrid() if not utils.isSequence(cells[0]): tets = [] nf = cells[0] + 1 for i, cl in enumerate(cells): if i == nf or i == 0: k = i + 1 nf = cl + k cell = [cells[j + k] for j in range(cl)] tets.append(cell) cells = tets # This would fill the points and use those to define orientation vpts = utils.numpy2vtk(pts, dtype=float) points = vtk.vtkPoints() points.SetData(vpts) self._data.SetPoints(points) # This fill the points and use cells to define orientation # points = vtk.vtkPoints() # for c in cells: # for pid in c: # points.InsertNextPoint(pts[pid]) # self._data.SetPoints(points) # Fill cells # https://vtk.org/doc/nightly/html/vtkCellType_8h_source.html for i, ct in enumerate(celltypes): cell_conn = cells[i] if ct == vtk.VTK_HEXAHEDRON: cell = vtk.vtkHexahedron() elif ct == vtk.VTK_TETRA: cell = vtk.vtkTetra() elif ct == vtk.VTK_VOXEL: cell = vtk.vtkVoxel() elif ct == vtk.VTK_WEDGE: cell = vtk.vtkWedge() elif ct == vtk.VTK_PYRAMID: cell = vtk.vtkPyramid() elif ct == vtk.VTK_HEXAGONAL_PRISM: cell = vtk.vtkHexagonalPrism() elif ct == vtk.VTK_PENTAGONAL_PRISM: cell = vtk.vtkPentagonalPrism() else: print("UGrid: cell type", ct, "not implemented. Skip.") continue cpids = cell.GetPointIds() for j, pid in enumerate(cell_conn): cpids.SetId(j, pid) self._data.InsertNextCell(ct, cpids) elif "UnstructuredGrid" in inputtype: self._data = inputobj elif isinstance(inputobj, str): from vedo.io import download, loadUnStructuredGrid if "https://" in inputobj: inputobj = download(inputobj, verbose=False) self._data = loadUnStructuredGrid(inputobj) self.filename = inputobj else: colors.printc("UGrid(): cannot understand input type:\n", inputtype, c='r') return # self._mapper = vtk.vtkDataSetMapper() self._mapper = vtk.vtkPolyDataMapper() self._mapper.SetInterpolateScalarsBeforeMapping( settings.interpolateScalarsBeforeMapping) if settings.usePolygonOffset: self._mapper.SetResolveCoincidentTopologyToPolygonOffset() pof, pou = settings.polygonOffsetFactor, settings.polygonOffsetUnits self._mapper.SetResolveCoincidentTopologyPolygonOffsetParameters( pof, pou) self.GetProperty().SetInterpolationToFlat() if not self._data: return # now fill the representation of the vtk unstr grid sf = vtk.vtkShrinkFilter() sf.SetInputData(self._data) sf.SetShrinkFactor(1.0) sf.Update() gf = vtk.vtkGeometryFilter() gf.SetInputData(sf.GetOutput()) gf.Update() self._polydata = gf.GetOutput() self._mapper.SetInputData(self._polydata) sc = None if self.useCells: sc = self._polydata.GetCellData().GetScalars() else: sc = self._polydata.GetPointData().GetScalars() if sc: self._mapper.SetScalarRange(sc.GetRange()) self.SetMapper(self._mapper) self.property = self.GetProperty()
bot_with_z.SetInputArrayToProcess(0, 0, 0, 0, "Elevation") bot_with_z.Update() bot_with_z = bot_with_z.GetOutput() if bot_with_z.GetPointData().GetArray("vtkValidPointMask").GetRange()[0] < 1: # there are some invalid points if opts.verbose: print "**** Incompatible meshes produced invalid points ****" if opts.verbose: print "Removing invalid points" only_valid = vtk.vtkThreshold() only_valid.SetInput(bot_with_z) only_valid.SetInputArrayToProcess(0, 0, 0, 0, "vtkValidPointMask") only_valid.ThresholdBetween(0.5, 1.5) only_valid.Update() only_valid = only_valid.GetOutput() only_valid_poly = vtk.vtkGeometryFilter() only_valid_poly.SetInput(only_valid) only_valid_poly.Update() only_valid_poly = only_valid_poly.GetOutput() # now must re-mesh if opts.verbose: print "Performing Delaunay triangulation" delaunay = vtk.vtkDelaunay2D() delaunay.SetInput(only_valid_poly) delaunay.Update() if opts.verbose: print "Getting rid of unused points" no_orphaned_points = vtk.vtkCleanPolyData() no_orphaned_points.SetInput(delaunay.GetOutput()) no_orphaned_points.Update() to_write = no_orphaned_points.GetOutput() else:
def construct_palettes(render_window): """ """ legend = {} render_window.OffScreenRenderingOn() # to not pop a vtk windows render_window.Render() renderers = render_window.GetRenderers() for renderer in renderers: for renProp in renderer.GetViewProps(): if not renProp.GetVisibility() or not isinstance( renProp, vtk.vtkActor): continue if hasattr(renProp, 'GetMapper'): mapper = renProp.GetMapper() if mapper is None: continue dataObject = mapper.GetInputDataObject(0, 0) dataset = None if dataObject.IsA('vtkCompositeDataSet'): if dataObject.GetNumberOfBlocks() == 1: dataset = dataObject.GetBlock(0) else: gf = vtk.vtkCompositeDataGeometryFilter() gf.SetInputData(dataObject) gf.Update() dataset = gf.GetOutput() elif dataObject.IsA('vtkUnstructuredGrid'): gf = vtk.vtkGeometryFilter() gf.SetInputData(dataObject) gf.Update() dataset = gf.GetOutput() else: dataset = mapper.GetInput() if dataset and not isinstance(dataset, (vtk.vtkPolyData)): # All data must be PolyData surfaces! gf = vtk.vtkGeometryFilter() gf.SetInputData(dataset) gf.Update() dataset = gf.GetOutputDataObject(0) if dataset and dataset.GetPoints(): scalar_visibility = mapper.GetScalarVisibility() array_access_mode = mapper.GetArrayAccessMode() array_name = mapper.GetArrayName( ) # if arrayAccessMode == 1 else mapper.GetArrayId() array_id = mapper.GetArrayId() scalar_mode = mapper.GetScalarMode() dataArray = None lookupTable = mapper.GetLookupTable() if scalar_visibility: dataArray, _ = get_dataset_scalars( dataset, scalar_mode, array_access_mode, array_id, array_name) # component = -1 => let specific instance get scalar from vector before mapping if dataArray: if dataArray.GetLookupTable(): lookupTable = dataArray.GetLookupTable() if array_name and legend is not None: legend.update({ array_name: vtk_lut_to_palette(lookupTable) }) return legend
def render_window_serializer(render_window): """ Function to convert a vtk render window in a list of 2-tuple where first value correspond to a relative file path in the `vtkjs` directory structure and values of the binary content of the corresponding file. """ render_window.OffScreenRenderingOn() # to not pop a vtk windows render_window.Render() renderers = render_window.GetRenderers() objIds = [] scDirs = [] sceneComponents = [] textureToSave = {} for renderer in renderers: for renProp in renderer.GetViewProps(): if not renProp.GetVisibility() or not isinstance( renProp, vtk.vtkActor): continue if hasattr(renProp, 'GetMapper'): mapper = renProp.GetMapper() if mapper is None: continue dataObject = mapper.GetInputDataObject(0, 0) dataset = None if dataObject.IsA('vtkCompositeDataSet'): if dataObject.GetNumberOfBlocks() == 1: dataset = dataObject.GetBlock(0) else: gf = vtk.vtkCompositeDataGeometryFilter() gf.SetInputData(dataObject) gf.Update() dataset = gf.GetOutput() elif dataObject.IsA('vtkUnstructuredGrid'): gf = vtk.vtkGeometryFilter() gf.SetInputData(dataObject) gf.Update() dataset = gf.GetOutput() else: dataset = mapper.GetInput() if dataset and not isinstance(dataset, (vtk.vtkPolyData)): # All data must be PolyData surfaces! gf = vtk.vtkGeometryFilter() gf.SetInputData(dataset) gf.Update() dataset = gf.GetOutputDataObject(0) if dataset and dataset.GetPoints(): componentName = str(id(renProp)) scalar_visibility = mapper.GetScalarVisibility() array_access_mode = mapper.GetArrayAccessMode() array_name = mapper.GetArrayName( ) # if arrayAccessMode == 1 else mapper.GetArrayId() array_id = mapper.GetArrayId() color_mode = mapper.GetColorMode() scalar_mode = mapper.GetScalarMode() arrayLocation = '' colorArray = None dataArray = None colorArrayName = '' lookupTable = mapper.GetLookupTable() if scalar_visibility: dataArray, arrayLocation = get_dataset_scalars( dataset, scalar_mode, array_access_mode, array_id, array_name) # component = -1 => let specific instance get scalar from vector before mapping if dataArray: if dataArray.GetLookupTable(): lookupTable = dataArray.GetLookupTable() colorArray = dataArray.GetLookupTable( ).MapScalars(dataArray, color_mode, -1) else: colorArray = lookupTable.MapScalars( dataArray, color_mode, -1) colorArrayName = '__CustomRGBColorArray__' colorArray.SetName(colorArrayName) color_mode = 0 colorArrayInfo = { 'colorArray': colorArray, 'location': arrayLocation } _write_data_set(scDirs, dataset, colorArrayInfo, newDSName=componentName) # Handle texture if any textureName = None if renProp.GetTexture() and renProp.GetTexture().GetInput( ): textureData = renProp.GetTexture().GetInput() textureName = 'texture_%d' % _get_object_id( textureData, objIds) textureToSave[textureName] = textureData sceneComponents.append({ "name": componentName, "type": "httpDataSetReader", "httpDataSetReader": { "url": componentName }, "actor": { # customProp "id": renProp.__this__, # vtkProp "visibility": renProp.GetVisibility() if renProp.IsA('vtkProp') else 0, "pickable": renProp.GetPickable() if renProp.IsA('vtkProp') else 0, "dragable": renProp.GetDragable() if renProp.IsA('vtkProp') else 0, "useBounds": renProp.GetUseBounds() if renProp.IsA('vtkProp') else 0, # vtkProp3D "origin": renProp.GetOrigin() if renProp.IsA('vtkProp3D') else [0, 0, 0], "scale": renProp.GetScale() if renProp.IsA('vtkProp3D') else [1, 1, 1], "position": renProp.GetPosition() if renProp.IsA('vtkProp3D') else [0, 0, 0], # vtkActor 'forceOpaque': renProp.GetForceOpaque() if renProp.IsA('vtkActor') else 0, 'forceTranslucent': renProp.GetForceTranslucent() if renProp.IsA('vtkActor') else 0, }, "actorRotation": renProp.GetOrientationWXYZ() if renProp.IsA('vtkProp3D') else [0, 0, 0, 0], "mapper": { "colorByArrayName": colorArrayName, "colorMode": color_mode, "scalarMode": scalar_mode }, "property": extract_renprop_properties(renProp), "lookupTable": { "range": lookupTable.GetRange(), "hueRange": lookupTable.GetHueRange() if hasattr( lookupTable, 'GetHueRange') else [0.5, 0] } }) if textureName: sceneComponents[-1]['texture'] = textureName # Save texture data if any for key, val in textureToSave.items(): _write_data_set(scDirs, val, None, newDSName=key) activeCamera = renderer.GetActiveCamera() background = renderer.GetBackground() sceneDescription = { "fetchGzip": False, "background": background, "camera": { "focalPoint": activeCamera.GetFocalPoint(), "position": activeCamera.GetPosition(), "viewUp": activeCamera.GetViewUp(), "clippingRange": activeCamera.GetClippingRange() }, "centerOfRotation": renderer.GetCenter(), "scene": sceneComponents, } scDirs.append(['index.json', json.dumps(sceneDescription, indent=4)]) # create binary stream of the vtkjs directory structure compression = zipfile.ZIP_DEFLATED with BytesIO() as in_memory: zf = zipfile.ZipFile(in_memory, mode="w") try: for dirPath, data in scDirs: zf.writestr(dirPath, data, compress_type=compression) finally: zf.close() in_memory.seek(0) return in_memory.read()
iD = vtk.vtkImageData() dims = [31, 31, 31] iD.SetSpacing(1.0, 1.0, 1.0) iD.SetOrigin(0, 0, 0) iD.SetDimensions(dims) xaxis = np.linspace(-0.5, 1.0, dims[0]) yaxis = np.linspace(-1.0, 1.0, dims[1]) zaxis = np.linspace(-1.0, 0.5, dims[2]) [xc, yc, zc] = np.meshgrid(zaxis, yaxis, xaxis, indexing="ij") data = np.sqrt(xc ** 2 + yc ** 2 + zc ** 2) image = dsa.WrapDataObject(iD) image.PointData.append(data.ravel(), "scalar") geom = vtk.vtkGeometryFilter() geom.SetInputData(iD) m = vtk.vtkPolyDataMapper() m.SetInputConnection(geom.GetOutputPort()) a = vtk.vtkActor() a.SetMapper(m) a.GetProperty().EdgeVisibilityOn() ren = vtk.vtkRenderer() ren.AddActor(a) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(600, 600)
for i in range(len(ListLineSourceElectron)): glyphActor_MC_electron.append( MyGlyphPoints.ReturnGlyphActorFromLineSource( ListLineSourceElectron[i], 7, banana)) for i in range(len(ListLineSourceGamma)): glyphActor_MC_gamma.append( MyGlyphPoints.ReturnGlyphActorFromLineSource( ListLineSourceGamma[i], 7, mint)) #open the geometry print bcolors.HEADER + "-------------------now loading the vtk geometry file:", VTKGeomFileName, "-------------------------" + bcolors.ENDC reader = vtk.vtkPolyDataReader() reader.SetFileName(VTKGeomFileName) reader.Update() imageDataGeometryFilter = vtk.vtkGeometryFilter() imageDataGeometryFilter.SetInputConnection(reader.GetOutputPort()) imageDataGeometryFilter.Update() mapper.SetInputConnection(imageDataGeometryFilter.GetOutputPort()) GeomActor = vtk.vtkActor() GeomActor.SetMapper(mapper) GeomActor.GetProperty().SetPointSize(10) GeomActor.GetProperty().SetOpacity(.1) print bcolors.OKBLUE + "-------------------DONE loading the vtk geometry file:" + bcolors.ENDC renWin = vtk.vtkRenderWindow() renWin.SetSize(3000, 1500) iren = vtk.vtkRenderWindowInteractor() iren.SetInteractorStyle(vtk.vtkInteractorStyleTrackballCamera()) iren.SetRenderWindow(renWin) #imageStyle=vtk.vtkInteractorStyleImage() # remove 3D interaction and only zoom, this would be ideal for the projection views (but at the moment cannot set only this style for one window)
extract.SetInputConnection(random.GetOutputPort()) extract.Update() # The cut plane plane = vtk.vtkPlane() plane.SetOrigin(0,0,0) plane.SetNormal(1,1,1) # Now create the usual extractor cutter = vtk.vtkExtractGeometry() cutter.SetInputConnection(extract.GetOutputPort()) cutter.SetImplicitFunction(plane) cutter.ExtractBoundaryCellsOn() cutter.ExtractOnlyBoundaryCellsOn() cutterSurface = vtk.vtkGeometryFilter() cutterSurface.SetInputConnection(cutter.GetOutputPort()) cutterSurface.MergingOff() cutterMapper = vtk.vtkPolyDataMapper() cutterMapper.SetInputConnection(cutterSurface.GetOutputPort()) cutterActor = vtk.vtkActor() cutterActor.SetMapper(cutterMapper) cutterActor.GetProperty().SetColor(1,1,1) # Throw in an outline outline = vtk.vtkOutlineFilter() outline.SetInputConnection(sample.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper()
def prepMarker(renWin, ren, marker, cmap=None): n = prepPrimitive(marker) if n == 0: return for i in range(n): ## Creates the glyph g = vtk.vtkGlyph2D() markers = vtk.vtkPolyData() x = marker.x[i] y = marker.y[i] c = marker.color[i] s = marker.size[i] / float(max(marker.worldcoordinate)) * 10. t = marker.type[i] N = max(len(x), len(y)) for a in [x, y]: while len(a) < n: a.append(a[-1]) pts = vtk.vtkPoints() geo, pts = project(pts, marker.projection, marker.worldcoordinate) for j in range(N): pts.InsertNextPoint(x[j], y[j], 0.) markers.SetPoints(pts) # Type ## Ok at this point generates the source for glpyh 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() 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 / 10. 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 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() #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() gs.SetScale(s) gs.Update() if pd is None: g.SetSourceConnection(gs.GetOutputPort()) g.SetInputData(markers) a = vtk.vtkActor() m = vtk.vtkPolyDataMapper() m.SetInputConnection(g.GetOutputPort()) m.Update() a.SetMapper(m) p = a.GetProperty() #Color if cmap is None: if marker.colormap is not None: cmap = marker.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, marker.viewport, wc=marker.worldcoordinate, geo=geo) return