def Create_Topo(Slope,Plane): ugrid = vtk.vtkUnstructuredGrid() gridreader=vtk.vtkUnstructuredGridReader() gridreader.SetFileName(Slope) gridreader.Update() ugrid = gridreader.GetOutput() GeomFilt1 = vtk.vtkGeometryFilter() GeomFilt1.SetInput(ugrid) GeomFilt1.Update() x = GeomFilt1.GetOutput() u = vtk.vtkUnstructuredGrid() bgridreader=vtk.vtkXMLUnstructuredGridReader() bgridreader.SetFileName(Plane) bgridreader.Update() u = bgridreader.GetOutput() GeomFilt2 = vtk.vtkGeometryFilter() GeomFilt2.SetInput(u) GeomFilt2.Update() y = GeomFilt2.GetOutput() append = vtk.vtkAppendPolyData() append.AddInput(x) append.AddInput(y) data = append.GetOutput() d = vtk.vtkDelaunay3D() d.SetInput(data) d.Update d.BoundingTriangulationOff() d.SetTolerance(0.00001) d.SetAlpha(0) d.Update() z = d.GetOutput() return z
def appendfilter(polydatas): """Append list of polydata objects.""" appender = vtk.vtkAppendPolyData() for polydata in polydatas: appender.AddInput(polydata) appender.Update() return appender.GetOutput()
def merge_polydata(pds): f = vtk.vtkAppendPolyData() for pd in pds: f.AddInput(pd) f.Update() return f.GetOutput()
def CreateCrossSections(files, outputAreas, outputGeometryFile, outputOutlineFile): areaFile = open(outputAreas, 'w') planeAppender = vtk.vtkAppendPolyData() outlineAppender = vtk.vtkAppendPolyData() for idx in range(len(files)): print 'Processing contour %d' % idx file = files[idx] (plane, outline) = CreatePlanarCrossSectionPolyDataFromFile(file) areaFile.write(str(ComputePolyDataArea(plane))) areaFile.write('\n') planeAppender.AddInputData(plane) outlineAppender.AddInputData(outline) planeWriter = vtk.vtkXMLPolyDataWriter() planeWriter.SetFileName(outputGeometryFile) planeWriter.SetInputConnection(planeAppender.GetOutputPort()) planeWriter.Update() outlineWriter = vtk.vtkXMLPolyDataWriter() outlineWriter.SetFileName(outputOutlineFile) outlineWriter.SetInputConnection(outlineAppender.GetOutputPort()) outlineWriter.Update() areaFile.close()
def CreatePlanarCrossSectionPolyDataFromFile(file): with open(file, 'r') as f: read_data = f.read() tokens = string.split(read_data) offset = 2 planeAppender = vtk.vtkAppendPolyData() outlineAppender = vtk.vtkAppendPolyData() # Iterate over separate pieces in the file while True: if (offset >= len(tokens)): break pointsInPiece = int(tokens[offset]) newPoints = vtk.vtkPoints() newPoints.SetNumberOfPoints(pointsInPiece) for ptId in xrange(pointsInPiece): x = float(tokens[ptId*3 + 0 + offset + 1]) y = float(tokens[ptId*3 + 1 + offset + 1]) z = float(tokens[ptId*3 + 2 + offset + 1]) newPoints.SetPoint(ptId, x, y, z) offset = offset + 3*pointsInPiece + 1 polygon = vtk.vtkPolyData() polygon.SetPoints(newPoints) polygon.Allocate(pointsInPiece) polygon.InsertNextCell(vtk.VTK_POLYGON, pointsInPiece, range(pointsInPiece)) triFilter = vtk.vtkTriangleFilter() triFilter.SetInputData(polygon) planeAppender.AddInputConnection(triFilter.GetOutputPort()) outline = vtk.vtkPolyData() outline.SetPoints(newPoints) outline.Allocate(pointsInPiece) outline.InsertNextCell(vtk.VTK_POLY_LINE, pointsInPiece, range(pointsInPiece)) outlineAppender.AddInputData(outline) planeAppender.Update() outlineAppender.Update() return (planeAppender.GetOutput(), outlineAppender.GetOutput())
def Merge5 (): reader = vtk.vtkPolyDataReader() reader.SetFileName('test10.vtk') reader2 = vtk.vtkPolyDataReader() reader2.SetFileName('test12.vtk') reader3 = vtk.vtkPolyDataReader() reader3.SetFileName('test13.vtk') app = vtk.vtkAppendPolyData() app.AddInputConnection(reader.GetOutputPort()) tr = vtk.vtkTransform() tr.Translate(-50.916666, -1.083333, 0) tr.RotateZ(90) tp = vtk.vtkTransformPolyDataFilter() tp.SetTransform(tr) tp.SetInputConnection(reader2.GetOutputPort()) app.AddInputConnection(tp.GetOutputPort()) tr2 = vtk.vtkTransform() tr2.Translate(-50.916666, -1.083333, 0) tp2 = vtk.vtkTransformPolyDataFilter() tp2.SetTransform(tr2) tp2.SetInputConnection(reader3.GetOutputPort()) app.AddInputConnection(tp2.GetOutputPort()) return app
def __init__(self): # Creates a cube image of height 0, thus creating a plane. cube = vtk.vtkCubeSource() cube.SetXLength(120) cube.SetYLength(120) cube.SetZLength(0) #cubeTransform = vtk.vtkTransform() #cubeTransform.Translate(0, 0, 0) cubeMapper = vtk.vtkPolyDataMapper() cubeMapper.SetInputConnection(cube.GetOutputPort()) cubeTransformFilter = vtk.vtkTransformPolyDataFilter() cubeTransformFilter.SetInputConnection(cube.GetOutputPort()) #cubeTransformFilter.SetTransform(cubeTransform) appendFilter = vtk.vtkAppendPolyData() #appendFilter.AddInputConnection(line.GetOutputPort()) appendFilter.AddInputConnection(cubeTransformFilter.GetOutputPort()) # gets the location of the tablet self.x = GlobalVariables.imageXDist/2.0 # @UndefinedVariable self.y = GlobalVariables.imageYDist/2.0 # @UndefinedVariable self.z = GlobalVariables.imageZDist/2.0 # @UndefinedVariable # moves the cube actor which is what moves the cursor self.cubeActor = vtk.vtkActor() self.cubeActor.SetMapper(cubeMapper) self.cubeActor.GetProperty().SetColor(0.2, 0.6, 0.8) self.cubeActor.SetPosition(self.x,self.y,self.z)#(self.sampleSpacing[0]/2,self.sampleSpacing[1]/2,self.sampleSpacing[2]/2)#(-30, -30, -150) #(70,90,50)
def __init__(self, slice3dVWRThingy, sliceGrid): self.slice3dVWR = slice3dVWRThingy self._grid = sliceGrid self._sliceDirectionsDict = {} # this same picker is used on all new IPWS of all sliceDirections self.ipwPicker = vtk.vtkCellPicker() self.currentCursor = None # configure the grid from scratch self._initialiseGrid() self._initUI() # bind all events self._bindEvents() # fill out our drop-down menu self._disableMenuItems = self._appendGridCommandsToMenu( self.slice3dVWR.controlFrame.slicesMenu, self.slice3dVWR.controlFrame, disable=True) self.overlayMode = 'greenOpacityRange' self.fusionAlpha = 0.4 # this will make all ipw slice polydata available at the output self.ipwAppendPolyData = vtk.vtkAppendPolyData() # this append filter will make all slice data available at the output self.ipwAppendFilter = vtk.vtkAppendFilter() # create the first slice self._createSlice('Axial')
def __init__(self): # Creates a cube image of height 0, thus creating a plane. cube = vtk.vtkCubeSource() cube.SetXLength(120) cube.SetYLength(120) cube.SetZLength(0) #cubeTransform = vtk.vtkTransform() #cubeTransform.Translate(0, 0, 0) cubeMapper = vtk.vtkPolyDataMapper() cubeMapper.SetInputConnection(cube.GetOutputPort()) cubeTransformFilter = vtk.vtkTransformPolyDataFilter() cubeTransformFilter.SetInputConnection(cube.GetOutputPort()) #cubeTransformFilter.SetTransform(cubeTransform) appendFilter = vtk.vtkAppendPolyData() #appendFilter.AddInputConnection(line.GetOutputPort()) appendFilter.AddInputConnection(cubeTransformFilter.GetOutputPort()) # gets the location of the tablet self.x = GlobalVariables.imageXDist / 2.0 # @UndefinedVariable self.y = GlobalVariables.imageYDist / 2.0 # @UndefinedVariable self.z = GlobalVariables.imageZDist / 2.0 # @UndefinedVariable # moves the cube actor which is what moves the cursor self.cubeActor = vtk.vtkActor() self.cubeActor.SetMapper(cubeMapper) self.cubeActor.GetProperty().SetColor(0.2, 0.6, 0.8) self.cubeActor.SetPosition( self.x, self.y, self.z ) #(self.sampleSpacing[0]/2,self.sampleSpacing[1]/2,self.sampleSpacing[2]/2)#(-30, -30, -150) #(70,90,50)
def treeTable2Mesh(self, tableNode): # convert tree table to mesh representation # each airway segment is visualized as a cylinder # label values for labled branches are assigned mainBranchLabels = [ 'Trachea', 'LMB', 'RMB', 'CrRMB', 'MiRMB', 'CaRMB', 'AcRMB' ] appendFilter = vtk.vtkAppendPolyData() table = tableNode.GetTable() for row in range(table.GetNumberOfRows()): radius = table.GetValueByName(row, 'radius').ToFloat() height = table.GetValueByName(row, 'length').ToFloat() branchName = table.GetValueByName(row, 'name').ToString() centroid = [ table.GetValueByName(row, 'centroidX').ToFloat(), table.GetValueByName(row, 'centroidY').ToFloat(), table.GetValueByName(row, 'centroidZ').ToFloat() ] direction = [ table.GetValueByName(row, 'directionX').ToFloat(), table.GetValueByName(row, 'directionY').ToFloat(), table.GetValueByName(row, 'directionZ').ToFloat() ] polyData = self.createCylinderMesh(centroid, direction, radius, height) if polyData: branchLabel = mainBranchLabels.index( branchName) + 1 if branchName in mainBranchLabels else 0 self.setPolyDataScalarValue(polyData, branchLabel, 'BranchLabel') appendFilter.AddInputDataObject(polyData) appendFilter.Update() return appendFilter.GetOutputDataObject(0)
def merge_models(self, modelA, modelB, modelC): scene = slicer.mrmlScene # Create model node mergedModel = slicer.vtkMRMLModelNode() mergedModel.SetScene(scene) mergedModel.SetName(modelName) dnode = slicer.vtkMRMLModelDisplayNode() snode = slicer.vtkMRMLModelStorageNode() mergedModel.SetAndObserveDisplayNodeID(dnode.GetID()) mergedModel.SetAndObserveStorageNodeID(snode.GetID()) scene.AddNode(dnode) scene.AddNode(snode) scene.AddNode(mergedModel) # Get transformed poly data from input models modelA_polydata = self.getTransformedPolyDataFromModel(self.modelA) modelB_polydata = self.getTransformedPolyDataFromModel(self.modelB) modelC_polydata = self.getTransformedPolyDataFromModel(self.modelC) # Append poly data appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputData(modelA_polydata) appendFilter.AddInputData(modelB_polydata) appendFilter.AddInputData(modelC_polydata) appendFilter.Update(); # Output mergedModel.SetAndObservePolyData(appendFilter.GetOutput()); mergedModel.SetAndObserveDisplayNodeID(dnode.GetID()); return mergedModel
def areaMeasurementsTable2Mesh(self, tableNode): # convert a measurements table to a mesh representation # the table node is assumed to contain columns: # (volume, mean, centroidX, centroidY, centroidZ) table = tableNode.GetTable() requiredColumns = set( ['area', 'mean', 'centroidX', 'centroidY', 'centroidZ']) tableColumns = set([ table.GetColumnName(i) for i in range(table.GetNumberOfColumns()) ]) if not requiredColumns.issubset( set(tableColumns)): # not a valid measurements table return vtk.vtkPolyData() appendFilter = vtk.vtkAppendPolyData() for row in range(table.GetNumberOfRows()): area = table.GetValueByName(row, 'area').ToFloat() radius = pow(area / (4.0 * math.pi), 1.0 / 2.0) mean = table.GetValueByName(row, 'mean').ToFloat() centroid = [ table.GetValueByName(row, 'centroidX').ToFloat(), table.GetValueByName(row, 'centroidY').ToFloat(), table.GetValueByName(row, 'centroidZ').ToFloat() ] polyData = self.sphereMesh(centroid, radius) self.setPolyDataScalarValue(polyData, mean, 'MeasurementMean') appendFilter.AddInputDataObject(polyData) appendFilter.Update() return appendFilter.GetOutputDataObject(0)
def __init__(self): super(SmartLock, self).__init__() self.setup() self.DEFAULT_DIR_KEY = __file__ self.segServer = SegmentationService(self) self.regServer = RegistrationService(self) self.usOverlayActor = None # Overlay self.usCorrectedActor = None # Corrected contours in 3D # Append all surfaces to this self.appendFilter = vtk.vtkAppendPolyData() # Single transform self.alignment = vtk.vtkTransform() #self.alignment.PostMultiply() # Do we need PostMultiply??? # Experiment with 2 transforms self.registration = vtk.vtkTransform() self.alignment.SetInput(self.registration) # Callback for displaying registration self.regServer.ready.connect(self.updateRegistration) # Callback for displaying segmentation self.segServer.ready.connect(self.updateSegmentation) self.btnReg.setEnabled(False) self.btnSeg.setEnabled(True)
def createActorTubes(self, elements): source = vtk.vtkAppendPolyData() mapper = vtk.vtkPolyDataMapper() actor = vtk.vtkActor() for element in elements: cross_section = element.cross_section if cross_section and self.plotRadius: polygon = self.createSectionPolygon(element) else: if self.defaultRadius is None: base_length = self.project.preprocessor.structure_principal_diagonal if element.length / 10 > base_length / 1000: self.defaultRadius = element.length / 10 else: self.defaultRadius = base_length / 1000 polygon = vtk.vtkRegularPolygonSource() polygon.SetRadius(self.defaultRadius) polygon.SetNumberOfSides(20) tube = self.generalSectionTube(element, polygon.GetOutputPort()) source.AddInputData(tube.GetOutput()) mapper.SetInputConnection(source.GetOutputPort()) actor.SetMapper(mapper) return actor
def main(opts, args): appender = vtk.vtkAppendPolyData() for f in args: o = nu.readVTK(f) appender.AddInput(o) appender.Update() nu.writeVTK(opts.output, appender.GetOutput())
def combine_polydata(*args): """ References: - https://www.vtk.org/Wiki/VTK/Examples/Python/Filtering/CombinePolyData """ # Append the two meshes append_filter = vtk.vtkAppendPolyData() #if vtk.VTK_MAJOR_VERSION <= 5: # append_filter.AddInputConnection(vtk_polydata_1.GetProducerPort()) # append_filter.AddInputConnection(vtk_polydata_2.GetProducerPort()) #else: # append_filter.AddInputData(vtk_polydata_1) # append_filter.AddInputData(vtk_polydata_2) for arg in args: if isinstance(arg, vtk.vtkPolyData): append_filter.AddInputData(arg) if isinstance(arg, list): for i in arg: append_filter.AddInputData(i) append_filter.Update() clean_filter = vtk.vtkCleanPolyData() clean_filter.SetInputConnection(append_filter.GetOutputPort()) clean_filter.Update() return clean_filter
def __build_actor(self): """ Function to plot the circle """ r = self.radius t = 0 self.posc_a = 0 self.posc_b = 0 self.segment = vtk.vtkAppendPolyData() self.xa = self.posc_a + r * cos(t) self.ya = self.posc_a + r * sin(t) while(t <= 2 * pi): self.GenerateCicleSegment(t) t = t + 0.05 self.GenerateCicleSegment(0) self.mapper.SetInputConnection(self.segment.GetOutputPort()) self.actor.SetMapper(self.mapper) self.actor.PickableOff()
def appendPolyData(polyDataList): assert len(polyDataList) append = vtk.vtkAppendPolyData() for polyData in polyDataList: append.AddInput(polyData) append.Update() return shallowCopy(append.GetOutput())
def extract(self): ''' Get points from ui, call line_query and plot data on matplotlib canvas ''' if not hasattr(self,'vtu_output'): return p1 = [self.ui.point1_x_coord.value(), self.ui.point1_y_coord.value(), self.ui.point1_z_coord.value()] p2 = [self.ui.point2_x_coord.value(), self.ui.point2_y_coord.value(), self.ui.point2_z_coord.value()] self.q = line_query(self.vtu_output,p1,p2,self.ui.extract_interval.value(),self.component) self.x = range(self.q.shape[0]) self.ui.figure.clear() # print(self.x,self.q) ax = self.ui.figure.add_subplot(111) ax.scatter(self.x,self.q[:,-1]) ax.set_ylabel("%s (MPa)"%self.component) ax.set_xlabel("Point number") ax.grid(b=True, which='major', color='#666666', linestyle='-') ax.minorticks_on() ax.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) self.ui.figure.tight_layout() self.ui.canvas.draw() #remove any line actor currently present if hasattr(self,'line_actor'): self.ren.RemoveActor(self.line_actor) self.ui.vtkWidget.update() #draw a line on the interactor line = vtk.vtkLineSource() line.SetResolution(self.ui.extract_interval.value()) line.SetPoint1(p1) line.SetPoint2(p2) line.Update() sphere1 = vtk.vtkSphereSource() sphere1.SetCenter(p1) sphere1.Update() sphere2 = vtk.vtkSphereSource() sphere2.SetCenter(p2) sphere2.Update() appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputData(sphere1.GetOutput()) appendFilter.AddInputData(line.GetOutput()) appendFilter.AddInputData(sphere2.GetOutput()) appendFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(appendFilter.GetOutput()) self.line_actor = vtk.vtkActor() self.line_actor.SetMapper(mapper) colors = vtk.vtkNamedColors() self.line_actor.GetProperty().SetColor(colors.GetColor3d("Violet")) self.ren.AddActor(self.line_actor) self.ui.export_line_button.setEnabled(True) self.ui.vtkWidget.update()
def makeCylinderPtsVTP(locXYZ,radius=50,height=50,res=10): # Load the file if type(locXYZ) == np.ndarray: loc = locXYZ elif type(locXYZ) == str: loc = np.genfromtxt(locXYZ) # Make append poly filter appPoly = vtk.vtkAppendPolyData() # Loop through all the locations for pt in loc[:,0:3]: # Make the cylinters cyl = vtk.vtkCylinderSource() cyl.SetCenter(pt) cyl.SetRadius(radius) cyl.SetHeight(height) cyl.SetResolution(res) # Rotate to be vertical rot = vtk.vtkTransform() rot.Translate(-pt) rot.PostMultiply() rot.RotateX(90) rot.Translate(pt) tranFor = vtk.vtkTransformPolyDataFilter() tranFor.SetInputConnection(cyl.GetOutputPort()) tranFor.SetTransform(rot) tranFor.Update() # Append appPoly.AddInputConnection(tranFor.GetOutputPort()) # Update and return. appPoly.Update() return appPoly.GetOutput()
def capsurface(polydata, arrayname=''): """Cap holes in surface with a flat cover.""" # generates a flat cover for a convex hole defined by edges fedges = extractboundaryedge(polydata) # find each connected edge connect = vtk.vtkPolyDataConnectivityFilter() connect.SetInput(fedges) connect.Update() ncontours = connect.GetNumberOfExtractedRegions() append = vtk.vtkAppendPolyData() append.AddInput(polydata) # generate each flat cover for i in range(ncontours): connect.AddSpecifiedRegion(i) connect.SetExtractionModeToSpecifiedRegions() connect.Update() edges = connect.GetOutput() cover = vtk.vtkPolyData() generatecover(edges, cover, arrayname) # append to original polydata append.AddInput(cover) connect.DeleteSpecifiedRegion(i) append.Update() outsurface = cleanpolydata(append.GetOutput()) return outsurface
def __init__(self): super(SmartLock, self).__init__() self.setup() self.DEFAULT_DIR_KEY = __file__ self.segServer = SegmentationService(self) self.regServer = RegistrationService(self) self.usActor = None # Used for overlay self.usCorrectedActor = None self.lastUSContours = None self.vessel = None # Update this when load interior and exterior self.CTContours = None # Append all surfaces to this self.appendFilter = vtk.vtkAppendPolyData() # TODO: Remove this self.alignment = vtk.vtkTransform() self.alignment.PostMultiply() self.misAlignment = vtk.vtkTransform() self.misAlignment.PostMultiply() self.regAlignment = vtk.vtkTransform() self.regAlignment.PostMultiply() self.alignment.Concatenate(self.misAlignment) self.alignment.Concatenate(self.regAlignment)
def __init__(self, amt, radius): Model.__init__(self) self.source = vtk.vtkAppendPolyData() for i in range(amt): opX = 1.0 opY = 1.0 opZ = 1.0 if random() > 0.5: opX *= -1.0 if random() > 0.5: opY *= -1.0 if random() > 0.5: opZ *= -1.0 sRad = 0.25 + ( random() * 0.25 ) x = float(random() * radius) * opX y = float(random() * radius) * opY z = float(random() * radius) * opZ s = vtk.vtkSphereSource() s.SetCenter(x,y,z) s.SetRadius(float(sRad)) s.Update() self.source.AddInput(s.GetOutput()) #add center s = vtk.vtkSphereSource() s.SetCenter(0.0, 0.0, 0.0) s.SetRadius(0.5) s.Update() self.source.AddInput(s.GetOutput()) self.Update()
def __init__(self, geom, ident=None): self.src = vtkAppendPolyData() ODE_Object.__init__(self, geom, ident) (radius, height) = geom.getParams() cylinder = vtkCylinderSource() cylinder.SetResolution(20) cylinder.SetRadius(radius) cylinder.SetHeight(height) sphere_1 = vtkSphereSource() sphere_1.SetThetaResolution(20) sphere_1.SetPhiResolution(11) sphere_1.SetRadius(radius) sphere_1.SetCenter(0, 0.5 * height, 0) sphere_2 = vtkSphereSource() sphere_2.SetThetaResolution(20) sphere_2.SetPhiResolution(11) sphere_2.SetRadius(radius) sphere_2.SetCenter(0, -0.5 * height, 0) self.src.AddInput(cylinder.GetOutput()) self.src.AddInput(sphere_1.GetOutput()) self.src.AddInput(sphere_2.GetOutput())
def df_to_vtp(df, output_path): append = vtk.vtkAppendPolyData() for index, row in df.iterrows(): cube = vtk.vtkCubeSource() xcom = 0.5 * (row.xmax + row.xmin) ycom = 0.5 * (row.ymax + row.ymin) zcom = 0.5 * (row.zmax + row.zmin) xsize = row.xmax - row.xmin ysize = row.ymax - row.ymin zsize = row.zmax - row.zmin cube.SetCenter(xcom, ycom, zcom) cube.SetXLength(xsize) cube.SetYLength(ysize) cube.SetZLength(zsize) cube.Update() append.AddInput(cube.GetOutput()) append.Update() writer = vtk.vtkXMLPolyDataWriter() writer.SetInput(append.GetOutput()) writer.SetFileName(output_path) writer.Write()
def get_cell_locator(self): ''' Get a vtkCellLocator object used for ray casting. Returns: vtk.vtkCellLocator : VTK cell locator. ''' # Don't return anything if we have no enabled geometry if len(self.get_enabled_features()) == 0: return None if self.cell_locator is None: appender = vtk.vtkAppendPolyData() for fname in self.get_enabled_features(): appender.AddInputData(self.features[fname].get_polydata()) appender.Update() self.cell_locator = vtk.vtkCellLocator() self.cell_locator.SetTolerance(1e-6) self.cell_locator.SetDataSet(appender.GetOutput()) self.cell_locator.BuildLocator() return self.cell_locator
def getPolyData(self): # VRML importer importer = vtk.vtkVRMLImporter() # WRL file to upload importer.SetFileName(self.filepath) # Read data importer.Read() self.polydata = vtk.vtkPolyData() append = vtk.vtkAppendPolyData() renActors = importer.GetRenderer().GetActors() renActors.InitTraversal() actor = renActors.GetNextActor() i = 0 while (actor != None): actor.GetProperty().SetAmbientColor(i, 1 - i, 0.0) actor.GetProperty().SetAmbient(1) append.AddInputData(actor.GetMapper().GetInput()) actor = renActors.GetNextActor() i += 0.05 append.Update() self.polydata.DeepCopy(append.GetOutput()) return self.polydata
def main(args): img_fn_array, L_root = [], [] normpath = os.path.normpath("/".join([args.dir_root, '**', '*'])) for img_fn in glob.iglob(normpath, recursive=True): if os.path.isfile(img_fn) and True in [ ext in img_fn for ext in [".vtk"] ]: img_obj = {} L_root.append(img_fn) img_obj["root"] = L_root img_obj["surf"] = args.surf img_obj["out"] = args.out img_fn_array.append(img_obj) for img_obj in img_fn_array: surf = img_obj["surf"] root = img_obj["root"] out = img_obj["out"] surf = ReadFile(surf) merge = vtk.vtkAppendPolyData() merge.AddInputData(surf) for i in range(len(root)): root_canal = ReadFile(root[i]) root_canal = AssignLabelToRoots(root_canal, surf, args.label_name) root_canal.GetPointData().SetActiveScalars(args.label_name) merge.AddInputData(root_canal) merge.Update() Write(merge.GetOutput(), out)
def sphere(resolution=3, size=1): grid = vtk.vtkAppendPolyData() # add the center to the mesh center = vtk.vtkPolyData() center.SetPoints(vtk.vtkPoints()) center.GetPoints().InsertNextPoint(0, 0, 0) grid.AddInput(center) # add spheres of increasing complexity subdivisions = 0 radius = 0 for i in range(resolution - 1): radius += float(size) / float(resolution - 1) sphere = nice_sphere(radius / 2.0, subdivisions) grid.AddInput(sphere) subdivisions += 1 cleaner = vtk.vtkCleanPolyData() cleaner.SetInput(grid.GetOutput()) mesh = vtk.vtkDelaunay3D() mesh.SetInput(cleaner.GetOutput()) return mesh
def calc_points(start, end, number_of_points): """Take start and end points of a line, write the start point up to but not include the end point as polydata according to number_of_points""" gaps = number_of_points - 1 if gaps == 0 or gaps == -1: gaps = 3 print("number of gaps", gaps) lon_gap = abs(float(start[0] - end[0]) / gaps) lat_gap = abs(float(start[1] - end[1]) / gaps) if start[1] > end[1]: # to ensure the direction of a line is correct lat_gap = -lat_gap if start[0] > end[0]: lon_gap = -lon_gap print("long gap", lon_gap, "lat gap", lat_gap) appender = vtk.vtkAppendPolyData() points, vertices, zvalues = create_poly() i = 0 while i < (number_of_points - 1): x, y = start insert_value(points, vertices, zvalues, x, y, 0.) start = (start[0] + lon_gap, start[1] + lat_gap) i += 1 poly_data = set_poly(points, vertices, zvalues) appender.AddInputData(poly_data) appender.Update() appender_data = appender.GetOutput() return appender_data
def loadDolfin(filename, exterior=False): """Reads a `Fenics/Dolfin` file format (.xml or .xdmf). Return an ``Actor(vtkActor)`` object.""" import sys if sys.version_info[0] < 3: return _loadDolfin_old(filename) import dolfin if filename.lower().endswith('.xdmf'): f = dolfin.XDMFFile(filename) m = dolfin.Mesh() f.read(m) else: m = dolfin.Mesh(filename) bm = dolfin.BoundaryMesh(m, "exterior") if exterior: poly = utils.buildPolyData(bm.coordinates(), bm.cells(), fast=True) else: polyb = utils.buildPolyData(bm.coordinates(), bm.cells(), fast=True) polym = utils.buildPolyData(m.coordinates(), m.cells(), fast=True) app = vtk.vtkAppendPolyData() app.AddInputData(polym) app.AddInputData(polyb) app.Update() poly = app.GetOutput() return Actor(poly).lw(0.1)
def BooleanAdd(self, mesh, inplace=False): """ Add a mesh to the current mesh. Parameters ---------- mesh : vtkInterface.PolyData The mesh to add. inplace : bool, optional Updates mesh in-place while returning nothing. Returns ------- joinedmesh : vtkInterface.PolyData Initial mesh and the new mesh when inplace=False. """ vtkappend = vtk.vtkAppendPolyData() vtkappend.AddInputData(self) vtkappend.AddInputData(mesh) vtkappend.Update() if inplace: self.Overwrite(vtkappend.GetOutput()) else: return PolyData(vtkappend.GetOutput())
def _draw_line(self): line1 = vtk.vtkLineSource() line1.SetPoint1(self.points[0]) line1.SetPoint2(self.points[1]) line2 = vtk.vtkLineSource() line2.SetPoint1(self.points[1]) line2.SetPoint2(self.points[2]) arc = self.DrawArc() line = vtk.vtkAppendPolyData() line.AddInput(line1.GetOutput()) line.AddInput(line2.GetOutput()) line.AddInput(arc.GetOutput()) c = vtk.vtkCoordinate() c.SetCoordinateSystemToWorld() m = vtk.vtkPolyDataMapper2D() m.SetInputConnection(line.GetOutputPort()) m.SetTransformCoordinate(c) a = vtk.vtkActor2D() a.SetMapper(m) a.GetProperty().SetColor(self.colour) self.line_actor = a
def assemble_neuron(neuron_num): print(f"Processing neuron {neuron_num}") files = glob.glob("meshes-with-axons-filled/*_n%03d.vtp" % neuron_num) out_filename = "meshes-with-axons-filled-assembled/n%02d.vtp" % neuron_num appendFilter = vtk.vtkAppendPolyData() for file in files: _, basename = os.path.split(file) x, y, z = int(basename[1]), int(basename[3]), int(basename[5]) print(x, y, z) # Prepare to read the file. readerVolume = vtk.vtkXMLPolyDataReader() readerVolume.SetFileName(file) readerVolume.Update() # Set up the transform filter translation = vtk.vtkTransform() translation.Translate(x * 1023.0, y * 1023.0, z * 1023.0 * 2.49) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetInputConnection(readerVolume.GetOutputPort()) transformFilter.SetTransform(translation) transformFilter.Update() appendFilter.AddInputData(transformFilter.GetOutput()) appendFilter.Update() writer = vtk.vtkXMLDataSetWriter() writer.SetFileName(out_filename) writer.SetInputData(appendFilter.GetOutput()) writer.Write()
def _draw_line(self): line1 = vtk.vtkLineSource() line1.SetPoint1(self.points[0]) line1.SetPoint2(self.points[1]) line2 = vtk.vtkLineSource() line2.SetPoint1(self.points[1]) line2.SetPoint2(self.points[2]) arc = self.DrawArc() line = vtk.vtkAppendPolyData() line.AddInputConnection(line1.GetOutputPort()) line.AddInputConnection(line2.GetOutputPort()) line.AddInputConnection(arc.GetOutputPort()) c = vtk.vtkCoordinate() c.SetCoordinateSystemToWorld() m = vtk.vtkPolyDataMapper2D() m.SetInputConnection(line.GetOutputPort()) m.SetTransformCoordinate(c) a = vtk.vtkActor2D() a.SetMapper(m) a.GetProperty().SetColor(self.colour) self.line_actor = a
def grid_create( arg_grid_delta, arg_grid_color, arg_grid_width, arg_projection, arg_ratioxy): gridpolydata=vtk.vtkAppendPolyData() for i in range(0,int(90*arg_ratioxy),int(arg_grid_delta*arg_ratioxy)) : latpolydata=latitude_create(i,arg_projection) gridpolydata.AddInputData(latpolydata) for i in range(0,int(-90*arg_ratioxy),int(-arg_grid_delta*arg_ratioxy)) : latpolydata=latitude_create(i,arg_projection) gridpolydata.AddInputData(latpolydata) if arg_projection == 'linear' : for i in range(-180,540,arg_grid_delta) : lonpolydata=longitude_create(i,arg_projection,arg_ratioxy) gridpolydata.AddInputData(lonpolydata) else: for i in range(0,180,arg_grid_delta) : lonpolydata=longitude_create(i,arg_projection) gridpolydata.AddInputData(lonpolydata) gridpolygonmapper=vtk.vtkDataSetMapper() gridpolygonmapper.SetInputConnection(gridpolydata.GetOutputPort()) gridpolygonactor=vtk.vtkActor() gridpolygonactor.SetMapper(gridpolygonmapper) gridpolygonactor.GetProperty().SetColor(arg_grid_color) gridpolygonactor.GetProperty().SetLineWidth(arg_grid_width) gridpolygonactor.GetProperty().SetAmbient(1) gridpolygonactor.GetProperty().SetDiffuse(0) gridpolygonactor.PickableOff() return(gridpolygonactor)
def append(polydata1, polydata2): """Define new polydata appending polydata1 and polydata2""" appender = vtk.vtkAppendPolyData() appender.AddInputData(polydata1) appender.AddInputData(polydata2) appender.Update() return appender.GetOutput()
def main(argv=None): dimension = 2 numprocs = 2 level = 0 # startlevel no_multigridlevels = 0 # check how many processors generated aggregation output # while check_files_for_next_level(0,numprocs, "aggs_level%LEVEL_proc%PROC.out") == True: # numprocs = numprocs + 1 # numprocs = numprocs - 1 # print "Aggregtaion information for " + str(numprocs) + " processors found" # process all multigrid levels while check_files_for_next_level(level, numprocs, "aggs_level%LEVEL_proc%PROC.out"): global_nodecoords = [] print "Level " + str(level) if level == 0: # read in coordinates (finest level global_nodecoords, dimension = read_finelevel_nodecoords_from_file("example.txt") else: global_nodecoords, dimension = read_nodecoords_from_file("nodes" + str(level) + ".txt") # read aggregates aggid2nodes, aggid2procs = readin_aggregates("aggs_level%LEVEL_proc%PROC.out", numprocs, level) # vtk polygon for output aggpolygons = vtk.vtkAppendPolyData() # collect all aggregates for aggid, agg_nodes in aggid2nodes.iteritems(): # build an aggregate if dimension == 2: prepareDelaunayData( dimension, agg_nodes, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs ) else: prepareDelaunayData3d( dimension, agg_nodes, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs ) # aggpolygons.GetOutput().GetPointData().SetVectors(vtkDisplacementVector) # aggpolygons.Update() writer = vtk.vtkXMLPolyDataWriter() fname = "aggs" + str(level) + ".vtp" writer.SetFileName(fname) writer.SetInput(aggpolygons.GetOutput()) writer.Write() write_nodes_file("nodes" + str(level + 1) + ".txt", aggid2nodes, global_nodecoords, dimension) # increment number of multigrid levels that have been found in the files if no_multigridlevels < level: no_multigridlevels = level print "VTK Export for level " + str(level) + " finished...\r\n" level = level + 1
def get_landmarks_as_spheres(lms): diag_len = Render3D.get_landmarks_bounding_box_diagonal_length(lms) # sphere radius is 0.8% of bounding box diagonal sphere_size = diag_len * 0.008 append = vtk.vtkAppendPolyData() for idx in range(len(lms)): lm = lms[idx] # scalars = vtk.vtkDoubleArray() # scalars.SetNumberOfComponents(1) sphere = vtk.vtkSphereSource() sphere.SetCenter(lm) sphere.SetRadius(sphere_size) sphere.SetThetaResolution(20) sphere.SetPhiResolution(20) sphere.Update() # scalars.SetNumberOfValues(sphere.GetOutput().GetNumberOfPoints()) # for s in range(sphere.GetOutput().GetNumberOfPoints()): # scalars.SetValue(s, dst) # sphere.GetOutput().GetPointData().SetScalars(scalars) append.AddInputData(sphere.GetOutput()) del sphere # del scalars append.Update() return append.GetOutput()
def __init__( self ): PerkEvaluatorMetric.__init__( self ) self.outputPolyData = vtk.vtkAppendPolyData() self.planeSource = vtk.vtkPlaneSource() self.planePolyData = self.planeSource.GetOutput()
def __create_vtk_rep(self, p1, p2): cone = self.__create_cone(p1, p2) line = self.__create_connecting_line(p1, p2) append_filter = vtk.vtkAppendPolyData() append_filter.AddInputData(cone); append_filter.AddInputData(line); append_filter.Update() return append_filter.GetOutput()
def Execute(self): if (self.Surface == None): self.PrintError('Error: no Surface.') appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputData(self.Surface) appendFilter.AddInputData(self.Surface2) appendFilter.Update() self.Surface = appendFilter.GetOutput()
def Merge(polydata_list): append = vtk.vtkAppendPolyData() for polydata in polydata_list: triangle = vtk.vtkTriangleFilter() triangle.SetInputData(polydata) append.AddInputData(triangle.GetOutput()) clean = vtk.vtkCleanPolyData() clean.SetInputData(append.GetOutput()) return append.GetOutput()
def onObjectMeshesComputed(self): self.dlg.accept() logger.debug( "*** Preparing 3D view ***" ) #Clean up possible previous 3D displays for c in self.cutter: if c: self.qvtk.renderer.RemoveActor(c) for a in self.objects: self.qvtk.renderer.RemoveActor(a) self.polygonAppender = vtkAppendPolyData() for g in self.dlg.extractor.meshes.values(): self.polygonAppender.AddInput(g) self.cutter[0] = Outliner(self.polygonAppender.GetOutput()) self.cutter[0].GetOutlineProperty().SetColor(1,0,0) self.cutter[1] = Outliner(self.polygonAppender.GetOutput()) self.cutter[1].GetOutlineProperty().SetColor(0,1,0) self.cutter[2] = Outliner(self.polygonAppender.GetOutput()) self.cutter[2].GetOutlineProperty().SetColor(0,0,1) for c in self.cutter: c.SetPickable(False) ## 1. Use a render window with alpha bits (as initial value is 0 (false)): #self.renderWindow.SetAlphaBitPlanes(True); ## 2. Force to not pick a framebuffer with a multisample buffer ## (as initial value is 8): #self.renderWindow.SetMultiSamples(0); ## 3. Choose to use depth peeling (if supported) (initial value is 0 (false)): #self.renderer.SetUseDepthPeeling(True); ## 4. Set depth peeling parameters ## - Set the maximum number of rendering passes (initial value is 4): #self.renderer.SetMaximumNumberOfPeels(100); ## - Set the occlusion ratio (initial value is 0.0, exact image): #self.renderer.SetOcclusionRatio(0.0); for i, g in self.dlg.extractor.meshes.items(): logger.debug( " - showing object with label = {}".format(i) ) mapper = vtkPolyDataMapper() mapper.SetInput(g) actor = vtkActor() actor.SetMapper(mapper) self.qvtk.registerObject(actor) self.objects.append(actor) if self.colorTable: c = self.colorTable[i] c = QColor.fromRgba(c) actor.GetProperty().SetColor(c.red()/255.0, c.green()/255.0, c.blue()/255.0) self.qvtk.renderer.AddActor(actor) self.qvtk.update()
def merge(pd1, pd2): """ merge two PolyDataSets into one. @param vtkPolyData pd1 the first dataset @param vtkPolyData pd2 the second dataset @return vtkPolyData the merged dataset """ a = vtkAppendPolyData() a.AddInput(pd1) a.AddInput(pd2) return a.GetOutput()
def gravar_Modelo_stl(self, path): app_polidata = vtk.vtkAppendPolyData() app_polidata.AddInput(self.polydata) app_polidata.AddInput(self.estruturas.GetOutput()) app_polidata.Update() write = vtk.vtkSTLWriter() write.SetInputData(app_polidata.GetOutput()) write.SetFileTypeToBinary() write.SetFileName(path) write.Write() write.Update()
def lump_poly(*args): """ Lump all passed-in poly together. FIXME: when lumped together, vectors are messed up. @return: output VTK object. @rtype: vtk.vtkobject """ import vtk apd = vtk.vtkAppendPolyData() for vbj in args: apd.AddInput(vbj.GetOutput()) return apd
def GetRepresentation(self, x, y, z): pc = self.camera.GetPosition() # camera position pf = self.camera.GetFocalPoint() # focal position pp = (x, y, z) # point where the user clicked # Vector from camera position to user clicked point vcp = [j-i for i,j in zip(pc, pp)] # Vector from camera position to camera focal point vcf = [j-i for i,j in zip(pc, pf)] # the vector where the perpendicular vector will be given n = [0,0,0] # The cross, or vectorial product, give a vector perpendicular to vcp # and vcf, in this case this vector will be in horizontal, this vector # will be stored in the variable "n" vtk.vtkMath.Cross(vcp, vcf, n) # then normalize n to only indicate the direction of this vector vtk.vtkMath.Normalize(n) # then p1 = [i*self.size + j for i,j in zip(n, pp)] p2 = [i*-self.size + j for i,j in zip(n, pp)] sh = vtk.vtkLineSource() sh.SetPoint1(p1) sh.SetPoint2(p2) n = [0,0,0] vcn = [j-i for i,j in zip(p1, pc)] vtk.vtkMath.Cross(vcp, vcn, n) vtk.vtkMath.Normalize(n) p3 = [i*self.size + j for i,j in zip(n, pp)] p4 = [i*-self.size +j for i,j in zip(n, pp)] sv = vtk.vtkLineSource() sv.SetPoint1(p3) sv.SetPoint2(p4) cruz = vtk.vtkAppendPolyData() cruz.AddInput(sv.GetOutput()) cruz.AddInput(sh.GetOutput()) c = vtk.vtkCoordinate() c.SetCoordinateSystemToWorld() m = vtk.vtkPolyDataMapper2D() m.SetInputConnection(cruz.GetOutputPort()) m.SetTransformCoordinate(c) a = vtk.vtkActor2D() a.SetMapper(m) a.GetProperty().SetColor(self.colour) return a
def Execute(self): if self.Surface == None: self.PrintError("Error: no Surface.") appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInput(self.Surface) appendFilter.AddInput(self.Surface2) appendFilter.Update() self.Surface = appendFilter.GetOutput() if self.Surface.GetSource(): self.Surface.GetSource().UnRegisterAllOutputs()
def ReadPDB(file_name): pdb = vtk.vtkPDBReader() pdb.SetFileName(file_name) pdb.SetHBScale(1.0) pdb.SetBScale(1.0) pdb.Update() sphere = vtk.vtkSphereSource() sphere.SetCenter(0, 0, 0) sphere.SetRadius(1) glyph = vtk.vtkGlyph3D() glyph.SetInputConnection(pdb.GetOutputPort()) glyph.SetSourceConnection(sphere.GetOutputPort()) glyph.SetOrient(1) glyph.SetColorMode(1) glyph.SetScaleMode(2) glyph.SetScaleFactor(.25) glyph.Update() tube = vtk.vtkTubeFilter() tube.SetInputConnection(pdb.GetOutputPort()) tube.SetNumberOfSides(6) tube.CappingOff() tube.SetRadius(0.2) tube.SetVaryRadius(0) tube.SetRadiusFactor(10) tube.Update() tubeMesh = vtk.vtkPolyData() tubeMesh.ShallowCopy(tube.GetOutput()) N = tubeMesh.GetNumberOfPoints() rgb_colors = tubeMesh.GetPointData().GetArray("rgb_colors") if rgb_colors is not None: if rgb_colors.GetNumberOfComponents() == 3: for i in range(N): rgb_colors.SetTupleValue(i, (127, 127, 127)) appendFilter = vtk.vtkAppendPolyData() appendFilter.AddInputConnection(glyph.GetOutputPort()) try: appendFilter.AddInputData(tubeMesh) except: appendFilter.AddInput(tubeMesh) appendFilter.Update() polyData = vtk.vtkPolyData() polyData.ShallowCopy(appendFilter.GetOutput()) return polyData
def save_atlas(polydata_list, out_dir): print "<registration_functions.py>: Save current atlas (sampled registered polydata)." appender = vtk.vtkAppendPolyData() idx = 0 n_subj = len(polydata_list) for pd in polydata_list: nf = pd.GetNumberOfLines() print "<registration_functions.py> subject:", idx+1, "/" , n_subj, "fibers:", nf if (vtk.vtkVersion().GetVTKMajorVersion() >= 6.0): appender.AddInputData(pd) else: appender.AddInput(pd) idx = idx + 1 appender.Update() wma.io.write_polydata(appender.GetOutput(), os.path.join(out_dir, 'atlas.vtk')) del appender
def view_polydatas(polydata_list): appender = vtk.vtkAppendPolyData() idx = 0 for pd in polydata_list: nf = pd.GetNumberOfLines() print idx print nf mask = numpy.ones(nf) colors = numpy.multiply(mask, idx-1) pd2 = wma.filter.mask(pd, mask, colors) appender.AddInput(pd2) idx = idx + 1 appender.Update() pd3 = appender.GetOutput() ren = wma.render.render(pd3) return ren
def test_create_report(self): self.delayDisplay('Starting %s' % inspect.stack()[0][3]) qrWidget = slicer.modules.QuantitativeReportingWidget with DICOMUtils.TemporaryDICOMDatabase(self.dicomDatabaseDir) as db: self.assertTrue(db.isOpen) self.assertEqual(slicer.dicomDatabase, db) self.loadTestVolume() success, err = qrWidget.saveReport() self.assertFalse(success) self.delayDisplay('Add segments') qrWidget = slicer.modules.QuantitativeReportingWidget segmentation = qrWidget.segmentEditorWidget.segmentationNode.GetSegmentation() segmentGeometries = { 'Tumor': [[2, 30, 30, -127.7], [2, 40, 40, -127.7], [2, 50, 50, -127.7], [2, 40, 80, -127.7]], 'Air': [[2, 60, 100, -127.7], [2, 80, 30, -127.7]] } for segmentName, segmentGeometry in segmentGeometries.iteritems(): appender = vtk.vtkAppendPolyData() for sphere in segmentGeometry: sphereSource = vtk.vtkSphereSource() sphereSource.SetRadius(sphere[0]) sphereSource.SetCenter(sphere[1], sphere[2], sphere[3]) appender.AddInputConnection(sphereSource.GetOutputPort()) segment = vtkSegmentationCore.vtkSegment() segment.SetName(segmentation.GenerateUniqueSegmentID(segmentName)) appender.Update() representationName = vtkSegmentationCore.vtkSegmentationConverter.GetSegmentationClosedSurfaceRepresentationName() segment.AddRepresentation(representationName, appender.GetOutput()) segmentation.AddSegment(segment) self.delayDisplay('Save report') success, err = qrWidget.saveReport() self.assertTrue(success) self.delayDisplay('Test passed!')