def OnExportSurface(self, pubsub_evt): filename, filetype = pubsub_evt.data if (filetype == const.FILETYPE_STL) or\ (filetype == const.FILETYPE_VTP) or\ (filetype == const.FILETYPE_PLY) or\ (filetype == const.FILETYPE_STL_ASCII): # First we identify all surfaces that are selected # (if any) proj = prj.Project() polydata_list = [] for index in proj.surface_dict: surface = proj.surface_dict[index] if surface.is_shown: polydata_list.append(surface.polydata) if len(polydata_list) == 0: utl.debug("oops - no polydata") return elif len(polydata_list) == 1: polydata = polydata_list[0] else: polydata = pu.Merge(polydata_list) # Having a polydata that represents all surfaces # selected, we write it, according to filetype if filetype == const.FILETYPE_STL: writer = vtk.vtkSTLWriter() writer.SetFileTypeToBinary() elif filetype == const.FILETYPE_STL_ASCII: writer = vtk.vtkSTLWriter() writer.SetFileTypeToASCII() elif filetype == const.FILETYPE_VTP: writer = vtk.vtkXMLPolyDataWriter() #elif filetype == const.FILETYPE_IV: # writer = vtk.vtkIVWriter() elif filetype == const.FILETYPE_PLY: writer = vtk.vtkPLYWriter() writer.SetFileTypeToASCII() writer.SetColorModeToOff() #writer.SetDataByteOrderToLittleEndian() #writer.SetColorModeToUniformCellColor() #writer.SetColor(255, 0, 0) if filetype in (const.FILETYPE_STL, const.FILETYPE_PLY): # Invert normals normals = vtk.vtkPolyDataNormals() normals.SetInputData(polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.UpdateInformation() normals.Update() polydata = normals.GetOutput() filename = filename.encode(wx.GetDefaultPyEncoding()) writer.SetFileName(filename) writer.SetInputData(polydata) writer.Write()
def __init__(self, mesh): assert mesh != None self._mesh = mesh self._batch = None self._color = (0.0, 1.0, 0.0, 1.0) #smooth_loop = vtk.vtkLoopSubdivisionFilter() #smooth_loop.SetNumberOfSubdivisions(3) #smooth_loop.SetInput(cleanPolyData.GetOutput()) #self.mesh = smooth_loop.GetOutput() normals = vtk.vtkPolyDataNormals() normals.SetInput(self._mesh) normals.ComputeCellNormalsOn() output = normals.GetOutput() output.Update(); cellData = output.GetCellData(); self._normals = cellData.GetNormals(); self._caster = vtk.vtkOBBTree() #set the 'mesh' as the caster's dataset self._caster.SetDataSet(self._mesh) #build a caster locator self._caster.BuildLocator()
def _initialize (self): debug ("In TensorGlyphs::_initialize ()") self.sphere.SetThetaResolution (8) self.sphere.SetPhiResolution (8) self.glyphs.SetInput (self.data_out) self.glyphs.SetSource (self.sphere.GetOutput()) self.glyphs.SetScaleFactor (1.0) self.glyphs.ClampScalingOn () self.glyphs.SetMaxScaleFactor (5.0) self.normals = vtk.vtkPolyDataNormals () self.normals.SetInput (self.glyphs.GetOutput ()) self.mapper.SetInput (self.normals.GetOutput ()) self.actor.SetMapper (self.mapper) self.actor.GetProperty ().SetLineWidth (2) self.actor.GetProperty ().BackfaceCullingOff () # self.actor.GetProperty ().FrontfaceCullingOff () self.actor.GetProperty ().SetColor (*Common.config.fg_color) self.center = self.data_out.GetCenter () self.renwin.add_actors (self.actor) # used for the pipeline browser self.pipe_objs = self.actor
def AddPolyData(self, polyData, colorMap=None): """ colorMap should be a vtkScalarsToColors (or derived class) object """ if colorMap is None: colorMap = VTKViewer.GetDefaultColorMap(polyData.GetScalarRange()) polyDataMapper = vtk.vtkPolyDataMapper() polyDataMapper.SetLookupTable(colorMap) if polyData.GetPointData().GetNormals() is None: polyDataNormals = vtk.vtkPolyDataNormals() try: polyDataNormals.SetInputData(polyData) except: polyDataNormals.SetInput(polyData) polyDataNormals.SetFeatureAngle(90.0) polyDataMapper.SetInputConnection( polyDataNormals.GetOutputPort()) else: try: polyDataMapper.SetInputData(polyData) except: polyDataMapper.SetInput(polyData) actor = vtk.vtkActor() actor.GetProperty().SetPointSize(3) actor.SetMapper(polyDataMapper) self.renderer.AddActor(actor)
def get_isosurface(self, iso_value=500): if not self.flag_read: sys.stderr.write('No Image Loaded!\n') return contour = vtk.vtkContourFilter() normals = vtk.vtkPolyDataNormals() stripper = vtk.vtkStripper() mapper = vtk.vtkPolyDataMapper() contour.SetInputData(self.reader) contour.SetValue(0, iso_value) normals.SetInputConnection(contour.GetOutputPort()) normals.SetFeatureAngle(60.0) normals.ReleaseDataFlagOn() stripper.SetInputConnection(normals.GetOutputPort()) stripper.ReleaseDataFlagOn() mapper.SetInputConnection(stripper.GetOutputPort()) mapper.SetScalarVisibility(False) actor = vtk.vtkActor() actor.SetMapper(mapper) # Default colour, should be changed. actor.GetProperty().SetDiffuseColor( [247.0 / 255.0, 150.0 / 255.0, 155.0 / 255.0]) # Look like red actor.GetProperty().SetSpecular(0.3) actor.GetProperty().SetSpecularPower(20) return actor
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkPolyDataNormals(), 'Processing.', ('vtkPolyData',), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def MouseMove(self, data): print("Load Cache %s" % data ) print ("Iren data") #print iren #addcube #print ren print ren.GetViewPoint() print ren.GetDisplayPoint() print ren.WorldToView() print ren.ComputeVisiblePropBounds() ysize = renWin.GetSize()[1] c.SetValue(0,ysize) c.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputData(c.GetOutput()) normals.SetFeatureAngle(25) #? normals.Update() normals.SetFeatureAngle(45) #? normals.Update() mapper2 = vtk.vtkPolyDataMapper() mapper2.SetInputData(normals.GetOutput()) mapper2.ScalarVisibilityOn() mapper2.SetScalarRange(-.5,1) mapper2.SetScalarModeToUsePointFieldData() mapper2.ColorByArrayComponent("Velocity", 0) actor2 = vtk.vtkActor() actor2.SetMapper(mapper2) ren.AddActor(actor2)
def Execute(self): if self.Surface == None: self.PrintError('Error: No Surface.') if self.ReferenceSurface == None: self.PrintError('Error: No ReferenceSurface.') if self.SignedDistanceArrayName != '': normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputData(self.ReferenceSurface) normalsFilter.AutoOrientNormalsOn() normalsFilter.SetFlipNormals(self.FlipNormals) normalsFilter.Update() self.ReferenceSurface.GetPointData().SetNormals(normalsFilter.GetOutput().GetPointData().GetNormals()) if self.DistanceArrayName != '' or self.DistanceVectorsArrayName != '' or self.SignedDistanceArrayName != '': self.PrintLog('Computing distance.') surfaceDistance = vtkvmtk.vtkvmtkSurfaceDistance() surfaceDistance.SetInputData(self.Surface) surfaceDistance.SetReferenceSurface(self.ReferenceSurface) if self.DistanceArrayName != '': surfaceDistance.SetDistanceArrayName(self.DistanceArrayName) if self.DistanceVectorsArrayName != '': surfaceDistance.SetDistanceVectorsArrayName(self.DistanceVectorsArrayName) if self.SignedDistanceArrayName != '': surfaceDistance.SetSignedDistanceArrayName(self.SignedDistanceArrayName) surfaceDistance.Update() self.Surface = surfaceDistance.GetOutput()
def __init__(self, grid, vtkish_polydata=None, angle=15): vtkPolyDataPipeline.__init__(self, vtkish_polydata) # Make sure grid argument is correct type assert isinstance(grid, vtkVolumeGrid) self.grid = grid # Split polys with intersection angles greater than angle vtk_dnorm = vtkPolyDataNormals() vtk_dnorm.SetFeatureAngle(angle) vtk_dnorm.SplittingOn() vtk_dnorm.ComputeCellNormalsOff() vtk_dnorm.ComputePointNormalsOff() self.append(vtk_dnorm) relax = self.grid.get_relaxation_factor() if relax is not None: print 'relax=',relax #vtk_subdiv = vtkButterflySubdivisionFilter() vtk_subdiv = vtkLinearSubdivisionFilter() self.append(vtk_subdiv) # Smooth out some of the sharp points. vtk_smooth = vtkSmoothPolyDataFilter() vtk_smooth.SetRelaxationFactor(relax) self.append(vtk_smooth)
def polyNorm(ren,obj): #@c Add vtkPolyDataNormals to the vtkPolyData viewing pipeline. #@note there is no proc to perform the reverse operation (i.e. remove #@note the normals). This is because the caller can presumably just #@note turn off normal-based properties via the actor's vtkProperty. #@a ren: renderer #@a obj: object name if isinstance(obj,list): tag = "%s_%s" % (ren[0],obj[0]) objName = obj[0] elif isinstance(obj,str): tag = "%s_%s" % (ren[0],obj) objName = obj else: raise ValueError("Argument type unsupported.") nrm = [None]*2 try: Map = getattr(vis,"p_map_"+tag) except: raise ValueError(objName + " not currently being displayed in " + ren[0]) act = getattr(vis,"p_act_"+tag) nrm[0] = "p_nrm_" + tag nrm[1] = vtk.vtkPolyDataNormals() nrm[1].SetInputDataObject(Map[1].GetInput()) Map[1].SetInputDataObject(nrm[1].GetOutput()) nrm[1].Update() setattr(vis,Map[0], Map) setattr(vis,act[0],act) setattr(vis,nrm[0],nrm) return act
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 vertex_normal(dataset): "Returns the vertex normal of each point in a dataset." if not dataset: raise RuntimeError("Need a dataset to compute vertex_normal") ds = dataset.NewInstance() ds.UnRegister(None) ds.CopyStructure(dataset.VTKObject) filter = vtk.vtkPolyDataNormals() filter.SetInputData(ds) filter.ComputeCellNormalsOff() filter.ComputePointNormalsOn() filter.SetFeatureAngle(180) filter.SplittingOff() filter.ConsistencyOff() filter.AutoOrientNormalsOff() filter.FlipNormalsOff() filter.NonManifoldTraversalOff() filter.Update() varray = filter.GetOutput().GetPointData().GetNormals() ans = dsa.vtkDataArrayToVTKArray(varray, dataset) # The association information has been lost over the vtk filter # we must reconstruct it otherwise lower pipeline will be broken. ans.Association = dsa.ArrayAssociation.POINT return ans
def create_actors_for_skin_and_bone(reader): actors_list = [] for contour_val, color, opacity in SKIN_BONE_LIST: contour = vtk.vtkContourFilter() contour.SetInput(reader.GetOutput()) contour.SetNumberOfContours(1) contour.SetValue(contour_val[0], contour_val[1]) normals = vtk.vtkPolyDataNormals() normals.SetInput(contour.GetOutput()) normals.SetFeatureAngle(60) normals.ConsistencyOff() normals.SplittingOff() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(normals.GetOutput()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) actor.GetProperty().SetOpacity(opacity) actor.RotateX(-90) actors_list.append(actor) return actors_list
def AddPolyData(self, polyData, colorMap=None): """ colorMap should be a vtkScalarsToColors (or derived class) object """ if colorMap is None: colorMap = VTKViewer.GetDefaultColorMap(polyData.GetScalarRange()) polyDataMapper = vtk.vtkPolyDataMapper() polyDataMapper.SetLookupTable(colorMap) if polyData.GetPointData().GetNormals() is None: polyDataNormals = vtk.vtkPolyDataNormals() # Migrate to VTK6: # http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput # Old: polyDataNormals.SetInput(polyData) polyDataNormals.SetInputData(polyData) polyDataNormals.SetFeatureAngle(90.0) polyDataMapper.SetInputConnection(polyDataNormals.GetOutputPort()) else: # Migrate to VTK6: # http://www.vtk.org/Wiki/VTK/VTK_6_Migration/Replacement_of_SetInput # Old: polyDataMapper.SetInput(polyData) polyDataMapper.SetInputData(polyData) actor = vtk.vtkActor() actor.GetProperty().SetPointSize(3) actor.SetMapper(polyDataMapper) self.renderer.AddActor(actor)
def setUp(self): self.vtk_iso = vtkContourFilter() # self.vtk_iso.SetInput(...) self.vtk_dnorm = vtkPolyDataNormals() self.vtk_subdiv = vtkLinearSubdivisionFilter() self.vtk_dmap = vtkPolyDataMapper()
def __init__(self, reader): self.reader = reader sg = self.src_glyph = vtk.vtkSphereSource() sg.SetRadius(0.5) sg.SetCenter(0.5, 0.0, 0.0) g = self.glyph = vtk.vtkTensorGlyph() g.SetInputConnection(self.reader.GetOutputPort()) g.SetSource(self.src_glyph.GetOutput()) g.SetScaleFactor(0.25) # The normals are needed to generate the right colors and if # not used some of the glyphs are black. self.normals = vtk.vtkPolyDataNormals() self.normals.SetInputConnection(g.GetOutputPort()) self.map = vtk.vtkPolyDataMapper() self.map.SetInputConnection(self.normals.GetOutputPort()) self.act = vtk.vtkActor() self.act.SetMapper(self.map) # An outline. self.of = vtk.vtkOutlineFilter() self.of.SetInputConnection(self.reader.GetOutputPort()) self.out_map = vtk.vtkPolyDataMapper() self.out_map.SetInputConnection(self.of.GetOutputPort()) self.out_act = vtk.vtkActor() self.out_act.SetMapper(self.out_map)
def Contours(self, num, opacity=0.2): contour = vtk.vtkMarchingContourFilter() contour.SetInput(self.vtkgrid) r = max(abs(self.vmin), abs(self.vmax)) if num % 2 == 0 or self.vmin * self.vmax >= 0: contour.GenerateValues( num, (self.vmin + r / num, self.vmax - r / num)) elif num == 1: contour.SetValue(0, 0) else: r = r - r / num contour.GenerateValues(num, -r, r) contour.ComputeScalarsOn() contour.UseScalarTreeOn() contour.Update() normals = vtk.vtkPolyDataNormals() normals.SetInput(contour.GetOutput()) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(normals.GetOutput()) mapper.SetLookupTable(self.lut) mapper.SetScalarRange(self.vmin, self.vmax) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) actor.GetProperty().SetLineWidth(3) return actor
def LerSTL(self, path): mesh= vtk.vtkSTLReader() mesh.SetFileName(path) mesh.Update() #self.pd = mesh.GetOutput() self.polydata = mesh.GetOutput() normals = vtk.vtkPolyDataNormals() #normals.SetInput(polydata) normals.SetInputData(mesh.GetOutput()) normals.ComputeCellNormalsOn() normals.Update() #mudanças para aumentar a normal self.vertices =pontos(normals.GetOutput()) self.normalsp = get_normals(normals.GetOutput()) stlMapper = vtk.vtkPolyDataMapper() stlMapper.SetInputConnection(normals.GetOutputPort()) stlActor = vtk.vtkLODActor() stlActor.SetMapper(stlMapper) self.renderer.AddActor(stlActor) self.Interactor.Render()
def PlaneSphereActors(): ps = vtk.vtkPlaneSource() ps.SetXResolution(10) ps.SetYResolution(10) ss = vtk.vtkSphereSource() ss.SetRadius (0.3) group = vtk.vtkMultiBlockDataGroupFilter() group.AddInputConnection(ps.GetOutputPort()) group.AddInputConnection(ss.GetOutputPort()) ag = vtk.vtkRandomAttributeGenerator() ag.SetInputConnection(group.GetOutputPort()) ag.GenerateCellScalarsOn() ag.AttributesConstantPerBlockOn() n = vtk.vtkPolyDataNormals() n.SetInputConnection(ag.GetOutputPort()) n.Update (); actors = [] it = n.GetOutputDataObject(0).NewIterator() it.InitTraversal() while not it.IsDoneWithTraversal(): pm = vtk.vtkPolyDataMapper() pm.SetInputData(it.GetCurrentDataObject()) a = vtk.vtkActor() a.SetMapper(pm) actors.append (a) it.GoToNextItem() return actors
def __draw_sphere(self,radius,center,color,resolution=20): source = vtk.vtkSphereSource() source.SetCenter(*center) source.SetRadius(radius) source.SetPhiResolution(resolution) source.SetThetaResolution(resolution) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(source.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(normals.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) prop = actor.GetProperty() prop.SetColor(color) #prop.SetInterpolationToPhong() brightness = np.max(color) specular_color = np.array(color)/brightness prop.SetSpecularColor(specular_color) prop.SetSpecular(0.1) prop.SetDiffuse(1) prop.SetAmbient(0) info = vtk.vtkInformation() info.Set(vtk.vtkShadowMapBakerPass.RECEIVER(),0) info.Set(vtk.vtkShadowMapBakerPass.OCCLUDER(),0) actor.SetPropertyKeys(info) self.ren.AddActor(actor)
def extrude (pts, z, h): cell = vtk.vtkIdList() vtk_pts = vtk.vtkPoints() vtk_pts.SetDataTypeToDouble() [ (vtk_pts.InsertNextPoint(pt[0], pt[1], z), cell.InsertNextId(i)) for i, pt in enumerate(pts) ] pd = vtk.vtkPolyData() pd.Allocate(1, 1) pd.SetPoints(vtk_pts) pd.InsertNextCell(vtk.VTK_POLYGON, cell) prod = vtk.vtkTrivialProducer() prod.SetOutput(pd) extr = vtk.vtkLinearExtrusionFilter() extr.SetInputConnection(prod.GetOutputPort()) extr.SetVector(0, 0, h) pn = vtk.vtkPolyDataNormals() pn.SetInputConnection(extr.GetOutputPort()) pn.AutoOrientNormalsOn() return pn
def wrapOpImp(self): consistenNormal = vtk.vtkPolyDataNormals(); consistenNormal.AutoOrientNormalsOn(); consistenNormal.SplittingOff(); consistenNormal.SetInputData(self.data); consistenNormal.Update(); result= consistenNormal.GetOutput(); return result;
def cellnormals(surface): """Add cell normals.""" normals = vtk.vtkPolyDataNormals() normals.SetInput(surface) normals.ComputePointNormalsOff() normals.ComputeCellNormalsOn() normals.Update() return normals.GetOutput()
def Compute_Normals(vtkmesh): normfilter=vtk.vtkPolyDataNormals() normfilter.SetInputData(vtkmesh) normfilter.ComputePointNormalsOn() normfilter.ComputeCellNormalsOff normfilter.SplittingOff() normfilter.Update() return normfilter.GetOutput()
def pointnormals(surface, flipnormals=False): """Add point normals.""" normals = vtk.vtkPolyDataNormals() normals.SetInput(surface) normals.AutoOrientNormalsOn() normals.SplittingOff() normals.SetFlipNormals(flipnormals) normals.Update() return normals.GetOutput()
def Execute(self): if self.Surface == None: self.PrintError('Error: No Surface.') if self.ReferenceSurface == None: self.PrintError('Error: No ReferenceSurface.') ## if (self.SignedDistanceArrayName != '') & (self.ReferenceSurface.GetPointData().GetNormals() == None): if (self.SignedDistanceArrayName != ''): normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInput(self.ReferenceSurface) normalsFilter.AutoOrientNormalsOn() normalsFilter.ConsistencyOn() normalsFilter.SplittingOff() normalsFilter.SetFlipNormals(self.FlipNormals) normalsFilter.Update() self.ReferenceSurface.GetPointData().SetNormals(normalsFilter.GetOutput().GetPointData().GetNormals()) self.PrintLog('Computing ICP transform.') icpTransform = vtkvmtk.vtkvmtkIterativeClosestPointTransform() icpTransform.SetSource(self.Surface) icpTransform.SetTarget(self.ReferenceSurface) icpTransform.GetLandmarkTransform().SetModeToRigidBody() icpTransform.StartByMatchingCentroidsOn() icpTransform.CheckMeanDistanceOn() icpTransform.SetMaximumNumberOfLandmarks(self.MaximumNumberOfLandmarks) icpTransform.SetMaximumNumberOfIterations(self.MaximumNumberOfIterations) icpTransform.SetMaximumMeanDistance(self.MaximumMeanDistance) if self.FarThreshold > 0.0: icpTransform.UseFarThresholdOn() icpTransform.SetFarThreshold(self.FarThreshold) else: icpTransform.UseFarThresholdOff() transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInput(self.Surface) transformFilter.SetTransform(icpTransform) transformFilter.Update() self.PrintLog('Mean distance: '+str(icpTransform.GetMeanDistance())) self.Surface = transformFilter.GetOutput() self.Matrix4x4 = icpTransform.GetMatrix() if (self.DistanceArrayName != '') | (self.SignedDistanceArrayName != ''): self.PrintLog('Computing distance.') surfaceDistance = vtkvmtk.vtkvmtkSurfaceDistance() surfaceDistance.SetInput(self.Surface) surfaceDistance.SetReferenceSurface(self.ReferenceSurface) if (self.DistanceArrayName != ''): surfaceDistance.SetDistanceArrayName(self.DistanceArrayName) if (self.SignedDistanceArrayName != ''): surfaceDistance.SetSignedDistanceArrayName(self.SignedDistanceArrayName) surfaceDistance.Update() self.Surface = surfaceDistance.GetOutput()
def test_contours(self): cell = vtk.vtkUnstructuredGrid() cell.ShallowCopy(self.Cell) np = self.Cell.GetNumberOfPoints() ncomb = pow(2, np) scalar = vtk.vtkDoubleArray() scalar.SetName("scalar") scalar.SetNumberOfTuples(np) cell.GetPointData().SetScalars(scalar) incorrectCases = [] for i in range(1,ncomb-1): c = Combination(np, i) for p in range(np): scalar.SetTuple1(p, c[p]) gradientFilter = vtk.vtkGradientFilter() gradientFilter.SetInputData(cell) gradientFilter.SetInputArrayToProcess(0,0,0,0,'scalar') gradientFilter.SetResultArrayName('grad') gradientFilter.Update() contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(gradientFilter.GetOutputPort()) contourFilter.SetNumberOfContours(1) contourFilter.SetValue(0, 0.5) contourFilter.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputConnection(contourFilter.GetOutputPort()) normalsFilter.SetConsistency(0) normalsFilter.SetFlipNormals(0) normalsFilter.SetSplitting(0) calcFilter = vtk.vtkArrayCalculator() calcFilter.SetInputConnection(normalsFilter.GetOutputPort()) calcFilter.SetAttributeTypeToPointData() calcFilter.AddVectorArrayName('grad') calcFilter.AddVectorArrayName('Normals') calcFilter.SetResultArrayName('dir') calcFilter.SetFunction('grad.Normals') calcFilter.Update() out = vtk.vtkUnstructuredGrid() out.ShallowCopy(calcFilter.GetOutput()) numPts = out.GetNumberOfPoints() if numPts > 0: dirArray = out.GetPointData().GetArray('dir') for p in range(numPts): if(dirArray.GetTuple1(p) > 0.0): # all normals are reversed incorrectCases.append(i) break self.assertEquals(','.join([str(i) for i in incorrectCases]), '')
def get_actor(vtk_source, color=color_diffuse, opacity=1.0, has_scalar_visibility=False, has_decimator=False): """ Set `scalar_visibility` be `True` makes `color` unavailable. :return: a vtkActor """ if has_decimator: # Reduce the number of triangles decimator = vtk.vtkDecimatePro() decimator.SetInputConnection(vtk_source.GetOutputPort()) # decimator.SetInputData(vtk_source) decimator.SetFeatureAngle(60) decimator.MaximumIterations = 1 decimator.PreserveTopologyOn() decimator.SetMaximumError(0.0002) decimator.SetTargetReduction(1) decimator.SetErrorIsAbsolute(1) decimator.SetAbsoluteError(0.0002) decimator.ReleaseDataFlagOn() # Generate Normals normals = vtk.vtkPolyDataNormals() if has_decimator: normals.SetInputConnection(decimator.GetOutputPort()) else: normals.SetInputConnection(vtk_source.GetOutputPort()) normals.SetFeatureAngle(60.0) normals.ReleaseDataFlagOn() stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) stripper.ReleaseDataFlagOn() mapper = vtk.vtkPolyDataMapper() # mapper.SetInputConnection(vtk_source.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) mapper.SetScalarVisibility(has_scalar_visibility) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(color) actor.GetProperty().SetSpecular(0.3) actor.GetProperty().SetSpecularPower(20) actor.GetProperty().SetInterpolation(2) # actor.GetProperty().SetRepresentation(2) # actor.GetProperty().SetEdgeVisibility(True) # actor.GetProperty().SetOpacity(opacity) if opacity < 1.0: if is_depth_peeling_supported(render_window, renderer, True): setup_evn_for_depth_peeling(render_window, renderer, max_peels, occlusion) actor.GetProperty().SetOpacity(opacity) else: print "Depth Peeling is not supported." return actor
def NotUsed (__vtk__temp0=0,__vtk__temp1=0): # This filter actually spoils the example because it asks for the whole input. # The only reason it is here is because sphere complains it cannot generate ghost cells. vtkExtractPolyDataPiece.piece() piece.SetInputConnection(sphere.GetOutputPort()) # purposely put seams in here. piece.CreateGhostCellsOff() # purposely put seams in here. pdn = vtk.vtkPolyDataNormals() pdn.SetInputConnection(piece.GetOutputPort())
def applyFilters(self, state): surface = None surface = state.inputModelNode.GetPolyDataConnection() if state.decimation: triangle = vtk.vtkTriangleFilter() triangle.SetInputConnection(surface) decimation = vtk.vtkDecimatePro() decimation.SetTargetReduction(state.reduction) decimation.SetBoundaryVertexDeletion(state.boundaryDeletion) decimation.PreserveTopologyOn() decimation.SetInputConnection(triangle.GetOutputPort()) surface = decimation.GetOutputPort() if state.smoothing: if state.smoothingMethod == "Laplace": smoothing = vtk.vtkSmoothPolyDataFilter() smoothing.SetBoundarySmoothing(state.boundarySmoothing) smoothing.SetNumberOfIterations(state.laplaceIterations) smoothing.SetRelaxationFactor(state.laplaceRelaxation) smoothing.SetInputConnection(surface) surface = smoothing.GetOutputPort() elif state.smoothingMethod == "Taubin": smoothing = vtk.vtkWindowedSincPolyDataFilter() smoothing.SetBoundarySmoothing(state.boundarySmoothing) smoothing.SetNumberOfIterations(state.taubinIterations) smoothing.SetPassBand(state.taubinPassBand) smoothing.SetInputConnection(surface) surface = smoothing.GetOutputPort() if state.normals: normals = vtk.vtkPolyDataNormals() normals.AutoOrientNormalsOn() normals.SetFlipNormals(state.flipNormals) normals.SetSplitting(state.splitting) normals.SetFeatureAngle(state.featureAngle) normals.ConsistencyOn() normals.SetInputConnection(surface) surface = normals.GetOutputPort() if state.cleaner: cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(surface) surface = cleaner.GetOutputPort() if state.connectivity: connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetExtractionModeToLargestRegion() connectivity.SetInputConnection(surface) surface = connectivity.GetOutputPort() state.outputModelNode.SetPolyDataConnection(surface) return True
def render_brainVolume(reader): # Create the renderer, the render window, and the interactor. The # renderer draws into the render window, the interactor enables mouse- # and keyboard-based interaction with the scene. aRenderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aRenderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # An isosurface, or contour value of 500 is known to correspond to the # brain of the patient. Once generated, a vtkPolyDataNormals filter is # is used to create normals for smooth surface shading during rendering. # The triangle stripper is used to create triangle strips from the # isosurface these render much faster on may systems. brainExtractor = vtk.vtkContourFilter() brainExtractor.SetInputConnection(reader.GetOutputPort()) brainExtractor.SetValue(1, 100) # Helper link : # http://www.programcreek.com/python/example/11893/vtk.vtkContourFilter # example 3 # set disc decibrain = vtk.vtkDecimatePro() decibrain.SetInputConnection(brainExtractor.GetOutputPort()) decibrain.SetTargetReduction(.1) decibrain.PreserveTopologyOn() # Use a filter to smooth the data (will add triangles and smooth) smoother = vtk.vtkSmoothPolyDataFilter() smoother.SetInputConnection(decibrain.GetOutputPort()) smoother.SetNumberOfIterations(100) smoother.SetFeatureAngle(90.0) smoother.SetRelaxationFactor(.7) # Set Normals brainNormals = vtk.vtkPolyDataNormals() brainNormals.SetInputConnection(smoother.GetOutputPort()) brainNormals.SetFeatureAngle(180.0) #set stripper brainStripper = vtk.vtkStripper() brainStripper.SetInputConnection(brainNormals.GetOutputPort()) # Create a mapper and actor for smoothed dataset brainMapper = vtk.vtkPolyDataMapper() brainMapper.SetInputConnection(brainStripper.GetOutputPort()) brainMapper.ScalarVisibilityOff() # set actor brain = vtk.vtkActor() brain.SetMapper(brainMapper) brain.GetProperty().SetDiffuseColor(.9, .5, .1) brain.GetProperty().SetSpecular(5) brain.GetProperty().SetSpecularPower(60) brain.GetProperty().SetOpacity(0.1) # An isosurface, or contour value of 1150 is known to correspond to the # brain of the patient. Once generated, a vtkPolyDataNormals filter is # is used to create normals for smooth surface shading during rendering. # The triangle stripper is used to create triangle strips from the # isosurface these render much faster on may systems. tumorExtractor = vtk.vtkContourFilter() tumorExtractor.SetInputConnection(reader.GetOutputPort()) tumorExtractor.SetValue(0, 0) # Use a filter to smooth the data (will add triangles and smooth) #smootherTumor = vtk.vtkSmoothPolyDataFilter() #smootherTumor.SetInputConnection(tumorExtractor.GetOutputPort()) #smootherTumor.SetNumberOfIterations(100) #smootherTumor.SetFeatureAngle(60.0) #smootherTumor.SetRelaxationFactor(.5) ## set Normals #tumorNormals = vtk.vtkPolyDataNormals() #tumorNormals.SetInputConnection(smootherTumor.GetOutputPort()) #tumorNormals.SetFeatureAngle(160.0) #tumorStripper = vtk.vtkStripper() #tumorStripper.SetInputConnection(tumorNormals.GetOutputPort()) #tumorMapper = vtk.vtkPolyDataMapper() #tumorMapper.SetInputConnection(tumorStripper.GetOutputPort()) #tumorMapper.ScalarVisibilityOff() #tumor = vtk.vtkActor() #tumor.SetMapper(tumorMapper) #tumor.GetProperty().SetDiffuseColor(.2, 0, .8) #tumor.GetProperty().SetSpecular(5) #tumor.GetProperty().SetSpecularPower(60) #tumor.GetProperty().SetOpacity(0.5) # An outline provides context around the data. outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(reader.GetOutputPort()) mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outlineData.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(mapOutline) outline.GetProperty().SetColor(0, 0, 0) # It is convenient to create an initial view of the data. The FocalPoint # and Position form a vector direction. Later on (ResetCamera() method) # this vector is used to position the camera to look at the data in # this direction. aCamera = vtk.vtkCamera() aCamera.SetViewUp(0, 0, -1) aCamera.SetPosition(0, 1, 0) aCamera.SetFocalPoint(0, 0, 0) aCamera.ComputeViewPlaneNormal() # Actors are added to the renderer. An initial camera view is created. # The Dolly() method moves the camera towards the FocalPoint, # thereby enlarging the image. aRenderer.AddActor(outline) aRenderer.AddActor(brain) #aRenderer.AddActor(tumor) aRenderer.SetActiveCamera(aCamera) aRenderer.ResetCamera() aCamera.Dolly(1.5) # Set a background color for the renderer and set the size of the # render window (expressed in pixels). aRenderer.SetBackground(1, 1, 1) renWin.SetSize(640, 480) # Note that when camera movement occurs (as it does in the Dolly() # method), the clipping planes often need adjusting. Clipping planes # consist of two planes: near and far along the view direction. The # near plane clips out objects in front of the plane the far plane # clips out objects behind the plane. This way only what is drawn # between the planes is actually rendered. aRenderer.ResetCameraClippingRange() # Interact with the data. iren.Initialize() renWin.Render() iren.Start()
def project_wss_derivative(du=0.001, velocity_file=None, stlfile='c0006.stl', output_fn='surface.vtp', velocity_name='v [m/s]', write=False, mu=1.0, move_mesh=False, sign=1): ''' Equidistant points from stl in normal direction Takes stl and vtu/vti and generates vtp ''' if type(stlfile) is str: stl = read_vtk(stlfile) else: stl = stlfile vertices = numpy_support.vtk_to_numpy(stl.GetPoints().GetData()) indices = numpy_support.vtk_to_numpy(stl.GetPolys().GetData()).reshape( -1, 4)[:, 1:4] merged = vtk.vtkPolyData() merged.DeepCopy(stl) vel_data = read_vtk(velocity_file) #vfm = getFileReaderOutput(fvmfile) # Compute normals to vertices normalGenerator = vtk.vtkPolyDataNormals() normalGenerator.SetInputData(merged) normalGenerator.ComputePointNormalsOn() normalGenerator.ComputeCellNormalsOff() normalGenerator.SetSplitting(0) normalGenerator.SetConsistency(0) normalGenerator.Update() merged = normalGenerator.GetOutput() normals = numpy_support.vtk_to_numpy(merged.GetPointData().GetNormals()) # WSS - LBM points = vtk.vtkPoints() pointsPolyData = vtk.vtkPolyData() for normal, pos in zip(normals, vertices): points.InsertNextPoint(pos + normal * (-du * sign)) pointsPolyData.SetPoints(points) probe_filter = vtk.vtkProbeFilter() probe_filter.SetInputData(pointsPolyData) probe_filter.SetSourceData(vel_data) probe_filter.GetOutputPort() probe_filter.Update() probed_data = probe_filter.GetOutput().GetPointData() if isinstance(velocity_name, str): v_vec = numpy_support.vtk_to_numpy(probed_data.GetArray(velocity_name)) elif isinstance(velocity_name, list): vx = numpy_support.vtk_to_numpy(probed_data.GetArray(velocity_name[0])) vy = numpy_support.vtk_to_numpy(probed_data.GetArray(velocity_name[1])) vz = numpy_support.vtk_to_numpy(probed_data.GetArray(velocity_name[2])) v_vec = np.stack((vx, vy, vz), 1).reshape((-1, 3)) else: raise NotImplementedError stress_norm = vtk.vtkFloatArray() stress_norm.SetNumberOfComponents(1) stress_norm.SetName("wss_n") for v in v_vec: s = mu * v / du if np.max(s) > 1e35 or np.min(s) < -1e35: s = np.array([np.nan]) stress_norm.InsertNextTypedTuple([np.linalg.norm(s)]) merged.GetPointData().AddArray(stress_norm) velocity = vtk.vtkFloatArray() velocity.SetNumberOfComponents(3) velocity.SetName("velocity_at_epsilon") for v in v_vec: if np.max(v) > 1e33 or np.min(v) < -1e33: s = np.array(3 * [0.001]) velocity.InsertNextTypedTuple(v) merged.GetPointData().AddArray(velocity) if move_mesh: merged.SetPoints(points) print('moving point by dx inside') merged.Modified() if write: writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(output_fn) writer.SetInputData(merged) writer.Write() print(output_fn, " written") return merged
def contours(img,spacing=[1.0,1.0,1.0],contours=[]): importer = numpy2VTK(img,spacing) if len(contours) == 0: contours = [[img.max(),1.0,1.0,1.0,1.0]] actors = [] for c in contours: contourExtractor = vtk.vtkContourFilter() contourExtractor.SetInputConnection(importer.GetOutputPort()) contourExtractor.SetValue(0, c[0]) # contourNormals = vtk.vtkPolyDataNormals() # contourNormals.SetInputConnection(contourExtractor.GetOutputPort()) # contourNormals.SetFeatureAngle(60.0) # contourStripper = vtk.vtkStripper() # contourStripper.SetInputConnection(contourNormals.GetOutputPort()) deci = vtk.vtkDecimatePro() deci.SetInputConnection(contourExtractor.GetOutputPort()) deci.SetTargetReduction(0.99) deci.PreserveTopologyOn () # smoother = vtk.vtkSmoothPolyDataFilter() # smoother.SetInputConnection(deci.GetOutputPort()) # smoother.SetNumberOfIterations(50) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(deci.GetOutputPort()) normals.FlipNormalsOn() # smoothFilter = vtk.vtkSmoothPolyDataFilter() # smoothFilter.SetInputConnection(contourStripper.GetOutputPort()) # smoothFilter.SetNumberOfIterations(50) # smoothFilter.Update() contourMapper = vtk.vtkPolyDataMapper() # contourMapper.SetInputConnection(contourStripper.GetOutputPort()) contourMapper.SetInputConnection(normals.GetOutputPort()) contourMapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper( contourMapper) actor.GetProperty().SetColor(c[1],c[2],c[3]) actor.GetProperty().SetOpacity(c[4]) actor.GetProperty().SetRepresentationToSurface() # # An outline provides context around the data. # outlineData = vtk.vtkOutlineFilter() # outlineData.SetInputConnection(v16.GetOutputPort()) # mapOutline = vtk.vtkPolyDataMapper() # mapOutline.SetInputConnection(outlineData.GetOutputPort()) # outline = vtk.vtkActor() # outline.SetMapper(mapOutline) # outline.GetProperty().SetColor(0, 0, 0) actors.append(actor) return actors
def join_process_surface(filenames, algorithm, smooth_iterations, smooth_relaxation_factor, decimate_reduction, keep_largest, fill_holes, options, msg_queue): def send_message(msg): try: msg_queue.put_nowait(msg) except queue.Full as e: print(e) send_message('Joining surfaces ...') polydata_append = vtk.vtkAppendPolyData() for f in filenames: reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(f) reader.Update() polydata = reader.GetOutput() polydata_append.AddInputData(polydata) del reader del polydata polydata_append.Update() # polydata_append.GetOutput().ReleaseDataFlagOn() polydata = polydata_append.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del polydata_append send_message('Cleaning surface ...') clean = vtk.vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() clean_ref = weakref.ref(clean) # clean_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) clean.PointMergingOn() clean.Update() del polydata polydata = clean.GetOutput() # polydata.SetSource(None) del clean if algorithm == 'ca_smoothing': send_message('Calculating normals ...') normals = vtk.vtkPolyDataNormals() normals_ref = weakref.ref(normals) # normals_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) # normals.ReleaseDataFlagOn() #normals.SetFeatureAngle(80) #normals.AutoOrientNormalsOn() normals.ComputeCellNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() # polydata.SetSource(None) del normals clean = vtk.vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() clean_ref = weakref.ref(clean) # clean_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) clean.PointMergingOn() clean.Update() del polydata polydata = clean.GetOutput() # polydata.SetSource(None) del clean # try: # polydata.BuildLinks() # except TypeError: # polydata.BuildLinks(0) # polydata = ca_smoothing.ca_smoothing(polydata, options['angle'], # options['max distance'], # options['min weight'], # options['steps']) send_message('Context Aware smoothing ...') mesh = cy_mesh.Mesh(polydata) cy_mesh.ca_smoothing(mesh, options['angle'], options['max distance'], options['min weight'], options['steps']) # polydata = mesh.to_vtk() # polydata.SetSource(None) # polydata.DebugOn() else: #smoother = vtk.vtkWindowedSincPolyDataFilter() send_message('Smoothing ...') smoother = vtk.vtkSmoothPolyDataFilter() smoother_ref = weakref.ref(smoother) # smoother_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(smoother_ref(), _("Creating 3D surface..."))) smoother.SetInputData(polydata) smoother.SetNumberOfIterations(smooth_iterations) smoother.SetRelaxationFactor(smooth_relaxation_factor) smoother.SetFeatureAngle(80) #smoother.SetEdgeAngle(90.0) #smoother.SetPassBand(0.1) smoother.BoundarySmoothingOn() smoother.FeatureEdgeSmoothingOn() #smoother.NormalizeCoordinatesOn() #smoother.NonManifoldSmoothingOn() # smoother.ReleaseDataFlagOn() # smoother.GetOutput().ReleaseDataFlagOn() smoother.Update() del polydata polydata = smoother.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del smoother if decimate_reduction: print("Decimating", decimate_reduction) send_message('Decimating ...') decimation = vtk.vtkQuadricDecimation() # decimation.ReleaseDataFlagOn() decimation.SetInputData(polydata) decimation.SetTargetReduction(decimate_reduction) decimation_ref = weakref.ref(decimation) # decimation_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(decimation_ref(), _("Creating 3D surface..."))) #decimation.PreserveTopologyOn() #decimation.SplittingOff() #decimation.BoundaryVertexDeletionOff() # decimation.GetOutput().ReleaseDataFlagOn() decimation.Update() del polydata polydata = decimation.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del decimation #to_measure.Register(None) # to_measure.SetSource(None) if keep_largest: send_message('Finding the largest ...') conn = vtk.vtkPolyDataConnectivityFilter() conn.SetInputData(polydata) conn.SetExtractionModeToLargestRegion() conn_ref = weakref.ref(conn) # conn_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(conn_ref(), _("Creating 3D surface..."))) conn.Update() # conn.GetOutput().ReleaseDataFlagOn() del polydata polydata = conn.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del conn #Filter used to detect and fill holes. Only fill boundary edges holes. #TODO: Hey! This piece of code is the same from #polydata_utils.FillSurfaceHole, we need to review this. if fill_holes: send_message('Filling holes ...') filled_polydata = vtk.vtkFillHolesFilter() # filled_polydata.ReleaseDataFlagOn() filled_polydata.SetInputData(polydata) filled_polydata.SetHoleSize(300) filled_polydata_ref = weakref.ref(filled_polydata) # filled_polydata_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(filled_polydata_ref(), _("Creating 3D surface..."))) filled_polydata.Update() # filled_polydata.GetOutput().ReleaseDataFlagOn() del polydata polydata = filled_polydata.GetOutput() #polydata.Register(None) # polydata.SetSource(None) # polydata.DebugOn() del filled_polydata to_measure = polydata normals = vtk.vtkPolyDataNormals() # normals.ReleaseDataFlagOn() # normals_ref = weakref.ref(normals) # normals_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) # normals.SetFeatureAngle(80) # normals.SplittingOff() # normals.AutoOrientNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del normals # Improve performance stripper = vtk.vtkStripper() # stripper.ReleaseDataFlagOn() # stripper_ref = weakref.ref(stripper) # stripper_ref().AddObserver("ProgressEvent", lambda obj,evt: # UpdateProgress(stripper_ref(), _("Creating 3D surface..."))) stripper.SetInputData(polydata) stripper.PassThroughCellIdsOn() stripper.PassThroughPointIdsOn() # stripper.GetOutput().ReleaseDataFlagOn() stripper.Update() del polydata polydata = stripper.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del stripper send_message('Calculating area and volume ...') measured_polydata = vtk.vtkMassProperties() measured_polydata.SetInputData(to_measure) measured_polydata.Update() volume = float(measured_polydata.GetVolume()) area = float(measured_polydata.GetSurfaceArea()) del measured_polydata filename = tempfile.mktemp(suffix='_full.vtp') writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(polydata) writer.SetFileName(filename) writer.Write() del writer print("MY PID", os.getpid()) return filename, {'volume': volume, 'area': area}
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.SetInputData(self.Mesh) extractSurface.Update() normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputConnection( extractSurface.GetOutputPort()) 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)
def init_cell_field_actors_borderless(self, actor_specs, drawing_params=None): hex_flag = False lattice_type_str = self.get_lattice_type_str() if lattice_type_str.lower() == 'hexagonal': hex_flag = True # todo 5 - check if this should be called earlier # self.extractCellFieldData() # initializes self.usedCellTypesList field_dim = self.currentDrawingParameters.bsd.fieldDim cell_type_image_data = vtk.vtkImageData() cell_type_image_data.SetDimensions( field_dim.x + 2, field_dim.y + 2, field_dim.z + 2 ) # adding 1 pixel border around the lattice to make rendering smooth at lattice borders cell_type_image_data.GetPointData().SetScalars(self.cell_type_array) voi = vtk.vtkExtractVOI() if VTK_MAJOR_VERSION >= 6: voi.SetInputData(cell_type_image_data) else: voi.SetInput(cell_type_image_data) # voi.SetVOI(1,self.dim[0]-1, 1,self.dim[1]-1, 1,self.dim[2]-1 ) # crop out the artificial boundary layer that we created voi.SetVOI(0, 249, 0, 189, 0, 170) # # todo 5- check if it is possible to call it once # self.usedCellTypesList = self.extractCellFieldData() number_of_actors = len(self.used_cell_types_list) # creating and initializing filters, smoothers and mappers - one for each cell type filterList = [ vtk.vtkDiscreteMarchingCubes() for i in range(number_of_actors) ] smootherList = [ vtk.vtkSmoothPolyDataFilter() for i in range(number_of_actors) ] normalsList = [ vtk.vtkPolyDataNormals() for i in range(number_of_actors) ] mapperList = [vtk.vtkPolyDataMapper() for i in range(number_of_actors)] # actorCounter=0 # for i in usedCellTypesList: for actorCounter, actor_number in enumerate(self.used_cell_types_list): # for actorCounter in xrange(len(self.usedCellTypesList)): if VTK_MAJOR_VERSION >= 6: filterList[actorCounter].SetInputData(cell_type_image_data) else: filterList[actorCounter].SetInput(cell_type_image_data) # filterList[actorCounter].SetInputConnection(voi.GetOutputPort()) # filterList[actorCounter].SetValue(0, usedCellTypesList[actorCounter]) filterList[actorCounter].SetValue( 0, self.used_cell_types_list[actorCounter]) smootherList[actorCounter].SetInputConnection( filterList[actorCounter].GetOutputPort()) # smootherList[actorCounter].SetNumberOfIterations(200) normalsList[actorCounter].SetInputConnection( smootherList[actorCounter].GetOutputPort()) normalsList[actorCounter].SetFeatureAngle(45.0) mapperList[actorCounter].SetInputConnection( normalsList[actorCounter].GetOutputPort()) mapperList[actorCounter].ScalarVisibilityOff() actors_dict = actor_specs.actors_dict cell_type_lut = self.get_type_lookup_table() cell_type_lut_max = cell_type_lut.GetNumberOfTableValues() - 1 if actor_number in list(actors_dict.keys()): actor = actors_dict[actor_number] actor.SetMapper(mapperList[actorCounter]) actor.GetProperty().SetDiffuseColor( cell_type_lut.GetTableValue( self.used_cell_types_list[actorCounter])[0:3]) # actor.GetProperty().SetDiffuseColor( # # self.celltypeLUT.GetTableValue(self.usedCellTypesList[actorCounter])[0:3]) # self.celltypeLUT.GetTableValue(actor_number)[0:3]) if hex_flag: actor.SetScale(self.xScaleHex, self.yScaleHex, self.zScaleHex)
def __init__(self, modelNode, imageSize=None, orientation=None, zoom=None, showFeatureEdges=False): # rollPitchYawDeg orientation = [0, 0, 0] if orientation is None else orientation zoom = 1.0 if zoom is None else zoom imageSize = [300, 300] if imageSize is None else imageSize showFeatureEdges = showFeatureEdges modelPolyData = modelNode.GetPolyData() renderer = vtk.vtkRenderer() renderer.SetBackground(1, 1, 1) renderer.SetUseDepthPeeling(1) renderer.SetMaximumNumberOfPeels(100) renderer.SetOcclusionRatio(0.1) renWin = vtk.vtkRenderWindow() renWin.OffScreenRenderingOn() renWin.SetSize(imageSize[0], imageSize[1]) renWin.SetAlphaBitPlanes(1) # for depth peeling renWin.SetMultiSamples(0) # for depth peeling renWin.AddRenderer(renderer) # Must be called after iren and renderer are linked or there will be problems renderer.Render() modelNormals = vtk.vtkPolyDataNormals() modelNormals.SetInputData(modelPolyData) modelMapper = vtk.vtkPolyDataMapper() modelMapper.SetInputConnection(modelNormals.GetOutputPort()) modelActor = vtk.vtkActor() modelActor.SetMapper(modelMapper) modelActor.GetProperty().SetColor(0.9, 0.9, 0.9) modelActor.GetProperty().SetOpacity(0.8) renderer.AddActor(modelActor) triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(modelNormals.GetOutputPort()) if showFeatureEdges: edgeExtractor = vtk.vtkFeatureEdges() edgeExtractor.SetInputConnection(triangleFilter.GetOutputPort()) edgeExtractor.ColoringOff() edgeExtractor.BoundaryEdgesOn() edgeExtractor.ManifoldEdgesOn() edgeExtractor.NonManifoldEdgesOn() modelEdgesMapper = vtk.vtkPolyDataMapper() modelEdgesMapper.SetInputConnection(edgeExtractor.GetOutputPort()) modelEdgesMapper.SetResolveCoincidentTopologyToPolygonOffset() modelEdgesActor = vtk.vtkActor() modelEdgesActor.SetMapper(modelEdgesMapper) modelEdgesActor.GetProperty().SetColor(0.0, 0.0, 0.0) renderer.AddActor(modelEdgesActor) # Set projection to parallel to enable estimate distances renderer.GetActiveCamera().ParallelProjectionOn() renderer.GetActiveCamera().Roll(orientation[0]) renderer.GetActiveCamera().Pitch(orientation[1]) renderer.GetActiveCamera().Yaw(orientation[2]) renderer.ResetCamera() renderer.GetActiveCamera().Zoom(zoom) windowToImageFilter = vtk.vtkWindowToImageFilter() windowToImageFilter.SetInput(renWin) windowToImageFilter.Update() screenshot = ctk.ctkVTKWidgetsUtils.vtkImageDataToQImage( windowToImageFilter.GetOutput()) bArray = qt.QByteArray() buffer = qt.QBuffer(bArray) buffer.open(qt.QIODevice.WriteOnly) screenshot.save(buffer, "PNG") self.dataValue = bArray.toBase64().data().decode() self.dataType = "image/png"
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) parison = vtk.vtkGeometryFilter() parison.SetInputConnection(connect2.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) cf = vtk.vtkContourFilter()
def applyFilters(self, state): surface = None surface = state.inputModelNode.GetPolyDataConnection() if state.decimation: triangle = vtk.vtkTriangleFilter() triangle.SetInputConnection(surface) decimation = vtk.vtkDecimatePro() decimation.SetTargetReduction(state.reduction) decimation.SetBoundaryVertexDeletion(state.boundaryDeletion) decimation.PreserveTopologyOn() decimation.SetInputConnection(triangle.GetOutputPort()) surface = decimation.GetOutputPort() if state.smoothing: if state.smoothingMethod == "Laplace": smoothing = vtk.vtkSmoothPolyDataFilter() smoothing.SetBoundarySmoothing(state.boundarySmoothing) smoothing.SetNumberOfIterations(state.laplaceIterations) smoothing.SetRelaxationFactor(state.laplaceRelaxation) smoothing.SetInputConnection(surface) surface = smoothing.GetOutputPort() elif state.smoothingMethod == "Taubin": smoothing = vtk.vtkWindowedSincPolyDataFilter() smoothing.SetBoundarySmoothing(state.boundarySmoothing) smoothing.SetNumberOfIterations(state.taubinIterations) smoothing.SetPassBand(state.taubinPassBand) smoothing.SetInputConnection(surface) surface = smoothing.GetOutputPort() if state.normals: normals = vtk.vtkPolyDataNormals() normals.SetAutoOrientNormals(state.autoOrientNormals) normals.SetFlipNormals(state.flipNormals) normals.SetSplitting(state.splitting) normals.SetFeatureAngle(state.featureAngle) normals.ConsistencyOn() normals.SetInputConnection(surface) surface = normals.GetOutputPort() if state.mirror: mirrorTransformMatrix = vtk.vtkMatrix4x4() mirrorTransformMatrix.SetElement(0, 0, -1 if state.mirrorX else 1) mirrorTransformMatrix.SetElement(1, 1, -1 if state.mirrorY else 1) mirrorTransformMatrix.SetElement(2, 2, -1 if state.mirrorZ else 1) mirrorTransform = vtk.vtkTransform() mirrorTransform.SetMatrix(mirrorTransformMatrix) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputConnection(surface) transformFilter.SetTransform(mirrorTransform) surface = transformFilter.GetOutputPort() if mirrorTransformMatrix.Determinant() < 0: reverse = vtk.vtkReverseSense() reverse.SetInputConnection(surface) surface = reverse.GetOutputPort() if state.cleaner: cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(surface) surface = cleaner.GetOutputPort() if state.fillHoles: fillHoles = vtk.vtkFillHolesFilter() fillHoles.SetHoleSize(state.fillHolesSize) fillHoles.SetInputConnection(surface) # Need to auto-orient normals, otherwise holes # could appear to be unfilled when only front-facing elements # are chosen to be visible. normals = vtk.vtkPolyDataNormals() normals.AutoOrientNormalsOn() normals.ConsistencyOn() normals.SetInputConnection(fillHoles.GetOutputPort()) surface = normals.GetOutputPort() if state.connectivity: connectivity = vtk.vtkPolyDataConnectivityFilter() connectivity.SetExtractionModeToLargestRegion() connectivity.SetInputConnection(surface) surface = connectivity.GetOutputPort() state.outputModelNode.SetPolyDataConnection(surface) return True
def fillCaps(self): # read the .obj and center it # polydata = Helpers.centerPolyData(Helpers.getObjData(modelFn)) # TODO: centering seems to glitch the tetgen somewhy polydata = Helpers.getObjData(modelFn) size = Helpers.getBounds(polydata) print "Model sizes:" + str(size) fillHolesFilter = vtk.vtkFillHolesFilter() fillHolesFilter.SetInputData(polydata) fillHolesFilter.SetHoleSize( 1000.0 ) # TODO: hole size: compute using model size (some factor of it) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(fillHolesFilter.GetOutputPort()) normals.ConsistencyOn() normals.SplittingOff() normals.Update() normals.GetOutput().GetPointData().SetNormals( polydata.GetPointData().GetNormals()) numOriginalCells = polydata.GetNumberOfCells() numNewCells = normals.GetOutput().GetNumberOfCells() it = normals.GetOutput().NewCellIterator() numCells = 0 it.InitTraversal() # Iterate over the original cells while (not it.IsDoneWithTraversal()) and numCells < numOriginalCells: it.GoToNextCell() numCells += 1 holePolyData = vtk.vtkPolyData() holePolyData.Allocate(normals.GetOutput(), numNewCells - numOriginalCells) holePolyData.SetPoints(normals.GetOutput().GetPoints()) cell = vtk.vtkGenericCell() # The remaining cells are the new ones from the hole filler while not it.IsDoneWithTraversal(): it.GetCell(cell) holePolyData.InsertNextCell(it.GetCellType(), cell.GetPointIds()) it.GoToNextCell() connectivity = vtk.vtkConnectivityFilter() connectivity.SetInputData(holePolyData) connectivity.SetExtractionModeToAllRegions() connectivity.ColorRegionsOn() connectivity.Update() capRegions = connectivity.GetOutput() outPD = vtk.vtkPolyData() outPD.Allocate(normals.GetOutput(), numNewCells) outPD.SetPoints(capRegions.GetPoints()) numOfCaps = connectivity.GetNumberOfExtractedRegions() print "Found " + str(numOfCaps) + " holes." # create the cap polydatas capPDs = [] for i in range(0, numOfCaps): capPD = vtk.vtkPolyData() capPD.Allocate(normals.GetOutput(), numNewCells) capPD.SetPoints(capRegions.GetPoints()) capPDs.append(capPD) capScalars = capRegions.GetCellData().GetScalars() cell = vtk.vtkGenericCell() it = capRegions.NewCellIterator() i = 0 while not it.IsDoneWithTraversal(): it.GetCell(cell) # outPD.InsertNextCell(it.GetCellType(), cell.GetPointIds()) capIdx = capScalars.GetValue(i) capPDs[capIdx].InsertNextCell(it.GetCellType(), cell.GetPointIds()) it.GoToNextCell() i = i + 1 sortedCaps = [] for i in range(0, len(capPDs)): capPD = capPDs[i] cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputData(capPD) cleanFilter.Update() cleanedPD = cleanFilter.GetOutput() area = Helpers.getArea(cleanedPD) radius = math.sqrt(area / math.pi) sortedCaps.append([cleanedPD, area, radius]) capPDs[i] = cleanedPD sortedCaps = sorted(sortedCaps, key=lambda x: x[1], reverse=True) [lastPd, area, radius] = sortedCaps[len(capPDs) - 1] print "Recommended edge size: " + str(radius / 2) scalarsName = "ModelFaceID" Helpers.appendScalars(polydata, 1, scalarsName) # 1 for the walls appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputData(outPD) appendFilter.AddInputData(polydata) scalarIdx = 2 for [capPD, area, radius] in sortedCaps: # if radius < 0.1: # Helpers.appendScalars(capPD, 1, scalarsName) # append the face ID idx # else: # Helpers.appendScalars(capPD, scalarIdx, scalarsName) # append the face ID idx Helpers.appendScalars(capPD, scalarIdx, scalarsName) # append the face ID idx appendFilter.AddInputData(capPD) print "Cap radius: " + str(radius) scalarIdx += 1 appendFilter.Update() cleanFilter = vtk.vtkCleanPolyData() cleanFilter.SetInputConnection(appendFilter.GetOutputPort()) cleanFilter.Update() joinedPD = cleanFilter.GetOutput() # joinedPD.GetCellData().SetScalars(scalars) # Write as VTP Helpers.writeVTP(meshFn, joinedPD) return [ polydata, [[capPD, radius] for [capPD, area, radius] in sortedCaps] ]
fileFormat = ofindFile("vtk/data/headsq/quarter.1") fileFormat = fileFormat.rstrip(".1") v16.SetFilePrefix(fileFormat) v16.SetImageRange(1, 93) v16.SetDataSpacing(3.2, 3.2, 1.5) # An isosurface, or contour value of 500 is known to correspond to the # skin of the patient. Once generated, a vtkPolyDataNormals filter is # is used to create normals for smooth surface shading during rendering. # The triangle stripper is used to create triangle strips from the # isosurface these render much faster on may systems. skinExtractor = vtk.vtkContourFilter() skinExtractor.SetInputConnection(v16.GetOutputPort()) skinExtractor.SetValue(0, 500) skinNormals = vtk.vtkPolyDataNormals() skinNormals.SetInputConnection(skinExtractor.GetOutputPort()) skinNormals.SetFeatureAngle(320.0) # An outline provides context around the data. outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(v16.GetOutputPort()) vtkNode = nodeCreate(nodeGetRoot()) mouse = interactorCreateMouse() interactorAttach(mouse, vtkNode) nodeSetPosition(vtkNode, (0, 0, -1)) queueInitializeView()
def __init__(self, interactor, renderer, mesh_filename, reg_filename): self.interactor = interactor self.renderer = renderer reader = vtk.vtkStructuredPointsReader() reader.SetFileName(mesh_filename) cf = vtk.vtkContourFilter() cf.SetInput(reader.GetOutput()) cf.SetValue(0, 1) deci = vtk.vtkDecimatePro() deci.SetInput(cf.GetOutput()) deci.SetTargetReduction(.1) deci.PreserveTopologyOn() smoother = vtk.vtkSmoothPolyDataFilter() smoother.SetInput(deci.GetOutput()) smoother.SetNumberOfIterations(100) normals = vtk.vtkPolyDataNormals() normals.SetInput(smoother.GetOutput()) normals.FlipNormalsOn() normals.SetFeatureAngle(60.0) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) lut = vtk.vtkLookupTable() lut.SetHueRange(0, 0) lut.SetSaturationRange(0, 0) lut.SetValueRange(0.2, 0.55) contourMapper = vtk.vtkPolyDataMapper() #contourMapper.SetInput(normals.GetOutput()) contourMapper.SetInput(stripper.GetOutput()) contourMapper.SetLookupTable(lut) self.contours = vtk.vtkActor() self.contours.SetMapper(contourMapper) #self.contours.GetProperty().SetRepresentationToWireframe() self.contours.GetProperty().SetRepresentationToSurface() #self.contours.GetProperty().SetInterpolationToGouraud() #self.contours.GetProperty().SetOpacity(1.0) #self.contours.GetProperty().SetAmbient(0.1) self.contours.GetProperty().SetDiffuse(0.1) #self.contours.GetProperty().SetSpecular(0.1) #self.contours.GetProperty().SetSpecularPower(0.1) # now setmatrix() on the actor from the reg file ! def array_to_vtkmatrix4x4(scipy_array): vtkmat = vtk.vtkMatrix4x4() for i in range(0, 4): for j in range(0, 4): vtkmat.SetElement(i, j, scipy_array[i, j]) return vtkmat mat = pickle.load(file(reg_filename, 'r')) vtkmat = array_to_vtkmatrix4x4(mat) self.contours.SetUserMatrix(vtkmat) #self.contours.GetProperty().SetOpacity(.38) #adjustable in the grid manager now # XXX YAH somehow get a callback when actor is moved... self.renderer.AddActor(self.contours)
def main(): colors = vtk.vtkNamedColors() ifn, index = get_program_parameters() # Prepare to read the file. readerVolume = vtk.vtkMetaImageReader() readerVolume.SetFileName(ifn) readerVolume.Update() # Extract the region of interest. voi = vtk.vtkExtractVOI() if vtk.VTK_MAJOR_VERSION <= 5: voi.SetInput(readerVolume.GetOutput()) else: voi.SetInputConnection(readerVolume.GetOutputPort()) voi.SetVOI(0, 517, 0, 228, 0, 392) voi.SetSampleRate(1, 1, 1) voi.Update() # Necessary for GetScalarRange(). srange = voi.GetOutput().GetScalarRange() # Needs Update() before! print("Range", srange) # Prepare surface generation. contour = vtk.vtkDiscreteMarchingCubes() # For label images. if vtk.VTK_MAJOR_VERSION <= 5: contour.SetInput(voi.GetOutput()) else: contour.SetInputConnection(voi.GetOutputPort()) # contour.ComputeNormalsOn() print("Doing label", index) contour.SetValue(0, index) contour.Update() # Needed for GetNumberOfPolys()!!! smoother = vtk.vtkWindowedSincPolyDataFilter() if vtk.VTK_MAJOR_VERSION <= 5: smoother.SetInput(contour.GetOutput()) else: smoother.SetInputConnection(contour.GetOutputPort()) smoother.SetNumberOfIterations(30) # This has little effect on the error! # smoother.BoundarySmoothingOff() # smoother.FeatureEdgeSmoothingOff() # smoother.SetFeatureAngle(120.0) # smoother.SetPassBand(.001) # This increases the error a lot! smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.GenerateErrorScalarsOn() # smoother.GenerateErrorVectorsOn() smoother.Update() smoothed_polys = smoother.GetOutput() smoother_error = smoothed_polys.GetPointData().GetScalars() # Find min and max z. se_range = smoother_error.GetRange() print("Smoother error range:", se_range) minz = se_range[0] # min(smoother_error) maxz = se_range[1] # max(smoother_error) if maxz > 1: print("Big smoother error: min/max:", minz, maxz) # minz = 0.3 # This way colours of different particles are comparable. # maxz = 1 minz = 0.3 maxz = 0.6 # Create the color map. colorLookupTable = vtk.vtkLookupTable() colorLookupTable.SetTableRange(minz, maxz) # This does nothing, use mapper.SetScalarRange(minz, maxz). colorLookupTable.SetHueRange(2 / 3.0, 1) # colorLookupTable.SetSaturationRange(0, 0) # colorLookupTable.SetValueRange(1, 0) # colorLookupTable.SetNumberOfColors(256) #256 default colorLookupTable.Build() # Calculate cell normals. triangleCellNormals = vtk.vtkPolyDataNormals() if vtk.VTK_MAJOR_VERSION <= 5: triangleCellNormals.SetInput(smoothed_polys) else: triangleCellNormals.SetInputData(smoothed_polys) triangleCellNormals.ComputeCellNormalsOn() triangleCellNormals.ComputePointNormalsOff() triangleCellNormals.ConsistencyOn() triangleCellNormals.AutoOrientNormalsOn() triangleCellNormals.Update() # Creates vtkPolyData. mapper = vtk.vtkPolyDataMapper() # mapper.SetInput(smoothed_polys) # This has no normals. if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(triangleCellNormals.GetOutput()) # This is better for vis;-) else: mapper.SetInputConnection(triangleCellNormals.GetOutputPort()) # this is better for vis;-) mapper.ScalarVisibilityOn() # Show colour. mapper.SetScalarRange(minz, maxz) # mapper.SetScalarModeToUseCellData() # Contains the label eg. 31 mapper.SetScalarModeToUsePointData() # The smoother error relates to the verts. mapper.SetLookupTable(colorLookupTable) # Take the isosurface data and create geometry. actor = vtk.vtkLODActor() actor.SetNumberOfCloudPoints(100000) actor.SetMapper(mapper) # Create the renderer. ren = vtk.vtkRenderer() ren.SetBackground(colors.GetColor3d("DimGray")) ren.AddActor(actor) # Create a window for the renderer of size 600X600 renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(600, 600) # Set a user interface interactor for the render window. iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Start the initialization and rendering. iren.Initialize() renWin.Render() ren.GetActiveCamera().SetPosition(268.628410, 128.452157, 24.517175) ren.GetActiveCamera().SetFocalPoint(256.006912, 175.949646, 24.175843) ren.GetActiveCamera().SetViewUp(0.844464, 0.227883, 0.484716) ren.ResetCameraClippingRange() renWin.Render() iren.Start()
def main(data_folder, slice_number): colors = vtk.vtkNamedColors() path = Path(data_folder) if path.is_dir(): s = '' fn_1 = path.joinpath('frog').with_suffix('.mhd') if not fn_1.is_file(): s += 'The file: {:s} does not exist.\n'.format(str(fn_1)) print(s) fn_2 = path.joinpath('frogtissue').with_suffix('.mhd') if not fn_2.is_file(): s += 'The file: {:s} does not exist.'.format(str(fn_2)) if s: print(s) return else: print('Expected a path to frog.mhs and frogtissue.mhd') return so = SliceOrder() # Now create the RenderWindow, Renderer and Interactor # ren1 = vtk.vtkRenderer() ren2 = vtk.vtkRenderer() ren3 = vtk.vtkRenderer() ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(ren1) ren_win.AddRenderer(ren2) ren_win.AddRenderer(ren3) ren_win.SetWindowName('FrogSlice') iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win) grey_reader = vtk.vtkMetaImageReader() grey_reader.SetFileName(str(fn_1)) grey_reader.Update() grey_padder = vtk.vtkImageConstantPad() grey_padder.SetInputConnection(grey_reader.GetOutputPort()) grey_padder.SetOutputWholeExtent(0, 511, 0, 511, slice_number, slice_number) grey_padder.SetConstant(0) grey_plane = vtk.vtkPlaneSource() grey_transform = vtk.vtkTransformPolyDataFilter() grey_transform.SetTransform(so.get('hfsi')) grey_transform.SetInputConnection(grey_plane.GetOutputPort()) grey_normals = vtk.vtkPolyDataNormals() grey_normals.SetInputConnection(grey_transform.GetOutputPort()) grey_normals.FlipNormalsOff() wllut = vtk.vtkWindowLevelLookupTable() wllut.SetWindow(255) wllut.SetLevel(128) wllut.SetTableRange(0, 255) wllut.Build() grey_mapper = vtk.vtkPolyDataMapper() grey_mapper.SetInputConnection(grey_plane.GetOutputPort()) grey_texture = vtk.vtkTexture() grey_texture.SetInputConnection(grey_padder.GetOutputPort()) grey_texture.SetLookupTable(wllut) grey_texture.SetColorModeToMapScalars() grey_texture.InterpolateOn() grey_actor = vtk.vtkActor() grey_actor.SetMapper(grey_mapper) grey_actor.SetTexture(grey_texture) segment_reader = vtk.vtkMetaImageReader() segment_reader.SetFileName(str(fn_2)) segment_reader.Update() segment_padder = vtk.vtkImageConstantPad() segment_padder.SetInputConnection(segment_reader.GetOutputPort()) segment_padder.SetOutputWholeExtent(0, 511, 0, 511, slice_number, slice_number) segment_padder.SetConstant(0) segment_plane = vtk.vtkPlaneSource() segment_transform = vtk.vtkTransformPolyDataFilter() segment_transform.SetTransform(so.get('hfsi')) segment_transform.SetInputConnection(segment_plane.GetOutputPort()) segment_normals = vtk.vtkPolyDataNormals() segment_normals.SetInputConnection(segment_transform.GetOutputPort()) segment_normals.FlipNormalsOn() lut = create_frog_lut(colors) segment_mapper = vtk.vtkPolyDataMapper() segment_mapper.SetInputConnection(segment_plane.GetOutputPort()) segment_texture = vtk.vtkTexture() segment_texture.SetInputConnection(segment_padder.GetOutputPort()) segment_texture.SetLookupTable(lut) segment_texture.SetColorModeToMapScalars() segment_texture.InterpolateOff() segment_actor = vtk.vtkActor() segment_actor.SetMapper(segment_mapper) segment_actor.SetTexture(segment_texture) segment_overlay_actor = vtk.vtkActor() segment_overlay_actor.SetMapper(segment_mapper) segment_overlay_actor.SetTexture(segment_texture) segment_overlay_actor.GetProperty().SetOpacity(.5) ren1.SetBackground(0, 0, 0) ren1.SetViewport(0, 0.5, 0.5, 1) ren_win.SetSize(640, 480) ren1.AddActor(grey_actor) ren2.SetBackground(0, 0, 0) ren2.SetViewport(0.5, 0.5, 1, 1) ren2.AddActor(segment_actor) cam1 = vtk.vtkCamera() cam1.SetViewUp(0, -1, 0) cam1.SetPosition(0, 0, -1) ren1.SetActiveCamera(cam1) ren1.ResetCamera() cam1.SetViewUp(0, -1, 0) cam1.SetPosition(0.0554068, -0.0596001, -0.491383) cam1.SetFocalPoint(0.0554068, -0.0596001, 0) ren1.ResetCameraClippingRange() ren3.AddActor(grey_actor) ren3.AddActor(segment_overlay_actor) segment_overlay_actor.SetPosition(0, 0, -0.01) ren1.SetBackground(colors.GetColor3d('SlateGray')) ren2.SetBackground(colors.GetColor3d('SlateGray')) ren3.SetBackground(colors.GetColor3d('SlateGray')) ren3.SetViewport(0, 0, 1, 0.5) ren2.SetActiveCamera(ren1.GetActiveCamera()) ren3.SetActiveCamera(ren1.GetActiveCamera()) ren_win.Render() iren.Start()
import vtk import math import random from scipy.spatial import Delaunay import numpy as np from fury import utils, window from vtk.util import numpy_support scene = window.Scene() reader = vtk.vtkPLYReader() reader.SetFileName("horse.ply") norms = vtk.vtkPolyDataNormals() norms.SetInputConnection(reader.GetOutputPort()) texture = vtk.vtkTexture() texture.CubeMapOn() files = [ "skybox-px.jpg", "skybox-nx.jpg", "skybox-py.jpg", "skybox-ny.jpg", "skybox-pz.jpg", "skybox-nz.jpg" ] # files = ["wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg"] for i in range(6): imgReader = vtk.vtkJPEGReader() imgReader.SetFileName(files[i]) flip = vtk.vtkImageFlip() flip.SetInputConnection(imgReader.GetOutputPort())
def main(): fileName1, fileName2 = get_program_parameters() colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor('BkgColor', [65, 99, 149, 255]) # Read a vtk file # pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName(fileName1) pl3d.SetQFileName(fileName2) pl3d.SetScalarFunctionNumber(100) # Density pl3d.SetVectorFunctionNumber(202) # Momentum pl3d.Update() pl3dOutput = pl3d.GetOutput().GetBlock(0) # What do we know about the data? # Get the extent of the data: imin,imax, jmin,jmax, kmin,kmax extent = pl3dOutput.GetExtent() scalarRange = pl3dOutput.GetScalarRange() # Planes are specified using a imin,imax, jmin,jmax, kmin,kmax coordinate # specification. Min and max i,j,k values are clamped to 0 and maximum value. # See the variable named extent for the values. # plane = vtk.vtkStructuredGridGeometryFilter() plane.SetInputData(pl3dOutput) plane.SetExtent(10, 10, 1, extent[3], 1, extent[5]) plane2 = vtk.vtkStructuredGridGeometryFilter() plane2.SetInputData(pl3dOutput) plane2.SetExtent(30, 30, 1, extent[3], 1, extent[5]) plane3 = vtk.vtkStructuredGridGeometryFilter() plane3.SetInputData(pl3dOutput) plane3.SetExtent(45, 45, 1, extent[3], 1, extent[5]) # We use an append filter because that way we can do the warping, etc. just # using a single pipeline and actor. # appendF = vtk.vtkAppendPolyData() appendF.AddInputConnection(plane.GetOutputPort()) appendF.AddInputConnection(plane2.GetOutputPort()) appendF.AddInputConnection(plane3.GetOutputPort()) # Warp warp = vtk.vtkWarpVector() warp.SetInputConnection(appendF.GetOutputPort()) warp.SetScaleFactor(0.005) warp.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputData(warp.GetPolyDataOutput()) normals.SetFeatureAngle(45) planeMapper = vtk.vtkPolyDataMapper() planeMapper.SetInputConnection(normals.GetOutputPort()) planeMapper.SetScalarRange(scalarRange) planeActor = vtk.vtkActor() planeActor.SetMapper(planeMapper) # The outline provides context for the data and the planes. outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(pl3dOutput) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(colors.GetColor3d('Black')) # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren.AddActor(planeActor) ren.AddActor(outlineActor) ren.SetBackground(colors.GetColor3d('BkgColor')) renWin.SetSize(512, 512) renWin.SetWindowName('VelocityProfile') iren.Initialize() renWin.Render() ren.GetActiveCamera().SetPosition(19.8562, -31.8912, 47.0755) ren.GetActiveCamera().SetFocalPoint(8.255, 0.147815, 29.7631) ren.GetActiveCamera().SetViewUp(-0.0333325, 0.465756, 0.884285) ren.GetActiveCamera().SetClippingRange(17.3078, 64.6375) renWin.Render() iren.Start()
def init_cell_field_borders_actors(self, actor_specs, drawing_params=None): """ initializes cell field actors where each cell is rendered individually as a separate spatial domain :param actor_specs: {ActorSpecs} :param drawing_params: {DrawingParameters} :return: None """ field_dim = self.currentDrawingParameters.bsd.fieldDim hex_flag = False lattice_type_str = self.get_lattice_type_str() # if lattice_type_str.lower() == 'hexagonal': # hex_flag = True hex_flag = self.is_lattice_hex(drawing_params=drawing_params) cell_type_image_data = vtk.vtkImageData() # adding 1 pixel border around the lattice to make rendering smooth at lattice borders cell_type_image_data.SetDimensions(field_dim.x + 2, field_dim.y + 2, field_dim.z + 2) cell_type_image_data.GetPointData().SetScalars(self.cell_id_array) # create a different actor for each cell type number_of_actors = len(self.used_cell_types_list) # creating and initializing filters, smoothers and mappers - one for each cell type filter_list = [ vtk.vtkDiscreteMarchingCubes() for i in range(number_of_actors) ] smoother_list = [ vtk.vtkSmoothPolyDataFilter() for i in range(number_of_actors) ] normals_list = [ vtk.vtkPolyDataNormals() for i in range(number_of_actors) ] mapper_list = [ vtk.vtkPolyDataMapper() for i in range(number_of_actors) ] for actor_counter, actor_number in enumerate( self.used_cell_types_list): if VTK_MAJOR_VERSION >= 6: filter_list[actor_counter].SetInputData(cell_type_image_data) else: filter_list[actor_counter].SetInput(cell_type_image_data) if self.used_cell_types_list[actor_counter] >= 1: ct_all = vtk_to_numpy(self.cell_type_array) cid_all = vtk_to_numpy(self.cell_id_array) cid_unique = np.unique(cid_all[ct_all == actor_number]) for idx in range(len(cid_unique)): filter_list[actor_counter].SetValue(idx, cid_unique[idx]) else: filter_list[actor_counter].SetValue(0, 13) # rwh: what the?? smoother_list[actor_counter].SetInputConnection( filter_list[actor_counter].GetOutputPort()) normals_list[actor_counter].SetInputConnection( smoother_list[actor_counter].GetOutputPort()) normals_list[actor_counter].SetFeatureAngle(45.0) mapper_list[actor_counter].SetInputConnection( normals_list[actor_counter].GetOutputPort()) mapper_list[actor_counter].ScalarVisibilityOff() actors_dict = actor_specs.actors_dict if actor_number in list(actors_dict.keys()): actor = actors_dict[actor_number] actor.SetMapper(mapper_list[actor_counter]) cell_type_lut = self.get_type_lookup_table() actor.GetProperty().SetDiffuseColor( cell_type_lut.GetTableValue(actor_number)[0:3]) if hex_flag: actor.SetScale(self.xScaleHex, self.yScaleHex, self.zScaleHex)
def CreateSurfaceFromPolydata(self, polydata, overwrite=False, name=None, colour=None, transparency=None, volume=None, area=None): normals = vtk.vtkPolyDataNormals() normals.SetInputData(polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() normals.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(normals.GetOutput()) mapper.ScalarVisibilityOff() mapper.ImmediateModeRenderingOn() # improve performance actor = vtk.vtkActor() actor.SetMapper(mapper) if overwrite: surface = Surface(index=self.last_surface_index) else: surface = Surface() if not colour: surface.colour = random.choice(const.SURFACE_COLOUR) else: surface.colour = colour surface.polydata = polydata if transparency: surface.transparency = transparency if name: surface.name = name # Append surface into Project.surface_dict proj = prj.Project() if overwrite: proj.ChangeSurface(surface) else: index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index # Set actor colour and transparency actor.GetProperty().SetColor(surface.colour) actor.GetProperty().SetOpacity(1 - surface.transparency) self.actors_dict[surface.index] = actor session = ses.Session() session.ChangeProject() # The following lines have to be here, otherwise all volumes disappear if not volume or not area: triangle_filter = vtk.vtkTriangleFilter() triangle_filter.SetInputData(polydata) triangle_filter.Update() measured_polydata = vtk.vtkMassProperties() measured_polydata.SetInputConnection( triangle_filter.GetOutputPort()) measured_polydata.Update() volume = measured_polydata.GetVolume() area = measured_polydata.GetSurfaceArea() surface.volume = volume surface.area = area print(">>>>", surface.volume) else: surface.volume = volume surface.area = area self.last_surface_index = surface.index Publisher.sendMessage('Load surface actor into viewer', actor=actor) Publisher.sendMessage('Update surface info in GUI', surface=surface) return surface.index
# Now create the RenderWindow, Renderer and Interactor # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) cowReader = vtk.vtkOBJReader() cowReader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/Viewpoint/cow.obj") plane = vtk.vtkPlane() plane.SetNormal(1, 0, 0) cowClipper = vtk.vtkClipPolyData() cowClipper.SetInputConnection(cowReader.GetOutputPort()) cowClipper.SetClipFunction(plane) cellNormals = vtk.vtkPolyDataNormals() cellNormals.SetInputConnection(cowClipper.GetOutputPort()) cellNormals.ComputePointNormalsOn() cellNormals.ComputeCellNormalsOn() reflect = vtk.vtkTransform() reflect.Scale(-1, 1, 1) cowReflect = vtk.vtkTransformPolyDataFilter() cowReflect.SetTransform(reflect) cowReflect.SetInputConnection(cellNormals.GetOutputPort()) cowReverse = vtk.vtkReverseSense() cowReverse.SetInputConnection(cowReflect.GetOutputPort()) cowReverse.ReverseNormalsOn() cowReverse.ReverseCellsOff() reflectedMapper = vtk.vtkPolyDataMapper() reflectedMapper.SetInputConnection(cowReverse.GetOutputPort()) reflected = vtk.vtkActor()
def AddNewActor(self, slice_, mask, surface_parameters): """ Create surface actor, save into project and send it to viewer. """ matrix = slice_.matrix filename_img = slice_.matrix_filename spacing = slice_.spacing algorithm = surface_parameters['method']['algorithm'] options = surface_parameters['method']['options'] surface_name = surface_parameters['options']['name'] quality = surface_parameters['options']['quality'] fill_holes = surface_parameters['options']['fill'] keep_largest = surface_parameters['options']['keep_largest'] mode = 'CONTOUR' # 'GRAYSCALE' min_value, max_value = mask.threshold_range colour = mask.colour[:3] try: overwrite = surface_parameters['options']['overwrite'] except KeyError: overwrite = False mask.matrix.flush() if quality in const.SURFACE_QUALITY.keys(): imagedata_resolution = const.SURFACE_QUALITY[quality][0] smooth_iterations = const.SURFACE_QUALITY[quality][1] smooth_relaxation_factor = const.SURFACE_QUALITY[quality][2] decimate_reduction = const.SURFACE_QUALITY[quality][3] #if imagedata_resolution: #imagedata = iu.ResampleImage3D(imagedata, imagedata_resolution) pipeline_size = 4 if decimate_reduction: pipeline_size += 1 if (smooth_iterations and smooth_relaxation_factor): pipeline_size += 1 if fill_holes: pipeline_size += 1 if keep_largest: pipeline_size += 1 ## Update progress value in GUI UpdateProgress = vu.ShowProgress(pipeline_size) UpdateProgress(0, _("Creating 3D surface...")) language = ses.Session().language if (prj.Project().original_orientation == const.CORONAL): flip_image = False else: flip_image = True n_processors = multiprocessing.cpu_count() pipe_in, pipe_out = multiprocessing.Pipe() o_piece = 1 piece_size = 2000 n_pieces = int(round(matrix.shape[0] / piece_size + 0.5, 0)) q_in = multiprocessing.Queue() q_out = multiprocessing.Queue() p = [] for i in range(n_processors): sp = surface_process.SurfaceProcess( pipe_in, filename_img, matrix.shape, matrix.dtype, mask.temp_file, mask.matrix.shape, mask.matrix.dtype, spacing, mode, min_value, max_value, decimate_reduction, smooth_relaxation_factor, smooth_iterations, language, flip_image, q_in, q_out, algorithm != 'Default', algorithm, imagedata_resolution) p.append(sp) sp.start() for i in range(n_pieces): init = i * piece_size end = init + piece_size + o_piece roi = slice(init, end) q_in.put(roi) print("new_piece", roi) for i in p: q_in.put(None) none_count = 1 while 1: msg = pipe_out.recv() if (msg is None): none_count += 1 else: UpdateProgress(msg[0] / (n_pieces * pipeline_size), msg[1]) if none_count > n_pieces: break polydata_append = vtk.vtkAppendPolyData() # polydata_append.ReleaseDataFlagOn() t = n_pieces while t: filename_polydata = q_out.get() reader = vtk.vtkXMLPolyDataReader() reader.SetFileName(filename_polydata) # reader.ReleaseDataFlagOn() reader.Update() # reader.GetOutput().ReleaseDataFlagOn() polydata = reader.GetOutput() # polydata.SetSource(None) polydata_append.AddInputData(polydata) del reader del polydata t -= 1 polydata_append.Update() # polydata_append.GetOutput().ReleaseDataFlagOn() polydata = polydata_append.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del polydata_append if algorithm == 'ca_smoothing': normals = vtk.vtkPolyDataNormals() normals_ref = weakref.ref(normals) normals_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) # normals.ReleaseDataFlagOn() #normals.SetFeatureAngle(80) #normals.AutoOrientNormalsOn() normals.ComputeCellNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() # polydata.SetSource(None) del normals clean = vtk.vtkCleanPolyData() # clean.ReleaseDataFlagOn() # clean.GetOutput().ReleaseDataFlagOn() clean_ref = weakref.ref(clean) clean_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( clean_ref(), _("Creating 3D surface..."))) clean.SetInputData(polydata) clean.PointMergingOn() clean.Update() del polydata polydata = clean.GetOutput() # polydata.SetSource(None) del clean # try: # polydata.BuildLinks() # except TypeError: # polydata.BuildLinks(0) # polydata = ca_smoothing.ca_smoothing(polydata, options['angle'], # options['max distance'], # options['min weight'], # options['steps']) mesh = cy_mesh.Mesh(polydata) cy_mesh.ca_smoothing(mesh, options['angle'], options['max distance'], options['min weight'], options['steps']) # polydata = mesh.to_vtk() # polydata.SetSource(None) # polydata.DebugOn() else: #smoother = vtk.vtkWindowedSincPolyDataFilter() smoother = vtk.vtkSmoothPolyDataFilter() smoother_ref = weakref.ref(smoother) smoother_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( smoother_ref(), _("Creating 3D surface..."))) smoother.SetInputData(polydata) smoother.SetNumberOfIterations(smooth_iterations) smoother.SetRelaxationFactor(smooth_relaxation_factor) smoother.SetFeatureAngle(80) #smoother.SetEdgeAngle(90.0) #smoother.SetPassBand(0.1) smoother.BoundarySmoothingOn() smoother.FeatureEdgeSmoothingOn() #smoother.NormalizeCoordinatesOn() #smoother.NonManifoldSmoothingOn() # smoother.ReleaseDataFlagOn() # smoother.GetOutput().ReleaseDataFlagOn() smoother.Update() del polydata polydata = smoother.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del smoother if decimate_reduction: print("Decimating", decimate_reduction) decimation = vtk.vtkQuadricDecimation() # decimation.ReleaseDataFlagOn() decimation.SetInputData(polydata) decimation.SetTargetReduction(decimate_reduction) decimation_ref = weakref.ref(decimation) decimation_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( decimation_ref(), _("Creating 3D surface..."))) #decimation.PreserveTopologyOn() #decimation.SplittingOff() #decimation.BoundaryVertexDeletionOff() # decimation.GetOutput().ReleaseDataFlagOn() decimation.Update() del polydata polydata = decimation.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del decimation #to_measure.Register(None) # to_measure.SetSource(None) if keep_largest: conn = vtk.vtkPolyDataConnectivityFilter() conn.SetInputData(polydata) conn.SetExtractionModeToLargestRegion() conn_ref = weakref.ref(conn) conn_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( conn_ref(), _("Creating 3D surface..."))) conn.Update() # conn.GetOutput().ReleaseDataFlagOn() del polydata polydata = conn.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del conn #Filter used to detect and fill holes. Only fill boundary edges holes. #TODO: Hey! This piece of code is the same from #polydata_utils.FillSurfaceHole, we need to review this. if fill_holes: filled_polydata = vtk.vtkFillHolesFilter() # filled_polydata.ReleaseDataFlagOn() filled_polydata.SetInputData(polydata) filled_polydata.SetHoleSize(300) filled_polydata_ref = weakref.ref(filled_polydata) filled_polydata_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( filled_polydata_ref(), _("Creating 3D surface..."))) filled_polydata.Update() # filled_polydata.GetOutput().ReleaseDataFlagOn() del polydata polydata = filled_polydata.GetOutput() #polydata.Register(None) # polydata.SetSource(None) # polydata.DebugOn() del filled_polydata to_measure = polydata # If InVesalius is running without GUI if wx.GetApp() is None: proj = prj.Project() #Create Surface instance if overwrite: surface = Surface(index=self.last_surface_index) proj.ChangeSurface(surface) else: surface = Surface(name=surface_name) index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index surface.colour = colour surface.polydata = polydata # With GUI else: normals = vtk.vtkPolyDataNormals() # normals.ReleaseDataFlagOn() normals_ref = weakref.ref(normals) normals_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( normals_ref(), _("Creating 3D surface..."))) normals.SetInputData(polydata) normals.SetFeatureAngle(80) normals.AutoOrientNormalsOn() # normals.GetOutput().ReleaseDataFlagOn() normals.Update() del polydata polydata = normals.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del normals # Improve performance stripper = vtk.vtkStripper() # stripper.ReleaseDataFlagOn() stripper_ref = weakref.ref(stripper) stripper_ref().AddObserver( "ProgressEvent", lambda obj, evt: UpdateProgress( stripper_ref(), _("Creating 3D surface..."))) stripper.SetInputData(polydata) stripper.PassThroughCellIdsOn() stripper.PassThroughPointIdsOn() # stripper.GetOutput().ReleaseDataFlagOn() stripper.Update() del polydata polydata = stripper.GetOutput() #polydata.Register(None) # polydata.SetSource(None) del stripper # Map polygonal data (vtkPolyData) to graphics primitives. mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(polydata) mapper.ScalarVisibilityOff() # mapper.ReleaseDataFlagOn() mapper.ImmediateModeRenderingOn() # improve performance # Represent an object (geometry & properties) in the rendered scene actor = vtk.vtkActor() actor.SetMapper(mapper) del mapper #Create Surface instance if overwrite: surface = Surface(index=self.last_surface_index) else: surface = Surface(name=surface_name) surface.colour = colour surface.polydata = polydata del polydata # Set actor colour and transparency actor.GetProperty().SetColor(colour) actor.GetProperty().SetOpacity(1 - surface.transparency) prop = actor.GetProperty() interpolation = int(ses.Session().surface_interpolation) prop.SetInterpolation(interpolation) proj = prj.Project() if overwrite: proj.ChangeSurface(surface) else: index = proj.AddSurface(surface) surface.index = index self.last_surface_index = index session = ses.Session() session.ChangeProject() measured_polydata = vtk.vtkMassProperties() # measured_polydata.ReleaseDataFlagOn() measured_polydata.SetInputData(to_measure) volume = float(measured_polydata.GetVolume()) area = float(measured_polydata.GetSurfaceArea()) surface.volume = volume surface.area = area self.last_surface_index = surface.index del measured_polydata del to_measure Publisher.sendMessage('Load surface actor into viewer', actor=actor) # Send actor by pubsub to viewer's render if overwrite and self.actors_dict.keys(): old_actor = self.actors_dict[self.last_surface_index] Publisher.sendMessage('Remove surface actor from viewer', actor=old_actor) # Save actor for future management tasks self.actors_dict[surface.index] = actor Publisher.sendMessage('Update surface info in GUI', surface=surface) #When you finalize the progress. The bar is cleaned. UpdateProgress = vu.ShowProgress(1) UpdateProgress(0, _("Ready")) Publisher.sendMessage('Update status text in GUI', label=_("Ready")) Publisher.sendMessage('End busy cursor') del actor
method = image_data.SetScalarComponentFromFloat except AttributeError: method = image_data.SetScalarComponentFromDouble for i in range(N): for j in range(N): a = float(i) / N b = float(j) / N v = 0.5 + 0.5 * cos(13 * a) * cos(8 * b + 3 * a * a) v = v**2 method(i, j, 0, 0, v) geometry_filter = vtk.vtkImageDataGeometryFilter() geometry_filter.SetInput(image_data) warp = vtk.vtkWarpScalar() warp.SetInput(geometry_filter.GetOutput()) warp.SetScaleFactor(8.1) normal_filter = vtk.vtkPolyDataNormals() normal_filter.SetInput(warp.GetOutput()) data_mapper = vtk.vtkDataSetMapper() data_mapper.SetInput(normal_filter.GetOutput()) data_actor = vtk.vtkActor() data_actor.SetMapper(data_mapper) renderer.AddActor(data_actor) table = vtk.vtkLookupTable() data_mapper.SetLookupTable(table) # the actual gradient editor code. def on_color_table_changed(): render_window.Render() # Gradient editor only works with tvtk objects, so convert the lut
#mMapper.ImmediateModeRenderingOn() mMapper.SetInputData(polydata) mActor = vtk.vtkActor() mActor.SetMapper(mMapper) mActor.GetProperty().SetOpacity(0.15) if scalarRange == (0.0, 1.0): mMapper.ScalarVisibilityOff() mActor.GetProperty().SetColor(1, 0, 0) #renDicom.AddActor(mActor) ############################################################################### # rechnische Vorbereitung auf Schnitt ############################################################################### normalGenerator = vtk.vtkPolyDataNormals() normalGenerator.SetInputData(polydata) normalGenerator.ComputePointNormalsOn() normalGenerator.ComputeCellNormalsOff() normalGenerator.Update() polydata = normalGenerator.GetOutput() normalGenerator = vtk.vtkPolyDataNormals() normalGenerator.SetInputData(polydata) normalGenerator.ComputePointNormalsOff() normalGenerator.ComputeCellNormalsOn() normalGenerator.Update() polydata = normalGenerator.GetOutput() ############################################################################### # Schnitt und Erstellung geschl. Kurve(n)
def makeActor(poly, c='gold', alpha=0.5, wire=False, bc=None, edges=False, legend=None, texture=None): ''' Return a vtkActor from an input vtkPolyData, optional args: c, color in RGB format, hex, symbol or name alpha, transparency (0=invisible) wire, show surface as wireframe bc, backface color of internal surface edges, show edges as line on top of surface legend optional string texture jpg file name of surface texture, eg. 'metalfloor1' ''' clp = vtk.vtkCleanPolyData() setInput(clp, poly) clp.Update() pdnorm = vtk.vtkPolyDataNormals() setInput(pdnorm, clp.GetOutput()) pdnorm.ComputePointNormalsOn() pdnorm.ComputeCellNormalsOn() pdnorm.FlipNormalsOff() pdnorm.ConsistencyOn() pdnorm.Update() mapper = vtk.vtkPolyDataMapper() # check if color string contains a float, in this case ignore alpha if alpha is None: alpha = 0.5 al = colors.getAlpha(c) if al: alpha = al setInput(mapper, pdnorm.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) prp = actor.GetProperty() ######################################################################### ### On some vtk versions/platforms points are redered as ugly squares ### in such a case uncomment this line: if vtk.vtkVersion().GetVTKMajorVersion() > 6: prp.RenderPointsAsSpheresOn() ######################################################################### if c is None: mapper.ScalarVisibilityOn() else: mapper.ScalarVisibilityOff() c = colors.getColor(c) prp.SetColor(c) prp.SetOpacity(alpha) prp.SetSpecular(0.1) prp.SetSpecularColor(c) prp.SetSpecularPower(1) prp.SetAmbient(0.1) prp.SetAmbientColor(c) prp.SetDiffuse(1) prp.SetDiffuseColor(c) if edges: prp.EdgeVisibilityOn() if wire: prp.SetRepresentationToWireframe() if texture: mapper.ScalarVisibilityOff() assignTexture(actor, texture) if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) actor.SetBackfaceProperty(backProp) assignPhysicsMethods(actor) assignConvenienceMethods(actor, legend) return actor
def __init__(self): """ Called when the logic class is instantiated. Can be used for initializing member variables. """ ScriptedLoadableModuleLogic.__init__(self) self.inputCurveNode = None self.inputCurveNodeObservations = [] self.inputSurfacePointsNode = None self.inputSurfacePointsNodeObservations = [] self.numberOfCurveLandmarkPoints = 80 self.printThreeDViewNode = None self.printThreeDWidget = None self.printViewWidth = 1024 self.printViewHeight = 1024 self.printXResolutionDpi = 300 self.printYResolutionDpi = 300 self.printScale = 2.0 #TODO: Workaround for scaling problem, see https://github.com/SlicerFab/SlicerFab/issues/13 self.printTransparentBackground = False # Create triangulated flat disk that will be warped self.surfaceUnitDisk = vtk.vtkDiskSource() self.surfaceUnitDisk.SetOuterRadius(1.0) self.surfaceUnitDisk.SetInnerRadius(0.0) self.surfaceUnitDisk.SetCircumferentialResolution( self.numberOfCurveLandmarkPoints) self.surfaceUnitDisk.SetRadialResolution(60) self.surfaceTriangulator = vtk.vtkDelaunay2D() self.surfaceTriangulator.SetTolerance( 0.01 ) # get rid of the small triangles near the center of the unit disk self.surfaceTriangulator.SetInputConnection( self.surfaceUnitDisk.GetOutputPort()) # Prepare transform object # points on the unit disk (circumference and surface) self.surfaceTransformSourcePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints.SetNumberOfPoints( self.numberOfCurveLandmarkPoints) import math angleIncrement = 2.0 * math.pi / float( self.numberOfCurveLandmarkPoints) for pointIndex in range(self.numberOfCurveLandmarkPoints): angle = float(pointIndex) * angleIncrement self.surfaceTransformSourceCurvePoints.SetPoint( pointIndex, math.cos(angle), math.sin(angle), 0) # points on the warped surface (curve points and surface points) self.surfaceTransformTargetPoints = vtk.vtkPoints() self.surfaceTransform = vtk.vtkThinPlateSplineTransform() self.surfaceTransform.SetSourceLandmarks( self.surfaceTransformSourcePoints) self.surfaceTransform.SetTargetLandmarks( self.surfaceTransformTargetPoints) # Transform polydata self.surfaceTransformFilter = vtk.vtkTransformPolyDataFilter() self.surfaceTransformFilter.SetTransform(self.surfaceTransform) self.surfaceTransformFilter.SetInputConnection( self.surfaceTriangulator.GetOutputPort()) self.cleanPolyDataFilter = vtk.vtkCleanPolyData() self.cleanPolyDataFilter.SetInputConnection( self.surfaceTransformFilter.GetOutputPort()) # self.surfacePolyDataNormalsThin = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThin.SetInputConnection( self.cleanPolyDataFilter.GetOutputPort()) # There are a few triangles in the triangulated unit disk with inconsistent # orientation. Enabling consistency check fixes them. self.surfacePolyDataNormalsThin.ConsistencyOn( ) # TODO: check if needed, probably not self.surfacePolyDataNormalsThin.SplittingOff( ) # this prevents stray normals at the edge TODO: check # Add thickness to warped surface (if needed) # self.surfacePolyDataNormals = vtk.vtkPolyDataNormals() # self.surfacePolyDataNormals.SetInputConnection(self.cleanPolyDataFilter.GetOutputPort()) # self.surfacePolyDataNormals.SplittingOff() # this prevents stray normals at the edge TODO: check self.surfaceOffset = vtk.vtkWarpVector() self.surfaceOffset.SetInputConnection( self.surfacePolyDataNormalsThin.GetOutputPort()) self.surfaceOffset.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) self.surfaceExtrude = vtk.vtkLinearExtrusionFilter() self.surfaceExtrude.SetInputConnection( self.surfaceOffset.GetOutputPort()) self.surfaceExtrude.SetExtrusionTypeToNormalExtrusion() self.surfacePolyDataNormalsThick = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThick.SetInputConnection( self.surfaceExtrude.GetOutputPort()) self.surfacePolyDataNormalsThick.AutoOrientNormalsOn()
def view_patch_vtk(r, azimuth=90, elevation=0, roll=-90, outfile=0, show=1): c = r.vColor ro = r r = createPolyData(r.vertices, r.faces) Colors = vtkUnsignedCharArray() Colors.SetNumberOfComponents(3) Colors.SetName("Colors") for i in range(len(ro.vertices)): Colors.InsertNextTuple3(255 * c[i, 0], 255 * c[i, 1], 255 * c[i, 2]) r.GetPointData().SetScalars(Colors) r.Modified() # ## r.Update() # mapper mapper = vtkPolyDataMapper() if VTK_MAJOR_VERSION <= 5: mapper.SetInput(r) else: # mapper.SetInputConnection(r.GetOutputPort()) mapper.SetInputData(r) actor = vtkActor() actor.SetMapper(mapper) # actor.GetProperty().SetInterpolationToPhong() normals = vtkPolyDataNormals() normals.SetInputData(r) normals.ComputePointNormalsOn() normals.ComputeCellNormalsOn() #normals.SplittingOff() normals.AutoOrientNormalsOn() normals.ConsistencyOn() #normals.SetFeatureAngle(4.01) normals.Update() mapper.SetInputData(normals.GetOutput()) ren = vtkRenderer() renWin = vtkRenderWindow() renWin.SetSize(1600, 1600) # renWin.SetDPI(200) if show == 0: renWin.SetOffScreenRendering(1) renWin.AddRenderer(ren) # create a renderwindowinteractor iren = vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren.SetBackground(256.0 / 256, 256.0 / 256, 256.0 / 256) ren.AddActor(actor) # enable user interface interactor iren.Initialize() renWin.Render() ren.GetActiveCamera().Azimuth(azimuth) ren.GetActiveCamera().Elevation(elevation) ren.GetActiveCamera().Roll(roll) renWin.Render() # windowToImageFilter->SetInput(renderWindow); # windowToImageFilter->SetMagnification(3); //set the resolution of the output image (3 times the current resolution of vtk render window) # windowToImageFilter->SetInputBufferTypeToRGBA(); //also record the alpha (transparency) channel # windowToImageFilter->ReadFrontBufferOff(); // read from the back buffer # windowToImageFilter->Update(); if outfile != 0: w2i = vtkWindowToImageFilter() writer = vtkPNGWriter() # iren.SetDPI(200) w2i.SetInput(renWin) w2i.SetInputBufferTypeToRGBA() w2i.ReadFrontBufferOff() w2i.Update() writer.SetInputData(w2i.GetOutput()) writer.SetFileName(outfile) iren.Render() writer.Write() # image = Image.open(outfile) # image.load() ## imageSize = image.size # imageBox = image.getbbox() # print(image.getbbox()) # cropped = image.crop(imageBox) # print(cropped.getbbox()) # cropped.save(outfile) if show != 0: iren.Start() close_window(iren) del renWin, iren
def testSphereWidget(self): # This example demonstrates how to use the vtkSphereWidget to control the # position of a light. # These are the pre-recorded events Recording = \ "# StreamVersion 1\n\ CharEvent 23 266 0 0 105 1 i\n\ KeyReleaseEvent 23 266 0 0 105 1 i\n\ EnterEvent 69 294 0 0 0 0 i\n\ MouseMoveEvent 69 294 0 0 0 0 i\n\ MouseMoveEvent 68 293 0 0 0 0 i\n\ MouseMoveEvent 67 292 0 0 0 0 i\n\ MouseMoveEvent 66 289 0 0 0 0 i\n\ MouseMoveEvent 66 282 0 0 0 0 i\n\ MouseMoveEvent 66 271 0 0 0 0 i\n\ MouseMoveEvent 69 253 0 0 0 0 i\n\ MouseMoveEvent 71 236 0 0 0 0 i\n\ MouseMoveEvent 74 219 0 0 0 0 i\n\ MouseMoveEvent 76 208 0 0 0 0 i\n\ MouseMoveEvent 78 190 0 0 0 0 i\n\ MouseMoveEvent 78 173 0 0 0 0 i\n\ MouseMoveEvent 77 162 0 0 0 0 i\n\ MouseMoveEvent 77 151 0 0 0 0 i\n\ MouseMoveEvent 77 139 0 0 0 0 i\n\ MouseMoveEvent 76 125 0 0 0 0 i\n\ MouseMoveEvent 73 114 0 0 0 0 i\n\ MouseMoveEvent 73 106 0 0 0 0 i\n\ MouseMoveEvent 73 101 0 0 0 0 i\n\ MouseMoveEvent 72 95 0 0 0 0 i\n\ MouseMoveEvent 72 92 0 0 0 0 i\n\ MouseMoveEvent 70 89 0 0 0 0 i\n\ MouseMoveEvent 69 86 0 0 0 0 i\n\ MouseMoveEvent 67 84 0 0 0 0 i\n\ MouseMoveEvent 65 81 0 0 0 0 i\n\ MouseMoveEvent 60 79 0 0 0 0 i\n\ MouseMoveEvent 59 79 0 0 0 0 i\n\ MouseMoveEvent 58 79 0 0 0 0 i\n\ MouseMoveEvent 57 78 0 0 0 0 i\n\ MouseMoveEvent 55 78 0 0 0 0 i\n\ MouseMoveEvent 54 77 0 0 0 0 i\n\ LeftButtonPressEvent 54 77 0 0 0 0 i\n\ MouseMoveEvent 61 79 0 0 0 0 i\n\ MouseMoveEvent 67 83 0 0 0 0 i\n\ MouseMoveEvent 72 88 0 0 0 0 i\n\ MouseMoveEvent 77 90 0 0 0 0 i\n\ MouseMoveEvent 78 91 0 0 0 0 i\n\ MouseMoveEvent 80 92 0 0 0 0 i\n\ MouseMoveEvent 84 93 0 0 0 0 i\n\ MouseMoveEvent 85 94 0 0 0 0 i\n\ MouseMoveEvent 88 97 0 0 0 0 i\n\ MouseMoveEvent 90 100 0 0 0 0 i\n\ MouseMoveEvent 92 102 0 0 0 0 i\n\ MouseMoveEvent 94 103 0 0 0 0 i\n\ MouseMoveEvent 97 105 0 0 0 0 i\n\ MouseMoveEvent 101 107 0 0 0 0 i\n\ MouseMoveEvent 102 109 0 0 0 0 i\n\ MouseMoveEvent 104 111 0 0 0 0 i\n\ MouseMoveEvent 108 113 0 0 0 0 i\n\ MouseMoveEvent 112 115 0 0 0 0 i\n\ MouseMoveEvent 118 119 0 0 0 0 i\n\ MouseMoveEvent 118 120 0 0 0 0 i\n\ MouseMoveEvent 118 123 0 0 0 0 i\n\ MouseMoveEvent 120 125 0 0 0 0 i\n\ MouseMoveEvent 122 128 0 0 0 0 i\n\ MouseMoveEvent 123 129 0 0 0 0 i\n\ MouseMoveEvent 125 132 0 0 0 0 i\n\ MouseMoveEvent 125 134 0 0 0 0 i\n\ MouseMoveEvent 127 138 0 0 0 0 i\n\ MouseMoveEvent 127 142 0 0 0 0 i\n\ MouseMoveEvent 127 147 0 0 0 0 i\n\ MouseMoveEvent 126 152 0 0 0 0 i\n\ MouseMoveEvent 126 155 0 0 0 0 i\n\ MouseMoveEvent 125 160 0 0 0 0 i\n\ MouseMoveEvent 125 167 0 0 0 0 i\n\ MouseMoveEvent 125 169 0 0 0 0 i\n\ MouseMoveEvent 125 174 0 0 0 0 i\n\ MouseMoveEvent 122 179 0 0 0 0 i\n\ MouseMoveEvent 120 183 0 0 0 0 i\n\ MouseMoveEvent 116 187 0 0 0 0 i\n\ MouseMoveEvent 113 192 0 0 0 0 i\n\ MouseMoveEvent 113 193 0 0 0 0 i\n\ MouseMoveEvent 111 195 0 0 0 0 i\n\ MouseMoveEvent 108 198 0 0 0 0 i\n\ MouseMoveEvent 106 200 0 0 0 0 i\n\ MouseMoveEvent 104 202 0 0 0 0 i\n\ MouseMoveEvent 103 203 0 0 0 0 i\n\ MouseMoveEvent 99 205 0 0 0 0 i\n\ MouseMoveEvent 97 207 0 0 0 0 i\n\ MouseMoveEvent 94 208 0 0 0 0 i\n\ MouseMoveEvent 91 210 0 0 0 0 i\n\ MouseMoveEvent 89 211 0 0 0 0 i\n\ MouseMoveEvent 86 211 0 0 0 0 i\n\ MouseMoveEvent 84 211 0 0 0 0 i\n\ MouseMoveEvent 80 211 0 0 0 0 i\n\ MouseMoveEvent 77 211 0 0 0 0 i\n\ MouseMoveEvent 75 211 0 0 0 0 i\n\ MouseMoveEvent 71 211 0 0 0 0 i\n\ MouseMoveEvent 68 211 0 0 0 0 i\n\ MouseMoveEvent 66 210 0 0 0 0 i\n\ MouseMoveEvent 62 210 0 0 0 0 i\n\ MouseMoveEvent 58 209 0 0 0 0 i\n\ MouseMoveEvent 54 207 0 0 0 0 i\n\ MouseMoveEvent 52 204 0 0 0 0 i\n\ MouseMoveEvent 51 203 0 0 0 0 i\n\ MouseMoveEvent 51 200 0 0 0 0 i\n\ MouseMoveEvent 48 196 0 0 0 0 i\n\ MouseMoveEvent 45 187 0 0 0 0 i\n\ MouseMoveEvent 45 181 0 0 0 0 i\n\ MouseMoveEvent 44 168 0 0 0 0 i\n\ MouseMoveEvent 40 161 0 0 0 0 i\n\ MouseMoveEvent 39 154 0 0 0 0 i\n\ MouseMoveEvent 38 146 0 0 0 0 i\n\ MouseMoveEvent 35 131 0 0 0 0 i\n\ MouseMoveEvent 34 121 0 0 0 0 i\n\ MouseMoveEvent 34 110 0 0 0 0 i\n\ MouseMoveEvent 34 103 0 0 0 0 i\n\ MouseMoveEvent 34 91 0 0 0 0 i\n\ MouseMoveEvent 34 86 0 0 0 0 i\n\ MouseMoveEvent 34 73 0 0 0 0 i\n\ MouseMoveEvent 35 66 0 0 0 0 i\n\ MouseMoveEvent 37 60 0 0 0 0 i\n\ MouseMoveEvent 37 53 0 0 0 0 i\n\ MouseMoveEvent 38 50 0 0 0 0 i\n\ MouseMoveEvent 38 48 0 0 0 0 i\n\ MouseMoveEvent 41 45 0 0 0 0 i\n\ MouseMoveEvent 43 45 0 0 0 0 i\n\ MouseMoveEvent 44 45 0 0 0 0 i\n\ MouseMoveEvent 47 43 0 0 0 0 i\n\ MouseMoveEvent 51 44 0 0 0 0 i\n\ MouseMoveEvent 54 44 0 0 0 0 i\n\ MouseMoveEvent 55 44 0 0 0 0 i\n\ MouseMoveEvent 59 44 0 0 0 0 i\n\ MouseMoveEvent 64 44 0 0 0 0 i\n\ MouseMoveEvent 67 44 0 0 0 0 i\n\ MouseMoveEvent 68 44 0 0 0 0 i\n\ MouseMoveEvent 71 44 0 0 0 0 i\n\ MouseMoveEvent 74 44 0 0 0 0 i\n\ MouseMoveEvent 77 44 0 0 0 0 i\n\ MouseMoveEvent 80 45 0 0 0 0 i\n\ MouseMoveEvent 81 45 0 0 0 0 i\n\ MouseMoveEvent 85 49 0 0 0 0 i\n\ MouseMoveEvent 89 50 0 0 0 0 i\n\ MouseMoveEvent 94 52 0 0 0 0 i\n\ MouseMoveEvent 99 56 0 0 0 0 i\n\ MouseMoveEvent 104 58 0 0 0 0 i\n\ MouseMoveEvent 107 61 0 0 0 0 i\n\ MouseMoveEvent 109 63 0 0 0 0 i\n\ MouseMoveEvent 109 67 0 0 0 0 i\n\ MouseMoveEvent 111 83 0 0 0 0 i\n\ MouseMoveEvent 113 86 0 0 0 0 i\n\ MouseMoveEvent 113 87 0 0 0 0 i\n\ MouseMoveEvent 113 89 0 0 0 0 i\n\ MouseMoveEvent 112 93 0 0 0 0 i\n\ MouseMoveEvent 112 97 0 0 0 0 i\n\ MouseMoveEvent 111 104 0 0 0 0 i\n\ MouseMoveEvent 112 108 0 0 0 0 i\n\ MouseMoveEvent 116 115 0 0 0 0 i\n\ MouseMoveEvent 116 123 0 0 0 0 i\n\ MouseMoveEvent 116 129 0 0 0 0 i\n\ MouseMoveEvent 119 138 0 0 0 0 i\n\ MouseMoveEvent 122 141 0 0 0 0 i\n\ MouseMoveEvent 127 148 0 0 0 0 i\n\ MouseMoveEvent 128 161 0 0 0 0 i\n\ MouseMoveEvent 131 166 0 0 0 0 i\n\ MouseMoveEvent 134 168 0 0 0 0 i\n\ MouseMoveEvent 135 171 0 0 0 0 i\n\ MouseMoveEvent 134 174 0 0 0 0 i\n\ MouseMoveEvent 132 176 0 0 0 0 i\n\ MouseMoveEvent 132 178 0 0 0 0 i\n\ MouseMoveEvent 129 180 0 0 0 0 i\n\ MouseMoveEvent 127 182 0 0 0 0 i\n\ MouseMoveEvent 124 185 0 0 0 0 i\n\ MouseMoveEvent 122 186 0 0 0 0 i\n\ MouseMoveEvent 118 189 0 0 0 0 i\n\ MouseMoveEvent 114 191 0 0 0 0 i\n\ MouseMoveEvent 114 193 0 0 0 0 i\n\ MouseMoveEvent 112 193 0 0 0 0 i\n\ MouseMoveEvent 111 194 0 0 0 0 i\n\ MouseMoveEvent 110 197 0 0 0 0 i\n\ MouseMoveEvent 110 198 0 0 0 0 i\n\ MouseMoveEvent 109 199 0 0 0 0 i\n\ MouseMoveEvent 108 200 0 0 0 0 i\n\ MouseMoveEvent 108 201 0 0 0 0 i\n\ MouseMoveEvent 108 202 0 0 0 0 i\n\ MouseMoveEvent 108 203 0 0 0 0 i\n\ MouseMoveEvent 104 206 0 0 0 0 i\n\ LeftButtonReleaseEvent 104 206 0 0 0 0 i\n\ MouseMoveEvent 104 205 0 0 0 0 i\n\ MouseMoveEvent 104 204 0 0 0 0 i\n\ MouseMoveEvent 105 205 0 0 0 0 i\n\ MouseMoveEvent 105 206 0 0 0 0 i\n\ " # Start by loading some data. # dem = vtk.vtkDEMReader() dem.SetFileName(VTK_DATA_ROOT + "/Data/SainteHelens.dem") dem.Update() Scale = 2 lut = vtk.vtkLookupTable() lut.SetHueRange(0.6, 0) lut.SetSaturationRange(1.0, 0) lut.SetValueRange(0.5, 1.0) lo = Scale * dem.GetElevationBounds()[0] hi = Scale * dem.GetElevationBounds()[1] shrink = vtk.vtkImageShrink3D() shrink.SetShrinkFactors(4, 4, 1) shrink.SetInputConnection(dem.GetOutputPort()) shrink.AveragingOn() geom = vtk.vtkImageDataGeometryFilter() geom.SetInputConnection(shrink.GetOutputPort()) geom.ReleaseDataFlagOn() warp = vtk.vtkWarpScalar() warp.SetInputConnection(geom.GetOutputPort()) warp.SetNormal(0, 0, 1) warp.UseNormalOn() warp.SetScaleFactor(Scale) warp.ReleaseDataFlagOn() elevation = vtk.vtkElevationFilter() elevation.SetInputConnection(warp.GetOutputPort()) elevation.SetLowPoint(0, 0, lo) elevation.SetHighPoint(0, 0, hi) elevation.SetScalarRange(lo, hi) elevation.ReleaseDataFlagOn() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(elevation.GetOutputPort()) normals.SetFeatureAngle(60) normals.ConsistencyOff() normals.SplittingOff() normals.ReleaseDataFlagOn() normals.Update() demMapper = vtk.vtkPolyDataMapper() demMapper.SetInputConnection(normals.GetOutputPort()) demMapper.SetScalarRange(lo, hi) demMapper.SetLookupTable(lut) demActor = vtk.vtkActor() demActor.SetMapper(demMapper) # Create the RenderWindow, Renderer and both Actors # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) iRen.LightFollowCameraOff() # iRen.SetInteractorStyle("") # The callback takes two arguments. # The first being the object that generates the event and # the second argument the event name (which is a string). def MoveLight(widget, event_string): light.SetPosition(rep.GetHandlePosition()) # Associate the line widget with the interactor rep = vtk.vtkSphereRepresentation() rep.SetPlaceFactor(4) rep.PlaceWidget(normals.GetOutput().GetBounds()) rep.HandleVisibilityOn() rep.SetRepresentationToWireframe() # rep HandleVisibilityOff # rep HandleTextOff sphereWidget = vtk.vtkSphereWidget2() sphereWidget.SetInteractor(iRen) sphereWidget.SetRepresentation(rep) # sphereWidget.TranslationEnabledOff() # sphereWidget.ScalingEnabledOff() sphereWidget.AddObserver("InteractionEvent", MoveLight) recorder = vtk.vtkInteractorEventRecorder() recorder.SetInteractor(iRen) # recorder.SetFileName("c:/record.log") # recorder.Record() recorder.ReadFromInputStringOn() recorder.SetInputString(Recording) # Add the actors to the renderer, set the background and size # ren.AddActor(demActor) ren.SetBackground(1, 1, 1) renWin.SetSize(300, 300) ren.SetBackground(0.1, 0.2, 0.4) cam1 = ren.GetActiveCamera() cam1.SetViewUp(0, 0, 1) cam1.SetFocalPoint(dem.GetOutput().GetCenter()) cam1.SetPosition(1, 0, 0) ren.ResetCamera() cam1.Elevation(25) cam1.Azimuth(125) cam1.Zoom(1.25) light = vtk.vtkLight() light.SetFocalPoint(rep.GetCenter()) light.SetPosition(rep.GetHandlePosition()) ren.AddLight(light) iRen.Initialize() renWin.Render() # render the image renWin.Render() # Actually probe the data recorder.Play() img_file = "TestSphereWidget.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
norms.InsertTuple3(1, -1.0, 0.0, 0.0) planes.SetPoints(points) planes.SetNormals(norms) # texture texReader = vtk.vtkStructuredPointsReader() texReader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/texThres2.vtk") texture = vtk.vtkTexture() texture.SetInputConnection(texReader.GetOutputPort()) texture.InterpolateOff() texture.RepeatOff() # read motor parts...each part colored separately # byu = vtk.vtkBYUReader() byu.SetGeometryFileName("" + str(VTK_DATA_ROOT) + "/Data/motor.g") byu.SetPartNumber(1) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(byu.GetOutputPort()) tex1 = vtk.vtkImplicitTextureCoords() tex1.SetInputConnection(normals.GetOutputPort()) tex1.SetRFunction(planes) # tex1 FlipTextureOn byuMapper = vtk.vtkDataSetMapper() byuMapper.SetInputConnection(tex1.GetOutputPort()) byuActor = vtk.vtkActor() byuActor.SetMapper(byuMapper) byuActor.SetTexture(texture) byuActor.GetProperty().SetColor(cold_grey) byu2 = vtk.vtkBYUReader() byu2.SetGeometryFileName("" + str(VTK_DATA_ROOT) + "/Data/motor.g") byu2.SetPartNumber(2) normals2 = vtk.vtkPolyDataNormals()
def main(): colors = vtk.vtkNamedColors() fileName = get_program_parameters() polyData = ReadPolyData(fileName) # A renderer. renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d("White")) # Create background colors for each viewport. backgroundColors = list() backgroundColors.append(colors.GetColor3d("Cornsilk")) backgroundColors.append(colors.GetColor3d("NavajoWhite")) backgroundColors.append(colors.GetColor3d("Tan")) # Create a renderer for each view port. ren = list() ren.append(vtk.vtkRenderer()) ren.append(vtk.vtkRenderer()) ren.append(vtk.vtkRenderer()) ren[0].SetViewport(0, 0, 1.0 / 3.0, 1) # Input ren[1].SetViewport(1.0 / 3.0, 0, 2.0 / 3.0, 1) # Normals (no split) ren[2].SetViewport(2.0 / 3.0, 0, 1, 1) # Normals (split) # Shared camera. camera = vtk.vtkCamera() normals = vtk.vtkPolyDataNormals() normals.SetInputData(polyData) normals.SetFeatureAngle(30.0) for i in range(0, 3): if i == 0: normals.ComputePointNormalsOff() elif i == 1: normals.ComputePointNormalsOn() normals.SplittingOff() else: normals.ComputePointNormalsOn() normals.SplittingOn() normals.Update() normalsPolyData = vtk.vtkPolyData() normalsPolyData.DeepCopy(normals.GetOutput()) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(normalsPolyData) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(colors.GetColor3d("Peacock")) actor.GetProperty().SetDiffuse(.7) actor.GetProperty().SetSpecularPower(20) actor.GetProperty().SetSpecular(.5) # add the actor ren[i].SetBackground(backgroundColors[i]) ren[i].SetActiveCamera(camera) ren[i].AddActor(actor) # Render window. renwin = vtk.vtkRenderWindow() renwin.AddRenderer(ren[0]) renwin.AddRenderer(ren[1]) renwin.AddRenderer(ren[2]) # An interactor. interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) renwin.SetSize(900, 300) ren[0].GetActiveCamera().SetFocalPoint(0, 0, 0) ren[0].GetActiveCamera().SetPosition(1, 0, 0) ren[0].GetActiveCamera().SetViewUp(0, 0, -1) ren[0].ResetCamera() ren[0].GetActiveCamera().Azimuth(120) ren[0].GetActiveCamera().Elevation(30) ren[0].GetActiveCamera().Dolly(1.1) ren[0].ResetCameraClippingRange() renwin.Render() ren[0].ResetCamera() renwin.Render() # Start. interactor.Initialize() interactor.Start()
ptLoad.ComputeEffectiveStressOn() ptLoad.SetModelBounds(-10,10,-10,10,-10,10) # extract plane of data plane = vtk.vtkImageDataGeometryFilter() plane.SetInputConnection(ptLoad.GetOutputPort()) plane.SetExtent(2,2,0,99,0,99) # Generate ellipsoids sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(8) sphere.SetPhiResolution(8) ellipsoids = vtk.vtkTensorGlyph() ellipsoids.SetInputConnection(ptLoad.GetOutputPort()) ellipsoids.SetSourceConnection(sphere.GetOutputPort()) ellipsoids.SetScaleFactor(10) ellipsoids.ClampScalingOn() ellipNormals = vtk.vtkPolyDataNormals() ellipNormals.SetInputConnection(ellipsoids.GetOutputPort()) # Map contour lut = vtk.vtkLogLookupTable() lut.SetHueRange(.6667,0.0) ellipMapper = vtk.vtkPolyDataMapper() ellipMapper.SetInputConnection(ellipNormals.GetOutputPort()) ellipMapper.SetLookupTable(lut) plane.Update() #force update for scalar range ellipMapper.SetScalarRange(plane.GetOutput().GetScalarRange()) ellipActor = vtk.vtkActor() ellipActor.SetMapper(ellipMapper) # # Create outline around data #
strips.GetCellData().AddArray(a) s = vtk.vtkSphereSource() s.Update() sphere = s.GetOutput() a2 = vtk.vtkFloatArray() a2.SetNumberOfTuples(96) a2.FillComponent(0, 2) a2.SetName("foo") sphere.GetCellData().AddArray(a2) app = vtk.vtkAppendPolyData() app.AddInputData(strips) app.AddInputData(sphere) pdn = vtk.vtkPolyDataNormals() pdn.SetInputConnection(app.GetOutputPort()) pdn.Update() output = pdn.GetOutput() foo = output.GetCellData().GetArray("foo") for i in range(0, 96): assert (foo.GetValue(i) == 2) for i in range(96, 116): assert (foo.GetValue(i) == 1)