def extrudePolygon(polyObject,extrudeFactor,vector=None,centered=False): """ Extrude polygons by a scalar factor. """ extrude = vtk.vtkLinearExtrusionFilter() extrude.CappingOn() if vector is not None: extrude.SetExtrusionTypeToVectorExtrusion() extrude.SetVector(vector) else: extrude.SetExtrusionTypeToNormalExtrusion() polyObject = normFilter(polyObject) extrude.SetInputData(polyObject) extrude.SetScaleFactor(extrudeFactor) extrude.Update() ext = extrude.GetOutput() if centered and vector is not None: extPts = npsup.vtk_to_numpy(ext.GetPoints().GetData()) newPts = vtk.vtkPoints() newNppts = extPts - (np.array(vector)*(extrudeFactor/2)) newPts.SetData(npsup.numpy_to_vtk(newNppts,deep=1)) ext.SetPoints(newPts) return ext
def extrude (pts, z, h): cell = vtk.vtkIdList() vtk_pts = vtk.vtkPoints() vtk_pts.SetDataTypeToDouble() [ (vtk_pts.InsertNextPoint(pt[0], pt[1], z), cell.InsertNextId(i)) for i, pt in enumerate(pts) ] pd = vtk.vtkPolyData() pd.Allocate(1, 1) pd.SetPoints(vtk_pts) pd.InsertNextCell(vtk.VTK_POLYGON, cell) prod = vtk.vtkTrivialProducer() prod.SetOutput(pd) extr = vtk.vtkLinearExtrusionFilter() extr.SetInputConnection(prod.GetOutputPort()) extr.SetVector(0, 0, h) pn = vtk.vtkPolyDataNormals() pn.SetInputConnection(extr.GetOutputPort()) pn.AutoOrientNormalsOn() return pn
def generalSectionTube(self, element, section): start = element.first_node.coordinates size = element.length u, v, w = element.section_directional_vectors matrix = vtk.vtkMatrix4x4() matrix.Identity() for i in range(3): matrix.SetElement(i, 0, v[i]) matrix.SetElement(i, 1, w[i]) matrix.SetElement(i, 2, u[i]) data = vtk.vtkTransformPolyDataFilter() extrusion = vtk.vtkLinearExtrusionFilter() transformation = vtk.vtkTransform() extrusion.SetScaleFactor(size) extrusion.SetInputConnection(section) transformation.Translate(start) transformation.Concatenate(matrix) data.SetTransform(transformation) data.SetInputConnection(extrusion.GetOutputPort()) data.Update() return data
def extrude(pts, z, h): cell = vtk.vtkIdList() vtk_pts = vtk.vtkPoints() vtk_pts.SetDataTypeToDouble() [(vtk_pts.InsertNextPoint(pt[0], pt[1], z), cell.InsertNextId(i)) for i, pt in enumerate(pts)] pd = vtk.vtkPolyData() pd.Allocate(1, 1) pd.SetPoints(vtk_pts) pd.InsertNextCell(vtk.VTK_POLYGON, cell) prod = vtk.vtkTrivialProducer() prod.SetOutput(pd) extr = vtk.vtkLinearExtrusionFilter() extr.SetInputConnection(prod.GetOutputPort()) extr.SetVector(0, 0, h) pn = vtk.vtkPolyDataNormals() pn.SetInputConnection(extr.GetOutputPort()) pn.AutoOrientNormalsOn() return pn
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkLinearExtrusionFilter(), 'Processing.', ('vtkPolyData', ), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def createTubeSection(self, element): extruderFilter = vtk.vtkLinearExtrusionFilter() polygon = self.createSectionPolygon(element) size = element.length extruderFilter.SetInputConnection(polygon.GetOutputPort()) extruderFilter.SetExtrusionTypeToVectorExtrusion() extruderFilter.SetVector(1, 0, 0) extruderFilter.SetScaleFactor(size * self.bff) extruderFilter.Update() return extruderFilter.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkLinearExtrusionFilter(), "Processing.", ("vtkPolyData",), ("vtkPolyData",), replaceDoc=True, inputFunctions=None, outputFunctions=None, )
def setup(self): #self.textSrc = vtk.vtkTextSource() self.textSrc = vtk.vtkVectorText() self.textSrc.SetText('SMILE') #self.textSrc.BackingOff() self.extruder = vtk.vtkLinearExtrusionFilter() self.extruder.SetInput(self.textSrc.GetOutput()) self.extruder.SetVector(0,0,0.4) self.normals = vtk.vtkPolyDataNormals() self.normals.SplittingOff() self.normals.SetInput(self.extruder.GetOutput()) self.setSource(self.normals) self._actor.GetProperty().SetAmbient(0.8)
def Text3D(string, depth=0.5): """ Create 3D text from a string""" vec_text = vtk.vtkVectorText() vec_text.SetText(string) extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection(vec_text.GetOutputPort()) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(0, 0, 1) extrude.SetScaleFactor(depth) tri_filter = vtk.vtkTriangleFilter() tri_filter.SetInputConnection(extrude.GetOutputPort()) tri_filter.Update() return pyvista.wrap(tri_filter.GetOutput())
def createBreastModel(self, breastBound, InputModel, breastFlag, reverseNormal, setInsideOut, plane, planeWithSplineTransform): # Creates the cropped breast model from the original input model and the created warped posterior wall of the breast # Clip the input model with the breast boundary loop to isolate the breast clippedBreastModel = vtk.vtkClipPolyData() clippedBreastModel.SetClipFunction(breastBound) clippedBreastModel.SetInputData(InputModel) # This value below may need to be changed clippedBreastModel.SetInsideOut(True) clippedBreastModel.Update() # Now use the vtkPolyDataConnectivityFilter to extract the largest region connectedBreastModel = vtk.vtkPolyDataConnectivityFilter() connectedBreastModel.SetInputConnection(clippedBreastModel.GetOutputPort()) connectedBreastModel.SetExtractionModeToLargestRegion() connectedBreastModel.Update() # linearly extrude the breast model to ensure the final surface will be airtight extrudeBreastModel = vtk.vtkLinearExtrusionFilter() extrudeBreastModel.SetInputConnection(connectedBreastModel.GetOutputPort()) extrudeBreastModel.SetScaleFactor(100) extrudeBreastModel.CappingOn() normVec = plane.GetNormal() if breastFlag == True: normVec = [normVec[0] * -1, normVec[1] * -1, normVec[2] * -1] if reverseNormal == True: normVec = [normVec[0] * -1, normVec[1] * -1, normVec[2] * -1] extrudeBreastModel.SetVector(normVec) extrudeBreastModel.Update() # create implicit representation of the plane transformed with the spline implictSplinePlane = vtk.vtkImplicitPolyDataDistance() implictSplinePlane.SetInput(planeWithSplineTransform.GetOutput()) # Now re-clip the now air-tight breast model wit the curved surface breastModel = vtk.vtkClipPolyData() breastModel.SetClipFunction(implictSplinePlane) breastModel.SetInputConnection(extrudeBreastModel.GetOutputPort()) # This value below may need to be changed if setInsideOut == True: breastModel.SetInsideOut(True) else: breastModel.SetInsideOut(False) breastModel.Update() return breastModel.GetOutput()
def __init__(self, scriptedEffect): self.scriptedEffect = scriptedEffect self.vectorText = vtk.vtkVectorText() self.scaleAndTranslateTransform = vtk.vtkTransform() self.polyScaleTransform = vtk.vtkTransformPolyDataFilter() self.polyScaleTransform.SetTransform(self.scaleAndTranslateTransform) self.polyScaleTransform.SetInputConnection(self.vectorText.GetOutputPort()) # get normals self.polyDataNormals = vtk.vtkPolyDataNormals() # computes cell normals self.polyDataNormals.SetInputConnection(self.polyScaleTransform.GetOutputPort()) self.polyDataNormals.ConsistencyOn() # extrude the marker to underside of valve self.extrusion = vtk.vtkLinearExtrusionFilter() self.extrusion.SetInputConnection(self.polyDataNormals.GetOutputPort()) self.extrusion.SetExtrusionTypeToVectorExtrusion() self.extrusion.CappingOn()
def create_extruded_text(text): """ Create extruded text. To be then translated and rotated :param text: input text. Useful for axes and telescopes labelling, :return: return transformed source. need a mapper and an actor then. """ textSource = vtk.vtkVectorText() textSource.SetText(text) textSource.Update() # Apply linear extrusion extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection(textSource.GetOutputPort()) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(0, 0, 1) extrude.SetScaleFactor(0.1) triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection(extrude.GetOutputPort()) return triangleFilter
def createPlaneModel(self, InputModel, plane, breastFlag): #this function creates a model (visual representation) of the defined plane #The input is linearly extruded to create a closed input model so that when the cutter extracts the # region it is large enough to create a plane to cover the entire breast closedInputModel = vtk.vtkLinearExtrusionFilter() closedInputModel.SetInputData(InputModel) closedInputModel.SetScaleFactor(100) closedInputModel.CappingOn() closedInputModel.Update() clippedInput = vtk.vtkClipPolyData() clippedInput.SetInputData(closedInputModel.GetOutput()) clippedInput.SetClipFunction(plane) clippedInput.SetValue(0) clippedInput.SetInsideOut(breastFlag) clippedInput.Update() cutterPlane = vtk.vtkCutter() cutterPlane.SetCutFunction(plane) cutterPlane.SetInputData(clippedInput.GetOutput()) cutterPlane.Update() cutterModel = vtk.vtkPolyData() cutterModel = cutterPlane.GetOutput() surfPlane = vtk.vtkSurfaceReconstructionFilter() surfPlane.SetInputData(cutterModel) surfPlane.SetSampleSpacing(2.5) cfPlane = vtk.vtkContourFilter() cfPlane.SetInputConnection(surfPlane.GetOutputPort()) cfPlane.SetValue(0, 0.0) reversePlane = vtk.vtkReverseSense() reversePlane.SetInputConnection(cfPlane.GetOutputPort()) reversePlane.ReverseCellsOn() reversePlane.ReverseNormalsOn() return reversePlane
def write_tube(self, tube, position, rotation): diskSource = vtk.vtkDiskSource() diskSource.SetInnerRadius(tube.rmin) diskSource.SetOuterRadius(tube.rmax) circumfrence = 2 * pi * tube.rmax # now in cm. diskSource.SetCircumferentialResolution(100) diskSource.Update() linearExtrusion = vtk.vtkLinearExtrusionFilter() linearExtrusion.SetInputConnection(diskSource.GetOutputPort()) linearExtrusion.SetExtrusionTypeToNormalExtrusion() linearExtrusion.SetVector(0, 0, 1) linearExtrusion.SetScaleFactor(tube.z) linearExtrusion.Update() implicit_transform = self.apply_transformations( linearExtrusion.GetOutputPort(), [0, 0, -tube.z / 2.], [0, 0, 0]) data = self.apply_transformations(implicit_transform.GetOutputPort(), position, rotation) self.logger.debug("Writing Tube") return data
def extrudePolygon(polyObject, extrudeFactor, vector=None, centered=False): """ Extrude polygons by a scalar factor. """ extrude = vtk.vtkLinearExtrusionFilter() extrude.CappingOn() if vector is not None: extrude.SetExtrusionTypeToVectorExtrusion() extrude.SetVector(vector) else: extrude.SetExtrusionTypeToNormalExtrusion() polyObject = normFilter(polyObject) extrude.SetInputData(polyObject) extrude.SetScaleFactor(extrudeFactor) extrude.Update() ext = extrude.GetOutput() if centered and vector is not None: extPts = npsup.vtk_to_numpy(ext.GetPoints().GetData()) newPts = vtk.vtkPoints() newNppts = extPts - (np.array(vector) * (extrudeFactor / 2)) newPts.SetData(npsup.numpy_to_vtk(newNppts, deep=1)) ext.SetPoints(newPts) return ext
def _buildPipeline(self): """Build underlying pipeline and configure rest of pipeline-dependent UI. """ # add the renderer self._renderer = vtk.vtkRenderer() self._renderer.SetBackground(0.5, 0.5, 0.5) self._viewFrame.rwi.GetRenderWindow().AddRenderer( self._renderer) self._histogram = vtkdevide.vtkImageHistogram2D() # make sure the user can't do anything entirely stupid istyle = vtk.vtkInteractorStyleImage() self._viewFrame.rwi.SetInteractorStyle(istyle) # we'll use this to keep track of our ImagePlaneWidget self._ipw = None self._overlayipw = None self._scalarBarWidget = None # self._appendPD = vtk.vtkAppendPolyData() self._extrude = vtk.vtkLinearExtrusionFilter() self._extrude.SetInput(self._appendPD.GetOutput()) self._extrude.SetScaleFactor(1) self._extrude.SetExtrusionTypeToNormalExtrusion() self._extrude.SetVector(0,0,1) self._pdToImageStencil = vtk.vtkPolyDataToImageStencil() self._pdToImageStencil.SetInput(self._extrude.GetOutput()) # stupid trick to make image with all ones, but as large as its # input self._allOnes = vtk.vtkImageThreshold() self._allOnes.ThresholdByLower(0.0) self._allOnes.ThresholdByUpper(0.0) self._allOnes.SetInValue(1.0) self._allOnes.SetOutValue(1.0) self._allOnes.SetInput(self._histogram.GetOutput()) self._stencil = vtk.vtkImageStencil() self._stencil.SetInput(self._allOnes.GetOutput()) #self._stencil.SetStencil(self._pdToImageStencil.GetOutput()) self._stencil.ReverseStencilOff() self._stencil.SetBackgroundValue(0) self._lookupAppend = vtk.vtkImageAppendComponents() self._lookup = vtkdevide.vtkHistogramLookupTable() self._lookup.SetInput1(self._lookupAppend.GetOutput()) self._lookup.SetInput2(self._stencil.GetOutput()) module_utils.create_standard_object_introspection( self, self._viewFrame, self._viewFrame.viewFramePanel, {'Module (self)' : self, 'vtkHistogram2D' : self._histogram, 'vtkRenderer' : self._renderer}, self._renderer.GetRenderWindow()) # add the ECASH buttons module_utils.create_eoca_buttons(self, self._viewFrame, self._viewFrame.viewFramePanel)
def __init__(self): """ Called when the logic class is instantiated. Can be used for initializing member variables. """ ScriptedLoadableModuleLogic.__init__(self) self.inputCurveNode = None self.inputCurveNodeObservations = [] self.inputSurfacePointsNode = None self.inputSurfacePointsNodeObservations = [] self.numberOfCurveLandmarkPoints = 80 self.printThreeDViewNode = None self.printThreeDWidget = None self.printViewWidth = 1024 self.printViewHeight = 1024 self.printXResolutionDpi = 300 self.printYResolutionDpi = 300 self.printScale = 2.0 #TODO: Workaround for scaling problem, see https://github.com/SlicerFab/SlicerFab/issues/13 self.printTransparentBackground = False # Create triangulated flat disk that will be warped self.surfaceUnitDisk = vtk.vtkDiskSource() self.surfaceUnitDisk.SetOuterRadius(1.0) self.surfaceUnitDisk.SetInnerRadius(0.0) self.surfaceUnitDisk.SetCircumferentialResolution( self.numberOfCurveLandmarkPoints) self.surfaceUnitDisk.SetRadialResolution(60) self.surfaceTriangulator = vtk.vtkDelaunay2D() self.surfaceTriangulator.SetTolerance( 0.01 ) # get rid of the small triangles near the center of the unit disk self.surfaceTriangulator.SetInputConnection( self.surfaceUnitDisk.GetOutputPort()) # Prepare transform object # points on the unit disk (circumference and surface) self.surfaceTransformSourcePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints = vtk.vtkPoints() self.surfaceTransformSourceCurvePoints.SetNumberOfPoints( self.numberOfCurveLandmarkPoints) import math angleIncrement = 2.0 * math.pi / float( self.numberOfCurveLandmarkPoints) for pointIndex in range(self.numberOfCurveLandmarkPoints): angle = float(pointIndex) * angleIncrement self.surfaceTransformSourceCurvePoints.SetPoint( pointIndex, math.cos(angle), math.sin(angle), 0) # points on the warped surface (curve points and surface points) self.surfaceTransformTargetPoints = vtk.vtkPoints() self.surfaceTransform = vtk.vtkThinPlateSplineTransform() self.surfaceTransform.SetSourceLandmarks( self.surfaceTransformSourcePoints) self.surfaceTransform.SetTargetLandmarks( self.surfaceTransformTargetPoints) # Transform polydata self.surfaceTransformFilter = vtk.vtkTransformPolyDataFilter() self.surfaceTransformFilter.SetTransform(self.surfaceTransform) self.surfaceTransformFilter.SetInputConnection( self.surfaceTriangulator.GetOutputPort()) self.cleanPolyDataFilter = vtk.vtkCleanPolyData() self.cleanPolyDataFilter.SetInputConnection( self.surfaceTransformFilter.GetOutputPort()) # self.surfacePolyDataNormalsThin = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThin.SetInputConnection( self.cleanPolyDataFilter.GetOutputPort()) # There are a few triangles in the triangulated unit disk with inconsistent # orientation. Enabling consistency check fixes them. self.surfacePolyDataNormalsThin.ConsistencyOn( ) # TODO: check if needed, probably not self.surfacePolyDataNormalsThin.SplittingOff( ) # this prevents stray normals at the edge TODO: check # Add thickness to warped surface (if needed) # self.surfacePolyDataNormals = vtk.vtkPolyDataNormals() # self.surfacePolyDataNormals.SetInputConnection(self.cleanPolyDataFilter.GetOutputPort()) # self.surfacePolyDataNormals.SplittingOff() # this prevents stray normals at the edge TODO: check self.surfaceOffset = vtk.vtkWarpVector() self.surfaceOffset.SetInputConnection( self.surfacePolyDataNormalsThin.GetOutputPort()) self.surfaceOffset.SetInputArrayToProcess( 0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) self.surfaceExtrude = vtk.vtkLinearExtrusionFilter() self.surfaceExtrude.SetInputConnection( self.surfaceOffset.GetOutputPort()) self.surfaceExtrude.SetExtrusionTypeToNormalExtrusion() self.surfacePolyDataNormalsThick = vtk.vtkPolyDataNormals() self.surfacePolyDataNormalsThick.SetInputConnection( self.surfaceExtrude.GetOutputPort()) self.surfacePolyDataNormalsThick.AutoOrientNormalsOn()
def create_sign(output_file, transform_file, text, height, width, depth, nobacking, visualize, overwrite, func): if os.path.isfile(output_file) and not overwrite: result = input('File \"{}\" already exists. Overwrite? [y/n]: '.format(output_file)) if result.lower() not in ['y', 'yes']: print('Not overwriting. Exiting...') os.sys.exit() message("Create vector text.") vecText = vtk.vtkVectorText() vecText.SetText(text) message("Apply linear extrusion.") extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection( vecText.GetOutputPort() ) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(0, 0, 1 ) extrude.SetScaleFactor (0.5) message("Apply triangle filter.") triangleFilter = vtk.vtkTriangleFilter() triangleFilter.SetInputConnection( extrude.GetOutputPort() ) triangleFilter.Update() i_width = triangleFilter.GetOutput().GetBounds()[1] - triangleFilter.GetOutput().GetBounds()[0] i_height = triangleFilter.GetOutput().GetBounds()[3] - triangleFilter.GetOutput().GetBounds()[2] i_depth = triangleFilter.GetOutput().GetBounds()[5] - triangleFilter.GetOutput().GetBounds()[4] message('Input text:', '{:8s} = {:8.2f} mm'.format('width',i_width), '{:8s} = {:8.2f} mm'.format('height',i_height), '{:8s} = {:8.2f} mm'.format('depth',i_depth)) scale = 1 transform = vtk.vtkTransform() if (width is not None and height is None): message('Scaling to width of {:.2f} mm'.format(width)) scale_width = width/i_width scale_height = scale_width elif (width is None and height is not None): message('Scaling to height of {:.2f} mm'.format(height)) scale_height = height/i_height scale_width = scale_height elif (width is not None and height is not None): message('Scaling to height of {:.2f} mm and width of {:.2f} mm'.format(height,width),'Text may be distorted!') scale_width = width/i_width scale_height = height/i_height else: message('No scaling applied to text') scale_width = 1 scale_height = 1 if (depth is not None): message('Setting depth to {:.2f} mm'.format(depth)) scale_depth = depth/i_depth transform.Scale(scale_width,scale_height,scale_depth) transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputConnection( triangleFilter.GetOutputPort() ) transformFilter.SetTransform( transform ) transformFilter.Update() o_width = transformFilter.GetOutput().GetBounds()[1] - transformFilter.GetOutput().GetBounds()[0] o_height = transformFilter.GetOutput().GetBounds()[3] - transformFilter.GetOutput().GetBounds()[2] o_depth = transformFilter.GetOutput().GetBounds()[5] - transformFilter.GetOutput().GetBounds()[4] o_center = transformFilter.GetOutput().GetCenter() message('Output text:', '{:8s} = {:8.2f} mm'.format('width',o_width), '{:8s} = {:8.2f} mm'.format('height',o_height), '{:8s} = {:8.2f} mm'.format('depth',o_depth)) if (not nobacking): message('Create a backing for the text.') cube = vtk.vtkCubeSource() shift = o_depth/5.0 cube.SetBounds( transformFilter.GetOutput().GetBounds()[0] - o_width * 0.05, transformFilter.GetOutput().GetBounds()[1] + o_width * 0.05, transformFilter.GetOutput().GetBounds()[2] - o_height * 0.1, transformFilter.GetOutput().GetBounds()[3] + o_height * 0.1, transformFilter.GetOutput().GetBounds()[4] - shift, transformFilter.GetOutput().GetBounds()[5] - shift - o_depth * 0.65 ) cube.Update() sign = joinPolyData( cube.GetOutput(), transformFilter.GetOutput() ) else: sign = transformFilter sign = applyTransform(transform_file, sign) if (visualize): mat4x4 = visualize_actors( sign.GetOutputPort(), None ) else: mat4x4 = vtk.vtkMatrix4x4() write_stl( sign.GetOutputPort(), output_file, mat4x4 ) return
def main(): # 3D source sphere sphereSource = vtk.vtkSphereSource() sphereSource.SetPhiResolution(30) sphereSource.SetThetaResolution(30) sphereSource.SetCenter(40, 40, 0) sphereSource.SetRadius(20) # generate circle by cutting the sphere with an implicit plane # (through its center, axis-aligned) circleCutter = vtk.vtkCutter() circleCutter.SetInputConnection(sphereSource.GetOutputPort()) cutPlane = vtk.vtkPlane() cutPlane.SetOrigin(sphereSource.GetCenter()) cutPlane.SetNormal(0, 0, 1) circleCutter.SetCutFunction(cutPlane) stripper = vtk.vtkStripper() stripper.SetInputConnection(circleCutter.GetOutputPort()) # valid circle stripper.Update() # that's our circle circle = stripper.GetOutput() # write circle out polyDataWriter = vtk.vtkXMLPolyDataWriter() polyDataWriter.SetInputData(circle) polyDataWriter.SetFileName("circle.vtp") polyDataWriter.SetCompressorTypeToNone() polyDataWriter.SetDataModeToAscii() polyDataWriter.Write() # prepare the binary image's voxel grid whiteImage = vtk.vtkImageData() bounds = [0] * 6 circle.GetBounds(bounds) spacing = [0] * 3 # desired volume spacing spacing[0] = 0.5 spacing[1] = 0.5 spacing[2] = 0.5 whiteImage.SetSpacing(spacing) # compute dimensions dim = [0] * 3 for i in range(3): dim[i] = int( math.ceil((bounds[i * 2 + 1] - bounds[i * 2]) / spacing[i])) + 1 if dim[i] < 1: dim[i] = 1 whiteImage.SetDimensions(dim) whiteImage.SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1) origin = [0] * 3 # NOTE: I am not sure whether or not we had to add some offset! origin[0] = bounds[0] # + spacing[0] / 2 origin[1] = bounds[2] # + spacing[1] / 2 origin[2] = bounds[4] # + spacing[2] / 2 whiteImage.SetOrigin(origin) whiteImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) # fill the image with foreground voxels: inval = 255 outval = 0 count = whiteImage.GetNumberOfPoints() # for (vtkIdType i = 0 i < count ++i) for i in range(count): whiteImage.GetPointData().GetScalars().SetTuple1(i, inval) # sweep polygonal data (this is the important thing with contours!) extruder = vtk.vtkLinearExtrusionFilter() extruder.SetInputData(circle) extruder.SetScaleFactor(1.0) #extruder.SetExtrusionTypeToNormalExtrusion() # not working extruder.SetExtrusionTypeToVectorExtrusion() extruder.SetVector(0, 0, 1) extruder.Update() # polygonal data -. image stencil: pol2stenc = vtk.vtkPolyDataToImageStencil() pol2stenc.SetTolerance(0) # important if extruder.SetVector(0, 0, 1) !!! pol2stenc.SetInputConnection(extruder.GetOutputPort()) #pol2stenc.SetInputData(circle) pol2stenc.SetOutputOrigin(origin) pol2stenc.SetOutputSpacing(spacing) pol2stenc.SetOutputWholeExtent(whiteImage.GetExtent()) pol2stenc.Update() # cut the corresponding white image and set the background: imgstenc = vtk.vtkImageStencil() imgstenc.SetInputData(whiteImage) imgstenc.SetStencilConnection(pol2stenc.GetOutputPort()) imgstenc.ReverseStencilOff() imgstenc.SetBackgroundValue(outval) imgstenc.Update() imageWriter = vtk.vtkMetaImageWriter() imageWriter.SetFileName("labelImage.mhd") imageWriter.SetInputConnection(imgstenc.GetOutputPort()) imageWriter.Write() imageWriter = vtk.vtkPNGWriter() imageWriter.SetFileName("labelImage.png") imageWriter.SetInputConnection(imgstenc.GetOutputPort()) imageWriter.Write()
disk = vtk.vtkVectorText() disk.SetText("o") t = vtk.vtkTransform() 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)
def main(): points_reader = PointCloudReader("../0000000000.bin") sphereSource = vtk.vtkSphereSource() sphereSource.SetPhiResolution(30) sphereSource.SetThetaResolution(30) sphereSource.SetCenter(40, 40, 0) sphereSource.SetRadius(20) circleCutter = vtk.vtkCutter() circleCutter.SetInputConnection(points_reader.GetOutputPort()) cutPlane = vtk.vtkPlane() cutPlane.SetOrigin([0, 0, 0]) # cutPlane.SetOrigin(sphereSource.GetCenter()) cutPlane.SetNormal(0, 0, 1) circleCutter.SetCutFunction(cutPlane) stripper = vtk.vtkStripper() stripper.SetInputConnection(circleCutter.GetOutputPort()) stripper.Update() circle = stripper.GetOutput() circle_actor = vtk.vtkActor() circle_mapper = vtk.vtkPolyDataMapper() circle_mapper.SetInputConnection(circleCutter.GetOutputPort()) circle_actor.SetMapper(circle_mapper) polyDataWriter = vtk.vtkXMLPolyDataWriter() polyDataWriter.SetInputData(circle) polyDataWriter.SetFileName("circle.vtp") polyDataWriter.SetCompressorTypeToNone() polyDataWriter.SetDataModeToAscii() polyDataWriter.Write() whiteImage = vtk.vtkImageData() bounds = circle.GetBounds() spacing = [0.5, 0.5, 0.5] whiteImage.SetSpacing(spacing) dim = [0, 0, 0] for i in range(3): dim[i] = math.ceil( (bounds[i * 2 + 1] - bounds[i * 2]) / spacing[i]) + 1 whiteImage.SetDimensions(dim) whiteImage.SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1) origin = [bounds[0], bounds[1], bounds[2]] whiteImage.SetOrigin(origin) whiteImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) inval = 255 outval = 0 count = whiteImage.GetNumberOfPoints() for i in range(count): scalars = whiteImage.GetPointData().GetScalars() # f = vtk.vtkFloatArray() # f.SetV scalars.SetValue(i, inval) extruder = vtk.vtkLinearExtrusionFilter() extruder.SetInputData(circle) extruder.SetScaleFactor(1.) extruder.SetVector(0, 0, 1) extruder.Update() pol2stenc = vtk.vtkPolyDataToImageStencil() pol2stenc.SetTolerance(0) pol2stenc.SetInputConnection(extruder.GetOutputPort()) pol2stenc.SetOutputOrigin(origin) pol2stenc.SetOutputSpacing(spacing) pol2stenc.SetOutputWholeExtent(whiteImage.GetExtent()) pol2stenc.Update() imgstenc = vtk.vtkImageStencil() imgstenc.SetInputData(whiteImage) imgstenc.SetStencilConnection(pol2stenc.GetOutputPort()) imgstenc.ReverseStencilOff() imgstenc.SetBackgroundValue(outval) imgstenc.Update() # mapper = vtk.vtkImageMapper() # mapper.SetInputConnection(imgstenc.GetOutputPort()) imgactor = vtk.vtkImageActor() imgactor.GetMapper().SetInputConnection(imgstenc.GetOutputPort()) renderer = vtk.vtkRenderer() renderer.SetBackground(0.1, 0.2, 0.4) renderer.AddActor(imgactor) renderer.AddActor(circle_actor) # renderer.AddActor(actor) renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) style = vtk.vtkInteractorStyleImage() interactor.SetInteractorStyle(style) renderer.ResetCamera() interactor.Start() imageWriter = vtk.vtkMetaImageWriter() imageWriter.SetFileName("labelImage.mhd") imageWriter.SetInputConnection(imgstenc.GetOutputPort()) imageWriter.Write()
# create pipeline - read data # reader = vtk.vtkPolyDataReader() reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/usa.vtk") # okay, now create some extrusion filters with actors for each US state math = vtk.vtkMath() i = 0 while i < 51: locals()[get_variable_name("extractCell", i, "")] = vtk.vtkGeometryFilter() locals()[get_variable_name("extractCell", i, "")].SetInputConnection(reader.GetOutputPort()) locals()[get_variable_name("extractCell", i, "")].CellClippingOn() locals()[get_variable_name("extractCell", i, "")].SetCellMinimum(i) locals()[get_variable_name("extractCell", i, "")].SetCellMaximum(i) locals()[get_variable_name("tf", i, "")] = vtk.vtkTriangleFilter() locals()[get_variable_name("tf", i, "")].SetInputConnection(locals()[get_variable_name("extractCell", i, "")].GetOutputPort()) locals()[get_variable_name("extrude", i, "")] = vtk.vtkLinearExtrusionFilter() locals()[get_variable_name("extrude", i, "")].SetInputConnection(locals()[get_variable_name("tf", i, "")].GetOutputPort()) locals()[get_variable_name("extrude", i, "")].SetExtrusionType(1) locals()[get_variable_name("extrude", i, "")].SetVector(0,0,1) locals()[get_variable_name("extrude", i, "")].CappingOn() locals()[get_variable_name("extrude", i, "")].SetScaleFactor(math.Random(1,10)) locals()[get_variable_name("mapper", i, "")] = vtk.vtkPolyDataMapper() locals()[get_variable_name("mapper", i, "")].SetInputConnection(locals()[get_variable_name("extrude", i, "")].GetOutputPort()) locals()[get_variable_name("actor", i, "")] = vtk.vtkActor() locals()[get_variable_name("actor", i, "")].SetMapper(locals()[get_variable_name("mapper", i, "")]) locals()[get_variable_name("actor", i, "")].GetProperty().SetColor(math.Random(0,1),math.Random(0,1),math.Random(0,1)) ren1.AddActor(locals()[get_variable_name("actor", i, "")]) i = i + 1 ren1.SetBackground(1,1,1) renWin.SetSize(500,250)
def _buildPipeline(self): """Build underlying pipeline and configure rest of pipeline-dependent UI. """ # add the renderer self._renderer = vtk.vtkRenderer() self._renderer.SetBackground(0.5, 0.5, 0.5) self._viewFrame.rwi.GetRenderWindow().AddRenderer(self._renderer) self._histogram = vtkdevide.vtkImageHistogram2D() # make sure the user can't do anything entirely stupid istyle = vtk.vtkInteractorStyleImage() self._viewFrame.rwi.SetInteractorStyle(istyle) # we'll use this to keep track of our ImagePlaneWidget self._ipw = None self._overlayipw = None self._scalarBarWidget = None # self._appendPD = vtk.vtkAppendPolyData() self._extrude = vtk.vtkLinearExtrusionFilter() self._extrude.SetInput(self._appendPD.GetOutput()) self._extrude.SetScaleFactor(1) self._extrude.SetExtrusionTypeToNormalExtrusion() self._extrude.SetVector(0, 0, 1) self._pdToImageStencil = vtk.vtkPolyDataToImageStencil() self._pdToImageStencil.SetInput(self._extrude.GetOutput()) # stupid trick to make image with all ones, but as large as its # input self._allOnes = vtk.vtkImageThreshold() self._allOnes.ThresholdByLower(0.0) self._allOnes.ThresholdByUpper(0.0) self._allOnes.SetInValue(1.0) self._allOnes.SetOutValue(1.0) self._allOnes.SetInput(self._histogram.GetOutput()) self._stencil = vtk.vtkImageStencil() self._stencil.SetInput(self._allOnes.GetOutput()) # self._stencil.SetStencil(self._pdToImageStencil.GetOutput()) self._stencil.ReverseStencilOff() self._stencil.SetBackgroundValue(0) self._lookupAppend = vtk.vtkImageAppendComponents() self._lookup = vtkdevide.vtkHistogramLookupTable() self._lookup.SetInput1(self._lookupAppend.GetOutput()) self._lookup.SetInput2(self._stencil.GetOutput()) module_utils.create_standard_object_introspection( self, self._viewFrame, self._viewFrame.viewFramePanel, {"Module (self)": self, "vtkHistogram2D": self._histogram, "vtkRenderer": self._renderer}, self._renderer.GetRenderWindow(), ) # add the ECASH buttons module_utils.create_eoca_buttons(self, self._viewFrame, self._viewFrame.viewFramePanel)
reader.SetFileName("" + str(VTK_DATA_ROOT) + "/Data/usa.vtk") # okay, now create some extrusion filters with actors for each US state math = vtk.vtkMath() i = 0 while i < 51: locals()[get_variable_name("extractCell", i, "")] = vtk.vtkGeometryFilter() locals()[get_variable_name("extractCell", i, "")].SetInputConnection(reader.GetOutputPort()) locals()[get_variable_name("extractCell", i, "")].CellClippingOn() locals()[get_variable_name("extractCell", i, "")].SetCellMinimum(i) locals()[get_variable_name("extractCell", i, "")].SetCellMaximum(i) locals()[get_variable_name("tf", i, "")] = vtk.vtkTriangleFilter() locals()[get_variable_name("tf", i, "")].SetInputConnection( locals()[get_variable_name("extractCell", i, "")].GetOutputPort()) locals()[get_variable_name("extrude", i, "")] = vtk.vtkLinearExtrusionFilter() locals()[get_variable_name("extrude", i, "")].SetInputConnection( locals()[get_variable_name("tf", i, "")].GetOutputPort()) locals()[get_variable_name("extrude", i, "")].SetExtrusionType(1) locals()[get_variable_name("extrude", i, "")].SetVector(0, 0, 1) locals()[get_variable_name("extrude", i, "")].CappingOn() locals()[get_variable_name("extrude", i, "")].SetScaleFactor(math.Random(1, 10)) locals()[get_variable_name("mapper", i, "")] = vtk.vtkPolyDataMapper() locals()[get_variable_name("mapper", i, "")].SetInputConnection( locals()[get_variable_name("extrude", i, "")].GetOutputPort()) locals()[get_variable_name("actor", i, "")] = vtk.vtkActor() locals()[get_variable_name("actor", i, "")].SetMapper(locals()[get_variable_name( "mapper", i, "")]) locals()[get_variable_name("actor", i, "")].GetProperty().SetColor(
def main(argv): if os.name == 'nt': VTK_DATA_ROOT = "c:/VTK82/build_Release/ExternalData/Testing/" else: VTK_DATA_ROOT = "/home/jmh/" if 1: v16 = vtk.vtkMetaImageReader() v16.SetFileName("/home/jmh/github/fis/data/Abdomen/CT-Abdomen.mhd") v16.Update() elif 0: fname = os.path.join(VTK_DATA_ROOT, "Data/headsq/quarter") v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64, 64) v16.SetDataByteOrderToLittleEndian() v16.SetImageRange(1, 93) v16.SetDataSpacing(3.2, 3.2, 1.5) v16.SetFilePrefix(fname) v16.ReleaseDataFlagOn() v16.SetDataMask(0x7fff) v16.Update() else: v16 = vtk.vtkMetaImageReader() v16.SetFileName("c:/github/fis/data/Abdomen/CT-Abdomen.mhd") v16.Update() rng = v16.GetOutput().GetScalarRange() shifter = vtk.vtkImageShiftScale() shifter.SetShift(-1.0*rng[0]) shifter.SetScale(255.0/(rng[1]-rng[0])) shifter.SetOutputScalarTypeToUnsignedChar() shifter.SetInputConnection(v16.GetOutputPort()) shifter.ReleaseDataFlagOff() shifter.Update() ImageViewer = vtk.vtkImageViewer2() ImageViewer.SetInputData(shifter.GetOutput()) ImageViewer.SetColorLevel(127) ImageViewer.SetColorWindow(255) iren = vtk.vtkRenderWindowInteractor() ImageViewer.SetupInteractor(iren) ImageViewer.Render() ImageViewer.GetRenderer().ResetCamera() ImageViewer.Render() dims = v16.GetOutput().GetDimensions() global minArea spacing = v16.GetOutput().GetSpacing() minArea = ( spacing[0] * spacing[1] ) / 0.1 # Slider screen representation SliderRepres = vtk.vtkSliderRepresentation2D() _min = ImageViewer.GetSliceMin() _max = ImageViewer.GetSliceMax() SliderRepres.SetMinimumValue(_min) SliderRepres.SetMaximumValue(_max) SliderRepres.SetValue(int((_min + _max) / 2)) SliderRepres.SetTitleText("Slice") SliderRepres.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint1Coordinate().SetValue(0.3, 0.05) SliderRepres.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() SliderRepres.GetPoint2Coordinate().SetValue(0.7, 0.05) SliderRepres.SetSliderLength(0.02) SliderRepres.SetSliderWidth(0.03) SliderRepres.SetEndCapLength(0.01) SliderRepres.SetEndCapWidth(0.03) SliderRepres.SetTubeWidth(0.005) SliderRepres.SetLabelFormat("%3.0lf") SliderRepres.SetTitleHeight(0.02) SliderRepres.SetLabelHeight(0.02) # Slider widget SliderWidget = vtk.vtkSliderWidget() SliderWidget.SetInteractor(iren) SliderWidget.SetRepresentation(SliderRepres) SliderWidget.KeyPressActivationOff() SliderWidget.SetAnimationModeToAnimate() SliderWidget.SetEnabled(True) SliderCb = vtkSliderCallback() SliderCb.SetImageViewer(ImageViewer) SliderWidget.AddObserver(vtk.vtkCommand.InteractionEvent, SliderCb.Execute) ImageViewer.SetSlice(int(SliderRepres.GetValue())) # Contour representation - responsible for placement of points, calculation of lines and contour manipulation global rep rep = vtk.vtkOrientedGlyphContourRepresentation() # vtkContourRepresentation has GetActiveNodeWorldPostion/Orientation rep.GetProperty().SetOpacity(0) #1 prop = rep.GetLinesProperty() from vtkUtils import renderLinesAsTubes from vtk.util.colors import red, green, pink, yellow renderLinesAsTubes(prop) prop.SetColor(yellow) propActive = rep.GetActiveProperty() #propActive.SetOpacity(0) # 2 renderLinesAsTubes(propActive) propActive.SetColor(green) shapeActive = rep.GetActiveCursorShape() warp = vtk.vtkWarpVector() warp.SetInputData(shapeActive) warp.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, vtk.vtkDataSetAttributes.NORMALS) scale = 0.4 warp.SetScaleFactor(scale) warp.Update() rep.SetActiveCursorShape(warp.GetOutput()) # Use vtkContourTriangulator to fill contours # Point placer imageActorPointPlacer = vtk.vtkImageActorPointPlacer() imageActorPointPlacer.SetImageActor(ImageViewer.GetImageActor()) rep.SetPointPlacer(imageActorPointPlacer) global ContourWidget # Contour widget - has a vtkWidgetEventTranslator which translate events to vtkContourWidget events ContourWidget = vtk.vtkContourWidget() ContourWidget.SetRepresentation(rep) ContourWidget.SetInteractor(iren) ContourWidget.SetEnabled(True) ContourWidget.ProcessEventsOn() ContourWidget.ContinuousDrawOn() # Can be Initialize() using polydata # Override methods that returns display position to get an overlay # (display postions) instead of computing it from world position and # the method BuildLines to interpolate using display positions # instead of world positions # Thinning of contour control points # AddFinalPointAction ContourWidget.AddObserver(vtk.vtkCommand.EndInteractionEvent, callback) if 0: # TODO: Make interior transparent contour = ContourWidget.GetContourRepresentation().GetContourRepresentationAsPolyData() tc = vtk.vtkContourTriangulator() tc.SetInputData(contour) tc.Update() # Extrusion towards camera extruder = vtk.vtkLinearExtrusionFilter() extruder.CappingOn() extruder.SetScalaFactor(1.0) extruder.SetInputData(tc.GetOutput()) extruder.SetVector(0,0,1.0) extruder.SetExtrusionTypeToNormalExtrusion() polyMapper = vtk.vtkPolyMapper() polyMapper.SetInputConnection(extruder.GetOutputPort()) polyMapper.ScalarVisibilityOn() polyMapper.Update() polyActor = vtk.vtkActor() polyActor.SetMapper(polyMapper) prop = polyActor.GetProperty() prop.SetColor(0,1,0) #prop.SetRepresentationToWireframe() renderer.AddActor(polyActor) renderer.GetRenderWindow().Render() iren.Start()
def text(txt, pos=(0, 0, 0), normal=(0, 0, 1), s=1, depth=0.1, c='k', alpha=1, bc=None, texture=None, followcam=False, cam=None): ''' Returns a vtkActor that shows a text in 3D. Options: pos = position in 3D space, if an integer is passed [1 -> 8], places text in one of the 4 corners s = size of text depth = text thickness followcam = False, if True the text will auto-orient itself to it. [**Example1**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/colorcubes.py) [**Example2**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/mesh_coloring.py) ''' if isinstance(pos, int): cornerAnnotation = vtk.vtkCornerAnnotation() cornerAnnotation.SetNonlinearFontScaleFactor(s / 3) cornerAnnotation.SetText(pos - 1, str(txt)) cornerAnnotation.GetTextProperty().SetColor(colors.getColor(c)) return cornerAnnotation tt = vtk.vtkVectorText() tt.SetText(str(txt)) tt.Update() ttmapper = vtk.vtkPolyDataMapper() if followcam: depth = 0 normal = (0, 0, 1) if depth: extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection(tt.GetOutputPort()) extrude.SetExtrusionTypeToVectorExtrusion() extrude.SetVector(0, 0, 1) extrude.SetScaleFactor(depth) ttmapper.SetInputConnection(extrude.GetOutputPort()) else: ttmapper.SetInputConnection(tt.GetOutputPort()) if followcam: ttactor = vtk.vtkFollower() ttactor.SetCamera(cam) else: ttactor = Actor() ttactor.SetMapper(ttmapper) ttactor.GetProperty().SetColor(colors.getColor(c)) # check if color string contains a float, in this case ignore alpha al = colors.getAlpha(c) if al: alpha = al ttactor.GetProperty().SetOpacity(alpha) nax = np.linalg.norm(normal) if nax: normal = np.array(normal) / nax theta = np.arccos(normal[2]) phi = np.arctan2(normal[1], normal[0]) ttactor.SetScale(s, s, s) ttactor.RotateZ(phi * 57.3) ttactor.RotateY(theta * 57.3) ttactor.SetPosition(pos) if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) ttactor.SetBackfaceProperty(backProp) if texture: ttactor.texture(texture) return ttactor
def make_patterned_polydata( inputContours, fillareastyle=None, fillareaindex=None, fillareacolors=None, fillareaopacity=None, size=None ): if inputContours is None or fillareastyle == "solid": return None if inputContours.GetNumberOfCells() == 0: return None if fillareaindex is None: fillareaindex = 1 if fillareaopacity is None: fillareaopacity = 100 num_pixels = num_pixels_for_size(size) # Create the plane that will be textured with the pattern # The bounds of the plane match the bounds of the input polydata bounds = inputContours.GetBounds() patternPlane = vtk.vtkPlaneSource() patternPlane.SetOrigin(bounds[0], bounds[2], 0.0) patternPlane.SetPoint1(bounds[0], bounds[3], 0.0) patternPlane.SetPoint2(bounds[1], bounds[2], 0.0) # Generate texture coordinates for the plane textureMap = vtk.vtkTextureMapToPlane() textureMap.SetInputConnection(patternPlane.GetOutputPort()) # Create the pattern image of the size of the input polydata # and type defined by fillareaindex xBounds = bounds[1] - bounds[0] yBounds = bounds[3] - bounds[2] if xBounds <= 1 and yBounds <= 1 and size is not None: xBounds *= size[0] yBounds *= size[1] xres, yres = int(xBounds), int(yBounds) xres = int(4.0 * xBounds) yres = int(4.0 * yBounds) # Handle the case when the bounds are less than 1 in physical dimensions patternImage = create_pattern(xres, yres, num_pixels, fillareastyle, fillareaindex, fillareacolors, fillareaopacity) if patternImage is None: return None # Extrude the contour since vtkPolyDataToImageStencil # requires 3D polydata extruder = vtk.vtkLinearExtrusionFilter() extruder.SetInputData(inputContours) extruder.SetScaleFactor(1.0) extruder.SetVector(0, 0, 1) extruder.SetExtrusionTypeToNormalExtrusion() # Create a binary image mask from the extruded polydata pol2stenc = vtk.vtkPolyDataToImageStencil() pol2stenc.SetTolerance(0) pol2stenc.SetInputConnection(extruder.GetOutputPort()) pol2stenc.SetOutputOrigin(bounds[0], bounds[2], 0.0) pol2stenc.SetOutputSpacing((bounds[1] - bounds[0]) / xres, (bounds[3] - bounds[2]) / yres, 0.0) pol2stenc.SetOutputWholeExtent(patternImage.GetExtent()) # Stencil out the fillarea from the pattern image stenc = vtk.vtkImageStencil() stenc.SetInputData(patternImage) stenc.SetStencilConnection(pol2stenc.GetOutputPort()) stenc.ReverseStencilOff() stenc.SetBackgroundColor(0, 0, 0, 0) stenc.Update() patternImage = stenc.GetOutput() # Create the texture using the stenciled pattern patternTexture = vtk.vtkTexture() patternTexture.SetInputData(patternImage) patternTexture.InterpolateOn() patternTexture.RepeatOn() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(textureMap.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.SetTexture(patternTexture) return actor
def Text( txt, pos=3, s=1, depth=0.1, justify="bottom-left", c=None, alpha=1, bc=None, bg=None, font="courier", followcam=False, ): """ Returns an ``Actor`` that shows a 2D/3D text. :param pos: position in 3D space, if an integer is passed [1,8], a 2D text is placed in one of the 4 corners: 1, bottom-left 2, bottom-right 3, top-left 4, top-right 5, bottom-middle 6, middle-right 7, middle-left 8, top-middle If a pair (x,y) is passed as input the 2D text is place at that position in the coordinate system of the 2D screen (with the origin sitting at the bottom left). :type pos: list, int :param float s: size of text. :param float depth: text thickness. :param str justify: text justification (bottom-left, bottom-right, top-left, top-right, centered). :param bg: background color of corner annotations. Only applies of `pos` is ``int``. :param str font: additional available fonts are: - Ageo - Aldora - CallingCode - Godsway - Gula - ImpactLabel - Komiko - Lamborgini - MidnightDrive - Militech - MonaShark - Montserrat - MyDisplaySt - PointedLaidSt - SchoolTeacher - SpecialElite Font choice does not apply for 3D text. A path to `otf` or `ttf` font-file can also be supplied as input. All fonts are free for personal use. Check out conditions in `vtkplotter/fonts/licenses` for commercial use and: https://www.1001freefonts.com :param followcam: if `True` the text will auto-orient itself to the active camera. A ``vtkCamera`` object can also be passed. :type followcam: bool, vtkCamera .. hint:: Examples, |fonts.py|_ |colorcubes.py|_ |markpoint.py|_ |annotations.py|_ |colorcubes| |markpoint| |fonts| """ if c is None: # automatic black or white if settings.plotter_instance and settings.plotter_instance.renderer: c = (0.9, 0.9, 0.9) if np.sum(settings.plotter_instance.renderer.GetBackground()) > 1.5: c = (0.1, 0.1, 0.1) else: c = (0.6, 0.6, 0.6) if isinstance(pos, int): # corners if pos > 8: pos = 8 if pos < 1: pos = 1 ca = vtk.vtkCornerAnnotation() ca.SetNonlinearFontScaleFactor(s/2.7) ca.SetText(pos - 1, str(txt)) ca.PickableOff() cap = ca.GetTextProperty() cap.SetColor(colors.getColor(c)) if font.lower() == "courier": cap.SetFontFamilyToCourier() elif font.lower() == "times": cap.SetFontFamilyToTimes() elif font.lower() == "arial": cap.SetFontFamilyToArial() else: cap.SetFontFamily(vtk.VTK_FONT_FILE) cap.SetFontFile(settings.fonts_path+font+'.ttf') if bg: bgcol = colors.getColor(bg) cap.SetBackgroundColor(bgcol) cap.SetBackgroundOpacity(alpha * 0.5) cap.SetFrameColor(bgcol) cap.FrameOn() setattr(ca, 'renderedAt', set()) settings.collectable_actors.append(ca) return ca elif len(pos)==2: # passing (x,y) coords actor2d = vtk.vtkActor2D() actor2d.SetPosition(pos) tmapper = vtk.vtkTextMapper() actor2d.SetMapper(tmapper) tp = tmapper.GetTextProperty() tp.BoldOff() tp.SetFontSize(s*20) tp.SetColor(colors.getColor(c)) tp.SetJustificationToLeft() tp.SetVerticalJustificationToBottom() if font.lower() == "courier": tp.SetFontFamilyToCourier() elif font.lower() == "times": tp.SetFontFamilyToTimes() elif font.lower() == "arial": tp.SetFontFamilyToArial() else: tp.SetFontFamily(vtk.VTK_FONT_FILE) import os if font in settings.fonts: tp.SetFontFile(settings.fonts_path + font + '.ttf') elif os.path.exists(font): tp.SetFontFile(font) else: colors.printc("~sad Font", font, "not found in", settings.fonts_path, c="r") colors.printc("~pin Available fonts are:", settings.fonts, c="m") return None if bg: bgcol = colors.getColor(bg) tp.SetBackgroundColor(bgcol) tp.SetBackgroundOpacity(alpha * 0.5) tp.SetFrameColor(bgcol) tp.FrameOn() tmapper.SetInput(str(txt)) actor2d.PickableOff() setattr(actor2d, 'renderedAt', set()) settings.collectable_actors.append(actor2d) return actor2d else: # otherwise build the 3D text, fonts do not apply tt = vtk.vtkVectorText() tt.SetText(str(txt)) tt.Update() tpoly = tt.GetOutput() bb = tpoly.GetBounds() dx, dy = (bb[1] - bb[0]) / 2 * s, (bb[3] - bb[2]) / 2 * s cm = np.array([(bb[1] + bb[0]) / 2, (bb[3] + bb[2]) / 2, (bb[5] + bb[4]) / 2]) * s shift = -cm if "bottom" in justify: shift += np.array([ 0, dy, 0]) if "top" in justify: shift += np.array([ 0,-dy, 0]) if "left" in justify: shift += np.array([ dx, 0, 0]) if "right" in justify: shift += np.array([-dx, 0, 0]) t = vtk.vtkTransform() t.Translate(shift) t.Scale(s, s, s) tf = vtk.vtkTransformPolyDataFilter() tf.SetInputData(tpoly) tf.SetTransform(t) tf.Update() tpoly = tf.GetOutput() if followcam: ttactor = vtk.vtkFollower() ttactor.GetProperty().SetOpacity(alpha) ttactor.GetProperty().SetColor(colors.getColor(c)) if isinstance(followcam, vtk.vtkCamera): ttactor.SetCamera(followcam) else: ttactor.SetCamera(settings.plotter_instance.camera) else: if depth: extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputData(tpoly) extrude.SetExtrusionTypeToVectorExtrusion() extrude.SetVector(0, 0, 1) extrude.SetScaleFactor(depth*dy) extrude.Update() tpoly = extrude.GetOutput() ttactor = Actor(tpoly, c, alpha, bc=bc) ttactor.SetPosition(pos) settings.collectable_actors.append(ttactor) return ttactor
def Extrude(Slope,Extrusion,Plane,Model,Sediment,Start_time,End_time,Time_step,Mesh): ugrid1 = vtk.vtkUnstructuredGrid() #1.import sloped sediment and change to polydata gridreader1=vtk.vtkUnstructuredGridReader() gridreader1.SetFileName(Slope) #.pvd gridreader1.Update() ugrid1 = gridreader1.GetOutput() GeomFilt1 = vtk.vtkGeometryFilter() GeomFilt1.SetInput(ugrid1) GeomFilt1.Update() y1 = GeomFilt1.GetOutput() Extrude = vtk.vtkLinearExtrusionFilter() #2. extrude the polydata and save it again as polydata Extrude.SetInput(y1) Extrude.SetExtrusionTypeToVectorExtrusion() Extrude.SetVector(0,0,-1) PreliminaryExtrusion = Extrude.GetOutput() PE = vtk.vtkPolyData() PE = PreliminaryExtrusion PE.Update() ugrid2 = vtk.vtkUnstructuredGrid() #3. import in the top surface of the sediment below gridreader2=vtk.vtkXMLUnstructuredGridReader() gridreader2.SetFileName(Plane) # 000000.vtu gridreader2.Update() ugrid2 = gridreader2.GetOutput() ExtrudedPoints = PE.GetPoints() #4. take points from the extruded polydata PlanePoints = ugrid2.GetPoints() #5. get points from surface below nPoints = PE.GetNumberOfPoints() #6. for first half of points determine if above or below last surface Begin = nPoints/2 #7. if below set as the same as bottom surface (slightly above?) #8. set second half counter = 0 uPoints = ugrid2.GetPoints() for p in range(Begin,nPoints): y = uPoints.GetPoint(counter)[2:] x = ExtrudedPoints.GetPoint(p)[:2] + y ExtrudedPoints.SetPoint(p,x) counter += 1 PE.Update() writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(Model) writer.SetInput(PE) writer.Update() writer.Write() ################################################################################################################# t = Start_time dt = Time_step ET = End_time et = ET-1 Save = Sediment + str(t) +'000000.vtu' Import = Sediment + str(t)+ '_sed_slope.pvd' NewSave = Sediment + str(t)+ 'extruded_sed_slope.pvd' SedimentGrid1 = vtk.vtkUnstructuredGrid() #1.import sloped sediment and change to polydata SedimentGridreader1=vtk.vtkUnstructuredGridReader() SedimentGridreader1.SetFileName(Import) #.pvd SedimentGridreader1.Update() SedimentGrid1 = SedimentGridreader1.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(SedimentGrid1) GeomFilt2.Update() ExtrudeInput1 = GeomFilt2.GetOutput() ExtrudeSed1 = vtk.vtkLinearExtrusionFilter() #2. extrude the polydata and save it again as polydata ExtrudeSed1.SetInput(ExtrudeInput1) ExtrudeSed1.SetExtrusionTypeToVectorExtrusion() ExtrudeSed1.SetVector(0,0,-1) PreliminarySedExtrusion1 = ExtrudeSed1.GetOutput() PSE1 = vtk.vtkPolyData() PSE1 = PreliminarySedExtrusion1 PSE1.Update() PreSurface1 = vtk.vtkUnstructuredGrid() #3. import in the top surface of the sediment below PSreader1=vtk.vtkGenericDataObjectReader() PSreader1.SetFileName(Slope) # 000000.vtu PSreader1.Update() PreSurface1 = PSreader1.GetOutput() ExtrudedSedPoints1 = PSE1.GetPoints() #4. take points from the extruded polydata PSPoints1 = PreSurface1.GetPoints() #5. get points from surface below SedPoints1 = PSE1.GetNumberOfPoints() #6. for first half of points determine if above or below last surface BeginSed1 = nPoints/2 EndSed1 = BeginSed1 - 1 #7. if below set as the same as bottom surface (slightly above? sedcounter1 = 0 #8. set second half sedcounter2 = BeginSed1 for p in range(BeginSed1,SedPoints1): y = PSPoints1.GetPoint(sedcounter1)[2:] x = ExtrudedSedPoints1.GetPoint(p)[:2] + y ExtrudedSedPoints1.SetPoint(p,x) sedcounter1 += 1 writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(NewSave) writer.SetInput(PSE1) writer.Update() writer.Write() ##################################################################################################################### while t <= et: t += dt pre = t -1 Previous = Sediment +str(pre) + '_sed_slope.pvd' PreviousSave = Sediment + str(pre)+ 'extruded_sed_slope.pvd' Import = Sediment + str(t)+ '_sed_slope.pvd' NewSave = Sediment + str(t)+ 'extruded_sed_slope.pvd' SedimentGrid2 = vtk.vtkUnstructuredGrid() SedimentGridreader2=vtk.vtkUnstructuredGridReader() SedimentGridreader2.SetFileName(Import) #.pvd SedimentGridreader2.Update() SedimentGrid2 = SedimentGridreader2.GetOutput() GeomFilt3 = vtk.vtkGeometryFilter() GeomFilt3.SetInput(SedimentGrid2) GeomFilt3.Update() ExtrudeInput = GeomFilt3.GetOutput() ExtrudeInput2 = GeomFilt3.GetOutput() ExtrudeSed2 = vtk.vtkLinearExtrusionFilter() ExtrudeSed2.SetInput(ExtrudeInput2) ExtrudeSed2.SetExtrusionTypeToVectorExtrusion() ExtrudeSed2.SetVector(0,0,-1) PreliminarySedExtrusion2 = ExtrudeSed2.GetOutput() PSE2 = vtk.vtkPolyData() PSE2 = PreliminarySedExtrusion2 PSE2.Update() PreSurface2 = vtk.vtkUnstructuredGrid() PSreader2=vtk.vtkGenericDataObjectReader() PSreader2.SetFileName(PreviousSave) # 000000.vtu PSreader2.Update() PreSurface2 = PSreader2.GetOutput() Append = vtk.vtkAppendPolyData() Append.AddInput(PreSurface2) Append.AddInput(PSE2) DD = Append.GetOutput() DD.Update() ExtrudedSedPoints = PSE2.GetPoints() PSPoints = PreSurface2.GetPoints() SedPoints = PSE2.GetNumberOfPoints() BeginSed = nPoints/2 EndSed = BeginSed - 1 sedcounter3 = 0 sedcounter4 = BeginSed Data = DD.GetPoints() mesh = Mesh m = (mesh+1)**2 c = t while c != 0: c = (c -1) e = int((c*m)*2) ee = int(e + m) for p in range(e,ee): A = Data.GetPoint(p+(2*m))[2:] #New sediment height B = Data.GetPoint(p)[2:] # old sediment height C = Data.GetPoint(p+m)[2:] # old sediment bottom if A < B: #If new sediment height is less than old sediment height y = (Data.GetPoint(p)[:2] + Data.GetPoint(p+(2*m))[2:]) Data.SetPoint(p,y) if A < C: x = Data.GetPoint(p+m)[:2] + Data.GetPoint(p)[2:] Data.SetPoint((p+m),x) f = int((t*m)*2+m) ff = int(f + m) for p in range(f,ff): y = Data.GetPoint((p-3*m))[2:] x = Data.GetPoint(p)[:2] + y Data.SetPoint(p,x) writer = vtk.vtkGenericDataObjectWriter() writer.SetFileName(NewSave) writer.SetInput(DD) writer.Update() writer.Write()
def main(): fileName = get_program_parameters() colors = vtk.vtkNamedColors() # Here we read the file keeping only the alpha characters # and calculate the frequency of each letter. with open(fileName) as f: freq = Counter() for x in f: remove_digits = re.sub("[\d_]", "", x.strip().lower()) freq += Counter(re.findall("\w", remove_digits, re.UNICODE)) maxFreq = max(list(freq.values())) keys = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ".lower()) # # graphics stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # # Setup letters # letters = list() extrude = list() mappers = list() actors = list() i = 0 for k in keys: letters.append(vtk.vtkVectorText()) letters[i].SetText(k.upper()) extrude.append(vtk.vtkLinearExtrusionFilter()) extrude[i].SetInputConnection(letters[i].GetOutputPort()) extrude[i].SetExtrusionTypeToVectorExtrusion() extrude[i].SetVector(0, 0, 1.0) extrude[i].SetScaleFactor(float(freq[k]) / maxFreq * 2.50) mappers.append(vtk.vtkPolyDataMapper()) mappers[i].SetInputConnection(extrude[i].GetOutputPort()) mappers[i].ScalarVisibilityOff() actors.append(vtk.vtkActor()) actors[i].SetMapper(mappers[i]) actors[i].GetProperty().SetColor(colors.GetColor3d("Peacock")) if freq[k] <= 0: actors[i].VisibilityOff() ren.AddActor(actors[i]) i += 1 # Position the actors. y = 0.0 for j in range(0, 2): x = 0.0 for i in range(0, 13): actors[j * 13 + i].SetPosition(x, y, 0.0) x += 1.5 y += -3.0 ren.ResetCamera() ren.SetBackground(colors.GetColor3d("Silver")) ren.GetActiveCamera().Elevation(30.0) ren.GetActiveCamera().Azimuth(-30.0) ren.GetActiveCamera().Dolly(1.25) ren.ResetCameraClippingRange() renWin.SetSize(640, 480) # Interact with the data. iren.Start()
def text(txt, pos=(0, 0, 0), normal=(0, 0, 1), s=1, depth=0.1, justify='bottom-left', c='k', alpha=1, bc=None, texture=None, followcam=False, cam=None): ''' Returns a ``vtkActor`` that shows a 3D text. :param pos: position in 3D space, if an integer is passed [1,8], place text in one of the 4 corners. :type pos: list, int :param float s: size of text. :param float depth: text thickness. :param str justify: text justification (bottom-left, bottom-right, top-left, top-right, centered). :param bool followcam: if `True` the text will auto-orient itself to the cam. .. hint:: Example: `colorcubes.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/colorcubes.py>`_ .. image:: https://user-images.githubusercontent.com/32848391/50738867-c0658e80-11d8-11e9-9e05-ac69b546b7ec.png ''' if isinstance(pos, int): cornerAnnotation = vtk.vtkCornerAnnotation() cornerAnnotation.SetNonlinearFontScaleFactor(s / 3) cornerAnnotation.SetText(pos - 1, str(txt)) cornerAnnotation.GetTextProperty().SetColor(colors.getColor(c)) return cornerAnnotation tt = vtk.vtkVectorText() tt.SetText(str(txt)) tt.Update() ttmapper = vtk.vtkPolyDataMapper() if followcam: depth = 0 normal = (0, 0, 1) if depth: extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection(tt.GetOutputPort()) extrude.SetExtrusionTypeToVectorExtrusion() extrude.SetVector(0, 0, 1) extrude.SetScaleFactor(depth) ttmapper.SetInputConnection(extrude.GetOutputPort()) else: ttmapper.SetInputConnection(tt.GetOutputPort()) if followcam: ttactor = vtk.vtkFollower() ttactor.SetCamera(cam) else: ttactor = Actor() ttactor.SetMapper(ttmapper) ttactor.GetProperty().SetColor(colors.getColor(c)) ttmapper.Update() bb = tt.GetOutput().GetBounds() dx, dy = (bb[1] - bb[0]) / 2 * s, (bb[3] - bb[2]) / 2 * s cm = np.array([(bb[1] + bb[0]) / 2, (bb[3] + bb[2]) / 2, (bb[5] + bb[4]) / 2]) * s shift = -cm if 'cent' in justify: pass elif 'bottom-left' in justify: shift += np.array([dx, dy, 0]) elif 'top-left' in justify: shift += np.array([dx, -dy, 0]) elif 'bottom-right' in justify: shift += np.array([-dx, dy, 0]) elif 'top-right' in justify: shift += np.array([-dx, -dy, 0]) else: colors.printc("text(): Unknown justify type", justify, c=1) # check if color string contains a float, in this case ignore alpha al = colors._getAlpha(c) if al: alpha = al ttactor.GetProperty().SetOpacity(alpha) nax = np.linalg.norm(normal) if nax: normal = np.array(normal) / nax theta = np.arccos(normal[2]) phi = np.arctan2(normal[1], normal[0]) ttactor.SetScale(s, s, s) ttactor.RotateZ(phi * 57.3) ttactor.RotateY(theta * 57.3) ttactor.SetPosition(pos + shift) if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) ttactor.SetBackfaceProperty(backProp) if texture: ttactor.texture(texture) ttactor.PickableOff() return ttactor
def Text( txt, pos=3, normal=(0, 0, 1), s=1, depth=0.1, justify="bottom-left", c=None, alpha=1, bc=None, bg=None, font="courier", followcam=False, ): """ Returns a ``vtkActor`` that shows a 3D text. :param pos: position in 3D space, if an integer is passed [1,8], a 2D text is placed in one of the 4 corners: 1, bottom-left 2, bottom-right 3, top-left 4, top-right 5, bottom-middle 6, middle-right 7, middle-left 8, top-middle :type pos: list, int :param float s: size of text. :param float depth: text thickness. :param str justify: text justification (bottom-left, bottom-right, top-left, top-right, centered). :param bg: background color of corner annotations. Only applies of `pos` is ``int``. :param str font: either `arial`, `courier` or `times`. Only applies of `pos` is ``int``. :param followcam: if `True` the text will auto-orient itself to the active camera. A ``vtkCamera`` object can also be passed. :type followcam: bool, vtkCamera .. hint:: |colorcubes.py|_ |markpoint.py|_ |annotations.py|_ |colorcubes| |markpoint| """ if c is None: # automatic black or white if settings.plotter_instance and settings.plotter_instance.renderer: c = (0.9, 0.9, 0.9) if np.sum( settings.plotter_instance.renderer.GetBackground()) > 1.5: c = (0.1, 0.1, 0.1) else: c = (0.6, 0.6, 0.6) if isinstance(pos, int): if pos > 8: pos = 8 if pos < 1: pos = 1 ca = vtk.vtkCornerAnnotation() ca.SetNonlinearFontScaleFactor(s / 2.7) ca.SetText(pos - 1, str(txt)) ca.PickableOff() cap = ca.GetTextProperty() cap.SetColor(colors.getColor(c)) if font.lower() == "courier": cap.SetFontFamilyToCourier() elif font.lower() == "times": cap.SetFontFamilyToTimes() else: cap.SetFontFamilyToArial() if bg: bgcol = colors.getColor(bg) cap.SetBackgroundColor(bgcol) cap.SetBackgroundOpacity(alpha * 0.5) cap.SetFrameColor(bgcol) cap.FrameOn() setattr(ca, 'renderedAt', set()) settings.collectable_actors.append(ca) return ca tt = vtk.vtkVectorText() tt.SetText(str(txt)) tt.Update() ttmapper = vtk.vtkPolyDataMapper() if followcam: depth = 0 normal = (0, 0, 1) if depth: extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection(tt.GetOutputPort()) extrude.SetExtrusionTypeToVectorExtrusion() extrude.SetVector(0, 0, 1) extrude.SetScaleFactor(depth) ttmapper.SetInputConnection(extrude.GetOutputPort()) else: ttmapper.SetInputConnection(tt.GetOutputPort()) if followcam: ttactor = vtk.vtkFollower() if isinstance(followcam, vtk.vtkCamera): ttactor.SetCamera(followcam) else: ttactor.SetCamera(settings.plotter_instance.camera) else: ttactor = Actor() ttactor.SetMapper(ttmapper) ttactor.GetProperty().SetColor(colors.getColor(c)) ttmapper.Update() bb = tt.GetOutput().GetBounds() dx, dy = (bb[1] - bb[0]) / 2 * s, (bb[3] - bb[2]) / 2 * s cm = np.array([(bb[1] + bb[0]) / 2, (bb[3] + bb[2]) / 2, (bb[5] + bb[4]) / 2]) * s shift = -cm if "cent" in justify: pass elif "bottom-left" in justify: shift += np.array([dx, dy, 0]) elif "top-left" in justify: shift += np.array([dx, -dy, 0]) elif "bottom-right" in justify: shift += np.array([-dx, dy, 0]) elif "top-right" in justify: shift += np.array([-dx, -dy, 0]) else: colors.printc("~lightning Text(): Unknown justify type", justify, c=1) ttactor.GetProperty().SetOpacity(alpha) nax = np.linalg.norm(normal) if nax: normal = np.array(normal) / nax theta = np.arccos(normal[2]) phi = np.arctan2(normal[1], normal[0]) ttactor.SetScale(s, s, s) ttactor.RotateZ(np.rad2deg(phi)) ttactor.RotateY(np.rad2deg(theta)) ttactor.SetPosition(pos + shift) if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(colors.getColor(bc)) backProp.SetOpacity(alpha) ttactor.SetBackfaceProperty(backProp) ttactor.PickableOff() settings.collectable_actors.append(ttactor) return ttactor
def main(): nx, ny, nz = get_program_parameters() colors = vtk.vtkNamedColors() angle = 0 r1 = 50 r2 = 30 centerX = 10.0 centerY = 5.0 points = vtk.vtkPoints() idx = 0 while angle <= 2.0 * vtk.vtkMath.Pi() + (vtk.vtkMath.Pi() / 60.0): points.InsertNextPoint(r1 * math.cos(angle) + centerX, r2 * math.sin(angle) + centerY, 0.0) angle = angle + (vtk.vtkMath.Pi() / 60.0) idx += 1 line = vtk.vtkPolyLine() line.GetPointIds().SetNumberOfIds(idx) for i in range(0, idx): line.GetPointIds().SetId(i, i) lines = vtk.vtkCellArray() lines.InsertNextCell(line) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetLines(lines) extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputData(polyData) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(nx, ny, nz) extrude.Update() # Create an oriented arrow startPoint = [0.0] * 3 endPoint = [0.0] * 3 startPoint[0] = centerX startPoint[1] = centerY startPoint[2] = 0.0 endPoint[0] = startPoint[0] + extrude.GetVector()[0] endPoint[1] = startPoint[1] + extrude.GetVector()[1] endPoint[2] = startPoint[2] + extrude.GetVector()[2] # Compute a basis normalizedX = [0.0] * 3 normalizedY = [0.0] * 3 normalizedZ = [0.0] * 3 # The X axis is a vector from start to end vtk.vtkMath.Subtract(endPoint, startPoint, normalizedX) length = vtk.vtkMath.Norm(normalizedX) vtk.vtkMath.Normalize(normalizedX) # The Z axis is an arbitrary vector cross X arbitrary = [0.0] * 3 arbitrary[0] = vtk.vtkMath.Random(-10, 10) arbitrary[1] = vtk.vtkMath.Random(-10, 10) arbitrary[2] = vtk.vtkMath.Random(-10, 10) vtk.vtkMath.Cross(normalizedX, arbitrary, normalizedZ) vtk.vtkMath.Normalize(normalizedZ) # The Y axis is Z cross X vtk.vtkMath.Cross(normalizedZ, normalizedX, normalizedY) matrix = vtk.vtkMatrix4x4() # Create the direction cosine matrix matrix.Identity() for i in range(0, 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) arrowSource = vtk.vtkArrowSource() arrowSource.SetTipResolution(31) arrowSource.SetShaftResolution(21) # Transform the polydata transformPD = vtk.vtkTransformPolyDataFilter() transformPD.SetTransform(transform) transformPD.SetInputConnection(arrowSource.GetOutputPort()) # Create a mapper and actor for the arrow arrowMapper = vtk.vtkPolyDataMapper() arrowMapper.SetInputConnection(transformPD.GetOutputPort()) arrowActor = vtk.vtkActor() arrowActor.SetMapper(arrowMapper) arrowActor.GetProperty().SetColor(colors.GetColor3d("Tomato")) tubes = vtk.vtkTubeFilter() tubes.SetInputData(polyData) tubes.SetRadius(2.0) tubes.SetNumberOfSides(21) lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection(tubes.GetOutputPort()) lineActor = vtk.vtkActor() lineActor.SetMapper(lineMapper) lineActor.GetProperty().SetColor(colors.GetColor3d("Peacock")) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(extrude.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d("Banana")) actor.GetProperty().SetOpacity(.7) ren = vtk.vtkRenderer() ren.SetBackground(colors.GetColor3d("SlateGray")) ren.AddActor(actor) ren.AddActor(lineActor) ren.AddActor(arrowActor) renWin = vtk.vtkRenderWindow() renWin.SetWindowName("Elliptical Cylinder Demo") renWin.AddRenderer(ren) renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) camera = vtk.vtkCamera() camera.SetPosition(0, 1, 0) camera.SetFocalPoint(0, 0, 0) camera.SetViewUp(0, 0, 1) camera.Azimuth(30) camera.Elevation(30) ren.SetActiveCamera(camera) ren.ResetCamera() ren.ResetCameraClippingRange() renWin.Render() iren.Start()
def extrudeFromPoints(self): pts = self.pickerstyle.getPoints("in1_pipeline") if (pts.GetNumberOfPoints() < 3): qtw.QMessageBox.warning( self, "Warning", "At least 3 points must be defined on image 1 to create extrusion." ) return if (not self.in1_pipe.getIsValidForExtrusion()): qtw.QMessageBox.warning( self, "Warning", "Extrusion may not work properly when input file is not of type AIM." ) # Spline spline = vtk.vtkParametricSpline() spline.SetPoints(pts) spline.ClosedOn() parametricFunction = vtk.vtkParametricFunctionSource() parametricFunction.SetParametricFunction(spline) parametricFunction.Update() # Extrude extrusionFactor = 100.0 # mm above and below surface # A large number will cause the extrusion to fill the extent of the input image positiveExtruder = vtk.vtkLinearExtrusionFilter() positiveExtruder.SetInputConnection(parametricFunction.GetOutputPort()) positiveExtruder.SetExtrusionTypeToNormalExtrusion() positiveExtruder.SetVector(0, 0, 1) positiveExtruder.CappingOn() positiveExtruder.SetScaleFactor(extrusionFactor) posTriFilter = vtk.vtkTriangleFilter() posTriFilter.SetInputConnection(positiveExtruder.GetOutputPort()) negativeExtruder = vtk.vtkLinearExtrusionFilter() negativeExtruder.SetInputConnection(parametricFunction.GetOutputPort()) negativeExtruder.SetExtrusionTypeToNormalExtrusion() negativeExtruder.SetVector(0, 0, -1) negativeExtruder.CappingOn() negativeExtruder.SetScaleFactor(extrusionFactor) negTriFilter = vtk.vtkTriangleFilter() negTriFilter.SetInputConnection(negativeExtruder.GetOutputPort()) # Combine data combiner = vtk.vtkAppendPolyData() combiner.AddInputConnection(posTriFilter.GetOutputPort()) combiner.AddInputConnection(negTriFilter.GetOutputPort()) cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(combiner.GetOutputPort()) cleaner.Update() el_size_mm = self.in1_pipe.getElementSize() dim = self.in1_pipe.getDimensions() extent = self.in1_pipe.getExtent() origin = self.in1_pipe.getOrigin() foregroundValue = 127 backgroundValue = 0 # Stencil whiteImage = vtk.vtkImageData() whiteImage.SetSpacing(el_size_mm) whiteImage.SetDimensions(dim) whiteImage.SetExtent(extent) whiteImage.SetOrigin(origin) whiteImage.AllocateScalars(vtk.VTK_CHAR, 1) whiteImage.GetPointData().GetScalars().Fill(foregroundValue) # Use our extruded polydata to stencil the solid image poly2sten = vtk.vtkPolyDataToImageStencil() poly2sten.SetTolerance(0) #poly2sten.SetInputConnection(clipper.GetOutputPort()) poly2sten.SetInputConnection(cleaner.GetOutputPort()) poly2sten.SetOutputOrigin(origin) poly2sten.SetOutputSpacing(el_size_mm) poly2sten.SetOutputWholeExtent(whiteImage.GetExtent()) stencil = vtk.vtkImageStencil() stencil.SetInputData(whiteImage) stencil.SetStencilConnection(poly2sten.GetOutputPort()) #stencil.ReverseStencilOff() stencil.SetBackgroundValue(backgroundValue) stencil.Update() # Write image filename, _ = qtw.QFileDialog.getSaveFileName( self, "Select the file to save to…", qtc.QDir.homePath(), "AIM File (*.aim)") if (filename): writer = vtkbone.vtkboneAIMWriter() writer.SetInputConnection(stencil.GetOutputPort()) writer.SetFileName(filename) writer.SetProcessingLog( '!-------------------------------------------------------------------------------\n' + 'Written by blQtViewer.') writer.Update() self.statusBar().showMessage("File " + filename + " written.", 4000)
def AddStock(renderers, filename, name, zPosition): print("Adding", name) # Read the data PolyDataRead = vtk.vtkPolyDataReader() PolyDataRead.SetFileName(filename) PolyDataRead.Update() # Create the labels. TextSrc = vtk.vtkVectorText() TextSrc.SetText(name) numberOfPoints = PolyDataRead.GetOutput().GetNumberOfPoints() nameIndex = int((numberOfPoints - 1) * 0.8) nameLocation = PolyDataRead.GetOutput().GetPoint(nameIndex) x = nameLocation[0] * 0.15 y = nameLocation[1] + 5.0 z = zPosition RibbonFilter = vtk.vtkRibbonFilter() RibbonFilter.SetInputConnection(PolyDataRead.GetOutputPort()) RibbonFilter.VaryWidthOn() RibbonFilter.SetWidthFactor(5) RibbonFilter.SetDefaultNormal(0, 1, 0) RibbonFilter.UseDefaultNormalOn() Extrude = vtk.vtkLinearExtrusionFilter() Extrude.SetInputConnection(RibbonFilter.GetOutputPort()) Extrude.SetVector(0, 1, 0) Extrude.SetExtrusionType(1) Extrude.SetScaleFactor(0.7) Transform = vtk.vtkTransform() Transform.Translate(0, 0, zPosition) Transform.Scale(0.15, 1, 1) TransformFilter = vtk.vtkTransformPolyDataFilter() TransformFilter.SetInputConnection(Extrude.GetOutputPort()) TransformFilter.SetTransform(Transform) for r in range(0, len(renderers)): LabelMapper = vtk.vtkPolyDataMapper() LabelMapper.SetInputConnection(TextSrc.GetOutputPort()) LabelActor = vtk.vtkFollower() LabelActor.SetMapper(LabelMapper) LabelActor.SetPosition(x, y, z) LabelActor.SetScale(2, 2, 2) LabelActor.SetOrigin(TextSrc.GetOutput().GetCenter()) # Increment zPosition. zPosition += 8.0 StockMapper = vtk.vtkPolyDataMapper() StockMapper.SetInputConnection(TransformFilter.GetOutputPort()) StockMapper.SetScalarRange(0, 8000) StockActor = vtk.vtkActor() StockActor.SetMapper(StockMapper) renderers[r].AddActor(StockActor) renderers[r].AddActor(LabelActor) LabelActor.SetCamera(renderers[r].GetActiveCamera()) return zPosition
def text(txt, pos=(0, 0, 0), normal=(0, 0, 1), s=1, depth=0.1, c='k', alpha=1, bc=None, texture=None, followcam=False, cam=None): ''' Returns a vtkActor that shows a text in 3D. pos = position in 3D space if an integer is passed [1 -> 8], places text in a corner s = size of text depth = text thickness followcam = True, the text will auto-orient itself to it ''' if isinstance(pos, int): cornerAnnotation = vtk.vtkCornerAnnotation() cornerAnnotation.SetNonlinearFontScaleFactor(s / 3) cornerAnnotation.SetText(pos - 1, txt) cornerAnnotation.GetTextProperty().SetColor(vc.getColor(c)) return cornerAnnotation tt = vtk.vtkVectorText() tt.SetText(txt) tt.Update() ttmapper = vtk.vtkPolyDataMapper() if depth: extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputConnection(tt.GetOutputPort()) extrude.SetExtrusionTypeToVectorExtrusion() extrude.SetVector(0, 0, 1) extrude.SetScaleFactor(depth) ttmapper.SetInputConnection(extrude.GetOutputPort()) else: ttmapper.SetInputConnection(tt.GetOutputPort()) if followcam: #follow cam ttactor = vtk.vtkFollower() ttactor.SetCamera(cam) else: ttactor = vtk.vtkActor() ttactor.SetMapper(ttmapper) ttactor.GetProperty().SetColor(vc.getColor(c)) # check if color string contains a float, in this case ignore alpha al = vc.getAlpha(c) if al: alpha = al ttactor.GetProperty().SetOpacity(alpha) nax = np.linalg.norm(normal) if nax: normal = np.array(normal) / nax theta = np.arccos(normal[2]) phi = np.arctan2(normal[1], normal[0]) ttactor.SetScale(s, s, s) ttactor.RotateZ(phi * 57.3) ttactor.RotateY(theta * 57.3) ttactor.SetPosition(pos) if bc: # defines a specific color for the backface backProp = vtk.vtkProperty() backProp.SetDiffuseColor(vc.getColor(bc)) backProp.SetOpacity(alpha) ttactor.SetBackfaceProperty(backProp) if texture: vu.assignTexture(ttactor, texture) vu.assignConvenienceMethods(ttactor, None) vu.assignPhysicsMethods(ttactor) return ttactor
def main(): colors = vtk.vtkNamedColors() angle = 0 r1 = 50 r2 = 30 centerX = 10.0 centerY = 5.0 points = vtk.vtkPoints() idx = 0 while angle <= 2.0 * vtk.vtkMath.Pi() + (vtk.vtkMath.Pi() / 60.0): points.InsertNextPoint(r1 * math.cos(angle) + centerX, r2 * math.sin(angle) + centerY, 0.0) angle = angle + (vtk.vtkMath.Pi() / 60.0) idx += 1 line = vtk.vtkPolyLine() line.GetPointIds().SetNumberOfIds(idx) for i in range(0, idx): line.GetPointIds().SetId(i, i) lines = vtk.vtkCellArray() lines.InsertNextCell(line) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetLines(lines) polyData.SetPolys(lines) # Adds cap extrude = vtk.vtkLinearExtrusionFilter() extrude.SetInputData(polyData) extrude.SetExtrusionTypeToNormalExtrusion() extrude.SetVector(0, 0, 100.0) extrude.SetCapping(True) #extrude.SetCapping(False) extrude.Update() lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputData(polyData) lineActor = vtk.vtkActor() lineActor.SetMapper(lineMapper) lineActor.GetProperty().SetColor(colors.GetColor3d("Peacock")) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(extrude.GetOutputPort()) back = vtk.vtkProperty() back.SetColor(colors.GetColor3d("Tomato")) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d("Banana")) #actor.SetBackfaceProperty(back) ren = vtk.vtkRenderer() ren.SetBackground(colors.GetColor3d("SlateGray")) ren.AddActor(actor) #ren.AddActor(lineActor) renWin = vtk.vtkRenderWindow() renWin.SetWindowName("EllipticalCylinder") renWin.AddRenderer(ren) renWin.SetSize(600, 600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(style) camera = vtk.vtkCamera() camera.SetPosition(0, 1, 0) camera.SetFocalPoint(0, 0, 0) camera.SetViewUp(0, 0, 1) camera.Azimuth(30) camera.Elevation(30) ren.SetActiveCamera(camera) ren.ResetCamera() ren.ResetCameraClippingRange() renWin.Render() iren.Start()
def make_patterned_polydata(inputContours, fillareastyle=None, fillareaindex=None, fillareacolors=None, fillareaopacity=None, size=None): if inputContours is None or fillareastyle == 'solid': return None if inputContours.GetNumberOfCells() == 0: return None if fillareaindex is None: fillareaindex = 1 if fillareaopacity is None: fillareaopacity = 100 num_pixels = num_pixels_for_size(size) # Create the plane that will be textured with the pattern # The bounds of the plane match the bounds of the input polydata bounds = inputContours.GetBounds() patternPlane = vtk.vtkPlaneSource() patternPlane.SetOrigin(bounds[0], bounds[2], 0.0) patternPlane.SetPoint1(bounds[0], bounds[3], 0.0) patternPlane.SetPoint2(bounds[1], bounds[2], 0.0) # Generate texture coordinates for the plane textureMap = vtk.vtkTextureMapToPlane() textureMap.SetInputConnection(patternPlane.GetOutputPort()) # Create the pattern image of the size of the input polydata # and type defined by fillareaindex xBounds = bounds[1] - bounds[0] yBounds = bounds[3] - bounds[2] if xBounds <= 1 and yBounds <= 1 and size is not None: xBounds *= size[0] yBounds *= size[1] xres, yres = int(xBounds), int(yBounds) xres = int(4.0 * xBounds) yres = int(4.0 * yBounds) # Handle the case when the bounds are less than 1 in physical dimensions patternImage = create_pattern(xres, yres, num_pixels, fillareastyle, fillareaindex, fillareacolors, fillareaopacity) if patternImage is None: return None # Extrude the contour since vtkPolyDataToImageStencil # requires 3D polydata extruder = vtk.vtkLinearExtrusionFilter() extruder.SetInputData(inputContours) extruder.SetScaleFactor(1.0) extruder.SetVector(0, 0, 1) extruder.SetExtrusionTypeToNormalExtrusion() # Create a binary image mask from the extruded polydata pol2stenc = vtk.vtkPolyDataToImageStencil() pol2stenc.SetTolerance(0) pol2stenc.SetInputConnection(extruder.GetOutputPort()) pol2stenc.SetOutputOrigin(bounds[0], bounds[2], 0.0) pol2stenc.SetOutputSpacing((bounds[1] - bounds[0]) / xres, (bounds[3] - bounds[2]) / yres, 0.0) pol2stenc.SetOutputWholeExtent(patternImage.GetExtent()) # Stencil out the fillarea from the pattern image stenc = vtk.vtkImageStencil() stenc.SetInputData(patternImage) stenc.SetStencilConnection(pol2stenc.GetOutputPort()) stenc.ReverseStencilOff() stenc.SetBackgroundColor(0, 0, 0, 0) stenc.Update() patternImage = stenc.GetOutput() # Create the texture using the stenciled pattern patternTexture = vtk.vtkTexture() patternTexture.SetInputData(patternImage) patternTexture.InterpolateOn() patternTexture.RepeatOn() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(textureMap.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.SetTexture(patternTexture) return actor