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
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)
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
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()
def get_arrow_orintation(endPoint, startPoint, norm=[0, 0, 1]): """ Compute orientation matrix.""" normalizedX = zero3() normalizedY = zero3() normalizedZ = zero3() math = vtk.vtkMath() math.Subtract(endPoint, startPoint, normalizedX) length = math.Norm(normalizedX) math.Normalize(normalizedX) # The Z axis is an arbitrary vector cross X math.Cross(normalizedX, norm, normalizedZ) math.Normalize(normalizedZ) # The Y axis is Z cross X math.Cross(normalizedZ, normalizedX, normalizedY) # Create the direction cosine matrix matrix = vtk.vtkMatrix4x4() matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) return matrix, length
def __init__(self, startPoint, endPoint, zAxis, clr2plt): super().__init__() colors = vtk.vtkNamedColors() USER_MATRIX = False # Create an arrow. arrowSource = vtk.vtkArrowSource() # Compute a basis normalizedX = [0 for i in range(3)] normalizedY = [0 for i in range(3)] normalizedZ = [0 for i in range(3)] # The X axis is a vector from start to end math = vtk.vtkMath() math.Subtract(endPoint, startPoint, normalizedX) length = math.Norm(normalizedX) print(length) math.Normalize(normalizedX) # The Z axis is an arbitrary vector cross X arbitrary = zAxis math.Cross(normalizedX, arbitrary, normalizedZ) math.Normalize(normalizedZ) # The Y axis is Z cross X math.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) # Apply the transforms transform = vtk.vtkTransform() transform.Translate(startPoint) transform.Concatenate(matrix) transform.Scale(length, length, length) # Transform the polydata transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetTransform(transform) transformPD.SetInputConnection(arrowSource.GetOutputPort()) # Create a mapper and actor for the arrow mapper = vtk.vtkPolyDataMapper() if USER_MATRIX: mapper.SetInputConnection(arrowSource.GetOutputPort()) self.SetUserMatrix(transform.GetMatrix()) else: mapper.SetInputConnection(transformPD.GetOutputPort()) self.SetMapper(mapper) self.GetProperty().SetColor(colors.GetColor3d(clr2plt)) renderer.AddActor(self)
def get_actor_from_arrow_vector(start_point, end_point, color=(0, 0, 0), line_width=20): arrow_source = vtk.vtkArrowSource() random.seed(8775070) # Compute a basis normalized_x = [0] * 3 normalized_y = [0] * 3 normalized_z = [0] * 3 # The X axis is a vector from start to end math = vtk.vtkMath() math.Subtract(end_point, start_point, normalized_x) length = math.Norm(normalized_x) math.Normalize(normalized_x) # The Z axis is an arbitrary vector cross X arbitrary = [0] * 3 arbitrary[0] = random.uniform(-10, 10) arbitrary[1] = random.uniform(-10, 10) arbitrary[2] = random.uniform(-10, 10) math.Cross(normalized_x, arbitrary, normalized_z) math.Normalize(normalized_z) # The Y axis is Z cross X math.Cross(normalized_z, normalized_x, normalized_y) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalized_x[i]) matrix.SetElement(i, 1, normalized_y[i]) matrix.SetElement(i, 2, normalized_z[i]) # Apply the transforms transform = vtk.vtkTransform() transform.Translate(start_point) transform.Concatenate(matrix) transform.Scale(length, line_width, line_width) # Transform the polydata transform_pd = vtk.vtkTransformPolyDataFilter() transform_pd.SetTransform(transform) transform_pd.SetInputConnection(arrow_source.GetOutputPort()) # Create a mapper and actor for the arrow mapper = vtk.vtkPolyDataMapper() actor = vtk.vtkActor() mapper.SetInputConnection(transform_pd.GetOutputPort()) actor.SetMapper(mapper) actor.GetProperty().SetColor(color[0], color[1], color[2]) return actor
def hsv2rgb(hsv): """Convert HSV to RGB color. :param hsv: """ ma = vtk.vtkMath() return ma.HSVToRGB(hsv)
def SetQuatOrientation( self, quaternion, shift, i_actor ): # if not self.iniOk : # raise Exception("vtpDrawScene not initialized. Call initScene() first") # Convert quat to the rotation matrix # self.mtxRot = [[0,0,0],[0,0,0],[0,0,0]] vtk.vtkMath().QuaternionToMatrix3x3(quaternion, self.mtxRot[i_actor]) # print(self.mtxRot[i_actor]) # norm matrix self.mtxRot[i_actor] = np.array(self.mtxRot[i_actor]).dot(np.array(self.norm_mat[i_actor])) # Rotation: convert 3x3 to 4x4 matrix mtxTr2 = vtk.vtkMatrix4x4() # identity mtx for i in range(3): for j in range(3) : mtxTr2.SetElement(i, j, self.mtxRot[i_actor][i][j]) # three transforms: # 1. move the object so the rotation center is in the coord center tr = vtk.vtkTransform() origin = np.array(self.modelActor[i_actor].GetOrigin()) position = np.array(self.modelActor[i_actor].GetPosition()) #trans = origin + position trans = position #trans = origin tr.Translate(-trans) mtxTr1 = tr.GetMatrix() # 2. rotate around coord center using mtxTr2 mtxTr12 = vtk.vtkMatrix4x4() vtk.vtkMatrix4x4().Multiply4x4 (mtxTr2, mtxTr1, mtxTr12) ## 3. move the object back tr = vtk.vtkTransform() tr.Translate(trans + np.array(shift)) mtxTr3 = tr.GetMatrix() mtxTr123 = vtk.vtkMatrix4x4() vtk.vtkMatrix4x4().Multiply4x4 (mtxTr3, mtxTr12, mtxTr123) tr = vtk.vtkTransform() tr.PreMultiply() # tr.PostMultiply() tr.Concatenate(mtxTr123) self.modelActor[i_actor].SetUserTransform(tr)
def get_distance(self, v0_id, v1_id): # Get 3d vector from id p0 = self.get_point(v0_id) p1 = self.get_point(v1_id) squaredDistance = vtk.vtkMath().Distance2BetweenPoints(p0, p1) return np.sqrt(squaredDistance)
def SetQuatOrientation(self, quaternion): if not self.iniOk: raise Exception( "vtpDrawScene not initialized. Call initScene() first") # Convert quat to the rotation matrix mtxRot = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] vtk.vtkMath().QuaternionToMatrix3x3(quaternion, mtxRot) # Rotation: convert 3x3 to 4x4 matrix mtxTr2 = vtk.vtkMatrix4x4() # identity mtx for i in range(3): for j in range(3): mtxTr2.SetElement(i, j, mtxRot[i][j]) self.modelActor.SetUserMatrix(mtxTr2) self.renWin.Render()
def rgb2hsv(rgb): """Convert RGB to HSV color. :param rgb: """ ma = vtk.vtkMath() return ma.RGBToHSV(getColor(rgb))
def wind_actor(x, y, speed, deg): arrow_length = speed * 10 arrow_source = vtk.vtkArrowSource() arrow_source.SetShaftResolution(50) arrow_source.SetTipResolution(50) start_point = [x, y, 25] end_point = [x - arrow_length * sin(radians(deg)), y - arrow_length * cos(radians(deg)), 25] normalizedX = [0 for i in range(3)] normalizedY = [0 for i in range(3)] normalizedZ = [0 for i in range(3)] # The X axis is a vector from start to end math = vtk.vtkMath() math.Subtract(end_point, start_point, normalizedX) length = math.Norm(normalizedX) math.Normalize(normalizedX) # The Z axis is an arbitrary vector cross X arbitrary = [0 for i in range(3)] arbitrary[0] = 1 arbitrary[1] = 1 arbitrary[2] = 1 math.Cross(normalizedX, arbitrary, normalizedZ) math.Normalize(normalizedZ) # The Y axis is Z cross X math.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalizedX[i]) matrix.SetElement(i, 1, normalizedY[i]) matrix.SetElement(i, 2, normalizedZ[i]) transform = vtk.vtkTransform() transform.Translate(start_point) transform.Concatenate(matrix) transform.Scale(length, length, length) transform_filter = vtk.vtkTransformPolyDataFilter() transform_filter.SetTransform(transform) transform_filter.SetInputConnection(arrow_source.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(transform_filter.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(255, 0, 0) actor.SetVisibility(True) return actor
def ResamplePoints(self, originalPoints, sampledPoints, samplingDistance, closedCurve): if (not originalPoints or not sampledPoints or samplingDistance <= 0): print("ResamplePoints failed: invalid inputs") return False if (originalPoints.GetNumberOfPoints() < 2): sampledPoints.DeepCopy(originalPoints) return True distanceFromLastSampledPoint = 0 previousCurvePoint = originalPoints.GetPoint(0) sampledPoints.Reset() sampledPoints.InsertNextPoint( previousCurvePoint) # First point in new set is always point 0 numberOfOriginalPoints = originalPoints.GetNumberOfPoints() totalSegmentLength = 0 for originalPointIndex in range(numberOfOriginalPoints): currentCurvePoint = originalPoints.GetPoint(originalPointIndex) segmentLength = math.sqrt(vtk.vtkMath().Distance2BetweenPoints( currentCurvePoint, previousCurvePoint)) totalSegmentLength += segmentLength if segmentLength <= 0: continue remainingSegmentLength = distanceFromLastSampledPoint + segmentLength if round(remainingSegmentLength, 4) >= round(samplingDistance, 4): segmentDirectionVector = np.array([ (currentCurvePoint[0] - previousCurvePoint[0]) / segmentLength, (currentCurvePoint[1] - previousCurvePoint[1]) / segmentLength, (currentCurvePoint[2] - previousCurvePoint[2]) / segmentLength ]) # distance of new sampled point from previous curve point distanceFromLastInterpolatedPoint = samplingDistance - distanceFromLastSampledPoint while (round(remainingSegmentLength, 4) >= round( samplingDistance, 4)): newSampledPoint = np.array([ previousCurvePoint[0] + segmentDirectionVector[0] * distanceFromLastInterpolatedPoint, previousCurvePoint[1] + segmentDirectionVector[1] * distanceFromLastInterpolatedPoint, previousCurvePoint[2] + segmentDirectionVector[2] * distanceFromLastInterpolatedPoint ]) sampledPoints.InsertNextPoint(newSampledPoint) distanceFromLastSampledPoint = 0 distanceFromLastInterpolatedPoint += samplingDistance remainingSegmentLength -= samplingDistance distanceFromLastSampledPoint = remainingSegmentLength else: distanceFromLastSampledPoint += segmentLength previousCurvePoint = currentCurvePoint return True
def addVector(self, quaternion): # make mapper for the data arrowSource = vtk.vtkArrowSource() arrowSource.SetShaftRadius(0.01) arrowSource.SetTipLength(.1) # arrowSource.SetNormalizedTipLength(0.05, 0.05, 0.05) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(arrowSource.GetOutputPort()) # create actor, set its mapper self.modelActor.append(vtk.vtkActor()) el = len(self.modelActor) - 1 self.modelActor[el].SetMapper(mapper) # Add the actor to the renderer, set the background and size. self.ren.AddActor(self.modelActor[el]) # self.mtxRot.append([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) # Get center of the bounding box origin = self.modelActor[el].GetCenter() # Set rotation center self.modelActor[el].SetOrigin(origin) self.modelActor[el].SetPosition([-0.016, -0.006, -0.162]) mtxRot = np.identity(3) vtk.vtkMath().QuaternionToMatrix3x3(quaternion, mtxRot) # Rotation: convert 3x3 to 4x4 matrix mtxTr = vtk.vtkMatrix4x4() # identity mtx for i in range(3): for j in range(3): mtxTr.SetElement(i, j, mtxRot[i][j]) tr = vtk.vtkTransform() tr.PreMultiply() tr.Concatenate(mtxTr) self.modelActor[el].SetUserTransform(tr)
def sliceClosestModel(self, point): originalModel = None # set up plane normal = np.array([ float(self.sliceLogic.GetSliceNode().GetName() == name) for name in ['Yellow', 'Green', 'Red'] ]) plane = vtk.vtkPlane() plane.SetOrigin(point) # point in plane plane.SetNormal(normal) # set up cutter cutter = vtk.vtkCutter() cutter.SetCutFunction(plane) cutter.SetGenerateCutScalars(0) cutter.Update() # init point locator and output pointsLocator = vtk.vtkPointLocator() globalMinDistance = 1000 outPolyData = vtk.vtkPolyData() # iterate over models in scene nModels = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLModelNode') for i in range(nModels): model = slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLModelNode') polyData = model.GetPolyData() if model.GetDisplayNode() and model.GetDisplayNode().GetVisibility( ) and polyData.GetNumberOfCells() > 1 and model.GetName( ) != 'auxSphereModel': # model visible and cells available cutter.SetInputData(polyData) cutter.Update() cutterOutput = cutter.GetOutput() if cutterOutput.GetNumberOfCells( ): # model intersects with plane # get distance from input point to closest point in model pointsLocator.SetDataSet(cutterOutput) pointsLocator.BuildLocator() closestPoint = cutterOutput.GetPoint( pointsLocator.FindClosestPoint(point)) localMinDistance = vtk.vtkMath().Distance2BetweenPoints( closestPoint, point) if localMinDistance < globalMinDistance: # new min outPolyData.DeepCopy(cutterOutput) globalMinDistance = localMinDistance originalModel = model # return in case no model found if not originalModel: return False, False # generate output triangulator = vtk.vtkContourTriangulator() triangulator.SetInputData(outPolyData) triangulator.Update() slicedModel = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode') slicedModel.SetAndObservePolyData(triangulator.GetOutput()) slicedModel.CreateDefaultDisplayNodes() slicedModel.GetDisplayNode().SetVisibility(0) return slicedModel, originalModel
def __init__(self, path): reader = vtk.vtkOBJReader() reader.SetFileName(path) reader.Update() self.obj = reader.GetOutput() self.math = vtk.vtkMath() # renderer self.ren = vtk.vtkRenderer() self.ren.SetBackground(ColorBackground) self.actors = {}
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)
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 )
def feed_points_to_polydatavtk(self, xs, ys, zs): ''' class method to load a vtk polydata object with a cloud of points xs,ys,zs=[x,x1,...],[y,y1,...],[z,z1,...] indicating locations of nodes to be meshed return:vtk polydata object ''' math = vtk.vtkMath() points = vtk.vtkPoints() for i in range(len(xs)): points.InsertPoint(i, xs[i], ys[i], zs[i]) profile = vtk.vtkPolyData() profile.SetPoints(points) return (profile)
def calcTransform(self, listLimbPoints): startPoint = [0 for i in range(3)] endPoint = [0 for i in range(3)] center = [0 for i in range(3)] normalizedX = [0 for i in range(3)] normalizedY = [0 for i in range(3)] normalizedZ = [0 for i in range(3)] math = vtk.vtkMath() arbitrary = [0 for i in range(3)] matrix = vtk.vtkMatrix4x4() arbitrary[0] = random.uniform(-10, 10) arbitrary[1] = random.uniform(-10, 10) arbitrary[2] = random.uniform(-10, 10) transform = vtk.vtkTransform() startPoint[0] = -listLimbPoints[0] startPoint[1] = -listLimbPoints[1] startPoint[2] = listLimbPoints[2] endPoint[0] = -listLimbPoints[3] endPoint[1] = -listLimbPoints[4] endPoint[2] = listLimbPoints[5] center[0] = (endPoint[0] + startPoint[0]) / 2 center[1] = (endPoint[1] + startPoint[1]) / 2 center[2] = (endPoint[2] + startPoint[2]) / 2 math.Subtract(endPoint, startPoint, normalizedX) length = math.Norm(normalizedX) math.Normalize(normalizedX) math.Cross(normalizedX, arbitrary, normalizedZ) math.Normalize(normalizedZ) math.Cross(normalizedZ, normalizedX, normalizedY) matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalizedY[i]) matrix.SetElement(i, 1, normalizedX[i]) matrix.SetElement(i, 2, normalizedZ[i]) #transform.PostMultiply() transform.Translate(center) transform.Concatenate(matrix) transform.Scale(1, -1, 1) return (transform, length)
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)
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
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
def colorCells(): 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
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
def execute(self, obj, event): for body_type in self.data: for body in body_type: body.trans.Identity() # Quaternion stuff yaw = body.angles[2] pitch = body.angles[1] roll = body.angles[0] cy = np.cos(yaw * 0.5) sy = np.sin(yaw * 0.5) cp = np.cos(pitch * 0.5) sp = np.sin(pitch * 0.5) cr = np.cos(roll * 0.5) sr = np.sin(roll * 0.5) w = cy * cp * cr + sy * sp * sr x = cy * cp * sr - sy * sp * cr y = sy * cp * sr + cy * sp * cr z = sy * cp * cr - cy * sp * sr body_quaternion = np.quaternion(w, x, y, z) # Convert to 4x4 vtkMatrix vtkmath = vtk.vtkMath() rot_mat_3x3 = np.zeros((3, 3)) vtkmath.QuaternionToMatrix3x3(body_quaternion.components, rot_mat_3x3) rot_mat_4x4 = np.zeros((4, 4)) rot_mat_4x4[0:3, 0:3] = rot_mat_3x3[:, :] rot_mat_4x4[-1, -1] = 1 vtk_matrix = vtk.vtkMatrix4x4() m, n = rot_mat_4x4.shape for i in range(m): for j in range(n): vtk_matrix.SetElement(i, j, rot_mat_4x4[i][j]) body.trans.SetMatrix(vtk_matrix) body.actor.SetUserTransform(body.trans) print(body.angles, '\n') obj.GetRenderWindow().Render()
def findClosestPointsTwoLists(X_source, X_target): '''return the closest points indexes in X_source from the X_target points, indexes output has the same length than X_target''' listPoints = X_source points = vtk.vtkPoints() points.SetDataTypeToDouble() listProbePoints = X_target probePoints = vtk.vtkPoints() probePoints.SetDataTypeToDouble() for [x, y] in listPoints: points.InsertNextPoint(x, y, 0.) for [x, y] in listProbePoints: probePoints.InsertNextPoint(x, y, 0.) polydata = vtk.vtkPolyData() polydata.SetPoints(points) points.ComputeBounds() staticLocator = vtk.vtkStaticPointLocator() staticLocator.SetDataSet(polydata) staticLocator.SetNumberOfPointsPerBucket(5) staticLocator.AutomaticOn() staticLocator.BuildLocator() staticClosestN = vtk.vtkIdList() ind = np.zeros(len(X_target), dtype=np.int) D = np.zeros(len(X_target)) math = vtk.vtkMath() x = [0, 0, 0] p = [0, 0, 0] staticClosestN = vtk.vtkIdList() for i in range(len(X_target)): staticLocator.FindClosestNPoints(1, probePoints.GetPoint(i), staticClosestN) ind[i] = staticClosestN.GetId(0) # we then select the closest point points.GetPoint(ind[i], x) probePoints.GetPoint(i, p) D[i] = math.Distance2BetweenPoints(x, p)**0.5 return ind, D
def drawArrow(start_point, end_point): math = vtk.vtkMath() # X-Axis is a vector from start to end normX = np.subtract(start_point, end_point) length = np.linalg.norm(normX) normX = np.divide(normX, length) # Z axis is an arbitrary vector cross X arbitrary = [0.0, 0.0, 1.0] normZ = np.cross(normX, arbitrary) # Y-Axis is Z cross X normY = np.cross(normZ, normX) tVec_at_b0_mat = vtk.vtkMatrix4x4() tVec_at_b0_mat.Identity() for i in range(3): tVec_at_b0_mat.SetElement(i, 0, normX[i]) tVec_at_b0_mat.SetElement(i, 1, normY[i]) tVec_at_b0_mat.SetElement(i, 2, normZ[i]) arrowBase = vtk.vtkArrowSource() arrowBase.Update() print(arrowBase.GetTipLength()) print(arrowBase.GetTipRadius()) print(arrowBase.GetTipResolution()) print(arrowBase.GetShaftRadius()) print(arrowBase.GetShaftResolution()) arrow_transform = vtk.vtkTransform() arrow_transform.Translate(start_point) arrow_transform.Concatenate(tVec_at_b0_mat) arrow_transform.Scale(length, length, length) arrow_transform.Update() transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetInputData(arrowBase.GetOutput()) transformPD.SetTransform(arrow_transform) transformPD.Update() return transformPD.GetOutput()
def opyfFindClosestPointandDistance3D(X): staticLocator, points, probePoints = opyfBuildLocatorandStuff3D(X) staticClosestN = vtk.vtkIdList() ind = np.zeros(len(X), dtype=np.int) D = np.zeros(len(X)) math = vtk.vtkMath() x = [0, 0, 0] p = [0, 0, 0] staticClosestN = vtk.vtkIdList() for i in range(len(X)): staticLocator.FindClosestNPoints(2, probePoints.GetPoint(i), staticClosestN) ind[i] = staticClosestN.GetId(1) # we then select the furthest point points.GetPoint(ind[i], x) points.GetPoint(i, p) D[i] = math.Distance2BetweenPoints(x, p)**0.5 return ind, D
def find_final_cut(self, normal, centroid): final_plane = vtk.vtkPlane() final_plane.SetOrigin(centroid) final_plane.SetNormal(normal) final_cutter = vtk.vtkCutter() final_cutter.SetInputData(self.pred_surface) final_cutter.SetCutFunction(final_plane) final_cutter.GenerateCutScalarsOff() final_stripper = vtk.vtkStripper() final_stripper.SetInputConnection(final_cutter.GetOutputPort()) final_stripper.Update() MaxCutNumber = 0 area = 0 minDist = np.inf minIDX = -1 minIDXarea = 0 for i in range(final_stripper.GetOutput().GetNumberOfCells()): final_pd = final_stripper.GetOutput().GetCell(i).GetPoints() final_CM = self.vtkCenterOfMass(final_pd) final_d2 = vtk.vtkMath().Distance2BetweenPoints(final_CM, centroid) if final_d2 < minDist: minDist = final_d2 minIDX = i # Final cut finalCut = vtk.vtkPolyData() finalCut.DeepCopy(final_stripper.GetOutput()) final_line = finalCut.GetCell(minIDX) points = final_line.GetPoints() #cells = vtk.vtkCellArray() #cells.InsertNextCell(final_line) # pd_finalCut = vtk.vtkPolyData() # pd_finalCut.SetPoints(points) # pd_finalCut.SetLines(cells) return points
def distanceAfterRegistration(self, initialModel, inputModel, fidList, transformNode): # Computes the distance between the models following registration # computes the distance between the entire models but if the code below is # uncommented then only the distance between the breasts will be computed breastBoundPolyData = vtk.vtkPolyData() self.FiducialsToPolyData(fidList, breastBoundPolyData) # Create plane of best fit from input breast boundary fiducials plane = vtk.vtkPlane() self.LeastSquaresPlane(inputModel, breastBoundPolyData, plane) #Compute the mean distance after registration # If above is uncommented comment out the two lines following sourcePolyData = initialModel.GetPolyData() targetPolyData = inputModel.GetPolyData() cellId = vtk.mutable(0) subId = vtk.mutable(0) dist2 = vtk.mutable(0.0) locator = vtk.vtkCellLocator() locator.SetDataSet(targetPolyData) locator.SetNumberOfCellsPerBucket(1) locator.BuildLocator() totalDistance = 0.0 sourcePoints = sourcePolyData.GetPoints() n = sourcePoints.GetNumberOfPoints() m = vtk.vtkMath() for sourcePointIndex in xrange(n): sourcePointPos = [0, 0, 0] sourcePoints.GetPoint(sourcePointIndex, sourcePointPos) transformedSourcePointPos = [0, 0, 0, 1] sourcePointPos.append(1) transformNode.GetTransformToParent().MultiplyPoint(sourcePointPos, transformedSourcePointPos) surfacePoint = [0, 0, 0] transformedSourcePointPos.pop() locator.FindClosestPoint(transformedSourcePointPos, surfacePoint, cellId, subId, dist2) totalDistance = totalDistance + math.sqrt(dist2) return (round((totalDistance/n),2))
def geodesic_distance(poly, start, end): ''' The mesh must be a manifold ''' d_graph = vtk.vtkDijkstraGraphGeodesicPath() d_graph.SetInputData(poly) d_graph.SetStartVertex(start) d_graph.SetEndVertex(end) d_graph.Update() id_list = d_graph.GetIdList() if id_list.GetNumberOfIds() == 0: return float("inf") distance = 0. points = poly.GetPoints() for i in range(id_list.GetNumberOfIds() - 1): i_curr = id_list.GetId(i) i_next = id_list.GetId(i + 1) dist = vtk.vtkMath() distance += dist.Distance2BetweenPoints(points.GetPoint(i_curr), points.GetPoint(i_next)) return distance
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)
def _get_transform(startPoint, endPoint, f): # Compute a basis normalized_x = [0 for i in range(3)] normalized_y = [0 for i in range(3)] normalized_z = [0 for i in range(3)] # The X axis is a vector from start to end math = vtk.vtkMath() math.Subtract(endPoint, startPoint, normalized_x) length = math.Norm(normalized_x) math.Normalize(normalized_x) # The Z axis is an arbitrary vector cross X arbitrary = [0 for i in range(3)] arbitrary[0] = random.uniform(-10, 10) arbitrary[1] = random.uniform(-10, 10) arbitrary[2] = random.uniform(-10, 10) math.Cross(normalized_x, arbitrary, normalized_z) math.Normalize(normalized_z) # The Y axis is Z cross X math.Cross(normalized_z, normalized_x, normalized_y) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(3): matrix.SetElement(i, 0, normalized_x[i]) matrix.SetElement(i, 1, normalized_y[i]) matrix.SetElement(i, 2, normalized_z[i]) # Apply the transforms transform = vtk.vtkTransform() transform.Translate(startPoint) transform.Concatenate(matrix) transform.Scale(length * f, length * f, length * f) return transform
def generateVTK2DFromPoints(listOfPoints, name): math = vtk.vtkMath() points = vtk.vtkPoints() for elt in listOfPoints: (i,x,y) = elt points.InsertPoint(i,x,y,0) profile = vtk.vtkPolyData() profile.SetPoints(points) delny = vtk.vtkDelaunay2D() delny.SetInputData(profile) delny.SetTolerance(0.0001) delny.SetAlpha(0) print("alpha :",delny.GetAlpha()) print("Output :", delny.GetOutput()) delny.BoundingTriangulationOff() toSave = vtk.vtkPolyDataWriter() toSave.SetInputConnection(delny.GetOutputPort()) toSave.SetFileName(name) toSave.Write()
def geodesic_distance_map(poly, start, threshold, max_depth=3000): ''' compute the geodesic distance map on a polydata from a starting point ''' count = 0 dist_arr = np.ones(poly.GetNumberOfPoints()) * np.inf vtk_math = vtk.vtkMath() points = poly.GetPoints() pt_queue = [start] dist_queue = [0.] visited_list = [start] while pt_queue and count < max_depth: count += 1 print("debug: ", pt_queue) node = pt_queue.pop(0) dist = dist_queue.pop(0) dist_arr[node] = dist tmplt_list = vtk.vtkIdList() poly.GetPointCells(node, tmplt_list) for i in range(tmplt_list.GetNumberOfIds()): tmplt_pt_list = vtk.vtkIdList() poly.GetCellPoints(tmplt_list.GetId(i), tmplt_pt_list) for j in range(tmplt_pt_list.GetNumberOfIds()): p_id = tmplt_pt_list.GetId(j) if not p_id in visited_list: visited_list.append(p_id) cum_dist = np.linalg.norm( np.array(points.GetPoint(node)) - np.array(points.GetPoint(p_id))) + dist print("dist: ", cum_dist) if cum_dist < threshold: pt_queue.append(p_id) dist_queue.append(cum_dist) print("count: ", count) return dist_arr
def generateVTKFromPoints(listOfPoints): math = vtk.vtkMath() points = vtk.vtkPoints() for elt in listOfPoints: (i,x,y,z) = elt points.InsertPoint(i,x,y,z) profile = vtk.vtkPolyData() profile.SetPoints(points) delny = vtk.vtkDelaunay3D() delny.SetInputData(profile) delny.SetTolerance(0.0001) delny.SetAlpha(0) print("alpha :",delny.GetAlpha()) print("Output :", delny.GetOutput()) delny.BoundingTriangulationOff() toSave = vtk.vtkUnstructuredGridWriter() toSave.SetInputConnection(delny.GetOutputPort()) toSave.SetFileName("Cube"+str(len(listOfPoints))+".vtk") toSave.Write()
def Execute(self): if self.Mesh == None: self.PrintError('Error: No input mesh.') if not self.CellEntityIdsArrayName: self.PrintError('Error: No input CellEntityIdsArrayName.') return cellEntityIdsArray = self.Mesh.GetCellData().GetArray(self.CellEntityIdsArrayName) #cut off the volumetric elements wallThreshold = vtk.vtkThreshold() wallThreshold.SetInputData(self.Mesh) wallThreshold.ThresholdByUpper(self.SurfaceCellEntityId-0.5) wallThreshold.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) wallThreshold.Update() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = wallThreshold.GetOutput() meshToSurface.Execute() #Compute the normals for this surface, orientation should be right because the surface is closed #TODO: Add option for cell normals in vmtksurfacenormals normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputData(meshToSurface.Surface) normalsFilter.SetAutoOrientNormals(1) normalsFilter.SetFlipNormals(0) normalsFilter.SetConsistency(1) normalsFilter.SplittingOff() normalsFilter.ComputePointNormalsOff() normalsFilter.ComputeCellNormalsOn() normalsFilter.Update() surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = normalsFilter.GetOutput() surfaceToMesh.Execute() #Save the current normals wallWithBoundariesMesh = surfaceToMesh.Mesh savedNormals = vtk.vtkDoubleArray() savedNormals.DeepCopy(wallWithBoundariesMesh.GetCellData().GetNormals()) savedNormals.SetName('SavedNormals') wallWithBoundariesMesh.GetCellData().AddArray(savedNormals) #cut off the boundaries and other surfaces extrudeThresholdLower = vtk.vtkThreshold() extrudeThresholdLower.SetInputData(wallWithBoundariesMesh) extrudeThresholdLower.ThresholdByLower(self.ExtrudeCellEntityId+0.5) extrudeThresholdLower.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) extrudeThresholdLower.Update() extrudeThresholdUpper = vtk.vtkThreshold() extrudeThresholdUpper.SetInputConnection(extrudeThresholdLower.GetOutputPort()) extrudeThresholdUpper.ThresholdByUpper(self.ExtrudeCellEntityId-0.5) extrudeThresholdUpper.SetInputArrayToProcess(0,0,0,1,self.CellEntityIdsArrayName) extrudeThresholdUpper.Update() meshToSurface = vmtkscripts.vmtkMeshToSurface() meshToSurface.Mesh = extrudeThresholdUpper.GetOutput() meshToSurface.Execute() #Compute cell normals without boundaries normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputData(meshToSurface.Surface) normalsFilter.SetAutoOrientNormals(1) normalsFilter.SetFlipNormals(0) normalsFilter.SetConsistency(1) normalsFilter.SplittingOff() normalsFilter.ComputePointNormalsOn() normalsFilter.ComputeCellNormalsOn() normalsFilter.Update() wallWithoutBoundariesSurface = normalsFilter.GetOutput() normals = wallWithoutBoundariesSurface.GetCellData().GetNormals() savedNormals = wallWithoutBoundariesSurface.GetCellData().GetArray('SavedNormals') math = vtk.vtkMath() #If the normal are inverted, recompute the normals with flipping on if normals.GetNumberOfTuples() > 0 and math.Dot(normals.GetTuple3(0),savedNormals.GetTuple3(0)) < 0: normalsFilter = vtk.vtkPolyDataNormals() normalsFilter.SetInputData(meshToSurface.Surface) normalsFilter.SetAutoOrientNormals(1) normalsFilter.SetFlipNormals(1) normalsFilter.SetConsistency(1) normalsFilter.SplittingOff() normalsFilter.ComputePointNormalsOn() normalsFilter.ComputeCellNormalsOn() normalsFilter.Update() wallWithoutBoundariesSurface = normalsFilter.GetOutput() wallWithoutBoundariesSurface.GetPointData().GetNormals().SetName('Normals') wallWithoutBoundariesSurface.GetCellData().RemoveArray('SavedNormals') surfaceToMesh = vmtkscripts.vmtkSurfaceToMesh() surfaceToMesh.Surface = wallWithoutBoundariesSurface surfaceToMesh.Execute() #Offset to apply to the array wallOffset = 0 if self.IncludeSurfaceCells or self.IncludeOriginalSurfaceCells: wallOffset += 1 if self.IncludeSurfaceCells or self.IncludeExtrudedSurfaceCells: wallOffset+=1 boundaryLayer = vmtkscripts.vmtkBoundaryLayer2() boundaryLayer.Mesh = surfaceToMesh.Mesh boundaryLayer.WarpVectorsArrayName = 'Normals' boundaryLayer.NegateWarpVectors = False boundaryLayer.ThicknessArrayName = self.ThicknessArrayName boundaryLayer.ConstantThickness = self.ConstantThickness boundaryLayer.IncludeSurfaceCells = self.IncludeSurfaceCells boundaryLayer.NumberOfSubLayers = self.NumberOfSubLayers boundaryLayer.SubLayerRatio = self.SubLayerRatio boundaryLayer.Thickness = self.Thickness boundaryLayer.ThicknessRatio = self.Thickness boundaryLayer.MaximumThickness = self.MaximumThickness boundaryLayer.CellEntityIdsArrayName = self.CellEntityIdsArrayName boundaryLayer.IncludeExtrudedOpenProfilesCells = self.IncludeExtrudedOpenProfilesCells boundaryLayer.IncludeExtrudedSurfaceCells = self.IncludeExtrudedSurfaceCells boundaryLayer.IncludeOriginalSurfaceCells = self.IncludeOriginalSurfaceCells boundaryLayer.LayerEntityId = self.SurfaceCellEntityId boundaryLayer.SurfaceEntityId = self.InletOutletCellEntityId + 1 if cellEntityIdsArray != None: #Append the new surface ids idRange = cellEntityIdsArray.GetRange() boundaryLayer.OpenProfilesEntityId = idRange[1] + wallOffset + 2 boundaryLayer.Execute() if cellEntityIdsArray != None: #offset the previous cellentityids to make room for the new ones arrayCalculator = vtk.vtkArrayCalculator() arrayCalculator.SetInputData(self.Mesh) if vtk.vtkVersion.GetVTKMajorVersion()>=9 or (vtk.vtkVersion.GetVTKMajorVersion()>=8 and vtk.vtkVersion.GetVTKMinorVersion()>=1): arrayCalculator.SetAttributeTypeToCellData() else: arrayCalculator.SetAttributeModeToUseCellData() arrayCalculator.AddScalarVariable("entityid",self.CellEntityIdsArrayName,0) arrayCalculator.SetFunction("if( entityid > " + str(self.InletOutletCellEntityId-1) +", entityid + " + str(wallOffset) + ", entityid)") arrayCalculator.SetResultArrayName('CalculatorResult') arrayCalculator.Update() #This need to be copied in order to be of the right type (int) cellEntityIdsArray.DeepCopy(arrayCalculator.GetOutput().GetCellData().GetArray('CalculatorResult')) arrayCalculator.SetFunction("if( entityid > " + str(self.SurfaceCellEntityId-1) +", entityid + 1, entityid)") arrayCalculator.Update() ##This need to be copied in order to be of the right type (int) cellEntityIdsArray.DeepCopy(arrayCalculator.GetOutput().GetCellData().GetArray('CalculatorResult')) appendFilter = vtkvmtk.vtkvmtkAppendFilter() appendFilter.AddInput(self.Mesh) appendFilter.AddInput(boundaryLayer.Mesh) appendFilter.Update() self.Mesh = appendFilter.GetOutput()
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 iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "skinOrder.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def __init__(self, ren): self.ren1 = ren # Get random numbers self.math = vtk.vtkMath() self.math.RandomSeed(1)
import vtk 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) # create some points on a sphere such that the data is not in the form # of z = f(x,y) # math1 = vtk.vtkMath() points = vtk.vtkPoints() vectors = vtk.vtkFloatArray() vectors.SetNumberOfComponents(3) i = 0 while i < 100: theta = math1.Random(0.31415, 2.8) phi = math1.Random(0.31415, 2.8) points.InsertPoint(i, math.cos(theta) * math.sin(phi), math.sin(theta) * math.sin(phi), math.cos(phi)) vectors.InsertTuple3(i, math.cos(theta) * math.sin(phi), math.sin(theta) * math.sin(phi), math.cos(phi)) i = i + 1 profile = vtk.vtkPolyData() profile.SetPoints(points)
def SetRandomSeed(caller, eventId): #print "Restart random number generator" raMath = vtk.vtkMath() raMath.RandomSeed(6)
def AddTimestamp( self, time, matrix, point, role ): if ( time == self.timePrev1 or time == self.timePrev2 or time == self.timePrev3 ): return if ( self.pointPrev3 == None or self.timePrev3 == None ): if ( self.pointPrev2 != None and self.timePrev2 != None ): self.pointPrev3 = self.pointPrev2[:] self.timePrev3 = self.timePrev2 if ( self.pointPrev1 != None ): self.pointPrev2 = self.pointPrev1[:] self.timePrev2 = self.timePrev1 if ( point != None ): self.pointPrev1 = point[:] self.timePrev1 = time return # Note that we are using backward difference formulas here # We might use central difference formulas for better accuracy, but it couldn't be extensible to real-time timeDiff01 = time - self.timePrev1 timeDiff12 = self.timePrev1 - self.timePrev2 timeDiff23 = self.timePrev2 - self.timePrev3 velocity0 = [ 0, 0, 0 ] vtk.vtkMath().Subtract( point[0:3], self.pointPrev1[0:3], velocity0 ) velocity0 = [ velocity0[ 0 ] / timeDiff01, velocity0[ 1 ] / timeDiff01, velocity0[ 2 ] / timeDiff01 ] velocity1 = [ 0, 0, 0 ] vtk.vtkMath().Subtract( self.pointPrev1[0:3], self.pointPrev2[0:3], velocity1 ) velocity1 = [ velocity1[ 0 ] / timeDiff12, velocity1[ 1 ] / timeDiff12, velocity1[ 2 ] / timeDiff12 ] velocity2 = [ 0, 0, 0 ] vtk.vtkMath().Subtract( self.pointPrev2[0:3], self.pointPrev3[0:3], velocity2 ) velocity2 = [ velocity2[ 0 ] / timeDiff23, velocity2[ 1 ] / timeDiff23, velocity2[ 2 ] / timeDiff23 ] acceleration0 = [ 0, 0, 0 ] vtk.vtkMath().Subtract( velocity0, velocity1, acceleration0 ) acceleration0 = [ acceleration0[ 0 ] / timeDiff01, acceleration0[ 1 ] / timeDiff01, acceleration0[ 2 ] / timeDiff01 ] acceleration1 = [ 0, 0, 0 ] vtk.vtkMath().Subtract( velocity1, velocity2, acceleration1 ) acceleration1 = [ acceleration1[ 0 ] / timeDiff12, acceleration1[ 1 ] / timeDiff12, acceleration1[ 2 ] / timeDiff12 ] jerk = [ 0, 0, 0 ] vtk.vtkMath().Subtract( acceleration0, acceleration1, jerk ) jerk = [ jerk[ 0 ] / timeDiff01, jerk[ 1 ] / timeDiff01, jerk[ 2 ] / timeDiff01 ] jerkMagnitude = math.pow( jerk[ 0 ], 2 ) + math.pow( jerk[ 1 ], 2 ) + math.pow( jerk[ 2 ], 2 ) self.squaredJerk += jerkMagnitude * timeDiff01 self.pointPrev3 = self.pointPrev2[:] # Require element copy self.timePrev3 = self.timePrev2 self.pointPrev2 = self.pointPrev1[:] # Require element copy self.timePrev2 = self.timePrev1 self.pointPrev1 = point[:] # Require element copy self.timePrev1 = time
def testParametricFunctions(self): # ------------------------------------------------------------ # Get a texture # ------------------------------------------------------------ textureReader = vtk.vtkJPEGReader() textureReader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg") texture = vtk.vtkTexture() texture.SetInputConnection(textureReader.GetOutputPort()) # ------------------------------------------------------------ # For each parametric surface: # 1) Create it # 2) Assign mappers and actors # 3) Position this object # 5) Add a label # ------------------------------------------------------------ # ------------------------------------------------------------ # Create a torus # ------------------------------------------------------------ torus = vtk.vtkParametricTorus() torusSource = vtk.vtkParametricFunctionSource() torusSource.SetParametricFunction(torus) torusSource.SetScalarModeToPhase() torusMapper = vtk.vtkPolyDataMapper() torusMapper.SetInputConnection(torusSource.GetOutputPort()) torusMapper.SetScalarRange(0, 360) torusActor = vtk.vtkActor() torusActor.SetMapper(torusMapper) torusActor.SetPosition(0, 12, 0) torusTextMapper = vtk.vtkTextMapper() torusTextMapper.SetInput("Torus") torusTextMapper.GetTextProperty().SetJustificationToCentered() torusTextMapper.GetTextProperty().SetVerticalJustificationToCentered() torusTextMapper.GetTextProperty().SetColor(1, 0, 0) torusTextMapper.GetTextProperty().SetFontSize(14) torusTextActor = vtk.vtkActor2D() torusTextActor.SetMapper(torusTextMapper) torusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() torusTextActor.GetPositionCoordinate().SetValue(0, 9.5, 0) # ------------------------------------------------------------ # Create a klein bottle # ------------------------------------------------------------ klein = vtk.vtkParametricKlein() kleinSource = vtk.vtkParametricFunctionSource() kleinSource.SetParametricFunction(klein) kleinSource.SetScalarModeToU0V0() kleinMapper = vtk.vtkPolyDataMapper() kleinMapper.SetInputConnection(kleinSource.GetOutputPort()) kleinMapper.SetScalarRange(0, 3) kleinActor = vtk.vtkActor() kleinActor.SetMapper(kleinMapper) kleinActor.SetPosition(8, 10.5, 0) kleinTextMapper = vtk.vtkTextMapper() kleinTextMapper.SetInput("Klein") kleinTextMapper.GetTextProperty().SetJustificationToCentered() kleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered() kleinTextMapper.GetTextProperty().SetColor(1, 0, 0) kleinTextMapper.GetTextProperty().SetFontSize(14) kleinTextActor = vtk.vtkActor2D() kleinTextActor.SetMapper(kleinTextMapper) kleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() kleinTextActor.GetPositionCoordinate().SetValue(8, 9.5, 0) # ------------------------------------------------------------ # Create a Figure-8 Klein # ------------------------------------------------------------ klein2 = vtk.vtkParametricFigure8Klein() klein2Source = vtk.vtkParametricFunctionSource() klein2Source.SetParametricFunction(klein2) klein2Source.GenerateTextureCoordinatesOn() klein2Mapper = vtk.vtkPolyDataMapper() klein2Mapper.SetInputConnection(klein2Source.GetOutputPort()) klein2Mapper.SetScalarRange(0, 3) klein2Actor = vtk.vtkActor() klein2Actor.SetMapper(klein2Mapper) klein2Actor.SetPosition(16, 12, 0) klein2Actor.SetTexture(texture) fig8KleinTextMapper = vtk.vtkTextMapper() fig8KleinTextMapper.SetInput("Fig-8.Klein") fig8KleinTextMapper.GetTextProperty().SetJustificationToCentered() fig8KleinTextMapper.GetTextProperty().SetVerticalJustificationToCentered() fig8KleinTextMapper.GetTextProperty().SetColor(1, 0, 0) fig8KleinTextMapper.GetTextProperty().SetFontSize(14) fig8KleinTextActor = vtk.vtkActor2D() fig8KleinTextActor.SetMapper(fig8KleinTextMapper) fig8KleinTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() fig8KleinTextActor.GetPositionCoordinate().SetValue(16, 9.5, 0) # ------------------------------------------------------------ # Create a mobius strip # ------------------------------------------------------------ mobius = vtk.vtkParametricMobius() mobiusSource = vtk.vtkParametricFunctionSource() mobiusSource.SetParametricFunction(mobius) mobiusSource.GenerateTextureCoordinatesOn() mobiusMapper = vtk.vtkPolyDataMapper() mobiusMapper.SetInputConnection(mobiusSource.GetOutputPort()) mobiusActor = vtk.vtkActor() mobiusActor.SetMapper(mobiusMapper) mobiusActor.RotateX(45) mobiusActor.SetPosition(24, 12, 0) mobiusActor.SetTexture(texture) mobiusTextMapper = vtk.vtkTextMapper() mobiusTextMapper.SetInput("Mobius") mobiusTextMapper.GetTextProperty().SetJustificationToCentered() mobiusTextMapper.GetTextProperty().SetVerticalJustificationToCentered() mobiusTextMapper.GetTextProperty().SetColor(1, 0, 0) mobiusTextMapper.GetTextProperty().SetFontSize(14) mobiusTextActor = vtk.vtkActor2D() mobiusTextActor.SetMapper(mobiusTextMapper) mobiusTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() mobiusTextActor.GetPositionCoordinate().SetValue(24, 9.5, 0) # ------------------------------------------------------------ # Create a super toroid # ------------------------------------------------------------ toroid = vtk.vtkParametricSuperToroid() toroid.SetN1(2) toroid.SetN2(3) toroidSource = vtk.vtkParametricFunctionSource() toroidSource.SetParametricFunction(toroid) toroidSource.SetScalarModeToU() toroidMapper = vtk.vtkPolyDataMapper() toroidMapper.SetInputConnection(toroidSource.GetOutputPort()) toroidMapper.SetScalarRange(0, 6.28) toroidActor = vtk.vtkActor() toroidActor.SetMapper(toroidMapper) toroidActor.SetPosition(0, 4, 0) superToroidTextMapper = vtk.vtkTextMapper() superToroidTextMapper.SetInput("Super.Toroid") superToroidTextMapper.GetTextProperty().SetJustificationToCentered() superToroidTextMapper.GetTextProperty().SetVerticalJustificationToCentered() superToroidTextMapper.GetTextProperty().SetColor(1, 0, 0) superToroidTextMapper.GetTextProperty().SetFontSize(14) superToroidTextActor = vtk.vtkActor2D() superToroidTextActor.SetMapper(superToroidTextMapper) superToroidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() superToroidTextActor.GetPositionCoordinate().SetValue(0, 1.5, 0) # ------------------------------------------------------------ # Create a super ellipsoid # ------------------------------------------------------------ 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) # ------------------------------------------------------------ # Create a closed 1D spline # ------------------------------------------------------------ spline2 = vtk.vtkParametricSpline() spline2.SetPoints(inputPoints) spline2.ClosedOn() spline2Source = vtk.vtkParametricFunctionSource() spline2Source.SetParametricFunction(spline2) spline2Mapper = vtk.vtkPolyDataMapper() spline2Mapper.SetInputConnection(spline2Source.GetOutputPort()) spline2Actor = vtk.vtkActor() spline2Actor.SetMapper(spline2Mapper) spline2Actor.SetPosition(24, 4, 0) spline2Actor.GetProperty().SetColor(0, 0, 0) spline2TextMapper = vtk.vtkTextMapper() spline2TextMapper.SetInput("Closed.Spline") spline2TextMapper.GetTextProperty().SetJustificationToCentered() spline2TextMapper.GetTextProperty().SetVerticalJustificationToCentered() spline2TextMapper.GetTextProperty().SetColor(1, 0, 0) spline2TextMapper.GetTextProperty().SetFontSize(14) spline2TextActor = vtk.vtkActor2D() spline2TextActor.SetMapper(spline2TextMapper) spline2TextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() spline2TextActor.GetPositionCoordinate().SetValue(24, 1.5, 0) # ------------------------------------------------------------ # Create a spiral conic # ------------------------------------------------------------ sconic = vtk.vtkParametricConicSpiral() sconic.SetA(0.8) sconic.SetB(2.5) sconic.SetC(0.4) sconicSource = vtk.vtkParametricFunctionSource() sconicSource.SetParametricFunction(sconic) sconicSource.SetScalarModeToDistance() sconicMapper = vtk.vtkPolyDataMapper() sconicMapper.SetInputConnection(sconicSource.GetOutputPort()) sconicActor = vtk.vtkActor() sconicActor.SetMapper(sconicMapper) sconicMapper.SetScalarRange(0, 9) sconicActor.SetPosition(0, -4, 0) sconicActor.SetScale(1.2, 1.2, 1.2) sconicTextMapper = vtk.vtkTextMapper() sconicTextMapper.SetInput("Spiral.Conic") sconicTextMapper.GetTextProperty().SetJustificationToCentered() sconicTextMapper.GetTextProperty().SetVerticalJustificationToCentered() sconicTextMapper.GetTextProperty().SetColor(1, 0, 0) sconicTextMapper.GetTextProperty().SetFontSize(14) sconicTextActor = vtk.vtkActor2D() sconicTextActor.SetMapper(sconicTextMapper) sconicTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() sconicTextActor.GetPositionCoordinate().SetValue(0, -6.5, 0) # ------------------------------------------------------------ # Create Boy's surface # ------------------------------------------------------------ boy = vtk.vtkParametricBoy() boySource = vtk.vtkParametricFunctionSource() boySource.SetParametricFunction(boy) boySource.SetScalarModeToModulus() boyMapper = vtk.vtkPolyDataMapper() boyMapper.SetInputConnection(boySource.GetOutputPort()) boyMapper.SetScalarRange(0, 2) boyActor = vtk.vtkActor() boyActor.SetMapper(boyMapper) boyActor.SetPosition(8, -4, 0) boyActor.SetScale(1.5, 1.5, 1.5) boyTextMapper = vtk.vtkTextMapper() boyTextMapper.SetInput("Boy") boyTextMapper.GetTextProperty().SetJustificationToCentered() boyTextMapper.GetTextProperty().SetVerticalJustificationToCentered() boyTextMapper.GetTextProperty().SetColor(1, 0, 0) boyTextMapper.GetTextProperty().SetFontSize(14) boyTextActor = vtk.vtkActor2D() boyTextActor.SetMapper(boyTextMapper) boyTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() boyTextActor.GetPositionCoordinate().SetValue(8, -6.5, 0) # ------------------------------------------------------------ # Create a cross cap # ------------------------------------------------------------ crossCap = vtk.vtkParametricCrossCap() crossCapSource = vtk.vtkParametricFunctionSource() crossCapSource.SetParametricFunction(crossCap) crossCapSource.SetScalarModeToY() crossCapMapper = vtk.vtkPolyDataMapper() crossCapMapper.SetInputConnection(crossCapSource.GetOutputPort()) crossCapActor = vtk.vtkActor() crossCapActor.SetMapper(crossCapMapper) crossCapActor.RotateX(65) crossCapActor.SetPosition(16, -4, 0) crossCapActor.SetScale(1.5, 1.5, 1.5) crossCapTextMapper = vtk.vtkTextMapper() crossCapTextMapper.SetInput("Cross.Cap") crossCapTextMapper.GetTextProperty().SetJustificationToCentered() crossCapTextMapper.GetTextProperty().SetVerticalJustificationToCentered() crossCapTextMapper.GetTextProperty().SetColor(1, 0, 0) crossCapTextMapper.GetTextProperty().SetFontSize(14) crossCapTextActor = vtk.vtkActor2D() crossCapTextActor.SetMapper(crossCapTextMapper) crossCapTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() crossCapTextActor.GetPositionCoordinate().SetValue(16, -6.5, 0) # ------------------------------------------------------------ # Create Dini's surface # ------------------------------------------------------------ dini = vtk.vtkParametricDini() diniSource = vtk.vtkParametricFunctionSource() diniSource.SetScalarModeToDistance() diniSource.SetParametricFunction(dini) diniMapper = vtk.vtkPolyDataMapper() diniMapper.SetInputConnection(diniSource.GetOutputPort()) diniActor = vtk.vtkActor() diniActor.SetMapper(diniMapper) diniActor.RotateX(-90) diniActor.SetPosition(24, -3, 0) diniActor.SetScale(1.5, 1.5, 0.5) diniTextMapper = vtk.vtkTextMapper() diniTextMapper.SetInput("Dini") diniTextMapper.GetTextProperty().SetJustificationToCentered() diniTextMapper.GetTextProperty().SetVerticalJustificationToCentered() diniTextMapper.GetTextProperty().SetColor(1, 0, 0) diniTextMapper.GetTextProperty().SetFontSize(14) diniTextActor = vtk.vtkActor2D() diniTextActor.SetMapper(diniTextMapper) diniTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() diniTextActor.GetPositionCoordinate().SetValue(24, -6.5, 0) # ------------------------------------------------------------ # Create Enneper's surface # ------------------------------------------------------------ enneper = vtk.vtkParametricEnneper() enneperSource = vtk.vtkParametricFunctionSource() enneperSource.SetParametricFunction(enneper) enneperSource.SetScalarModeToQuadrant() enneperMapper = vtk.vtkPolyDataMapper() enneperMapper.SetInputConnection(enneperSource.GetOutputPort()) enneperMapper.SetScalarRange(1, 4) enneperActor = vtk.vtkActor() enneperActor.SetMapper(enneperMapper) enneperActor.SetPosition(0, -12, 0) enneperActor.SetScale(0.25, 0.25, 0.25) enneperTextMapper = vtk.vtkTextMapper() enneperTextMapper.SetInput("Enneper") enneperTextMapper.GetTextProperty().SetJustificationToCentered() enneperTextMapper.GetTextProperty().SetVerticalJustificationToCentered() enneperTextMapper.GetTextProperty().SetColor(1, 0, 0) enneperTextMapper.GetTextProperty().SetFontSize(14) enneperTextActor = vtk.vtkActor2D() enneperTextActor.SetMapper(enneperTextMapper) enneperTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() enneperTextActor.GetPositionCoordinate().SetValue(0, -14.5, 0) # ------------------------------------------------------------ # Create an ellipsoidal surface # ------------------------------------------------------------ ellipsoid = vtk.vtkParametricEllipsoid() ellipsoid.SetXRadius(1) ellipsoid.SetYRadius(0.75) ellipsoid.SetZRadius(0.5) ellipsoidSource = vtk.vtkParametricFunctionSource() ellipsoidSource.SetParametricFunction(ellipsoid) ellipsoidSource.SetScalarModeToZ() ellipsoidMapper = vtk.vtkPolyDataMapper() ellipsoidMapper.SetInputConnection(ellipsoidSource.GetOutputPort()) ellipsoidMapper.SetScalarRange(-0.5, 0.5) ellipsoidActor = vtk.vtkActor() ellipsoidActor.SetMapper(ellipsoidMapper) ellipsoidActor.SetPosition(8, -12, 0) ellipsoidActor.SetScale(1.5, 1.5, 1.5) ellipsoidTextMapper = vtk.vtkTextMapper() ellipsoidTextMapper.SetInput("Ellipsoid") ellipsoidTextMapper.GetTextProperty().SetJustificationToCentered() ellipsoidTextMapper.GetTextProperty().SetVerticalJustificationToCentered() ellipsoidTextMapper.GetTextProperty().SetColor(1, 0, 0) ellipsoidTextMapper.GetTextProperty().SetFontSize(14) ellipsoidTextActor = vtk.vtkActor2D() ellipsoidTextActor.SetMapper(ellipsoidTextMapper) ellipsoidTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() ellipsoidTextActor.GetPositionCoordinate().SetValue(8, -14.5, 0) # ------------------------------------------------------------ # Create an surface with random hills on it. # Note that for testing, we will disable the # random generation of the surfaces. This is # because random number generators do not # return the same result on different operating # systems. # ------------------------------------------------------------ randomHills = vtk.vtkParametricRandomHills() randomHills.AllowRandomGenerationOff() randomHills.GenerateTheHills() randomHillsSource = vtk.vtkParametricFunctionSource() randomHillsSource.SetParametricFunction(randomHills) randomHillsSource.GenerateTextureCoordinatesOn() randomHillsMapper = vtk.vtkPolyDataMapper() randomHillsMapper.SetInputConnection(randomHillsSource.GetOutputPort()) randomHillsActor = vtk.vtkActor() randomHillsActor.SetMapper(randomHillsMapper) randomHillsActor.SetPosition(16, -14, 0) randomHillsActor.SetScale(0.2, 0.2, 0.2) randomHillsActor.SetTexture(texture) randomHillsTextMapper = vtk.vtkTextMapper() randomHillsTextMapper.SetInput("Random.Hills") randomHillsTextMapper.GetTextProperty().SetJustificationToCentered() randomHillsTextMapper.GetTextProperty().SetVerticalJustificationToCentered() randomHillsTextMapper.GetTextProperty().SetColor(1, 0, 0) randomHillsTextMapper.GetTextProperty().SetFontSize(14) randomHillsTextActor = vtk.vtkActor2D() randomHillsTextActor.SetMapper(randomHillsTextMapper) randomHillsTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() randomHillsTextActor.GetPositionCoordinate().SetValue(16, -14.5, 0) # ------------------------------------------------------------ # Create an Steiner's Roman Surface. # ------------------------------------------------------------ roman = vtk.vtkParametricRoman() roman.SetRadius(1.5) romanSource = vtk.vtkParametricFunctionSource() romanSource.SetParametricFunction(roman) romanSource.SetScalarModeToX() romanMapper = vtk.vtkPolyDataMapper() romanMapper.SetInputConnection(romanSource.GetOutputPort()) romanActor = vtk.vtkActor() romanActor.SetMapper(romanMapper) romanActor.SetPosition(24, -12, 0) romanTextMapper = vtk.vtkTextMapper() romanTextMapper.SetInput("Roman") romanTextMapper.GetTextProperty().SetJustificationToCentered() romanTextMapper.GetTextProperty().SetVerticalJustificationToCentered() romanTextMapper.GetTextProperty().SetColor(1, 0, 0) romanTextMapper.GetTextProperty().SetFontSize(14) romanTextActor = vtk.vtkActor2D() romanTextActor.SetMapper(romanTextMapper) romanTextActor.GetPositionCoordinate().SetCoordinateSystemToWorld() romanTextActor.GetPositionCoordinate().SetValue(24, -14.5, 0) # ------------------------------------------------------------ # Create the RenderWindow, Renderer and both Actors # ------------------------------------------------------------ ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # add actors ren.AddViewProp(torusActor) ren.AddViewProp(kleinActor) ren.AddViewProp(klein2Actor) ren.AddViewProp(toroidActor) ren.AddViewProp(superEllipsoidActor) ren.AddViewProp(mobiusActor) ren.AddViewProp(splineActor) ren.AddViewProp(spline2Actor) ren.AddViewProp(sconicActor) ren.AddViewProp(boyActor) ren.AddViewProp(crossCapActor) ren.AddViewProp(diniActor) ren.AddViewProp(enneperActor) ren.AddViewProp(ellipsoidActor) ren.AddViewProp(randomHillsActor) ren.AddViewProp(romanActor) #add text actors ren.AddViewProp(torusTextActor) ren.AddViewProp(kleinTextActor) ren.AddViewProp(fig8KleinTextActor) ren.AddViewProp(mobiusTextActor) ren.AddViewProp(superToroidTextActor) ren.AddViewProp(superEllipsoidTextActor) ren.AddViewProp(splineTextActor) ren.AddViewProp(spline2TextActor) ren.AddViewProp(sconicTextActor) ren.AddViewProp(boyTextActor) ren.AddViewProp(crossCapTextActor) ren.AddViewProp(diniTextActor) ren.AddViewProp(enneperTextActor) ren.AddViewProp(ellipsoidTextActor) ren.AddViewProp(randomHillsTextActor) ren.AddViewProp(romanTextActor) ren.SetBackground(0.7, 0.8, 1) renWin.SetSize(500, 500) ren.ResetCamera() ren.GetActiveCamera().Zoom(1.3) iren.Initialize() renWin.Render() #iren.Start() img_file = "TestParametricFunctions.png" vtk.test.Testing.compareImage(iren.GetRenderWindow(),vtk.test.Testing.getAbsImagePath(img_file),threshold=25) vtk.test.Testing.interact()
var_name += repr(arg) return var_name #init Tk try: import Tkinter pythonTk = Tkinter.Tk() pythonTk.withdraw() except: pythonTk = None pass #no hassles if Tk is not present. # setup some common things for testing rtTempObject = vtk.vtkObject() rtExMath = vtk.vtkMath() rtExMath.RandomSeed(6) # create the testing class to do the work rtTester = vtk.vtkTesting() for arg in sys.argv[2:]: rtTester.AddArgument(arg) VTK_DATA_ROOT = rtTester.GetDataRoot() if rtTester.IsInteractiveModeSpecified() == 0: vtk.vtkRenderWindowInteractor = vtkTestingInteractor # load in the script test_script = sys.argv[1]
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() cam.SetPosition(3.89696, 7.20771, 1.44123) cam.SetFocalPoint(3.96132, 0, 0) cam.SetViewUp(-0.0079335, 0.196002, -0.980571) cam.SetClippingRange(5.42814, 9.78848) ren.SetBackground(colors.GetRGBColor("black")) renWin.SetSize(400, 150) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin); renWin.Render() img_file = "TestPlatonicSolids.png" vtk.test.Testing.compareImage(iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
#!/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)
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] l_ringVect = [l_slice.GetPoint(j)[k] - l_sliceCenter[k] for k in xrange(3)] vtkmath.Cross(l_ringSliceAlphaVect, l_ringVect, l_p1) l_p2 = vtkmath.Dot(l_p1, m_average) l_angleBetweenRunningAndInitialVector = vtkmath.AngleBetweenVectors( l_ringSliceAlphaVect, l_ringVect ) if ( l_angleBetweenRunningAndInitialVector > vtkmath.RadiansFromDegrees(l_sectionDegree - m_errorTolerance / 2) and l_angleBetweenRunningAndInitialVector < vtkmath.RadiansFromDegrees(l_sectionDegree + m_errorTolerance / 2.0) and l_p2 > 0 ): l_ringSliceAlphaVect = l_ringVect l_holeList.append([l_ringVect[k] + l_sliceCenter[k] for k in xrange(3)]) l_sectionDegree += l_uniformSectionDegree - vtkmath.DegreesFromRadians( l_angleBetweenRunningAndInitialVector ) break if l_loopbreak == m_holePerSlice: raise RuntimeError("Current error tolerence setting is to low to produce anything.") l_loopbreak += 1 m_holeList.extend(l_holeList) self._openingList = m_openingList return m_holeList
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()
def distance2(pnt1,pnt2): return vtk.vtkMath().Distance2BetweenPoints(pnt1,pnt2)
def myMain(controller,args): fname=args.fname controller=args.controller myid = controller.GetLocalProcessId(); numProcs = controller.GetNumberOfProcesses(); pts=np.loadtxt(fname) sf=100 paint=rgbPainter() r,t,z = rec2cyl(pts[:,0],pts[:,1],pts[:,2]) #im=np.abs(getGeomImperfection(r,z,np.mean(r))) if pts.shape[1] == 4: im=pts[:,3] else: im=getGeomImperfection(r,z,np.mean(r)) rid=r-im xx,yy,zz=cyl2rec(rid+im*sf,t,z) math = vtk.vtkMath() points = vtk.vtkPoints() colors =vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3); colors.SetName("Colors"); for i in range(0,pts.shape[0]): #points.InsertPoint(i,pts[i][0],pts[i][1],pts[i][2] ) points.InsertPoint(i,xx[i],yy[i],zz[i] ) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.GetPointData().SetScalars(colors) polydata.Update() surf =vtk.vtkSurfaceReconstructionFilter() surf.SetInput(polydata) surf.SetNeighborhoodSize(40) #surf.SetSampleSpacing(6.0) if (myid != 0): controller.AddRMI(surf.Update,'',200) controller.ProcessRMIs(); else: contourFilter = vtk.vtkContourFilter() contourFilter.SetInputConnection(surf.GetOutputPort()) reverse = vtk.vtkReverseSense() reverse.SetInputConnection(contourFilter.GetOutputPort()) reverse.ReverseCellsOn() reverse.ReverseNormalsOn() reverse.Update() outputPolyData=reverse.GetOutput() #for i in range(0,pts.shape[0]): # dcolor=np.zeros(3) # colorLookupTable.GetColor(im[i],dcolor) # cc=dcolor*255.0 # colors.InsertNextTupleValue(cc) #outputPolyData.GetPointData().SetScalars(polydata.GetPointData().GetScalars() ); newSurf = transform_back( points, reverse.GetOutput()); pts2=np.zeros((newSurf.GetNumberOfPoints(),3)) for i in range(0,newSurf.GetNumberOfPoints()): pts2[i,:]=newSurf.GetPoint(i) r2,t2,z2 = rec2cyl(pts2[:,0],pts2[:,1],pts2[:,2]) im2=getGeomImperfection(r2,z2,np.mean(r2)) #im2-=np.min(im2) #im2=np.abs(im2) paint.setValue(np.min(im2)) paint.setValue(np.max(im2)) for i in range(0,newSurf.GetNumberOfPoints()): colors.InsertNextTupleValue(paint.getRGB(im2[i])) newSurf.GetPointData().SetScalars(colors ); mapper = vtk.vtkPolyDataMapper(); mapper.InterpolateScalarsBeforeMappingOn() #mapper.SetInputConnection(outputPolyData.GetProducerPort()) mapper.SetInputConnection(newSurf.GetProducerPort()) mapper.SetScalarModeToUsePointData() mapper.ScalarVisibilityOn(); surfaceActor = vtk.vtkActor(); surfaceActor.SetMapper(mapper); ren = vtk.vtkRenderer(); renWin = vtk.vtkRenderWindow(); renWin.AddRenderer(ren); iren = vtk.vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) ren.AddActor(surfaceActor); ren.SetBackground(1, 1, 1); renWin.SetSize(800, 600); prn=1000. pc=-prn plXY = vtk.vtkPlaneSource() plXY.SetPoint1(prn,-prn,0) plXY.SetPoint2(-prn,prn,0) plXY.SetOrigin(pc,pc,0) plXY.SetCenter(0,0,0) plXYmap = vtk.vtkPolyDataMapper() plXYmap.SetInput(plXY.GetOutput()) plXYact = vtk.vtkActor() plXYact.SetMapper(plXYmap) plXYact.GetProperty().SetOpacity(0.1) plYZ = vtk.vtkPlaneSource() plYZ.SetCenter(0,pc,pc) plYZ.SetPoint1(0,prn,-prn) plYZ.SetPoint2(0,-prn,prn) plYZmap = vtk.vtkPolyDataMapper() plYZmap.SetInput(plYZ.GetOutput()) plYZact = vtk.vtkActor() plYZact.SetMapper(plYZmap) plYZact.GetProperty().SetOpacity(0.1) plZX = vtk.vtkPlaneSource() plZX.SetCenter(pc,0,pc) plZX.SetPoint1(prn,0,-prn) plZX.SetPoint2(-prn,0,prn) plZXmap = vtk.vtkPolyDataMapper() plZXmap.SetInput(plZX.GetOutput()) plZXact = vtk.vtkActor() plZXact.SetMapper(plZXmap) plZXact.GetProperty().SetOpacity(0.1) ren.AddActor(plXYact) ren.AddActor(plYZact) ren.AddActor(plZXact) ax=vtk.vtkAxesActor() ax.GetXAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ax.GetYAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ax.GetZAxisCaptionActor2D().GetProperty().SetColor(0,0,0) ow=vtk.vtkOrientationMarkerWidget() ow.SetOrientationMarker(ax) ow.SetInteractor(iren) ow.SetViewport( 0.0, 0.0, 0.4, 0.4 ) ow.SetEnabled( 1 ) ow.InteractiveOn() lut=vtk.vtkLookupTable() lut.SetHueRange( 0.66667, 0.0 ) lut.SetSaturationRange (1.0, 1.0) lut.SetNumberOfColors(50)# len(self.plotables)) lut.SetTableRange(paint.getMinValue(),paint.getMaxValue()) lut.Build() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetOrientationToHorizontal() scalar_bar.SetLookupTable(lut) scalar_bar.SetTitle("Imperfection value"); scalar_bar.SetNumberOfLabels(11) scalar_bar_widget = vtk.vtkScalarBarWidget() scalar_bar_widget.SetInteractor(iren) scalar_bar_widget.SetScalarBarActor(scalar_bar) scalar_bar_widget.On() iren.Initialize(); renWin.Render(); iren.Start();
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()
def get_actors(args = None): # This will be used later to get random numbers. math = vtk.vtkMath() # Total number of points. numberOfInputPoints = 20 # One spline for each direction. aSplineX = vtk.vtkCardinalSpline() aSplineY = vtk.vtkCardinalSpline() aSplineZ = vtk.vtkCardinalSpline() # Generate random (pivot) points and add the corresponding # coordinates to the splines. # aSplineX will interpolate the x values of the points # aSplineY will interpolate the y values of the points # aSplineZ will interpolate the z values of the points inputPoints = vtk.vtkPoints() for i in range(0, numberOfInputPoints): x = math.Random(0, 1) y = math.Random(0, 1) z = math.Random(0, 1) aSplineX.AddPoint(i, x) aSplineY.AddPoint(i, y) aSplineZ.AddPoint(i, z) inputPoints.InsertPoint(i, x, y, z) # The following section will create glyphs for the pivot points # in order to make the effect of the spline more clear. # Create a polydata to be glyphed. inputData = vtk.vtkPolyData() inputData.SetPoints(inputPoints) # Use sphere as glyph source. balls = vtk.vtkSphereSource() balls.SetRadius(.01) balls.SetPhiResolution(10) balls.SetThetaResolution(10) glyphPoints = vtk.vtkGlyph3D() glyphPoints.SetInput(inputData) glyphPoints.SetSource(balls.GetOutput()) glyphMapper = vtk.vtkPolyDataMapper() glyphMapper.SetInputConnection(glyphPoints.GetOutputPort()) glyph = vtk.vtkActor() glyph.SetMapper(glyphMapper) glyph.GetProperty().SetDiffuseColor(tomato) glyph.GetProperty().SetSpecular(.3) glyph.GetProperty().SetSpecularPower(30) # Generate the polyline for the spline. points = vtk.vtkPoints() profileData = vtk.vtkPolyData() # Number of points on the spline numberOfOutputPoints = 400 # Interpolate x, y and z by using the three spline filters and # create new points for i in range(0, numberOfOutputPoints): t = (numberOfInputPoints-1.0)/(numberOfOutputPoints-1.0)*i points.InsertPoint(i, aSplineX.Evaluate(t), aSplineY.Evaluate(t), aSplineZ.Evaluate(t)) # Create the polyline. lines = vtk.vtkCellArray() lines.InsertNextCell(numberOfOutputPoints) for i in range(0, numberOfOutputPoints): lines.InsertCellPoint(i) profileData.SetPoints(points) profileData.SetLines(lines) # Add thickness to the resulting line. profileTubes = vtk.vtkTubeFilter() profileTubes.SetNumberOfSides(8) profileTubes.SetInput(profileData) profileTubes.SetRadius(.005) profileMapper = vtk.vtkPolyDataMapper() profileMapper.SetInputConnection(profileTubes.GetOutputPort()) profile = vtk.vtkActor() profile.SetMapper(profileMapper) profile.GetProperty().SetDiffuseColor(banana) profile.GetProperty().SetSpecular(.3) profile.GetProperty().SetSpecularPower(30) return (glyph, profile)
def uniformFn(NPts,points): math = vtk.vtkMath() math.RandomSeed(27183) for i in range(0,NPts): points.SetPoint(i,math.Random(0,1),math.Random(0,1),0.0)
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Interpolate onto a volume # Parameters for debugging NPts = 100 #Keep test small math = vtk.vtkMath() math.RandomSeed(31415) res = 50 polyData = vtk.vtkPolyData() pts = vtk.vtkPoints() pts.SetDataTypeToFloat() pts.SetNumberOfPoints(NPts) for i in range(0,NPts): pts.SetPoint(i,math.Random(-1,1),math.Random(-1,1),math.Random(-1,1)) polyData.SetPoints(pts); # Generate signed distance function and contour it dist = vtk.vtkUnsignedDistance() dist.SetInputData(polyData) dist.SetRadius(0.25) #how far out to propagate distance calculation dist.SetDimensions(res,res,res) dist.CappingOn() dist.AdjustBoundsOn() dist.SetAdjustDistance(0.01) # Extract the surface with modified flying edges
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": ballActor, profile = vtkpoints(points, color=color[color.keys()[k]], radius=radius[radius.keys()[k]]) ren.AddActor(ballActor) # Add the actors to the renderer, set the background and size if shape_type.keys()[k] == "disks": print "trying disk plot" disk_pos = data[data.keys()[k]] disk_dir = shape_type[shape_type.keys()[k]] for i in range(0, size(disk_pos, 0)): d = disk_dir[i] * 90 diskactor = vtkdisk(c=(0, 0, 0)) diskactor.RotateX(90) diskactor.SetPosition(disk_pos[i][0], disk_pos[i][1], disk_pos[i][2]) diskactor.RotateZ(d[0]) diskactor.RotateX(d[1]) ren.AddActor(diskactor) print "done disk" except AttributeError: pass ballActor, profile = vtkpoints(points, color=color[color.keys()[k]], radius=radius[radius.keys()[k]]) ren.AddActor(ballActor) # Add the actors to the renderer, set the background and size # outline = vtk.vtkOutlineFilter() # outline.SetInput(mapBalls.GetOutput()) # outlineMapper = vtk.vtkPolyDataMapper() # outlineMapper.SetInput(outline.GetOutput()) # outlineActor = vtk.vtkActor() # outlineActor.SetMapper(outlineMapper) # outlineActor.GetProperty().SetColor(1,1,1) iren.Initialize() ren.ResetCamera() renWin.Render() iren.Start()