Exemplo n.º 1
1
 def addPlaneCutter(self, i):
     #take record of the plane weight 
     planeWeightTextValue = self.planeWeightText[i].text()
     self.planeWtInt[i] = planeWeightTextValue.toFloat()
     self.ren.RemoveActor(self.planeActor)
     plane=vtk.vtkPlane()
     plane.SetOrigin(float(self.firstPlanePtValueRecord[i][0]),float(self.firstPlanePtValueRecord[i][1]), float(self.firstPlanePtValueRecord[i][2]) )
     a = np.array([self.secondPlanePtValueRecord[i][0]-self.firstPlanePtValueRecord[i][0], self.secondPlanePtValueRecord[i][1]-self.firstPlanePtValueRecord[i][1], self.secondPlanePtValueRecord[i][2]-self.firstPlanePtValueRecord[i][2]])
     b = np.array([self.thirdPlanePtValueRecord[i][0]-self.firstPlanePtValueRecord[i][0], self.thirdPlanePtValueRecord[i][1]-self.firstPlanePtValueRecord[i][1],self.thirdPlanePtValueRecord[i][2]-self.firstPlanePtValueRecord[i][2]])
     self.planeOrigin[i] = self.firstPlanePtValueRecord[i]
     self.planeNormal[i] = np.cross(a, b)
     self.planeNormal[i] = self.planeNormal[i] / np.linalg.norm(self.planeNormal[i])
     plane.SetNormal(self.planeNormal[i])
                 
     #create cutter
     cutter=vtk.vtkCutter()
     cutter.SetCutFunction(plane)
     cutter.SetInputConnection(self.append.GetOutputPort())
     cutter.Update()
     cutterMapper=vtk.vtkPolyDataMapper()
     cutterMapper.SetInputConnection(cutter.GetOutputPort())
                 
     
     self.planeActor.GetProperty().SetColor(1.0,1,0)
     self.planeActor.GetProperty().SetLineWidth(2)
     self.planeActor.SetMapper(cutterMapper)
                 
     self.ren.AddActor(self.planeActor)
Exemplo n.º 2
0
def setClipPlanes(mapper, xmin, xmax, ymin, ymax):
    clipPlaneCollection = vtk.vtkPlaneCollection()

    if xmin != xmax:
      clipPlaneXMin = vtk.vtkPlane()
      clipPlaneXMin.SetOrigin(xmin, 0.0, 0.0)
      clipPlaneXMin.SetNormal(1.0, 0.0, 0.0)

      clipPlaneXMax = vtk.vtkPlane()
      clipPlaneXMax.SetOrigin(xmax, 0.0, 0.0)
      clipPlaneXMax.SetNormal(-1.0, 0.0, 0.0)

      clipPlaneCollection.AddItem(clipPlaneXMin)
      clipPlaneCollection.AddItem(clipPlaneXMax)

    if ymin != ymax:
      clipPlaneYMin = vtk.vtkPlane()
      clipPlaneYMin.SetOrigin(0.0, ymin, 0.0)
      clipPlaneYMin.SetNormal(0.0, 1.0, 0.0)

      clipPlaneYMax = vtk.vtkPlane()
      clipPlaneYMax.SetOrigin(0.0, ymax, 0.0)
      clipPlaneYMax.SetNormal(0.0, -1.0, 0.0)

      clipPlaneCollection.AddItem(clipPlaneYMin)
      clipPlaneCollection.AddItem(clipPlaneYMax)

    if clipPlaneCollection.GetNumberOfItems() > 0:
        mapper.SetClippingPlanes(clipPlaneCollection)
Exemplo n.º 3
0
 def testPassByReference(self):
     t = vtk.mutable(0.0)
     p0 = (0.5, 0.0, 0.0)
     n = (1.0, 0.0, 0.0)
     p1 = (0.0, 0.0, 0.0)
     p2 = (1.0, 1.0, 1.0)
     x = [0.0, 0.0, 0.0]
     vtk.vtkPlane.IntersectWithLine(p1, p2, n, p0, t, x)
     self.assertEqual(round(t,6), 0.5)
     self.assertEqual(round(x[0],6), 0.5)
     self.assertEqual(round(x[1],6), 0.5)
     self.assertEqual(round(x[2],6), 0.5)
     vtk.vtkPlane().IntersectWithLine(p1, p2, n, p0, t, x)
     self.assertEqual(round(t,6), 0.5)
     self.assertEqual(round(x[0],6), 0.5)
     self.assertEqual(round(x[1],6), 0.5)
     self.assertEqual(round(x[2],6), 0.5)
     t.set(0)
     p = vtk.vtkPlane()
     p.SetOrigin(0.5, 0.0, 0.0)
     p.SetNormal(1.0, 0.0, 0.0)
     p.IntersectWithLine(p1, p2, t, x)
     self.assertEqual(round(t,6), 0.5)
     self.assertEqual(round(x[0],6), 0.5)
     self.assertEqual(round(x[1],6), 0.5)
     self.assertEqual(round(x[2],6), 0.5)
     vtk.vtkPlane.IntersectWithLine(p, p1, p2, t, x)
     self.assertEqual(round(t,6), 0.5)
     self.assertEqual(round(x[0],6), 0.5)
     self.assertEqual(round(x[1],6), 0.5)
     self.assertEqual(round(x[2],6), 0.5)
Exemplo n.º 4
0
def cut_brain_hemi(hemi_elec_data, hemi_poly_data):
    depth_elec_data = hemi_elec_data[(hemi_elec_data.eType == 'D') | (hemi_elec_data.eType == 'd')]
    print depth_elec_data
    print

    x_coords = np.array([avg_surf.x_snap for avg_surf in depth_elec_data.avgSurf], dtype=np.float)
    y_coords = np.array([avg_surf.y_snap for avg_surf in depth_elec_data.avgSurf], dtype=np.float)
    z_coords = np.array([avg_surf.z_snap for avg_surf in depth_elec_data.avgSurf], dtype=np.float)

    x_min, x_max = np.min(x_coords), np.max(x_coords)
    y_min, y_max = np.min(y_coords), np.max(y_coords)
    z_min, z_max = np.min(z_coords), np.max(z_coords)

    clipPlane = vtk.vtkPlane()
    clipPlane.SetNormal(0.0, 0.0, 1.0)
    # clipPlane.SetOrigin(0, 0, np.max(z_coords))
    # clipPlane.SetOrigin(np.max(x_coords), np.max(y_coords), np.max(z_coords))

    clipPlane.SetOrigin(0, 0, -500)

    clipper = vtk.vtkClipPolyData()
    clipper.SetInputData(hemi_poly_data)
    clipper.SetClipFunction(clipPlane)

    return clipper
Exemplo n.º 5
0
    def initialize (self):
        debug ("In CutPlane::initialize ()")
        self.plane = vtk.vtkPlane ()
        self.fil = vtk.vtkCutter ()
        out = self.prev_fil.GetOutput()
        self.fil.SetInput (out)
        self.fil.SetCutFunction (self.plane)

        self.center = out.GetCenter ()
        self.plane.SetOrigin (self.center)
        self.plane.SetNormal (0.0, 0.0, 1.0)

        self.step_var = Tkinter.DoubleVar ()
        self.n_step_var = Tkinter.IntVar ()
        self.resoln_var = Tkinter.DoubleVar ()
        self.resoln_var.set (1.0)
        self.slider = []
        self.set_def_step_size ()
        self.step_var.set (self.step_size)
        self.n_step_var.set (10)        
        self.slider_pos = 0
        self._auto_sweep_init ()
        self.sweep_step.set (1)

        self.fil.Update ()
Exemplo n.º 6
0
    def clip(inp, origin, normal, inside_out=False, take_cell=False):
        """
        VTK operation: clip.  A vtkGeometryFilter is used to convert the
        resulted vtkUnstructuredMesh object into a vtkPolyData object.

        @param inp: input VTK object.
        @type inp: vtk.vtkobject
        @param origin: a 3-tuple for cut origin.
        @type origin: tuple
        @param normal: a 3-tuple for cut normal.
        @type normal: tuple
        @keyword inside_out: make inside out.  Default False.
        @type inside_out: bool
        @keyword take_cell: treat the input VTK object with values on cells.
            Default False.
        @type: take_cell: bool
        @return: output VTK object.
        @rtype: vtk.vtkobject
        """
        import vtk

        pne = vtk.vtkPlane()
        pne.SetOrigin(origin)
        pne.SetNormal(normal)
        clip = vtk.vtkClipDataSet()
        if take_cell:
            clip.SetInput(inp)
        else:
            clip.SetInputConnection(inp.GetOutputPort())
        clip.SetClipFunction(pne)
        if inside_out:
            clip.InsideOutOn()
        parison = vtk.vtkGeometryFilter()
        parison.SetInputConnection(clip.GetOutputPort())
        return parison
Exemplo n.º 7
0
    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 create_cut_acto_plane(self,xpos,ypos,zpos,plane_id):
        #vtk plane
        plane=vtk.vtkPlane()
        plane.SetOrigin(xpos,ypos,zpos)

        if plane_id==0:
            plane.SetNormal(1,0,0)
        if plane_id==1:
            plane.SetNormal(0,1,0)
        if plane_id==2:
            plane.SetNormal(0.0,0.0,1)

        #create cutter
        cutter=vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(self.dti_reader.GetOutputPort())
        cutter.Update()


        #probe filter for the cutting plane
        probe_filter=vtk.vtkProbeFilter()
        probe_filter.SetInputConnection(cutter.GetOutputPort())
        probe_filter.SetSourceConnection(self.dti_reader.GetOutputPort())


        self.plane1=plane

        return probe_filter
Exemplo n.º 9
0
    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()
Exemplo n.º 10
0
    def get(self):
        resultado = {}
        imageData = reader.get("IMAGE", self.subj, format="VTK", name=self.get_argument("type", None), space="world")

        plane=vtk.vtkPlane()
        if (self.get_argument("plane", None) == "x"):
            plane.SetNormal(1,0,0)
            plane.SetOrigin(float(self.get_argument("pos", None)),0,0)
        if (self.get_argument("plane", None) == "y"):
            plane.SetNormal(0,1,0)
            plane.SetOrigin(0,float(self.get_argument("pos", None)),0)
        if (self.get_argument("plane", None) == "z"):
            plane.SetNormal(0,0,1)
            plane.SetOrigin(0,0,float(self.get_argument("pos", None)))
            
        planeCut = vtk.vtkCutter()
        planeCut.SetInputData(imageData)
        planeCut.SetCutFunction(plane)
        planeCut.Update()
                
        resultado['subject'] = self.subj
        resultado['type'] = 'image'
        resultado['plane'] = self.get_argument("plane", None)    
        resultado['pos'] = self.get_argument("pos", None)    
        resultado['bounds'] = planeCut.GetOutput().GetBounds()
        resultado['dimensions'] = imageData.GetDimensions()
        resultado['scalars'] = numpy_support.vtk_to_numpy(planeCut.GetOutput().GetPointData().GetScalars()).tolist()

        self.set_header("Content-Type","application/json")
        self.write(json.dumps(resultado, separators=(',',':')))
Exemplo n.º 11
0
def Slice_VTK_data_to_VTK(inputFileName,
                             outputFileName,
                                 point, normal,
                                 resolution
                                           ):
    reader = vtk.vtkXMLUnstructuredGridReader()
    reader.SetFileName(inputFileName)
    reader.Update()
    
    plane = vtk.vtkPlane()
    plane.SetOrigin(point)
    plane.SetNormal(normal)

    cutter = vtk.vtkFiltersCorePython.vtkCutter()
    cutter.SetCutFunction(plane)
    cutter.SetInputConnection(reader.GetOutputPort())
    cutter.Update()

    #Convert tht polydata structure générated by cutter into unstructured grid by triangulation
    triFilter = vtk.vtkDataSetTriangleFilter()
    triFilter.SetInputConnection(cutter.GetOutputPort())
    triFilter.Update()
    
    writer = vtk.vtkXMLUnstructuredGridWriter()
    writer.SetInputData(triFilter.GetOutput())
    writer.SetFileName(outputFileName)
    writer.Write()
def clipSurfacesForCutLVMesh(
        endo,
        epi,
        height,
        verbose=1):

    myVTK.myPrint(verbose, "*** clipSurfacesForCutLVMesh ***")

    plane = vtk.vtkPlane()
    plane.SetNormal(0,0,-1)
    plane.SetOrigin(0,0,height)

    clip = vtk.vtkClipPolyData()
    clip.SetClipFunction(plane)
    clip.SetInputData(endo)
    clip.Update()
    clipped_endo = clip.GetOutput(0)

    clip = vtk.vtkClipPolyData()
    clip.SetClipFunction(plane)
    clip.SetInputData(epi)
    clip.Update()
    clipped_epi = clip.GetOutput(0)

    return (clipped_endo,
            clipped_epi)
Exemplo n.º 13
0
	def InitVTKMethods(self):
		"""Initializes the VTK methods to be used."""
		self.colortable=ColorTableSource()
		self._plane=vtkPlane()
		self._cutter=vtkCutter()
		self._mapper=vtkDataSetMapper()
		self.actor=vtkLODActor()
Exemplo n.º 14
0
    def _fbzCutPlane(self, fbz, giaN, giaGlenoid):
        """Calculate cut-plane corresponding to fbz.

        fbz is a list containing the two points defining a single FBZ
        (forbidden zone).  giaN is the glenoid-insertion axis normal.
        giaGlenoid is the user-selected gia point on the glenoid.

        This method will return a cut-plane to enforce the given fbz such
        that giaGlenoid is on the inside of the implicit plane.
        """
        
        fbzV = map(operator.sub, fbz[0], fbz[1])
        fbzPN = [0,0,0]
        vtk.vtkMath.Cross(fbzV, giaN, fbzPN)
        vtk.vtkMath.Normalize(fbzPN)
        fbzPlane = vtk.vtkPlane()
        fbzPlane.SetOrigin(fbz[0])
        fbzPlane.SetNormal(fbzPN)
        insideVal = fbzPlane.EvaluateFunction(giaGlenoid)
        if insideVal < 0:
            # eeep, it's outside, so flip the planeNormal
            fbzPN = [-1.0 * i for i in fbzPN]
            fbzPlane.SetNormal(fbzPN)

        return fbzPlane
Exemplo n.º 15
0
	def __init__(self, embryo,  parent=None):
		
		#super(vtkSimVisualizerCutter, self).__init__(embryo,parent)
		vtkSimVisualizer.__init__(self,embryo,parent=parent)
		
		# Check if 3D embryo
		if self.embryo.geometry.dim==2:
			printWarning("vtkSimVisualizerCutter does only work and make sense for 3D geometries. Will not initialize cutter and fall back tostandad vtkSimVisualizer.")
			return
		
		self.vtkWidgetCut,self.renCut,self.irenCut=self.initVTKWidget(self.frame)
		
		# Plane used for cutting
		self.plane = vtk.vtkPlane()
		
		# Cutter
		self.cutter = vtk.vtkCutter()
		
		# Plane widget
		self.initPlaneWidget()
		
		# Add Layout
		self.layout.addWidget(self.vtkWidgetCut,1,2)
	
		# Run cut mesh once
		self.CutMesh()
	
		self.irenCut.Initialize()
Exemplo n.º 16
0
	def __init__(self, embryo,  parent=None):
		
		super(vtkSimVisualizerCutter, self).__init__(parent)
		
		# Load embryo
		self.embryo=embryo
		
		# Check if simulation is saved
		if len(self.embryo.simulation.vals)==0:
			printWarning("Embryo does not have saved simulation. Rerun simulation with saveSim=True.")
			
		# Check if 3D embryo
		if self.embryo.geometry.dim==2:
			printError("vtkSimVisualizerCutter does only work and make sense for 3D geometries. Use vtkSimVisualizer instead.")
		
		# To numpy array 
		self.embryo.simulation.vals=np.array(self.embryo.simulation.vals)
		
		# Frame
		self.frame = QtGui.QFrame()
		
		# Vtk widgets
		self.vtkWidget,self.ren,self.iren=self.initVTKWidget(self.frame)
		self.vtkWidgetCut,self.renCut,self.irenCut=self.initVTKWidget(self.frame)
		
		# Add slider for 3D
		self.slider,self.label=self.initSlider(0, len(self.embryo.simulation.tvecSim)-1,self.sliderCallback)
		
		# Setup 3D simulation plot
		self.init3D()
		
		# Plane used for cutting
		self.plane = vtk.vtkPlane()
		
		# Cutter
		self.cutter = vtk.vtkCutter()
		
		# Plane widget
		self.initPlaneWidget()
		
		# Add Layout
		self.layout=QtGui.QGridLayout()
		self.layout.addWidget(self.vtkWidget,1,1)
		self.layout.addWidget(self.vtkWidgetCut,1,2)
		self.layout.addWidget(self.slider,2,1)
		self.layout.addWidget(self.label,3,1)
		
		# Set central widget
		self.frame.setLayout(self.layout)
		self.setCentralWidget(self.frame)
		
		self.setWindowTitle('vtkSimVisualizerCutter of embryo ' + self.embryo.name)
		
		# Run cut mesh once
		self.CutMesh()
		
		# Show everything
		self.show()
		self.iren.Initialize()
		self.irenCut.Initialize()
	def __init__(self, parent, visualizer, **kws):
		"""
		Initialization
		"""
		self.x, self.y, self.z = -1, -1, -1
		#self.name = "Clipping Plane"
		self.parent = parent        
		self.on = 0
		self.renew = 1
		self.currentPlane = None
		self.clipped = 0
		self.clippedModules = []
		self.planeWidget = vtk.vtkPlaneWidget()
		self.planeWidget.AddObserver("InteractionEvent", self.clipVolumeRendering)
		self.planeWidget.SetResolution(20)
		self.planeWidget.SetRepresentationToOutline()
		self.planeWidget.NormalToXAxisOn()
		self.renderer = self.parent.getRenderer()
		self.plane = vtk.vtkPlane()

		iactor = parent.wxrenwin.GetRenderWindow().GetInteractor()
		self.planeWidget.SetInteractor(iactor)
		VisualizationModule.__init__(self, parent, visualizer, **kws)
		
		self.descs = {"ShowControl": "Show controls",
					  "AllModules": "Clip all modules",
					  "ClippedModule": "Module to clip"}
		self.filterDesc = "Clip rendering using a plane"
Exemplo n.º 18
0
    def addContourObject(self, contourObject, prop3D):
        """Activate contouring for the contourObject.  The contourObject
        is usually a tdObject and specifically a vtkPolyData.  We also
        need the prop3D that represents this polydata in the 3d scene.
        """
        if self._contourObjectsDict.has_key(contourObject):
            # we already have this, thanks
            return

        try:
            contourable = contourObject.IsA('vtkPolyData')
        except:
            contourable = False

        if contourable:
            # we need a cutter to calculate the contours and then a stripper
            # to string them all together
            cutter = vtk.vtkCutter()
            plane = vtk.vtkPlane()
            cutter.SetCutFunction(plane)
            trfm = vtk.vtkTransform()
            trfm.SetMatrix(prop3D.GetMatrix())
            trfmFilter = vtk.vtkTransformPolyDataFilter()
            trfmFilter.SetTransform(trfm)
            trfmFilter.SetInput(contourObject)
            cutter.SetInput(trfmFilter.GetOutput())
            stripper = vtk.vtkStripper()
            stripper.SetInput(cutter.GetOutput())
            
            #
            #tubef = vtk.vtkTubeFilter()
            #tubef.SetNumberOfSides(12)
            #tubef.SetRadius(0.5)
            #tubef.SetInput(stripper.GetOutput())

            # and create the overlay at least for the 3d renderer
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInput(stripper.GetOutput())
            mapper.ScalarVisibilityOff()
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            c = self.sliceDirections.slice3dVWR._tdObjects.getObjectColour(
                contourObject)
            actor.GetProperty().SetColor(c)
            actor.GetProperty().SetInterpolationToFlat()

            # add it to the renderer
            self.sliceDirections.slice3dVWR._threedRenderer.AddActor(actor)
            
            # add all necessary metadata to our dict
            contourDict = {'contourObject' : contourObject,
                           'contourObjectProp' : prop3D,
                           'trfmFilter' : trfmFilter,
                           'cutter' : cutter,
                           'tdActor' : actor}
                           
            self._contourObjectsDict[contourObject] = contourDict

            # now sync the bugger
            self.syncContourToObject(contourObject)
Exemplo n.º 19
0
def cut(cube, normal):
    plane=vtk.vtkPlane()
    plane.SetOrigin(cube.GetCenter())
    plane.SetNormal(*normal)
     
    #create cutter
    cutter=vtk.vtkCutter()
    cutter.SetCutFunction(plane)
    cutter.SetInputConnection(cube.GetOutputPort())
    cutter.Update()
    cutterMapper=vtk.vtkPolyDataMapper()
    cutterMapper.SetInputConnection( cutter.GetOutputPort())
     
    #create plane actor
    planeActor=vtk.vtkActor()
    planeActor.GetProperty().SetColor(1.0,1,0)
    planeActor.GetProperty().SetLineWidth(2)
    planeActor.SetMapper(cutterMapper)
     
    #create renderers and add actors of plane and cube
    ren.AddActor(planeActor)
   
    ret = [] 
    points = cutter.GetOutput().GetPoints()
    for i in range(points.GetNumberOfPoints()):
        point = points.GetPoint(i)
        ret.append( point )
    return ret 
Exemplo n.º 20
0
	def makePlaneClipper(vtkObj):
		"""Makes a plane and clipper """
		plane = vtk.vtkPlane()
		clipper = vtk.vtkClipDataSet()
		clipper.SetInputConnection(vtkObj.GetProducerPort())
		clipper.SetClipFunction(plane)
		clipper.InsideOutOff()
		return clipper, plane
Exemplo n.º 21
0
def planeToVTK(pp):
    """Create an equivalent vtkPlane object."""
    vp = vtk.vtkPlane()
    if pp.normal is not None:
        vp.SetNormal(pp.normal)
    if pp.centre is not None:
        vp.SetOrigin(pp.centre)
    return vp
Exemplo n.º 22
0
 def ExtractMesh(self):
     meshExtractFilter = vtk.vtkExtractGeometry()
     meshExtractFilter.SetInputData(self.Mesh)
     meshExtractFilter.SetExtractInside(self.InsideOut)
     clipPlane = vtk.vtkPlane()
     self.PlaneWidget.GetPlane(clipPlane)
     meshExtractFilter.SetImplicitFunction(clipPlane)
     meshExtractFilter.Update()
     return meshExtractFilter.GetOutput()
Exemplo n.º 23
0
 def ClipMesh(self):
     meshClipFilter = vtk.vtkClipDataSet()
     meshClipFilter.SetInputData(self.Mesh)
     meshClipFilter.SetInsideOut(self.InsideOut)
     clipPlane = vtk.vtkPlane()
     self.PlaneWidget.GetPlane(clipPlane)
     meshClipFilter.SetClipFunction(clipPlane)
     meshClipFilter.Update()
     return meshClipFilter.GetOutput()
Exemplo n.º 24
0
def cutdataset(dataset, point, normal):
    cutplane = vtk.vtkPlane()
    cutplane.SetOrigin(point)
    cutplane.SetNormal(normal)
    cutter = vtk.vtkCutter()
    cutter.SetInputData(dataset)
    cutter.SetCutFunction(cutplane)
    cutter.Update()
    return cutter.GetOutput()
Exemplo n.º 25
0
 def CutMesh(self):
     cutPlane = vtk.vtkPlane()
     self.PlaneWidget.GetPlane(cutPlane)
     self.MeshCutFilter.SetCutFunction(cutPlane)
     self.MeshCutFilter.Update()
     self.Actor = vtk.vtkActor()
     mapper = vtk.vtkDataSetMapper()
     mapper.SetInputConnection(self.MeshCutFilter.GetOutputPort())
     self.Actor.SetMapper(mapper)
     self.vmtkRenderer.Renderer.AddActor(self.Actor)
Exemplo n.º 26
0
 def __init__ (self, mod_m):
     debug ("In CutPlaneModule::__init ()")
     Module.__init__ (self, mod_m)
     # this should be a vtkPlane
     self.plane = vtk.vtkPlane ()
     self.step_var = Tkinter.DoubleVar ()
     self.n_step_var = Tkinter.IntVar ()
     self.resoln_var = Tkinter.DoubleVar ()
     self.resoln_var.set (1.0)
     self.slider = []
Exemplo n.º 27
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()
 
        # 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
Exemplo n.º 28
0
def slicedataset(dataset, point, normal):
    """Slice through a vtkDataSet object with a plane defined by point and
    normal."""
    cutplane = vtk.vtkPlane()
    cutplane.SetOrigin(point)
    cutplane.SetNormal(normal)
    cutter = vtk.vtkCutter()
    cutter.SetInput(dataset)
    cutter.SetCutFunction(cutplane)
    cutter.Update()
    return cutter.GetOutput()
Exemplo n.º 29
0
	def createCuttingPlane(self,normal,dimension):
		cuttingPlane = vtk.vtkPlane()
		#Set origin to the center of the data set so every slice makes contact
		cuttingPlane.SetOrigin(float(self.center[0]),float(self.center[1]),float(self.center[2]))
		cuttingPlane.SetNormal(float(normal['x']), float(normal['y']), float(normal['z']))
		self.cutter = self.createCutter(cuttingPlane)
		self.outputPortForMapper = self.cutter.GetOutputPort()
		self.createMapper(False)
		self.createActor()
		rotationDegrees = 45
		self.modifyActorForCuttingPlane(rotationDegrees)
		self.finalizePipeline()
Exemplo n.º 30
0
 def SetIolet(self, iolet):
     self.iolet = iolet
     
     plane = vtkPlane()
     r = iolet.Centre
     plane.SetOrigin(r.x, r.y, r.z)
     n = iolet.Normal
     plane.SetNormal(n.x, n.y, n.z)
     self.cutter.SetCutFunction(plane)
     
     self.regionPicker.SetClosestPoint(r.x, r.y, r.z)
     return
Exemplo n.º 31
0
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Create the RenderWindow, Renderer and both Actors
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
sphere = vtk.vtkSphereSource()
sphere.SetPhiResolution(15)
sphere.SetThetaResolution(30)
plane = vtk.vtkPlane()
plane.SetNormal(1,0,0)
cut = vtk.vtkCutter()
cut.SetInputConnection(sphere.GetOutputPort())
cut.SetCutFunction(plane)
cut.GenerateCutScalarsOn()
strip = vtk.vtkStripper()
strip.SetInputConnection(cut.GetOutputPort())
points = vtk.vtkPoints()
points.InsertPoint(0,1,0,0)
lines = vtk.vtkCellArray()
lines.InsertNextCell(2)
#number of points
lines.InsertCellPoint(0)
lines.InsertCellPoint(0)
tip = vtk.vtkPolyData()
Exemplo n.º 32
0
imageActor = vtk.vtkImageActor()
imageActor.GetMapper().SetInputConnection(mapToColors.GetOutputPort())
imageActor.SetDisplayExtent(32, 32, 0, 63, 0, 92)

#---------------------------------------------------------
# make a transform and some clipping planes
transform = vtk.vtkTransform()
transform.RotateWXYZ(-20, 0.0, -0.7, 0.7)

volume.SetUserTransform(transform)
bone.SetUserTransform(transform)
imageActor.SetUserTransform(transform)

c = volume.GetCenter()

volumeClip = vtk.vtkPlane()
volumeClip.SetNormal(0, 1, 0)
volumeClip.SetOrigin(c[0], c[1], c[2])

boneClip = vtk.vtkPlane()
boneClip.SetNormal(1, 0, 0)
boneClip.SetOrigin(c[0], c[1], c[2])

volumeMapper.AddClippingPlane(volumeClip)
boneMapper.AddClippingPlane(boneClip)

#---------------------------------------------------------
ren.AddViewProp(volume)
ren.AddViewProp(bone)
ren.AddViewProp(imageActor)
Exemplo n.º 33
0
def main():
    colors = vtk.vtkNamedColors()

    fileName, numberOfCuts = get_program_parameters()
    reader = vtk.vtkXMLPolyDataReader()
    reader.SetFileName(fileName)
    reader.Update()

    bounds = reader.GetOutput().GetBounds()
    print('Bounds:', ', '.join(['{:.3f}'.format(f) for f in bounds]))

    plane = vtk.vtkPlane()
    plane.SetOrigin((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[4])
    plane.SetNormal(0, 0, 1)

    # Create cutter
    high = plane.EvaluateFunction((bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, bounds[5])

    cutter = vtk.vtkCutter()
    cutter.SetInputConnection(reader.GetOutputPort())
    cutter.SetCutFunction(plane)
    cutter.GenerateValues(numberOfCuts, 0.99, 0.99 * high)

    cutterMapper = vtk.vtkPolyDataMapper()
    cutterMapper.SetInputConnection(cutter.GetOutputPort())
    cutterMapper.ScalarVisibilityOff()

    # Create cut actor
    cutterActor = vtk.vtkActor()
    cutterActor.GetProperty().SetColor(colors.GetColor3d("Banana"))
    cutterActor.GetProperty().SetLineWidth(2)
    cutterActor.SetMapper(cutterMapper)

    # Create model actor
    modelMapper = vtk.vtkPolyDataMapper()
    modelMapper.SetInputConnection(reader.GetOutputPort())
    modelMapper.ScalarVisibilityOff()

    modelActor = vtk.vtkActor()
    modelActor.GetProperty().SetColor(colors.GetColor3d("Flesh"))
    modelActor.SetMapper(modelMapper)

    # Create renderers and add actors of plane and model
    renderer = vtk.vtkRenderer()
    renderer.AddActor(cutterActor)
    renderer.AddActor(modelActor)

    # Add renderer to renderwindow and render
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(600, 600)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    renderer.SetBackground(colors.GetColor3d("Burlywood"))
    renderer.GetActiveCamera().SetPosition(0, -1, 0)
    renderer.GetActiveCamera().SetFocalPoint(0, 0, 0)
    renderer.GetActiveCamera().SetViewUp(0, 0, 1)
    renderer.GetActiveCamera().Azimuth(30)
    renderer.GetActiveCamera().Elevation(30)

    renderer.ResetCamera()
    renderWindow.Render()
    renderWindow.SetWindowName('CutWithCutFunction')

    interactor.Start()
Exemplo n.º 34
0
def main():
    filename = get_program_parameters()

    # Create the reader for the data.
    reader = vtk.vtkUnstructuredGridReader()
    reader.SetFileName(filename)
    reader.Update()

    bounds = reader.GetOutput().GetBounds()
    center = reader.GetOutput().GetCenter()

    colors = vtk.vtkNamedColors()
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(colors.GetColor3d('Wheat'))
    renderer.UseHiddenLineRemovalOn()

    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindow.SetSize(640, 480)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    xnorm = [-1.0, -1.0, 1.0]

    clipPlane = vtk.vtkPlane()
    clipPlane.SetOrigin(reader.GetOutput().GetCenter())
    clipPlane.SetNormal(xnorm)

    clipper = vtk.vtkTableBasedClipDataSet()
    clipper.SetClipFunction(clipPlane)
    clipper.SetInputData(reader.GetOutput())
    clipper.SetValue(0.0)
    clipper.GenerateClippedOutputOn()
    clipper.Update()

    insideMapper = vtk.vtkDataSetMapper()
    insideMapper.SetInputData(clipper.GetOutput())
    insideMapper.ScalarVisibilityOff()

    insideActor = vtk.vtkActor()
    insideActor.SetMapper(insideMapper)
    insideActor.GetProperty().SetDiffuseColor(colors.GetColor3d('banana'))
    insideActor.GetProperty().SetAmbient(.3)
    insideActor.GetProperty().EdgeVisibilityOn()

    clippedMapper = vtk.vtkDataSetMapper()
    clippedMapper.SetInputData(clipper.GetClippedOutput())
    clippedMapper.ScalarVisibilityOff()

    clippedActor = vtk.vtkActor()
    clippedActor.SetMapper(clippedMapper)
    clippedActor.GetProperty().SetDiffuseColor(colors.GetColor3d('tomato'))
    insideActor.GetProperty().SetAmbient(.3)
    clippedActor.GetProperty().EdgeVisibilityOn()

    # Create transforms to make a better visualization
    insideTransform = vtk.vtkTransform()
    insideTransform.Translate(-(bounds[1] - bounds[0]) * 0.75, 0, 0)
    insideTransform.Translate(center[0], center[1], center[2])
    insideTransform.RotateY(-120.0)
    insideTransform.Translate(-center[0], -center[1], -center[2])
    insideActor.SetUserTransform(insideTransform)

    clippedTransform = vtk.vtkTransform()
    clippedTransform.Translate((bounds[1] - bounds[0]) * 0.75, 0, 0)
    clippedTransform.Translate(center[0], center[1], center[2])
    clippedTransform.RotateY(60.0)
    clippedTransform.Translate(-center[0], -center[1], -center[2])
    clippedActor.SetUserTransform(clippedTransform)

    renderer.AddViewProp(clippedActor)
    renderer.AddViewProp(insideActor)

    renderer.ResetCamera()
    renderer.GetActiveCamera().Dolly(1.4)
    renderer.ResetCameraClippingRange()
    renderWindow.Render()
    renderWindow.SetWindowName('ClipUnstructuredGridWithPlane')
    renderWindow.Render()

    interactor.Start()

    # Generate a report
    numberOfCells = clipper.GetOutput().GetNumberOfCells()
    print('------------------------')
    print('The inside dataset contains a \n', clipper.GetOutput().GetClassName(), ' that has ', numberOfCells, ' cells')
    cellMap = dict()
    for i in range(0, numberOfCells):
        cellMap.setdefault(clipper.GetOutput().GetCellType(i), 0)
        cellMap[clipper.GetOutput().GetCellType(i)] += 1
    # Sort by key and put into an OrderedDict.
    # An OrderedDict remembers the order in which the keys have been inserted.
    for k, v in collections.OrderedDict(sorted(cellMap.items())).items():
        print('\tCell type ', vtk.vtkCellTypes.GetClassNameFromTypeId(k), ' occurs ', v, ' times.')

    numberOfCells = clipper.GetClippedOutput().GetNumberOfCells()
    print('------------------------')
    print('The clipped dataset contains a \n', clipper.GetClippedOutput().GetClassName(), ' that has ', numberOfCells,
          ' cells')
    outsideCellMap = dict()
    for i in range(0, numberOfCells):
        outsideCellMap.setdefault(clipper.GetClippedOutput().GetCellType(i), 0)
        outsideCellMap[clipper.GetClippedOutput().GetCellType(i)] += 1
    for k, v in collections.OrderedDict(sorted(outsideCellMap.items())).items():
        print('\tCell type ', vtk.vtkCellTypes.GetClassNameFromTypeId(k), ' occurs ', v, ' times.')
Exemplo n.º 35
0
    def Execute(self):

        from vmtk import vmtkscripts
        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()
Exemplo n.º 36
0
def Main():
    global continuousSize, continuousType, continuousData, contours, planeSource1s, planeSource2s, planeSource3s, plane1s, plane2s, plane3s, clipper1s, clipper2s, clipper3s, clipX, clipY, clipZ, lut

    print "data: %s" % sys.argv[1]
    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(sys.argv[1])
    reader.Update()

    print "gradientmag: %s" % sys.argv[2]
    gmreader = vtk.vtkStructuredPointsReader()
    gmreader.SetFileName(sys.argv[2])
    gmreader.Update()

    continuousSize = 0
    continuousType = "HSV"
    continuousData = []

    print "params: %s" % sys.argv[3]
    loadParamsFile(sys.argv[3])

    clipX = 0
    clipY = 0
    clipZ = 0

    r = reader.GetOutput().GetScalarRange()
    datamin = r[0]
    datamax = r[1]

    for i in range(4, len(sys.argv)):
        if sys.argv[i] == "--clip":
            print "clip (%s,%s,%s)" % (sys.argv[i + 1], sys.argv[i + 2],
                                       sys.argv[i + 3])
            clipX = float(sys.argv[i + 1])
            clipY = float(sys.argv[i + 2])
            clipZ = float(sys.argv[i + 3])

    clipperActors = []
    planeSource1s = []
    planeSource2s = []
    planeSource3s = []
    plane1s = []
    plane2s = []
    plane3s = []
    clipper1s = []
    clipper2s = []
    clipper3s = []

    for i in range(0, len(continuousData)):
        contours = vtk.vtkContourFilter()
        contours.SetInputConnection(reader.GetOutputPort())
        contours.ComputeNormalsOn()
        contours.SetValue(0, float(continuousData[i][0]))

        planeSource1s.append(vtk.vtkPlaneSource())
        planeSource1s[i].SetNormal(1, 0, 0)
        planeSource1s[i].SetOrigin(clipX, 0, 0)
        plane1s.append(vtk.vtkPlane())
        plane1s[i].SetNormal(planeSource1s[i].GetNormal())
        plane1s[i].SetOrigin(planeSource1s[i].GetOrigin())
        clipper1s.append(vtk.vtkClipPolyData())
        clipper1s[i].SetClipFunction(plane1s[i])
        clipper1s[i].SetInputConnection(contours.GetOutputPort())
        clipper1s[i].Update()

        planeSource2s.append(vtk.vtkPlaneSource())
        planeSource2s[i].SetNormal(0, 1, 0)
        planeSource2s[i].SetOrigin(0, clipY, 0)
        plane2s.append(vtk.vtkPlane())
        plane2s[i].SetNormal(planeSource2s[i].GetNormal())
        plane2s[i].SetOrigin(planeSource2s[i].GetOrigin())
        clipper2s.append(vtk.vtkClipPolyData())
        clipper2s[i].SetClipFunction(plane2s[i])
        clipper2s[i].SetInputConnection(clipper1s[i].GetOutputPort())
        clipper2s[i].Update()

        planeSource3s.append(vtk.vtkPlaneSource())
        planeSource3s[i].SetNormal(0, 0, 1)
        planeSource3s[i].SetOrigin(0, 0, clipZ)
        plane3s.append(vtk.vtkPlane())
        plane3s[i].SetNormal(planeSource3s[i].GetNormal())
        plane3s[i].SetOrigin(planeSource3s[i].GetOrigin())
        clipper3s.append(vtk.vtkClipPolyData())
        clipper3s[i].SetClipFunction(plane3s[i])
        clipper3s[i].SetInputConnection(clipper2s[i].GetOutputPort())
        clipper3s[i].Update()

        probeFilter = vtk.vtkProbeFilter()
        probeFilter.SetInputConnection(0, clipper3s[i].GetOutputPort())
        probeFilter.SetInputConnection(1, gmreader.GetOutputPort())
        probeFilter.Update()

        gmrange = probeFilter.GetOutput().GetScalarRange()
        gmin = gmrange[0]
        gmax = gmrange[1]

        gmclipper1 = vtk.vtkClipPolyData()
        gmclipper1.SetInputConnection(probeFilter.GetOutputPort())
        gmclipper1.InsideOutOff()
        gmclipper1.SetValue(int(continuousData[i][1]))
        gmclipper1.Update()

        gmclipper2 = vtk.vtkClipPolyData()
        gmclipper2.SetInputConnection(gmclipper1.GetOutputPort())
        gmclipper2.InsideOutOn()
        gmclipper2.SetValue(int(continuousData[i][2]))
        gmclipper2.Update()

        lut = vtk.vtkColorTransferFunction()
        if continuousType == "HSV":
            lut.SetColorSpaceToHSV()
            p = continuousData[i]
            print "Color: %s" % p
            lut.AddHSVPoint(p[0], p[3], p[4], p[5])
        elif continuousType == "RGB":
            lut.SetColorSpaceToRGB()
            p = continuousData[i]
            print "Color: %s" % p
            lut.AddRGBPoint(p[0], p[3], p[4], p[5])

        clipperMapper = vtk.vtkPolyDataMapper()
        clipperMapper.SetLookupTable(lut)
        clipperMapper.SetInputConnection(gmclipper2.GetOutputPort())

        clipperActors.append(vtk.vtkActor())
        clipperActors[i].GetProperty().SetRepresentationToWireframe()
        clipperActors[i].SetMapper(clipperMapper)

        backFaces = vtk.vtkProperty()
        backFaces.SetSpecular(0)
        backFaces.SetDiffuse(0)
        backFaces.SetAmbient(0)
        backFaces.SetAmbientColor(1, 0, 0)
        clipperActors[i].SetBackfaceProperty(backFaces)

    lut_color = vtk.vtkColorTransferFunction()
    for d in continuousData:
        if continuousType == "HSV":
            lut_color.SetColorSpaceToHSV()
            lut_color.AddHSVPoint(d[0], d[3], d[4], d[5])
        elif continuousType == "RGB":
            lut_color.SetColorSpaceToRGB()
            lut_color.AddRGBPoint(d[0], d[3], d[4], d[5])

    colorMapper = vtk.vtkPolyDataMapper()
    colorMapper.SetLookupTable(lut_color)

    colorBar = vtkScalarBarActor()
    colorBar.SetLookupTable(colorMapper.GetLookupTable())
    colorBar.SetTitle("isovalue")
    colorBar.SetNumberOfLabels(6)
    colorBar.SetLabelFormat("%4.0f")
    colorBar.SetPosition(0.9, 0.1)
    colorBar.SetWidth(0.1)
    colorBar.SetHeight(0.7)

    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    for i in range(0, len(clipperActors)):
        clipperActors[i].GetProperty().SetOpacity(
            continuousData[i][6])  # load opacity for actor
        ren.AddActor(clipperActors[i])
    ren.AddActor(colorBar)

    # for depth peeling
    ren.SetUseDepthPeeling(1)
    ren.SetMaximumNumberOfPeels(2)  # default 4
    ren.SetOcclusionRatio(0.1)  # default 0

    ren.ResetCamera()
    ren.SetBackground(0.2, 0.3, 0.4)
    ren.ResetCameraClippingRange()

    # for depth peeling
    renWin.SetAlphaBitPlanes(1)
    renWin.SetMultiSamples(0)

    renWin.SetSize(1200, 600)

    clipXSlider = vtk.vtkSliderRepresentation2D()
    clipXSlider.SetMinimumValue(0)
    clipXSlider.SetMaximumValue(300)
    clipXSlider.SetValue(clipX)
    clipXSlider.SetTitleText("X")
    clipXSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipXSlider.GetPoint1Coordinate().SetValue(0.0, 0.3)
    clipXSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipXSlider.GetPoint2Coordinate().SetValue(0.2, 0.3)
    clipXSlider.SetSliderLength(0.02)
    clipXSlider.SetSliderWidth(0.03)
    clipXSlider.SetEndCapLength(0.01)
    clipXSlider.SetEndCapWidth(0.03)
    clipXSlider.SetTubeWidth(0.005)
    clipXSlider.SetLabelFormat("%1.2lf")
    clipXSlider.SetTitleHeight(0.02)
    clipXSlider.SetLabelHeight(0.02)
    SliderWidget2 = vtk.vtkSliderWidget()
    SliderWidget2.SetInteractor(iren)
    SliderWidget2.SetRepresentation(clipXSlider)
    SliderWidget2.KeyPressActivationOff()
    SliderWidget2.SetAnimationModeToAnimate()
    SliderWidget2.SetEnabled(True)
    SliderWidget2.AddObserver("InteractionEvent", clipXSliderHandler)

    clipYSlider = vtk.vtkSliderRepresentation2D()
    clipYSlider.SetMinimumValue(0)
    clipYSlider.SetMaximumValue(300)
    clipYSlider.SetValue(clipY)
    clipYSlider.SetTitleText("Y")
    clipYSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipYSlider.GetPoint1Coordinate().SetValue(0.0, 0.2)
    clipYSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipYSlider.GetPoint2Coordinate().SetValue(0.2, 0.2)
    clipYSlider.SetSliderLength(0.02)
    clipYSlider.SetSliderWidth(0.03)
    clipYSlider.SetEndCapLength(0.01)
    clipYSlider.SetEndCapWidth(0.03)
    clipYSlider.SetTubeWidth(0.005)
    clipYSlider.SetLabelFormat("%1.2lf")
    clipYSlider.SetTitleHeight(0.02)
    clipYSlider.SetLabelHeight(0.02)
    SliderWidget3 = vtk.vtkSliderWidget()
    SliderWidget3.SetInteractor(iren)
    SliderWidget3.SetRepresentation(clipYSlider)
    SliderWidget3.KeyPressActivationOff()
    SliderWidget3.SetAnimationModeToAnimate()
    SliderWidget3.SetEnabled(True)
    SliderWidget3.AddObserver("InteractionEvent", clipYSliderHandler)

    clipZSlider = vtk.vtkSliderRepresentation2D()
    clipZSlider.SetMinimumValue(0)
    clipZSlider.SetMaximumValue(300)
    clipZSlider.SetValue(clipZ)
    clipZSlider.SetTitleText("Z")
    clipZSlider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipZSlider.GetPoint1Coordinate().SetValue(0.0, 0.1)
    clipZSlider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
    clipZSlider.GetPoint2Coordinate().SetValue(0.2, 0.1)
    clipZSlider.SetSliderLength(0.02)
    clipZSlider.SetSliderWidth(0.03)
    clipZSlider.SetEndCapLength(0.01)
    clipZSlider.SetEndCapWidth(0.03)
    clipZSlider.SetTubeWidth(0.005)
    clipZSlider.SetLabelFormat("%1.2lf")
    clipZSlider.SetTitleHeight(0.02)
    clipZSlider.SetLabelHeight(0.02)
    SliderWidget4 = vtk.vtkSliderWidget()
    SliderWidget4.SetInteractor(iren)
    SliderWidget4.SetRepresentation(clipZSlider)
    SliderWidget4.KeyPressActivationOff()
    SliderWidget4.SetAnimationModeToAnimate()
    SliderWidget4.SetEnabled(True)
    SliderWidget4.AddObserver("InteractionEvent", clipZSliderHandler)

    # Render
    iren.Initialize()
    renWin.Render()
    iren.Start()
Exemplo n.º 37
0
def CuttingPlane(a, b, c):
    N = PlaneNormal(a, b, c)
    plane = vtk.vtkPlane()
    plane.SetOrigin(a, 0, 0)
    plane.SetNormal(*N)
    return plane