def writeDefects(defects_n, defects_v, numdefect_n, numdefect_v, outfile): # Preparing the vtp output # Create point structure in vtk Points = vtk.vtkPoints() print "Created Points" # Create (something) associated to the points, with different values for each Number = vtk.vtkDoubleArray() Number.SetNumberOfComponents(1) Number.SetName('Number') Size = vtk.vtkDoubleArray() Size.SetNumberOfComponents(1) Size.SetName('Size') print "Created Number" # Put one point at the centre, and the ndefect ones around it Points.InsertNextPoint(0, 0, 0) Number.InsertNextValue(0) Size.InsertNextValue(0) for u in range(numdefect_n): Points.InsertNextPoint(defects_n[u, 1], defects_n[u, 2], defects_n[u, 3]) Number.InsertNextValue(1) Size.InsertNextValue(1.0) for u in range(numdefect_v): Points.InsertNextPoint(defects_v[u, 1], defects_v[u, 2], defects_v[u, 3]) Number.InsertNextValue(2) Size.InsertNextValue(1.0) print "Added Particles and Numbers" lines = vtk.vtkCellArray() line = vtk.vtkLine() for i in range(numdefect_n): line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, i + 1) lines.InsertNextCell(line) for i in range(numdefect_v): line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, numdefect_n + i + 1) lines.InsertNextCell(line) print "Added lines" polydata = vtk.vtkPolyData() polydata.SetPoints(Points) polydata.SetLines(lines) polydata.GetPointData().AddArray(Number) polydata.GetPointData().AddArray(Size) print "Finished Polydata" polydata.Modified() writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(outfile) # Python 2.7 vs. 3 incompatibility? if vtk.VTK_MAJOR_VERSION <= 5: writer.SetInput(polydata) else: writer.SetInputData(polydata) writer.SetDataModeToAscii() writer.Write() print "Wrote File"
def run(self, entries, hippotargets, inputObstacle1, inputObstacle2): # assign vtk functions to variable names lines = vtk.vtkCellArray(); Path = vtk.vtkPolyData(); points = vtk.vtkPoints() # Compute the thresholded output volume using the Threshold Scalar Volume CLI module vtk_mesh = MarchingCubes_alg() OBB_obstacle1_tree, OBB_tree_obstacle2 = vtk_mesh.run(inputObstacle1, inputObstacle2) for i in range(0, entries.GetNumberOfFiducials()): entry = [0, 0, 0]; entries.GetNthFiducialPosition(i, entry) for j in range(0, hippotargets.GetNumberOfFiducials()): target = [0, 0, 0]; hippotargets.GetNthFiducialPosition(j, target) line = vtk.vtkLine() line.GetPointIds().SetId(0, points.InsertNextPoint(entry[0], entry[1], entry[2])) line.GetPointIds().SetId(1, points.InsertNextPoint(target[0], target[1], target[2])) # problem: intersectwithline produced all 0 for all paths if (OBB_obstacle1_tree.IntersectWithLine(entry, target, vtk.vtkPoints(), vtk.vtkIdList()) == 0): if (OBB_obstacle2_tree.IntersectWithLine(entry, target, vtk.vtkPoints(), vtk.vtkIdList()) == 0): line = vtk.vtkLine() line.GetPointIds().SetId(0, points.InsertNextPoint(entry[0], entry[1], entry[2])) line.GetPointIds().SetId(1, points.InsertNextPoint(target[0], target[1], target[2])) # Calculate the length of the line length = numpy.sqrt((target[0] - entry[0]) * 2 + (target[1] - entry[1]) * 2 + (target[2] - entry[2]) * 2) if length < 55: # Check the threshold lines.InsertNextCell(line) # Store the line in array Path.SetPoints(points) Path.SetLines(lines) pathNode = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode', 'GoodPath') pathNode.SetAndObserveMesh(Path)
def _create_pyramid_lines(self, current_box_idx): """Collects points into lines for the pyramid Args: current_box_idx: Current box index, used for point indexing """ point_idx_start = current_box_idx * 5 line1 = vtk.vtkLine() line1.GetPointIds().SetId(0, point_idx_start + 1) line1.GetPointIds().SetId(1, point_idx_start) line2 = vtk.vtkLine() line2.GetPointIds().SetId(0, point_idx_start + 2) line2.GetPointIds().SetId(1, point_idx_start) line3 = vtk.vtkLine() line3.GetPointIds().SetId(0, point_idx_start + 3) line3.GetPointIds().SetId(1, point_idx_start) line4 = vtk.vtkLine() line4.GetPointIds().SetId(0, point_idx_start + 4) line4.GetPointIds().SetId(1, point_idx_start) self.vtk_pyramid_lines.InsertNextCell(line1) self.vtk_pyramid_lines.InsertNextCell(line2) self.vtk_pyramid_lines.InsertNextCell(line3) self.vtk_pyramid_lines.InsertNextCell(line4)
def numpyToPd(d): ''' input is a list of points ''' pd = vtk.vtkPolyData() pts = vtk.vtkPoints() for p in d: x1 = p[0] x2 = p[1] x3 = 0 pts.InsertNextPoint([x1, x2, x3]) pd.SetPoints(pts) lines = vtk.vtkCellArray() for i in range(len(d) - 1): l = vtk.vtkLine() l.GetPointIds().SetId(0, i) l.GetPointIds().SetId(1, i + 1) lines.InsertNextCell(l) l = vtk.vtkLine() l.GetPointIds().SetId(0, len(d) - 1) l.GetPointIds().SetId(1, 0) lines.InsertNextCell(l) pd.SetLines(lines) return pd
def __gen_gesture_vtp(self, path_gesture_data, vtk_path): ''' generate gesture vtp file format dependent on time for paraview agrs: path_gesture_data: nx12 numpy array, contains [x, y, z, pos_xaxis_x, pos_xaxis_y, pos_xaxis_z, pos_yaxis_x, pos_yaxis_y, pos_yaxis_z, pos_zaxis_x, pos_zaxis_y, pos_zaxis_z] vtk_path: string, the stored gesture vtp files path and file name ''' number_of_steps = path_gesture_data.shape[0] writer = vtk.vtkXMLPolyDataWriter() data_to_write = vtk.vtkPolyData() writer.SetNumberOfTimeSteps(number_of_steps) writer.SetInputData(data_to_write) writer.SetFileName(vtk_path) writer.Start() for i in range(number_of_steps): # 每个姿态图就是一个ployData linepoly = vtk.vtkPolyData() # 每个姿态图上有四个点 each_ges_points = vtk.vtkPoints() each_ges_points.SetNumberOfPoints(4) each_ges_points.SetPoint(0, path_gesture_data[i, 0], path_gesture_data[i, 1], path_gesture_data[i, 2]) for j in range(1, 4): each_ges_points.SetPoint(j, path_gesture_data[i, 3 * j], path_gesture_data[i, 3 * j + 1], path_gesture_data[i, 3 * j + 2]) linepoly.SetPoints(each_ges_points) # 三个方向上的姿态线为一个cell lines = vtk.vtkCellArray() # x 方向上的姿态线 line0 = vtk.vtkLine() line0.GetPointIds().SetId(0, 0) line0.GetPointIds().SetId(1, 1) # y 方向上的姿态线 line1 = vtk.vtkLine() line1.GetPointIds().SetId(0, 0) line1.GetPointIds().SetId(1, 2) # z 方向上的姿态线 line2 = vtk.vtkLine() line2.GetPointIds().SetId(0, 0) line2.GetPointIds().SetId(1, 3) lines.InsertNextCell(line0) lines.InsertNextCell(line1) lines.InsertNextCell(line2) # setup colors colors = vtk.vtkNamedColors() Colors = vtk.vtkUnsignedCharArray() Colors.SetNumberOfComponents(3) Colors.SetName("Colors") Colors.InsertNextTypedTuple(colors.GetColor3ub("red")) Colors.InsertNextTypedTuple(colors.GetColor3ub("yellow")) Colors.InsertNextTypedTuple(colors.GetColor3ub("green")) linepoly.SetLines(lines) linepoly.GetCellData().SetScalars(Colors) data_to_write.ShallowCopy(linepoly) writer.WriteNextTime(i) writer.Stop() print("gesture vtp file is generated!")
def execute(self, obj, event): # Animate the visualization self.timer_count = (self.timer_count + 1) % ( 2018 - 1930 + 1 ) # Once the entire sequence has been animated, restart from the beginning # Generate a point on each unit vector that corresponds to that unit vector's genre's popularity for a given time year_popularity = self.genre_popularity[ self.timer_count] # Get the dict for this year year_popularity = list(sorted(year_popularity.items( ))) # Convert the dict into a list of [key, value] year_pop_sum = sum([ n[1] for n in year_popularity ]) # Compute the total number of ratings submitted for this year normalised_year_popularity = list( map( lambda n: [ n[0], (3 * n[1] / year_pop_sum if year_pop_sum > 0 else n[1]) ], year_popularity) ) # Normalised popularities (sum over genres = 1) # The maximum normalised_year_pop ever is <0.33, so multiply all pop values by 3 (to make the plot more readable) # Create points on each unit vector proportionately distant from origin to this genre's popularity for that year pop_lines = vtk.vtkCellArray() pop_points = vtk.vtkPoints() for index, unit_vector in enumerate(self.unit_vectors): pop_points.InsertNextPoint( unit_vector[0] * normalised_year_popularity[index][1], unit_vector[1] * normalised_year_popularity[index][1], 0) if index > 0: line = vtk.vtkLine() line.GetPointIds().SetId(0, index - 1) line.GetPointIds().SetId(1, index) pop_lines.InsertNextCell(line) # Add the last line that joins the last pop_point to the first pop_point line = vtk.vtkLine() line.GetPointIds().SetId(0, index) line.GetPointIds().SetId(1, 0) pop_lines.InsertNextCell(line) # Create a Polydata to store all the lines in popLinesPolyData = vtk.vtkPolyData() # Add the lines to the dataset popLinesPolyData.SetPoints(pop_points) popLinesPolyData.SetLines(pop_lines) # Create a mapper and actor for the lines pop_line_mapper = vtk.vtkPolyDataMapper() pop_line_mapper.SetInputData(popLinesPolyData) # Set this new mapper as the mapper self.line_actor.SetMapper(pop_line_mapper) # Update the year text self.text_actor.SetInput(str(self.timer_count + 1930)) # Get the interaction object iren = obj # Render the new frame iren.GetRenderWindow().Render()
def ROI_circlePolyData(center, r, indicator): """ Create a vtkActor object of ROI circle. :param center: The center coordinates of the ROI. :param r: The radius of ROI. :param indicator: Indicates which plane the circle is on. (0: YZ plane, 1: XZ plane, 2: XY plane. :return: A vtkActor object. """ # Create points of the circle. circle_data = [] for i in range(180): circle_data.append([ r * np.cos(float(i * np.pi / 90)), r * np.sin(float(i * np.pi / 90)) ]) circle_data[i].insert(indicator, 0) circle_data[i] = np.array(circle_data[i]) + np.array(center) circle_points = vtk.vtkPoints() # store all the points on the circle circle = vtk.vtkCellArray() # store all the line segments on the circle colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) for point in circle_data: circle_points.InsertNextPoint(point) for i in range(len(circle_data) - 1): line = vtk.vtkLine() # Connect two adjacent points with line segments line.GetPointIds().SetId(0, i) line.GetPointIds().SetId(1, i + 1) circle.InsertNextCell(line) colors.InsertNextTypedTuple([255, 0, 0]) # red color line = vtk.vtkLine() line.GetPointIds().SetId(0, len(circle_data) - 1) line.GetPointIds().SetId(1, 0) circle.InsertNextCell(line) colors.InsertNextTypedTuple([255, 0, 0]) circlePolyData = vtk.vtkPolyData() circlePolyData.SetPoints(circle_points) circlePolyData.SetLines(circle) circlePolyData.GetCellData().SetScalars(colors) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(circlePolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetLineWidth(5) return actor
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.3, 0.4, 0.5) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create lines. points = vtk.vtkPoints() points.InsertPoint(0, 0, 0, 1) points.InsertPoint(1, 1, 0, 0) points.InsertPoint(2, 0, 1, 0) points.InsertPoint(3, 1, 1, 1) line1 = vtk.vtkLine() line1.GetPointIds().SetId(0, 0) line1.GetPointIds().SetId(1, 1) line2 = vtk.vtkLine() line2.GetPointIds().SetId(0, 2) line2.GetPointIds().SetId(1, 3) lines = vtk.vtkCellArray() lines.InsertNextCell(line1) lines.InsertNextCell(line2) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetLines(lines) ruledSurfaceFilter = vtk.vtkRuledSurfaceFilter() ruledSurfaceFilter.SetInputConnection(polyData.GetProducerPort()) ruledSurfaceFilter.SetResolution(21, 21) ruledSurfaceFilter.SetRuledModeToResample() # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(ruledSurfaceFilter.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(0.89, 0.81, 0.34) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def __init__(self, parent=None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.3, 0.4, 0.5) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create lines. points = vtk.vtkPoints() points.InsertPoint(0, 0, 0, 1) points.InsertPoint(1, 1, 0, 0) points.InsertPoint(2, 0, 1, 0) points.InsertPoint(3, 1, 1, 1) line1 = vtk.vtkLine() line1.GetPointIds().SetId(0, 0) line1.GetPointIds().SetId(1, 1) line2 = vtk.vtkLine() line2.GetPointIds().SetId(0, 2) line2.GetPointIds().SetId(1, 3) lines = vtk.vtkCellArray() lines.InsertNextCell(line1) lines.InsertNextCell(line2) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.SetLines(lines) ruledSurfaceFilter = vtk.vtkRuledSurfaceFilter() ruledSurfaceFilter.SetInputConnection(polyData.GetProducerPort()) ruledSurfaceFilter.SetResolution(21, 21) ruledSurfaceFilter.SetRuledModeToResample() # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(ruledSurfaceFilter.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(0.89, 0.81, 0.34) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def createCellLinesForPoints(renderer,pts): """ Adds Edges to the renderer detemined by the given points Args: renderer(vtkRenderer) = the renderer pts (numpy array) = array of the 2d points """ pd1=pts[0,:] pd2=pts[1,:] pd3=pts[3,:] pd4=pts[2,:] p1=np.append(pd1,0) p2=np.append(pd2,0) p3=np.append(pd3,0) p4=np.append(pd4,0) pts=vtk.vtkPoints() pts.InsertNextPoint(p1) pts.InsertNextPoint(p2) pts.InsertNextPoint(p3) pts.InsertNextPoint(p4) polyData=vtk.vtkPolyData() polyData.SetPoints(pts) # create lines lin1=vtk.vtkLine() lin1.GetPointIds().SetId(0,0) lin1.GetPointIds().SetId(1,1) lin2=vtk.vtkLine() lin2.GetPointIds().SetId(0,1) lin2.GetPointIds().SetId(1,2) lin3=vtk.vtkLine() lin3.GetPointIds().SetId(0,2) lin3.GetPointIds().SetId(1,3) lin4=vtk.vtkLine() lin4.GetPointIds().SetId(0,3) lin4.GetPointIds().SetId(1,0) lines=vtk.vtkCellArray() lines.InsertNextCell(lin1) lines.InsertNextCell(lin2) lines.InsertNextCell(lin3) lines.InsertNextCell(lin4) polyData.SetLines(lines) mapper=vtk.vtkPolyDataMapper() mapper.SetInputData(polyData) mapper.Update() actor=vtk.vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor)
def _create_cart3d_free_edegs(self, model, nodes, elements): free_edges = model.get_free_edges(elements) nfree_edges = len(free_edges) if nfree_edges: # yellow = (1., 1., 0.) pink = (0.98, 0.4, 0.93) npoints = 2 * nfree_edges if 'free_edges' not in self.alt_grids: self.create_alternate_vtk_grid('free_edges', color=pink, line_width=3, opacity=1.0, representation='surface') j = 0 points = vtk.vtkPoints() points.SetNumberOfPoints(npoints) self.alt_grids['free_edges'].Allocate(nfree_edges, 1000) elem = vtk.vtkLine() # elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) # elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) etype = vtk.vtkLine().GetCellType() for free_edge in free_edges: # (p1, p2) = free_edge for ipoint, node_id in enumerate(free_edge): point = nodes[node_id, :] points.InsertPoint(j + ipoint, *point) elem = vtk.vtkLine() elem.GetPointIds().SetId(0, j) elem.GetPointIds().SetId(1, j + 1) self.alt_grids['free_edges'].InsertNextCell( etype, elem.GetPointIds()) j += 2 self.alt_grids['free_edges'].SetPoints(points) else: # TODO: clear free edges pass if 'free_edges' in self.alt_grids: self._add_alt_actors(self.alt_grids) self.geometry_actors['free_edges'].Modified() if hasattr(self.geometry_actors['free_edges'], 'Update'): self.geometry_actors['free_edges'].Update()
def drawBones(bones, outFile): ptsVtk = vtk.vtkPoints() ptsAll = np.vstack(bones) # pts.InsertNextPoint(p1) for i in range(ptsAll.shape[0]): ptsVtk.InsertNextPoint(ptsAll[i, :].tolist()) polyData = vtk.vtkPolyData() polyData.SetPoints(ptsVtk) lines = vtk.vtkCellArray() for i in range(int(ptsAll.shape[0] / 2)): line = vtk.vtkLine() line.GetPointIds().SetId( 0, i * 2) # the second 0 is the index of the Origin in the vtkPoints line.GetPointIds().SetId( 1, i * 2 + 1) # the second 1 is the index of P0 in the vtkPoints # line. lines.InsertNextCell(line) polyData.SetLines(lines) writer = vtk.vtkPolyDataWriter() writer.SetInputData(polyData) writer.SetFileName(outFile) writer.Update()
def drawCurve2(myscreen, curve, curvecolor): oPoints = vtk.vtkPoints() lineCells=vtk.vtkCellArray() idx = 0 last_idx = 0 segs=[] first = 1 print " curve with ", len(curve)," points" for p in curve: oPoints.InsertNextPoint( p[0], p[1], 0) if first==0: seg = [last_idx,idx] segs.append(seg) first = 0 last_idx = idx idx = idx + 1 # create line and cells for seg in segs: line = vtk.vtkLine() line.GetPointIds().SetId(0, seg[0]) line.GetPointIds().SetId(1, seg[1]) lineCells.InsertNextCell(line) linePolyData = vtk.vtkPolyData() linePolyData.SetPoints(oPoints) linePolyData.SetLines(lineCells) linePolyData.Modified() linePolyData.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linePolyData) edge_actor = vtk.vtkActor() edge_actor.SetMapper(mapper) edge_actor.GetProperty().SetColor( curvecolor ) myscreen.addActor( edge_actor )
def __init__(self, p1=(0, 0, 0), p2=(1, 1, 1), radius=0.2, color=(0, 1, 1)): """ tube""" points = vtk.vtkPoints() points.InsertNextPoint(p1) points.InsertNextPoint(p2) line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, 1) lines = vtk.vtkCellArray() lines.InsertNextCell(line) self.pdata = vtk.vtkPolyData() self.pdata.SetPoints(points) self.pdata.SetLines(lines) tubefilter = vtk.vtkTubeFilter() tubefilter.SetInputData(self.pdata) tubefilter.SetRadius(radius) tubefilter.SetNumberOfSides(50) tubefilter.Update() self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(tubefilter.GetOutputPort()) self.SetMapper(self.mapper) self.SetColor(color)
def set_bbox_line_actor(self, corners, faces, color): edge_set1 = np.vstack([np.array(faces)[:, 0], np.array(faces)[:, 1]]).T edge_set2 = np.vstack([np.array(faces)[:, 1], np.array(faces)[:, 2]]).T edge_set3 = np.vstack([np.array(faces)[:, 2], np.array(faces)[:, 3]]).T edge_set4 = np.vstack([np.array(faces)[:, 3], np.array(faces)[:, 0]]).T edges = np.vstack([edge_set1, edge_set2, edge_set3, edge_set4]) edges = np.unique(np.sort(edges, axis=1), axis=0) pts = vtk.vtkPoints() for corner in corners: pts.InsertNextPoint(corner) lines = vtk.vtkCellArray() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") for edge in edges: line = vtk.vtkLine() line.GetPointIds().SetId(0, edge[0]) line.GetPointIds().SetId(1, edge[1]) lines.InsertNextCell(line) colors.InsertNextTuple3(*color) linesPolyData = vtk.vtkPolyData() linesPolyData.SetPoints(pts) linesPolyData.SetLines(lines) linesPolyData.GetCellData().SetScalars(colors) return linesPolyData
def setEdgesPolydata(self, vd): self.edges = [] self.edges = vd.getEdgesGenerators() self.epts = vtk.vtkPoints() nid = 0 lines=vtk.vtkCellArray() for e in self.edges: p1 = self.scale*e[0] p2 = self.scale*e[1] self.epts.InsertNextPoint( p1.x, p1.y, p1.z) self.epts.InsertNextPoint( p2.x, p2.y, p2.z) line = vtk.vtkLine() line.GetPointIds().SetId(0,nid) line.GetPointIds().SetId(1,nid+1) nid = nid+2 lines.InsertNextCell(line) linePolyData = vtk.vtkPolyData() linePolyData.SetPoints(self.epts) linePolyData.SetLines(lines) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linePolyData) self.edge_actor = vtk.vtkActor() self.edge_actor.SetMapper(mapper) self.edge_actor.GetProperty().SetColor( camvtk.cyan ) myscreen.addActor( self.edge_actor ) myscreen.render()
def drawCurve2(myscreen, curve, curvecolor): oPoints = vtk.vtkPoints() lineCells = vtk.vtkCellArray() idx = 0 last_idx = 0 segs = [] first = 1 print " curve with ", len(curve), " points" for p in curve: oPoints.InsertNextPoint(p[0], p[1], 0) if first == 0: seg = [last_idx, idx] segs.append(seg) first = 0 last_idx = idx idx = idx + 1 # create line and cells for seg in segs: line = vtk.vtkLine() line.GetPointIds().SetId(0, seg[0]) line.GetPointIds().SetId(1, seg[1]) lineCells.InsertNextCell(line) linePolyData = vtk.vtkPolyData() linePolyData.SetPoints(oPoints) linePolyData.SetLines(lineCells) linePolyData.Modified() # linePolyData.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(linePolyData) edge_actor = vtk.vtkActor() edge_actor.SetMapper(mapper) edge_actor.GetProperty().SetColor(curvecolor) myscreen.addActor(edge_actor)
def draw_lines(nodes, color): points = vtk.vtkPoints() lines = vtk.vtkCellArray() nodecnt = 0 colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") for node in nodes: edges = node.getedges() for edge in edges: x0,y0,z0 = edge[0] x1,y1,z1 = edge[1] points.InsertNextPoint(edge[0]) points.InsertNextPoint(edge[1]) line = vtk.vtkLine() line.GetPointIds().SetId(0,nodecnt) line.GetPointIds().SetId(1,nodecnt+1) lines.InsertNextCell(line) nodecnt += 2 colors.InsertNextTupleValue(color) # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(points) # Add the lines to the dataset linesPolyData.SetLines(lines) linesPolyData.GetCellData().SetScalars(colors) return linesPolyData
def set_vtk_data(self): """ :return: """ # points self.points = vtk.vtkPoints() self.points.SetNumberOfPoints(2) for i, node in enumerate(self.node_list): if len(node) == 2: node = np.append(node, 0.) self.points.InsertPoint(i, node) # set vtk line object self.line = vtk.vtkLine() self.line.GetPointIds().SetId(0, 0) self.line.GetPointIds().SetId(1, 1) self.line_grid = vtk.vtkUnstructuredGrid() self.line_grid.Allocate(1, 1) self.line_grid.InsertNextCell(self.line.GetCellType(), self.line.GetPointIds()) self.line_grid.SetPoints(self.points) self.vtk_mapper = vtk.vtkDataSetMapper() self.vtk_mapper.SetInputData(self.line_grid) self.vtk_actor = vtk.vtkActor() self.vtk_actor.SetMapper(self.vtk_mapper) self.vtk_actor.AddPosition(self._parent.R) self.vtk_actor.SetOrientation(np.rad2deg(self._parent.theta)) self.vtk_actor.GetProperty().SetColor(self.color)
def __init__(self, parent = None): super(VTKFrame, self).__init__(parent) self.vtkWidget = QVTKRenderWindowInteractor(self) vl = QtGui.QVBoxLayout(self) vl.addWidget(self.vtkWidget) vl.setContentsMargins(0, 0, 0, 0) self.ren = vtk.vtkRenderer() self.ren.SetBackground(0.1, 0.2, 0.4) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create source # Create five points. origin = [0.0, 0.0, 0.0] p0 = [1.0, 0.0, 0.0] p1 = [0.0, 1.0, 0.0] p2 = [0.0, 1.0, 2.0] p3 = [1.0, 2.0, 3.0] p4 = [1.0, 2.0, 8.0] # Create a vtkPoints object and store the points in it points = vtk.vtkPoints() points.InsertNextPoint(origin) points.InsertNextPoint(p0) points.InsertNextPoint(p1) points.InsertNextPoint(p2) points.InsertNextPoint(p3) points.InsertNextPoint(p4) # Create a cell array to store the lines in and add the lines to it lines = vtk.vtkCellArray() for i in range(4): line = vtk.vtkLine() line.GetPointIds().SetId(0,i) line.GetPointIds().SetId(1,i+1) lines.InsertNextCell(line) # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(points) # Add the lines to the dataset linesPolyData.SetLines(lines) # Setup actor and mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linesPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def GetNormalLines(vtx, normals, scale): """ Returns polydata with lines to visualize normals. This can be used for either vertex or face normals; just specify the normals start points with "vtx". """ linePoints = vtk.vtkPoints() aLine = vtk.vtkLine() aLineGrid = vtk.vtkUnstructuredGrid() aLineGrid.Allocate(1, 1) aLineGrid.SetPoints(linePoints) for i in xrange(vtx.GetNumberOfTuples()): xyz0 = vtx.GetTuple3(i) nxyz = normals.GetTuple3(i) linePoints.InsertNextPoint(xyz0[0], xyz0[1], xyz0[2]) linePoints.InsertNextPoint(xyz0[0]+nxyz[0]*scale, xyz0[1]+nxyz[1]*scale, xyz0[2]+nxyz[2]*scale) aLine.GetPointIds().SetId(0, 2*i) aLine.GetPointIds().SetId(1, 2*i+1) aLineGrid.InsertNextCell(aLine.GetCellType(), aLine.GetPointIds()) return aLineGrid
def VisualizeBones(inSkelJsonFile, outSkelVTK): jData = json.load(open(inSkelJsonFile)) jointPosition = jData["JointPos"] numJoints = len(jointPosition[0]) ptsVtk = vtk.vtkPoints() # pts.InsertNextPoint(p1) for i in range(numJoints): ptsVtk.InsertNextPoint( [jointPosition[0][i], jointPosition[1][i], jointPosition[2][i]]) polyData = vtk.vtkPolyData() polyData.SetPoints(ptsVtk) lines = vtk.vtkCellArray() for i in range(1, numJoints): iParent = jData['Parents'].get(str(i)) if iParent != None: line = vtk.vtkLine() line.GetPointIds().SetId( 0, i) # the second 0 is the index of the Origin in the vtkPoints line.GetPointIds().SetId( 1, iParent) # the second 1 is the index of P0 in the vtkPoints lines.InsertNextCell(line) polyData.SetLines(lines) writer = vtk.vtkPolyDataWriter() writer.SetInputData(polyData) writer.SetFileName(outSkelVTK) writer.Update()
def vtkDrawLine( pts=None ): # ------------------------------------------------- # # --- [1] Define structures --- # # ------------------------------------------------- # points = vtk.vtkPoints() lines = vtk.vtkCellArray() length = np.cumsum( np.sqrt( np.sum( np.diff( pts, axis=0 )**2, axis=1 ) ) ) l_norm = np.insert( length, 0, 0.0 ) / float( length[-1] ) l_norm = vtknp.numpy_to_vtk( l_norm, deep=True ) # ------------------------------------------------- # # --- [2] Define Line --- # # ------------------------------------------------- # index = 0 for ik in range( pts.shape[0]-1 ): # -- register points as end point -- # start = pts[ik ] end = pts[ik+1] points.InsertNextPoint( start[x_], start[y_], start[z_] ) points.InsertNextPoint( end[x_], end[y_], end[z_] ) # -- connect two point to make line -- # line = vtk.vtkLine() line.GetPointIds().SetId( 0, index ) line.GetPointIds().SetId( 1, index+1 ) index += 2 lines.InsertNextCell( line ) # -- set vtk poly data -- # poly_data = vtk.vtkPolyData() poly_data.SetPoints(points) poly_data.SetLines(lines) poly_data.GetCellData().AddArray( l_norm ) return ( poly_data )
def drawCorrs(pts1, pts2, outCorrFile): ptsVtk = vtk.vtkPoints() ptsAll = np.vstack([pts1, pts2]) numPts = pts1.shape[0] assert pts1.shape[0] == pts2.shape[0] # pts.InsertNextPoint(p1) for i in range(ptsAll.shape[0]): ptsVtk.InsertNextPoint(ptsAll[i, :].tolist()) polyData = vtk.vtkPolyData() polyData.SetPoints(ptsVtk) lines = vtk.vtkCellArray() for i in range(pts1.shape[0]): line = vtk.vtkLine() line.GetPointIds().SetId( 0, i) # the second 0 is the index of the Origin in the vtkPoints line.GetPointIds().SetId( 1, i + numPts) # the second 1 is the index of P0 in the vtkPoints # line. lines.InsertNextCell(line) polyData.SetLines(lines) writer = vtk.vtkPolyDataWriter() writer.SetInputData(polyData) writer.SetFileName(outCorrFile) writer.Update()
def edges(indices): """ Maps a numpy ndarray to an vtkCellArray of vtkLines Args: indices (numpy.ndarray<int>): A numpy.ndarray of shape (n,2) of indices that define n edges Returns: vtk_lines (vtk.vtkCellArray): VTK representation of the edges """ if not isinstance(indices, numpy.ndarray): raise Numpy2VtkFormatException( 'lines needs numpy array as input' ) if len(indices.shape) != 2 or indices.shape[1] != 2: raise Numpy2VtkFormatException( 'lines needs a nx2 ndarray as input' ) if indices.dtype != numpy.int: raise Numpy2VtkFormatException( 'lines needs to be numpy array of type numpy.int' ) vtk_lines = vtk.vtkCellArray() for e in indices: line = vtk.vtkLine() line.GetPointIds().SetId(0, e[0]) line.GetPointIds().SetId(1, e[1]) vtk_lines.InsertNextCell(line) return vtk_lines
def vtk_lines(start_points, end_points, color=Color.White): assert (len(start_points) == len(end_points)) colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") actors = [] vtk_points = vtk.vtkPoints() for start, end in zip(start_points, end_points): vtk_points.InsertNextPoint(start) vtk_points.InsertNextPoint(end) N_lines = len(start_points) lines = vtk.vtkCellArray() for lineId in 2 * np.arange(N_lines): line = vtk.vtkLine() line.GetPointIds().SetId(0, lineId) line.GetPointIds().SetId(1, lineId + 1) lines.InsertNextCell(line) colors.InsertNextTuple(color) # Create a polydata to store everything in lines_poly_data = vtk.vtkPolyData() lines_poly_data.SetPoints(vtk_points) lines_poly_data.SetLines(lines) lines_poly_data.GetCellData().SetScalars(colors) # Visualize mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(lines_poly_data) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def set_vtk_data(self, q=None): """ :param q: :return: """ # points self.points = vtk.vtkPoints() self.points.SetNumberOfPoints(2) for i, node in enumerate(self.r_P_list): if len(node) == 2: node = np.append(node, 0.) self.points.InsertPoint(i, node) # set vtk line object self.line = vtk.vtkLine() self.line.GetPointIds().SetId(0, 0) self.line.GetPointIds().SetId(1, 1) self.line_grid = vtk.vtkUnstructuredGrid() self.line_grid.Allocate(1, 1) self.line_grid.InsertNextCell(self.line.GetCellType(), self.line.GetPointIds()) self.line_grid.SetPoints(self.points) self.vtk_mapper = vtk.vtkDataSetMapper() self.vtk_mapper.SetInputData(self.line_grid) self.vtk_actor = vtk.vtkActor() self.vtk_actor.SetMapper(self.vtk_mapper) self.vtk_actor.GetProperty().SetColor(self.color)
def mesh2polydata(mesh): points = vtk.vtkPoints() lines = vtk.vtkCellArray() faces = vtk.vtkCellArray() v = mesh.vertices l = mesh.lines f = mesh.faces for i in range(v.shape[0]): points.InsertNextPoint(v[i][0], v[i][1], v[i][2]) for i in range(l.shape[0]): vtkLine = vtk.vtkLine() vtkLine.GetPointIds().SetId(0, l[i][0]) vtkLine.GetPointIds().SetId(1, l[i][1]) lines.InsertNextCell(vtkLine) for i in range(f.shape[0]): vtkTri = vtk.vtkTriangle() vtkTri.GetPointIds().SetId(0, f[i][0]) vtkTri.GetPointIds().SetId(1, f[i][1]) vtkTri.GetPointIds().SetId(2, f[i][2]) faces.InsertNextCell(vtkTri) pd = vtk.vtkPolyData() pd.SetPoints(points) pd.SetLines(lines) pd.SetPolys(faces) return pd
def source(self): for element in self.elements: _nodes = vtk.vtkPoints() _edges = vtk.vtkCellArray() _data = vtk.vtkPolyData() _colorFilter = vtk.vtkUnsignedCharArray() _colorFilter.SetNumberOfComponents(3) _nodes.InsertPoint(0, element.first_node.x, element.first_node.y, element.first_node.z) _nodes.InsertPoint(1, element.last_node.x, element.last_node.y, element.last_node.z) line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, 1) _edges.InsertNextCell(line) _data.SetPoints(_nodes) _data.SetLines(_edges) color = [0, 0, 255] for _ in range(_nodes.GetNumberOfPoints()): _colorFilter.InsertNextTypedTuple(color) _data.GetPointData().SetScalars(_colorFilter) _tubeFilter = vtk.vtkTubeFilter() _tubeFilter.SetInputData(_data) _tubeFilter.SetRadius(0.003) _tubeFilter.SetNumberOfSides(50) _tubeFilter.Update() self._object.AddInputConnection(_tubeFilter.GetOutputPort()) self._object.Update()
def __init__(self, points): if not isinstance(points, Iterable): raise TypeError('Input argument must be an iterable') try: points = tuple(map(_parse_vector3, points)) except TypeError: raise TypeError( 'All points must be a a list of three number values') n = len(points) lines_data = vtkPolyData() # Create the set of points _points = vtkPoints() for point in points: _points.InsertNextPoint(*point) lines_data.SetPoints(_points) # Connect the points using lines lines = vtkCellArray() for i in range(1, n): line = vtkLine() line.GetPointIds().SetId(0, i - 1) line.GetPointIds().SetId(1, i) lines.InsertNextCell(line) lines_data.SetLines(lines) super().__init__(lines_data)
def __init__(self, center=(0, 0, 0), radius=1, color=(0, 1, 1), resolution=50): """ create circle """ lines = vtk.vtkCellArray() id = 0 points = vtk.vtkPoints() for n in xrange(0, resolution): line = vtk.vtkLine() angle1 = (float(n) / (float(resolution))) * 2 * math.pi angle2 = (float(n + 1) / (float(resolution))) * 2 * math.pi p1 = (center[0] + radius * math.cos(angle1), center[1] + radius * math.sin(angle1), center[2]) p2 = (center[0] + radius * math.cos(angle2), center[1] + radius * math.sin(angle2), center[2]) points.InsertNextPoint(p1) points.InsertNextPoint(p2) line.GetPointIds().SetId(0, id) id = id + 1 line.GetPointIds().SetId(1, id) id = id + 1 lines.InsertNextCell(line) self.pdata = vtk.vtkPolyData() self.pdata.SetPoints(points) self.pdata.SetLines(lines) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInput(self.pdata) self.SetMapper(self.mapper) self.SetColor(color)
def __init__(self,center=(0,0,0) , radius=1, color=(0,1,1), resolution=50 ): """ create circle """ lines =vtk.vtkCellArray() id = 0 points = vtk.vtkPoints() for n in xrange(0,resolution): line = vtk.vtkLine() angle1 = (float(n)/(float(resolution)))*2*math.pi angle2 = (float(n+1)/(float(resolution)))*2*math.pi p1 = (center[0]+radius*math.cos(angle1), center[1]+radius*math.sin(angle1), center[2]) p2 = (center[0]+radius*math.cos(angle2), center[1]+radius*math.sin(angle2), center[2]) points.InsertNextPoint(p1) points.InsertNextPoint(p2) line.GetPointIds().SetId(0,id) id=id+1 line.GetPointIds().SetId(1,id) id=id+1 lines.InsertNextCell(line) self.pdata = vtk.vtkPolyData() self.pdata.SetPoints(points) self.pdata.SetLines(lines) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInput(self.pdata) self.SetMapper(self.mapper) self.SetColor(color)
def close_cell(section): #assume the cell array of lines section.BuildCells() section.BuildLinks() numberOfLinePoints = section.GetNumberOfPoints() cell_ids = vtk.vtkIdList() numberOfSingleCellPoints = 0 termination_pts = [] for i in range(section.GetNumberOfPoints()): section.GetPointCells(i, cell_ids) if (cell_ids.GetNumberOfIds() == 1): numberOfSingleCellPoints += 1 termination_pts.append(i) if (numberOfSingleCellPoints == 2): print(termination_pts) line = vtk.vtkLine() line.GetPointIds().SetId(0, termination_pts[0]) line.GetPointIds().SetId(1, termination_pts[1]) section.GetLines().InsertNextCell(line) elif (numberOfSingleCellPoints > 2): print("disconnected section")
def MoleculeCurvature(self, in_residue): """last calculated curvature which also updates triangles_centers_pointlocator. * it takes into account the last curvature extraction that has been run (mean or gaussian). """ point_data = self.curvature_polydata.GetPointData( ) # the last updated self.curvature_polydata data_array = point_data.GetScalars() pos = np.array([0.0, 0.0, 0.0]) i = 0 molecule_atoms = self.univ.select_atoms( "resid " + str(in_residue) + " and name H1 C1" ) # C1 C2 C3 are the head beads for glycoceramides. for atom in molecule_atoms: # average position if necessary pos += atom.position i += 1 pos /= i point_id = self.triangles_centers_pointlocator.FindClosestPoint(pos) point_coor = self.triangles_centers_pointlocator.GetDataSet( ).GetPoints().GetPoint(point_id) #distance = vtk.vtkMath.Distance2BetweenPoints(point_coor,pos) value = data_array.GetTuple1(point_id) ## for test ## index1 = self.test_points.InsertNextPoint(pos) index2 = self.test_points.InsertNextPoint(point_coor) line = vtk.vtkLine() line.GetPointIds().SetId(0, index1) line.GetPointIds().SetId(1, index2) self.test_lines.InsertNextCell(line) #### return [value, point_id]
def draw_lines(self): index = 0 for line_type, end_point in self.path_points: # print line_type, end_point self.points.InsertNextPoint(end_point[:3]) self.colors.InsertNextTypedTuple(self.path_colors[line_type]) line = vtk.vtkLine() if index == 0: line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, 1) else: line.GetPointIds().SetId(0, index-1) line.GetPointIds().SetId(1, index) self.lines.InsertNextCell(line) index += 1 # free up memory, lots of it for big files self.path_points = [] self.poly_data.SetPoints(self.points) self.poly_data.SetLines(self.lines) self.poly_data.GetCellData().SetScalars(self.colors) self.data_mapper.SetInputData(self.poly_data) self.data_mapper.Update() self.path_actor.SetMapper(self.data_mapper)
def save_contour_as_vtp(points, lines, filename): """ Generates a .vtp file for the given contour to use in ShapeWorks optimizer points: Nx3 np.ndarray of points in the contour lines: Mx2 np.ndarray of lines in the contour filename: output .vtp filename """ vtk_pts = vtk.vtkPoints() n = points.shape[0] for j in range(n): x, y, z = points[j] vtk_pts.InsertNextPoint((x,y,z)) vtk_lines = vtk.vtkCellArray() m = lines.shape[0] for j in range(m): vtk_line = vtk.vtkLine() vtk_line.GetPointIds().SetId(0, lines[j][0]) vtk_line.GetPointIds().SetId(1, lines[j][1]) vtk_lines.InsertNextCell(vtk_line) polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_pts) polydata.SetLines(vtk_lines) writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(filename) writer.SetInputData(polydata) writer.Write()
def insertLine(lines, id0, id1): line = vtk.vtkLine() lPointIds = line.GetPointIds() lPointIds.SetId( 0, id0) lPointIds.SetId( 1, id1) if( containsLine(lines, line) == 0): lines.InsertNextCell( line )
def ndarray_to_vtkcellarray(array): bonds=vtk.vtkCellArray() for data in array: line = vtk.vtkLine() line.GetPointIds().SetId(0,int(data[0])) line.GetPointIds().SetId(1,int(data[1])) bonds.InsertNextCell(line) return bonds
def _create_cart3d_free_edegs(self, model, nodes, elements): free_edges = model.get_free_edges(elements) nfree_edges = len(free_edges) if nfree_edges: # yellow = (1., 1., 0.) pink = (0.98, 0.4, 0.93) npoints = 2 * nfree_edges if 'free_edges' not in self.alt_grids: self.create_alternate_vtk_grid('free_edges', color=pink, line_width=3, opacity=1.0, representation='surface') j = 0 points = vtk.vtkPoints() points.SetNumberOfPoints(npoints) self.alt_grids['free_edges'].Allocate(nfree_edges, 1000) elem = vtk.vtkLine() # elem.GetPointIds().SetId(0, nidMap[nodeIDs[0]]) # elem.GetPointIds().SetId(1, nidMap[nodeIDs[1]]) etype = vtk.vtkLine().GetCellType() for free_edge in free_edges: # (p1, p2) = free_edge for ipoint, node_id in enumerate(free_edge): point = nodes[node_id, :] points.InsertPoint(j + ipoint, *point) elem = vtk.vtkLine() elem.GetPointIds().SetId(0, j) elem.GetPointIds().SetId(1, j + 1) self.alt_grids['free_edges'].InsertNextCell(etype, elem.GetPointIds()) j += 2 self.alt_grids['free_edges'].SetPoints(points) else: # TODO: clear free edges pass if 'free_edges' in self.alt_grids: self._add_alt_actors(self.alt_grids) self.geometry_actors['free_edges'].Modified() if hasattr(self.geometry_actors['free_edges'], 'Update'): self.geometry_actors['free_edges'].Update()
def RenderRay(start, end, rayNumber): print '* * * RenderRay: ', rayNumber print 'ray coords start: ', start print 'ray coords end: ', end p_rays.InsertNextPoint(start) p_rays.InsertNextPoint(end) ray = vtk.vtkLine() ray.GetPointIds().SetId(0,(rayNumber -1)*2) ray.GetPointIds().SetId(1,(rayNumber-1)*2+1) rays.InsertNextCell(ray)
def _createline(self, pointnumbers): if depth(pointnumbers) >= 3: for p in pointnumbers: self._createline(p) else: for i in range(len(pointnumbers) - 1): line = vtk.vtkLine() line.GetPointIds().SetId(0, pointnumbers[i]) line.GetPointIds().SetId(1, pointnumbers[i + 1]) self.lines.InsertNextCell(line) i = i + 1
def RenderTriangleAsLine(points, triangleNumber): print '* * * RenderTriangle: ', triangleNumber print 'Triangle points: ', tri print (triangleNumber-1)*3 p_triangles.InsertNextPoint(points[0]) p_triangles.InsertNextPoint(points[1]) p_triangles.InsertNextPoint(points[2]) line1 = vtk.vtkLine(); line1.GetPointIds().SetId(0, 0+(triangleNumber-1)*3); line1.GetPointIds().SetId(1, 1+(triangleNumber-1)*3); line2 = vtk.vtkLine(); line2.GetPointIds().SetId(0, 0+(triangleNumber-1)*3); line2.GetPointIds().SetId(1, 2+(triangleNumber-1)*3); line3 = vtk.vtkLine(); line3.GetPointIds().SetId(0, 1+(triangleNumber-1)*3); line3.GetPointIds().SetId(1, 2+(triangleNumber-1)*3); triangles.InsertNextCell(line1); triangles.InsertNextCell(line2); triangles.InsertNextCell(line3);
def draw_lines(nodes, color): colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") cnt = 0 noderange = 100 mod = 1 edges = nodes[0].getedges() points = vtk.vtkPoints() lines = vtk.vtkCellArray() nodecnt = 0 while cnt < len(nodes): node = nodes[cnt] cnt += 1 edges = node.getedges() for edge in edges: x0,y0,z0 = edge[0] x1,y1,z1 = edge[1] points.InsertNextPoint(edge[0]) points.InsertNextPoint(edge[1]) line = vtk.vtkLine() line.GetPointIds().SetId(0,nodecnt) line.GetPointIds().SetId(1,nodecnt+1) lines.InsertNextCell(line) nodecnt += 2 colors.InsertNextTupleValue(color) if cnt % mod == 0: print "noderange", noderange, "cnt", cnt, "mod",mod # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(points) # Add the lines to the dataset linesPolyData.SetLines(lines) linesPolyData.GetCellData().SetScalars(colors) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linesPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) renderer.AddActor(actor) points = vtk.vtkPoints() lines = vtk.vtkCellArray() nodecnt = 0 renderWindow.Render() camera = renderer.GetActiveCamera() camera.Azimuth(0.1) print "done!"
def normal_drawer(plane_normal, plane_seed): print( " Drawing plane Normals") for plane in range(len(plane_normal)): pl= plane_seed[plane] pl=pl[pl.find('(') :] pl=pl[pl.find('[')+1 :] pl=pl[: pl.find(']')] pt=pl.split(',') #print(pt) p0x=float(pt[0]) p0y=float(pt[1]) p0z=float(pt[2]) pn=plane_normal[plane] p0 = [p0x, p0y, p0z] p1 = [p0x+pn[0], p0y+pn[1], p0z+pn[2]] # Create a vtkPoints object and store the points in it points = vtk.vtkPoints() #points.InsertNextPoint(origin) points.InsertNextPoint(p0) points.InsertNextPoint(p1) # Create a cell array to store the lines in and add the lines to it lines = vtk.vtkCellArray() line = vtk.vtkLine() line.GetPointIds().SetId(0,0) line.GetPointIds().SetId(1,1) lines.InsertNextCell(line) # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(points) # Add the lines to the dataset linesPolyData.SetLines(lines) # Setup actor and mapper mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(linesPolyData) else: mapper.SetInputData(linesPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(1,0,0) renderer.AddActor(actor)
def draw(self, graphics): cell, pointnums = super(Line, self).draw(graphics) # colour bugfix for polylines for __ in range(len(pointnums) - 2): graphics.colours.InsertNextTupleValue(self.colour or graphics.default_colour) for i in range(len(pointnums) - 1): line = vtk.vtkLine() line.GetPointIds().SetId(0, pointnums[i]) line.GetPointIds().SetId(1, pointnums[i + 1]) cell.InsertNextCell(line) graphics.data.SetLines(cell)
def write_vtk_file( filename, point_data ): ''' Writes a line into a VTK file with given points :param filename: Name of the file e.g. "test.vtk" :param points: Points in a line in array format .. code-block:: python # Example usage: import pytools as pt filename = "test.vtk" point_data = [[0.,0.,0.], [1.,1.,1.], [2.,2.,2.], [3.,3.,3.], [4.,4.,4.]] pt.miscellaneous.write_vtk_file( filename=filename, point_data=point_data ) ''' import vtk # Create a line object ####################################### # Create a vtkPoints object and store the points in it points = vtk.vtkPoints() for point in point_data: points.InsertNextPoint(point) # Create a cell array to store the lines in and add the lines to it lines = vtk.vtkCellArray() for i in range(len(point_data)-1): line = vtk.vtkLine() line.GetPointIds().SetId(0,i) line.GetPointIds().SetId(1,i+1) lines.InsertNextCell(line) # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(points) # Add the lines to the dataset linesPolyData.SetLines(lines) ####################################### # Write the Line object ####################################### polyDataWriter = vtk.vtkPolyDataWriter() polyDataWriter.SetFileName(filename) polyDataWriter.SetInput(linesPolyData) polyDataWriter.Write()
def unstructuredgrid( self, points, npars=None ): """add unstructured grid""" points = _nansplit( points ) #assert isinstance( points, (list,tuple,numpy.ndarray) ), 'Expected list of point arrays' import vtk vtkPoints = vtk.vtkPoints() vtkPoints.SetNumberOfPoints( sum(pts.shape[0] for pts in points) ) cnt = 0 for pts in points: np, ndims = pts.shape if not npars: npars = ndims vtkelem = None if np == 2: vtkelem = vtk.vtkLine() elif np == 3: vtkelem = vtk.vtkTriangle() elif np == 4: if npars == 2: vtkelem = vtk.vtkQuad() elif npars == 3: vtkelem = vtk.vtkTetra() elif np == 8: vtkelem = vtk.vtkVoxel() # TODO hexahedron for not rectilinear NOTE ordering changes! if not vtkelem: raise Exception( 'not sure what to do with cells with ndims=%d and npoints=%d' % (ndims,np) ) if ndims < 3: pts = numpy.concatenate([pts,numpy.zeros(shape=(pts.shape[0],3-ndims))],axis=1) cellpoints = vtkelem.GetPointIds() for i,point in enumerate(pts): vtkPoints .SetPoint( cnt, point ) cellpoints.SetId( i, cnt ) cnt +=1 self.vtkMesh.InsertNextCell( vtkelem.GetCellType(), cellpoints ) self.vtkMesh.SetPoints( vtkPoints )
def drawLineBetweenPoints(self, point1, point2): # Create a vtkPoints object and store the points in it points = vtk.vtkPoints() points.InsertNextPoint(point1) points.InsertNextPoint(point2) # Create line line = vtk.vtkLine() line.GetPointIds().SetId(0,0) line.GetPointIds().SetId(1,1) lineCellArray = vtk.vtkCellArray() lineCellArray.InsertNextCell(line) # Update model data self.line.GetPolyData().SetPoints(points) self.line.GetPolyData().SetLines(lineCellArray)
def setEdges(self, vd): self.edges = [] self.edges = vd.getEdgesGenerators() self.epts = vtk.vtkPoints() nid = 0 lines=vtk.vtkCellArray() for e in self.edges: p1 = e[0] p2 = e[1] self.epts.InsertNextPoint( p1.x, p1.y, p1.z) self.epts.InsertNextPoint( p2.x, p2.y, p2.z) line = vtk.vtkLine() line.GetPointIds().SetId(0,nid) line.GetPointIds().SetId(1,nid+1) nid = nid+2 lines.InsertNextCell(line) linePolyData = vtk.vtkPolyData() linePolyData.SetPoints(self.epts) linePolyData.SetLines(lines) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linePolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor( camvtk.cyan ) myscreen.addActor( actor ) #myscreen.removeActor(e) #e.Delete() #self.edges = [] #for e in vd.getEdgesGenerators(): # ofset = 0 # p1 = e[0] + ofset*e[2] # p2 = e[1] + ofset*e[2] # actor = camvtk.Line( p1=( p1.x,p1.y,p1.z), p2=(p2.x,p2.y,p2.z), color=self.edgeColor ) # myscreen.addActor(actor) # self.edges.append(actor) #actor1 = camvtk.Sphere( center=(p1.x,p1.y,p1.z), radius=2, color=camvtk.pink ) #actor2 = camvtk.Sphere( center=(p2.x,p2.y,p2.z), radius=2, color=camvtk.lgreen ) #myscreen.addActor(actor1) #self.edges.append(actor1) #myscreen.addActor(actor2) #self.edges.append(actor2) myscreen.render()
def drawLine(self, points): try: self.viewer.GetRenderer().RemoveActor(self.actor) self.viewer.GetRenderer().Render() except: pass point1 = points[0] point2 = points[1] points = vtk.vtkPoints() points.SetNumberOfPoints(2) points.Allocate(2) points.InsertPoint(0, point1[0], point1[1], 0.001) points.InsertPoint(1, point2[0], point2[1], 0.001) dist = numpy.sqrt(numpy.square((point1[0]-point2[0])*0.028) + numpy.square((point1[1]-point2[1])*0.030)) self.cells = vtk.vtkCellArray() self.cells.Initialize() line = vtk.vtkLine() line.GetPointIds().SetId(0,0) line.GetPointIds().SetId(1,1) self.cells.InsertNextCell(line) self.poly = vtk.vtkPolyData() self.poly.Initialize() self.poly.SetPoints(points) self.poly.SetLines(self.cells) self.poly.Modified() mapper = vtk.vtkPolyDataMapper2D() #print(dir(mapper)) mapper.SetInput(self.poly) mapper.ScalarVisibilityOn() mapper.SetScalarModeToUsePointData() mapper.Update() self.actor = vtk.vtkActor2D() self.actor.SetMapper(mapper) self.viewer.GetRenderer().AddActor2D(self.actor) self.dist = dist
def plotLineZaxis(self): # Create a vtkPoints object and store the points in it self.pos = [0.0, 0.0, 0.0, 0.0] self.targetFiducial.GetNthFiducialWorldCoordinates(0, self.pos) targetP = [self.pos[i] for i in (0,1,2)] self.surfPoint = [0.0, 0.0, 0.0, 0.0] self.surfaceFiducial.GetNthFiducialWorldCoordinates(0, self.surfPoint) surfaceP = [self.surfPoint[i] for i in (0,1,2)] self.zVector = np.subtract(targetP,surfaceP) points = vtk.vtkPoints() points.InsertNextPoint(targetP) points.InsertNextPoint(surfaceP) # Create line line = vtk.vtkLine() line.GetPointIds().SetId(0,0) line.GetPointIds().SetId(1,1) lineCellArray = vtk.vtkCellArray() lineCellArray.InsertNextCell(line) self.lineNode = slicer.vtkMRMLModelNode() self.lineNode.SetName('LineZ') linePolyData = vtk.vtkPolyData() self.lineNode.SetAndObservePolyData(linePolyData) modelDisplay = slicer.vtkMRMLModelDisplayNode() modelDisplay.SetSliceIntersectionVisibility(True) modelDisplay.SetColor(1,1,1) slicer.mrmlScene.AddNode(modelDisplay) self.lineNode.SetAndObserveDisplayNodeID(modelDisplay.GetID()) slicer.mrmlScene.AddNode(self.lineNode) self.lineNode.GetPolyData().SetPoints(points) self.lineNode.GetPolyData().SetLines(lineCellArray) #self.lineNode.SetAndObserveTransformNodeID(self.boxToReference.GetID()) self.drawPlane(surfaceP, self.zVector) self.definePlaneAxis(surfaceP, self.zVector)
def ModelIni(self): Grid = vtk.vtkPolyData() Points = vtk.vtkPoints() for x in self.Points.Node: Points.InsertNextPoint(x[0],x[1],x[2]) lines = vtk.vtkCellArray() line = vtk.vtkLine() for x in self.element.Line: line.GetPointIds().SetId(0, x[0]) line.GetPointIds().SetId(1, x[1]) lines.InsertNextCell(line) Grid.SetPoints(Points) Grid.SetLines(lines) if vtk.VTK_MAJOR_VERSION <= 5: Grid.Update() source = Grid mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(source) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetColor(255,255,255) renderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renderer.AddActor(actor) renderer.SetBackground(84/255,89/255,109/255) renderer.ResetCamera() renderer.GetActiveCamera().ParallelProjectionOn() renWin.SetSize(600, 600) self.model = {'RenderWindow':renWin, 'iterRender':iren}
def add_line(points, ugrid, phi): """add line to output grid """ # base point x0 = [math.cos(phi) * EMIT_RAD, math.sin(phi) * EMIT_RAD, 0] # unrotated beam end point xdash = EMIT_RAD - Z_LEN * math.atan(THETA) ydash = Z_LEN * math.atan(TAU) # apply rotational matrix on end point in (x,y)-plane x1 = [xdash*math.cos(phi)-ydash*math.sin(phi), xdash*math.sin(phi)+ydash*math.cos(phi), Z_LEN] line = vtk.vtkLine() line.GetPointIds().SetId(0, points.InsertNextPoint(x0)) line.GetPointIds().SetId(1, points.InsertNextPoint(x1)) ugrid.InsertNextCell(line.GetCellType(), line.GetPointIds())
def drawLines(lines): points = vtk.vtkPoints() vtk_lines = vtk.vtkCellArray() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) index = 0 for line in lines: (start, end) = line points.InsertNextPoint(start[0], start[1], start[2]) points.InsertNextPoint(end[0], end[1], end[2]) vtk_line = vtk.vtkLine() vtk_line.GetPointIds().SetId(0, index) vtk_line.GetPointIds().SetId(1, index + 1) index += 2 vtk_lines.InsertNextCell(vtk_line) colors.InsertNextTuple3(0, 0, 0) poly_data = vtk.vtkPolyData() poly_data.SetPoints(points) poly_data.SetLines(vtk_lines) poly_data.GetCellData().SetScalars(colors) return poly_data
def get_linear_cell(cell): """ Get equivalent linear cell to vtkCell cell""" if cell.GetCellType() in (vtk.VTK_POLY_LINE,): linear_cell = vtk.vtkLine() linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0)) linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1)) elif cell.GetCellType() in (vtk.VTK_QUADRATIC_TRIANGLE,): linear_cell = vtk.vtkTriangle() linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0)) linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1)) linear_cell.GetPoints().SetPoint(2, cell.GetPoints().GetPoint(2)) elif cell.GetCellType() in (vtk.VTK_QUADRATIC_TETRA,): linear_cell = vtk.vtkTetra() linear_cell.GetPoints().SetPoint(0, cell.GetPoints().GetPoint(0)) linear_cell.GetPoints().SetPoint(1, cell.GetPoints().GetPoint(1)) linear_cell.GetPoints().SetPoint(2, cell.GetPoints().GetPoint(2)) linear_cell.GetPoints().SetPoint(3, cell.GetPoints().GetPoint(3)) else: linear_cell = cell return linear_cell
def getlsactor(ls): # # import pprint # pprint.pprint(ls) # Create a vtkPoints object and store the points in it points = vtk.vtkPoints() for l in ls: points.InsertNextPoint(l[0]) points.InsertNextPoint(l[1]) # Create a cell array to store the lines in and add the lines to it lines = vtk.vtkCellArray() for i in range(len(ls)): # 长度为线段的条数 line = vtk.vtkLine() line.GetPointIds().SetId(0, 2*i) # ??????????? line.GetPointIds().SetId(1, 2*i+1) lines.InsertNextCell(line) # Create a polydata to store everything in linesPolyData = vtk.vtkPolyData() # Add the points to the dataset linesPolyData.SetPoints(points) # Add the lines to the dataset linesPolyData.SetLines(lines) # Setup actor and mapper mapper = vtk.vtkPolyDataMapper() if vtk.VTK_MAJOR_VERSION <= 5: mapper.SetInput(linesPolyData) else: mapper.SetInputData(linesPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def __init__(self, pointList=[], color=(1,1,1) ): self.src=[] points = vtk.vtkPoints() polyline = vtk.vtkCellArray() idx = 0 first = 1 last_idx = 0 segs=[] for p in pointList: points.InsertNextPoint(p.x, p.y, 0) #print "p = ",p if first==0: seg = [last_idx,idx] segs.append(seg) first = 0 last_idx = idx idx = idx + 1 for seg in segs: line = vtk.vtkLine() line.GetPointIds().SetId(0, seg[0]) line.GetPointIds().SetId(1, seg[1]) #print " indexes: ", seg[0]," to ",seg[1] polyline.InsertNextCell(line) polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(polyline) polydata.Modified() polydata.Update() self.src=polydata self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInput(self.src) self.SetMapper(self.mapper) self.SetColor(color) polydata.Modified() polydata.Update()
def create_actor_polygon(pts, color, **kwargs): """ Creates a VTK actor for rendering polygons. :param pts: points :type pts: vtkFloatArray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) line_width = kwargs.get('size', 1.0) # Create points points = vtk.vtkPoints() points.SetData(pts) # Number of points num_points = points.GetNumberOfPoints() # Create lines cells = vtk.vtkCellArray() for i in range(num_points - 1): line = vtk.vtkLine() line.GetPointIds().SetId(0, i) line.GetPointIds().SetId(1, i + 1) cells.InsertNextCell(line) # Create a PolyData object and add points & lines polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(cells) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) actor.GetProperty().SetLineWidth(line_width) # Return the actor return actor