def cutWithPlane(self, origin=(0, 0, 0), normal=(1, 0, 0)): """ Cut the mesh with the plane defined by a point and a normal. :param origin: the cutting plane goes through this point :param normal: normal of the cutting plane """ strn = str(normal) if strn == "x": normal = (1, 0, 0) elif strn == "y": normal = (0, 1, 0) elif strn == "z": normal = (0, 0, 1) elif strn == "-x": normal = (-1, 0, 0) elif strn == "-y": normal = (0, -1, 0) elif strn == "-z": normal = (0, 0, -1) plane = vtk.vtkPlane() plane.SetOrigin(origin) plane.SetNormal(normal) clipper = vtk.vtkClipDataSet() clipper.SetInputData(self._ugrid) clipper.SetClipFunction(plane) clipper.GenerateClipScalarsOff() clipper.GenerateClippedOutputOff() clipper.SetValue(0) clipper.Update() cout = clipper.GetOutput() return self._update(cout)
def makePlaneClipper(vtkObj,plane): """Makes a plane and clipper """ clipper = vtk.vtkClipDataSet() clipper.SetInputConnection(vtkObj.GetProducerPort()) clipper.SetClipFunction(plane) clipper.InsideOutOff() return clipper
def ClipMRIWithCylinder(mri_data,cylinderTransformed): implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance() implicitPolyDataDistance.SetInput(cylinderTransformed) mri_data_copy=mri_data # Create an array to hold distance information signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName("SignedDistances") # Evaluate the signed distance function at all of the grid points for pointId in range(mri_data.GetNumberOfPoints()): p = mri_data.GetPoint(pointId) signedDistance = implicitPolyDataDistance.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) # add the SignedDistances to the grid mriDistanceData=np.zeros([int(mri_data.GetNumberOfPoints()),1]) for i in range(mri_data.GetNumberOfPoints()): mriDist=signedDistances.GetTuple(i)[0] mriDistanceData[i]=mriDist mriDistVtk=vtk.vtkDoubleArray() mriDistVtk.SetArray(mriDistanceData,mri_data.GetNumberOfPoints(),1) mri_data_copy.GetPointData().SetScalars(mriDistVtk) clipper = vtk.vtkClipDataSet() clipper.SetInputData(mri_data_copy) clipper.InsideOutOn() clipper.SetValue(0.0) clipper.Update() return clipper
def clip(inp, origin, normal, inside_out=False, take_cell=False): """ VTK operation: clip. A vtkGeometryFilter is used to convert the resulted vtkUnstructuredMesh object into a vtkPolyData object. @param inp: input VTK object. @type inp: vtk.vtkobject @param origin: a 3-tuple for cut origin. @type origin: tuple @param normal: a 3-tuple for cut normal. @type normal: tuple @keyword inside_out: make inside out. Default False. @type inside_out: bool @keyword take_cell: treat the input VTK object with values on cells. Default False. @type: take_cell: bool @return: output VTK object. @rtype: vtk.vtkobject """ import vtk pne = vtk.vtkPlane() pne.SetOrigin(origin) pne.SetNormal(normal) clip = vtk.vtkClipDataSet() if take_cell: clip.SetInput(inp) else: clip.SetInputConnection(inp.GetOutputPort()) clip.SetClipFunction(pne) if inside_out: clip.InsideOutOn() parison = vtk.vtkGeometryFilter() parison.SetInputConnection(clip.GetOutputPort()) return parison
def clip(dataset, normal='x', origin=None, invert=True): """ Clip a dataset by a plane by specifying the origin and normal. If no parameters are given the clip will occur in the center of that dataset Parameters ---------- normal : tuple(float) or str Length 3 tuple for the normal vector direction. Can also be specified as a string conventional direction such as ``'x'`` for ``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)``, etc. origin : tuple(float) The center ``(x,y,z)`` coordinate of the plane on which the clip occurs invert : bool Flag on whether to flip/invert the clip """ if isinstance(normal, str): normal = NORMALS[normal.lower()] # find center of data if origin not specified if origin is None: origin = dataset.center # create the plane for clipping plane = _generate_plane(normal, origin) # run the clip alg = vtk.vtkClipDataSet() alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut alg.SetClipFunction(plane) # the the cutter to use the plane we made alg.SetInsideOut(invert) # invert the clip if needed alg.Update() # Perfrom the Cut return _get_output(alg)
def cutPolyData(dataSet, **kwargs): # Read options pt = kwargs.get('point') normal = kwargs.get('normal') delta = kwargs.get('maxDist') if pt == None: raise RuntimeError('No point provided') if normal == None: raise RuntimeError('No normal provided') # Create plane plane = vtk.vtkPlane() plane.SetOrigin(pt[0], pt[1], pt[2]) plane.SetNormal(normal[0], normal[1], normal[2]) cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetInputData(dataSet) if delta == None: cutter.Update() return cutter.GetOutput() else: # Create a box box = vtk.vtkBox() box.SetBounds(pt[0]-delta, pt[0]+delta, pt[1]-delta, pt[1]+delta, pt[2]-delta, pt[2]+delta) # Clip data with a box clipper = vtk.vtkClipDataSet() clipper.SetClipFunction(box) clipper.SetInputConnection(cutter.GetOutputPort()) clipper.InsideOutOn() clipper.Update() return clipper.GetOutput()
def clipDataSetWithPolygon(vtkDataSet, vtkPoly, returnImpDist=False, insideOut=True, extractBounds=False): """ Function to clips cells from a vtkDataSet, given polygon/s in a vtkPolyData. Returns a clipped cells that fall inside or outside the polygon boundary. """ # Make a implicit function impDist = convertToImplicitPolyDataDistance(vtkPoly) # Reduce the data to the bounds if extractBounds: extBoundsFilt = extractDataSetByBounds(vtkDataSet, vtkPoly) else: extBoundsFilt = extractDataSetByBounds(vtkDataSet, vtkDataSet) if vtkDataSet.IsA('vtkPolyData'): clipFilt = vtk.vtkClipPolyData() else: clipFilt = vtk.vtkClipDataSet() clipFilt.SetInsideOut(insideOut + 0) clipFilt.SetInputConnection(extBoundsFilt.GetOutputPort()) clipFilt.SetClipFunction(impDist) clipFilt.SetOutputPointsPrecision(vtk.vtkAlgorithm.DOUBLE_PRECISION) # clipFilt.SetMergeTolerance(0.000001) clipFilt.Update() if returnImpDist: return clipFilt.GetOutput(), impDist else: return clipFilt.GetOutput()
def clip(inp, origin, normal, inside_out=False, take_cell=False): """ VTK operation: clip. A vtkGeometryFilter is used to convert the resulted vtkUnstructuredMesh object into a vtkPolyData object. @param inp: input VTK object. @type inp: vtk.vtkobject @param origin: a 3-tuple for cut origin. @type origin: tuple @param normal: a 3-tuple for cut normal. @type normal: tuple @keyword inside_out: make inside out. Default False. @type inside_out: bool @keyword take_cell: treat the input VTK object with values on cells. Default False. @type: take_cell: bool @return: output VTK object. @rtype: vtk.vtkobject """ import vtk pne = vtk.vtkPlane() pne.SetOrigin(origin) pne.SetNormal(normal) clip = vtk.vtkClipDataSet() if take_cell: clip.SetInput(inp) else: clip.SetInputConnection(inp.GetOutputPort()) clip.SetClipFunction(pne) if inside_out: clip.InsideOutOn() parison = vtk.vtkGeometryFilter() parison.SetInputConnection(clip.GetOutputPort()) return parison
def create_renderer_2(bone, skin): ''' Return the second renderer bone: the bone dataset skin: the skin dataset ''' # creating the sphere clipping sphere = vtk.vtkSphere() sphere.SetRadius(60) sphere.SetCenter(70, 30, 100) # clipping clipper = vtk.vtkClipDataSet() clipper.SetClipFunction(sphere) clipper.SetInputConnection(skin.GetOutputPort()) skin = clipper # creating actors bone_actor = create_actor(bone) bone_actor.GetProperty().SetColor(0.94, 0.94, 0.94) # spliting the skin in 2 different actors for front face opacity frontface_actor = create_actor(skin) frontface_actor.GetProperty().SetColor(0.8, 0.62, 0.62) backface_actor = create_actor(skin) backface_actor.GetProperty().SetColor(0.8, 0.62, 0.62) backface_actor.GetProperty().FrontfaceCullingOn() # changing opacity of the front one frontface_actor.GetProperty().SetOpacity(0.6) # creating renderer ren = create_renderer([bone_actor, frontface_actor, backface_actor]) ren.SetBackground(0.824, 1, 0.824) return ren
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkClipDataSet(), 'Processing.', ('vtkDataSet',), ('vtkUnstructuredGrid', 'vtkUnstructuredGrid'), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def computeVolumes(meshVTK, th, scalarFieldName='rvot', path=None, writeInletOutlet=True, returnMeshes=False, **kwargs): meshVTK.GetPointData().SetActiveScalars(scalarFieldName) clip = vtk.vtkClipDataSet() clip.SetInputData(meshVTK) clip.SetValue(th) clip.SetInsideOut(kwargs.get('greaterOrEqual', True)) # Get <= clip.Update() tetrahedrilize = vtk.vtkDataSetTriangleFilter() tetrahedrilize.SetInputConnection(clip.GetOutputPort()) tetrahedrilize.Update() outlet = tetrahedrilize.GetOutput() clip2 = vtk.vtkClipDataSet() clip2.SetInputData(meshVTK) clip2.SetValue(th) clip2.SetInsideOut(not kwargs.get('greaterOrEqual', True)) clip2.Update() tetrahedrilize2 = vtk.vtkDataSetTriangleFilter() tetrahedrilize2.SetInputConnection(clip2.GetOutputPort()) tetrahedrilize2.Update() inlet = tetrahedrilize2.GetOutput() if path is not None: path = path.replace('.1', '') if writeInletOutlet: utilities.writeUnstructuredGridVTK( utilities.appendStringBeforeFileType( path, kwargs.get('name1', '_inlet')), inlet) utilities.writeUnstructuredGridVTK( utilities.appendStringBeforeFileType( path, kwargs.get('name2', '_outlet')), outlet) else: utilities.writeUnstructuredGridVTK(path, inlet) if not returnMeshes: return computeVolumeTetrahedralMesh( inlet), computeVolumeTetrahedralMesh(outlet) else: return inlet, outlet
def ClipMesh(self): meshClipFilter = vtk.vtkClipDataSet() meshClipFilter.SetInputData(self.Mesh) meshClipFilter.SetInsideOut(self.InsideOut) clipPlane = vtk.vtkPlane() self.PlaneWidget.GetPlane(clipPlane) meshClipFilter.SetClipFunction(clipPlane) meshClipFilter.Update() return meshClipFilter.GetOutput()
def ClipMesh(self): meshClipFilter = vtk.vtkClipDataSet() meshClipFilter.SetInputData(self.Mesh) meshClipFilter.SetInsideOut(self.InsideOut) clipPlane = vtk.vtkPlane() self.PlaneWidget.GetPlane(clipPlane) meshClipFilter.SetClipFunction(clipPlane) meshClipFilter.Update() return meshClipFilter.GetOutput()
def clipData(inputData, distanceFunc, insideOut): evalDistanceOnGrid("SignedDistance", inputData, distanceFunc) clipper = vtk.vtkClipDataSet() clipper.SetInputData(inputData) if insideOut: clipper.InsideOutOn() clipper.SetValue(0.0) clipper.Update() return clipper.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkClipDataSet(), 'Processing.', ('vtkDataSet', ), ('vtkUnstructuredGrid', 'vtkUnstructuredGrid'), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def clipVTK(meshVTK, th=0, scalarName='rvot', insideOut=False): """ Clips a mesh using VTK """ meshVTK.GetPointData().SetActiveScalars(scalarName) clip = vtk.vtkClipDataSet() clip.SetValue(th) clip.SetInsideOut(insideOut) clip.SetInputData(meshVTK) clip.Update() return clip.GetOutput()
def cutWithMesh(self, mesh, invert=False, onlyTets=False, onlyBoundary=False): """ Cut a ``TetMesh`` mesh with a ``Mesh``. :param bool invert: if True return cut off part of the input TetMesh. """ polymesh = mesh.polydata() ug = self._ugrid scalname = ug.GetCellData().GetScalars().GetName() ippd = vtk.vtkImplicitPolyDataDistance() ippd.SetInput(polymesh) if onlyTets or onlyBoundary: clipper = vtk.vtkExtractGeometry() clipper.SetInputData(ug) clipper.SetImplicitFunction(ippd) clipper.SetExtractInside(not invert) clipper.SetExtractBoundaryCells(False) if onlyBoundary: clipper.SetExtractBoundaryCells(True) clipper.SetExtractOnlyBoundaryCells(True) else: signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName("SignedDistances") for pointId in range(ug.GetNumberOfPoints()): p = ug.GetPoint(pointId) signedDistance = ippd.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) ug.GetPointData().SetScalars(signedDistances) clipper = vtk.vtkClipDataSet() clipper.SetInputData(ug) clipper.SetInsideOut(not invert) clipper.SetValue(0.0) clipper.Update() cug = clipper.GetOutput() if scalname: # not working if self.useCells: self.selectCellArray(scalname) else: self.selectPointArray(scalname) self._update(cug) return self
def create_renderer_3(bone, skin): ''' Return the third renderer bone: the bone dataset skin: the skin dataset ''' # creating the sphere clipping radius = 60 center = [70, 30, 100] sphere = vtk.vtkSphere() sphere.SetRadius(radius) sphere.SetCenter(center) # clipping clipper = vtk.vtkClipDataSet() clipper.SetClipFunction(sphere) clipper.SetInputConnection(skin.GetOutputPort()) skin = clipper # creating actors bone_actor = create_actor(bone) bone_actor.GetProperty().SetColor(0.94, 0.94, 0.94) skin_actor = create_actor(skin) skin_actor.GetProperty().SetColor(0.8, 0.62, 0.62) # creating the sphere actor ---- # sampling using the sphere implicit function sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(sphere) sample.SetSampleDimensions(50, 50, 50) sample.SetModelBounds(center[0] - radius, center[0] + radius, center[1] - radius, center[1] + radius, center[2] - radius, center[2] + radius) # contouring. The sphere is described by a 0 iso-value sphere_actor = create_iso_actor(sample, 0) # design sphere_actor.GetProperty().SetColor(0.85, 0.8, 0.1) sphere_actor.GetProperty().SetOpacity(0.15) # creating renderer ren = create_renderer([bone_actor, skin_actor, sphere_actor]) ren.SetBackground(0.827, 0.824, 1) return ren
def Clip_VTK_data_to_VTK(inputFileName, outputFileName, point, normal, resolution): reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(inputFileName) reader.Update() plane = vtk.vtkPlane() plane.SetOrigin(point) plane.SetNormal(normal) clipper = vtk.vtkClipDataSet() clipper.SetClipFunction(plane) clipper.SetInputConnection(reader.GetOutputPort()) clipper.Update() writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetInputData(clipper.GetOutput()) writer.SetFileName(outputFileName) writer.Write()
def Execute(self): if (self.Mesh == None): self.PrintError('Error: no Mesh.') self.Planes = vtk.vtkPlanes() self.Clipper = vtk.vtkClipDataSet() self.Clipper.SetInput(self.Mesh) self.Clipper.SetClipFunction(self.Planes) self.Clipper.GenerateClippedOutputOn() self.Clipper.InsideOutOn() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) mapper = vtk.vtkDataSetMapper() mapper.SetInput(self.Mesh) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) self.BoxWidget = vtk.vtkBoxWidget() self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.BoxWidget.GetFaceProperty().SetColor(0.6, 0.6, 0.2) self.BoxWidget.GetFaceProperty().SetOpacity(0.25) self.vmtkRenderer.AddKeyBinding('i', 'Interact.', self.InteractCallback) self.vmtkRenderer.AddKeyBinding('space', 'Clip.', self.ClipCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.Mesh.GetSource(): self.Mesh.GetSource().UnRegisterAllOutputs()
def new_implicit_plane_widget( data_source) -> Tuple[vtk.vtkAbstractWidget, vtk.vtkProp]: # This portion of the code clips the mace with the vtkPlanes # implicit function. The clipped region is colored green. select_plane = vtk.vtkPlane() clipper = vtk.vtkClipDataSet() clipper.SetInputConnection(data_source.GetOutputPort()) clipper.SetClipFunction(select_plane) clipper.InsideOutOn() selectMapper = vtk.vtkPolyDataMapper() selectMapper.SetInputConnection(clipper.GetOutputPort()) selectActor = vtk.vtkActor() selectActor.SetMapper(selectMapper) selectActor.GetProperty().SetColor(0, 1, 1) selectActor.VisibilityOff() selectActor.SetScale(1.01, 1.01, 1.01) # Associate the line widget with the interactor planeRep = vtk.vtkImplicitPlaneRepresentation() planeRep.SetPlaceFactor(2.0) data_source.Update() bounds = data_source.GetOutput().GetBounds() origin = [ (bounds[0] + bounds[1]) / 2.0, (bounds[2] + bounds[3]) / 2.0, (bounds[4] + bounds[5]) / 2.0, ] planeRep.PlaceWidget(bounds) planeRep.SetOrigin(origin) planeWidget = vtk.vtkImplicitPlaneWidget2() planeWidget.SetRepresentation(planeRep) # planeWidget.SetInputConnection(glyph.GetOutputPort()) def myCallback(obj, event): planeRep.GetPlane(select_plane) print("MYCALLBACK", type(obj), type(event), event) selectActor.VisibilityOn() planeWidget.AddObserver("InteractionEvent", myCallback) return planeWidget, selectActor
def Execute(self): if (self.Mesh == None): self.PrintError('Error: no Mesh.') self.Planes = vtk.vtkPlanes() self.Clipper = vtk.vtkClipDataSet() self.Clipper.SetInput(self.Mesh) self.Clipper.SetClipFunction(self.Planes) self.Clipper.GenerateClippedOutputOn() self.Clipper.InsideOutOn() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) mapper = vtk.vtkDataSetMapper() mapper.SetInput(self.Mesh) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) self.BoxWidget = vtk.vtkBoxWidget() self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.BoxWidget.GetFaceProperty().SetColor(0.6,0.6,0.2) self.BoxWidget.GetFaceProperty().SetOpacity(0.25) self.vmtkRenderer.AddKeyBinding('i','Interact.', self.InteractCallback) self.vmtkRenderer.AddKeyBinding('space','Clip.', self.ClipCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.Mesh.GetSource(): self.Mesh.GetSource().UnRegisterAllOutputs()
def Clip_VTK_data_to_VTK(inputFileName, outputFileName, point, normal, resolution ): reader = vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(inputFileName) reader.Update() plane = vtk.vtkPlane() plane.SetOrigin(point) plane.SetNormal(normal) clipper = vtk.vtkClipDataSet() clipper.SetClipFunction(plane) clipper.SetInputConnection(reader.GetOutputPort()) clipper.Update() writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetInputData(clipper.GetOutput()) writer.SetFileName(outputFileName) writer.Write()
def clip(dataset, normal='x', origin=None, invert=True): """ Clip a dataset by a plane by specifying the origin and normal. If no parameters are given the clip will occur in the center of that dataset dataset : """ if isinstance(normal, str): normal = NORMALS[normal.lower()] # find center of data if origin not specified if origin is None: origin = dataset.center # create the plane for clipping plane = _generate_plane(normal, origin) # run the clip alg = vtk.vtkClipDataSet() alg.SetInputDataObject( dataset) # Use the grid as the data we desire to cut alg.SetClipFunction(plane) # the the cutter to use the plane we made alg.SetInsideOut(invert) # invert the clip if needed alg.Update() # Perfrom the Cut return _get_output(alg)
def main(): # vtkFlyingEdges3D was introduced in VTK >= 8.2 use_flying_edges = vtk_version_ok(8, 2, 0) colors = vtk.vtkNamedColors() file_name = get_program_parameters() colors.SetColor('SkinColor', [240, 184, 160, 255]) colors.SetColor('BackfaceColor', [255, 229, 200, 255]) colors.SetColor('BkgColor', [51, 77, 102, 255]) # Read the volume data reader = vtk.vtkMetaImageReader() reader.SetFileName(file_name) reader.Update() # An isosurface, or contour value of 500 is known to correspond to the # skin of the patient. if use_flying_edges: try: skin_extractor = vtk.vtkFlyingEdges3D() except AttributeError: skin_extractor = vtk.vtkMarchingCubes() else: skin_extractor = vtk.vtkMarchingCubes() skin_extractor.SetInputConnection(reader.GetOutputPort()) skin_extractor.SetValue(0, 500) # Define a spherical clip function to clip the isosurface clip_function = vtk.vtkSphere() clip_function.SetRadius(50) clip_function.SetCenter(73, 52, 15) # Clip the isosurface with a sphere skin_clip = vtk.vtkClipDataSet() skin_clip.SetInputConnection(skin_extractor.GetOutputPort()) skin_clip.SetClipFunction(clip_function) skin_clip.SetValue(0) skin_clip.GenerateClipScalarsOn() skin_clip.Update() skin_mapper = vtk.vtkDataSetMapper() skin_mapper.SetInputConnection(skin_clip.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skin_mapper) skin.GetProperty().SetDiffuseColor(colors.GetColor3d('SkinColor')) back_prop = vtk.vtkProperty() back_prop.SetDiffuseColor(colors.GetColor3d('BackfaceColor')) skin.SetBackfaceProperty(back_prop) # Define a model for the "lens". Its geometry matches the implicit # sphere used to clip the isosurface lens_model = vtk.vtkSphereSource() lens_model.SetRadius(50) lens_model.SetCenter(73, 52, 15) lens_model.SetPhiResolution(201) lens_model.SetThetaResolution(101) # Sample the input volume with the lens model geometry lens_probe = vtk.vtkProbeFilter() lens_probe.SetInputConnection(lens_model.GetOutputPort()) lens_probe.SetSourceConnection(reader.GetOutputPort()) # Clip the lens data with the isosurface value lens_clip = vtk.vtkClipDataSet() lens_clip.SetInputConnection(lens_probe.GetOutputPort()) lens_clip.SetValue(500) lens_clip.GenerateClipScalarsOff() lens_clip.Update() # Define a suitable grayscale lut bw_lut = vtk.vtkLookupTable() bw_lut.SetTableRange(0, 2048) bw_lut.SetSaturationRange(0, 0) bw_lut.SetHueRange(0, 0) bw_lut.SetValueRange(0.2, 1) bw_lut.Build() lens_mapper = vtk.vtkDataSetMapper() lens_mapper.SetInputConnection(lens_clip.GetOutputPort()) lens_mapper.SetScalarRange(lens_clip.GetOutput().GetScalarRange()) lens_mapper.SetLookupTable(bw_lut) lens = vtk.vtkActor() lens.SetMapper(lens_mapper) # 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. a_camera = vtk.vtkCamera() a_camera.SetViewUp(0, 0, -1) a_camera.SetPosition(0, -1, 0) a_camera.SetFocalPoint(0, 0, 0) a_camera.ComputeViewPlaneNormal() a_camera.Azimuth(30.0) a_camera.Elevation(30.0) # 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 data within the render window. # a_renderer = vtk.vtkRenderer() ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(a_renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win) # 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. a_renderer.AddActor(lens) a_renderer.AddActor(skin) a_renderer.SetActiveCamera(a_camera) a_renderer.ResetCamera() a_camera.Dolly(1.5) # Set a background color for the renderer and set the size of the # render window (expressed in pixels). a_renderer.SetBackground(colors.GetColor3d('BkgColor')) ren_win.SetSize(640, 480) ren_win.SetWindowName('TissueLens') # 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. a_renderer.ResetCameraClippingRange() # Initialize the event loop and then start it. ren_win.Render() iren.Initialize() iren.Start()
def Execute(self): if (self.Mesh == None): self.PrintError('Error: no Mesh.') if (self.Centerlines == None): self.PrintError('Error: no Centerlines') #Save the centerlines previousCenterlines = self.Centerlines cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Centerlines) cleaner.Update() self.Centerlines = cleaner.GetOutput() if self.Tolerance == -1: self.Tolerance = 0.000001*self.Mesh.GetLength() if self.RadiusArrayName != '': self.RadiusArray = self.Centerlines.GetPointData().GetArray(self.RadiusArrayName) if self.RadiusArray == None: self.PrintError('Error : could not find radius array') if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 meshMapper = vtk.vtkDataSetMapper() meshMapper.SetInput(self.Mesh) meshMapper.ScalarVisibilityOff() self.MeshActor = vtk.vtkActor() self.MeshActor.SetMapper(meshMapper) self.MeshActor.GetProperty().SetOpacity(0.25) self.MeshActor.PickableOff() self.vmtkRenderer.Renderer.AddActor(self.MeshActor) centerlinesMapper = vtk.vtkDataSetMapper() centerlinesMapper.SetInput(self.Centerlines) centerlinesMapper.ScalarVisibilityOff() self.CenterlinesActor = vtk.vtkActor() self.CenterlinesActor.SetMapper(centerlinesMapper) self.vmtkRenderer.Renderer.AddActor(self.CenterlinesActor) glyphs = vtk.vtkGlyph3D() glyphSource = vtk.vtkSphereSource() glyphSource.SetRadius(1) glyphs.SetInput(self.Spheres) glyphs.SetSource(glyphSource.GetOutput()) glyphs.SetScaleModeToScaleByScalar() glyphs.SetScaleFactor(1.) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInput(glyphs.GetOutput()) glyphMapper.ScalarVisibilityOff() self.SpheresActor = vtk.vtkActor() self.SpheresActor.SetMapper(glyphMapper) self.SpheresActor.GetProperty().SetColor(1.0,0.0,0.0) self.SpheresActor.GetProperty().SetOpacity(0.25) self.SpheresActor.PickableOff() self.vmtkRenderer.Renderer.AddActor(self.SpheresActor) self.InterpolatedGlyphs = vtk.vtkGlyph3D() interpolatedGlyphSource = vtk.vtkSphereSource() interpolatedGlyphSource.SetRadius(1) self.InterpolatedGlyphs.SetInput(self.Centerlines) self.InterpolatedGlyphs.SetSource(interpolatedGlyphSource.GetOutput()) #scaling is off for now self.InterpolatedGlyphs.SetScaleModeToDataScalingOff() self.InterpolatedGlyphs.SetScaleFactor(0.) interpolatedGlyphMapper = vtk.vtkPolyDataMapper() interpolatedGlyphMapper.SetInput(self.InterpolatedGlyphs.GetOutput()) interpolatedGlyphMapper.ScalarVisibilityOff() self.InterpolatedSpheresActor = vtk.vtkActor() self.InterpolatedSpheresActor.SetMapper(interpolatedGlyphMapper) self.InterpolatedSpheresActor.GetProperty().SetColor(0.0,1.0,0.0) self.InterpolatedSpheresActor.GetProperty().SetOpacity(0.25) self.InterpolatedSpheresActor.PickableOff() self.InterpolatedSpheresActor.VisibilityOff() self.vmtkRenderer.Renderer.AddActor(self.InterpolatedSpheresActor) polyBallMapper = vtk.vtkPolyDataMapper() polyBallMapper.ScalarVisibilityOff() self.PolyBallActor = vtk.vtkActor() self.PolyBallActor.SetMapper(polyBallMapper) self.PolyBallActor.GetProperty().SetColor(0.0,1.0,0.0) self.PolyBallActor.GetProperty().SetOpacity(0.25) self.PolyBallActor.PickableOff() self.PolyBallActor.VisibilityOff() self.vmtkRenderer.Renderer.AddActor(self.PolyBallActor) self.SphereWidget = vtk.vtkSphereWidget() self.SphereWidget.TranslationOff() self.SphereWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.SphereWidget.AddObserver("InteractionEvent", self.SphereCallback) self.Clipper = vtk.vtkClipDataSet() self.Clipper.SetInput(self.Mesh) self.Clipper.SetInsideOut(self.InsideOut) self.Clipper.GenerateClippedOutputOn() #self.LineClipper = vtkvmtk.vtkvmtkClipDataSetLine() #self.LineClipper.SetInput(self.Mesh) #self.LineClipper.SetInsideOut(self.InsideOut) #self.LineClipper.GenerateClippedOutputOn() self.InitializeSpheres() self.PreviewMesh = self.Mesh self.Display() self.PolyBallActor.VisibilityOff() self.ClipMesh() if self.ClippedMesh == None: #return an empty mesh self.ClippedMesh = vtk.vtkUnstructuredGrid() elif self.IncludeSurfaceCells: #Create the surface cells self.PreviewMesh = self.CreateSurfaceCells(self.PreviewMesh) self.ClippedMesh = self.CreateSurfaceCells(self.ClippedMesh) self.Mesh = self.PreviewMesh if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.Mesh.GetSource(): self.Mesh.GetSource().UnRegisterAllOutputs() #Restore the centerlines self.Centerlines = previousCenterlines
reader.SetFileName(objectPath) reader.Update() # plane = vtk.vtkPlane() # plane.SetOrigin(reader.GetOutput().GetCenter()) # plane.SetNormal(0.5, 0.5, 0.5) # planeClip = vtk.vtkClipDataSet() # planeClip.SetInputConnection(reader.GetOutputPort()) # planeClip.SetClipFunction(plane) sphere = vtk.vtkSphere() sphere.SetCenter(0, 0, 0) sphere.SetRadius(30) sphereClip = vtk.vtkClipDataSet() sphereClip.SetInputConnection(reader.GetOutputPort()) sphereClip.SetClipFunction(sphere) clipMapper = vtk.vtkDataSetMapper() # clipMapper.SetInputConnection(planeClip.GetOutputPort()) clipMapper.SetInputConnection(sphereClip.GetOutputPort()) clipMapper.SetScalarRange(reader.GetOutput().GetScalarRange()) actor = vtk.vtkActor() actor.SetMapper(clipMapper) # Create a rendering window and renderer renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow()
actoriso = vtk.vtkActor() actoriso.SetMapper(mapperiso) # Disable the scalar coloring mapperiso.ScalarVisibilityOff() # Set the color to black actoriso.GetProperty().SetColor(0, 0, 0) # Set the line width larger actoriso.GetProperty().SetLineWidth(2) # add the actor to the rendering renderer.AddViewProp(actoriso) # Step 7 - Clipping the data # Remove first the iso actor renderer.RemoveViewProp(actoriso) # Clip the data cf = vtk.vtkClipDataSet() # Set the clipping plane plane = vtk.vtkPlane() cf.SetClipFunction(plane) print plane # Set the plane origin plane.SetOrigin(560000, 5120000, 2000) # Connect the pipeline cf.SetInputConnection(warp.GetOutputPort()) mapper.SetInputConnection(cf.GetOutputPort()) # Step 8 - Clipping Widget interaction # Creates an implicit plane widget widget = vtk.vtkImplicitPlaneWidget() widget.PlaceWidget(warp.GetOutput().GetBounds()) widget.SetOrigin([plane.GetOrigin()[x] for x in 0, 1, 2])
aWedge.GetPointIds().SetId(5, 5) aWedge.GetPointIds().SetId(6, 6) aWedge.GetPointIds().SetId(7, 7) aWedge.GetPointIds().SetId(8, 8) aWedge.GetPointIds().SetId(9, 9) aWedge.GetPointIds().SetId(10, 10) aWedge.GetPointIds().SetId(11, 11) aWedge.GetPointIds().SetId(12, 12) aWedge.GetPointIds().SetId(13, 13) aWedge.GetPointIds().SetId(14, 14) aWedgeGrid = vtk.vtkUnstructuredGrid() aWedgeGrid.Allocate(1, 1) aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds()) aWedgeGrid.SetPoints(wedgePoints) aWedgeGrid.GetPointData().SetScalars(wedgeScalars) wedgeContours = vtk.vtkClipDataSet() wedgeContours.SetInputData(aWedgeGrid) wedgeContours.SetValue(0.5) aWedgeContourMapper = vtk.vtkDataSetMapper() aWedgeContourMapper.SetInputConnection(wedgeContours.GetOutputPort()) aWedgeContourMapper.ScalarVisibilityOff() aWedgeMapper = vtk.vtkDataSetMapper() aWedgeMapper.SetInputData(aWedgeGrid) aWedgeMapper.ScalarVisibilityOff() aWedgeActor = vtk.vtkActor() aWedgeActor.SetMapper(aWedgeMapper) aWedgeActor.GetProperty().SetRepresentationToWireframe() aWedgeActor.GetProperty().SetAmbient(1.0) aWedgeContourActor = vtk.vtkActor() aWedgeContourActor.SetMapper(aWedgeContourMapper) aWedgeContourActor.GetProperty().SetAmbient(1.0)
def __init__(self, slider_x, slider_y, slider_z, parent=None): super(VTK_Widget1, self).__init__(parent) self.source_is_connected = False self.slider_x = slider_x self.slider_y = slider_y self.slider_z = slider_z # vtk to point data self.c2p = vtk.vtkCellDataToPointData() self.opacityTransferFunction = vtk.vtkPiecewiseFunction() self.colorTransferFunction = vtk.vtkColorTransferFunction() # clip plane self.clip_plane = vtk.vtkPlane() self.clip_plane.SetNormal(0, 0, 1) self.clipper = vtk.vtkClipDataSet() self.clipper.SetClipFunction(self.clip_plane) self.clipper.SetInputConnection(self.c2p.GetOutputPort()) # create a volume property for describing how the data will look self.volumeProperty = vtk.vtkVolumeProperty() self.volumeProperty.SetColor(self.colorTransferFunction) self.volumeProperty.SetScalarOpacity(self.opacityTransferFunction) self.volumeProperty.ShadeOn() self.volumeProperty.SetInterpolationTypeToLinear() # convert to unstructured grid volume self.triangleFilter = vtk.vtkDataSetTriangleFilter() self.triangleFilter.TetrahedraOnlyOn() self.triangleFilter.SetInputConnection(self.clipper.GetOutputPort()) # create a ray cast mapper self.compositeFunction = vtk.vtkUnstructuredGridBunykRayCastFunction() self.volumeMapper = vtk.vtkUnstructuredGridVolumeRayCastMapper() self.volumeMapper.SetRayCastFunction(self.compositeFunction) self.volumeMapper.SetInputConnection(self.triangleFilter.GetOutputPort()) # create a volume self.volume = vtk.vtkVolume() self.volume.SetMapper(self.volumeMapper) self.volume.SetProperty(self.volumeProperty) self.volume.VisibilityOff() # create the VTK widget for rendering self.vtkw = QVTKRenderWindowInteractor(self) self.ren = vtk.vtkRenderer() self.vtkw.GetRenderWindow().AddRenderer(self.ren) self.ren.AddVolume(self.volume) self.alphaSlider = QSlider(Qt.Horizontal) self.alphaSlider.setValue(33) self.alphaSlider.setRange(0, 100) self.alphaSlider.setTickPosition(QSlider.NoTicks) self.connect(self.alphaSlider, SIGNAL("valueChanged(int)"), self.AdjustAlpha) self.alphaLabel = QLabel("alpha: ") # layout manager self.layout = QVBoxLayout() self.layout2 = QHBoxLayout() self.layout2.addWidget(self.alphaLabel) self.layout2.addWidget(self.alphaSlider) self.layout.addWidget(self.vtkw) self.layout.addSpacing(34) self.layout.addLayout(self.layout2) self.setLayout(self.layout) # initialize the interactor self.vtkw.Initialize() self.vtkw.Start() # Associate the line widget with the interactor self.planeWidget = vtk.vtkImplicitPlaneWidget() self.planeWidget.SetInteractor(self.vtkw) self.planeWidget.AddObserver("InteractionEvent", self.PlaneWidgetCallback) self.planeWidget.DrawPlaneOff() self.planeWidget.TubingOn()
[0.5, 0.25, 0]]) edgePoints.SetData(ntov(edgePointsCoords)) edgeScalars = vtk.vtkFloatArray() edgeScalars.SetNumberOfTuples(3) edgeScalars.InsertValue(0, 0.0) edgeScalars.InsertValue(1, 0.0) edgeScalars.InsertValue(2, 0.9) aEdge = vtk.vtkQuadraticEdge() for i in range(aEdge.GetNumberOfPoints()): aEdge.GetPointIds().SetId(i, i) aEdgeGrid = vtk.vtkUnstructuredGrid() aEdgeGrid.Allocate(1, 1) aEdgeGrid.InsertNextCell(aEdge.GetCellType(), aEdge.GetPointIds()) aEdgeGrid.SetPoints(edgePoints) aEdgeGrid.GetPointData().SetScalars(edgeScalars) edgeclips = vtk.vtkClipDataSet() edgeclips.SetInputData(aEdgeGrid) edgeclips.SetValue(0.5) aEdgeclipMapper = vtk.vtkDataSetMapper() aEdgeclipMapper.SetInputConnection(edgeclips.GetOutputPort()) aEdgeclipMapper.ScalarVisibilityOff() aEdgeMapper = vtk.vtkDataSetMapper() aEdgeMapper.SetInputData(aEdgeGrid) aEdgeMapper.ScalarVisibilityOff() aEdgeActor = vtk.vtkActor() aEdgeActor.SetMapper(aEdgeMapper) aEdgeActor.GetProperty().SetRepresentationToWireframe() aEdgeActor.GetProperty().SetAmbient(1.0) aEdgeclipActor = vtk.vtkActor() aEdgeclipActor.SetMapper(aEdgeclipMapper) aEdgeclipActor.GetProperty().BackfaceCullingOn()
def Execute(self): if (self.Mesh == None): self.PrintError('Error: no Mesh.') if (self.Centerlines == None): self.PrintError('Error: no Centerlines') #Save the centerlines previousCenterlines = self.Centerlines cleaner = vtk.vtkCleanPolyData() cleaner.SetInputData(self.Centerlines) cleaner.Update() self.Centerlines = cleaner.GetOutput() if self.Tolerance == -1: self.Tolerance = 0.000001*self.Mesh.GetLength() if self.RadiusArrayName != '': self.RadiusArray = self.Centerlines.GetPointData().GetArray(self.RadiusArrayName) if self.RadiusArray == None: self.PrintError('Error : could not find radius array') if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 meshMapper = vtk.vtkDataSetMapper() meshMapper.SetInputData(self.Mesh) meshMapper.ScalarVisibilityOff() self.MeshActor = vtk.vtkActor() self.MeshActor.SetMapper(meshMapper) self.MeshActor.GetProperty().SetOpacity(0.25) self.MeshActor.PickableOff() self.vmtkRenderer.Renderer.AddActor(self.MeshActor) centerlinesMapper = vtk.vtkDataSetMapper() centerlinesMapper.SetInputData(self.Centerlines) centerlinesMapper.ScalarVisibilityOff() self.CenterlinesActor = vtk.vtkActor() self.CenterlinesActor.SetMapper(centerlinesMapper) self.vmtkRenderer.Renderer.AddActor(self.CenterlinesActor) glyphs = vtk.vtkGlyph3D() glyphSource = vtk.vtkSphereSource() glyphSource.SetRadius(1) glyphs.SetInputData(self.Spheres) glyphs.SetSourceConnection(glyphSource.GetOutputPort()) glyphs.SetScaleModeToScaleByScalar() glyphs.SetScaleFactor(1.) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyphs.GetOutput()) glyphMapper.ScalarVisibilityOff() self.SpheresActor = vtk.vtkActor() self.SpheresActor.SetMapper(glyphMapper) self.SpheresActor.GetProperty().SetColor(1.0,0.0,0.0) self.SpheresActor.GetProperty().SetOpacity(0.25) self.SpheresActor.PickableOff() self.vmtkRenderer.Renderer.AddActor(self.SpheresActor) self.InterpolatedGlyphs = vtk.vtkGlyph3D() interpolatedGlyphSource = vtk.vtkSphereSource() interpolatedGlyphSource.SetRadius(1) self.InterpolatedGlyphs.SetInputData(self.Centerlines) self.InterpolatedGlyphs.SetSourceConnection(interpolatedGlyphSource.GetOutputPort()) #scaling is off for now self.InterpolatedGlyphs.SetScaleModeToDataScalingOff() self.InterpolatedGlyphs.SetScaleFactor(0.) interpolatedGlyphMapper = vtk.vtkPolyDataMapper() interpolatedGlyphMapper.SetInputConnection(self.InterpolatedGlyphs.GetOutputPort()) interpolatedGlyphMapper.ScalarVisibilityOff() self.InterpolatedSpheresActor = vtk.vtkActor() self.InterpolatedSpheresActor.SetMapper(interpolatedGlyphMapper) self.InterpolatedSpheresActor.GetProperty().SetColor(0.0,1.0,0.0) self.InterpolatedSpheresActor.GetProperty().SetOpacity(0.25) self.InterpolatedSpheresActor.PickableOff() self.InterpolatedSpheresActor.VisibilityOff() self.vmtkRenderer.Renderer.AddActor(self.InterpolatedSpheresActor) polyBallMapper = vtk.vtkPolyDataMapper() polyBallMapper.ScalarVisibilityOff() self.PolyBallActor = vtk.vtkActor() self.PolyBallActor.SetMapper(polyBallMapper) self.PolyBallActor.GetProperty().SetColor(0.0,1.0,0.0) self.PolyBallActor.GetProperty().SetOpacity(0.25) self.PolyBallActor.PickableOff() self.PolyBallActor.VisibilityOff() self.vmtkRenderer.Renderer.AddActor(self.PolyBallActor) self.SphereWidget = vtk.vtkSphereWidget() self.SphereWidget.TranslationOff() self.SphereWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.SphereWidget.AddObserver("InteractionEvent", self.SphereCallback) self.Clipper = vtk.vtkClipDataSet() self.Clipper.SetInputData(self.Mesh) self.Clipper.SetInsideOut(self.InsideOut) self.Clipper.GenerateClippedOutputOn() #self.LineClipper = vtkvmtk.vtkvmtkClipDataSetLine() #self.LineClipper.SetInputData(self.Mesh) #self.LineClipper.SetInsideOut(self.InsideOut) #self.LineClipper.GenerateClippedOutputOn() self.InitializeSpheres() self.PreviewMesh = self.Mesh self.Display() self.PolyBallActor.VisibilityOff() self.ClipMesh() if self.ClippedMesh == None: #return an empty mesh self.ClippedMesh = vtk.vtkUnstructuredGrid() elif self.IncludeSurfaceCells: #Create the surface cells self.PreviewMesh = self.CreateSurfaceCells(self.PreviewMesh) self.ClippedMesh = self.CreateSurfaceCells(self.ClippedMesh) self.Mesh = self.PreviewMesh if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.Mesh.GetSource(): self.Mesh.GetSource().UnRegisterAllOutputs() #Restore the centerlines self.Centerlines = previousCenterlines
def AddPolyData(self, polydata, property, thickness): doit = True if (not polydata or self.HasDataSet(polydata) or not self.Image): doit = False if doit: if thickness: self.BoxThickness = thickness clipper = vtk.vtkClipDataSet() clipper.GenerateClippedOutputOff() clipper.InsideOutOn() clipper.SetInput(polydata) direction = self.GetOrthogonalAxis(self.Orientation) if direction == vtkViewImage.X_ID: self.DataSetCutBox.SetBounds( self.DataSetCutPlane.GetOrigin()[0]-0.5*self.BoxThickness, self.DataSetCutPlane.GetOrigin()[1]+0.5*self.BoxThickness, self.GetWholeMinPosition(1), self.GetWholeMaxPosition(1), self.GetWholeMinPosition(2), self.GetWholeMaxPosition(2)) elif direction == vtkViewImage.Y_ID: self.DataSetCutBox.SetBounds( self.GetWholeMinPosition(0), self.GetWholeMaxPosition(0), self.DataSetCutPlane.GetOrigin()[0]-0.5*self.BoxThickness, self.DataSetCutPlane.GetOrigin()[1]+0.5*self.BoxThickness, self.GetWholeMinPosition(2), self.GetWholeMaxPosition(2)) elif direction == vtkViewImage.Z_ID: self.DataSetCutBox.SetBounds( self.GetWholeMinPosition(0), self.GetWholeMaxPosition(0), self.GetWholeMinPosition(1), self.GetWholeMaxPosition(1), self.DataSetCutPlane.GetOrigin()[0]-0.5*self.BoxThickness, self.DataSetCutPlane.GetOrigin()[1]+0.5*self.BoxThickness ) clipper.SetClipFunction(self.DataSetCutBox) clipper.Update() matrix = vtk.vtkMatrix4x4() for i in range(3): for j in range(3): matrix.SetElement(i,j,self.ImageReslice.GetResliceAxes().GetElement(j,i)) matrix.SetElement(3, 3, 1) mapper= vtk.vtkDataSetMapper() mapper.SetInput(clipper.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.SetUseMatrix(matrix) if property: actor.SetProperty(property) self.AddActor(actor) self.DataSetList.append(polydata) self.DataSetActorList.append(actor) self.ResetAndRestablishZoomAndCamera() del actor del mapper del matrix del clipper return self.GetDataSetActor(polydata)
aWedge.GetPointIds().SetId(5, 5) aWedge.GetPointIds().SetId(6, 6) aWedge.GetPointIds().SetId(7, 7) aWedge.GetPointIds().SetId(8, 8) aWedge.GetPointIds().SetId(9, 9) aWedge.GetPointIds().SetId(10, 10) aWedge.GetPointIds().SetId(11, 11) aWedge.GetPointIds().SetId(12, 12) aWedge.GetPointIds().SetId(13, 13) aWedge.GetPointIds().SetId(14, 14) aWedgeGrid = vtk.vtkUnstructuredGrid() aWedgeGrid.Allocate(1, 1) aWedgeGrid.InsertNextCell(aWedge.GetCellType(), aWedge.GetPointIds()) aWedgeGrid.SetPoints(wedgePoints) aWedgeGrid.GetPointData().SetScalars(wedgeScalars) wedgeContours = vtk.vtkClipDataSet() wedgeContours.SetInputData(aWedgeGrid) wedgeContours.SetValue(0.5) aWedgeContourMapper = vtk.vtkDataSetMapper() aWedgeContourMapper.SetInputConnection(wedgeContours.GetOutputPort()) aWedgeContourMapper.ScalarVisibilityOff() aWedgeMapper = vtk.vtkDataSetMapper() aWedgeMapper.SetInputData(aWedgeGrid) aWedgeMapper.ScalarVisibilityOff() aWedgeActor = vtk.vtkActor() aWedgeActor.SetMapper(aWedgeMapper) aWedgeActor.GetProperty().SetRepresentationToWireframe() aWedgeActor.GetProperty().SetAmbient(1.0) aWedgeContourActor = vtk.vtkActor() aWedgeContourActor.SetMapper(aWedgeContourMapper) aWedgeContourActor.GetProperty().SetAmbient(1.0)
def main(): filename = get_program_parameters() # Create the reader for the data. reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.Update() bounds = reader.GetOutput().GetBounds() center = reader.GetOutput().GetCenter() colors = vtk.vtkNamedColors() renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d("Wheat")) renderer.UseHiddenLineRemovalOn() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetSize(640, 480) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) xnorm = [-1.0, -1.0, 1.0] clipPlane = vtk.vtkPlane() clipPlane.SetOrigin(reader.GetOutput().GetCenter()) clipPlane.SetNormal(xnorm) clipper = vtk.vtkClipDataSet() clipper.SetClipFunction(clipPlane) clipper.SetInputData(reader.GetOutput()) clipper.SetValue(0.0) clipper.GenerateClippedOutputOn() clipper.Update() insideMapper = vtk.vtkDataSetMapper() insideMapper.SetInputData(clipper.GetOutput()) insideMapper.ScalarVisibilityOff() insideActor = vtk.vtkActor() insideActor.SetMapper(insideMapper) insideActor.GetProperty().SetDiffuseColor(colors.GetColor3d("banana")) insideActor.GetProperty().SetAmbient(.3) insideActor.GetProperty().EdgeVisibilityOn() clippedMapper = vtk.vtkDataSetMapper() clippedMapper.SetInputData(clipper.GetClippedOutput()) clippedMapper.ScalarVisibilityOff() clippedActor = vtk.vtkActor() clippedActor.SetMapper(clippedMapper) clippedActor.GetProperty().SetDiffuseColor(colors.GetColor3d("tomato")) insideActor.GetProperty().SetAmbient(.3) clippedActor.GetProperty().EdgeVisibilityOn() # Create transforms to make a better visualization insideTransform = vtk.vtkTransform() insideTransform.Translate(-(bounds[1] - bounds[0]) * 0.75, 0, 0) insideTransform.Translate(center[0], center[1], center[2]) insideTransform.RotateY(-120.0) insideTransform.Translate(-center[0], -center[1], -center[2]) insideActor.SetUserTransform(insideTransform) clippedTransform = vtk.vtkTransform() clippedTransform.Translate((bounds[1] - bounds[0]) * 0.75, 0, 0) clippedTransform.Translate(center[0], center[1], center[2]) clippedTransform.RotateY(60.0) clippedTransform.Translate(-center[0], -center[1], -center[2]) clippedActor.SetUserTransform(clippedTransform) renderer.AddViewProp(clippedActor) renderer.AddViewProp(insideActor) renderer.ResetCamera() renderer.GetActiveCamera().Dolly(1.4) renderer.ResetCameraClippingRange() renderWindow.Render() renderWindow.SetWindowName('ClipUnstructuredGridWithPlane2') renderWindow.Render() interactor.Start() # Generate a report numberOfCells = clipper.GetOutput().GetNumberOfCells() print("------------------------") print("The inside dataset contains a \n", clipper.GetOutput().GetClassName(), " that has ", numberOfCells, " cells") cellMap = dict() for i in range(0, numberOfCells): cellMap.setdefault(clipper.GetOutput().GetCellType(i), 0) cellMap[clipper.GetOutput().GetCellType(i)] += 1 # Sort by key and put into an OrderedDict. # An OrderedDict remembers the order in which the keys have been inserted. for k, v in collections.OrderedDict(sorted(cellMap.items())).items(): print("\tCell type ", vtk.vtkCellTypes.GetClassNameFromTypeId(k), " occurs ", v, " times.") numberOfCells = clipper.GetClippedOutput().GetNumberOfCells() print("------------------------") print("The clipped dataset contains a \n", clipper.GetClippedOutput().GetClassName(), " that has ", numberOfCells, " cells") outsideCellMap = dict() for i in range(0, numberOfCells): outsideCellMap.setdefault(clipper.GetClippedOutput().GetCellType(i), 0) outsideCellMap[clipper.GetClippedOutput().GetCellType(i)] += 1 for k, v in collections.OrderedDict(sorted( outsideCellMap.items())).items(): print("\tCell type ", vtk.vtkCellTypes.GetClassNameFromTypeId(k), " occurs ", v, " times.")
def main(): colors = vtk.vtkNamedColors() # Create polydata to slice the grid with. In this case, use a cone. This # could # be any polydata including a stl file. cone = vtk.vtkConeSource() cone.SetResolution(50) cone.SetDirection(0, 0, -1) cone.SetHeight(3.0) cone.CappingOn() cone.Update() # Implicit function that will be used to slice the mesh implicitPolyDataDistance = vtk.vtkImplicitPolyDataDistance() implicitPolyDataDistance.SetInput(cone.GetOutput()) # create a grid dimension = 51 xCoords = vtk.vtkFloatArray() for x, i in enumerate(np.linspace(-1.0, 1.0, dimension)): xCoords.InsertNextValue(i) yCoords = vtk.vtkFloatArray() for y, i in enumerate(np.linspace(-1.0, 1.0, dimension)): yCoords.InsertNextValue(i) zCoords = vtk.vtkFloatArray() for z, i in enumerate(np.linspace(-1.0, 1.0, dimension)): zCoords.InsertNextValue(i) # # create a grid - if not using numpy # dimension = 51 # xCoords = vtk.vtkFloatArray() # for i in range(0, dimension): # xCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1)) # # yCoords = vtk.vtkFloatArray() # for i in range(0, dimension): # yCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1)) # # zCoords = vtk.vtkFloatArray() # for i in range(0, dimension): # zCoords.InsertNextValue(-1.0 + i * 2.0 / (dimension - 1)) # The coordinates are assigned to the rectilinear grid. Make sure that # the number of values in each of the XCoordinates, YCoordinates, # and ZCoordinates is equal to what is defined in SetDimensions(). rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(xCoords.GetNumberOfTuples(), yCoords.GetNumberOfTuples(), zCoords.GetNumberOfTuples()) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(zCoords) # Create an array to hold distance information signedDistances = vtk.vtkFloatArray() signedDistances.SetNumberOfComponents(1) signedDistances.SetName('SignedDistances') # Evaluate the signed distance function at all of the grid points for pointId in range(0, rgrid.GetNumberOfPoints()): p = rgrid.GetPoint(pointId) signedDistance = implicitPolyDataDistance.EvaluateFunction(p) signedDistances.InsertNextValue(signedDistance) # Add the SignedDistances to the grid rgrid.GetPointData().SetScalars(signedDistances) # Use vtkClipDataSet to slice the grid with the polydata clipper = vtk.vtkClipDataSet() clipper.SetInputData(rgrid) clipper.InsideOutOn() clipper.SetValue(0.0) clipper.GenerateClippedOutputOn() clipper.Update() # --- mappers, actors, render, etc. --- # mapper and actor to view the cone coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(cone.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) # geometry filter to view the background grid geometryFilter = vtk.vtkRectilinearGridGeometryFilter() geometryFilter.SetInputData(rgrid) geometryFilter.SetExtent(0, dimension, 0, dimension, int(dimension / 2), int(dimension / 2)) geometryFilter.Update() rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(geometryFilter.GetOutputPort()) rgridMapper.SetScalarRange( rgrid.GetPointData().GetArray('SignedDistances').GetRange()) wireActor = vtk.vtkActor() wireActor.SetMapper(rgridMapper) wireActor.GetProperty().SetRepresentationToWireframe() # mapper and actor to view the clipped mesh clipperMapper = vtk.vtkDataSetMapper() clipperMapper.SetInputConnection(clipper.GetOutputPort()) clipperMapper.ScalarVisibilityOff() clipperOutsideMapper = vtk.vtkDataSetMapper() clipperOutsideMapper.SetInputConnection(clipper.GetOutputPort(1)) clipperOutsideMapper.ScalarVisibilityOff() clipperActor = vtk.vtkActor() clipperActor.SetMapper(clipperMapper) clipperActor.GetProperty().SetColor(colors.GetColor3d('Banana')) clipperOutsideActor = vtk.vtkActor() clipperOutsideActor.SetMapper(clipperOutsideMapper) clipperOutsideActor.GetProperty().SetColor( colors.GetColor3d('Banana')) # A renderer and render window # Create a renderer, render window, and interactor leftViewport = [0.0, 0.0, 0.5, 1.0] leftRenderer = vtk.vtkRenderer() leftRenderer.SetViewport(leftViewport) leftRenderer.SetBackground(colors.GetColor3d('SteelBlue')) rightViewport = [0.5, 0.0, 1.0, 1.0] rightRenderer = vtk.vtkRenderer() rightRenderer.SetViewport(rightViewport) rightRenderer.SetBackground(colors.GetColor3d('CadetBlue')) # add the actors leftRenderer.AddActor(wireActor) leftRenderer.AddActor(clipperActor) rightRenderer.AddActor(clipperOutsideActor) renwin = vtk.vtkRenderWindow() renwin.SetSize(640, 480) renwin.AddRenderer(leftRenderer) renwin.AddRenderer(rightRenderer) renwin.SetWindowName('ClipDataSetWithPolyData') # An interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) # Share the camera leftRenderer.GetActiveCamera().SetPosition(0, -1, 0) leftRenderer.GetActiveCamera().SetFocalPoint(0, 0, 0) leftRenderer.GetActiveCamera().SetViewUp(0, 0, 1) leftRenderer.GetActiveCamera().Azimuth(30) leftRenderer.GetActiveCamera().Elevation(30) leftRenderer.ResetCamera() rightRenderer.SetActiveCamera(leftRenderer.GetActiveCamera()) renwin.Render() interactor.Start() # Generate a report ct = vtk.vtkCellTypes() numberOfCells = clipper.GetOutput().GetNumberOfCells() print('------------------------') print('The clipped dataset(inside) contains a\n', clipper.GetOutput().GetClassName(), 'that has', numberOfCells, 'cells') cellMap = dict() for i in range(0, numberOfCells): cellMap[clipper.GetOutput().GetCellType(i)] = cellMap.get(clipper.GetOutput().GetCellType(i), 0) + 1 for k, v in cellMap.items(): print('\tCell type ', ct.GetClassNameFromTypeId(k), 'occurs', v, 'times.') numberOfCells = clipper.GetClippedOutput().GetNumberOfCells() print('------------------------') print('The clipped dataset(outside) contains a\n', clipper.GetClippedOutput().GetClassName(), 'that has', numberOfCells, 'cells') outsideCellMap = dict() for i in range(0, numberOfCells): outsideCellMap[clipper.GetClippedOutput().GetCellType(i)] = outsideCellMap.get( clipper.GetClippedOutput().GetCellType(i), 0) + 1 for k, v in outsideCellMap.items(): print('\tCell type ', ct.GetClassNameFromTypeId(k), 'occurs', v, 'times.')
def Execute(self): if self.Mesh == None: self.PrintError('Error: no Mesh.') ## if (self.FOVNormal != [0.0, 0.0, 1.0]): ## ## translation = [-self.FOVCenter[0], -self.FOVCenter[1], -self.FOVCenter[2]] ## ## referenceNormal = [0.0, 0.0, 1.0] ## rotationAxis = [0.0, 0.0, 0.0] ## vtk.vtkMath.Normalize(self.FOVNormal) ## vtk.vtkMath.Cross(self.FOVNormal,referenceNormal,rotationAxis) ## angle = self.AngleBetweenNormals(referenceNormal,self.FOVNormal) / vtk.vtkMath.Pi() * 180.0 ## ## transform = vtk.vtkTransform() ## transform.PostMultiply() ## transform.Translate(translation) ## transform.RotateWXYZ(angle,rotationAxis) ## transform.Translate(self.FOVCenter) ## ## transformFilter = vtk.vtkTransformFilter() ## transformFilter.SetInput(self.Mesh) ## transformFilter.SetTransform(transform) ## transformFilter.Update() ## ## acquiredMesh = transformFilter.GetOutput() if (self.KSpaceDimensionality == 3) or not self.SliceModel: origin = [ self.FOVCenter[0] - self.FOV[0] / 2.0, self.FOVCenter[1] - self.FOV[1] / 2.0, self.FOVCenter[2] - self.FOV[2] / 2.0 ] spacing = [ self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2] ] self.KSpace = self.AcquireKSpace(self.Mesh, origin, spacing) elif self.KSpaceDimensionality == 2: kSpaceAppend = vtk.vtkImageAppend() kSpaceAppend.SetAppendAxis(2) sliceLocations = [] sliceLocation = self.FOVCenter[2] - self.FOV[2] / 2.0 while (sliceLocation < self.FOVCenter[2] + self.FOV[2] / 2.0): sliceLocations.append(sliceLocation) sliceLocation += self.SliceSpacing spacing = [ self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2] ] bounds = self.Mesh.GetBounds() for sliceLocation in sliceLocations: self.PrintLog("Processing slice at" + float(sliceLocation)) origin = [ self.FOVCenter[0] - self.FOV[0] / 2.0, self.FOVCenter[1] - self.FOV[1] / 2.0, sliceLocation ] clipper1 = vtk.vtkClipDataSet() clipper1.SetInput(self.Mesh) clipper1.InsideOutOff() plane1 = vtk.vtkPlane() plane1.SetNormal(0.0, 0.0, 1.0) plane1.SetOrigin(0.0, 0.0, sliceLocation - self.SliceThickness / 2.0) clipper1.SetClipFunction(plane1) clipper1.Update() clipper2 = vtk.vtkClipDataSet() clipper2.SetInput(clipper1.GetOutput()) clipper2.InsideOutOn() plane2 = vtk.vtkPlane() plane2.SetNormal(0.0, 0.0, 1.0) plane2.SetOrigin(0.0, 0.0, sliceLocation + self.SliceThickness / 2.0) clipper2.SetClipFunction(plane2) clipper2.Update() clipper2Bounds = clipper2.GetOutput().GetBounds() cleaner = vtk.vtkExtractUnstructuredGrid() cleaner.SetInput(clipper2.GetOutput()) cleaner.ExtentClippingOn() cleaner.SetExtent(clipper2Bounds[0], clipper2Bounds[1], clipper2Bounds[2], clipper2Bounds[3], sliceLocation - self.SliceThickness / 2.0, sliceLocation + self.SliceThickness / 2.0) cleaner.Update() tetraFilter = vtk.vtkDataSetTriangleFilter() tetraFilter.SetInput(cleaner.GetOutput()) tetraFilter.Update() sliceMesh = tetraFilter.GetOutput() self.PrintLog("Number of integration elements:" + int(sliceMesh.GetNumberOfCells())) sliceKSpace = self.AcquireKSpace(sliceMesh, origin, spacing) kSpaceAppend.AddInput(sliceKSpace) kSpaceAppend.Update() self.KSpace = self.ComputeKSpaceOperation(kSpaceAppend.GetOutput())
def Execute(self): if self.Mesh == None: self.PrintError("Error: no Mesh.") self.Clipper = vtk.vtkClipDataSet() self.Clipper.SetInput(self.Mesh) self.Clipper.GenerateClippedOutputOn() self.Clipper.SetInsideOut(self.InsideOut) if self.Interactive: self.Planes = vtk.vtkPlanes() self.Clipper.SetClipFunction(self.Planes) self.Cutter = vtk.vtkCutter() self.Cutter.SetInput(self.Mesh) self.Cutter.SetCutFunction(self.Planes) self.ClippedMesh = vtk.vtkUnstructuredGrid() self.Surface = vtk.vtkPolyData() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) mapper = vtk.vtkDataSetMapper() mapper.SetInput(self.Mesh) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) self.BoxWidget = vtk.vtkBoxWidget() self.BoxWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.BoxWidget.GetFaceProperty().SetColor(0.6, 0.6, 0.2) self.BoxWidget.GetFaceProperty().SetOpacity(0.25) self.vmtkRenderer.AddKeyBinding("i", "Interact.", self.InteractCallback) self.vmtkRenderer.AddKeyBinding("space", "Clip.", self.ClipCallback) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate() else: self.Mesh.GetPointData().SetActiveScalars(self.ClipArrayName) self.Clipper.GenerateClipScalarsOff() self.Clipper.SetValue(self.ClipValue) self.Clipper.Update() self.Cutter = vtk.vtkContourFilter() self.Cutter.SetInput(self.Mesh) self.Cutter.SetValue(0, self.ClipValue) self.Cutter.Update() self.Mesh = self.Clipper.GetOutput() self.Surface = self.Cutter.GetOutput() self.ClippedMesh = self.Clipper.GetClippedOutput() if self.Mesh.GetSource(): self.Mesh.GetSource().UnRegisterAllOutputs()
def Execute(self): if self.Mesh == None: self.PrintError('Error: no Mesh.') ## if (self.FOVNormal != [0.0, 0.0, 1.0]): ## ## translation = [-self.FOVCenter[0], -self.FOVCenter[1], -self.FOVCenter[2]] ## ## referenceNormal = [0.0, 0.0, 1.0] ## rotationAxis = [0.0, 0.0, 0.0] ## vtk.vtkMath.Normalize(self.FOVNormal) ## vtk.vtkMath.Cross(self.FOVNormal,referenceNormal,rotationAxis) ## angle = self.AngleBetweenNormals(referenceNormal,self.FOVNormal) / vtk.vtkMath.Pi() * 180.0 ## ## transform = vtk.vtkTransform() ## transform.PostMultiply() ## transform.Translate(translation) ## transform.RotateWXYZ(angle,rotationAxis) ## transform.Translate(self.FOVCenter) ## ## transformFilter = vtk.vtkTransformFilter() ## transformFilter.SetInput(self.Mesh) ## transformFilter.SetTransform(transform) ## transformFilter.Update() ## ## acquiredMesh = transformFilter.GetOutput() if (self.KSpaceDimensionality == 3) or not self.SliceModel: origin = [self.FOVCenter[0] - self.FOV[0]/2.0, self.FOVCenter[1] - self.FOV[1]/2.0, self.FOVCenter[2] - self.FOV[2]/2.0] spacing = [self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2]] self.KSpace = self.AcquireKSpace(self.Mesh,origin,spacing) elif self.KSpaceDimensionality == 2: kSpaceAppend = vtk.vtkImageAppend() kSpaceAppend.SetAppendAxis(2) sliceLocations = [] sliceLocation = self.FOVCenter[2] - self.FOV[2]/2.0 while (sliceLocation < self.FOVCenter[2] + self.FOV[2]/2.0): sliceLocations.append(sliceLocation) sliceLocation += self.SliceSpacing spacing = [self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2]] bounds = self.Mesh.GetBounds() for sliceLocation in sliceLocations: self.PrintLog("Processing slice at" + float(sliceLocation)) origin = [self.FOVCenter[0] - self.FOV[0]/2.0, self.FOVCenter[1] - self.FOV[1]/2.0, sliceLocation] clipper1 = vtk.vtkClipDataSet() clipper1.SetInput(self.Mesh) clipper1.InsideOutOff() plane1 = vtk.vtkPlane() plane1.SetNormal(0.0,0.0,1.0) plane1.SetOrigin(0.0,0.0,sliceLocation - self.SliceThickness / 2.0) clipper1.SetClipFunction(plane1) clipper1.Update() clipper2 = vtk.vtkClipDataSet() clipper2.SetInput(clipper1.GetOutput()) clipper2.InsideOutOn() plane2 = vtk.vtkPlane() plane2.SetNormal(0.0,0.0,1.0) plane2.SetOrigin(0.0,0.0,sliceLocation + self.SliceThickness / 2.0) clipper2.SetClipFunction(plane2) clipper2.Update() clipper2Bounds = clipper2.GetOutput().GetBounds() cleaner = vtk.vtkExtractUnstructuredGrid() cleaner.SetInput(clipper2.GetOutput()) cleaner.ExtentClippingOn() cleaner.SetExtent(clipper2Bounds[0],clipper2Bounds[1], clipper2Bounds[2],clipper2Bounds[3], sliceLocation-self.SliceThickness/2.0,sliceLocation+self.SliceThickness/2.0) cleaner.Update() tetraFilter = vtk.vtkDataSetTriangleFilter() tetraFilter.SetInput(cleaner.GetOutput()) tetraFilter.Update() sliceMesh = tetraFilter.GetOutput() self.PrintLog("Number of integration elements:" + int(sliceMesh.GetNumberOfCells())) sliceKSpace = self.AcquireKSpace(sliceMesh,origin,spacing) kSpaceAppend.AddInput(sliceKSpace) kSpaceAppend.Update() self.KSpace = self.ComputeKSpaceOperation(kSpaceAppend.GetOutput())
actoriso.GetProperty().SetColor(0,0,0) # Set the line width larger actoriso.GetProperty().SetLineWidth(2) # add the actor to the rendering renderer.AddViewProp(actoriso) # Start the UI Loop iren.Initialize() renwin.Render() iren.Start() # Removes the iso actor renderer.RemoveViewProp(actoriso) # Clip the data cf = vtk.vtkClipDataSet() # Set the clipping plane plane = vtk.vtkPlane() cf.SetClipFunction(plane) print plane # Set the plane origin plane.SetOrigin(560000,5120000,2000) # Connect the pipeline cf.SetInputConnection(warp.GetOutputPort()) mapper.SetInputConnection(cf.GetOutputPort()) # Start the UI Loop iren.Initialize() renwin.Render() iren.Start()
def DisplayNodalScalarsClip(self, vector): try: if len(vector) != len(self.node): raise BaseException except: print "Input vector length does not length of nodes in class" sys.exit() myUnGrid = vtk.vtkUnstructuredGrid() myPoints = vtk.vtkPoints() myCells = vtk.vtkCellArray() Tri = False Tetra = False #define pts if len(self.node[0]) == 2: Tri = True else: Tetra = True if Tri == True: #set pts for coords in self.node: myPoints.InsertNextPoint((coords[0], coords[1], 0.0)) #set Cells for coords in self.elems: myCells.InsertNextCell(3) myCells.InsertCellPoint(coords[0]) myCells.InsertCellPoint(coords[1]) myCells.InsertCellPoint(coords[2]) myUnGrid.SetPoints(myPoints) myUnGrid.SetCells(vtk.VTK_TRIANGLE, myCells) if Tetra == True: #set pts for coords in self.node: myPoints.InsertNextPoint((coords[0], coords[1], coords[2])) #set Cells for coords in self.elems: myCells.InsertNextCell(4) myCells.InsertCellPoint(coords[0]) myCells.InsertCellPoint(coords[1]) myCells.InsertCellPoint(coords[2]) myCells.InsertCellPoint(coords[3]) myUnGrid.SetPoints(myPoints) myUnGrid.SetCells(vtk.VTK_TETRA, myCells) #scalar myScalars = vtk.vtkFloatArray() myScalars.SetNumberOfComponents(1) for i in range(0, len(vector)): myScalars.InsertNextTuple1(vector[i]) myUnGrid.GetPointData().SetScalars(myScalars) #clipping plane = vtk.vtkPlane() plane.SetOrigin(0, 0, 0) plane.SetNormal(0, 1, 0) clipper = vtk.vtkClipDataSet() clipper.SetClipFunction(plane) clipper.SetInput(myUnGrid) clipperMapper = vtk.vtkDataSetMapper() clipperMapper.SetInputConnection(clipper.GetOutputPort()) clipperMapper.SetScalarRange(np.min(vector), np.max(vector)) clipperActor = vtk.vtkActor() clipperActor.SetMapper(clipperMapper) #colorbar scalarBar = vtk.vtkScalarBarActor() scalarBar.SetTitle("Scalar Values") scalarBar.SetLookupTable(clipperMapper.GetLookupTable()) scalarBar.SetOrientationToVertical() #position bar pos = scalarBar.GetPositionCoordinate() pos.SetCoordinateSystemToNormalizedViewport() pos.SetValue(0.85, 0.05) scalarBar.SetWidth(.1) scalarBar.SetHeight(.95) ren = vtk.vtkRenderer() ren.AddActor(clipperActor) ren.AddActor(scalarBar) renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) renWin.SetSize(300, 300) renWin.Render() interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renWin) interactor.Initialize() interactor.Start()
Ids = vtk.vtkIdList() Ids.InsertNextId(0) Ids.InsertNextId(1) Ids.InsertNextId(2) Ids.InsertNextId(3) Ids.InsertNextId(4) Ids.InsertNextId(5) grid = vtk.vtkUnstructuredGrid() grid.Allocate(10, 10) grid.InsertNextCell(13, Ids) grid.SetPoints(Points) grid.GetPointData().SetScalars(Scalars) # Clip the wedge clipper = vtk.vtkClipDataSet() clipper.SetInputData(grid) clipper.SetValue(0.5) # build tubes for the triangle edges # wedgeEdges = vtk.vtkExtractEdges() wedgeEdges.SetInputConnection(clipper.GetOutputPort()) wedgeEdgeTubes = vtk.vtkTubeFilter() wedgeEdgeTubes.SetInputConnection(wedgeEdges.GetOutputPort()) wedgeEdgeTubes.SetRadius(.005) wedgeEdgeTubes.SetNumberOfSides(6) wedgeEdgeMapper = vtk.vtkPolyDataMapper() wedgeEdgeMapper.SetInputConnection(wedgeEdgeTubes.GetOutputPort()) wedgeEdgeMapper.ScalarVisibilityOff() wedgeEdgeActor = vtk.vtkActor()
center = output.GetCenter() sphere = vtk.vtkSphere() sphere.SetCenter(center) sphere.SetRadius(2.0) sphere2 = vtk.vtkSphere() sphere2.SetCenter(center[0] + 4.0, center[1], center[2]) sphere2.SetRadius(4.0) boolOp = vtk.vtkImplicitBoolean() boolOp.SetOperationTypeToUnion() boolOp.AddFunction(sphere) boolOp.AddFunction(sphere2) # clip the structured grid to produce a tetrahedral mesh clip = vtk.vtkClipDataSet() clip.SetInputData(output) clip.SetClipFunction(boolOp) clip.InsideOutOn() gf = vtk.vtkGeometryFilter() gf.SetInputConnection(clip.GetOutputPort()) clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputConnection(gf.GetOutputPort()) clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(output)
Ids = vtk.vtkIdList() Ids.InsertNextId(0) Ids.InsertNextId(1) Ids.InsertNextId(2) Ids.InsertNextId(3) Ids.InsertNextId(4) Ids.InsertNextId(5) Ids.InsertNextId(6) Ids.InsertNextId(7) Grid = vtk.vtkUnstructuredGrid() Grid.Allocate(10, 10) Grid.InsertNextCell(12, Ids) Grid.SetPoints(Points) Grid.GetPointData().SetScalars(Scalars) #Clip the hex clipper = vtk.vtkClipDataSet() clipper.SetInputData(Grid) clipper.SetValue(0.5) # build tubes for the triangle edges # tetEdges = vtk.vtkExtractEdges() tetEdges.SetInputConnection(clipper.GetOutputPort()) tetEdgeTubes = vtk.vtkTubeFilter() tetEdgeTubes.SetInputConnection(tetEdges.GetOutputPort()) tetEdgeTubes.SetRadius(.005) tetEdgeTubes.SetNumberOfSides(6) tetEdgeTubes.UseDefaultNormalOn() tetEdgeTubes.SetDefaultNormal(.577, .577, .577) tetEdgeMapper = vtk.vtkPolyDataMapper() tetEdgeMapper.SetInputConnection(tetEdgeTubes.GetOutputPort()) tetEdgeMapper.ScalarVisibilityOff()
edgePoints.InsertPoint(2, 0.5, 0.25, 0) edgeScalars = vtk.vtkFloatArray() edgeScalars.SetNumberOfTuples(3) edgeScalars.InsertValue(0, 0.0) edgeScalars.InsertValue(1, 0.0) edgeScalars.InsertValue(2, 0.9) aEdge = vtk.vtkQuadraticEdge() aEdge.GetPointIds().SetId(0, 0) aEdge.GetPointIds().SetId(1, 1) aEdge.GetPointIds().SetId(2, 2) aEdgeGrid = vtk.vtkUnstructuredGrid() aEdgeGrid.Allocate(1, 1) aEdgeGrid.InsertNextCell(aEdge.GetCellType(), aEdge.GetPointIds()) aEdgeGrid.SetPoints(edgePoints) aEdgeGrid.GetPointData().SetScalars(edgeScalars) edgeclips = vtk.vtkClipDataSet() edgeclips.SetInputData(aEdgeGrid) edgeclips.SetValue(0.5) aEdgeclipMapper = vtk.vtkDataSetMapper() aEdgeclipMapper.SetInputConnection(edgeclips.GetOutputPort()) aEdgeclipMapper.ScalarVisibilityOff() aEdgeMapper = vtk.vtkDataSetMapper() aEdgeMapper.SetInputData(aEdgeGrid) aEdgeMapper.ScalarVisibilityOff() aEdgeActor = vtk.vtkActor() aEdgeActor.SetMapper(aEdgeMapper) aEdgeActor.GetProperty().SetRepresentationToWireframe() aEdgeActor.GetProperty().SetAmbient(1.0) aEdgeclipActor = vtk.vtkActor() aEdgeclipActor.SetMapper(aEdgeclipMapper) aEdgeclipActor.GetProperty().BackfaceCullingOn()