• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python vtk.vtkMath函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中vtk.vtkMath函数的典型用法代码示例。如果您正苦于以下问题:Python vtkMath函数的具体用法?Python vtkMath怎么用?Python vtkMath使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了vtkMath函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: computeYaw

    def computeYaw(self, markupsNode1, landmark1Index, markupsNode2, landmark2Index, markupsNode3, landmark3Index, markupsNode4, landmark4Index):
        # Yaw is computed by projection on the plan (x,y)
        coord1 = [-1, -1, -1]
        coord2 = [-1, -1, -1]
        coord3 = [-1, -1, -1]
        coord4 = [-1, -1, -1]

        markupsNode1.GetNthFiducialPosition(landmark1Index, coord1)
        markupsNode2.GetNthFiducialPosition(landmark2Index, coord2)
        markupsNode3.GetNthFiducialPosition(landmark3Index, coord3)
        markupsNode4.GetNthFiducialPosition(landmark4Index, coord4)
        
        vectLine1 = [coord2[0]-coord1[0], coord2[1]-coord1[1], 0 ]
        normVectLine1 = numpy.sqrt( vectLine1[0]*vectLine1[0] + vectLine1[1]*vectLine1[1] ) 
        print "vecline1", vectLine1, normVectLine1
        vectLine2 = [coord4[0]-coord3[0],coord4[1]-coord3[1], 0]
        normVectLine2 = numpy.sqrt( vectLine2[0]*vectLine2[0] + vectLine2[1]*vectLine2[1] ) 
        print "vecline2", vectLine2, normVectLine2
        yawNotSigned = round(vtk.vtkMath().DegreesFromRadians(vtk.vtkMath().AngleBetweenVectors(vectLine1, vectLine2)), self.numberOfDecimals)
        print"YAWCOMPUTED",  yawNotSigned
        
        if normVectLine1 != 0 and normVectLine2 != 0:
            normalizedVectLine1 = [(1/normVectLine1)*vectLine1[0], (1/normVectLine1)*vectLine1[1], 0]
            print "normalizedVectLine1" , normalizedVectLine1
            normalizedVectLine2 = [(1/normVectLine2)*vectLine2[0], (1/normVectLine2)*vectLine2[1], 0]
            print "normalizedVectLine2" , normalizedVectLine2
            det2D = normalizedVectLine1[0]*normalizedVectLine2[1] - normalizedVectLine1[1]*normalizedVectLine2[0]
            print det2D
            print math.copysign(yawNotSigned, det2D)
            return math.copysign(yawNotSigned, det2D)
        else:
            print " ERROR, norm of your vector is 0! DEFINE A VECTOR!"
            return None
开发者ID:luciemac,项目名称:Q3DCExtension,代码行数:33,代码来源:Q3DC.py


示例2: calc_seg_perp_vector

def calc_seg_perp_vector(Xpts,Ypts,Zpts,direction):
## @brief Function to calculate the normal to three points. This is used for
#	  the first and last segmentations to specify as an end derivative.
#  @param Xpts, x coordinate for three points
#  @param Ypts, y coordinate for three points
#  @param Zpts, z coordinate for three points
#  @param direction, direction in which the normal should face. The dot
#	  product of this and the normal calculated will be > 0.
#  @return perp, the normal to the given three points
  	math = vtk.vtkMath()

	#Initiate vecs for cross product
	vec1 = [Xpts[1]-Xpts[0],Ypts[1]-Ypts[0],Zpts[1]-Zpts[0]]
	vec2 = [Xpts[2]-Xpts[0],Ypts[2]-Ypts[2],Zpts[2]-Zpts[0]]
	perp = [0.0,0.0,0.0]
	dirl = [0.0,0.0,0.0]
	for i in range(3):
		dirl[i] = direction[i]

	math.Cross(vec1,vec2,perp)
	dotval = math.Dot(perp,dirl)
	if (dotval < 0):
		for i in range(3):
			perp[i] = -1.0*perp[i]

	return perp
开发者ID:vgurev,项目名称:SimVascular,代码行数:26,代码来源:nurbs_lofting.py


示例3: __init__

    def __init__(self):

        self._ROIVisibility = False
        self._ROIStencil = None
        self._IgnoreResetPoints = False
        self._Objects3D = []
        self.bIsConnected = False

        self._Math = vtk.vtkMath()
        self.__Cube = ROICubeFactory.ROICubeFactory()
        self.__Cylinder = ROICylinderFactory.ROICylinderFactory()
        self.__Sphere = ROISphereFactory.ROISphereFactory()

        self.__Cube.SetVisibility(True)
        self.__Cylinder.SetVisibility(False)
        self.__Sphere.SetVisibility(False)

        # two marks for visual cues for key 7 and 8
        self._Mark = []
        for i in range(2):
            m = SphereMarkFactory.SphereMarkFactory()
            m.SetColor(1.0, 1.0, 0.0)
            m.SetSize(10.)
            m.SetOpacity(0.)
            self._Mark.append(m)

        self._Objects3D.append(self.__Cylinder)
        self._Objects3D.append(self.__Cube)
        self._Objects3D.append(self.__Sphere)
        self._Objects3D.append(self._Mark[0])
        self._Objects3D.append(self._Mark[1])

        # Bind some events
        self.__Cube.AddObserver('StartAction', self.onStartAction)
开发者ID:andyTsing,项目名称:MicroView,代码行数:34,代码来源:vtkROIView.py


示例4: display

def display(data, data2=None, data3=None):
    # Generate some random points

    math = vtk.vtkMath()
    points = vtk.vtkPoints()
    
    [data, scalefactor]=scaledata(data)
    for i in range(len(data)):
        points.InsertNextPoint( data[i,0],data[i,1], data[i,2]);
    ballActor = vtksetup(points, color=red, radius=.001)
    [ren,renWin,iren]=vtkwindow()
    ren.AddActor(ballActor) # Add the actors to the renderer, set the background and size
    
    if data2 != None:
        data=data2*scalefactor
        points = vtk.vtkPoints()
        for i in range(len(data)):
            points.InsertNextPoint( data[i,0],data[i,1], data[i,2]);
        ballActor = vtksetup(points, color=blue)
        ren.AddActor(ballActor)
    
    if data3 != None:
        data=data3*scalefactor
        points = vtk.vtkPoints()
        for i in range(len(data)):
            points.InsertNextPoint( data[i,0],data[i,1], data[i,2]);
        ballActor = vtksetup(points, color=green, radius=.007)
        ren.AddActor(ballActor)



    # Interact with the data.
    iren.Initialize()
    renWin.Render()
    iren.Start()
开发者ID:badbytes,项目名称:pymeg,代码行数:35,代码来源:plotvtksurface.py


示例5: defineDistances

 def defineDistances(self, markupsNode1, landmark1Index, markupsNode2, landmark2Index):
     coord1 = [-1, -1, -1]
     coord2 = [-1, -1, -1]
     markupsNode1.GetNthFiducialPosition(landmark1Index, coord1)
     markupsNode2.GetNthFiducialPosition(landmark2Index, coord2)
     print "point A: ", coord1
     print "point B: ", coord2
     diffRAxis = coord2[0] - coord1[0]
     diffAAxis = coord2[1] - coord1[1]
     diffSAxis = coord2[2] - coord1[2]
     threeDDistance = math.sqrt(vtk.vtkMath().Distance2BetweenPoints(coord1, coord2))
     return round(diffRAxis, self.numberOfDecimals), round(diffAAxis, self.numberOfDecimals), round(diffSAxis, self.numberOfDecimals), round(threeDDistance, self.numberOfDecimals)
开发者ID:luciemac,项目名称:Q3DCExtension,代码行数:12,代码来源:Q3DC.py


示例6: AddTimestamp

  def AddTimestamp( self, time, matrix, point, role ):  
    if ( time == self.timePrev ):
      return
    
    if ( self.timePrev == None or self.matrixPrev == None ):
      self.timePrev = time
      self.matrixPrev = vtk.vtkMatrix4x4()
      self.matrixPrev.DeepCopy( matrix )
      return
    
    invertPrev = vtk.vtkMatrix4x4()
    invertPrev.DeepCopy( self.matrixPrev )
    invertPrev.Invert()
    
    currChangeMatrix = vtk.vtkMatrix4x4()
    vtk.vtkMatrix4x4().Multiply4x4( matrix, invertPrev, currChangeMatrix )

    currChangeTransform = vtk.vtkTransform()
    currChangeTransform.SetMatrix( currChangeMatrix )
    
    currVelocity = [ 0, 0, 0 ]
    currChangeTransform.GetPosition( currVelocity )
    
    vtk.vtkMath().MultiplyScalar( currVelocity, 1 / ( time - self.timePrev ) )
    currAbsVelocity = math.sqrt( currVelocity[ 0 ] * currVelocity[ 0 ] + currVelocity[ 1 ] * currVelocity[ 1 ] + currVelocity[ 2 ] * currVelocity[ 2 ] )
    
    currentTestState = ( currAbsVelocity > TranslationalActions.VELOCITY_THRESHOLD )
    
    if ( currentTestState == self.actionState ):
      self.completeActionTime = time
    else:
      if ( ( time - self.completeActionTime ) > TranslationalActions.TIME_THRESHOLD ):
        self.actionState = currentTestState
        self.completeActionTime = time
        if ( currentTestState == 1 ):
          self.numActions += 1
        
    self.timePrev = time
    self.matrixPrev = vtk.vtkMatrix4x4()
    self.matrixPrev.DeepCopy( matrix )
开发者ID:PerkTutor,项目名称:PythonMetrics,代码行数:40,代码来源:TranslationalActions.py


示例7: updateLine

	def updateLine(self):
		"""
		Update the line to be near the selected point
		"""          
		
		self.polyGrid = vtk.vtkUnstructuredGrid()
		self.mapper.SetInput(self.polyGrid)

		
		pts = []
		pts.append((10, 105, 0))
		pts.append((10, 95, 0))
		pts.append((10, 100, 0))
		pts.append((10 + self.widthPx, 100, 0))
		pts.append((10 + self.widthPx, 105, 0))
		pts.append((10 + self.widthPx, 95, 0))
		n, points = self.pointsToPolyline(pts)
		print "widthPx=", 100
		pts2 = [(0, 0, 0), (self.widthPx, 0, 0)]
		n, points2 = self.pointsToPolyline(pts2, 1)
		p1, p2 = points2
		m = vtk.vtkMath()
		x, y, z = p1
		x *= self.voxelSize[0] * 1000000
		y *= self.voxelSize[1] * 1000000
		z *= self.voxelSize[2] * 1000000
		p1 = (x, y, z)
		x, y, z = p2
		x *= self.voxelSize[0] * 1000000
		y *= self.voxelSize[1] * 1000000
		z *= self.voxelSize[2] * 1000000
		p2 = (x, y, z)
		diff = m.Distance2BetweenPoints(p2, p1)

		
		print "got diff=", diff
		self.width = diff

		self.textActor.SetDisplayPosition(-40 + self.widthPx / 2, 80)
		self.textActor.SetInput("%.2fum" % self.width)

		
		self.polyLine.GetPointIds().SetNumberOfIds(n)
		for i in range(n):
			self.polyLine.GetPointIds().SetId(i, i)
		
		self.polyGrid.InsertNextCell(self.polyLine.GetCellType(),
									 self.polyLine.GetPointIds())
		self.polyGrid.SetPoints(points)
开发者ID:chalkie666,项目名称:bioimagexd-svn-import-from-sourceforge,代码行数:49,代码来源:ScaleBar.py


示例8: colorCells

def colorCells (__vtk__temp0=0,__vtk__temp1=0):
    randomColorGenerator = vtk.vtkMath()
    input = randomColors.GetInput()
    output = randomColors.GetOutput()
    numCells = input.GetNumberOfCells()
    colors = vtk.vtkFloatArray()
    colors.SetNumberOfTuples(numCells)
    i = 0
    while i < numCells:
        colors.SetValue(i,randomColorGenerator.Random(0,1))
        i = i + 1

    output.GetCellData().CopyScalarsOff()
    output.GetCellData().PassData(input.GetCellData())
    output.GetCellData().SetScalars(colors)
    del colors
    #reference counting - it's ok
    del randomColorGenerator
开发者ID:timkrentz,项目名称:SunTracker,代码行数:18,代码来源:volTM2DRotateClip.py


示例9: calc_seg_perp_vector

def calc_seg_perp_vector(Xpts,Ypts,Zpts,direction):
  	math = vtk.vtkMath()

	#Initiate vecs for cross product
	vec1 = [Xpts[1]-Xpts[0],Ypts[1]-Ypts[0],Zpts[1]-Zpts[0]]
	vec2 = [Xpts[2]-Xpts[0],Ypts[2]-Ypts[2],Zpts[2]-Zpts[0]]
	perp = [0.0,0.0,0.0]
	dirl = [0.0,0.0,0.0]
	for i in range(3):
		dirl[i] = direction[i]

	math.Cross(vec1,vec2,perp)
	dotval = math.Dot(perp,dirl)
	if (dotval < 0):
		for i in range(3):
			perp[i] = -1.0*perp[i]

	return perp
开发者ID:GeethaE,项目名称:SimVascular,代码行数:18,代码来源:nurbs_lofting.py


示例10: __init__

 def __init__(self, sim, pos, dims, density, fixed=False):
     # ODE initialization
     x, y, z = pos # initial pos
     lx, ly, lz = dims # dimensions
     self.sim = sim # link to the sim object
     self.body = ode.Body(self.sim.world) # ode body
     mass = ode.Mass() # mass object
     mass.setBox(density, lx, ly, lz) # calculate mass
     self.body.setMass(mass) # link mass to body
     self.body.setPosition(pos) # set the initial pos
     self.geom = ode.GeomBox(self.sim.space, lengths=dims) # geometry
     self.geom.setBody(self.body) # link geometry and body
     if fixed:
         self.fixedJoint = ode.FixedJoint(self.sim.world)
         self.fixedJoint.attach(self.body,self.sim.space.getBody())
         self.fixedJoint.setFixed()
     # VTK initialization
     self.math = vtk.vtkMath()
     self.cube = vtk.vtkCubeSource()
     self.cube.SetXLength(lx)
     self.cube.SetYLength(ly)
     self.cube.SetZLength(lz)
     self.cube.SetCenter((0.0,0.0,0.0))
     self.reader = vtk.vtkJPEGReader()
     self.reader.SetFileName(ROBOT_IMAGE)
     self.texture = vtk.vtkTexture()
     transform = vtk.vtkTransform()
     transform.Scale(1.0,1.0,1.0)
     self.texture.SetTransform(transform)
     self.texture.SetInput(self.reader.GetOutput())
     self.mapper = vtk.vtkPolyDataMapper()
     self.mapper.SetInput(self.cube.GetOutput())
     self.actor = vtk.vtkActor()
     self.actor.SetMapper(self.mapper)
     self.actor.SetTexture(self.texture)
     sim.renderer.AddActor(self.actor)
     # Self-include in the bodies for visualization
     sim.bodies.append(self)
开发者ID:fuesika,项目名称:pyrobosim,代码行数:38,代码来源:robot.py


示例11: testPlatonicSolids

    def testPlatonicSolids(self):

        # Create five instances of vtkPlatonicSolidSource
        # corresponding to each of the five Platonic solids.
        #
        tet = vtk.vtkPlatonicSolidSource()
        tet.SetSolidTypeToTetrahedron()
        tetMapper = vtk.vtkPolyDataMapper()
        tetMapper.SetInputConnection(tet.GetOutputPort())
        tetActor = vtk.vtkActor()
        tetActor.SetMapper(tetMapper)

        cube = vtk.vtkPlatonicSolidSource()
        cube.SetSolidTypeToCube()
        cubeMapper = vtk.vtkPolyDataMapper()
        cubeMapper.SetInputConnection(cube.GetOutputPort())
        cubeActor = vtk.vtkActor()
        cubeActor.SetMapper(cubeMapper)
        cubeActor.AddPosition(2.0, 0, 0)

        oct = vtk.vtkPlatonicSolidSource()
        oct.SetSolidTypeToOctahedron()
        octMapper = vtk.vtkPolyDataMapper()
        octMapper.SetInputConnection(oct.GetOutputPort())
        octActor = vtk.vtkActor()
        octActor.SetMapper(octMapper)
        octActor.AddPosition(4.0, 0, 0)

        icosa = vtk.vtkPlatonicSolidSource()
        icosa.SetSolidTypeToIcosahedron()
        icosaMapper = vtk.vtkPolyDataMapper()
        icosaMapper.SetInputConnection(icosa.GetOutputPort())
        icosaActor = vtk.vtkActor()
        icosaActor.SetMapper(icosaMapper)
        icosaActor.AddPosition(6.0, 0, 0)

        dode = vtk.vtkPlatonicSolidSource()
        dode.SetSolidTypeToDodecahedron()
        dodeMapper = vtk.vtkPolyDataMapper()
        dodeMapper.SetInputConnection(dode.GetOutputPort())
        dodeActor = vtk.vtkActor()
        dodeActor.SetMapper(dodeMapper)
        dodeActor.AddPosition(8.0, 0, 0)

        # Create rendering stuff
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        # Add the actors to the renderer, set the background and size
        #
        ren.AddActor(tetActor)
        ren.AddActor(cubeActor)
        ren.AddActor(octActor)
        ren.AddActor(icosaActor)
        ren.AddActor(dodeActor)

        colors = self.Colors()

        # Create a lookup table with colors for each face
        #
        math = vtk.vtkMath()
        lut = vtk.vtkLookupTable()
        lut.SetNumberOfColors(20)
        lut.Build()
        lut.SetTableValue(0, colors.GetRGBAColor("red"))
        lut.SetTableValue(1, colors.GetRGBAColor("lime"))
        lut.SetTableValue(2, colors.GetRGBAColor("yellow"))
        lut.SetTableValue(3, colors.GetRGBAColor("blue"))
        lut.SetTableValue(4, colors.GetRGBAColor("magenta"))
        lut.SetTableValue(5, colors.GetRGBAColor("cyan"))
        lut.SetTableValue(6, colors.GetRGBAColor("spring_green"))
        lut.SetTableValue(7, colors.GetRGBAColor("lavender"))
        lut.SetTableValue(8, colors.GetRGBAColor("mint_cream"))
        lut.SetTableValue(9, colors.GetRGBAColor("violet"))
        lut.SetTableValue(10, colors.GetRGBAColor("ivory_black"))
        lut.SetTableValue(11, colors.GetRGBAColor("coral"))
        lut.SetTableValue(12, colors.GetRGBAColor("pink"))
        lut.SetTableValue(13, colors.GetRGBAColor("salmon"))
        lut.SetTableValue(14, colors.GetRGBAColor("sepia"))
        lut.SetTableValue(15, colors.GetRGBAColor("carrot"))
        lut.SetTableValue(16, colors.GetRGBAColor("gold"))
        lut.SetTableValue(17, colors.GetRGBAColor("forest_green"))
        lut.SetTableValue(18, colors.GetRGBAColor("turquoise"))
        lut.SetTableValue(19, colors.GetRGBAColor("plum"))

        lut.SetTableRange(0, 19)
        tetMapper.SetLookupTable(lut)
        tetMapper.SetScalarRange(0, 19)
        cubeMapper.SetLookupTable(lut)
        cubeMapper.SetScalarRange(0, 19)
        octMapper.SetLookupTable(lut)
        octMapper.SetScalarRange(0, 19)
        icosaMapper.SetLookupTable(lut)
        icosaMapper.SetScalarRange(0, 19)
        dodeMapper.SetLookupTable(lut)
        dodeMapper.SetScalarRange(0, 19)

        cam = ren.GetActiveCamera()
#.........这里部分代码省略.........
开发者ID:151706061,项目名称:VTK,代码行数:101,代码来源:TestPlatonicSolids.py


示例12: distance2

def distance2(pnt1,pnt2):

    return vtk.vtkMath().Distance2BetweenPoints(pnt1,pnt2)
开发者ID:jrper,项目名称:ParticleModule,代码行数:3,代码来源:IO.py


示例13: testSkinOrder

    def testSkinOrder(self):

        # Create the RenderWindow, Renderer and Interactor
        #
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)

        RESOLUTION = 64
        START_SLICE = 50
        END_SLICE = 60
        PIXEL_SIZE = 3.2
        centerX = RESOLUTION / 2
        centerY = RESOLUTION / 2
        centerZ = (END_SLICE - START_SLICE) / 2
        endX = RESOLUTION - 1
        endY = RESOLUTION - 1
        endZ = END_SLICE - 1
        origin = (RESOLUTION / 2.0) * PIXEL_SIZE * -1.0

        math = vtk.vtkMath()

        orders = ["ap", "pa", "si", "iss", "lr", "rl"]
        sliceOrder = SliceOrder.SliceOrder()

        reader = list()
        iso = list()
        mapper = list()
        actor = list()

        skinColors = [
            [0.875950, 0.598302, 0.656878],
            [0.641134, 0.536594, 0.537889],
            [0.804079, 0.650506, 0.558249],
            [0.992896, 0.603716, 0.660385],
            [0.589101, 0.513448, 0.523095],
            [0.650247, 0.700527, 0.752458],
        ]

        for idx, order in enumerate(orders):
            reader.append(vtk.vtkVolume16Reader())
            reader[idx].SetDataDimensions(RESOLUTION, RESOLUTION)
            reader[idx].SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
            reader[idx].SetDataSpacing(PIXEL_SIZE, PIXEL_SIZE, 1.5)
            reader[idx].SetDataOrigin(origin, origin, 1.5)
            reader[idx].SetImageRange(START_SLICE, END_SLICE)
            if order == "ap":
                reader[idx].SetTransform(sliceOrder.ap)
            elif order == "pa":
                reader[idx].SetTransform(sliceOrder.pa)
            elif order == "si":
                reader[idx].SetTransform(sliceOrder.si)
            elif order == "iss":
                reader[idx].SetTransform(sliceOrder.iss)
            elif order == "lr":
                reader[idx].SetTransform(sliceOrder.lr)
            elif order == "rl":
                reader[idx].SetTransform(sliceOrder.rl)
            else:
                s = "No such transform exists."
                raise Exception(s)

            reader[idx].SetHeaderSize(0)
            reader[idx].SetDataMask(0x7FFF)
            reader[idx].SetDataByteOrderToLittleEndian()
            reader[idx].GetExecutive().SetReleaseDataFlag(0, 1)

            iso.append(vtk.vtkContourFilter())
            iso[idx].SetInputConnection(reader[idx].GetOutputPort())
            iso[idx].SetValue(0, 550.5)
            iso[idx].ComputeScalarsOff()
            iso[idx].ReleaseDataFlagOn()

            mapper.append(vtk.vtkPolyDataMapper())
            mapper[idx].SetInputConnection(iso[idx].GetOutputPort())
            mapper[idx].ImmediateModeRenderingOn()

            actor.append(vtk.vtkActor())
            actor[idx].SetMapper(mapper[idx])
            #            r = math.Random(.5, 1)
            #            g = math.Random(.5, 1)
            #            b = math.Random(.5, 1)
            #            print r, g, b
            actor[idx].GetProperty().SetDiffuseColor(
                #                        math.Random(.5, 1), math.Random(.5, 1), math.Random(.5, 1))
                #                        r, g, b)
                skinColors[idx]
            )
            ren.AddActor(actor[idx])

        renWin.SetSize(300, 300)
        ren.ResetCamera()
        ren.GetActiveCamera().Azimuth(210)
        ren.GetActiveCamera().Elevation(30)
        ren.GetActiveCamera().Dolly(1.2)
        ren.ResetCameraClippingRange()

        ren.SetBackground(0.8, 0.8, 0.8)

        # render and interact with data
#.........这里部分代码省略.........
开发者ID:jlec,项目名称:VTK,代码行数:101,代码来源:skinOrder.py


示例14: SetRandomSeed

def SetRandomSeed(caller, eventId):
    #print "Restart random number generator"
    raMath = vtk.vtkMath()
    raMath.RandomSeed(6)
开发者ID:0004c,项目名称:VTK,代码行数:4,代码来源:TestOpacityVectors.py


示例15: display

def display(data, datascalevec=None, radius=None, color=None, shape_type=None):
    """display(data, radius=1, datascalevec=.5):
    or
    r = random.randn(10,3)
    d = {1:r,2:r+2}
    plotvtk.display(d,color=[[255,0,0],[0,0,255]],radius=[[.004],[.01]])
    or
    radius={'0':.004,'1':.004}
    color={'0':[255,0,0],'1':[0,0,255]}
    plotvtk.display(d,color=color,radius=radius)
    """
    try:
        if shape(data)[0] == 3 and shape(data)[1] != 3:
            print "array is probably transposed wrong. transposing"
            data = transpose(data)
    except IndexError:  # it probably a dictionary
        pass
        for i in data.keys():
            if len(shape(data[i])) == 1:
                # data 1D array
                pass

            elif shape(data[i])[0] == 3 and shape(data[i])[1] != 3:
                print "dictionary array is probably transposed wrong. transposing"
                data[i] = transpose(data[i])

    # set some defaults if nothing defined
    defcolor = array([[255, 0, 0]])  # red
    defradius = array([[0.004]])

    # Adding feature to handle a single array or a dictionary of arrays
    # so as to handle multiple data.
    if type(data) == dict:
        for d in data.keys():
            numdata = len(data[d])
            if color == None:
                # color = red
                print "making default color scheme"
                color = array(
                    [
                        arange(0, 255, 255 / len(data[d]))[::-1],
                        arange(0, 255, 255 / len(data[d])),
                        arange(0, 255, 255 / len(data[d])),
                    ]
                ).T

            if radius == None:
                radius = tile([defradius], len(data[d])).T
    else:
        print "data in non dict form"
        data = {1: data}
        radius = defradius
        color = defcolor

    [ren, renWin, iren] = vtkwindow()
    print "ln", len(data.keys())
    for k in range(0, len(data.keys())):
        print shape(data[data.keys()[k]])  # , len(data[k]), shape(color)

        if k == -1:
            [sdata, scalefactor] = scaledata(float_(data[data.keys()[k]]))
            print "scaled data"
        else:
            sdata = float_(data[data.keys()[k]])

        points = vtk.vtkPoints()
        math = vtk.vtkMath()
        # some 2 pnts of fake data at 0,0,0
        pointsfake = vtk.vtkPoints()
        pointsfake.InsertNextPoint(0, 0, 0)
        pointsfake.InsertNextPoint(0, 0, 0)
        pointsfake.InsertNextPoint(0, 0, 0)
        ballActor, profile = vtkpoints(pointsfake, color=[0, 255, 0], radius=0.0000)  # radius[k])
        ren.AddActor(ballActor)  # Add the actors to the renderer, set the background and size
        # end of fake data

        print "lengthofdata", len(sdata)
        if len(shape(sdata)) == 1:  # add dimension
            sdata = array([sdata])
        if len(sdata) < 3:  # tile to fix some bug where no points plotted unless = or greater than 3 points
            sdata = tile(sdata, [3 - len(sdata) + 1, 1])
        print "len", len(sdata)
        for i in range(len(sdata)):
            points.InsertNextPoint(sdata[i, 0], sdata[i, 1], sdata[i, 2])

        # make color and radius dictonaries.
        if type(color) == list and type(radius) == list:
            c = {}
            r = {}
            for cr in range(0, len(color)):
                c[cr] = color[cr]
            for cr in range(len(radius)):
                r[cr] = radius[cr]
            color = c
            radius = r

        print k
        # print shape_type.keys()[k]#shape_type[shape_type.keys()[k]]
        try:
            if shape_type.keys()[k] == "points":
#.........这里部分代码省略.........
开发者ID:neurodebian,项目名称:pymeg,代码行数:101,代码来源:plotvtk.py


示例16:

imageSource = vtk.vtkRTAnalyticSource()
imageSource.SetWholeExtent(extent[0], extent[1], extent[2], extent[3],
                           extent[4], extent[5])
imageSource.SetCenter(center)
imageSource.Update()

img = imageSource.GetOutput()
scalarRange = img.GetScalarRange()
origin = img.GetOrigin()
spacing = img.GetSpacing()


# create an unstructured grid by generating a point cloud and
# applying Delaunay triangulation on it.
vtk.vtkMath().RandomSeed(0) # vtkPointSource internally uses vtkMath::Random()
pointSource = vtk.vtkPointSource()
pointSource.SetCenter(center)
pointSource.SetRadius(center[0])
pointSource.SetNumberOfPoints(24 * 24 * 24)

delaunay3D = vtk.vtkDelaunay3D()
delaunay3D.SetInputConnection(pointSource.GetOutputPort())

# probe into img using unstructured grif geometry
probe1 = vtk.vtkProbeFilter()
probe1.SetSourceData(img)
probe1.SetInputConnection(delaunay3D.GetOutputPort())

# probe into the unstructured grid using ImageData geometry
outputData = vtk.vtkImageData()
开发者ID:ALouis38,项目名称:VTK,代码行数:30,代码来源:TestProbeFilterImageInput.py


示例17: GetSemiUniDistnaceGrid

    def GetSemiUniDistnaceGrid(
        self, m_holePerSlice, m_numberOfSlice, m_errorTolerance=1, m_startPadding=0, m_endPadding=0, m_bufferDeg=40
    ):
        """
        Obtain a set of coordinates roughly equal to a projection of periodic square grid vertex on the arm
        surface. The gird also can arbitrarily has a buffer zone where no holes are drilled.

        :param m_holePerSlice:      [int]   Desired number of holes per slice
        :param m_numberOfSlice:     [int]   Desired number of slices
        :param m_errorTolerance:    [float] The maximum allowed deviation of hole coordinate from idea grid
        :param m_startPadding:      [int]   Starting side padding where no holes will be drilled
        :param m_endPadding:        [int]   Ending side padding where no holes will be drilled
        :param m_bufferDeg:         [float] Angle between planes where buffers zones are in between. Default to 40
        :return: [list] List of hole coordinates
        """
        vtkmath = vtk.vtkMath()

        if not self._centerLine._IS_READ_FLAG:
            self._centerLine.Read()

        if self._bufferAngle != None:
            m_bufferDeg = self._bufferAngle

        m_totalDistance = 0
        for i in xrange(
            1 + int(m_startPadding / 0.3), self._centerLine._data.GetNumberOfPoints() - int(m_endPadding / 0.3)
        ):
            m_totalDistance += self._centerLine.GetDistance(i, i - 1)

        # Shrink the distance a bit before deviding it so that all intervals will lie in the padded segment
        m_sliceSpacing = (m_totalDistance) * 0.98 / (m_numberOfSlice)
        m_intervalIndexes = self._centerLine.GetEqualDistanceIntervalsIndex(
            m_sliceSpacing, m_startPadding, m_endPadding
        )
        self._centerLineIntervals = m_intervalIndexes

        m_tangents = []
        for k in xrange(len(m_intervalIndexes)):
            m_tmp = self._centerLine.GetNormalizedTangent(m_intervalIndexes[k], range=12, step=3)
            m_tangents.append(m_tmp)

        m_average = [sum([m_tangents[i][j] for i in xrange(3)]) / float(len(m_tangents)) for j in xrange(3)]

        m_openingList = []
        m_holeList = []
        m_alphaNormal = None
        m_masterPt = self._centerLine.GetPoint(m_intervalIndexes[0])

        # Define cast opening zone and start drilling zone
        if m_bufferDeg != None and self._openingMarker != None:
            m_kdtree = vtk.vtkKdTreePointLocator()
            m_kdtree.SetDataSet(self._centerLine._data)
            m_kdtree.BuildLocator()
            m_closestCenterlinePointId = m_kdtree.FindClosestPoint(self._openingMarker)
            m_closestCenterlinePoint = self._centerLine.GetPoint(m_closestCenterlinePointId)
            m_masterPt = m_closestCenterlinePoint

        # Drill along intervals
        for i in xrange(len(m_intervalIndexes)):
            l_sliceCenter = self._centerLine.GetPoint(m_intervalIndexes[i])
            l_slice = self.SliceSurface(l_sliceCenter, m_average)
            if i == 0:
                # Define the starting vector for all slice
                # l_ringAlphaPt = l_slice.GetPoint(i)
                l_ringAlphaVect = [self._openingMarker[j] - m_masterPt[j] for j in xrange(3)]
                m_alphaNormal = [0, 0, 0]
                vtkmath.Cross(m_average, l_ringAlphaVect, m_alphaNormal)
                m_alphaNormalMag = sum([m_alphaNormal[i] for i in xrange(3)])
                m_alphaNormal = [m_alphaNormal[i] / m_alphaNormalMag for i in xrange(3)]

            # Define an initial accuracy which relax if no suitable points is found, affects calculation speed
            m_loopAccuracy = 0.25
            m_ringSliceAlphaVect = None
            while m_ringSliceAlphaVect == None:
                for j in xrange(l_slice.GetNumberOfPoints()):
                    l_ringSliceAlphaVect = [l_slice.GetPoint(j)[k] - l_sliceCenter[k] for k in xrange(3)]
                    # l_ringSliceMasterVect = [l_slice.GetPoint(j)[k] - m_masterPt[k] for k in xrange(3)]
                    if (
                        math.fabs(vtkmath.Dot(l_ringSliceAlphaVect, m_alphaNormal)) < m_loopAccuracy
                        and vtkmath.Dot(l_ringSliceAlphaVect, l_ringAlphaVect) > 0
                    ):
                        m_ringSliceAlphaVect = l_ringSliceAlphaVect
                        break
                m_loopAccuracy *= 2
                if m_loopAccuracy >= 10:
                    raise ValueError("Slice Alpha Vector search reaches maximum tolerance")
                    break

            l_uniformSectionDegree = (360.0 - m_bufferDeg) / m_holePerSlice
            l_sectionDegree = (360.0 - m_bufferDeg) / m_holePerSlice
            l_loopbreak = 0
            m_openingList.append(
                [l_ringSliceAlphaVect[k] + l_sliceCenter[k] for k in xrange(3)]
            )  # Include first vector
            l_holeList = []
            while len(l_holeList) < m_holePerSlice - 1:
                if len(l_holeList) == 0:
                    l_sectionDegree += m_bufferDeg / 2
                for j in xrange(l_slice.GetNumberOfPoints()):
                    l_p1 = [0.0, 0.0, 0.0]
#.........这里部分代码省略.........
开发者ID:teracamo,项目名称:vtkSemiUniformGridding,代码行数:101,代码来源:PolyDataHandler.py


示例18:

t.Translate(1.1,0,0)
tf = vtk.vtkTransformFilter()
tf.SetTransform(t)
tf.SetInputConnection(disk.GetOutputPort())
strips = vtk.vtkStripper()
strips.SetInputConnection(tf.GetOutputPort())
strips.Update()
app = vtk.vtkAppendPolyData()
app.AddInputData(disk.GetOutput())
app.AddInputData(strips.GetOutput())
app.Update()
model = app.GetOutput()
extrude = vtk.vtkLinearExtrusionFilter()
extrude.SetInputData(model)
# create random cell scalars for the model before extrusion.
rn = vtk.vtkMath()
rn.RandomSeed(1230)
cellColors = vtk.vtkUnsignedCharArray()
cellColors.SetNumberOfComponents(3)
cellColors.SetNumberOfTuples(model.GetNumberOfCells())
i = 0
while i < model.GetNumberOfCells():
    cellColors.InsertComponent(i,0,rn.Random(100,255))
    cellColors.InsertComponent(i,1,rn.Random(100,255))
    cellColors.InsertComponent(i,2,rn.Random(100,255))
    i = i + 1

model.GetCellData().SetScalars(cellColors)
# Lets test the arrow source instead of creating another test.
arrow1 = vtk.vtkArrowSource()
mapper1 = vtk.vtkPolyDataMapper()
开发者ID:timkrentz,项目名称:SunTracker,代码行数:31,代码来源:extrudeCopyCD.py


示例19: testParametricFunctions


#.........这里部分代码省略.........
        # ------------------------------------------------------------
        superEllipsoid = vtk.vtkParametricSuperEllipsoid()
        superEllipsoid.SetXRadius(1.25)
        superEllipsoid.SetYRadius(1.5)
        superEllipsoid.SetZRadius(1.0)
        superEllipsoid.SetN1(1.1)
        superEllipsoid.SetN2(1.75)
        superEllipsoidSource = vtk.vtkParametricFunctionSource()
        superEllipsoidSource.SetParametricFunction(superEllipsoid)
        superEllipsoidSource.SetScalarModeToV()

        superEllipsoidMapper = vtk.vtkPolyDataMapper()
        superEllipsoidMapper.SetInputConnection(superEllipsoidSource.GetOutputPort())
        superEllipsoidMapper.SetScalarRange(0, 3.14)

        superEllipsoidActor = vtk.vtkActor()
        superEllipsoidActor.SetMapper(superEllipsoidMapper)
        superEllipsoidActor.SetPosition(8, 4, 0)

        superEllipsoidTextMapper = vtk.vtkTextMapper()
        superEllipsoidTextMapper.SetInput("Super.Ellipsoid")
        superEllipsoidTextMapper.GetTextProperty().SetJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        superEllipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0)
        superEllipsoidTextMapper.GetTextProperty().SetFontSize(14)
        superEllipsoidTextActor = vtk.vtkActor2D()
        superEllipsoidTextActor.SetMapper(superEllipsoidTextMapper)
        superEllipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        superEllipsoidTextActor.GetPositionCoordinate().SetValue(8, 1.5, 0)

        # ------------------------------------------------------------
        # Create an open 1D spline
        # ------------------------------------------------------------
        math = vtk.vtkMath()
        inputPoints = vtk.vtkPoints()
        for i in range(0, 10):
            x = math.Random(-1, 1)
            y = math.Random(-1, 1)
            z = math.Random(-1, 1)
            inputPoints.InsertPoint(i,x,y,z)

        spline = vtk.vtkParametricSpline()
        spline.SetPoints(inputPoints)
        spline.ClosedOff()
        splineSource = vtk.vtkParametricFunctionSource()
        splineSource.SetParametricFunction(spline)

        splineMapper = vtk.vtkPolyDataMapper()
        splineMapper.SetInputConnection(splineSource.GetOutputPort())

        splineActor = vtk.vtkActor()
        splineActor.SetMapper(splineMapper)
        splineActor.SetPosition(16, 4, 0)
        splineActor.GetProperty().SetColor(0, 0, 0)

        splineTextMapper = vtk.vtkTextMapper()
        splineTextMapper.SetInput("Open.Spline")
        splineTextMapper.GetTextProperty().SetJustificationToCentered()
        splineTextMapper.GetTextProperty().SetVerticalJustificationToCentered()
        splineTextMapper.GetTextProperty().SetColor(1, 0, 0)
        splineTextMapper.GetTextProperty().SetFontSize(14)
        splineTextActor = vtk.vtkActor2D()
        splineTextActor.SetMapper(splineTextMapper)
        splineTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld()
        splineTextActor.GetPositionCoordinate().SetValue(16, 1.5, 0)
开发者ID:AndreasFetzer,项目名称:VTK,代码行数:66,代码来源:TestParametricFunctions.py


示例20: vtkGetDataRoot

#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()

# Generate random planes to form a convex polyhedron.
# Create a polyhedral representation of the planes.
# get the interactor ui
# create some points laying between 1<=r<5 (r is radius)
# the points also have normals pointing away from the origin.
#
mathObj = vtk.vtkMath()
points = vtk.vtkPoints()
normals = vtk.vtkFloatArray()
normals.SetNumberOfComponents(3)
i = 0
while i < 100:
    radius = 1.0
    theta = mathObj.Random(0,360)
    phi = mathObj.Random(0,180)
    x = expr.expr(globals(), locals(),["radius","*","sin","(","phi",")*","cos","(","theta",")"])
    y = expr.expr(globals(), locals(),["radius","*","sin","(","phi",")*","sin","(","theta",")"])
    z = expr.expr(globals(), locals(),["radius","*","cos","(","phi",")"])
    points.InsertPoint(i,x,y,z)
    normals.InsertTuple3(i,x,y,z)
    i = i + 1

planes = vtk.vtkPlanes()
planes.SetPoints(points)
planes.SetNormals(normals)
开发者ID:151706061,项目名称:VTK,代码行数:31,代码来源:hull.py



注:本文中的vtk.vtkMath函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python vtk.vtkMatrix4x4函数代码示例发布时间:2022-05-26
下一篇:
Python vtk.vtkMassProperties函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap