def MaskWithPatch(id,t,c,r,maskArray,centerlines,voronoi): patch = ExtractPatch(id,centerlines) tubeFunction = vtkvmtk.vtkvmtkPolyBallLine() tubeFunction.SetInput(patch) tubeFunction.SetPolyBallRadiusArrayName(radiusArrayName) lastSphere = vtk.vtkSphere() lastSphere.SetRadius(r*1.5) lastSphere.SetCenter(c) for i in range(voronoi.GetNumberOfPoints()): point = [0.0,0.0,0.0] voronoiVector = [0.0,0.0,0.0] voronoi.GetPoint(i,point) voronoiVector[0] = point[0]-c[0] voronoiVector[1] = point[1]-c[1] voronoiVector[2] = point[2]-c[2] voronoiVectorDot = vtk.vtkMath.Dot(voronoiVector,t) tubevalue = tubeFunction.EvaluateFunction(point) spherevalue = lastSphere.EvaluateFunction(point) if (spherevalue<0.0) & (voronoiVectorDot<0.0): continue elif (tubevalue<=0.0): maskArray.SetTuple1(i,1)
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 testStructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() st = vtk.vtkStructuredGrid() st.SetDimensions(i.GetDimensions()) nps = i.GetNumberOfPoints() ps = vtk.vtkPoints() ps.SetNumberOfPoints(nps) for idx in xrange(nps): ps.SetPoint(idx, i.GetPoint(idx)) st.SetPoints(ps) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(st) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def openSurfaceAtPoint(self, polyData, seed): ''' Returns a new surface with an opening at the given seed. ''' someradius = 1.0 pointLocator = vtk.vtkPointLocator() pointLocator.SetDataSet(polyData) pointLocator.BuildLocator() # find the closest point next to the seed on the surface # id = pointLocator.FindClosestPoint(int(seed[0]),int(seed[1]),int(seed[2])) id = pointLocator.FindClosestPoint(seed) # the seed is now guaranteed on the surface seed = polyData.GetPoint(id) sphere = vtk.vtkSphere() sphere.SetCenter(seed[0], seed[1], seed[2]) sphere.SetRadius(someradius) clip = vtk.vtkClipPolyData() clip.SetInputData(polyData) clip.SetClipFunction(sphere) clip.Update() outPolyData = vtk.vtkPolyData() outPolyData.DeepCopy(clip.GetOutput()) return outPolyData
def _add_ugrid_nodes_to_grid(self, name, diff_node_ids, nodes): """ based on: _add_nastran_nodes_to_grid """ nnodes = nodes.shape[0] assert nnodes > 0, nnodes # if nnodes == 0: # return nnodes = len(diff_node_ids) points = vtk.vtkPoints() points.SetNumberOfPoints(nnodes) for nid in diff_node_ids: node = nodes[nid, :] print('nid=%s node=%s' % (nid, node)) points.InsertPoint(nid, *node) if 1: elem = vtk.vtkVertex() elem.GetPointIds().SetId(0, nid) else: elem = vtk.vtkSphere() sphere_size = self._get_sphere_size(dim_max) elem.SetRadius(sphere_size) elem.SetCenter(points.GetPoint(nid)) self.alt_grids[name].InsertNextCell(elem.GetCellType(), elem.GetPointIds()) self.alt_grids[name].SetPoints(points)
def SphereDrill(self, m_holelist, m_holeRadius, m_quiet=False): """ Drill sphere at locations specified by m_holelist. :param m_holelist: [list] A list of coordinates where holes are to be drilled :param m_holeRadius: [float] The radius of the hole to drill :param m_quiet: [bool] :return: """ m_totalNumOfHoles = len(m_holelist) if not m_quiet: t = time.time() print "Drilling" for i in xrange(m_totalNumOfHoles): m_sphere = vtk.vtkSphere() m_sphere.SetCenter(m_holelist[i]) m_sphere.SetRadius(m_holeRadius) clipper = vtk.vtkClipPolyData() clipper.SetInputData(self._data) clipper.SetClipFunction(m_sphere) clipper.Update() clipped = clipper.GetOutput() self._data.DeepCopy(clipped) if not m_quiet: print "\t%s/%s -- %.2f %%" % (i + 1, m_totalNumOfHoles, (i + 1) * 100 / float(m_totalNumOfHoles)) if not m_quiet: print "Finished: Totaltime used = %.2f s" % (time.time() - t) pass
def testUnstructured(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) t = vtk.vtkThreshold() t.SetInputConnection(rt.GetOutputPort()) t.ThresholdByUpper(-10) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputConnection(t.GetOutputPort()) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64) eg = vtk.vtkEnSightGoldReader() eg.SetCaseFileName(VTK_DATA_ROOT + "/Data/EnSight/elements.case") eg.Update() pl = vtk.vtkPlane() pl.SetOrigin(3.5, 3.5, 0.5) pl.SetNormal(0, 0, 1) c.SetInputConnection(eg.GetOutputPort()) c.SetClipFunction(pl) c.SetInsideOut(1) c.Update() data = c.GetOutputDataObject(0).GetBlock(0) self.assertEqual(data.GetNumberOfCells(), 75) rw = vtk.vtkRenderWindow() ren = vtk.vtkRenderer() rw.AddRenderer(ren) mapper = vtk.vtkDataSetMapper() mapper.SetInputData(data) actor = vtk.vtkActor() actor.SetMapper(mapper) ren.AddActor(actor) ac = ren.GetActiveCamera() ac.SetPosition(-7.9, 9.7, 14.6) ac.SetFocalPoint(3.5, 3.5, 0.5) ac.SetViewUp(0.08, 0.93, -0.34) rw.Render() ren.ResetCameraClippingRange() rtTester = vtk.vtkTesting() for arg in sys.argv[1:]: rtTester.AddArgument(arg) rtTester.AddArgument("-V") rtTester.AddArgument("tableBasedClip.png") rtTester.SetRenderWindow(rw) rw.Render() rtResult = rtTester.RegressionTest(10)
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 Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') if self.WidgetType == "box": self.ClipFunction = vtk.vtkPlanes() elif self.WidgetType == "sphere": self.ClipFunction = vtk.vtkSphere() self.Clipper = vtk.vtkClipPolyData() self.Clipper.SetInput(self.Surface) self.Clipper.SetClipFunction(self.ClipFunction) self.Clipper.GenerateClippedOutputOn() self.Clipper.InsideOutOn() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.Surface) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) if self.WidgetType == "box": self.ClipWidget = vtk.vtkBoxWidget() self.ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2) self.ClipWidget.GetFaceProperty().SetOpacity(0.25) elif self.WidgetType == "sphere": self.ClipWidget = vtk.vtkSphereWidget() self.ClipWidget.GetSphereProperty().SetColor(0.6,0.6,0.2) self.ClipWidget.GetSphereProperty().SetOpacity(0.25) self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6,0.0,0.0) self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75) self.ClipWidget.SetRepresentationToSurface() self.ClipWidget.SetPhiResolution(20) self.ClipWidget.SetThetaResolution(20) self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.Display() self.Transform = vtk.vtkTransform() self.ClipWidget.GetTransform(self.Transform) if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.CleanOutput == 1: cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() self.Surface = cleaner.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def getImplicitSphere(self): impSphere = vtk.vtkSphere() # implicit sphere centerPoint = self.getCentralPoint() radius = self.getRadius() impSphere.SetRadius(radius) impSphere.SetCenter(centerPoint) return impSphere
def Execute(self): if (self.Surface == None): self.PrintError('Error: no Surface.') if self.WidgetType == "box": self.ClipFunction = vtk.vtkPlanes() elif self.WidgetType == "sphere": self.ClipFunction = vtk.vtkSphere() self.Clipper = vtk.vtkClipPolyData() self.Clipper.SetInput(self.Surface) self.Clipper.SetClipFunction(self.ClipFunction) self.Clipper.GenerateClippedOutputOn() self.Clipper.InsideOutOn() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.Surface) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) if self.WidgetType == "box": self.ClipWidget = vtk.vtkBoxWidget() self.ClipWidget.GetFaceProperty().SetColor(0.6, 0.6, 0.2) self.ClipWidget.GetFaceProperty().SetOpacity(0.25) elif self.WidgetType == "sphere": self.ClipWidget = vtk.vtkSphereWidget() self.ClipWidget.GetSphereProperty().SetColor(0.6, 0.6, 0.2) self.ClipWidget.GetSphereProperty().SetOpacity(0.25) self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6, 0.0, 0.0) self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75) self.ClipWidget.SetRepresentationToSurface() self.ClipWidget.SetPhiResolution(20) self.ClipWidget.SetThetaResolution(20) self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.Display() if self.OwnRenderer: self.vmtkRenderer.Deallocate() if self.CleanOutput == 1: cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() self.Surface = cleaner.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def __init__(self, map_actor, text_actor): self.AddObserver("MouseMoveEvent", self.mouse_move_event) self.map_actor = map_actor self.text_actor = text_actor self.elevation_actor = vtk.vtkActor() self.sphere = vtk.vtkSphere() self.cutter = vtk.vtkCutter() self.stripper = vtk.vtkStripper() self.tube_filter = vtk.vtkTubeFilter() self.mapper = vtk.vtkDataSetMapper() self.picker = vtk.vtkPointPicker()
def create_sphere(radius, center, thetaResolution=50, phiResolution=50): s = vtk.vtkSphere() s.SetRadius(radius) s.SetCenter(center) ss = vtk.vtkSphereSource() ss.SetThetaResolution(thetaResolution) ss.SetPhiResolution(phiResolution) ss.SetCenter(center) ss.SetRadius(radius) return s, ss
def extract_sphere(data, origin, radius): """Extracts a spherical slice of data from VTK data object """ sphere = vtk.vtkSphere() sphere.SetRadius(radius) cutter = vtk.vtkCutter() cutter.SetInputDataObject(data.reader.GetOutput()) cutter.SetCutFunction(sphere) cutter.Update() return cutter.GetOutputDataObject(0)
def CreateSkinClipping(cf): sphere = vtk.vtkSphere() sphere.SetCenter(xCenter, yCenter, zCenter) sphere.SetRadius(radius) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(cf.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.SetValue(0) clipper.Update() return clipper
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 FindClippingPointOnParentArtery(centerlines, parentCenterlines, toll): divergingPointID = -1 divergingPoint = [0.0, 0.0, 0.0] divergingPointMISR = -1 clippingPointID = -1 clippingPoint = [0.0, 0.0, 0.0] cell0PointIds = vtk.vtkIdList() cell1PointIds = vtk.vtkIdList() centerlines.GetCellPoints( 0, cell0PointIds) #this is the cl that goes through the aneurysm centerlines.GetCellPoints(1, cell1PointIds) for i in range( 0, min(cell0PointIds.GetNumberOfIds(), cell1PointIds.GetNumberOfIds())): cell0Point = centerlines.GetPoint(cell0PointIds.GetId(i)) cell1Point = centerlines.GetPoint(cell1PointIds.GetId(i)) distanceBetweenPoints = math.sqrt( vtk.vtkMath.Distance2BetweenPoints(cell0Point, cell1Point)) if (distanceBetweenPoints > toll): divergingPointID = cell1PointIds.GetId(i) divergingPoint = centerlines.GetPoint(cell1PointIds.GetId(i)) divergingPointMISR = centerlines.GetPointData().GetArray( radiusArrayName).GetTuple1(cell1PointIds.GetId(i)) break MISphere = vtk.vtkSphere() MISphere.SetCenter(divergingPoint) MISphere.SetRadius(divergingPointMISR) tempPoint = [0.0, 0.0, 0.0] for i in range(divergingPointID, 0, -1): value = MISphere.EvaluateFunction(centerlines.GetPoint(i)) if (value >= 0.0): tempPoint = centerlines.GetPoint(i) break locator = vtk.vtkPointLocator() locator.SetDataSet(parentCenterlines) locator.BuildLocator() clippingPointID = locator.FindClosestPoint(tempPoint) clippingPoint = parentCenterlines.GetPoint(clippingPointID) return clippingPoint, divergingPoint
def MakeScalars(dims, origin, spacing, scalars): # Implicit function used to compute scalars sphere = vtk.vtkSphere() sphere.SetRadius(3) sphere.SetCenter(5, 5, 5) scalars.SetNumberOfTuples(dims[0] * dims[1] * dims[2]) for k in range(0, dims[2]): z = origin[2] + spacing[2] * k for j in range(0, dims[1]): y = origin[1] + spacing[1] * j for i in range(0, dims[0]): x = origin[0] + spacing[0] * i scalars.SetValue(k * dims[0] * dims[1] + j * dims[0] + i, sphere.EvaluateFunction(x, y, z))
def mouseMoveEvent(self, obj, event): clickPos = self.GetInteractor().GetEventPosition() picker = vtk.vtkPointPicker() picker.Pick(clickPos[0], clickPos[1], 0, self.GetDefaultRenderer()) point = picker.GetPointId() if (point != -1): altitude = self.grid.GetPointData().GetScalars().GetValue(point) self.textActor.SetInput("Altitude : " + str(altitude) + "m") altitudeSphere = vtk.vtkSphere() altitudeSphere.SetRadius(EARTH_RADIUS + altitude) self.cutter.SetCutFunction(altitudeSphere) self.renWin.Render() self.OnMouseMove() return
def main(): colors = vtk.vtkNamedColors() sphere = vtk.vtkSphere() sphere.SetCenter(0, 0, 0) sphere.SetRadius(0.5) # 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(sphere) sample.SetModelBounds(-.5, .5, -.5, .5, -.5, .5) sample.SetSampleDimensions(20, 20, 20) 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) renwin.SetWindowName('ImplicitSphere1') # An interactor interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renwin) # Start interactor.Initialize() renwin.Render() interactor.Start()
def main(): colors = vtk.vtkNamedColors() # Set the background color. colors.SetColor("BkgColor", [51, 77, 102, 255]) sphere = vtk.vtkSphere() # Sample the function sample = vtk.vtkSampleFunction() sample.SetSampleDimensions(50, 50, 50) sample.SetImplicitFunction(sphere) value = 2.0 xmin = -value xmax = value ymin = -value ymax = value zmin = -value zmax = value sample.SetModelBounds(xmin, xmax, ymin, ymax, zmin, zmax) # Create the 0 isosurface contours = vtk.vtkContourFilter() contours.SetInputConnection(sample.GetOutputPort()) contours.GenerateValues(1, 1, 1) # Map the contours to graphical primitives contourMapper = vtk.vtkPolyDataMapper() contourMapper.SetInputConnection(contours.GetOutputPort()) contourMapper.ScalarVisibilityOff() # Create an actor for the contours contourActor = vtk.vtkActor() contourActor.SetMapper(contourMapper) # Visualize renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindow.SetWindowName('ImplicitSphere') interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderer.AddActor(contourActor) renderer.SetBackground(colors.GetColor3d("BkgColor")) renderWindow.Render() interactor.Start()
def vtk_sphere(center, radius): """Returns a vtk sphere object based on the bounds Args: center (list): Center of the sphere radius (float): Radius of the sphere Returns: sphere (vtkSphere): A vtkSphere """ sphere = vtk.vtkSphere() sphere.SetCenter(center) sphere.SetRadius(radius) return sphere
def make_blob(n, radius): blob_image = vtk.vtkImageData() max_r = 50 - 2.0 * radius random_sequence = vtk.vtkMinimalStandardRandomSequence() random_sequence.SetSeed(5071) for i in range(0, n): sphere = vtk.vtkSphere() sphere.SetRadius(radius) x = random_sequence.GetRangeValue(-max_r, max_r) random_sequence.Next() y = random_sequence.GetRangeValue(-max_r, max_r) random_sequence.Next() z = random_sequence.GetRangeValue(-max_r, max_r) random_sequence.Next() sphere.SetCenter(int(x), int(y), int(z)) sampler = vtk.vtkSampleFunction() sampler.SetImplicitFunction(sphere) sampler.SetOutputScalarTypeToFloat() sampler.SetSampleDimensions(100, 100, 100) sampler.SetModelBounds(-50, 50, -50, 50, -50, 50) thres = vtk.vtkImageThreshold() thres.SetInputConnection(sampler.GetOutputPort()) thres.ThresholdByLower(radius * radius) thres.ReplaceInOn() thres.ReplaceOutOn() thres.SetInValue(i + 1) thres.SetOutValue(0) thres.Update() if i == 0: blob_image.DeepCopy(thres.GetOutput()) max_value = vtk.vtkImageMathematics() max_value.SetInputData(0, blob_image) max_value.SetInputData(1, thres.GetOutput()) max_value.SetOperationToMax() max_value.Modified() max_value.Update() blob_image.DeepCopy(max_value.GetOutput()) return blob_image
def testImage(self): r = vtk.vtkRTAnalyticSource() r.SetWholeExtent(-5, 5, -5, 5, -5, 5) r.Update() s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputConnection(r.GetOutputPort()) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def move_past_sphere(centerline, center, r, start, step=-1, stop=0, X=0.8): """Moves a point along the centerline until it as outside MIS""" # Create the minimal inscribed sphere MISphere = vtk.vtkSphere() MISphere.SetCenter(center) MISphere.SetRadius(r * X) tempPoint = [0.0, 0.0, 0.0] # Go the length of one MISR backwards for i in range(start, stop, step): value = MISphere.EvaluateFunction(centerline.GetPoint(i)) if (value >= 0.0): tempPoint = centerline.GetPoint(i) break r = centerline.GetPointData().GetArray(radiusArrayName).GetTuple1(i) return tempPoint, r
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 create_sphere_clipping(vtk_algo, radius, coordinates): """Create a clipping actor between the vtk_object provided and a sphere at the coordinates and of the radius :param vtk_algo: The object to clip with the sphere :param radius: The radius of the sphere :param coordinates: The coordinates of the sphere :returns: An actor representing the object clipped with the sphere """ sphere = vtk.vtkSphere() sphere.SetRadius(radius) sphere.SetCenter(coordinates) clipper = vtk.vtkClipPolyData() clipper.SetInputConnection(vtk_algo.GetOutputPort()) clipper.SetClipFunction(sphere) clipper.GenerateClippedOutputOn() clipper.SetValue(0.5) return create_actor(clipper)
def FindClippingPointOnParentArtery(centerlines,parentCenterlines,toll): divergingPointID = -1 divergingPoint = [0.0,0.0,0.0] divergingPointMISR = -1 clippingPointID = -1 clippingPoint = [0.0,0.0,0.0] cell0PointIds = vtk.vtkIdList() cell1PointIds = vtk.vtkIdList() centerlines.GetCellPoints(0,cell0PointIds) #this is the cl that goes through the aneurysm centerlines.GetCellPoints(1,cell1PointIds) for i in range(0,min(cell0PointIds.GetNumberOfIds(),cell1PointIds.GetNumberOfIds())): cell0Point = centerlines.GetPoint(cell0PointIds.GetId(i)) cell1Point = centerlines.GetPoint(cell1PointIds.GetId(i)) distanceBetweenPoints = math.sqrt(vtk.vtkMath.Distance2BetweenPoints(cell0Point,cell1Point)) if (distanceBetweenPoints>toll): divergingPointID = cell1PointIds.GetId(i) divergingPoint = centerlines.GetPoint(cell1PointIds.GetId(i)) divergingPointMISR = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell1PointIds.GetId(i)) break MISphere = vtk.vtkSphere() MISphere.SetCenter(divergingPoint) MISphere.SetRadius(divergingPointMISR) tempPoint = [0.0,0.0,0.0] for i in range(divergingPointID,0,-1): value = MISphere.EvaluateFunction(centerlines.GetPoint(i)) if (value>=0.0): tempPoint = centerlines.GetPoint(i) break locator = vtk.vtkPointLocator() locator.SetDataSet(parentCenterlines) locator.BuildLocator() clippingPointID = locator.FindClosestPoint(tempPoint) clippingPoint = parentCenterlines.GetPoint(clippingPointID) return clippingPoint,divergingPoint
def testRectilinear(self): rt = vtk.vtkRTAnalyticSource() rt.SetWholeExtent(-5, 5, -5, 5, -5, 5) rt.Update() i = rt.GetOutput() r = vtk.vtkRectilinearGrid() dims = i.GetDimensions() r.SetDimensions(dims) exts = i.GetExtent() orgs = i.GetOrigin() xs = vtk.vtkFloatArray() xs.SetNumberOfTuples(dims[0]) for d in range(dims[0]): xs.SetTuple1(d, orgs[0] + exts[0] + d) r.SetXCoordinates(xs) ys = vtk.vtkFloatArray() ys.SetNumberOfTuples(dims[1]) for d in range(dims[1]): ys.SetTuple1(d, orgs[1] + exts[2] + d) r.SetYCoordinates(ys) zs = vtk.vtkFloatArray() zs.SetNumberOfTuples(dims[2]) for d in range(dims[2]): zs.SetTuple1(d, orgs[2] + exts[4] + d) r.SetZCoordinates(zs) s = vtk.vtkSphere() s.SetRadius(2) s.SetCenter(0,0,0) c = vtk.vtkTableBasedClipDataSet() c.SetInputData(r) c.SetClipFunction(s) c.SetInsideOut(1) c.Update() self.assertEqual(c.GetOutput().GetNumberOfCells(), 64)
def move_past_sphere(centerline, center, r, start, step=-1, stop=0, scale_factor=0.8): """Moves a point along the centerline until it as outside the a sphere with radius (r) and a center (center). Args: centerline (vtkPolyData): Centerline to move along. center (list): point list of the center of the sphere r (float): the radius of a sphere start (int): id of the point along the centerline where to start. step (int): direction along the centerline. stop (int): ID along centerline, for when to stop searching. scale_factor (float): Scale the radius with this factor. Returns: tmp_point (list): The first point on the centerline outside the sphere r (float): minimal inscribed sphere radius at the new point. i (int): the centerline ID at the new point. """ # Create the minimal inscribed sphere misr_sphere = vtk.vtkSphere() misr_sphere.SetCenter(center) misr_sphere.SetRadius(r * scale_factor) tmp_point = [0.0, 0.0, 0.0] # Go the length of one MISR backwards for i in range(start, stop, step): value = misr_sphere.EvaluateFunction(centerline.GetPoint(i)) if value >= 0.0: tmp_point = centerline.GetPoint(i) break r = centerline.GetPointData().GetArray(radiusArrayName).GetTuple1(i) return tmp_point, r, i
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()
print("Minor Version: ", rpd.GetFileMinorVersion()) print("File Version: ", rpd.GetFileVersion()) # Compare the strings and make sure a version difference is published. if not "4.2" in legacyOutStr: print("Bad legacy writer output") sys.exit(1) if not "5.1" in outStr: print("Bad writer output") sys.exit(1) # Write / read unstructured data - legacy version # Convert polydata to unstructured grid print("\nI/O vtkUnstructuredGrid") sph = vtk.vtkSphere() sph.SetRadius(10000000) extract = vtk.vtkExtractGeometry() extract.SetInputConnection(sphere.GetOutputPort()) extract.SetImplicitFunction(sph) wug = vtk.vtkUnstructuredGridWriter() wug.SetFileVersion(42) wug.WriteToOutputStringOn() wug.SetInputConnection(extract.GetOutputPort()) wug.Write() legacyOutStr = wug.GetOutputString() #print(legacyOutStr) rug = vtk.vtkUnstructuredGridReader()
VTK_DATA_ROOT = vtkGetDataRoot() # create pipeline # pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName(VTK_DATA_ROOT + "/Data/combxyz.bin") pl3d.SetQFileName(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(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)
# implicit function. In this case the implicit function is formed by # the boolean combination of two ellipsoids. import vtk # Here we create two ellipsoidal implicit functions and boolean them # together tto 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(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.
iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create implicit function primitives 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()
def main(): colors = vtk.vtkNamedColors() fileName = get_program_parameters() # Read the image. readerFactory = vtk.vtkImageReader2Factory() reader = readerFactory.CreateImageReader2(fileName) reader.SetFileName(fileName) reader.Update() cast = vtk.vtkImageCast() cast.SetInputConnection(reader.GetOutputPort()) cast.SetOutputScalarTypeToDouble() # Get rid of the discrete scalars. smooth = vtk.vtkImageGaussianSmooth() smooth.SetInputConnection(cast.GetOutputPort()) smooth.SetStandardDeviations(0.8, 0.8, 0) m1 = vtk.vtkSphere() m1.SetCenter(310, 130, 0) m1.SetRadius(0) m2 = vtk.vtkSampleFunction() m2.SetImplicitFunction(m1) m2.SetModelBounds(0, 264, 0, 264, 0, 1) m2.SetSampleDimensions(264, 264, 1) m3 = vtk.vtkImageShiftScale() m3.SetInputConnection(m2.GetOutputPort()) m3.SetScale(0.000095) div = vtk.vtkImageMathematics() div.SetInputConnection(0, smooth.GetOutputPort()) div.SetInputConnection(1, m3.GetOutputPort()) div.SetOperationToMultiply() # Create the actors. colorWindow = 256.0 colorLevel = 127.5 originalActor = vtk.vtkImageActor() originalActor.GetMapper().SetInputConnection(cast.GetOutputPort()) originalActor.GetProperty().SetColorWindow(colorWindow) originalActor.GetProperty().SetColorLevel(colorLevel) filteredActor = vtk.vtkImageActor() filteredActor.GetMapper().SetInputConnection(div.GetOutputPort()) # Define the viewport ranges. # (xmin, ymin, xmax, ymax) originalViewport = [0.0, 0.0, 0.5, 1.0] filteredViewport = [0.5, 0.0, 1.0, 1.0] # Setup the renderers. originalRenderer = vtk.vtkRenderer() originalRenderer.SetViewport(originalViewport) originalRenderer.AddActor(originalActor) originalRenderer.ResetCamera() originalRenderer.SetBackground(colors.GetColor3d("SlateGray")) filteredRenderer = vtk.vtkRenderer() filteredRenderer.SetViewport(filteredViewport) filteredRenderer.AddActor(filteredActor) filteredRenderer.ResetCamera() filteredRenderer.SetBackground(colors.GetColor3d("LightSlateGray")) renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(600, 300) renderWindow.AddRenderer(originalRenderer) renderWindow.AddRenderer(filteredRenderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() style = vtk.vtkInteractorStyleImage() renderWindowInteractor.SetInteractorStyle(style) renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.Initialize() renderWindowInteractor.Start()
def _createImplicit(self, implicitType, implicitName, bounds, primaryInput): if implicitType in self._implicitTypes and \ implicitName not in self._implicitsDict: pi = primaryInput rwi = self.slice3dVWR.threedFrame.threedRWI implicitInfoBounds = None if implicitType == "Plane": implicitWidget = vtk.vtkImplicitPlaneWidget() implicitWidget.SetPlaceFactor(1.25) if pi != None: implicitWidget.SetInput(pi) implicitWidget.PlaceWidget() b = pi.GetBounds() implicitWidget.SetOrigin(b[0], b[2], b[4]) implicitInfoBounds = b elif bounds != None: implicitWidget.PlaceWidget(bounds) implicitWidget.SetOrigin(bounds[0], bounds[2], bounds[4]) implicitInfoBounds = bounds else: # this can never happen pass implicitWidget.SetInteractor(rwi) implicitWidget.On() # create the implicit function implicitFunction = vtk.vtkPlane() # sync it to the initial widget self._syncPlaneFunctionToWidget(implicitWidget) # add it to the output self.outputImplicitFunction.AddFunction(implicitFunction) # now add an observer to the widget def observerImplicitPlaneWidget(widget, eventName): # sync it to the initial widget ret = self._syncPlaneFunctionToWidget(widget) # also select the correct grid row if ret != None: name, ii = ret row = self.findGridRowByName(name) if row >= 0: self._grid.SelectRow(row) oId = implicitWidget.AddObserver('EndInteractionEvent', observerImplicitPlaneWidget) elif implicitType == "Sphere": implicitWidget = vtk.vtkSphereWidget() implicitWidget.SetPlaceFactor(1.25) implicitWidget.TranslationOn() implicitWidget.ScaleOn() #implicitWidget.HandleVisibilityOn() if pi != None: implicitWidget.SetInput(pi) implicitWidget.PlaceWidget() b = pi.GetBounds() implicitInfoBounds = b #implicitWidget.SetOrigin(b[0], b[2], b[4]) elif bounds != None: implicitWidget.PlaceWidget(bounds) implicitInfoBounds = bounds #implicitWidget.SetOrigin(bounds[0], bounds[2], bounds[4]) else: # this can never happen pass implicitWidget.SetInteractor(rwi) implicitWidget.On() # create the implicit function implicitFunction = vtk.vtkSphere() # sync it to the initial widget self._syncSphereFunctionToWidget(implicitWidget) # add it to the output self.outputImplicitFunction.AddFunction(implicitFunction) # now add an observer to the widget def observerImplicitSphereWidget(widget, eventName): # sync it to the initial widget ret = self._syncSphereFunctionToWidget(widget) # also select the correct grid row if ret != None: name, ii = ret row = self.findGridRowByName(name) if row >= 0: self._grid.SelectRow(row) oId = implicitWidget.AddObserver('EndInteractionEvent', observerImplicitSphereWidget) if implicitWidget: # set the priority so it gets interaction before the # ImagePlaneWidget. 3D widgets have default priority 0.5, # so we assign our widgets just a tad higher. (voiwidget # has 0.6 for example) # NB: in a completely weird twist of events, only slices # added AFTER this widget will act like they have lower # priority. The initial slice still takes events from us! implicitWidget.SetPriority(0.7) # add to our internal thingy ii = implicitInfo() ii.name = implicitName ii.type = implicitType ii.widget = implicitWidget ii.bounds = implicitInfoBounds ii.oId = oId ii.function = implicitFunction self._implicitsDict[implicitName] = ii # now add to the grid nrGridRows = self._grid.GetNumberRows() self._grid.AppendRows() self._grid.SetCellValue(nrGridRows, self._gridNameCol, implicitName) self._grid.SetCellValue(nrGridRows, self._gridTypeCol, implicitType) # set the relevant cells up for Boolean for col in [self._gridEnabledCol]: self._grid.SetCellRenderer(nrGridRows, col, wx.grid.GridCellBoolRenderer()) self._grid.SetCellAlignment(nrGridRows, col, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE) self._setImplicitEnabled(ii.name, True)
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 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()
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # This example demonstrates adding two implicit models # to produce an (unexpected!) result # first we load in the standard vtk packages into tcl geomObject1 = vtk.vtkCone() geomObject2 = vtk.vtkSphere() geomObject2.SetRadius(0.5) geomObject2.SetCenter(0.5, 0, 0) sum = vtk.vtkImplicitSum() sum.SetNormalizeByWeight(1) sum.AddFunction(geomObject1, 2) sum.AddFunction(geomObject2, 1) sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(sum) sample.SetSampleDimensions(60, 60, 60) sample.ComputeNormalsOn() surface = vtk.vtkContourFilter() surface.SetInputConnection(sample.GetOutputPort()) surface.SetValue(0, 0.0) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(0.2, 0.4, 0.6) actor.GetProperty().SetSpecular(0.4)
g3Mapper.SetScalarRange(output.GetScalarRange()) g3Actor = vtk.vtkActor() g3Actor.SetMapper(g3Mapper) g3Actor.AddPosition(0,0,15) gf4 = vtk.vtkDataSetSurfaceFilter() gf4.SetInputConnection(gf2.GetOutputPort()) gf4.UseStripsOn() g4Mapper = vtk.vtkPolyDataMapper() g4Mapper.SetInputConnection(gf4.GetOutputPort()) g4Mapper.SetScalarRange(output.GetScalarRange()) g4Actor = vtk.vtkActor() g4Actor.SetMapper(g4Mapper) g4Actor.AddPosition(0,15,15) # create pipeline - unstructured grid # s = vtk.vtkSphere() s.SetCenter(output.GetCenter()) s.SetRadius(100.0) #everything eg = vtk.vtkExtractGeometry() eg.SetInputData(output) eg.SetImplicitFunction(s) gf5 = vtk.vtkDataSetSurfaceFilter() gf5.SetInputConnection(eg.GetOutputPort()) g5Mapper = vtk.vtkPolyDataMapper() g5Mapper.SetInputConnection(gf5.GetOutputPort()) g5Mapper.SetScalarRange(output.GetScalarRange()) g5Actor = vtk.vtkActor() g5Actor.SetMapper(g5Mapper) g5Actor.AddPosition(0,0,30) gf6 = vtk.vtkDataSetSurfaceFilter()
def Execute(self): if self.Surface == None: self.PrintError('Error: no Surface.') self.Clipper = vtk.vtkClipPolyData() self.Clipper.SetInput(self.Surface) self.Clipper.GenerateClippedOutputOn() self.Clipper.SetInsideOut(self.InsideOut) if self.Interactive: if self.WidgetType == "box": self.ClipFunction = vtk.vtkPlanes() elif self.WidgetType == "sphere": self.ClipFunction = vtk.vtkSphere() self.Clipper.SetClipFunction(self.ClipFunction) self.Cutter = vtk.vtkCutter() self.Cutter.SetInput(self.Surface) self.Cutter.SetCutFunction(self.ClipFunction) self.ClippedSurface = vtk.vtkPolyData() self.CutLines = vtk.vtkPolyData() if not self.vmtkRenderer: self.vmtkRenderer = vmtkrenderer.vmtkRenderer() self.vmtkRenderer.Initialize() self.OwnRenderer = 1 self.vmtkRenderer.RegisterScript(self) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.Surface) mapper.ScalarVisibilityOff() self.Actor = vtk.vtkActor() self.Actor.SetMapper(mapper) self.vmtkRenderer.Renderer.AddActor(self.Actor) if self.WidgetType == "box": self.ClipWidget = vtk.vtkBoxWidget() self.ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2) self.ClipWidget.GetFaceProperty().SetOpacity(0.25) elif self.WidgetType == "sphere": self.ClipWidget = vtk.vtkSphereWidget() self.ClipWidget.GetSphereProperty().SetColor(0.6,0.6,0.2) self.ClipWidget.GetSphereProperty().SetOpacity(0.25) self.ClipWidget.GetSelectedSphereProperty().SetColor(0.6,0.0,0.0) self.ClipWidget.GetSelectedSphereProperty().SetOpacity(0.75) self.ClipWidget.SetRepresentationToSurface() self.ClipWidget.SetPhiResolution(20) self.ClipWidget.SetThetaResolution(20) self.ClipWidget.SetInteractor(self.vmtkRenderer.RenderWindowInteractor) self.vmtkRenderer.AddKeyBinding('space','Clip.',self.ClipCallback) self.vmtkRenderer.AddKeyBinding('i','Interact.',self.InteractCallback) self.Display() self.Transform = vtk.vtkTransform() self.ClipWidget.GetTransform(self.Transform) if self.OwnRenderer: self.vmtkRenderer.Deallocate() else: self.Surface.GetPointData().SetActiveScalars(self.ClipArrayName) self.Clipper.GenerateClipScalarsOff() self.Clipper.SetValue(self.ClipValue) self.Clipper.Update() self.Cutter = vtk.vtkContourFilter() self.Cutter.SetInput(self.Surface) self.Cutter.SetValue(0,self.ClipValue) self.Cutter.Update() self.Surface = self.Clipper.GetOutput() self.ClippedSurface = self.Clipper.GetClippedOutput() self.CutLines = self.Cutter.GetOutput() if self.CleanOutput == 1: cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.Surface) cleaner.Update() self.Surface = cleaner.GetOutput() cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.ClippedSurface) cleaner.Update() self.ClippedSurface = cleaner.GetOutput() cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(self.CutLines) cleaner.Update() stripper = vtk.vtkStripper() stripper.SetInput(cleaner.GetOutput()) stripper.Update() self.CutLines = stripper.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
#!/usr/bin/env python import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # This example demonstrates adding two implicit models # to produce an (unexpected!) result # first we load in the standard vtk packages into tcl geomObject1 = vtk.vtkCone() geomObject2 = vtk.vtkSphere() geomObject2.SetRadius(0.5) geomObject2.SetCenter(0.5,0,0) sum = vtk.vtkImplicitSum() sum.SetNormalizeByWeight(1) sum.AddFunction(geomObject1,2) sum.AddFunction(geomObject2,1) sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(sum) sample.SetSampleDimensions(60,60,60) sample.ComputeNormalsOn() surface = vtk.vtkContourFilter() surface.SetInputConnection(sample.GetOutputPort()) surface.SetValue(0,0.0) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetDiffuseColor(0.2,0.4,0.6) actor.GetProperty().SetSpecular(0.4)
def SmoothClippedVoronoiDiagram(voronoi,centerlines): numberOfPoints = voronoi.GetNumberOfPoints() numberOfCenterlinesPoints = centerlines.GetNumberOfPoints() maskArray = vtk.vtkIntArray() maskArray.SetNumberOfComponents(1) maskArray.SetNumberOfTuples(numberOfPoints) maskArray.FillComponent(0,0) for i in range(numberOfCenterlinesPoints): localRadius = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(i) threshold = localRadius*(1.0 - smoothingFactor) sphere = vtk.vtkSphere() sphere.SetRadius(localRadius) sphere.SetCenter(centerlines.GetPoint(i)) localMaskArray = vtk.vtkIntArray() localMaskArray.SetNumberOfComponents(1) localMaskArray.SetNumberOfTuples(numberOfPoints) localMaskArray.FillComponent(0,0) for j in range(numberOfPoints): value = sphere.EvaluateFunction(voronoi.GetPoint(j)) if (value <= 0.0): localMaskArray.SetTuple1(j,1) for j in range(numberOfPoints): value = localMaskArray.GetTuple1(j) if (value==1): r = voronoi.GetPointData().GetArray(radiusArrayName).GetTuple1(j) if (r>threshold): maskArray.SetTuple1(j,1) finalNumberOfMaskedPoints = ComputeNumberOfMaskedPoints(maskArray) print('from original number of points ', numberOfPoints,'to',finalNumberOfMaskedPoints) smoothedDiagram = vtk.vtkPolyData() points = vtk.vtkPoints() cellArray = vtk.vtkCellArray() radiusArray = vtk.vtkDoubleArray() radiusArray.SetNumberOfComponents(1) radiusArray.SetNumberOfTuples(finalNumberOfMaskedPoints) radiusArray.FillComponent(0,0.0) radiusArray.SetName(radiusArrayName) count = 0 for i in range(numberOfPoints): value = maskArray.GetTuple1(i) if (value==1): radius = voronoi.GetPointData().GetArray(radiusArrayName).GetTuple1(i) points.InsertNextPoint(voronoi.GetPoint(i)) cellArray.InsertNextCell(1) cellArray.InsertCellPoint(count) radiusArray.SetTuple1(count,radius) count +=1 smoothedDiagram.SetPoints(points) smoothedDiagram.SetVerts(cellArray) smoothedDiagram.GetPointData().AddArray(radiusArray) return smoothedDiagram
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)
# Parameters for debugging NPts = 1000000 math = vtk.vtkMath() math.RandomSeed(31415) # create pipeline # points = vtk.vtkBoundedPointSource() points.SetNumberOfPoints(NPts) points.ProduceRandomScalarsOn() points.ProduceCellOutputOff() points.Update() # Create a sphere implicit function sphere = vtk.vtkSphere() sphere.SetCenter(0.0, 0.1, 0.2) sphere.SetRadius(0.75) # Extract points within sphere extract = vtk.vtkFitImplicitFunction() extract.SetInputConnection(points.GetOutputPort()) extract.SetImplicitFunction(sphere) extract.SetThreshold(0.005) extract.GenerateVerticesOn() # Clip out some of the points with a plane; requires vertices plane = vtk.vtkPlane() plane.SetOrigin(sphere.GetCenter()) plane.SetNormal(1, 1, 1)
ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # create implicit function primitives 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)
def gen_slice(args): verbose = args.verbose origin = args.origin normal = args.normal output_file = args.output_file[0] input_file = args.input_file[0] variable = args.variable[0] on_sphere = args.sphere sphere_radius = args.sphere_radius depth = args.sphere_radius xi = [] yi = [] zi = [] vtu_files = [] path = os.path.dirname(input_file) if (not on_sphere): if (normal == (0,0,1)): index_1 = 0 index_2 = 1 x_axis = "X" y_axis = "Y" elif(normal == (0,1,0)): index_1 = 0 index_2 = 2 x_axis = "X" y_axis = "Depth" elif(normal == (1,0,0)): index_1 = 1 index_2 = 2 x_axis = "Y" y_axis = "Depth" else: print "Normal should be one of (1,0,0), (0,1,0), or (0,0,1)" sys.exit(-1) # check origin if (origin == None): print "Origin should be a set of three corrdinate, eg. (0,0,-10)" sys.exit(-1) else: import fluidity.spheretools as st index_1 = 0 index_2 = 1 index_3 = 2 x_axis = "Longitude" y_axis = "Latitude" # get vtus from pvtu file. They are in lines such as: # <Piece Source="restratA-np64-adapt-C_99/restratA-np64-adapt-C_99_0.vtu" /> # As PVTU is XML, parse as such and grab the Piece elements xml_root = etree.parse(input_file,xml_parser) find = etree.XPath("//Piece") peices = find(xml_root) for p in peices: name = p.attrib['Source'] vtu_files.append(os.path.join(path,name)) if (on_sphere): sphere = vtk.vtkSphere() sphere.SetCenter(0,0,0) sphere.SetRadius(sphere_radius-10) else: plane = vtk.vtkPlane() plane.SetOrigin(origin[0], origin[1], origin[2]) plane.SetNormal(normal[0],normal[1],normal[2]) getMagnitude = False component = -1 # Special cases of variables if (variable == "VelocityMagnitude"): getMagnitude = True variable = "Velocity_projection" if (variable == "VelocityU"): getMagnitude = False variable = "ProjectedVelocity" component = 0 if (variable == "VelocityV"): getMagnitude = False variable = "ProjectedVelocity" component = 1 if (variable == "BedShearStressMagnitude"): getMagnitude = True variable = "BedShearStress_projection" if (variable == "MaxBedShearStressMagnitude"): getMagnitude = True variable = "MaxBedShearStress_projection" if (variable == "AveBedShearStressMagnitude"): getMagnitude = True variable = "AveBedShearStress_projection" if (variable == "MaxVelocityMagnitude"): getMagnitude = True variable = "MaxVelocity_projection" if (variable == "AveVelocityMagnitude"): getMagnitude = True variable = "AveVelocity_projection" if (variable == "AveVelocityU"): getMagnitude = False component = 0 variable = "AveVelocity_projection" if (variable == "AveVelocityV"): getMagnitude = False component = 1 variable = "AveVelocity_projection" if (variable == "MaxVelocityU"): getMagnitude = False component = 0 variable = "MaxVelocity_projection" if (variable == "MaxVelocityV"): getMagnitude = False component = 1 variable = "MaxVelocity_projection" if (variable == "AveBedShearStressU"): getMagnitude = False component = 0 variable = "AveBedShearStress_projection" if (variable == "AveBedShearStressV"): getMagnitude = False component = 1 variable = "AveBedShearStress_projection" if (variable == "MaxBedShearStressU"): getMagnitude = False component = 0 variable = "MaxBedShearStress_projection" if (variable == "MaxBedShearStressV"): getMagnitude = False component = 1 variable = "MaxBedShearStress_projection" comp_1 = [] comp_2 = [] comp_3 = [] # the above are for later...numpy.array[[list],[list]] is sllloooowww #for each vtu, grab any slice data i = 0 for v in vtu_files: if (verbose): print v # grab the number num = i # Start by loading some data. reader=vtk.vtkXMLUnstructuredGridReader() reader.SetFileName(v) reader.Update() grid=reader.GetOutput() grid.GetPointData().SetActiveScalars(variable) cut = vtk.vtkCutter() if (on_sphere): cut.SetCutFunction(sphere) else: cut.SetCutFunction(plane) cut.SetInputConnection(reader.GetOutputPort()) cut.Update() i = i+1 d = cut.GetOutput().GetPointData().GetScalars() d.GetNumberOfTuples() slice_data = np.array([d.GetTuple(i) for i in range(d.GetNumberOfTuples())]) c = cut.GetOutput() coords = [] for i in range(0,c.GetNumberOfPoints()): coords.append(c.GetPoint(i)) coords = np.array(coords) if (len(slice_data) > 0): n_comps = len(slice_data[0]) if (on_sphere): if (n_comps == 3): # project vectors and coords for i in range(0,len(coords[:,0])): #print coords[i,0],coords[i,1],coords[i,2] #print slice_data[i,0],slice_data[i,1],slice_data[i,2] [[radial, polar, azimuthal],[lat,lon]] = \ sp.vector_cartesian_2_spherical_polar(slice_data[i,0],slice_data[i,1],slice_data[i,2], coords[i,0],coords[i,1],coords[i,2]) xi.append(math.degrees(lon)) yi.append(math.degrees(lat)) slice_data[i,0] = radial slice_data[i,1] = polar slice_data[i,2] = azimuthal elif (n_comps == 1): #project points only for i in range(0,len(coords[:,0])): lat,lon = st.cart2polar(coords[i,:]) xi.append(math.degrees(lon)) yi.append(math.degrees(lat)) else: print("Unknown number of componenets - not a 3D vector or scalar") sys.exit(-1) else: xi.extend(coords[:,index_1]) yi.extend(coords[:,index_2]) if (getMagnitude): # How to calculate the magnitude nicely..? Below seems rather brute force. mag = [] mag = slice_data[:,0] for j in range(0,len(mag)): mag[j] = mag[j]*mag[j] for i in range(1,n_comps): for j in range(0,len(mag)): mag[j] = mag[j] + slice_data[j,i]*slice_data[j,i] for j in range(0,len(mag)): mag[j] =math.sqrt(mag[j]) zi.extend(mag) elif (component > -1): zi.extend(slice_data[:,component]) else: if (n_comps == 3): comp_1.extend(slice_data[:,0]) comp_2.extend(slice_data[:,1]) comp_3.extend(slice_data[:,2]) else: zi.extend(slice_data[:,0]) # THe data contain > 1 components, but we only want one if (component > -1 or getMagnitude) : n_comps = 1 #if (component == 1): # zi = comp_1 #elif (component == 2): # zi = comp_2 #elif (component == 3): # zi = comp_3 #else: # print "Error - you seem to be generating 4D data!" # sys.exit(-1) coords = [] # need to tidy up these arrays - lot's duplicate points from halos, DG, or whatever if (n_comps == 3): for i in range(len(xi)): coords.append([xi[i],yi[i],comp_1[i],comp_2[i],comp_3[i]]) elif (n_comps == 1): for i in range(len(xi)): coords.append([xi[i],yi[i],zi[i]]) else: print "Error. I expect 1 or 3 components" sys.exit(-1) if (verbose): print "Removing duplicated points" coords_checked = unique(coords) if (verbose): print "Saving file" xi = [] yi = [] zi = [] for c in coords_checked: xi.append(c[0]) yi.append(c[1]) if (n_comps == 3): zi.append([c[2], c[3], c[4]]) else: zi.append(c[2]) i += 1 # Store data as a pickle data = [xi,yi,zi] # Add axes labels axes_info = [index_1,index_2,x_axis,y_axis] data.append(axes_info) pickle.dump( data, open( output_file, "wb" ) )
math.Random(.2, 1), 1) i += 1 lut = vtk.vtkLookupTable() MakeColors(lut, 256) n = 20 radius = 10 # This has been moved outside the loop so that the code can be correctly # translated to python blobImage = vtk.vtkImageData() i = 0 while i < n: sphere = vtk.vtkSphere() sphere.SetRadius(radius) max = 50 - radius sphere.SetCenter(int(math.Random(-max, max)), int(math.Random(-max, max)), int(math.Random(-max, max))) sampler = vtk.vtkSampleFunction() sampler.SetImplicitFunction(sphere) sampler.SetOutputScalarTypeToFloat() sampler.SetSampleDimensions(51, 51, 51) sampler.SetModelBounds(-50, 50, -50, 50, -50, 50) thres = vtk.vtkImageThreshold() thres.SetInputConnection(sampler.GetOutputPort()) thres.ThresholdByLower(radius * radius) thres.ReplaceInOn()
res = 50 # Create the RenderWindow, Renderers and both Actors ren0 = vtk.vtkRenderer() ren1 = vtk.vtkRenderer() ren2 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren0) renWin.AddRenderer(ren1) renWin.AddRenderer(ren2) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create a synthetic source: sample a sphere across a volume sphere = vtk.vtkSphere() sphere.SetCenter( 0.0,0.0,0.0) sphere.SetRadius(0.25) sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(sphere) sample.SetModelBounds(-0.5,0.5, -0.5,0.5, -0.5,0.5) sample.SetSampleDimensions(res,res,res) sample.Update() # Adds random attributes random = vtk.vtkRandomAttributeGenerator() random.SetGenerateCellScalars(True) random.SetInputConnection(sample.GetOutputPort()) # Convert the image data to unstructured grid
# res = 200 # Create the RenderWindow, Renderers and both Actors ren0 = vtk.vtkRenderer() ren1 = vtk.vtkRenderer() ren2 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren0) renWin.AddRenderer(ren1) renWin.AddRenderer(ren2) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create a synthetic source: sample a sphere across a volume sphere = vtk.vtkSphere() sphere.SetCenter(0.0, 0.0, 0.0) sphere.SetRadius(0.25) sample = vtk.vtkSampleFunction() sample.SetImplicitFunction(sphere) sample.SetModelBounds(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5) sample.SetSampleDimensions(res, res, res) sample.Update() # Adds random attributes random = vtk.vtkRandomAttributeGenerator() random.SetGenerateCellScalars(True) random.SetInputConnection(sample.GetOutputPort()) # Convert the image data to unstructured grid
sTube = positions[0] sTubeX = sTube[:,0] sTubeY = sTube[:,1] sTubeZ = sTube[:,2] tPairs = [] for i in range(1,np.shape(positions[0])[0]): tPairs.append((i-1,i)) spheres = [None]*np.size(sTubeX) sphereActs = [None]*np.size(sTubeX) 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()