Esempio n. 1
0
 def _colorPoints(plist, cols, r, alpha):
     n = len(plist)
     if n > len(cols):
         colors.printc("~times Error: mismatch in colorPoints()",
                       n,
                       len(cols),
                       c=1)
         exit()
     if n != len(cols):
         colors.printc("~lightning Warning: mismatch in colorPoints()", n,
                       len(cols))
     src = vtk.vtkPointSource()
     src.SetNumberOfPoints(n)
     src.Update()
     vgf = vtk.vtkVertexGlyphFilter()
     vgf.SetInputData(src.GetOutput())
     vgf.Update()
     pd = vgf.GetOutput()
     ucols = vtk.vtkUnsignedCharArray()
     ucols.SetNumberOfComponents(3)
     ucols.SetName("pointsRGB")
     for i in range(len(plist)):
         c = np.array(colors.getColor(cols[i])) * 255
         ucols.InsertNextTuple3(c[0], c[1], c[2])
     pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))
     pd.GetPointData().SetScalars(ucols)
     actor = Actor(pd, c, alpha)
     actor.mapper.ScalarVisibilityOn()
     actor.GetProperty().SetInterpolationToFlat()
     actor.GetProperty().SetPointSize(r)
     settings.collectable_actors.append(actor)
     return actor
Esempio n. 2
0
    def get_xyz(self, xyz):

        # FIXME: I actually do have to implement this. Sigh.  I have to use point probes to get the values,
        # FIXME: But I can do them all at once to save time. (this is needed during the resample)

        # 1) define point
        # 2) apply filter
        # 3) return point
        point = vtk.vtkPointSource()
        point.SetCenter(xyz)
        point.SetNumberOfPoints(1)
        point.SetRadius(1e-12)
        point.Update()

        output = self.reader.GetOutput()
        b_field = output.GetPointData().GetArray(self.array)
        output.GetPointData().SetVectors(b_field)
        probe = vtk.vtkProbeFilter()
        probe.SetInputConnection(point.GetOutputPort())
        probe.SetSourceData(output)
        probe.Update()

        pointN = dsa.WrapDataObject(probe.GetOutput())
        pVal = pointN.GetPointData().GetArray(self.array)
        # print ("Value: {}".format(pVal.flatten()))

        return pVal.flatten()
Esempio n. 3
0
def removeOutliers(points, radius, c='k', alpha=1, legend=None):
    '''
    Remove outliers from a cloud of points within radius search
    '''
    isactor = False
    if isinstance(points, vtk.vtkActor):
        isactor = True
        poly = vu.polydata(points)
    else:
        src = vtk.vtkPointSource()
        src.SetNumberOfPoints(len(points))
        src.Update()
        vpts = src.GetOutput().GetPoints()
        for i, p in enumerate(points):
            vpts.SetPoint(i, p)
        poly = src.GetOutput()

    removal = vtk.vtkRadiusOutlierRemoval()
    vu.setInput(removal, poly)

    removal.SetRadius(radius)
    removal.SetNumberOfNeighbors(5)
    removal.GenerateOutliersOff()
    removal.Update()
    rpoly = removal.GetOutput()
    print("# of removed outlier points: ", removal.GetNumberOfPointsRemoved(),
          '/', poly.GetNumberOfPoints())
    outpts = []
    for i in range(rpoly.GetNumberOfPoints()):
        outpts.append(list(rpoly.GetPoint(i)))
    outpts = np.array(outpts)
    if not isactor: return outpts

    actor = vs.points(outpts, c=c, alpha=alpha, legend=legend)
    return actor  # return same obj for concatenation
Esempio n. 4
0
 def load_config (self, file):
     debug ("In PointStreamer::load_config ()")
     self.setup_pipeline ()
     val = file.readline ()
     try:
         self.n_pnt, self.strmln_mode, self.integration_mode = eval (val)
     except ValueError: # old format
         self.n_pnt, self.strmln_mode = eval (val)
     # For backward compatibility - the dummy is actually unused.
     dummy_seed = vtk.vtkPointSource ()        
     p = vtkPipeline.vtkMethodParser.VtkPickler ()
     for i in (self.sphere_src, self.sphere_map, self.sphere_act,
               self.sphere_act.GetProperty (),
               dummy_seed, self.strmln, self.ribbonf, self.tubef, 
               self.stream_map, self.stream_act,
               self.stream_act.GetProperty ()):
         p.load (i, file)
     self.setup_stream_pipeline ()
     self.radius = self.sphere_src.GetRadius ()
     self.cen = list (self.sphere_src.GetCenter ())
     self.color_mode = self.strmln.GetSpeedScalars ()
     if self.stream_map.GetScalarVisibility () == 0:
         self.color_mode = -1
     self.do_color_mode ()
     self.update ()
     self.update_integration_mode ()
def points(plist, c='b', tags=[], r=5, alpha=1, legend=None):
    '''
    Build a vtkActor for a list of points.

    c can be a list of [R,G,B] colors of same length as plist
    
    If tags (a list of strings) is specified, is displayed along 
    with the points.
    '''

    if len(plist) == 0: return None
    if vu.isSequence(c) and vu.isSequence(c[0]):
        return _colorPoints(plist, c, r, alpha, legend)

    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(len(plist))
    src.Update()
    pd = src.GetOutput()
    if len(plist) == 1:  #passing just one point
        pd.GetPoints().SetPoint(0, [0, 0, 0])
    else:
        for i, p in enumerate(plist):
            pd.GetPoints().SetPoint(i, p)
    actor = vu.makeActor(pd, c, alpha)
    actor.GetProperty().SetPointSize(r)
    if len(plist) == 1: actor.SetPosition(plist[0])

    if legend: setattr(actor, 'legend', legend)
    return actor
Esempio n. 6
0
def main():
    colors = vtk.vtkNamedColors()

    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetWindowName('InteractorStyleTrackballCamera')

    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)

    # create source
    src = vtk.vtkPointSource()
    src.SetCenter(0, 0, 0)
    src.SetNumberOfPoints(50)
    src.SetRadius(5)
    src.Update()

    actor = point_to_glyph(src.GetOutput().GetPoints(), 0.05)
    actor.GetProperty().SetColor(colors.GetColor3d('Gold'))

    # assign actor to the renderer
    ren.AddActor(actor)
    ren.SetBackground(colors.GetColor3d('RoyalBLue'))

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
Esempio n. 7
0
def _colorPoints(plist, cols, r, alpha, legend):
    n = len(plist)
    if n > len(cols):
        colors.printc("Mismatch in colorPoints()", n, len(cols), c=1)
        exit()
    if n != len(cols):
        colors.printc("Warning: mismatch in colorPoints()", n, len(cols))
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(n)
    src.Update()
    vertexFilter = vtk.vtkVertexGlyphFilter()
    vertexFilter.SetInputData(src.GetOutput())
    vertexFilter.Update()
    pd = vertexFilter.GetOutput()
    ucols = vtk.vtkUnsignedCharArray()
    ucols.SetNumberOfComponents(3)
    ucols.SetName("RGB")
    for i, p in enumerate(plist):
        c = np.array(colors.getColor(cols[i])) * 255
        ucols.InsertNextTuple3(c[0], c[1], c[2])
    pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))
    pd.GetPointData().SetScalars(ucols)
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(pd)
    mapper.ScalarVisibilityOn()
    actor = Actor()  #vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetInterpolationToFlat()
    actor.GetProperty().SetOpacity(alpha)
    actor.GetProperty().SetPointSize(r)
    return actor
Esempio n. 8
0
    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
        source = vtk.vtkPointSource()
        source.SetCenter(0, 0, 0)
        source.SetNumberOfPoints(50)
        source.SetRadius(5.0)
        source.Update()
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 9
0
def extract_probe_data(case_name='windfarm',
                       wind_direction_start=0,
                       wind_direction_end=360,
                       wind_direction_step=10,
                       num_processes=16,
                       probe_location_file='name_x_y_z.txt',
                       offset=0.0,
                       **kwargs):
    import vtk
    from vtk.util import numpy_support as VN
    probe_location_array = np.genfromtxt(probe_location_file, dtype=None)
    probe = vtk.vtkProbeFilter()
    point = vtk.vtkPointSource()
    for wd in range(wind_direction_start, wind_direction_end, wind_direction_step):
        directory = case_name + '_' + str(int(wd)) + '_P' + str(num_processes) + '_OUTPUT'
        filename = case_name + '_' + str(int(wd)) + '.pvd'
        reader = OpenDataFile('./' + directory + '/' + filename)
        local_volume = servermanager.Fetch(reader)
        for location in probe_location_array:
            name = location[0]
            easting = location[1]
            northing = location[2]
            height = location[3] + offset
            point.SetNumberOfPoints(1)
            point.SetCenter([easting, northing, height])
            probe.SetInputConnection(point.GetOutputPort())
            probe.SetSourceData(local_volume)
            probe.Update()
            V = VN.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray('V'))
            ti = VN.vtk_to_numpy(probe.GetOutput().GetPointData().GetArray('ti'))
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_V_x ' + str(V[0][0])
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_V_y ' + str(V[0][1])
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_V_z ' + str(V[0][2])
            print str(wd) + ' ' + name + '_zoffset_' + str(offset) + '_ti ' + str(ti[0] + 0.1)
        def keyPressEvent(obj, event):
            key = obj.GetKeySym()
            #print key
            # translation
            if key == "h":
                #print "key is ",key
                coor = interactor.GetEventPosition()
                #print "click position is ", coor  # coordinate in 2d view
                point = interactor.GetPicker().GetSelectionPoint()
                #print "2d coordinate is", point    # coordinate in 2d view
                interactor.GetPicker().Pick(interactor.GetEventPosition()[0],
                                            interactor.GetEventPosition()[1],
                                            0, renderer)
                picked = interactor.GetPicker().GetPickPosition()
                #print "3d coordinate is ",picked  # this is the true 3d coordinate

                self.points.append(picked)  # add point here
                #print self.points

                ptSrc = vtk.vtkPointSource()
                ptSrc.Update()
                mapper = vtk.vtkPolyDataMapper()
                mapper.SetInputData(ptSrc.GetOutput())
                actor = vtk.vtkActor()
                actor.SetMapper(mapper)
                actor.GetProperty().SetPointSize(5)
                actor.GetProperty().SetColor(1, 0, 0)
                actor.SetPosition(picked)
                renderer.AddActor(actor)
                win.Render()
            elif key == "s":  # save to file
                self._write_points(self.points, save_file)
            else:
                pass
    def create_stream_line(self,y1,y2,y3,n,r=10):

        seeds = vtk.vtkPointSource()
        seeds.SetNumberOfPoints(n)
        seeds.SetCenter(y1, y2, y3)
        seeds.SetRadius(r)
        seeds.SetDistributionToShell()



        integ = vtk.vtkRungeKutta4()
        streamline = vtk.vtkStreamLine()
        streamline.SetInputConnection(self.vec_reader.GetOutputPort())
        streamline.SetSourceConnection(seeds.GetOutputPort())
        streamline.SetMaximumPropagationTime(220)
        streamline.SetIntegrationStepLength(0.05)
        streamline.SetStepLength(0.5)
        streamline.SpeedScalarsOn()
        streamline.SetNumberOfThreads(1)
        streamline.SetIntegrationDirectionToIntegrateBothDirections()

        streamline.SetIntegrator(integ)
        streamline.SetSpeedScalars(220);

        streamlineMapper = vtk.vtkPolyDataMapper()
        streamlineMapper.SetInputConnection(streamline.GetOutputPort())
        streamlineMapper.SetLookupTable(self.arrowColor)


        streamline_actor = vtk.vtkActor()
        streamline_actor.SetMapper(streamlineMapper)
        streamline_actor.VisibilityOn()

        return streamline_actor
Esempio n. 12
0
 def __init__(self,ext_actors=None): #ext_actors is a list of any external vtkActors.
     #initializations:
     self.renderer  = vtk.vtkRenderer()
     self.window    = vtk.vtkRenderWindow()
     self.window.SetSize(1000,1000)
     self.mapper    = vtk.vtkPolyDataMapper()
     self.points    = vtk.vtkPoints()
     self.poly_data = vtk.vtkPolyData()
     self.glyph3d   = vtk.vtkGlyph3D()
     self.actor     = vtk.vtkActor()
     self.point_s   = vtk.vtkPointSource()
     self.sphere    = vtk.vtkSphereSource() 
     self.interactor= vtk.vtkRenderWindowInteractor()
     self.inter_sty = PdbInteractorStyle()
     self.axes_actor= vtk.vtkAxesActor()
     #configurations:
     self.point_s.SetNumberOfPoints(1)
     self.sphere.SetRadius(1.0)
     self.interactor.SetInteractorStyle(self.inter_sty)
     self.interactor.SetRenderWindow(self.window)
     self.axes_actor.SetTotalLength(100,100,100)
     if ext_actors:
         self.ex_actors = ext_actors
     else:
         self.ex_actors=[]
Esempio n. 13
0
def recoSurface(points, bins=256,
                c='gold', alpha=1, wire=False, bc='t', legend=None):
    '''
    Surface reconstruction from sparse points.

    [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/advanced/recosurface.py)  

    ![reco](https://user-images.githubusercontent.com/32848391/46817107-b3263880-cd7e-11e8-985d-f5d158992f0c.png)
    '''

    if isinstance(points, vtk.vtkActor):
        points = points.coordinates()
    N = len(points)
    if N < 50:
        print('recoSurface: Use at least 50 points.')
        return None
    points = np.array(points)

    ptsSource = vtk.vtkPointSource()
    ptsSource.SetNumberOfPoints(N)
    ptsSource.Update()
    vpts = ptsSource.GetOutput().GetPoints()
    for i, p in enumerate(points):
        vpts.SetPoint(i, p)
    polyData = ptsSource.GetOutput()

    distance = vtk.vtkSignedDistance()
    f = 0.1
    x0, x1, y0, y1, z0, z1 = polyData.GetBounds()
    distance.SetBounds(x0-(x1-x0)*f, x1+(x1-x0)*f,
                       y0-(y1-y0)*f, y1+(y1-y0)*f,
                       z0-(z1-z0)*f, z1+(z1-z0)*f)
    if polyData.GetPointData().GetNormals():
        distance.SetInputData(polyData)
    else:
        normals = vtk.vtkPCANormalEstimation()
        normals.SetInputData(polyData)
        normals.SetSampleSize(int(N/50))
        normals.SetNormalOrientationToGraphTraversal()
        distance.SetInputConnection(normals.GetOutputPort())
        print('Recalculating normals for', N,
              'points, sample size=', int(N/50))
        
    b = polyData.GetBounds()
    diagsize = np.sqrt((b[1]-b[0])**2 + (b[3]-b[2])**2 + (b[5]-b[4])**2)
    radius = diagsize/bins*5
    distance.SetRadius(radius)
    distance.SetDimensions(bins, bins, bins)
    distance.Update()

    print('Calculating mesh from points with R =', radius)
    surface = vtk.vtkExtractSurface()
    surface.SetRadius(radius * .99)
    surface.HoleFillingOn()
    surface.ComputeNormalsOff()
    surface.ComputeGradientsOff()
    surface.SetInputConnection(distance.GetOutputPort())
    surface.Update()
    return Actor(surface.GetOutput(), c, alpha, wire, bc, legend)
Esempio n. 14
0
def pointsource(center=[0, 0, 0], radius=1.0, numberofpoints=100):
    """Create a random cloud of points"""
    points = vtk.vtkPointSource()
    points.SetNumberOfPoints(numberofpoints)
    points.SetCenter(center)
    points.SetRadius(radius)
    points.Update()
    return points.GetOutput()
Esempio n. 15
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkPointSource(),
                                       'Processing.', (), ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Esempio n. 16
0
def pointsource(center=[0, 0, 0], radius=1.0, numberofpoints=100):
    """Create a random cloud of points"""
    points = vtk.vtkPointSource()
    points.SetNumberOfPoints(numberofpoints)
    points.SetCenter(center)
    points.SetRadius(radius)
    points.Update()
    return points.GetOutput()
def recoSurface(points,
                bins=256,
                c='gold',
                alpha=1,
                wire=False,
                bc='t',
                edges=False,
                legend=None):
    '''
    Surface reconstruction from sparse points.
    '''

    if isinstance(points, vtk.vtkActor): points = vu.coordinates(points)
    N = len(points)
    if N < 50:
        print('recoSurface: Use at least 50 points.')
        return None
    points = np.array(points)

    ptsSource = vtk.vtkPointSource()
    ptsSource.SetNumberOfPoints(N)
    ptsSource.Update()
    vpts = ptsSource.GetOutput().GetPoints()
    for i, p in enumerate(points):
        vpts.SetPoint(i, p)
    polyData = ptsSource.GetOutput()

    distance = vtk.vtkSignedDistance()
    f = 0.1
    x0, x1, y0, y1, z0, z1 = polyData.GetBounds()
    distance.SetBounds(x0 - (x1 - x0) * f, x1 + (x1 - x0) * f,
                       y0 - (y1 - y0) * f, y1 + (y1 - y0) * f,
                       z0 - (z1 - z0) * f, z1 + (z1 - z0) * f)
    if polyData.GetPointData().GetNormals():
        distance.SetInputData(polyData)
        vu.setInput(distance, polyData)
    else:
        normals = vtk.vtkPCANormalEstimation()
        vu.setInput(normals, polyData)
        normals.SetSampleSize(int(N / 50))
        normals.SetNormalOrientationToGraphTraversal()
        distance.SetInputConnection(normals.GetOutputPort())
        print('Recalculating normals for', N, 'points, sample size=',
              int(N / 50))
    radius = vu.diagonalSize(polyData) / bins * 5
    distance.SetRadius(radius)
    distance.SetDimensions(bins, bins, bins)
    distance.Update()

    print('Calculating mesh from points with R =', radius)
    surface = vtk.vtkExtractSurface()
    surface.SetRadius(radius * .99)
    surface.HoleFillingOn()
    surface.ComputeNormalsOff()
    surface.ComputeGradientsOff()
    surface.SetInputConnection(distance.GetOutputPort())
    surface.Update()
    return vu.makeActor(surface.GetOutput(), c, alpha, wire, bc, edges, legend)
Esempio n. 18
0
def main():
    # Create 5 points (vtkPolyData)
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(5)
    pointSource.Update()

    polydata = pointSource.GetOutput()

    print "points in polydata are", polydata.GetNumberOfPoints()

    # Create 2 points in a vtkUnstructuredGrid
    points = vtk.vtkPoints()
    points.InsertNextPoint(0, 0, 0)
    points.InsertNextPoint(0, 0, 1)

    ug = vtk.vtkUnstructuredGrid()
    ug.SetPoints(points)
    print "points in unstructured grid are", ug.GetNumberOfPoints()

    # Combine the two data sets
    appendFilter = vtk.vtkAppendFilter()
    appendFilter.AddInputData(polydata)
    appendFilter.AddInputData(ug)
    appendFilter.Update()

    combined = vtk.vtkUnstructuredGrid()

    combined = appendFilter.GetOutput()
    print "Combined points are", combined.GetNumberOfPoints()

    # Create a mapper and actor
    colors = vtk.vtkNamedColors()

    mapper = vtk.vtkDataSetMapper()
    mapper.SetInputConnection(appendFilter.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(5)

    # Create a renderer, render window, and interactor
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetRenderWindow(renderWindow)

    # Add the actor to the scene
    renderer.AddActor(actor)
    renderer.SetBackground(colors.GetColor3d("SlateGray"))

    # Render and interact
    renderWindow.Render()
    renderWindowInteractor.Start()
Esempio n. 19
0
    def test_vtk_shananigans(self):
        sphere = vtk.vtkPointSource()
        sphere.SetNumberOfPoints(25)
        mesh = Mesh("data/wing_off_files/synth_wing_v3.off")
        # Triangulate the points with vtkDelaunay3D. This generates a convex hull
        # of tetrahedron.
        delny = vtk.vtkDelaunay3D()
        delny.SetInputConnection(sphere.GetOutputPort())
        delny.SetTolerance(0.01)
        print(dir(mesh.pv_mesh))
        # The triangulation has texture coordinates generated so we can map
        # a texture onto it.
        tmapper = vtk.vtkTextureMapToCylinder()
        tmapper.SetInputDataObject(mesh.pv_mesh.GetPointData().GetOutputPort())
        tmapper.PreventSeamOn()

        # We scale the texture coordinate to get some repeat patterns.
        xform = vtk.vtkTransformTextureCoords()
        xform.SetInputConnection(tmapper.GetOutputPort())
        xform.SetScale(4, 4, 1)

        # vtkDataSetMapper internally uses a vtkGeometryFilter to extract the
        # surface from the triangulation. The output (which is vtkPolyData) is
        # then passed to an internal vtkPolyDataMapper which does the
        # rendering.
        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputConnection(xform.GetOutputPort())

        # A texture is loaded using an image reader. Textures are simply images.
        # The texture is eventually associated with an actor.
        bmpReader = vtk.vtkPNGReader()
        bmpReader.SetFileName("data/textures/checkers.png")
        atext = vtk.vtkTexture()
        atext.SetInputConnection(bmpReader.GetOutputPort())
        atext.InterpolateOn()
        triangulation = vtk.vtkActor()
        triangulation.SetMapper(mapper)
        triangulation.SetTexture(atext)

        # Create the standard rendering stuff.
        ren = vtk.vtkRenderer()
        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        iren = vtk.vtkRenderWindowInteractor()
        iren.SetRenderWindow(renWin)

        # Add the actors to the renderer, set the background and size
        ren.AddActor(triangulation)
        ren.SetBackground(1, 1, 1)
        renWin.SetSize(300, 300)

        iren.Initialize()
        renWin.Render()
        iren.Start()
Esempio n. 20
0
    def __init__(self, center=(0, 0, 0), color=(1, 2, 3)):
        """ create point """
        self.src = vtk.vtkPointSource()
        self.src.SetCenter(center)
        self.src.SetRadius(0)
        self.src.SetNumberOfPoints(1)

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputConnection(self.src.GetOutputPort())
        self.SetMapper(self.mapper)
        self.SetColor(color)
Esempio n. 21
0
    def __init__(self, center=(0,0,0), color=(1,2,3) ):   
        """ create point """
        self.src = vtk.vtkPointSource()
        self.src.SetCenter(center)
        self.src.SetRadius(0)
        self.src.SetNumberOfPoints(1)

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInput(self.src.GetOutput())
        self.SetMapper(self.mapper)
        self.SetColor(color)
Esempio n. 22
0
def ReadPolyData(fileName):
    polyData = vtk.vtkPolyData()
    extension = fileName.split(".")[-1].lower()

    if (extension == "ply"):
        reader = vtk.vtkPLYReader()
        reader.SetFileName(fileName)
        reader.Update()
        polyData = reader.GetOutput()
    elif (extension == "vtp"):
        reader = vtk.vtkXMLPolyDataReader()
        reader.SetFileName(fileName)
        reader.Update()
        polyData = reader.GetOutput()
    elif (extension == "vtk"):
        reader = vtk.vtkPolyDataReader()
        reader.SetFileName(fileName)
        reader.Update()
        polyData = reader.GetOutput()
    elif (extension == "obj"):
        reader = vtk.vtkOBJReader()
        reader.SetFileName(fileName)
        reader.Update()
        polyData = reader.GetOutput()
    elif (extension == "stl"):
        reader = vtk.vtkSTLReader()
        reader.SetFileName(fileName)
        reader.Update()
        polyData = reader.GetOutput()
    elif (extension == "g"):
        reader = vtk.vtkBYUReader()
        reader.SetGeometryFileName(fileName)
        reader.Update()
        polyData = reader.GetOutput()
    else:
        randomSequence = vtk.vtkMinimalStandardRandomSequence()
        randomSequence.SetSeed(8775070)
        points = vtk.vtkPointSource()
        points.SetNumberOfPoints(100000)
        points.SetRadius(10.0)

        # Random position
        x = randomSequence.GetRangeValue(-100, 100)
        randomSequence.Next()
        y = randomSequence.GetRangeValue(-100, 100)
        randomSequence.Next()
        z = randomSequence.GetRangeValue(-100, 100)
        randomSequence.Next()
        points.SetCenter(x, y, z)
        points.SetDistributionToShell()
        points.Update()
        polyData = points.GetOutput()
    return polyData
Esempio n. 23
0
def cluster(points, radius, legend=None):
    '''
    Clustering of points in space.
    radius, is the radius of local search.
    Individual subsets can be accessed through actor.clusters

    [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/clustering.py)    

    ![cluster](https://user-images.githubusercontent.com/32848391/46817286-2039ce00-cd7f-11e8-8b29-42925e03c974.png)
    '''
    if isinstance(points, vtk.vtkActor):
        poly = points.polydata()
    else:
        src = vtk.vtkPointSource()
        src.SetNumberOfPoints(len(points))
        src.Update()
        vpts = src.GetOutput().GetPoints()
        for i, p in enumerate(points):
            vpts.SetPoint(i, p)
        poly = src.GetOutput()

    cluster = vtk.vtkEuclideanClusterExtraction()
    cluster.SetInputData(poly)
    cluster.SetExtractionModeToAllClusters()
    cluster.SetRadius(radius)
    cluster.ColorClustersOn()
    cluster.Update()

    idsarr = cluster.GetOutput().GetPointData().GetArray('ClusterId')
    Nc = cluster.GetNumberOfExtractedClusters()

    sets = [[] for i in range(Nc)]
    for i, p in enumerate(points):
        sets[idsarr.GetValue(i)].append(p)

    acts = []
    for i, aset in enumerate(sets):
        acts.append(vs.points(aset, c=i))

    actor = Assembly(acts, legend=legend)

    actor.info['clusters'] = sets
    print('Nr. of extracted clusters', Nc)
    if Nc > 10:
        print('First ten:')
    for i in range(Nc):
        if i > 9:
            print('...')
            break
        print('Cluster #'+str(i)+',  N =', len(sets[i]))
    print('Access individual clusters through attribute: actor.cluster')
    return actor
Esempio n. 24
0
 def __get_points_object__(xyz):
     """
     get the vtk point object for the location (x,y,z)
     :param xyz: must be in the form (x1,y1,z1),(x2,y2,z2), ..., (xn, yn, zn)]
     :return: vtk point object
     """
     # TODO: Need to fix this to handle all points, not just the first
     source = vtk.vtkPointSource()
     source.SetCenter(xyz[0])
     source.SetRadius(0)
     source.SetNumberOfPoints(1)
     source.Update()
     return source
Esempio n. 25
0
 def save_config (self, file):
     debug ("In PointStreamer::save_config ()")
     file.write ("%d, %d, %d\n"%(self.n_pnt, self.strmln_mode,
                                 self.integration_mode))
     # For backward compatibility - the dummy is actually unused.
     dummy_seed = vtk.vtkPointSource ()
     p = vtkPipeline.vtkMethodParser.VtkPickler ()
     for i in (self.sphere_src, self.sphere_map, self.sphere_act, 
               self.sphere_act.GetProperty (),
               dummy_seed, self.strmln, self.ribbonf, self.tubef, 
               self.stream_map, self.stream_act,
               self.stream_act.GetProperty ()):
         p.dump (i, file)
def main():
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(20)
    pointSource.Update()

    idFilter = vtk.vtkIdFilter()
    idFilter.SetInputConnection(pointSource.GetOutputPort())
    idFilter.SetIdsArrayName("OriginalIds")
    idFilter.Update()

    surfaceFilter = vtk.vtkDataSetSurfaceFilter()
    surfaceFilter.SetInputConnection(idFilter.GetOutputPort())
    surfaceFilter.Update()

    poly_input = surfaceFilter.GetOutput()

    # Create a mapper and actor
    mapper = vtk.vtkPolyDataMapper()

    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInputConnection(poly_input.GetProducerPort())
    else:
        mapper.SetInputData(poly_input)
    mapper.ScalarVisibilityOff()

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # Visualize
    renderer = vtk.vtkRenderer()
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.AddRenderer(renderer)

    areaPicker = vtk.vtkAreaPicker()
    renderWindowInteractor = vtk.vtkRenderWindowInteractor()
    renderWindowInteractor.SetPicker(areaPicker)
    renderWindowInteractor.SetRenderWindow(renderWindow)

    renderer.AddActor(actor)
    #renderer.SetBackground(1,1,1) # Background color white

    renderWindow.Render()

    style = vtk.vtkRenderWindowInteractor()
    #style = myInteractorStyle()
    #style = InteractorStyle()
    #style = QVTKRenderWindowInteractor()
    #style.SetPoints(poly_input)
    renderWindowInteractor.SetInteractorStyle(style)

    renderWindowInteractor.Start()
Esempio n. 27
0
def getpsactor(ps):   # ps 是点云映射到Grid的空间坐标
    # create source
    """
    # vtkPointSource用来创建围绕特定中心点,特定直径的和特定数量点集合组成的球体。
    # 默认点是随机分布在球体里面。也可以生产的点只分布在球面上。
    # 基本用法:
    # SetRadius()设置球体半径
    # SetCenter()设置球体中心点
    # SetNumberOfPoints()设置球中的点的个数
    # SetDistributionToUniform()设置点的分布在球体内
    # SetDistributionToShell()设置点分布在球面上。

    """
    src = vtk.vtkPointSource()
    src.SetCenter(0, 0, 0)       # 设置圆心
    src.SetNumberOfPoints(50)    # 设置点的个数
    src.SetRadius(5)             # 设置半径
    src.Update()                 # ???????
    # ps = [[1,1,1],[2,2,2]]
    # print src.GetOutput()
    points = vtk.vtkPoints()
    vertices = vtk.vtkCellArray()  # 创建一个cell对象
    for p in ps:
    # Create the topology of the point (a vertex)
        id = points.InsertNextPoint(p)
        vertices.InsertNextCell(1)  # 将cell的容量增加1
        vertices.InsertCellPoint(id)  # 将 id所指的点插入cell

    # Create a polydata object  # polydata : 多边形数据
    point = vtk.vtkPolyData()

    # vertex : 顶点  topology:拓扑
    # Set the points and vertices we created as the geometry and topology of the polydata
    point.SetPoints(points)
    point.SetVerts(vertices)
    # mapper
    # mapper = vtk.vtkPolyDataMapper()
    # Visualize
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(point)
    else:
        mapper.SetInputData(point)

    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    # actor.GetProperty().SetPointSize(2)
    # assign actor to the renderer
    return actor
Esempio n. 28
0
def delaunay2D(plist, tol=None, c='gold', alpha=0.5, wire=False, bc=None, edges=False, 
               legend=None, texture=None):
    '''
    Create a mesh from points in the XY plane.
    '''
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(len(plist))
    src.Update()
    pd = src.GetOutput()
    for i,p in enumerate(plist): pd.GetPoints().SetPoint(i, p)
    delny = vtk.vtkDelaunay2D()
    vu.setInput(delny, pd)
    if tol: delny.SetTolerance(tol)
    delny.Update()
    return vu.makeActor(delny.GetOutput(), c, alpha, wire, bc, edges, legend, texture)
Esempio n. 29
0
def cluster(points, radius, legend=None):
    '''
    Clustering of points in space.
    radius, is the radius of local search.
    Individual subsets can be accessed through actor.clusters
    '''
    if isinstance(points, vtk.vtkActor):
        poly = vu.polydata(points)
    else:
        src = vtk.vtkPointSource()
        src.SetNumberOfPoints(len(points))
        src.Update()
        vpts = src.GetOutput().GetPoints()
        for i, p in enumerate(points):
            vpts.SetPoint(i, p)
        poly = src.GetOutput()

    cluster = vtk.vtkEuclideanClusterExtraction()
    vu.setInput(cluster, poly)
    cluster.SetExtractionModeToAllClusters()
    cluster.SetRadius(radius)
    cluster.ColorClustersOn()
    cluster.Update()

    idsarr = cluster.GetOutput().GetPointData().GetArray('ClusterId')
    Nc = cluster.GetNumberOfExtractedClusters()

    sets = [[] for i in range(Nc)]
    for i, p in enumerate(points):
        sets[idsarr.GetValue(i)].append(p)

    acts = []
    for i, aset in enumerate(sets):
        acts.append(vs.points(aset, c=i))

    actor = vu.makeAssembly(acts, legend=legend)
    setattr(actor, 'clusters', sets)
    print('Nr. of extracted clusters', Nc)
    if Nc > 10: print('First ten:')
    for i in range(Nc):
        if i > 9:
            print('...')
            break
        print('Cluster #' + str(i) + ',  N =', len(sets[i]))
    print('Access individual clusters through attribute: actor.cluster')
    return actor
Esempio n. 30
0
    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
        pointSource = vtk.vtkPointSource()
        pointSource.SetNumberOfPoints(5)
        pointSource.Update()

        points = pointSource.GetOutput().GetPoints()
        xSpline = vtk.vtkKochanekSpline()
        ySpline = vtk.vtkKochanekSpline()
        zSpline = vtk.vtkKochanekSpline()

        spline = vtk.vtkParametricSpline()
        spline.SetXSpline(xSpline)
        spline.SetYSpline(ySpline)
        spline.SetZSpline(zSpline)
        spline.SetPoints(points)

        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(spline)
        functionSource.Update()

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(functionSource.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 31
0
    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
        pointSource = vtk.vtkPointSource()
        pointSource.SetNumberOfPoints(5)
        pointSource.Update()

        points = pointSource.GetOutput().GetPoints()
        xSpline = vtk.vtkKochanekSpline()
        ySpline = vtk.vtkKochanekSpline()
        zSpline = vtk.vtkKochanekSpline()

        spline = vtk.vtkParametricSpline()
        spline.SetXSpline(xSpline)
        spline.SetYSpline(ySpline)
        spline.SetZSpline(zSpline)
        spline.SetPoints(points)

        functionSource = vtk.vtkParametricFunctionSource()
        functionSource.SetParametricFunction(spline)
        functionSource.Update()
 
        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(functionSource.GetOutputPort())
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 32
0
    def initialize (self, valid_coord):        
        """ Initializes the seed given an array of valid co-ordinate
        directions. [x-axis, y-axis, z_axis] is the format.  For
        instance if x-axis == 0 then the data is along the YZ plane.
        This method is responsible for actually creating the seed. """

        debug ("In SeedManager::initialize ()")
        assert len (valid_coord) == 3
        self.dim = reduce (lambda x, y: x+y, valid_coord)
        if self.dim == 3:
            self.seed = vtk.vtkPointSource ()
        else:
            self.seed = vtk.vtkDiskSource ()
            self.seed.SetRadialResolution (1)
            self.seed.SetInnerRadius (0.0)
            self.transform = vtk.vtkTransformFilter ()
            self.transform.SetTransform (vtk.vtkTransform ())
            self.transform.SetInput (self.seed.GetOutput ())
            self.orient_2d (valid_coord)
Esempio n. 33
0
def delaunay2D(plist, tol=None, c='gold', alpha=0.5, wire=False, bc=None, edges=False,
               legend=None, texture=None):
    '''
    Create a mesh from points in the XY plane.

    [**Example**](https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/delaunay2d.py)
    '''
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(len(plist))
    src.Update()
    pd = src.GetOutput()
    for i, p in enumerate(plist):
        pd.GetPoints().SetPoint(i, p)
    delny = vtk.vtkDelaunay2D()
    vu.setInput(delny, pd)
    if tol:
        delny.SetTolerance(tol)
    delny.Update()
    return vu.makeActor(delny.GetOutput(), c, alpha, wire, bc, edges, legend, texture)
    def create_stream_line(self,y1,y2,y3,n,r=10,tr=2):

        seeds = vtk.vtkPointSource()
        seeds.SetNumberOfPoints(n)
        seeds.SetCenter(y1, y2, y3)
        seeds.SetRadius(r)
        seeds.SetDistributionToShell()


        integ = vtk.vtkRungeKutta4()
        streamline = vtk.vtkStreamLine()
        streamline.SetInputConnection(self.vec_reader.GetOutputPort())
        streamline.SetSourceConnection(seeds.GetOutputPort())
        streamline.SetMaximumPropagationTime(220)
        streamline.SetIntegrationStepLength(0.05)
        streamline.SetStepLength(0.5)
        streamline.SpeedScalarsOn()
        streamline.SetNumberOfThreads(1)
        streamline.SetIntegrationDirectionToIntegrateBothDirections()
        streamline.SetIntegrator(integ)
        streamline.SetSpeedScalars(220);


        streamline_mapper = vtk.vtkPolyDataMapper()
        streamline_mapper.SetInputConnection(streamline.GetOutputPort())


        streamTube = vtk.vtkTubeFilter()
        streamTube.SetInputConnection(streamline.GetOutputPort())
        streamTube.SetRadius(tr)
        streamTube.SetNumberOfSides(12)
        streamTube.SetVaryRadiusToVaryRadiusByVector()
        mapStreamTube = vtk.vtkPolyDataMapper()
        mapStreamTube.SetInputConnection(streamTube.GetOutputPort())
        mapStreamTube.SetLookupTable(self.arrowColor)

        streamTubeActor = vtk.vtkActor()
        streamTubeActor.SetMapper(mapStreamTube)
        streamTubeActor.GetProperty().BackfaceCullingOn()

        return streamTubeActor
Esempio n. 35
0
def points(plist, r=4, c='k', alpha=1, legend=None):
    '''
    Build a point ``Actor`` for a list of points.

    :param r: point radius.
    :type r: float
    :param c: color name, number, or list of [R,G,B] colors of same length as plist.
    :type c: int, str, list
    :param float alpha: transparency in range [0,1].

    .. hint:: Example: `lorenz.py <https://github.com/marcomusy/vtkplotter/blob/master/examples/basic/lorenz.py>`_

        .. image:: https://user-images.githubusercontent.com/32848391/46818115-be7a6380-cd80-11e8-8ffb-60af2631bf71.png
    '''
    n = len(plist)
    if n == 0:
        return None
    elif n == 3:  # assume plist is in the format [all_x, all_y, all_z]
        if utils.isSequence(plist[0]) and len(plist[0]) > 3:
            plist = list(zip(plist[0], plist[1], plist[2]))
    elif n == 2:  # assume plist is in the format [all_x, all_y, 0]
        if utils.isSequence(plist[0]) and len(plist[0]) > 3:
            plist = list(zip(plist[0], plist[1], [0] * len(plist[0])))

    if utils.isSequence(c) and utils.isSequence(c[0]) and len(c[0]) == 3:
        return _colorPoints(plist, c, r, alpha, legend)

    n = len(plist)  # refresh
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(n)
    src.Update()
    pd = src.GetOutput()
    if n == 1:  # passing just one point
        pd.GetPoints().SetPoint(0, [0, 0, 0])
    else:
        pd.GetPoints().SetData(numpy_to_vtk(plist, deep=True))
    actor = Actor(pd, c, alpha, legend=legend)
    actor.GetProperty().SetPointSize(r)
    if n == 1:
        actor.SetPosition(plist[0])
    return actor
Esempio n. 36
0
def getpsactor(ps):

    # create source
    src = vtk.vtkPointSource()
    src.SetCenter(0, 0, 0)
    src.SetNumberOfPoints(50)
    src.SetRadius(5)
    src.Update()
    # ps = [[1,1,1],[2,2,2]]
    # print src.GetOutput()
    points = vtk.vtkPoints()
    vertices = vtk.vtkCellArray()
    for p in ps:
        # Create the topology of the point (a vertex)
        if len(p) == 2:
            p = [p[0], p[1], 0]
        id = points.InsertNextPoint(p)
        vertices.InsertNextCell(1)
        vertices.InsertCellPoint(id)

    # Create a polydata object
    point = vtk.vtkPolyData()

    # Set the points and vertices we created as the geometry and topology of the polydata
    point.SetPoints(points)
    point.SetVerts(vertices)
    # mapper
    # mapper = vtk.vtkPolyDataMapper()
    # Visualize
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(point)
    else:
        mapper.SetInputData(point)

    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    # actor.GetProperty().SetPointSize(2)
    # assign actor to the renderer
    return actor
Esempio n. 37
0
def loadPCD(filename, c, alpha, legend):
    '''Return vtkActor from Point Cloud file format'''
    if not os.path.exists(filename):
        vc.printc('Error in loadPCD: Cannot find file', filename, c=1)
        return None
    f = open(filename, 'r')
    lines = f.readlines()
    f.close()
    start = False
    pts = []
    N, expN = 0, 0
    for text in lines:
        if start:
            if N >= expN:
                break
            l = text.split()
            pts.append([float(l[0]), float(l[1]), float(l[2])])
            N += 1
        if not start and 'POINTS' in text:
            expN = int(text.split()[1])
        if not start and 'DATA ascii' in text:
            start = True
    if expN != N:
        vc.printc('Mismatch in pcd file', expN, len(pts), c='red')
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(len(pts))
    src.Update()
    poly = src.GetOutput()
    for i, p in enumerate(pts):
        poly.GetPoints().SetPoint(i, p)
    if not poly:
        vc.printc('Unable to load', filename, c='red')
        return False
    actor = vu.makeActor(poly, vc.getColor(c), alpha)
    actor.GetProperty().SetPointSize(4)
    if legend:
        setattr(actor, 'legend', legend)
    if legend is True:
        setattr(actor, 'legend', os.path.basename(filename))
    return actor
Esempio n. 38
0
def make_stream_actors(position, color):
    """Create a stream and use two mappers. One to represent velocity with
    the default colour, and the other to change the colour.
    """
    seed = vtk.vtkPointSource()
    seed.SetRadius(15)
    seed.SetNumberOfPoints(100)
    seed.SetCenter(*position)

    stream_tracer = vtk.vtkStreamTracer()
    stream_tracer.SetInputConnection(mixer.GetOutputPort())
    stream_tracer.SetMaximumPropagation(500)
    stream_tracer.SetIntegrator(vtk.vtkRungeKutta45())
    stream_tracer.SetIntegrationDirectionToBoth()
    stream_tracer.SetTerminalSpeed(0.0001)
    stream_tracer.SetSource(seed.GetOutput())

    stream_tube = vtk.vtkTubeFilter()
    stream_tube.SetInputConnection(stream_tracer.GetOutputPort())
    stream_tube.SetRadius(.2)
    stream_tube.SetNumberOfSides(12)

    # Solid transparent colour
    stream_mapper1 = vtk.vtkPolyDataMapper()
    stream_mapper1.SetInputConnection(stream_tube.GetOutputPort())
    stream_mapper1.ScalarVisibilityOff()

    stream_actor1 = vtk.vtkActor()
    stream_actor1.GetProperty().SetColor(*color)
    stream_actor1.SetMapper(stream_mapper1)
    stream_actor1.GetProperty().SetOpacity(0.4)

    # opaque velocity colour
    stream_mapper2 = vtk.vtkPolyDataMapper()
    stream_mapper2.SetInputConnection(stream_tube.GetOutputPort())

    stream_actor2 = vtk.vtkActor()
    stream_actor2.SetMapper(stream_mapper2)
    stream_actor2.GetProperty().SetOpacity(1.)
    return [stream_actor1, stream_actor2]
Esempio n. 39
0
 def VisVertices(self):
     actor = vtk.vtkActor()
     glyph3d = vtk.vtkGlyph3D()
     point_s = vtk.vtkPointSource()
     mapper = vtk.vtkPolyDataMapper()
     window = vtk.vtkRenderWindow()
     renderer = vtk.vtkRenderer()
     interactor = vtk.vtkRenderWindowInteractor()
     poly_data = vtk.vtkPolyData()
     point_s.SetNumberOfPoints(1)
     interactor.SetRenderWindow(window)
     poly_data.SetPoints(self.points)
     glyph3d.SetSourceConnection(point_s.GetOutputPort())
     glyph3d.SetInputData(poly_data)
     mapper.SetInputConnection(glyph3d.GetOutputPort())
     actor.SetMapper(mapper)
     window.AddRenderer(renderer)
     renderer.AddActor(actor)
     renderer.SetBackground(0.1, 0.2, 0.3)
     renderer.ResetCamera()
     window.Render()
     interactor.Start()
Esempio n. 40
0
def main():
    colors = vtk.vtkNamedColors()

    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)
    renWin.SetWindowName('PointSize')

    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # create source
    src = vtk.vtkPointSource()
    src.SetCenter(0, 0, 0)
    src.SetNumberOfPoints(10)
    src.SetRadius(5)
    src.Update()

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(src.GetOutputPort())

    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(colors.GetColor3d('Yellow'))

    actor.GetProperty().SetPointSize(5)

    # assign actor to the renderer
    ren.AddActor(actor)
    ren.SetBackground(colors.GetColor3d('RoyalBLue'))

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
Esempio n. 41
0
    def __init__(self, zMin=0, zMax=1, maxNumPoints=1e8):
        self.maxNumPoints = maxNumPoints
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(1, 255)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        self.vtkActor.GetProperty().SetPointSize(2)
        self.vtkActor.SetMapper(mapper)
        
        # create source
        src = vtk.vtkPointSource()
        #src.SetCenter(0, 0, 0)
        src.SetNumberOfPoints(50)
        src.SetRadius(5)
        src.Update()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(src.GetOutputPort())
    def __init__(self, zMin=0, zMax=1, maxNumPoints=1e8):
        self.maxNumPoints = maxNumPoints
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(1, 255)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        self.vtkActor.GetProperty().SetPointSize(2)
        self.vtkActor.SetMapper(mapper)

        # create source
        src = vtk.vtkPointSource()
        #src.SetCenter(0, 0, 0)
        src.SetNumberOfPoints(50)
        src.SetRadius(5)
        src.Update()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(src.GetOutputPort())
Esempio n. 43
0
def test():
    # create a rendering window and renderer
    ren = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(ren)

    # create a renderwindowinteractor
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    # create source
    src = vtk.vtkPointSource()
    src.SetCenter(0, 0, 0)
    src.SetNumberOfPoints(50)

    points = np.zeros((50, 3))
    for k in range(50):
        point = 20 * (np.random.rand(3) - 0.5)

    src.SetRadius(5)
    src.Update()

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(src.GetOutputPort())

    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    # assign actor to the renderer
    ren.AddActor(actor)

    # enable user interface interactor
    iren.Initialize()
    renWin.Render()
    iren.Start()
def _colorPoints(plist, cols, r, alpha, legend):
    if len(plist) > len(cols):
        vio.printc(("Mismatch in colorPoints()", len(plist), len(cols)), 1)
        exit()
    if len(plist) != len(cols):
        vio.printc(
            ("Warning: mismatch in colorPoints()", len(plist), len(cols)))
    src = vtk.vtkPointSource()
    src.SetNumberOfPoints(len(plist))
    src.Update()
    vertexFilter = vtk.vtkVertexGlyphFilter()
    vu.setInput(vertexFilter, src.GetOutput())
    vertexFilter.Update()
    pd = vertexFilter.GetOutput()
    ucols = vtk.vtkUnsignedCharArray()
    ucols.SetNumberOfComponents(3)
    ucols.SetName("RGB")
    for i, p in enumerate(plist):
        pd.GetPoints().SetPoint(i, p)
        c = np.array(vc.getColor(cols[i])) * 255
        if vu.vtkMV:
            ucols.InsertNextTuple3(c[0], c[1], c[2])
        else:
            ucols.InsertNextTupleValue(c)
    pd.GetPointData().SetScalars(ucols)
    mapper = vtk.vtkPolyDataMapper()
    vu.setInput(mapper, pd)
    mapper.ScalarVisibilityOn()
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetInterpolationToFlat()
    # check if color string contains a float, in this case ignore alpha
    al = vc.getAlpha(c)
    if al: alpha = al
    actor.GetProperty().SetOpacity(alpha)
    actor.GetProperty().SetPointSize(r)
    return actor
Esempio n. 45
0
import vtk

points = vtk.vtkPointSource()
points.SetCenter(0.0, 0.0, 0.0)
points.SetNumberOfPoints(500)
points.SetRadius(50.0)

m = vtk.vtkPolyDataMapper()
m.SetInput(points.GetOutput())

a = vtk.vtkActor()
a.SetMapper(m)
r = vtk.vtkRenderer()
r.AddActor(a)
w = vtk.vtkRenderWindow()
w.AddRenderer(r)
i = vtk.vtkRenderWindowInteractor()
i.SetRenderWindow(w)

i.Initialize()
i.Start()
Esempio n. 46
0
maxVelocity =reader.GetOutput().GetPointData().GetVectors().GetMaxNorm()
maxTime = 35.0*length/maxVelocity

# Now we will generate multiple streamlines in the data. We create a
# random cloud of points and then use those as integration seeds. We
# select the integration order to use (RungeKutta order 4) and
# associate it with the streamer. The start position is the position
# in world space where we want to begin streamline integration; and we
# integrate in both directions. The step length is the length of the
# line segments that make up the streamline (i.e., related to
# display). The IntegrationStepLength specifies the integration step
# length as a fraction of the cell size that the streamline is in.

# Create source for streamtubes
seeds = vtk.vtkPointSource()
seeds.SetRadius(0.15)
seeds.SetCenter(0.1, 2.1, 0.5)
seeds.SetNumberOfPoints(6)

integ = vtk.vtkRungeKutta4()
streamer = vtk.vtkStreamLine()
streamer.SetInputConnection(reader.GetOutputPort())
streamer.SetSource(seeds.GetOutput())
streamer.SetMaximumPropagationTime(500)
streamer.SetStepLength(0.5)
streamer.SetIntegrationStepLength(0.05)
streamer.SetIntegrationDirectionToIntegrateBothDirections()
streamer.SetIntegrator(integ)

# The tube is wrapped around the generated streamline. By varying the
    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 a set of points
        fixedPointSource = vtk.vtkPointSource()
        fixedPointSource.SetNumberOfPoints(2)

        # Calculate the distance to the camera of each point
        distanceToCamera = vtk.vtkDistanceToCamera()
        distanceToCamera.SetInputConnection(fixedPointSource.GetOutputPort())
        distanceToCamera.SetScreenSize(100.0)

        # Glyph each point with an arrow
        arrow = vtk.vtkArrowSource()
        fixedGlyph = vtk.vtkGlyph3D()
        fixedGlyph.SetInputConnection(distanceToCamera.GetOutputPort())
        fixedGlyph.SetSourceConnection(arrow.GetOutputPort())

        # Scale each point
        fixedGlyph.SetScaleModeToScaleByScalar()
        fixedGlyph.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, 
                "DistanceToCamera")

        # Create a mapper
        fixedMapper = vtk.vtkPolyDataMapper()
        fixedMapper.SetInputConnection(fixedGlyph.GetOutputPort())
        fixedMapper.SetScalarVisibility(False)
 
        # Create an actor
        fixedActor = vtk.vtkActor()
        fixedActor.SetMapper(fixedMapper)
        fixedActor.GetProperty().SetColor(0, 1, 1)

        #............................................................
        # Draw some spheres that get bigger when zooming in.
        # Create a set of points
        pointSource = vtk.vtkPointSource()
        pointSource.SetNumberOfPoints(4)

        # Glyph each point with a sphere
        sphere = vtk.vtkSphereSource()
        glyph = vtk.vtkGlyph3D()
        glyph.SetInputConnection(pointSource.GetOutputPort())
        glyph.SetSourceConnection(sphere.GetOutputPort())
        glyph.SetScaleFactor(0.1)

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(glyph.GetOutputPort())
        mapper.SetScalarVisibility(False)
 
        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        actor.GetProperty().SetColor(0, 1, 1)

        distanceToCamera.SetRenderer(self.ren)

        # Add the actors to the scene
        self.ren.AddActor(fixedActor)
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
Esempio n. 48
0
VTK_DATA_ROOT = vtkGetDataRoot()

# Test label reading from an MNI tag file
#

# The current directory must be writeable.
#
try:
    fname = "mni-tagtest.tag"
    channel = open(fname, "wb")
    channel.close()

    # create some random points in a sphere
    #
    sphere1 = vtk.vtkPointSource()
    sphere1.SetNumberOfPoints(13)

    xform = vtk.vtkTransform()
    xform.RotateWXYZ(20, 1, 0, 0)

    xformFilter = vtk.vtkTransformFilter()
    xformFilter.SetTransform(xform)
    xformFilter.SetInputConnection(sphere1.GetOutputPort())

    labels = vtk.vtkStringArray()
    labels.InsertNextValue("0")
    labels.InsertNextValue("1")
    labels.InsertNextValue("2")
    labels.InsertNextValue("3")
    labels.InsertNextValue("Halifax")
Esempio n. 49
0
#
planeMapper = vtk.vtkDataSetMapper()
planeMapper.SetInputConnection(meshReader.GetOutputPort())
planeMapper.SetScalarRange(meshReader.GetOutput().GetScalarRange())
planeMapper.SetLookupTable(lut)
gridActor = vtk.vtkActor()
gridActor.SetMapper(planeMapper)
gridActor.SetScale(1.0,1.0,0.0000001)
gridActor.GetProperty().SetRepresentationToWireframe()


# create streamlines
#xmin= -1953764.5423199304  xmax= 1473590.7094357659
#ymin= -3071352.8797937827  ymax= 1150611.477018431
seedsSphere = vtk.vtkPointSource()
seedsSphere.SetRadius(1400000.0)
seedsSphere.SetCenter(0.0, 0.0, 0.0)
seedsSphere.SetNumberOfPoints(2000)
seedTransform = vtk.vtkTransform()
seedTransform.Scale(1.0,1.0,0.0)
seedTransform.RotateZ(1.0*float(options.frame)) # 1 degree
seedFilter = vtk.vtkTransformPolyDataFilter()
seedFilter.SetTransform(seedTransform)
seedFilter.SetInputConnection(seedsSphere.GetOutputPort())

integ = vtk.vtkRungeKutta4()
streamer = vtk.vtkStreamTracer()
streamer.SetInputConnection(meshReader.GetOutputPort())
#streamer.SetStartPosition(0.18474886E+01, 0.12918899E+00, 0.00000000E+00)
streamer.SetSource(seedFilter.GetOutput())
Esempio n. 50
0
#!/usr/bin/env python
# Sanjaya Gajurel, Computational Scientist, Case Western Reserve University, April 2015
import sys
import vtk
import os
#------------------------------------------------------------------------------
# Script Entry Point
#------------------------------------------------------------------------------
if __name__ == "__main__":

    print "vtkGraph: Building a graph using Unstructured Grid & dumping it in a vtk file, vertex.vtu, to be visualized using ParaView"

    pointSource = vtk.vtkPointSource()
    pointSource.Update()

    # Create an integer array to store vertex id data & link it with its degree value as a scalar.
    degree  = vtk.vtkIntArray()
    degree.SetNumberOfComponents(1)
    degree.SetName("degree")
    degree.SetNumberOfTuples(7)
    degree.SetValue(0,2)
    degree.SetValue(1,1)
    degree.SetValue(2,3)
    degree.SetValue(3,3)
    degree.SetValue(4,4)
    degree.SetValue(5,2)
    degree.SetValue(6,1)

    pointSource.GetOutput().GetPointData().AddArray(degree)

   # Assign co-ordinates for vertices
Esempio n. 51
0
def main():
    pointSource = vtk.vtkPointSource()
    pointSource.SetNumberOfPoints(50)
    pointSource.Update()

    print("There are %s input points\n" % pointSource.GetOutput().GetNumberOfPoints())

    ids = vtk.vtkIdTypeArray()
    ids.SetNumberOfComponents(1)

    # Set values
    i = 10
    while i < 20:
        ids.InsertNextValue(i)
        i += 1

    selectionNode = vtk.vtkSelectionNode()
    selectionNode.SetFieldType(1) # POINT
    #  CELL_DATA = 0
    #  POINT_DATA = 1
    #  FIELD_DATA = 2
    #  VERTEX_DATA = 3
    #  EDGE_DATA = 4

    selectionNode.SetContentType(4) # INDICES
    #SELECTIONS = 0
    #GLOBALIDS = 1
    #PEDIGREEIDS = 2
    #VALUES = 3
    #INDICES = 4
    #FRUSTUM = 5
    #LOCATIONS = 6
    #THRESHOLDS = 7
    #BLOCKS = 8
    selectionNode.SetSelectionList(ids)

    selection = vtk.vtkSelection()
    selection.AddNode(selectionNode)

    extractSelection = vtk.vtkExtractSelection()

    extractSelection.SetInputConnection(0, pointSource.GetOutputPort())
    if vtk.VTK_MAJOR_VERSION <= 5:
        extractSelection.SetInput(1, selection)
    else:
        extractSelection.SetInputData(1, selection)
    extractSelection.Update()

    # In selection
    selected = vtk.vtkUnstructuredGrid()
    selected.ShallowCopy(extractSelection.GetOutput())

    print("There are %s points in the selection" % selected.GetNumberOfPoints())
    print("There are %s cells in the selection" %selected.GetNumberOfCells())

    # Get points that are NOT in the selection
    # invert the selection
    selectionNode.GetProperties().Set(vtk.vtkSelectionNode.INVERSE(), 1)
    extractSelection.Update()

    notSelected = vtk.vtkUnstructuredGrid()
    notSelected.ShallowCopy(extractSelection.GetOutput())

    print("There are %s points NOT in the selection" % notSelected.GetNumberOfPoints())
    print("There are %s cells NOT in the selection" % notSelected.GetNumberOfCells())

    inputMapper = vtk.vtkDataSetMapper()
    inputMapper.SetInputConnection(pointSource.GetOutputPort())
    inputActor = vtk.vtkActor()
    inputActor.SetMapper(inputMapper)

    selectedMapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        selectedMapper.SetInputConnection(selected.GetProducerPort())
    else:
        selectedMapper.SetInputData(selected)
    selectedActor = vtk.vtkActor()
    selectedActor.SetMapper(selectedMapper)

    notSelectedMapper = vtk.vtkDataSetMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        notSelectedMapper.SetInputConnection(notSelected.GetProducerPort())
    else:
        notSelectedMapper.SetInputData(notSelected)
    notSelectedActor = vtk.vtkActor()
    notSelectedActor.SetMapper(notSelectedMapper)


    # There will be one render window
    renderWindow = vtk.vtkRenderWindow()
    renderWindow.SetSize(900, 300)

    # And one interactor
    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(renderWindow)

    # Define viewport ranges
    # (xmin, ymin, xmax, ymax)
    leftViewport = [0.0, 0.0, 0.33, 1.0]
    centerViewport = [0.33, 0.0, .66, 1.0]
    rightViewport = [0.66, 0.0, 1.0, 1.0]

    # Setup the renderers
    leftRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(leftRenderer)
    leftRenderer.SetViewport(leftViewport)
    leftRenderer.SetBackground(.6, .5, .4)

    centerRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(centerRenderer)
    centerRenderer.SetViewport(centerViewport)
    centerRenderer.SetBackground(.3, .1, .4)

    rightRenderer = vtk.vtkRenderer()
    renderWindow.AddRenderer(rightRenderer)
    rightRenderer.SetViewport(rightViewport)
    rightRenderer.SetBackground(.4, .5, .6)

    leftRenderer.AddActor(inputActor)
    centerRenderer.AddActor(selectedActor)
    rightRenderer.AddActor(notSelectedActor)

    leftRenderer.ResetCamera()
    centerRenderer.ResetCamera()
    rightRenderer.ResetCamera()

    renderWindow.Render()
    interactor.Start()
Esempio n. 52
0
contour_mapper.ScalarVisibilityOff()

contour_actor = vtk.vtkActor()
contour_actor.SetMapper(contour_mapper)
contour_actor.GetProperty().SetColor(.9,.9,.9)
ren.AddActor(contour_actor)


#	Calculating starting point of particles
dims = reader.GetOutput().GetExtent()
cy = (dims[3] - dims[2]) / 4.0
cz = (dims[5] - dims[4]) / 2.0


#	Creation of patricle source 1
particle_source = vtk.vtkPointSource()
particle_source.SetCenter(0, cy, cz)
particle_source.SetRadius(radius)
particle_source.SetNumberOfPoints(num_points)

#	Add streamlines from pointsource
stream_lines = vtk.vtkStreamLine()
stream_lines.SetInputConnection(reader.GetOutputPort())
stream_lines.SetSourceConnection(particle_source.GetOutputPort())
stream_lines.SetStepLength(step_len)
stream_lines.SetMaximumPropagationTime(prop_time)
stream_lines.SetTerminalSpeed(0.05)
stream_lines.SetIntegrationDirectionToForward()

#	Add tube around streamlines
tube_filter = vtk.vtkTubeFilter()
import vtk

# create a rendering window and renderer
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)

# create a renderwindowinteractor
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)


# create source
src = vtk.vtkPointSource()
src.SetCenter(0, 0, 0)
src.SetNumberOfPoints(50)
src.SetRadius(5)
src.Update()


# mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(src.GetOutput())

# actor
actor = vtk.vtkActor()
actor.SetMapper(mapper)

# assign actor to the renderer
ren.AddActor(actor)
Esempio n. 54
0
def test_map_source_object():
    "Returns actor -> mapper -> object."
    obj = vtk.vtkPointSource()
    m, a = map_source_object(obj)
    assert isinstance(m.GetInput(), vtk.vtkObject)
    assert m is a.GetMapper()