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 __create_box(self): xi = yi = 0.1 xf = yf = 200 line_i = vtk.vtkLineSource() line_i.SetPoint1((xi, yi, 0)) line_i.SetPoint2((xf, yi, 0)) self.line_i = line_i self.line_i_actor = self.__create_line_actor(line_i) line_s = vtk.vtkLineSource() line_s.SetPoint1((xi, yf, 0)) line_s.SetPoint2((xf, yf, 0)) self.line_s = line_s self.line_s_actor = self.__create_line_actor(line_s) line_l = vtk.vtkLineSource() line_l.SetPoint1((xi, yi, 0)) line_l.SetPoint2((xi, yf, 0)) self.line_l = line_l self.line_l_actor = self.__create_line_actor(line_l) line_r = vtk.vtkLineSource() line_r.SetPoint1((xf, yi, 0)) line_r.SetPoint2((xf, yf, 0)) self.line_r = line_r self.line_r_actor = self.__create_line_actor(line_r) box_actor = vtk.vtkPropAssembly() box_actor.AddPart(self.line_i_actor) box_actor.AddPart(self.line_s_actor) box_actor.AddPart(self.line_l_actor) box_actor.AddPart(self.line_r_actor) self.box_actor = box_actor
def __init__(self): self._line1 = vtk.vtkLineSource() self._line2 = vtk.vtkLineSource() self.AddInput(self._line1.GetOutput()) self.AddInput(self._line2.GetOutput()) self._center = (0, 0, 0) self._size = 10
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 add_line(self, start, end, color=(0.5, 0.5, 0.5), width=1): """ Adds a line. Args: start: Starting coordinates for line. end: Ending coordinates for line. color: Color for text as RGB. Defaults to grey. width: Width of line. Defaults to 1. """ source = vtk.vtkLineSource() source.SetPoint1(start) source.SetPoint2(end) vertexIDs = vtk.vtkStringArray() vertexIDs.SetNumberOfComponents(1) vertexIDs.SetName("VertexIDs") # Set the vertex labels vertexIDs.InsertNextValue("a") vertexIDs.InsertNextValue("b") source.GetOutput().GetPointData().AddArray(vertexIDs) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) actor.GetProperty().SetLineWidth(width) self.ren.AddActor(actor)
def lines(plist0, plist1=None, lw=1, dotted=False, c='r', alpha=1, legend=None): '''Build the line segments between two lists of points plist0 and plist1. plist0 can be also passed in the form [[point1, point2], ...] ''' if plist1 is not None: plist0 = list(zip(plist0, plist1)) polylns = vtk.vtkAppendPolyData() for twopts in plist0: lineSource = vtk.vtkLineSource() lineSource.SetPoint1(twopts[0]) lineSource.SetPoint2(twopts[1]) polylns.AddInputConnection(lineSource.GetOutputPort()) polylns.Update() actor = vu.makeActor(polylns.GetOutput(), c, alpha, legend=legend) actor.GetProperty().SetLineWidth(lw) if dotted: actor.GetProperty().SetLineStipplePattern(0xf0f0) actor.GetProperty().SetLineStippleRepeatFactor(1) return actor
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 draw_line(self, l): """ """ if l in self.lines: return self.lines.append(l) line = vtk.vtkLineSource() line.SetPoint1(l.p1.x, l.p1.y, l.p1.z) line.SetPoint2(l.p2.x, l.p2.y, l.p2.z) # lineMapper = vtk.vtkPolyDataMapper() # lineMapper.SetInputConnection(line.GetOutputPort()) # lineActor = vtk.vtkActor() # lineActor.SetMapper(lineMapper) tubeFilter = vtk.vtkTubeFilter() tubeFilter.SetInputConnection(line.GetOutputPort()) tubeFilter.SetRadius(l.radius) tubeFilter.SetNumberOfSides(10) tubeFilter.Update() tubeMapper = vtk.vtkPolyDataMapper() tubeMapper.SetInputConnection(tubeFilter.GetOutputPort()) tubeActor = vtk.vtkActor() tubeActor.SetMapper(tubeMapper) tubeActor.GetProperty().SetColor(l.color[0], l.color[1], l.color[2]) self.rend.AddActor(tubeActor) self.tubeActors.append(tubeActor)
def __init__(self, p1, p2, grupo="parede", cor=(128, 128, 128)): """ Construtor da classe Parede. Args: p1 (int[2]): tupla com as posições [x,y] iniciais. p2 (int[2]): tupla com as posições [x,y] finais. grupo (string): Grupo desse elemento. Padrão "parede". cor (int[3]): tupla as 3 componentes RBG 0-255 para cor do elemento. """ Elemento.__init__(self, grupo) self._tipo = "Parede" # transforma os vetores 2d em 3d com z=0 para utilização no VTK self.p1 = np.pad(p1, (0, 1), 'constant') self.p2 = np.pad(p2, (0, 1), 'constant') u = self.p2 - self.p1 self.L = np.linalg.norm(u) N = np.array([-u[1], u[0]]) self.eqreta = np.array([N[0], N[1], np.cross(p1, p2)]) self.normal = N self.C = (self.p1 + self.p2) / 2 #vtk lineSource = vtk.vtkLineSource() lineSource.SetPoint1(self.p1) lineSource.SetPoint2(self.p2) self._set_vtk(lineSource, cor)
def pca(points, pvalue=.95, c='c', alpha=0.5, pcaAxes=False, legend=None): ''' Show the oriented PCA ellipsoid that contains fraction pvalue of points. axes = True, show the 3 PCA semi axes Extra info is stored in actor.sphericity, actor.va, actor.vb, actor.vc (sphericity = 1 for a perfect sphere) ''' try: from scipy.stats import f except: vc.printc("Error in ellipsoid(): scipy not installed. Skip.",1) return None if isinstance(points, vtk.vtkActor): points=vu.coordinates(points) if len(points) == 0: return None P = np.array(points, ndmin=2, dtype=float) cov = np.cov(P, rowvar=0) # covariance matrix U, s, R = np.linalg.svd(cov) # singular value decomposition p, n = s.size, P.shape[0] fppf = f.ppf(pvalue, p, n-p)*(n-1)*p*(n+1)/n/(n-p) # f % point function ua,ub,uc = np.sqrt(s*fppf)*2 # semi-axes (largest first) center = np.mean(P, axis=0) # centroid of the hyperellipsoid sphericity = ( ((ua-ub)/(ua+ub))**2 + ((ua-uc)/(ua+uc))**2 + ((ub-uc)/(ub+uc))**2 )/3. *4. elliSource = vtk.vtkSphereSource() elliSource.SetThetaResolution(48) elliSource.SetPhiResolution(48) matri = vtk.vtkMatrix4x4() matri.DeepCopy((R[0][0] *ua, R[1][0] *ub, R[2][0] *uc, center[0], R[0][1] *ua, R[1][1] *ub, R[2][1] *uc, center[1], R[0][2] *ua, R[1][2] *ub, R[2][2] *uc, center[2], 0,0,0,1)) vtra = vtk.vtkTransform() vtra.SetMatrix(matri) ftra = vtk.vtkTransformFilter() ftra.SetTransform(vtra) ftra.SetInputConnection(elliSource.GetOutputPort()) ftra.Update() actor_elli = vu.makeActor(ftra.GetOutput(), c, alpha, legend=legend) actor_elli.GetProperty().BackfaceCullingOn() actor_elli.GetProperty().SetInterpolationToPhong() if pcaAxes: axs = [] for ax in ([1,0,0], [0,1,0], [0,0,1]): l = vtk.vtkLineSource() l.SetPoint1([0,0,0]) l.SetPoint2(ax) l.Update() t = vtk.vtkTransformFilter() t.SetTransform(vtra) vu.setInput(t, l.GetOutput()) t.Update() axs.append(vu.makeActor(t.GetOutput(), c, alpha)) finact = vu.makeAssembly([actor_elli]+axs, legend=legend) else : finact = actor_elli setattr(finact, 'sphericity', sphericity) setattr(finact, 'va', ua) setattr(finact, 'vb', ub) setattr(finact, 'vc', uc) return finact
def add_edge(self, start, end, colour=Colours.BASE0): """Appends an edge to the edges list.""" # Line line = vtkLineSource() line.SetPoint1(start) line.SetPoint2(end) # Line Mapper line_mapper = vtkPolyDataMapper() line_mapper.SetInputConnection(line.GetOutputPort()) self.edge_colours.append(colour) self.line_mappers.append(line_mapper) # Bar bar = vtkTubeFilter() bar.SetInputConnection(line.GetOutputPort()) bar.SetRadius(2.5) self.bar_data.append(bar) # Bar Mapper # Tried this, but mapping the ribbon caused beaucoup errors, # debugging would take a week.There must be some kind of way # out of here. # Said the joker to the thief # There's too much confusion # I can't get no relief # No reason to get excited, the thief he kindly spoke # But you and I have been through that # And this is not our fate # So let us not talk falsely now, the hour is getting late. # (2011-08-12) bar_mapper = vtkPolyDataMapper() bar_mapper.SetInputConnection(bar.GetOutputPort()) self.bar_mappers.append(bar_mapper)
def createNeedle(length=30.0, transform=vtk.vtkTransform()): """ Create a needle with a given length. The needle is pointing from (0,0,0) into the z-direction. Return an actor for the needle and a filter, which can be used for retrieveing the transformed data to be used for e.g. an intersection """ lineSource = vtk.vtkLineSource() lineSource.SetPoint1(0.0,0.0,0.0) lineSource.SetPoint2(0.0,0.0,length) lineSource.SetResolution(100) lineSource.Update() filt = vtk.vtkTransformPolyDataFilter() filt.SetInputConnection(lineSource.GetOutputPort()) filt.SetTransform(transform) filt.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(filt.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) prop = actor.GetProperty() prop.SetLineWidth(6) prop.SetColor(colors.GetColor3d("Peacock")) renderLinesAsTubes(prop) return actor, filt
def draw_unlit_line(ren, x1, y1, z1, x2, y2, z2, color=[0,0,0], width=1): line = vtk.vtkLineSource() line.SetPoint1(x1,y1,z1) line.SetPoint2(x2,y2,z2) # Create line mapper and actor linem = vtk.vtkPolyDataMapper() linem.SetInputConnection(line.GetOutputPort()) linea = vtk.vtkActor() linea.SetMapper(linem) linea.GetProperty().SetLineWidth(width) linea.GetProperty().SetColor(color) linea.GetProperty().SetLighting(0) # Create tube mapper and actor (filtered line) tubef = vtk.vtkTubeFilter() tubef.SetInputConnection(line.GetOutputPort()) tubef.SetRadius(0.05*width) tubef.SetNumberOfSides(50); tubef.CappingOn() tubef.Update() tubem = vtk.vtkPolyDataMapper() tubem.SetInputConnection(tubef.GetOutputPort()) tubea = vtk.vtkActor() tubea.SetMapper(tubem) tubea.GetProperty().SetColor(color) tubea.GetProperty().SetLighting(0) ren.AddActor(tubea)
def main(): colors = vtk.vtkNamedColors() lines = vtk.vtkLineSource() # Create two points, P0 and P1 p0 = [1.0, 0.0, 0.0] p1 = [5.0, 0.0, 0.0] lines.SetResolution(11) lines.SetPoint1(p0) lines.SetPoint2(p1) lines.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(lines.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetLineWidth(5) actor.GetProperty().SetColor(colors.GetColor3d("Banana")) StippledLine(actor, 0xA1A1, 2) ren1 = vtk.vtkRenderer() ren1.SetBackground(colors.GetColor3d("SlateGray")) renWin = vtk.vtkRenderWindow() renWin.SetSize(640, 480) renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) ren1.AddActor(actor) renWin.Render() iren.Start()
def __init__(self): super(ParticleAdvection, self).__init__(nInputPorts=1, inputType='vtkDataSet', nOutputPorts=1, outputType='vtkUnstructuredGrid') self.Cache = None # Seed for the particles self.Source = vtk.vtkLineSource() self.Source.SetPoint1(3, 0, 0) self.Source.SetPoint2(3, 6, 0) self.Source.SetResolution(20) self.Source.Update() self.NumPts = self.Source.GetOutput().GetNumberOfPoints() # We use the probe filter to sample the input # field at particle locations. self.Probe = vtk.vtkProbeFilter() # Create a polydata to represent the particle locations # at which we will sample the velocity fields. self.ProbePoints = vtk.vtkPolyData() pts = vtk.vtkPoints() self.ProbePoints.SetPoints(pts) self.Probe.SetInputData(self.ProbePoints) self.UpdateTimeIndex = 0
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkLineSource(), 'Processing.', (), ('vtkPolyData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def lines(plist0, plist1=None, lw=1, c='r', alpha=1, dotted=False, legend=None): ''' Build the line segments between two lists of points `plist0` and `plist1`. `plist0` can be also passed in the form ``[[point1, point2], ...]``. .. hint:: Example: `fitspheres2.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/fitspheres2.py>`_ ''' if plist1 is not None: plist0 = list(zip(plist0, plist1)) polylns = vtk.vtkAppendPolyData() for twopts in plist0: lineSource = vtk.vtkLineSource() lineSource.SetPoint1(twopts[0]) lineSource.SetPoint2(twopts[1]) polylns.AddInputConnection(lineSource.GetOutputPort()) polylns.Update() actor = Actor(polylns.GetOutput(), c, alpha, legend=legend) actor.GetProperty().SetLineWidth(lw) if dotted: actor.GetProperty().SetLineStipplePattern(0xf0f0) actor.GetProperty().SetLineStippleRepeatFactor(1) return actor
def initUI(self): self.planes = vtk.vtkPlanes() self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.vtkWidget.GetRenderWindow().GetInteractor().SetInteractorStyle( MainInteractorStyle()) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() self.drawPoint = [[0, 0, 0], [360, 0, 0]] self.loadFile(self._filePath) #================Draw CoordLine================ self.lineSource = vtk.vtkLineSource() self.targetPoint = vtk.vtkSphereSource() self.incidencePoint = vtk.vtkSphereSource() self.drawCoordLine() self.drawCoordPoint() self.initCutPlane() self.initCutSlider() self.initText() # self.initBoxWidget() pass
def __init__(self, center, index, deviation, coord_axis, color): self.coord_axis = coord_axis self.index = index self.end_points = [] self.reset_points = [] # Define the enpoints of the line midpoints = center.copy() for mult in [-.5, 1.]: midpoints[self.index] += mult * deviation self.end_points.append(midpoints.copy()) # Store copy of inital points for resets self.reset_points = copy.deepcopy(self.end_points) # Create the line source self.lineSource = vtk.vtkLineSource() self.lineSource.SetPoint1(*self.end_points[0]) self.lineSource.SetPoint2(*self.end_points[1]) # Create the mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self.lineSource.GetOutputPort()) # Create the mapper self.actor = vtk.vtkActor() self.actor.SetMapper(mapper) self.actor.GetProperty().SetColor(*color) self.actor.GetProperty().SetOpacity(1.)
def __draw_sample_as_line(self,sample,color,warning_color): a = self.__line_actors.get(sample) if a is not None: a.SetVisibility(1) return p1 = sample.coil_center p2 = sample.sphere_intersection p1 = (p2+(p1-p2)/np.linalg.norm(p1-p2)*self.COIL_HEIGHT) #p3 = p1+(p2-p1)*1.2 # an extra 20% to guarantee it goes into the sphere p3 = p1+(p2-p1)*500 source = vtk.vtkLineSource() source.SetPoint1(p1) source.SetPoint2(p3) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.__line_actors[sample]=actor prop = actor.GetProperty() if sample.timing_error > 1: if warning_color is None: warning_color = self.SAMPLE_LINE_WARNING_COLOR prop.SetColor(warning_color) else: if color is None: color = self.SAMPLE_LINE_COLOR prop.SetColor(color) prop.SetAmbient(1.0)
def drawLineBetween2Landmark(self, landmark1ID, landmark2ID, markupsDictionary): markupsNode1 = slicer.mrmlScene.GetNodeByID(self.findMarkupsNodeFromLandmarkID(markupsDictionary, landmark1ID)) markupsNode2 = slicer.mrmlScene.GetNodeByID(self.findMarkupsNodeFromLandmarkID(markupsDictionary, landmark2ID)) landmark1Index = markupsNode1.GetMarkupIndexByID(landmark1ID) landmark2Index = markupsNode2.GetMarkupIndexByID(landmark2ID) coord1 = [-1, -1, -1] coord2 = [-1, -1, -1] markupsNode1.GetNthFiducialPosition(landmark1Index, coord1) markupsNode2.GetNthFiducialPosition(landmark2Index, coord2) line = vtk.vtkLineSource() line.SetPoint1(coord1) line.SetPoint2(coord2) line.Update() mapper = vtk.vtkPolyDataMapper() actor = vtk.vtkActor() mapper.SetInputData(line.GetOutput()) mapper.Update() actor.SetMapper(mapper) layoutManager = slicer.app.layoutManager() threeDWidget = layoutManager.threeDWidget(0) threeDView = threeDWidget.threeDView() renderWindow = threeDView.renderWindow() renderers = renderWindow.GetRenderers() renderer = renderers.GetFirstRenderer() renderWindow.AddRenderer(renderer) renderer.AddActor(actor) renderWindow.Render() return renderer, actor
def __init__(self): ActorFactory.__init__(self) self._Property = vtk.vtkProperty() self._Plane = None self._Line = [] for i in range(4): self._Line.append(vtk.vtkLineSource())
def probeVolume(self, volumeNode, rulerNode): # get ruler ednpoints coordinates in RAS p0ras = rulerNode.GetPolyData().GetPoint(0) + (1,) p1ras = rulerNode.GetPolyData().GetPoint(1) + (1,) # RAS --> IJK ras2ijk = vtk.vtkMatrix4x4() volumeNode.GetRASToIJKMatrix(ras2ijk) p0ijk = [int(round(c)) for c in ras2ijk.MultiplyPoint(p0ras)[:3]] p1ijk = [int(round(c)) for c in ras2ijk.MultiplyPoint(p1ras)[:3]] # Create VTK line that will be used for sampling line = vtk.vtkLineSource() line.SetResolution(100) line.SetPoint1(p0ijk) line.SetPoint2(p1ijk) # Create VTK probe filter and sample the image probe = vtk.vtkProbeFilter() probe .SetInputConnection(line.GetOutputPort()) probe.SetSourceData(volumeNode.GetImageData()) probe.Update() # Return VTK array return probe.GetOutput().GetPointData().GetArray('ImageScalars')
def Lines(plist0, plist1=None, lw=1, c="r", alpha=1, dotted=False): """ Build the line segments between two lists of points `plist0` and `plist1`. `plist0` can be also passed in the form ``[[point1, point2], ...]``. |lines| .. hint:: |fitspheres2.py|_ """ if plist1 is not None: plist0 = list(zip(plist0, plist1)) polylns = vtk.vtkAppendPolyData() for twopts in plist0: lineSource = vtk.vtkLineSource() lineSource.SetPoint1(twopts[0]) lineSource.SetPoint2(twopts[1]) polylns.AddInputConnection(lineSource.GetOutputPort()) polylns.Update() actor = Actor(polylns.GetOutput(), c, alpha) actor.GetProperty().SetLineWidth(lw) if dotted: actor.GetProperty().SetLineStipplePattern(0xF0F0) actor.GetProperty().SetLineStippleRepeatFactor(1) return actor
def add_line_probe(self, name, p0, p1, n_point): """ Create the line probe - VTK object. Parameters ---------- name : str The probe name. p0 : array_like The coordinates of the start point. p1 : array_like The coordinates of the end point. n_point : int The number of probe points. """ line = vtk.vtkLineSource() line.SetPoint1(p0) line.SetPoint2(p1) line.SetResolution(n_point) line.Update() pars = nm.arange(n_point + 1) / nm.float(n_point) self.probes[name] = (line, pars) self.probes_png[name] = False
def _createCylinder(self, endPt1, endPt2, res=20): """ Create a cylinder oriented to have the given end points. :@type endPt1: Vec3f :@param endPt1: The first end point to align the cylinder with. :@type endPt2: Vec3f :@param endPt2: The second end point to align the cylinder with. :@type radius: float :@param radius: The radius of the cylinder. :@type res: int :@param res: The circular resolution of the cylinder (number of sides). Must be at least 3. :@rtype: vtk.vtkActor :@return: A renderable actor representing a cylinder. """ res = 3 if res < 3 else res line = vtk.vtkLineSource() line.SetPoint1(endPt1.x,endPt1.y,endPt1.z) line.SetPoint2(endPt2.x,endPt2.y,endPt2.z) # Create a tube filter to represent the line as a cylinder. tube = vtk.vtkTubeFilter() tube.SetInput(line.GetOutput()) tube.SetRadius(self.actor_radius) tube.SetNumberOfSides(res) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(tube.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def Line(pointa=(-0.5, 0., 0.), pointb=(0.5, 0., 0.), resolution=1): """Create a line. Parameters ---------- pointa : np.ndarray or list Location in [x, y, z]. pointb : np.ndarray or list Location in [x, y, z]. resolution : int number of pieces to divide line into """ if resolution <= 0: raise ValueError('Resolution must be positive') if np.array(pointa).size != 3: raise TypeError('Point A must be a length three tuple of floats.') if np.array(pointb).size != 3: raise TypeError('Point B must be a length three tuple of floats.') src = vtk.vtkLineSource() src.SetPoint1(*pointa) src.SetPoint2(*pointb) src.SetResolution(resolution) src.Update() line = pyvista.wrap(src.GetOutput()) # Compute distance of every point along line compute = lambda p0, p1: np.sqrt(np.sum((p1 - p0)**2, axis=1)) distance = compute(np.array(pointa), line.points) line['Distance'] = distance return line
def sample_vtk(file, p1=None, p2=None, x_c=0, N_points=101, solver=None, verbose=True): """ Samples velocity field in a given VTK file, along a line defined with p1 and p2, or x_c. :param file: Path to the VTK file :type file: str :param p1: Coordinates of the starting point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z] :type p1: list :param p2: Coordinates of the ending point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z] :type p2: list :param x_c: If p1 and p2 are not provided, this parameter serves the x coordinate of the vertical line. :type x_c: float :param N_points: The number of points to sample the velocity in. :type N_points: int """ if verbose: print 'Sampling a VTK file: {}'.format(file) solver = solver or postprocess.determineSolver(file) if type(file) == str: vtkFile = vtkextract.vtkFile() vtkFile.solver = solver vtkFile.readFile(file, verbose=False) else: vtkFile = file centers = vtkFile.getCenters() vtkFile.getVolumes() bounds = vtkFile.bounds p1 = p1 or [x_c, 0, -1] p2 = p2 or [x_c, 0, np.max(bounds[:, 4:])] if len(p1) == 2: p1.insert(1, 0) #if 2D data is provided if len(p2) == 2: p2.insert(1, 0) line = vtk.vtkLineSource() line.SetResolution(N_points - 1) line.SetPoint1(p1) line.SetPoint2(p2) probe = vtk.vtkProbeFilter() probe.SetInputConnection(line.GetOutputPort()) probe.SetSourceConnection(vtkFile.outputPort) probe.Update() probe = probe.GetOutput() vel = probe.GetPointData().GetArray(vtkFile.velArray[solver]) vel = np.array([vel.GetTuple(j) for j in range(probe.GetNumberOfPoints())]) line = np.array( [probe.GetPoint(j) for j in range(probe.GetNumberOfPoints())]) return line, vel
def create_line_actors(self): lm = slicer.app.layoutManager() threeDView = lm.threeDWidget(0).threeDView() renderer = threeDView.renderWindow().GetRenderers().GetFirstRenderer() self.line_actors = [] self.tube_actors = [] self.node_graph_actors_lookup = -1 * np.ones( [len(self.node_array), len(self.node_array)], dtype=int) # By default each connection is connected to every node for i, node_i in enumerate(self.node_array): current_line_actors = [] for j in range(i + 1, len(self.node_array)): node_j = self.node_array[j] self.list_index = i self.node_graph_actors_lookup[i][j] = len(self.line_actors) # instantiate two dictionnaries line = {} tube = {} line['source'] = vtk.vtkLineSource() line['source'].SetPoint1(node_i['coord']) line['source'].SetPoint2(node_j['coord']) line['seed'] = node_i line['target'] = node_j #create mapper and actor line['actor'] = vtk.vtkActor() line_mapper = vtk.vtkPolyDataMapper() line_mapper.SetInputConnection(line['source'].GetOutputPort()) line['actor'].SetMapper(line_mapper) line['actor'].GetProperty().SetOpacity(0.1) renderer.AddActor(line['actor']) self.line_actors.append(line) # Add a tube around each line tube['filter'] = vtk.vtkTubeFilter() tube['filter'].SetInputConnection( line['source'].GetOutputPort()) tube['filter'].SetRadius(0.5) tube['filter'].SetNumberOfSides(3) #create mapper and actor tube['actor'] = vtk.vtkActor() tube['mapper'] = vtk.vtkPolyDataMapper() tube['mapper'].SetInputConnection( tube['filter'].GetOutputPort()) tube['actor'].GetProperty().SetOpacity(1) tube['actor'].SetMapper(tube['mapper']) renderer.AddActor(tube['actor']) self.tube_actors.append(tube)
def _create_geometry(self): self._line_source = vtk.vtkLineSource() m = vtk.vtkPolyDataMapper() m.SetInput(self._line_source.GetOutput()) a = vtk.vtkActor() a.SetMapper(m) a.GetProperty().SetColor(0.0, 0.0, 0.0) self.props = [a]
def starInterpolation(self, data, xy, h): """ Interpolate along a star stencil @param data either self.refData or self.spcData @param xy x and y coordinates at center of stencil @param h excursion from the center @return {'w': value, 'e': value, 'n': value, 's': value} """ lineX = vtk.vtkLineSource() lineX.SetPoint1(xy[0] - h, xy[1], 0.0) lineX.SetPoint2(xy[0] + h, xy[1], 0.0) lineX.SetResolution(1) lineY = vtk.vtkLineSource() lineY.SetPoint1(xy[0], xy[1] - h, 0.0) lineY.SetPoint2(xy[0], xy[1] + h, 0.0) lineY.SetResolution(1) probeX = vtk.vtkProbeFilter() if vtk.VTK_MAJOR_VERSION >= 6: probeX.SetSourceData(data['polydata']) else: probeX.SetSource(data['polydata']) probeX.SetInputConnection(lineX.GetOutputPort()) probeX.Update() probeY = vtk.vtkProbeFilter() if vtk.VTK_MAJOR_VERSION >= 6: probeY.SetSourceData(data['polydata']) else: probeY.SetSource(data['polydata']) probeY.SetInputConnection(lineY.GetOutputPort()) probeY.Update() res = {} # west and east res['w'] = probeX.GetOutput().GetPointData().GetArray(0).GetTuple(0) res['e'] = probeX.GetOutput().GetPointData().GetArray(0).GetTuple(1) # south and north res['s'] = probeY.GetOutput().GetPointData().GetArray(0).GetTuple(0) res['n'] = probeY.GetOutput().GetPointData().GetArray(0).GetTuple(1) return res
def createLine1(): lineSource = vtk.vtkLineSource() lineSource.SetPoint1(p1) lineSource.SetPoint2(p2) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(lineSource.GetOutputPort()) return mapper
def create_line(p1, p2, sample_points): # Create the line along which you want to sample line = vtk.vtkLineSource() line.SetResolution(sample_points) line.SetPoint1(p1) line.SetPoint2(p2) line.Update() return line
def createVtkLine(self, p1, p2, numPoints): # Create the line along which you want to sample along line = vtk.vtkLineSource() line.SetResolution(numPoints) line.SetPoint1(p1) line.SetPoint2(p2) line.Update() return line
def createLine(p1,p2,numPoints): # Create the line along which you want to sample line = vtk.vtkLineSource() line.SetResolution(numPoints) line.SetPoint1(p1) line.SetPoint2(p2) line.Update() return line
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkLineSource(), 'Processing.', (), ('vtkPolyData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def _create_geometry(self): self._line_source = vtk.vtkLineSource() m = vtk.vtkPolyDataMapper() m.SetInputConnection(self._line_source.GetOutputPort()) a = vtk.vtkActor() a.SetMapper(m) a.GetProperty().SetColor(0.0, 0.0, 0.0) self.props = [a]
def __init__(self,p1=(0,0,0) , p2=(1,1,1), color=(0,1,1) ): """ line """ self.src = vtk.vtkLineSource() self.src.SetPoint1(p1) self.src.SetPoint2(p2) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInput(self.src.GetOutput()) self.SetMapper(self.mapper) self.SetColor(color)
def get_line_actor(p0,p1): source = vtk.vtkLineSource() source.SetPoint1(p0) source.SetPoint2(p1) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def __init__(self,source): self.line = vtk.vtkLineSource() self.line.SetResolution(800) self.line.SetPoint1(0,800,0) self.line.SetPoint2(800,800,0) self.SetInputConnection(self.line.GetOutputPort()) self.SetSource(source) '''
def __init__(self, p1=(0, 0, 0), p2=(1, 1, 1), color=(0, 1, 1)): """ line """ self.src = vtk.vtkLineSource() self.src.SetPoint1(p1) self.src.SetPoint2(p2) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.src.GetOutputPort()) self.SetMapper(self.mapper) self.SetColor(color)
def make_scaleBar_actor(O, N): x0 = float(O[0]) x1 = float(O[1]) x2 = float(O[2]) #(x0-y0)*N[0]+(x1-y1)*N[1] + (x2-y2)*N[2] = 0 #(x0-y0)^2+(x1-y1)^2 + (x2-y2)^2 = 100^2 #y1 = (x2-y2)*N[2]/N[1]+x1 #y1 = x1 + sqrt(100^2 - (x2-y2)^2) if max(N) == N[0]: y0 = x0 if N[1] == 0. and N[2] == 0.: y2 = x2 + 66 y1 = x1 elif N[1] == 0: y1 = x1 + 66 / (1 + (N[1] / N[2])) y2 = (x1 - y1) * (N[1] / N[2]) + x1 else: y2 = x2 + 66 / (1 + (N[2] / N[1])) y1 = (x2 - y2) * (N[2] / N[1]) + x1 elif max(N) == N[1]: y1 = x1 if N[0] == 0. and N[2] == 0.: y2 = x2 y0 = x0 + 66 elif N[2] == 0: y2 = x2 + 66 / (1 + (N[2] / N[0])) y0 = (x2 - y2) * (N[2] / N[0]) + x0 else: y2 = x2 + 66 / (1 + (N[2] / N[0])) y0 = (x2 - y2) * (N[2] / N[0]) + x0 else: y2 = x2 if N[1] == 0. and N[0] == 0.: y1 = x1 + 66 y0 = x0 elif N[1] == 0: y1 = x1 + 66 / (1 + (N[1] / N[0])) y0 = (x1 - y1) * (N[1] / N[0]) + x0 else: y1 = x1 + 66 / (1 + (N[1] / N[0])) y0 = (x1 - y1) * (N[1] / N[0]) + x0 sbSource = vtk.vtkLineSource() sbSource.SetPoint1(x0, x1, x2) sbSource.SetPoint2(y0, y1, y2) sbMapper = vtk.vtkPolyDataMapper() sbMapper.SetInputConnection(sbSource.GetOutputPort()) #create an actor sbActor = vtk.vtkActor() sbActor.SetMapper(sbMapper) sbActor.GetProperty().SetColor(0, 0, 0) sbActor.GetProperty().SetOpacity(1) sbActor.GetProperty().SetLineWidth(2) return sbActor
def __init__(self): ActorFactory.__init__(self) self.cubeactors = [] self._FaceProperty = vtk.vtkProperty() self._FaceProperty.SetOpacity(0.0002) self._FaceProperty.SetRepresentationToWireframe() self._EdgeProperty = vtk.vtkProperty() self._EdgeProperty.SetColor(1, 0, 0) self._EdgeProperty.SetOpacity(0.0) self._ClippingPlanes = [] for i in range(6): self._ClippingPlanes.append(vtk.vtkPlane()) self._ClippingPlanesCollection = None self._LineSources = [] self._PlaneSources = [] self._Planes = [] self._Plane = None self._Bounds = (-0.5, +0.5, -0.5, +0.5, -0.5, +0.5) bounds = self._Bounds self._Vertices = [[bounds[0], bounds[2], bounds[4]], [bounds[1], bounds[2], bounds[4]], [bounds[0], bounds[3], bounds[4]], [bounds[1], bounds[3], bounds[4]], [bounds[0], bounds[2], bounds[5]], [bounds[1], bounds[2], bounds[5]], [bounds[0], bounds[3], bounds[5]], [bounds[1], bounds[3], bounds[5]]] self._PlaneVertexIndices = ((0, 2, 4), (7, 3, 5), (0, 4, 1), (7, 6, 3), (0, 1, 2), (7, 5, 6)) self._LineVertexIndices = ((0, 1), (2, 3), (4, 5), (6, 7), (0, 2), (1, 3), (4, 6), (5, 7), (0, 4), (1, 5), (2, 6), (3, 7)) for i in range(12): self._LineSources.append(vtk.vtkLineSource()) for i in range(6): self._PlaneSources.append(vtk.vtkPlaneSource()) plane = ClippingCubeFacePlane(self, self._Vertices, i) self._Planes.append(plane) self._ResetPlanes() self.BindEvent("<ButtonPress>", self.DoStartAction) self.BindEvent("<ButtonRelease>", self.DoEndAction) self.BindEvent("<Motion>", self.DoPush) self.ShowCubeWhenPicked = 0
def addLine(pos1, pos2, color): source = vtk.vtkLineSource() source.SetPoint1(*pos1) source.SetPoint2(*pos2) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(source.GetOutput()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) ren.AddActor(actor)
def createLine(self, p1, p2, numPoints): """ Create the sample line """ line = vtk.vtkLineSource() line.SetResolution(numPoints) line.SetPoint1(p1) line.SetPoint2(p2) line.Update() return line
def __init__(self): self._lines = [] for i in range(4): line = vtk.vtkLineSource() self._lines.append(line) self.AddInput(line.GetOutput()) self._bounds = None self._center = None self._sizes = None
def drawLine(self, start, end, color): line = vtk.vtkLineSource() line.SetPoint1(start) line.SetPoint2(end) line.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(line.GetOutput()) self.addActor(mapper, color)
def getElasticLink(self, nodeA, nodeB): source = vtk.vtkLineSource() source.SetPoint1(nodeA.x, nodeA.y, nodeA.z) source.SetPoint2(nodeB.x, nodeB.y, nodeB.z) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(0/255,255/255,152/255) return actor
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._input_data = None self._output_dict = {} # polydata pipeline to make crosshairs self._ls1 = vtk.vtkLineSource() self._ls2 = vtk.vtkLineSource() self._ls3 = vtk.vtkLineSource() self._append_pd = vtk.vtkAppendPolyData() self._append_pd.AddInput(self._ls1.GetOutput()) self._append_pd.AddInput(self._ls2.GetOutput()) self._append_pd.AddInput(self._ls3.GetOutput()) NoConfigModuleMixin.__init__( self, {'Module (self)' : self}) self.sync_module_logic_with_config()
def draw_axis(self): """ """ xaxis = vtk.vtkLineSource() xaxis.SetPoint1(0,0,0) xaxis.SetPoint2(1,0,0) xmapper = vtk.vtkPolyDataMapper() xmapper.SetInputConnection(xaxis.GetOutputPort()) xactor = vtk.vtkActor() xactor.SetMapper(xmapper) xactor.GetProperty().SetColor(1,0,0) yaxis = vtk.vtkLineSource() yaxis.SetPoint1(0,0,0) yaxis.SetPoint2(0,1,0) ymapper = vtk.vtkPolyDataMapper() ymapper.SetInputConnection(yaxis.GetOutputPort()) yactor = vtk.vtkActor() yactor.SetMapper(ymapper) yactor.GetProperty().SetColor(0,1,0) zaxis = vtk.vtkLineSource() zaxis.SetPoint1(0,0,0) zaxis.SetPoint2(0,0,1) zmapper = vtk.vtkPolyDataMapper() zmapper.SetInputConnection(zaxis.GetOutputPort()) zactor = vtk.vtkActor() zactor.SetMapper(zmapper) zactor.GetProperty().SetColor(0,0,1) self.rend.AddActor(xactor) self.rend.AddActor(yactor) self.rend.AddActor(zactor)
def sample_vtk(file, p1=None, p2=None, x_c=0, N_points=101, solver=None, verbose=True): """ Samples velocity field in a given VTK file, along a line defined with p1 and p2, or x_c. :param file: Path to the VTK file :type file: str :param p1: Coordinates of the starting point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z] :type p1: list :param p2: Coordinates of the ending point of the sample line. Can be either 2D or 3D [x, y] or [x, y, z] :type p2: list :param x_c: If p1 and p2 are not provided, this parameter serves the x coordinate of the vertical line. :type x_c: float :param N_points: The number of points to sample the velocity in. :type N_points: int """ if verbose: print 'Sampling a VTK file: {}'.format(file) solver=solver or postprocess.determineSolver(file) if type(file) == str: vtkFile = vtkextract.vtkFile() vtkFile.solver = solver vtkFile.readFile(file, verbose=False) else: vtkFile = file centers = vtkFile.getCenters() vtkFile.getVolumes() bounds = vtkFile.bounds p1 = p1 or [x_c, 0, -1] p2 = p2 or [x_c, 0, np.max(bounds[:, 4:])] if len(p1) == 2: p1.insert(1, 0) #if 2D data is provided if len(p2) == 2: p2.insert(1, 0) line = vtk.vtkLineSource() line.SetResolution(N_points - 1) line.SetPoint1(p1) line.SetPoint2(p2) probe = vtk.vtkProbeFilter() probe.SetInputConnection(line.GetOutputPort()) probe.SetSourceConnection(vtkFile.outputPort) probe.Update() probe = probe.GetOutput() vel=probe.GetPointData().GetArray(vtkFile.velArray[solver]) vel=np.array([vel.GetTuple(j) for j in range(probe.GetNumberOfPoints())]) line=np.array([probe.GetPoint(j) for j in range(probe.GetNumberOfPoints())]) return line, vel
def addline(pos1,pos2,color=(1,0,0),res=1): line=vtk.vtkLineSource() line.SetResolution(res) line.SetPoint1(pos1) line.SetPoint2(pos2) linem = vtk.vtkPolyDataMapper() linem.SetInput(line.GetOutput()) linea = vtk.vtkActor() linea.SetMapper(linem) linea.GetProperty().SetColor(color) return linea
def addLine(renderer, p1, p2, color=[0.0,0.0,1.0]): line = vtk.vtkLineSource() line.SetPoint1(p1) line.SetPoint2(p2) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(line.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(color) renderer.AddActor(actor)
def GenerateCicleSegment(self, t): """ Generate cicle segment """ x = self.posc_a + self.radius * cos(t) y = self.posc_b + self.radius * sin(t) ls = vtk.vtkLineSource() ls.SetPoint1(self.xa, self.ya, 0) ls.SetPoint2(x, y, 0) self.segment.AddInput(ls.GetOutput()) self.xa, self.ya = x, y
def __add_line_to_ren(origin, vec, ren): import vtk p1 = origin p2 = np.array(origin) + np.array(vec) source = vtk.vtkLineSource() source.SetPoint1(p1) source.SetPoint2(p2) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(source.GetOutputPort()) ac = vtk.vtkActor() ac.SetMapper(mapper) ren.AddActor(ac) return ac