def __init__(self, geom, ident=None): self.src = vtkContourFilter() ODE_Object.__init__(self, geom, ident) (radius, height) = geom.getParams() cylinder = vtkCylinder() cylinder.SetRadius(radius) vertPlane = vtkPlane() vertPlane.SetOrigin(0, height / 2, 0) vertPlane.SetNormal(0, 1, 0) basePlane = vtkPlane() basePlane.SetOrigin(0, -height / 2, 0) basePlane.SetNormal(0, -1, 0) sphere_1 = vtkSphere() sphere_1.SetCenter(0, -height / 2, 0) sphere_1.SetRadius(radius) sphere_2 = vtkSphere() sphere_2.SetCenter(0, height / 2, 0) sphere_2.SetRadius(radius) # Combine primitives, Clip the cone with planes. cylinder_fct = vtkImplicitBoolean() cylinder_fct.SetOperationTypeToIntersection() cylinder_fct.AddFunction(cylinder) cylinder_fct.AddFunction(vertPlane) cylinder_fct.AddFunction(basePlane) # Take a bite out of the ice cream. capsule = vtkImplicitBoolean() capsule.SetOperationTypeToUnion() capsule.AddFunction(cylinder_fct) capsule.AddFunction(sphere_1) capsule.AddFunction(sphere_2) capsule_fct = vtkSampleFunction() capsule_fct.SetImplicitFunction(capsule) capsule_fct.ComputeNormalsOff() capsule_fct.SetModelBounds(-height - radius, height + radius, -height - radius, height + radius, -height - radius, height + radius) self.src.SetInputConnection(capsule_fct.GetOutputPort()) self.src.SetValue(0, 0.0)
def sumImplicitFunc(impFunctions): impBool = vtk.vtkImplicitBoolean() impBool.SetOperationTypeToDifference() for impFunc in impFunctions: impBool.AddFunction(impFunc) return impBool
def _Clip(self, pd): # The plane implicit function will be >0 for all the points in the positive side # of the plane (i.e. x s.t. n.(x-o)>0, where n is the plane normal and o is the # plane origin). plane = vtkPlane() plane.SetOrigin(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z) plane.SetNormal(self.Iolet.Normal.x, self.Iolet.Normal.y, self.Iolet.Normal.z) # The sphere implicit function will be >0 for all the points outside the sphere. sphere = vtkSphere() sphere.SetCenter(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z) sphere.SetRadius(self.Iolet.Radius) # The VTK_INTERSECTION operator takes the maximum value of all the registered # implicit functions. This will result in the function evaluating to >0 for all # the points outside the sphere plus those inside the sphere in the positive # side of the plane. clippingFunction = vtkImplicitBoolean() clippingFunction.AddFunction(plane) clippingFunction.AddFunction(sphere) clippingFunction.SetOperationTypeToIntersection() clipper = vtkClipPolyData() clipper.SetInput(pd) clipper.SetClipFunction(clippingFunction) # Filter to get part closest to seed point connectedRegionGetter = vtkPolyDataConnectivityFilter() connectedRegionGetter.SetExtractionModeToClosestPointRegion() connectedRegionGetter.SetClosestPoint(*self.SeedPoint) connectedRegionGetter.SetInputConnection(clipper.GetOutputPort()) connectedRegionGetter.Update() return connectedRegionGetter.GetOutput()
def GenerateImplicitFunction(bounding_planes): planes = vtk.vtkImplicitBoolean() planes.SetOperationTypeToIntersection() for plane in bounding_planes: planes.AddFunction(plane) return planes
def create_sliced_skin(): plane = vtk.vtkPlane() impl_plane = vtk.vtkImplicitBoolean() impl_plane.SetOperationTypeToDifference() impl_plane.AddFunction(plane) cf = create_contour(SKIN_ISO_VALUE) cutter = vtk.vtkCutter() cutter.SetInputConnection(cf.GetOutputPort()) cutter.SetCutFunction(plane) for i in range(19): cutter.SetValue(i, i * 11) stripper = vtk.vtkStripper() stripper.SetInputConnection(cutter.GetOutputPort()) stripper.Update() tube_filter = vtk.vtkTubeFilter() tube_filter.SetInputConnection(stripper.GetOutputPort()) tube_filter.SetRadius(2.0) mapper_skin = vtk.vtkPolyDataMapper() mapper_skin.SetInputConnection(tube_filter.GetOutputPort()) mapper_skin.SetScalarVisibility(0) actor = vtk.vtkActor() actor.SetMapper(mapper_skin) actor.GetProperty().SetColor(SKIN_COLOR) return actor
def Clipper(src, dx, dy, dz): """ Clip a vtkPolyData source. A cube is made whose size corresponds the the bounds of the source. Then each side is shrunk by the appropriate dx, dy or dz. After this operation the source is clipped by the cube. :param: src - the vtkPolyData source :param: dx - the amount to clip in the x-direction :param: dy - the amount to clip in the y-direction :param: dz - the amount to clip in the z-direction :return: vtkPolyData. """ bounds = [0, 0, 0, 0, 0, 0] src.GetBounds(bounds) plane1 = vtk.vtkPlane() plane1.SetOrigin(bounds[0] + dx, 0, 0) plane1.SetNormal(1, 0, 0) plane2 = vtk.vtkPlane() plane2.SetOrigin(bounds[1] - dx, 0, 0) plane2.SetNormal(-1, 0, 0) plane3 = vtk.vtkPlane() plane3.SetOrigin(0, bounds[2] + dy, 0) plane3.SetNormal(0, 1, 0) plane4 = vtk.vtkPlane() plane4.SetOrigin(0, bounds[3] - dy, 0) plane4.SetNormal(0, -1, 0) plane5 = vtk.vtkPlane() plane5.SetOrigin(0, 0, bounds[4] + dz) plane5.SetNormal(0, 0, 1) plane6 = vtk.vtkPlane() plane6.SetOrigin(0, 0, bounds[5] - dz) plane6.SetNormal(0, 0, -1) clipFunction = vtk.vtkImplicitBoolean() clipFunction.SetOperationTypeToUnion() clipFunction.AddFunction(plane1) clipFunction.AddFunction(plane2) clipFunction.AddFunction(plane3) clipFunction.AddFunction(plane4) clipFunction.AddFunction(plane5) clipFunction.AddFunction(plane6) # Clip it. clipper = vtk.vtkClipPolyData() clipper.SetClipFunction(clipFunction) clipper.SetInputData(src) clipper.GenerateClipScalarsOff() clipper.GenerateClippedOutputOff() #clipper.GenerateClippedOutputOn() clipper.Update() return clipper.GetOutput()
def wrapOpImp(self): self.preMashCommand.data = self.mashData; self.mashData = self.preMashCommand.execute(); self.transform_one.data = self.data; import vtkMeasure; data_one = self.transform_one.perform(); measure_one = vtkMeasure.measure_factory(data_one); self.transform_two.data = self.mashData; data_two = self.transform_two.perform() measure_two = vtkMeasure.measure_factory(data_two); poly2Vops = Poly2ImageOp(); poly2Vops.data = data_one; img_data_one = poly2Vops.perform(); resoulation_one = poly2Vops.resoulation; poly2Vops.data = data_two; img_data_two = poly2Vops.perform(); resoulation_two = poly2Vops.resoulation; resoulation = [min(resoulation_one[0],resoulation_two[0]),min(resoulation_one[1],resoulation_two[1]),min(resoulation_one[2],resoulation_two[2])]; self.transform_one.data = data_one; self.transform_two.data = data_two; implicitV_One = vtk.vtkImplicitVolume(); implicitV_One.SetVolume(img_data_one); transform_one = self.transform_one.getLinkedTransform(); implicitV_One.SetTransform(transform_one.GetInverse()); implicitV_One.SetOutValue(IMAGEOUT); implicitV_Two = vtk.vtkImplicitVolume(); implicitV_Two.SetVolume(img_data_two); transform_two = self.transform_two.getLinkedTransform(); implicitV_Two.SetTransform(transform_two.GetInverse()); implicitV_Two.SetOutValue(IMAGEOUT); boolOp = vtk.vtkImplicitBoolean(); boolOp.AddFunction(implicitV_One); boolOp.AddFunction(implicitV_Two); boolOp.SetOperationTypeToUnion(); #boolOp.SetOperationTypeToDifference(); #boolOp.SetOperationTypeToIntersection(); implicit2Poly = Implicit2Poly(); import vtk2Box; xMin = min(measure_one.xSize[0],measure_two.xSize[0]); xMax = max(measure_one.xSize[1],measure_two.xSize[1]); yMin = min(measure_one.ySize[0],measure_two.ySize[0]); yMax = max(measure_one.ySize[1],measure_two.ySize[1]); zMin = min(measure_one.zSize[0],measure_two.zSize[0]); zMax = max(measure_one.zSize[1],measure_two.zSize[1]); implicit2Poly.bbox = vtk2Box.BBox(xMin,xMax,yMin,yMax,zMin,zMax); implicit2Poly.resoulation = resoulation; implicit2Poly.data = boolOp; result = implicit2Poly.perform(); return result;
def Clipper(src, dx, dy, dz): ''' Clip a vtkPolyData source. A cube is made whose size corresponds the the bounds of the source. Then each side is shrunk by the appropriate dx, dy or dz. After this operation the source is clipped by the cube. :param: src - the vtkPolyData source :param: dx - the amount to clip in the x-direction :param: dy - the amount to clip in the y-direction :param: dz - the amount to clip in the z-direction :return: vtkPolyData. ''' bounds = [0,0,0,0,0,0] src.GetBounds(bounds) plane1 = vtk.vtkPlane() plane1.SetOrigin(bounds[0] + dx, 0, 0) plane1.SetNormal(1, 0, 0) plane2 = vtk.vtkPlane() plane2.SetOrigin(bounds[1] - dx, 0, 0) plane2.SetNormal(-1, 0, 0) plane3 = vtk.vtkPlane() plane3.SetOrigin(0, bounds[2] + dy, 0) plane3.SetNormal(0, 1, 0) plane4 = vtk.vtkPlane() plane4.SetOrigin(0, bounds[3] - dy, 0) plane4.SetNormal(0, -1, 0) plane5 = vtk.vtkPlane() plane5.SetOrigin(0, 0, bounds[4] + dz) plane5.SetNormal(0, 0, 1) plane6 = vtk.vtkPlane() plane6.SetOrigin(0, 0, bounds[5] - dz) plane6.SetNormal(0, 0, -1) clipFunction = vtk.vtkImplicitBoolean() clipFunction.SetOperationTypeToUnion() clipFunction.AddFunction(plane1) clipFunction.AddFunction(plane2) clipFunction.AddFunction(plane3) clipFunction.AddFunction(plane4) clipFunction.AddFunction(plane5) clipFunction.AddFunction(plane6) # Clip it. clipper =vtk.vtkClipPolyData() clipper.SetClipFunction(clipFunction) clipper.SetInputData(src) clipper.GenerateClipScalarsOff() clipper.GenerateClippedOutputOff() #clipper.GenerateClippedOutputOn() clipper.Update() return clipper.GetOutput()
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create cylinder cylinder = vtk.vtkCylinder() cylinder.SetCenter(0, 0, 0) cylinder.SetRadius(1.0) # Create plane plane = vtk.vtkPlane() plane.SetOrigin(0, 0, 0) plane.SetNormal(0, -1, 0) # Cut the cylinder cuted_cylinder = vtk.vtkImplicitBoolean() cuted_cylinder.SetOperationTypeToIntersection() #cuted_cylinder.SetOperationTypeToUnion() cuted_cylinder.AddFunction(cylinder) cuted_cylinder.AddFunction(plane) # Sample sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(cuted_cylinder) sample.SetModelBounds(-1.5 , 1.5 , -1.5 , 1.5 , -1.5 , 1.5) sample.SetSampleDimensions(60, 60, 60) sample.SetComputeNormals(0) # surface = vtk.vtkContourFilter() #surface.SetInput(sample.GetOutput()) surface.SetInputConnection(sample.GetOutputPort()) # Create a mapper mapper = vtk.vtkPolyDataMapper() #mapper.SetInput(surface.GetOutput()) mapper.SetInputConnection(surface.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def LST_create_mirror_plane(): # create a sphere sphere = vtk.vtkSphere() sphere.SetRadius(12) sphere.SetCenter(0, 0, 0) # create a box box = vtk.vtkSphere() box.SetRadius(28.) box.SetCenter(25, 0, 0) # box = vtk.vtkBox() # box.SetBounds(-1, 1, -1, 1, -1, 1) # combine the two implicit functions boolean = vtk.vtkImplicitBoolean() boolean.SetOperationTypeToDifference() # boolean.SetOperationTypeToUnion() # boolean.SetOperationTypeToIntersection() boolean.AddFunction(sphere) boolean.AddFunction(box) # The sample function generates a distance function from the implicit # function. This is then contoured to get a polygonal surface. sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(boolean) sample.SetModelBounds(-50, 50, -50, 50, -50, 50) sample.SetSampleDimensions(200, 200, 200) sample.ComputeNormalsOff() # contour surface = vtk.vtkContourFilter() surface.SetInputConnection(sample.GetOutputPort()) surface.SetValue(0, 0.0) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) #mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) #actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetColor(tomato) # actor.SetPosition(cam_height, 0, 0) return actor
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() sphere1 = vtk.vtkSphere() sphere1.SetCenter(0.9, 0, 0) sphere2 = vtk.vtkSphere() sphere2.SetCenter(-0.9, 0, 0) implicitBoolean = vtk.vtkImplicitBoolean() implicitBoolean.AddFunction(sphere1) implicitBoolean.AddFunction(sphere2) implicitBoolean.SetOperationTypeToUnion() #implicitBoolean.SetOperationTypeToIntersection() # Sample the function sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(implicitBoolean) sample.SetModelBounds(-3, 3, -3, 3, -3, 3) # Create the 0 isosurface contours = vtk.vtkContourFilter() contours.SetInputConnection(sample.GetOutputPort()) contours.GenerateValues(1, 1, 1) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(contours.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() sphere1 = vtk.vtkSphere() sphere1.SetCenter(0.9, 0, 0) sphere2 = vtk.vtkSphere() sphere2.SetCenter(-0.9, 0, 0) implicitBoolean = vtk.vtkImplicitBoolean() implicitBoolean.AddFunction(sphere1) implicitBoolean.AddFunction(sphere2) implicitBoolean.SetOperationTypeToUnion() #implicitBoolean.SetOperationTypeToIntersection() # Sample the function sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(implicitBoolean) sample.SetModelBounds(-3, 3, -3, 3, -3, 3) # Create the 0 isosurface contours = vtk.vtkContourFilter() contours.SetInputConnection(sample.GetOutputPort()) contours.GenerateValues(1, 1, 1) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(contours.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def __init__(self, slice3dVWRThingy, implicitsGrid): self.slice3dVWR = slice3dVWRThingy self._grid = implicitsGrid # dict with name as key, values are implicitInfo classes self._implicitsDict = {} # we have to update this function when: # * a new implicit is created # * an implicit is deleted # * the user has adjusted the representative widget self.outputImplicitFunction = vtk.vtkImplicitBoolean() self.outputImplicitFunction.SetOperationTypeToUnion() self._initialiseGrid() self._setupGUI() self._bindEvents()
def getBoundaryNodes(mesh, radius1, radius2, used_nodes): numPts = mesh.GetNumberOfPoints() boundary_nodes = vtk.vtkIdList() #First get the points within a sphere on the boundaries using the boundary points as seed points for ptID in xrange(0, numPts): if (mesh.GetPointData().GetArray('GlobalBoundaryPoints').GetValue(ptID) > 0): x0, y0, z0 = mesh.GetPoint(ptID) neighbrs = vtk.vtkExtractGeometry() sphere1 = vtk.vtkSphere() sphere1.SetCenter(x0, y0, z0) sphere1.SetRadius(float(radius1)) sphere2 = vtk.vtkSphere() sphere2.SetCenter(x0, y0, z0) sphere2.SetRadius(float(radius2)) diff = vtk.vtkImplicitBoolean() diff.AddFunction(sphere2) diff.AddFunction(sphere1) diff.SetOperationTypeToDifference() neighbrs.SetImplicitFunction(sphere2) neighbrs.ExtractInsideOn() neighbrs.ExtractBoundaryCellsOn() neighbrs.SetInputData(mesh) neighbrs.Update() neighbors = vtk.vtkConnectivityFilter() neighbors.SetInputData(neighbrs.GetOutput()) neighbors.SetExtractionModeToClosestPointRegion() neighbors.SetClosestPoint(x0, y0, z0) neighbors.Update() neighbors = neighbors.GetOutput() for neighborID in xrange(0, neighbors.GetNumberOfPoints()): meshID = mesh.FindPoint(neighbors.GetPoint(neighborID)) if (used_nodes.IsId(meshID) < 0): boundary_nodes.InsertNextId(meshID) used_nodes.InsertNextId(meshID) writeVTU(neighbors, 'test_extraction.vtu') return [boundary_nodes, used_nodes]
def _Clip(self, pd): # The plane implicit function will be >0 for all the points in the positive side # of the plane (i.e. x s.t. n.(x-o)>0, where n is the plane normal and o is the # plane origin). plane = vtkPlane() plane.SetOrigin(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z) plane.SetNormal(self.Iolet.Normal.x, self.Iolet.Normal.y, self.Iolet.Normal.z) # The sphere implicit function will be >0 for all the points outside # the sphere. sphere = vtkSphere() sphere.SetCenter(self.Iolet.Centre.x, self.Iolet.Centre.y, self.Iolet.Centre.z) sphere.SetRadius(self.Iolet.Radius) # The VTK_INTERSECTION operator takes the maximum value of all the registered # implicit functions. This will result in the function evaluating to >0 for all # the points outside the sphere plus those inside the sphere in the positive # side of the plane. clippingFunction = vtkImplicitBoolean() clippingFunction.AddFunction(plane) clippingFunction.AddFunction(sphere) clippingFunction.SetOperationTypeToIntersection() clipper = vtkClipPolyData() clipper.SetInputData(pd) clipper.SetClipFunction(clippingFunction) # Filter to get part closest to seed point connectedRegionGetter = vtkPolyDataConnectivityFilter() connectedRegionGetter.SetExtractionModeToClosestPointRegion() connectedRegionGetter.SetClosestPoint(*self.SeedPoint) connectedRegionGetter.SetInputConnection(clipper.GetOutputPort()) connectedRegionGetter.Update() return connectedRegionGetter.GetOutput()
def cylinderclip(dataset, point0, point1,normal,radius): """Define cylinder. The cylinder is infinite in extent. We therefore have to truncate the cylinder using vtkImplicitBoolean in combination with 2 clipping planes located at point0 and point1. The radius of the cylinder is set to be slightly larger than 'maxradius'.""" rotationaxis = cross([0, 1, 0], normal) rotationangle = (180 / math.pi) * angle([0, 1, 0], normal) transform = vtk.vtkTransform() transform.Translate(point0) transform.RotateWXYZ(rotationangle, rotationaxis) transform.Inverse() cylinder = vtk.vtkCylinder() cylinder.SetRadius(radius) cylinder.SetTransform(transform) plane0 = vtk.vtkPlane() plane0.SetOrigin(point0) plane0.SetNormal([-x for x in normal]) plane1 = vtk.vtkPlane() plane1.SetOrigin(point1) plane1.SetNormal(normal) clipfunction = vtk.vtkImplicitBoolean() clipfunction.SetOperationTypeToIntersection() clipfunction.AddFunction(cylinder) clipfunction.AddFunction(plane0) clipfunction.AddFunction(plane1) clipper = vtk.vtkClipPolyData() clipper.SetInputData(dataset) clipper.SetClipFunction(clipfunction) clipper.Update() return extractlargestregion(clipper.GetOutput())
pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName("" + str(VTK_DATA_ROOT) + "/Data/combxyz.bin") pl3d.SetQFileName("" + str(VTK_DATA_ROOT) + "/Data/combq.bin") pl3d.SetScalarFunctionNumber(100) pl3d.SetVectorFunctionNumber(202) pl3d.Update() output = pl3d.GetOutput().GetBlock(0) # create a crazy implicit function center = output.GetCenter() sphere = vtk.vtkSphere() sphere.SetCenter(center) sphere.SetRadius(2.0) sphere2 = vtk.vtkSphere() sphere2.SetCenter(expr.expr(globals(), locals(),["lindex(center,0)","+","4.0"]),lindex(center,1),lindex(center,2)) sphere2.SetRadius(4.0) bool = vtk.vtkImplicitBoolean() bool.SetOperationTypeToUnion() bool.AddFunction(sphere) bool.AddFunction(sphere2) # clip the structured grid to produce a tetrahedral mesh clip = vtk.vtkClipDataSet() clip.SetInputData(output) clip.SetClipFunction(bool) 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()
def main(): colors = vtk.vtkNamedColors() # create a sphere sphere = vtk.vtkSphere() sphere.SetRadius(1) sphere.SetCenter(1, 0, 0) # create a box box = vtk.vtkBox() box.SetBounds(-1, 1, -1, 1, -1, 1) # combine the two implicit functions boolean = vtk.vtkImplicitBoolean() boolean.SetOperationTypeToDifference() # boolean.SetOperationTypeToUnion() # boolean.SetOperationTypeToIntersection() boolean.AddFunction(box) boolean.AddFunction(sphere) # The sample function generates a distance function from the implicit # function. This is then contoured to get a polygonal surface. sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(boolean) sample.SetModelBounds(-1, 2, -1, 1, -1, 1) sample.SetSampleDimensions(40, 40, 40) sample.ComputeNormalsOff() # contour surface = vtk.vtkContourFilter() surface.SetInputConnection(sample.GetOutputPort()) surface.SetValue(0, 0.0) # mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().EdgeVisibilityOn() actor.GetProperty().SetColor(colors.GetColor3d('AliceBlue')) actor.GetProperty().SetEdgeColor(colors.GetColor3d('SteelBlue')) # A renderer and render window renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d('Silver')) # add the actor renderer.AddActor(actor) # render window renwin = vtk.vtkRenderWindow() renwin.AddRenderer(renderer) # An interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) # Start interactor.Initialize() renwin.Render() # renderer.GetActiveCamera().AddObserver('ModifiedEvent', CameraModifiedCallback) renderer.GetActiveCamera().SetPosition(5.0, -4.0, 1.6) renderer.GetActiveCamera().SetViewUp(0.1, 0.5, 0.9) renderer.GetActiveCamera().SetDistance(6.7) renwin.Render() interactor.Start()
def makeModels(self): """ make vtk model """ # Here we create two ellipsoidal implicit functions and boolean them # together to form a "cross" shaped implicit function. quadric = vtk.vtkQuadric() quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0) sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(quadric) sample.ComputeNormalsOff() trans = vtk.vtkTransform() trans.Scale(1, .5, .333) sphere = vtk.vtkSphere() sphere.SetRadius(self.radius) sphere.SetTransform(trans) trans2 = vtk.vtkTransform() trans2.Scale(.25, .5, 1.0) sphere2 = vtk.vtkSphere() sphere2.SetRadius(self.radius) sphere2.SetTransform(trans2) self.sphere_geom_1 = sphere self.sphere_geom_2 = sphere2 union = vtk.vtkImplicitBoolean() union.AddFunction(sphere) union.AddFunction(sphere2) union.SetOperationType(0) # Here is where it gets interesting. The implicit function is used to # extract those cells completely inside the function. They are then # shrunk to helpr show what was extracted. extract = vtk.vtkExtractGeometry() extract.SetInputConnection(sample.GetOutputPort()) extract.SetImplicitFunction(union) shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(extract.GetOutputPort()) shrink.SetShrinkFactor(self.shrink_factor) dataMapper = vtk.vtkDataSetMapper() dataMapper.SetInputConnection(shrink.GetOutputPort()) self.shrink_geom = shrink # data actor self.data_actor = vtk.vtkActor() self.data_actor.SetMapper(dataMapper) # The outline gives context to the original data. outline = vtk.vtkOutlineFilter() outline.SetInputConnection(sample.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) # outline actor self.outline_actor = vtk.vtkActor() self.outline_actor.SetMapper(outlineMapper) outlineProp = self.outline_actor.GetProperty() outlineProp.SetColor(0, 0, 0)
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Construct a Cylinder from (x1, y1, z1) to (x2, y2, z2), the inner and outer radius r1, r2 x1, y1, z1 = 10, 2, 3 x2, y2, z2 = 10, 20, 30 r1, r2 = 3, 8 dx, dy, dz = x2-x1, y2-y1, z2-z1 # create axis object axisSource = vtk.vtkLineSource() axisSource = vtk.vtkLineSource() axisSource.SetPoint1(x1, y1, z1) axisSource.SetPoint2(x2, y2, z2) axisMapper = vtk.vtkPolyDataMapper() axisMapper.SetInputConnection(axisSource.GetOutputPort()) axisActor = vtk.vtkActor() axisActor.GetProperty().SetColor(0, 0, 1) axisActor.SetMapper(axisMapper) self.ren.AddActor(axisActor) # Create planes plane1 = vtk.vtkPlane() plane1.SetOrigin(x1, y1, z1) plane1.SetNormal(-dx, -dy, -dz) plane2 = vtk.vtkPlane() plane2.SetOrigin(x2, y2, z2) plane2.SetNormal(dx, dy, dz) # Create cylinders out_cylinder = vtk.vtkCylinder() out_cylinder.SetCenter(0, 0, 0) out_cylinder.SetRadius(r2) in_cylinder = vtk.vtkCylinder() in_cylinder.SetCenter(0, 0, 0) in_cylinder.SetRadius(r1) # The rotation axis of cylinder is along the y-axis # What we need is the axis (x2-x1, y2-y1, z2-z1) angle = math.acos(dy/math.sqrt(dx**2 + dy**2 + dz**2)) * 180.0 / math.pi transform = vtk.vtkTransform() transform.RotateWXYZ(-angle, dz, 1, -dx) transform.Translate(-x1, -y1, -z1) out_cylinder.SetTransform(transform) in_cylinder.SetTransform(transform) # Cutted object cuted = vtk.vtkImplicitBoolean() cuted.SetOperationTypeToIntersection() cuted.AddFunction(out_cylinder) cuted.AddFunction(plane1) cuted.AddFunction(plane2) cuted2 = vtk.vtkImplicitBoolean() cuted2.SetOperationTypeToDifference() cuted2.AddFunction(cuted) cuted2.AddFunction(in_cylinder) # Sample sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(cuted2) sample.SetModelBounds(-100 , 100 , -100 , 100 , -100 , 100) sample.SetSampleDimensions(300, 300, 300) sample.SetComputeNormals(0) # Filter surface = vtk.vtkContourFilter() surface.SetInputConnection(sample.GetOutputPort()) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
# Create a cylinder cyl = vtk.vtkCylinder() cyl.SetCenter(-2, 0, 0) cyl.SetRadius(0.02) # Create a (thin) box implicit function box = vtk.vtkBox() box.SetBounds(-1, 0.5, -0.5, 0.5, -0.0005, 0.0005) # Create a sphere implicit function sphere = vtk.vtkSphere() sphere.SetCenter(2, 0, 0) sphere.SetRadius(0.8) # Boolean (union) these together imp = vtk.vtkImplicitBoolean() imp.SetOperationTypeToUnion() imp.AddFunction(cyl) imp.AddFunction(box) imp.AddFunction(sphere) # Extract points along sphere surface extract = vtk.vtkFitImplicitFunction() extract.SetInputConnection(points.GetOutputPort()) extract.SetImplicitFunction(imp) extract.SetThreshold(0.0005) extract.Update() # Now generate normals from resulting points curv = vtk.vtkPCACurvatureEstimation() curv.SetInputConnection(extract.GetOutputPort())
pl3d.SetVectorFunctionNumber(202) pl3d.Update() output = pl3d.GetOutput().GetBlock(0) # create a crazy implicit function 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())
vertPlane.SetNormal(-1, 0, 0) basePlane = vtk.vtkPlane() basePlane.SetOrigin(1.2, 0, 0) basePlane.SetNormal(1, 0, 0) iceCream = vtk.vtkSphere() iceCream.SetCenter(1.333, 0, 0) iceCream.SetRadius(0.5) bite = vtk.vtkSphere() bite.SetCenter(1.5, 0, 0.5) bite.SetRadius(0.25) # combine primitives to build ice-cream cone theCone = vtk.vtkImplicitBoolean() theCone.SetOperationTypeToIntersection() theCone.AddFunction(cone) theCone.AddFunction(vertPlane) theCone.AddFunction(basePlane) theCream = vtk.vtkImplicitBoolean() theCream.SetOperationTypeToDifference() theCream.AddFunction(iceCream) theCream.AddFunction(bite) # iso-surface to create geometry theConeSample = vtk.vtkSampleFunction() theConeSample.SetImplicitFunction(theCone) theConeSample.SetModelBounds(-1, 1.5, -1.25, 1.25, -1.25, 1.25) theConeSample.SetSampleDimensions(60, 60, 60)
for i in range(len(spheres)): spheres[i] = vtk.vtkSphere() spheres[i].SetCenter(sTubeX[i], sTubeY[i], sTubeZ[i]) spheres[i].SetRadius(scalars[0]) cyls = [None]*len(tPairs) for c in range(len(cyls)): icyl = vtk.vtkCylinder() p1 = vtk.vtkPlane() p1.SetOrigin(sTubeX[tPairs[c][0]],sTubeY[tPairs[c][0]],sTubeZ[tPairs[c][0]]) p1.SetNormal(sTubeX[tPairs[c][1]] - sTubeX[tPairs[c][0]],sTubeY[tPairs[c][1]] - sTubeY[tPairs[c][0]],sTubeZ[tPairs[c][1]] - sTubeZ[tPairs[c][0]]) p2 = vtk.vtkPlane() p2.SetOrigin(sTubeX[tPairs[c][1]],sTubeY[tPairs[c][1]],sTubeZ[tPairs[c][1]]) p2.SetNormal(sTubeX[tPairs[c][0]] - sTubeX[tPairs[c][1]],sTubeY[tPairs[c][0]] - sTubeY[tPairs[c][1]],sTubeZ[tPairs[c][0]] - sTubeZ[tPairs[c][1]]) ccyl = vtk.vtkImplicitBoolean() ccyl.SetOperationTypeToIntersection() ccyl.AddFunction(icyl) ccyl.AddFunction(p1) ccyl.AddFunction(p2) print np.shape(pairs) print np.shape(positions) tube = vtk.vtkImplicitBoolean() tube.SetOperationTypeToUnion() for s in spheres: tube.AddFunction(s)
def main(): colors = vtk.vtkNamedColors() ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) quadric = vtk.vtkQuadric() quadric.SetCoefficients(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0) sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(quadric) sample.ComputeNormalsOff() trans = vtk.vtkTransform() trans.Scale(1, 0.5, 0.333) sphere = vtk.vtkSphere() sphere.SetRadius(0.25) sphere.SetTransform(trans) trans2 = vtk.vtkTransform() trans2.Scale(0.25, 0.5, 1.0) sphere2 = vtk.vtkSphere() sphere2.SetRadius(0.25) sphere2.SetTransform(trans2) booleanUnion = vtk.vtkImplicitBoolean() booleanUnion.AddFunction(sphere) booleanUnion.AddFunction(sphere2) booleanUnion.SetOperationType(0) # boolean Union extract = vtk.vtkExtractGeometry() extract.SetInputConnection(sample.GetOutputPort()) extract.SetImplicitFunction(booleanUnion) shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(extract.GetOutputPort()) shrink.SetShrinkFactor(0.5) dataMapper = vtk.vtkDataSetMapper() dataMapper.SetInputConnection(shrink.GetOutputPort()) dataActor = vtk.vtkActor() dataActor.SetMapper(dataMapper) # outline outline = vtk.vtkOutlineFilter() outline.SetInputConnection(sample.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(0, 0, 0) # Add the actors to the renderer, set the background and size # ren1.AddActor(outlineActor) ren1.AddActor(dataActor) ren1.SetBackground(colors.GetColor3d("SlateGray")) renWin.SetSize(640, 480) renWin.SetWindowName('ExtractData') renWin.Render() ren1.GetActiveCamera().Azimuth(30) ren1.GetActiveCamera().Elevation(30) renWin.Render() iren.Start()
def normal(mcBone, mcSkin): """ Create the default visualisation of the skin. A sphere is clipping the skin near the articulation and is slightly visible using a low opacity. Args: mcBone: vtkMarchingCubes used to create the bone mcSkin: vtkMarchingCubes used to create the skin Returns: vtkAssembly """ # Create a sphere for clipping sphere = vtk.vtkSphere() sphere.SetCenter(80, 20, 120) sphere.SetRadius(60) theSphere = vtk.vtkImplicitBoolean() theSphere.SetOperationTypeToDifference() theSphere.AddFunction(sphere) # Display the sphere theSphereSample = vtk.vtkSampleFunction() theSphereSample.SetImplicitFunction(theSphere) theSphereSample.SetModelBounds(-1000, 1000, -1000, 1000, -1000, 1000) theSphereSample.SetSampleDimensions(120, 120, 120) theSphereSample.ComputeNormalsOff() theSphereSurface = vtk.vtkContourFilter() theSphereSurface.SetInputConnection(theSphereSample.GetOutputPort()) theSphereSurface.SetValue(0, 0.0) mapperSphere = vtk.vtkPolyDataMapper() mapperSphere.SetInputConnection(theSphereSurface.GetOutputPort()) mapperSphere.ScalarVisibilityOff() actorSphere = vtk.vtkActor() actorSphere.SetMapper(mapperSphere) actorSphere.GetProperty().SetColor(white) actorSphere.GetProperty().SetOpacity(0.1) # Clip skin with a sphere clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(mcSkin.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.SetValue(1) clipper.Update() # Skin mapper and actor mapperSkin = vtk.vtkDataSetMapper() mapperSkin.SetInputConnection(clipper.GetOutputPort()) mapperSkin.ScalarVisibilityOff() actorSkin = vtk.vtkActor() actorSkin.SetMapper(mapperSkin) actorSkin.GetProperty().SetColor(0.95, 0.64, 0.64) # Bone mapper and actor mapperBone = vtk.vtkDataSetMapper() mapperBone.SetInputConnection(mcBone.GetOutputPort()) mapperBone.ScalarVisibilityOff() actorBone = vtk.vtkActor() actorBone.SetMapper(mapperBone) actorBone.GetProperty().SetColor(0.9, 0.9, 0.9) # Group the actors assembly = vtk.vtkAssembly() assembly.AddPart(actorSkin) assembly.AddPart(actorBone) assembly.AddPart(actorSphere) return assembly
renderWindowInteractor.SetRenderWindow(renwin) renwin.Render() # Enable user interface interactor. renderWindowInteractor.Initialize() renwin.Render() renderWindowInteractor.Start() if __name__ == '__main__': reader = read_SLC_file('vw_knee.slc') sphere, sphere_source = create_sphere(50, (60, 50, 105)) impl_sphere = vtk.vtkImplicitBoolean() impl_sphere.SetOperationTypeToDifference() impl_sphere.AddFunction(sphere) # Create mappers and actors. # Knee with lot of transparent slices actor_sliced = create_sliced_skin() # Knee with opacity on front-face and a sphere to see the patella actor_opaque = create_skin(impl_sphere) inside_skin = vtk.vtkProperty() inside_skin.SetColor(SKIN_COLOR) actor_opaque.SetBackfaceProperty(inside_skin) actor_opaque.GetProperty().SetOpacity(0.5)
def getModelROIStencil(self): import time _t0 = time.time() t1 = self.__Transform.GetInverse() roi_type = self.getModelROIType() roi_orientation = self.getModelROIOrientation() # bounds, extent and center b = self.getModelROIBounds() # abort early if we haven't been fully set up yet if b is None: return None # determine transformed boundary _index = [ [0, 2, 4], [0, 2, 5], [0, 3, 4], [0, 3, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], ] b_t = [1e38, -1e38, 1e38, -1e38, 1e38, -1e38] is_identity = True # is transform identity? is_identity = self.__Transform.GetMatrix().Determinant() == 1.0 #is_identity = False for i in range(8): i2 = _index[i] pt = [b[i2[0]], b[i2[1]], b[i2[2]]] _temp = self.__Transform.TransformPoint(pt[0], pt[1], pt[2]) b_t[0] = min(_temp[0], b_t[0]) b_t[1] = max(_temp[0], b_t[1]) b_t[2] = min(_temp[1], b_t[2]) b_t[3] = max(_temp[1], b_t[3]) b_t[4] = min(_temp[2], b_t[4]) b_t[5] = max(_temp[2], b_t[5]) e_t = self._BoundsToExtent(b_t) # sanity check - check for inversion (caused by negative spacing) e_t = list(e_t) for i in range(3): if e_t[i * 2] > e_t[i * 2 + 1]: v = e_t[i * 2] e_t[i * 2] = e_t[i * 2 + 1] e_t[i * 2 + 1] = v # expand stencil extent by one pixel on all sides e_t = (e_t[0] - 1, e_t[1] + 1, e_t[2] - 1, e_t[3] + 1, e_t[4] - 1, e_t[5] + 1) # make sure we're dealing with ints e_t = map(int, e_t) if is_identity: # fast, but limited to canonical objects self._StencilGenerator = vtk.vtkROIStencilSource() else: # slow, but more generic self._StencilGenerator = vtk.vtkImplicitFunctionToImageStencil() self._StencilGenerator.SetOutputOrigin(self.getImageOrigin()) self._StencilGenerator.SetOutputSpacing(self.getImageSpacing()) # set extent of stencil - taking into account transformation self._StencilGenerator.SetOutputWholeExtent(e_t) if is_identity: # use DG's fast routines if roi_type == 'box': self._StencilGenerator.SetShapeToBox() elif roi_type == 'cylinder': if roi_orientation == 'X': self._StencilGenerator.SetShapeToCylinderX() elif roi_orientation == 'Y': self._StencilGenerator.SetShapeToCylinderY() elif roi_orientation == 'Z': self._StencilGenerator.SetShapeToCylinderZ() elif roi_type == 'ellipsoid': self._StencilGenerator.SetShapeToEllipsoid() self._StencilGenerator.SetBounds(b) else: # use JG's slow routines if roi_type == 'box': obj = vtk.vtkBox() obj.SetTransform(t1) obj.SetBounds(b) elif roi_type == 'cylinder': cyl = vtk.vtkCylinder() cyl.SetRadius(1.0) xc, yc, zc = (b[1] + b[0]) * \ 0.5, (b[3] + b[2]) * 0.5, (b[5] + b[4]) * 0.5 diam_a, diam_b, diam_c = ( b[1] - b[0]), (b[3] - b[2]), (b[5] - b[4]) # The cylinder is infinite in extent, so needs to be cropped by using the intersection # of three implicit functions -- the cylinder, and two cropping # planes obj = vtk.vtkImplicitBoolean() obj.SetOperationTypeToIntersection() obj.AddFunction(cyl) clip1 = vtk.vtkPlane() clip1.SetNormal(0, 1, 0) obj.AddFunction(clip1) clip2 = vtk.vtkPlane() clip2.SetNormal(0, -1, 0) obj.AddFunction(clip2) t2 = vtk.vtkTransform() t2.Translate(xc, yc, zc) if roi_orientation == 'X': # cylinder is infinite in extent in the y-axis t2.Scale(1, diam_b / 2.0, diam_c / 2.0) t2.RotateZ(90) r = diam_a / 2.0 elif roi_orientation == 'Y': # cylinder is infinite in extent in the y-axis t2.Scale(diam_a / 2.0, 1, diam_c / 2.0) r = diam_b / 2.0 elif roi_orientation == 'Z': # cylinder is infinite in extent in the y-axis t2.Scale(diam_a / 2.0, diam_b / 2.0, 1) t2.RotateX(90) r = diam_c / 2.0 clip1.SetOrigin(0, r, 0) clip2.SetOrigin(0, -r, 0) # combine transforms t2.SetInput(self.__Transform) obj.SetTransform(t2.GetInverse()) elif roi_type == 'ellipsoid': obj = vtk.vtkSphere() obj.SetRadius(1.0) xc, yc, zc = (b[1] + b[0]) * \ 0.5, (b[3] + b[2]) * 0.5, (b[5] + b[4]) * 0.5 diam_a, diam_b, diam_c = ( b[1] - b[0]), (b[3] - b[2]), (b[5] - b[4]) t2 = vtk.vtkTransform() t2.Translate(xc, yc, zc) t2.Scale(diam_a / 2.0, diam_b / 2.0, diam_c / 2.0) # combine transforms t2.SetInput(self.__Transform) obj.SetTransform(t2.GetInverse()) self._StencilGenerator.SetInput(obj) _t1 = time.time() self._StencilGenerator.Update() _t2 = time.time() return self._StencilGenerator.GetOutput()
def main(): colors = vtk.vtkNamedColors() # Create implicit function primitives. These have been carefully placed to # give the effect that we want. We are going to use various combinations of # these functions to create the shape we want for example, we use planes # intersected with a cone (which is infinite in extent) to get a finite # cone. # cone = vtk.vtkCone() cone.SetAngle(20) vertPlane = vtk.vtkPlane() vertPlane.SetOrigin(.1, 0, 0) vertPlane.SetNormal(-1, 0, 0) basePlane = vtk.vtkPlane() basePlane.SetOrigin(1.2, 0, 0) basePlane.SetNormal(1, 0, 0) iceCream = vtk.vtkSphere() iceCream.SetCenter(1.333, 0, 0) iceCream.SetRadius(0.5) bite = vtk.vtkSphere() bite.SetCenter(1.5, 0, 0.5) bite.SetRadius(0.25) # Combine primitives to build ice-cream cone. Clip the cone with planes. theCone = vtk.vtkImplicitBoolean() theCone.SetOperationTypeToIntersection() theCone.AddFunction(cone) theCone.AddFunction(vertPlane) theCone.AddFunction(basePlane) # Take a bite out of the ice cream. theCream = vtk.vtkImplicitBoolean() theCream.SetOperationTypeToDifference() theCream.AddFunction(iceCream) theCream.AddFunction(bite) # The sample function generates a distance function from the # implicit function (which in this case is the cone). This is # then contoured to get a polygonal surface. # theConeSample = vtk.vtkSampleFunction() theConeSample.SetImplicitFunction(theCone) theConeSample.SetModelBounds(-1, 1.5, -1.25, 1.25, -1.25, 1.25) theConeSample.SetSampleDimensions(128, 128, 128) theConeSample.ComputeNormalsOff() theConeSurface = vtk.vtkContourFilter() theConeSurface.SetInputConnection(theConeSample.GetOutputPort()) theConeSurface.SetValue(0, 0.0) coneMapper = vtk.vtkPolyDataMapper() coneMapper.SetInputConnection(theConeSurface.GetOutputPort()) coneMapper.ScalarVisibilityOff() coneActor = vtk.vtkActor() coneActor.SetMapper(coneMapper) coneActor.GetProperty().SetColor(colors.GetColor3d("chocolate")) # The same here for the ice cream. # theCreamSample = vtk.vtkSampleFunction() theCreamSample.SetImplicitFunction(theCream) theCreamSample.SetModelBounds(0, 2.5, -1.25, 1.25, -1.25, 1.25) theCreamSample.SetSampleDimensions(128, 128, 128) theCreamSample.ComputeNormalsOff() theCreamSurface = vtk.vtkContourFilter() theCreamSurface.SetInputConnection(theCreamSample.GetOutputPort()) theCreamSurface.SetValue(0, 0.0) creamMapper = vtk.vtkPolyDataMapper() creamMapper.SetInputConnection(theCreamSurface.GetOutputPort()) creamMapper.ScalarVisibilityOff() creamActor = vtk.vtkActor() creamActor.SetMapper(creamMapper) creamActor.GetProperty().SetDiffuseColor(colors.GetColor3d("mint")) creamActor.GetProperty().SetSpecular(.6) creamActor.GetProperty().SetSpecularPower(50) # Create the usual rendering stuff. # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size. # ren1.AddActor(coneActor) ren1.AddActor(creamActor) ren1.SetBackground(colors.GetColor3d("SlateGray")) renWin.SetSize(640, 480) ren1.ResetCamera() ren1.GetActiveCamera().Roll(90) ren1.GetActiveCamera().Dolly(1.25) ren1.ResetCameraClippingRange() iren.Initialize() # render the image # renWin.Render() iren.Start()
def main(): colors = vtk.vtkNamedColors() # Demonstrate the use of clipping on polygonal data # # create pipeline # plane = vtk.vtkPlaneSource() plane.SetXResolution(25) plane.SetYResolution(25) plane.SetOrigin(-1, -1, 0) plane.SetPoint1(1, -1, 0) plane.SetPoint2(-1, 1, 0) transformSphere = vtk.vtkTransform() transformSphere.Identity() transformSphere.Translate(0.4, -0.4, 0) transformSphere.Inverse() sphere = vtk.vtkSphere() sphere.SetTransform(transformSphere) sphere.SetRadius(.5) transformCylinder = vtk.vtkTransform() transformCylinder.Identity() transformCylinder.Translate(-0.4, 0.4, 0) transformCylinder.RotateZ(30) transformCylinder.RotateY(60) transformCylinder.RotateX(90) transformCylinder.Inverse() cylinder = vtk.vtkCylinder() cylinder.SetTransform(transformCylinder) cylinder.SetRadius(.3) boolean = vtk.vtkImplicitBoolean() boolean.AddFunction(cylinder) boolean.AddFunction(sphere) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(plane.GetOutputPort()) clipper.SetClipFunction(boolean) clipper.GenerateClippedOutputOn() clipper.GenerateClipScalarsOn() clipper.SetValue(0) clipMapper = vtk.vtkPolyDataMapper() clipMapper.SetInputConnection(clipper.GetOutputPort()) clipMapper.ScalarVisibilityOff() clipActor = vtk.vtkActor() clipActor.SetMapper(clipMapper) clipActor.GetProperty().SetDiffuseColor(colors.GetColor3d("Black")) clipActor.GetProperty().SetRepresentationToWireframe() clipInsideMapper = vtk.vtkPolyDataMapper() clipInsideMapper.SetInputData(clipper.GetClippedOutput()) clipInsideMapper.ScalarVisibilityOff() clipInsideActor = vtk.vtkActor() clipInsideActor.SetMapper(clipInsideMapper) clipInsideActor.GetProperty().SetDiffuseColor( colors.GetColor3d("Dim_Gray")) # Create graphics stuff # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren1.AddActor(clipActor) ren1.AddActor(clipInsideActor) ren1.SetBackground(colors.GetColor3d("Wheat")) ren1.ResetCamera() ren1.GetActiveCamera().Dolly(1.4) ren1.ResetCameraClippingRange() renWin.SetSize(640, 480) # render the image # renWin.Render() iren.Start()
def getModelROIStencil(self): import time _t0 = time.time() t1 = self.__Transform.GetInverse() roi_type = self.getModelROIType() roi_orientation = self.getModelROIOrientation() # bounds, extent and center b = self.getModelROIBounds() # abort early if we haven't been fully set up yet if b is None: return None # determine transformed boundary _index = [[0, 2, 4], [0, 2, 5], [0, 3, 4], [0, 3, 5], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5]] b_t = [1e38, -1e38, 1e38, -1e38, 1e38, -1e38] is_identity = True # is transform identity? is_identity = self.__Transform.GetMatrix().Determinant() == 1.0 # is_identity = False for i in range(8): i2 = _index[i] pt = [b[i2[0]], b[i2[1]], b[i2[2]]] _temp = self.__Transform.TransformPoint(pt[0], pt[1], pt[2]) b_t[0] = min(_temp[0], b_t[0]) b_t[1] = max(_temp[0], b_t[1]) b_t[2] = min(_temp[1], b_t[2]) b_t[3] = max(_temp[1], b_t[3]) b_t[4] = min(_temp[2], b_t[4]) b_t[5] = max(_temp[2], b_t[5]) e_t = self._BoundsToExtent(b_t) # sanity check - check for inversion (caused by negative spacing) e_t = list(e_t) for i in range(3): if e_t[i * 2] > e_t[i * 2 + 1]: v = e_t[i * 2] e_t[i * 2] = e_t[i * 2 + 1] e_t[i * 2 + 1] = v # expand stencil extent by one pixel on all sides e_t = (e_t[0] - 1, e_t[1] + 1, e_t[2] - 1, e_t[3] + 1, e_t[4] - 1, e_t[5] + 1) # make sure we're dealing with ints e_t = map(int, e_t) if is_identity: # fast, but limited to canonical objects self._StencilGenerator = vtk.vtkROIStencilSource() else: # slow, but more generic self._StencilGenerator = vtk.vtkImplicitFunctionToImageStencil() self._StencilGenerator.SetOutputOrigin(self.getImageOrigin()) self._StencilGenerator.SetOutputSpacing(self.getImageSpacing()) # set extent of stencil - taking into account transformation self._StencilGenerator.SetOutputWholeExtent(e_t) if is_identity: # use DG's fast routines if roi_type == "box": self._StencilGenerator.SetShapeToBox() elif roi_type == "cylinder": if roi_orientation == "X": self._StencilGenerator.SetShapeToCylinderX() elif roi_orientation == "Y": self._StencilGenerator.SetShapeToCylinderY() elif roi_orientation == "Z": self._StencilGenerator.SetShapeToCylinderZ() elif roi_type == "ellipsoid": self._StencilGenerator.SetShapeToEllipsoid() self._StencilGenerator.SetBounds(b) else: # use JG's slow routines if roi_type == "box": obj = vtk.vtkBox() obj.SetTransform(t1) obj.SetBounds(b) elif roi_type == "cylinder": cyl = vtk.vtkCylinder() cyl.SetRadius(1.0) xc, yc, zc = (b[1] + b[0]) * 0.5, (b[3] + b[2]) * 0.5, (b[5] + b[4]) * 0.5 diam_a, diam_b, diam_c = (b[1] - b[0]), (b[3] - b[2]), (b[5] - b[4]) # The cylinder is infinite in extent, so needs to be cropped by using the intersection # of three implicit functions -- the cylinder, and two cropping # planes obj = vtk.vtkImplicitBoolean() obj.SetOperationTypeToIntersection() obj.AddFunction(cyl) clip1 = vtk.vtkPlane() clip1.SetNormal(0, 1, 0) obj.AddFunction(clip1) clip2 = vtk.vtkPlane() clip2.SetNormal(0, -1, 0) obj.AddFunction(clip2) t2 = vtk.vtkTransform() t2.Translate(xc, yc, zc) if roi_orientation == "X": # cylinder is infinite in extent in the y-axis t2.Scale(1, diam_b / 2.0, diam_c / 2.0) t2.RotateZ(90) r = diam_a / 2.0 elif roi_orientation == "Y": # cylinder is infinite in extent in the y-axis t2.Scale(diam_a / 2.0, 1, diam_c / 2.0) r = diam_b / 2.0 elif roi_orientation == "Z": # cylinder is infinite in extent in the y-axis t2.Scale(diam_a / 2.0, diam_b / 2.0, 1) t2.RotateX(90) r = diam_c / 2.0 clip1.SetOrigin(0, r, 0) clip2.SetOrigin(0, -r, 0) # combine transforms t2.SetInput(self.__Transform) obj.SetTransform(t2.GetInverse()) elif roi_type == "ellipsoid": obj = vtk.vtkSphere() obj.SetRadius(1.0) xc, yc, zc = (b[1] + b[0]) * 0.5, (b[3] + b[2]) * 0.5, (b[5] + b[4]) * 0.5 diam_a, diam_b, diam_c = (b[1] - b[0]), (b[3] - b[2]), (b[5] - b[4]) t2 = vtk.vtkTransform() t2.Translate(xc, yc, zc) t2.Scale(diam_a / 2.0, diam_b / 2.0, diam_c / 2.0) # combine transforms t2.SetInput(self.__Transform) obj.SetTransform(t2.GetInverse()) self._StencilGenerator.SetInput(obj) _t1 = time.time() self._StencilGenerator.Update() _t2 = time.time() return self._StencilGenerator.GetOutput()
def _extract_polygon(self, PolyData, is_clean): self._contour_widget.EnabledOff() print "Init Extracting" self.setCursor(QCursor(Qt.WaitCursor)) QApplication.processEvents() polydata_rep = self._contour_representation.GetContourRepresentationAsPolyData() planes = self.get_frustrum() normal = planes.GetNormals() nor = np.array([0,0,0]) normal.GetTuple(5, nor) #progressBar.setValue(10) #QApplication.processEvents() selection = vtkImplicitSelectionLoop() selection.SetLoop(polydata_rep.GetPoints()) selection.SetNormal(nor[0], nor[1], nor[2]) #progressBar.setValue(20) #QApplication.processEvents() tip = vtkImplicitBoolean() tip.AddFunction(selection) tip.AddFunction(planes) tip.SetOperationTypeToIntersection() tip.Modified() #progressBar.setValue(40) #QApplication.processEvents() if is_clean: extractGeometry = vtkExtractPolyDataGeometry() else: extractGeometry = vtkExtractGeometry() extractGeometry.SetInput(PolyData) extractGeometry.SetImplicitFunction(tip) if is_clean: extractGeometry.ExtractInsideOff() extractGeometry.Update() if is_clean: clean = vtkCleanPolyData() clean.SetInputConnection(extractGeometry.GetOutputPort()) clean.Update() #progressBar.setValue(80) #QApplication.processEvents() filter = vtkDataSetSurfaceFilter() if is_clean: filter.SetInputConnection(clean.GetOutputPort()) else: filter.SetInputConnection(extractGeometry.GetOutputPort()) filter.Update() #progressBar.setValue(90) #QApplication.processEvents() self.setCursor(QCursor(Qt.ArrowCursor)) QApplication.processEvents() self.extract_action.setEnabled(False) self.clean_action.setEnabled(False) print "End Extracting" return filter.GetOutput()
def __init__(self, name, file_path="", density=0, volume=0, mass=0, J_zz=0, u_CAD=np.zeros(3), r_CAD=np.zeros(3), theta=np.zeros(3), dR=np.zeros(3), dtheta=np.zeros(3), color=np.ones(3, dtype="float32"), _dict={}, connected_to_ground=False, parent=None): """ Constructor of body class :param name: body name (string) :param filename: absolute path file of body properties :param density: density of the material of the body :param volume: volume of the body (as float) in m^3 :param mass: mass of the body (as float) in kg :param J_zz: mass moment of inertia of a body against z-axis (as float) in kg*m^2 :param u_CAD: a vector to mass center of a body in body CAD CS (as array) in m :param r_CAD: a vector to body CAD CS in GCS of a system (as array) in m :param theta: orientation angles (numpy array) in degrees :param dR: a vector of velocities (numpy array) in m/s :param dtheta: a vector of angular velocities (numpy array) in deg/s :param color: a color vector (RGB) :param properties_file: a path to mass and geometry properties data in .dat file (todo) :param geometry_data_file: a path to geometry .stl or .obj file (todo) """ super(RigidBody, self).__init__(name=name, file_path=file_path, parent=parent) # type of body self.body_type = "rigid body" # body id self.body_id = self._count() # body coordinates self.q_i_size = 3 # geometry and physical properties self.mass = mass self.J_zz = J_zz # size of mass matrix self.M_size = self.q_i_dim = 3 # material properties self.density = density self.volume = volume # visualization properties # size self.size = 1. # coordinate system properties self.u_CAD = u_CAD self.r_CAD = r_CAD # dynamic properties # transform with respect to selected CS # options: CAD, LCS self.transformCS = "CAD" self.R = self.u_CAD + self.r_CAD # (initial) coordinates and angles (in degrees) self.theta = theta # (initial) translational and rotational velocities self.dR = dR self.dtheta = dtheta # visualization properties self.color = color # connected to ground self._connected_to_ground = connected_to_ground # set directory to read body data from file self.file_path = file_path # os.chdir(MBD_folder_abs_path) # read body properties file if os.path.isfile(self.file_path): self._dict = read_body_data_file.read_body_data_file( self.file_path) self.add_attributes_from_dict(self._dict) # check if both files exist if not os.path.isfile(self.file_path): raise IOError, "Properties file not found!" if self._geometry_type == self.geometry_file_extension and self.geometry_filename is not None: if not os.path.isfile(self.geometry_filename): print "Geometry file %s not found!" % self.geometry_filename # additional translation due to rotation with respect to CAD CS # self.u_CAD[0:2] = Ai_ui_P_vector(self.u_CAD[0:2], 0)#self.theta[2] _R = self.u_CAD - Ai_ui_P_vector(self.u_CAD, self.theta[2]) #np.zeros(3)# # reevaluate R, based on body data from .dat file if all(self.u_CAD == np.zeros(3)) and all(self.r_CAD == np.zeros(3)): pass else: self.R = self.u_CAD + self.r_CAD # create geometry object # read geometry file and save vertices and normals if self._parent is not None: os.chdir(self._parent._parent.MBD_folder_abs_path) if self.geometry_filename is not None: if os.path.isfile(self.geometry_filename): # get extension self._geometry_type = os.path.splitext( self.geometry_filename)[1] if self._geometry_type == ".stl": self.geometry = Geometry(self.geometry_filename, parent=self) elif self._geometry_type == ".txt": self.geometry = Geometry2D(self.geometry_filename, parent=self) else: raise ValueError, "Object attribute _geometry_type not correct!" elif self._geometry_type == "line": self.geometry = Line(parent=self) elif self._geometry_type == "cylinder": self.geometry = vtk.vtkCylinderSource() self.geometry.SetRadius(self.R0) self.geometry.SetHeight(self.L) self.geometry.SetResolution(40) elif self._geometry_type == "box-cylinder": self.geometry_list = [None, None] # create a box box = vtk.vtkBox() box.SetBounds(-self.a, +self.a, -self.b, +self.b, -self.c, +self.c) # create a sphere cylinder = vtk.vtkCylinder() cylinder.SetRadius(self.R0) # cylinder.SetCenter(0,0,0) geometry_list = [box, cylinder] # combine the two implicit functions boolean = vtk.vtkImplicitBoolean() boolean.SetOperationTypeToDifference() # boolean.SetOperationTypeToUnion() # boolean.SetOperationTypeToIntersection() for geometry in geometry_list: boolean.AddFunction(geometry) # The sample function generates a distance function from the implicit # function. This is then contoured to get a polygonal surface. sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(boolean) sample.SetModelBounds(-10E-3, +10E-3, -10E-3, +10E-3, -10E-3, +10E-3) sample.SetSampleDimensions(40, 40, 40) sample.ComputeNormalsOn() # contour self.surface = vtk.vtkContourFilter() self.surface.SetInputConnection(sample.GetOutputPort()) self.surface.SetValue(0, 0.0) else: if self.geometry is None: print "Body geometry file %s not found! Attribute self.geometry for body %s not created." % ( self.geometry_filename, self._name) # add additional attributes to geometry object _dict_geometry = extract_from_dictionary_by_string_in_key( _dict, "geometry.") if self.geometry is not None and _dict_geometry: self.geometry.add_attributes_from_dict(_dict_geometry) if (self.r_CAD == np.zeros(3)).all() and (self.u_CAD == np.zeros(3)).all(): self.r_CAD = self.R
quadric.SetCoefficients(.5, 1, .2, 0, .1, 0, 0, .2, 0, 0) sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(quadric) sample.ComputeNormalsOff() trans = vtk.vtkTransform() trans.Scale(1, .5, .333) sphere = vtk.vtkSphere() sphere.SetRadius(0.25) sphere.SetTransform(trans) trans2 = vtk.vtkTransform() trans2.Scale(.25, .5, 1.0) sphere2 = vtk.vtkSphere() sphere2.SetRadius(0.25) sphere2.SetTransform(trans2) union = vtk.vtkImplicitBoolean() union.AddFunction(sphere) union.AddFunction(sphere2) union.SetOperationType(0) #union # Here is where it gets interesting. The implicit function is used to # extract those cells completely inside the function. They are then # shrunk to help show what was extracted. extract = vtk.vtkExtractGeometry() extract.SetInputConnection(sample.GetOutputPort()) extract.SetImplicitFunction(union) shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(extract.GetOutputPort()) shrink.SetShrinkFactor(0.5) dataMapper = vtk.vtkDataSetMapper() dataMapper.SetInputConnection(shrink.GetOutputPort())
cone = vtk.vtkCone() cone.SetAngle(20) vertPlane = vtk.vtkPlane() vertPlane.SetOrigin(.1,0,0) vertPlane.SetNormal(-1,0,0) basePlane = vtk.vtkPlane() basePlane.SetOrigin(1.2,0,0) basePlane.SetNormal(1,0,0) iceCream = vtk.vtkSphere() iceCream.SetCenter(1.333,0,0) iceCream.SetRadius(0.5) bite = vtk.vtkSphere() bite.SetCenter(1.5,0,0.5) bite.SetRadius(0.25) # combine primitives to build ice-cream cone theCone = vtk.vtkImplicitBoolean() theCone.SetOperationTypeToIntersection() theCone.AddFunction(cone) theCone.AddFunction(vertPlane) theCone.AddFunction(basePlane) theCream = vtk.vtkImplicitBoolean() theCream.SetOperationTypeToDifference() theCream.AddFunction(iceCream) theCream.AddFunction(bite) # iso-surface to create geometry theConeSample = vtk.vtkSampleFunction() theConeSample.SetImplicitFunction(theCone) theConeSample.SetModelBounds(-1,1.5,-1.25,1.25,-1.25,1.25) theConeSample.SetSampleDimensions(60,60,60) theConeSample.ComputeNormalsOff() theConeSurface = vtk.vtkMarchingContourFilter()
import vtk # create a sphere sphere = vtk.vtkSphere() sphere.SetRadius(1) sphere.SetCenter(1, 0, 0) # create a box box = vtk.vtkBox() box.SetBounds(-1, 1, -1, 1, -1, 1) # combine the two implicit functions boolean = vtk.vtkImplicitBoolean() boolean.SetOperationTypeToDifference() # boolean.SetOperationTypeToUnion() # boolean.SetOperationTypeToIntersection() boolean.AddFunction(box) boolean.AddFunction(sphere) # The sample function generates a distance function from the implicit # function. This is then contoured to get a polygonal surface. sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(boolean) sample.SetModelBounds(-1, 2, -1, 1, -1, 1) sample.SetSampleDimensions(40, 40, 40) sample.ComputeNormalsOff() # contour surface = vtk.vtkContourFilter() surface.SetInputConnection(sample.GetOutputPort()) surface.SetValue(0, 0.0)
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputData(self.Surface) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.Loop == None: self.PrintError('Error: no Loop.') select = vtk.vtkImplicitSelectionLoop() select.SetLoop(self.Loop.GetPoints()) normal = [0.0, 0.0, 0.0] centroid = [0.0, 0.0, 0.0] vtk.vtkPolygon().ComputeNormal(self.Loop.GetPoints(), normal) #compute centroid and check normals p = [0.0, 0.0, 0.0] for i in range(self.Loop.GetNumberOfPoints()): p = self.Loop.GetPoint(i) centroid[0] += p[0] centroid[1] += p[1] centroid[2] += p[2] centroid[0] = centroid[0] / self.Loop.GetNumberOfPoints() centroid[1] = centroid[1] / self.Loop.GetNumberOfPoints() centroid[2] = centroid[2] / self.Loop.GetNumberOfPoints() print "loop centroid", centroid locator = vtk.vtkPointLocator() locator.SetDataSet(self.Surface) locator.AutomaticOn() locator.BuildLocator() idsurface = locator.FindClosestPoint(centroid) if (self.Surface.GetPointData().GetNormals() == None): normalsFilter = vmtkscripts.vmtkSurfaceNormals() normalsFilter.Surface = self.Surface normalsFilter.NormalsArrayName = 'Normals' normalsFilter.Execute() self.Surface = normalsFilter.Surface normalsurface = [0.0, 0.0, 0.0] self.Surface.GetPointData().GetNormals().GetTuple( idsurface, normalsurface) print "loop normal: ", normal print "surface normal inside the loop: ", normalsurface check = vtk.vtkMath.Dot(normalsurface, normal) if check < 0: normal[0] = -normal[0] normal[1] = -normal[1] normal[2] = -normal[2] #compute plane proj = float(vtk.vtkMath.Dot(self.Loop.GetPoint(0), normal)) point = [0.0, 0.0, 0.0] self.Loop.GetPoint(0, point) for i in range(self.Loop.GetNumberOfPoints()): tmp = vtk.vtkMath.Dot(self.Loop.GetPoint(i), normal) if tmp < proj: proj = tmp self.Loop.GetPoint(i, point) origin = [0.0, 0.0, 0.0] origin[0] = point[0] #- normal[0] origin[1] = point[1] #- normal[1] origin[2] = point[2] #- normal[2] plane = vtk.vtkPlane() plane.SetNormal(normal[0], normal[1], normal[2]) plane.SetOrigin(origin[0], origin[1], origin[2]) #set bool Bool = vtk.vtkImplicitBoolean() Bool.SetOperationTypeToDifference() Bool.AddFunction(select) Bool.AddFunction(plane) clipper = vtk.vtkClipPolyData() clipper.SetInputData(self.Surface) clipper.SetClipFunction(Bool) clipper.GenerateClippedOutputOn() clipper.InsideOutOff() clipper.Update() self.Surface = clipper.GetOutput()
# Create a cylinder cyl = vtk.vtkCylinder() cyl.SetCenter(-2,0,0) cyl.SetRadius(0.02) # Create a (thin) box implicit function box = vtk.vtkBox() box.SetBounds(-1,0.5, -0.5,0.5, -0.0005, 0.0005) # Create a sphere implicit function sphere = vtk.vtkSphere() sphere.SetCenter(2,0,0) sphere.SetRadius(0.8) # Boolean (union) these together imp = vtk.vtkImplicitBoolean() imp.SetOperationTypeToUnion() imp.AddFunction(cyl) imp.AddFunction(box) imp.AddFunction(sphere) # Generate scalars and vector sample = vtk.vtkSampleImplicitFunctionFilter() sample.SetInputConnection(points.GetOutputPort()) sample.SetImplicitFunction(imp) sample.Update() print(sample.GetOutput().GetScalarRange()) # Now see if we can extract the three objects as separate clusters. extr = vtk.vtkEuclideanClusterExtraction() extr.SetInputConnection(sample.GetOutputPort())
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInput(self.Surface) triangleFilter.Update() self.Surface = triangleFilter.GetOutput() if self.Loop == None: self.PrintError('Error: no Loop.') select = vtk.vtkImplicitSelectionLoop() select.SetLoop(self.Loop.GetPoints()) normal = [0.0,0.0,0.0] centroid = [0.0,0.0,0.0] vtk.vtkPolygon().ComputeNormal(self.Loop.GetPoints(),normal) #compute centroid and check normals p = [0.0,0.0,0.0] for i in range (self.Loop.GetNumberOfPoints()): p = self.Loop.GetPoint(i) centroid[0] += p[0] centroid[1] += p[1] centroid[2] += p[2] centroid[0] = centroid[0] / self.Loop.GetNumberOfPoints() centroid[1] = centroid[1] / self.Loop.GetNumberOfPoints() centroid[2] = centroid[2] / self.Loop.GetNumberOfPoints() print "loop centroid", centroid locator = vtk.vtkPointLocator() locator.SetDataSet(self.Surface) locator.AutomaticOn() locator.BuildLocator() idsurface = locator.FindClosestPoint(centroid) if (self.Surface.GetPointData().GetNormals() == None): normalsFilter = vmtkscripts.vmtkSurfaceNormals() normalsFilter.Surface = self.Surface normalsFilter.NormalsArrayName = 'Normals' normalsFilter.Execute() self.Surface = normalsFilter.Surface normalsurface = [0.0,0.0,0.0] self.Surface.GetPointData().GetNormals().GetTuple(idsurface,normalsurface) print "loop normal: ", normal print "surface normal inside the loop: ", normalsurface check = vtk.vtkMath.Dot(normalsurface,normal) if check < 0: normal[0] = - normal[0] normal[1] = - normal[1] normal[2] = - normal[2] #compute plane proj = float(vtk.vtkMath.Dot(self.Loop.GetPoint(0),normal)) point = [0.0,0.0,0.0] self.Loop.GetPoint(0,point) for i in range (self.Loop.GetNumberOfPoints()): tmp = vtk.vtkMath.Dot(self.Loop.GetPoint(i),normal) if tmp < proj: proj = tmp self.Loop.GetPoint(i,point) origin = [0.0,0.0,0.0] origin[0] = point[0] #- normal[0] origin[1] = point[1] #- normal[1] origin[2] = point[2] #- normal[2] plane=vtk.vtkPlane() plane.SetNormal(normal[0],normal[1],normal[2]) plane.SetOrigin(origin[0],origin[1],origin[2]) #set bool Bool = vtk.vtkImplicitBoolean() Bool.SetOperationTypeToDifference() Bool.AddFunction(select) Bool.AddFunction(plane) clipper=vtk.vtkClipPolyData() clipper.SetInput(self.Surface) clipper.SetClipFunction(Bool) clipper.GenerateClippedOutputOn() clipper.InsideOutOff() clipper.Update() self.Surface = clipper.GetOutput()
def UpdateVTKWindow(self,x,y,z): self.widget.GetRenderWindow().RemoveRenderer(self.ren) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.1, 0.7) self.widget.GetRenderWindow().AddRenderer(self.ren) scalars = vtk.vtkIntArray() self.pnt = vtk.vtkPoints() cells = vtk.vtkCellArray() self.pnt.SetNumberOfPoints(self.data.shape[0]) cells.Allocate(self.data.shape[0],32) for i in xrange(0, self.data.shape[0]): if self.colors is not None: if self.cbs[self.colors[i]].IsChecked(): self.pnt.InsertPoint(i, self.data[i,x], self.data[i,y], self.data[i,z]) cells.InsertNextCell(1) cells.InsertCellPoint(i) else: self.pnt.InsertPoint(i, self.data[i,x], self.data[i,y], self.data[i,z]) cells.InsertNextCell(1) cells.InsertCellPoint(i) if self.colors is not None: for i in xrange(0, self.data.shape[0]): scalars.InsertNextTuple1(self.colors[i]) else: for i in xrange(0, self.data.shape[0]): scalars.InsertNextTuple1(0) # create poly of the points self.poly = vtk.vtkPolyData() self.poly.SetPoints(self.pnt) self.poly.SetVerts(cells) self.poly.GetPointData().SetScalars(scalars) self.normals = vtk.vtkPolyDataNormals() self.normals.SetInput(self.poly) # add box widget for clipping # points inside the box are colored green apd = vtk.vtkAppendPolyData() apd.AddInput(self.poly) # create mapper pipline for the poly pntmapper = vtk.vtkPolyDataMapper() self.clipper.SetInput(apd.GetOutput()) self.region = vtk.vtkImplicitBoolean() self.region.SetOperationTypeToUnion() self.clipper.SetClipFunction(self.region) self.clipper.InsideOutOn() selectMapper = vtk.vtkPolyDataMapper() selectMapper.SetInput(self.clipper.GetOutput()) selectMapper.ScalarVisibilityOff() self.selectActor.SetMapper(selectMapper) self.selectActor.GetProperty().SetColor(0, 1, 0) self.selectActor.VisibilityOff() self.selectActor.SetScale(1.01, 1.01, 1.01) if self.colors is not None: pntmapper.SetLookupTable(self.lut) pntmapper.SetInput(apd.GetOutput()) pntmapper.SetScalarRange(0, self.maxcolor) # create and add actor of mapper to renderer pntactor = vtk.vtkLODActor() # pntactor.GetProperty().SetColor(1,0,0) pntactor.SetMapper(pntmapper) pntactor.VisibilityOn() # create axes axes = vtk.vtkAxes() axes.SetOrigin(0,0,0) axes.SetScaleFactor(numpy.max(self.data)) axesTubes = vtk.vtkTubeFilter() axesTubes.SetInput(axes.GetOutput()) axesTubes.SetRadius(axes.GetScaleFactor()/200.0) axesTubes.SetNumberOfSides(6) #create axes mapper axesmapper = vtk.vtkPolyDataMapper() axesmapper.SetInput(axesTubes.GetOutput()) #create actor and add to renderer axesactor = vtk.vtkActor() axesactor.SetMapper(axesmapper) #create labels sf = axes.GetScaleFactor() xactor = self.BuildLabelActor(self.radioX.GetString(x), {}) xactor.SetScale(0.075*sf, 0.075*sf, 0.075*sf) xactor.SetPosition(0.2*sf, 0.05*sf, -0.05*sf) xactor.GetProperty().SetColor(0, 0, 0) yactor = self.BuildLabelActor(self.radioY.GetString(y), {'RotateZ': 90}) yactor.SetScale(0.075*sf, 0.075*sf, 0.075*sf) yactor.SetPosition(-0.05*sf, 0.2*sf, -0.05*sf) yactor.GetProperty().SetColor(0, 0, 0) zactor = self.BuildLabelActor(self.radioZ.GetString(z), {'RotateY': 90}) zactor.SetScale(0.075*sf, 0.075*sf, 0.075*sf) zactor.SetPosition(-0.05*sf, 0.05*sf, 0.6*sf) zactor.GetProperty().SetColor(0, 0, 0) self.ren.AddActor(xactor) self.ren.AddActor(yactor) self.ren.AddActor(zactor) self.ren.AddActor(axesactor) self.ren.AddActor(pntactor) self.ren.AddActor(self.selectActor) self.widget.Update() self.ren.ResetCamera()