Python vtk.vtkPoints() Examples

The following are 30 code examples of vtk.vtkPoints(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module vtk , or try the search function .
Example #1
Source File: vis.py    From DeepV2D with BSD 3-Clause "New" or "Revised" License 11 votes vote down vote up
def create_pointcloud_polydata(points, colors=None):
    """https://github.com/lmb-freiburg/demon
    Creates a vtkPolyData object with the point cloud from numpy arrays
    
    points: numpy.ndarray
        pointcloud with shape (n,3)
    
    colors: numpy.ndarray
        uint8 array with colors for each point. shape is (n,3)

    Returns vtkPolyData object
    """
    vpoints = vtk.vtkPoints()
    vpoints.SetNumberOfPoints(points.shape[0])
    for i in range(points.shape[0]):
        vpoints.SetPoint(i, points[i])
    vpoly = vtk.vtkPolyData()
    vpoly.SetPoints(vpoints)
    
    if not colors is None:
        vcolors = vtk.vtkUnsignedCharArray()
        vcolors.SetNumberOfComponents(3)
        vcolors.SetName("Colors")
        vcolors.SetNumberOfTuples(points.shape[0])
        for i in range(points.shape[0]):
            vcolors.SetTuple3(i ,colors[i,0],colors[i,1], colors[i,2])
        vpoly.GetPointData().SetScalars(vcolors)

    vcells = vtk.vtkCellArray()
    
    for i in range(points.shape[0]):
        vcells.InsertNextCell(1)
        vcells.InsertCellPoint(i)
        
    vpoly.SetVerts(vcells)
    
    return vpoly 
Example #2
Source File: vtkModule.py    From discretize with MIT License 7 votes vote down vote up
def __create_structured_grid(ptsMat, dims, models=None):
        """An internal helper to build out structured grids"""
        # Adjust if result was 2D:
        if ptsMat.shape[1] == 2:
            # Figure out which dim is null
            nullDim = dims.index(None)
            ptsMat = np.insert(ptsMat, nullDim, np.zeros(ptsMat.shape[0]), axis=1)
        if ptsMat.shape[1] != 3:
            raise RuntimeError('Points of the mesh are improperly defined.')
        # Convert the points
        vtkPts = _vtk.vtkPoints()
        vtkPts.SetData(_nps.numpy_to_vtk(ptsMat, deep=True))
        # Uncover hidden dimension
        for i, d in enumerate(dims):
            if d is None:
                dims[i] = 0
            dims[i] = dims[i] + 1
        output = _vtk.vtkStructuredGrid()
        output.SetDimensions(dims[0], dims[1], dims[2]) # note this subtracts 1
        output.SetPoints(vtkPts)
        # Assign the model('s) to the object
        return assign_cell_data(output, models=models) 
Example #3
Source File: visualization_3d.py    From gempy with GNU Lesser General Public License v3.0 7 votes vote down vote up
def create_surface_points(self, vertices):
        """
        Method to create the points that form the surfaces
        Args:
            vertices (numpy.array): 2D array (XYZ) with the coordinates of the points

        Returns:
            vtk.vtkPoints: with the coordinates of the points
        """
        Points = vtk.vtkPoints()
        if self.ve != 1:
            vertices[:, 2] = vertices[:, 2] * self.ve
        #     raise NotImplementedError('Vertical exageration for surfaces not implemented yet.')
        # for v in vertices:
        #     v[-1] = self.ve * v[-1]
        #     Points.InsertNextPoint(v)
        Points.SetData(numpy_to_vtk(vertices))

        return Points 
Example #4
Source File: plot_cosipy_fields_vtk.py    From cosipy with GNU General Public License v3.0 7 votes vote down vote up
def createDEM_v2():

    ds = xr.open_dataset('../data/output/Peru_20160601-20180530_comp4.nc')
    
    points = vtk.vtkPoints()
    quad = vtk.vtkQuad()
    cells = vtk.vtkCellArray()
    
    numPoints = ds.south_north.size*ds.west_east.size
   
    print('Write points \n')
    for i,j in product(ds.south_north.values,ds.west_east.values):
            points.InsertNextPoint(ds.lat.isel(south_north=i,west_east=j), ds.lon.isel(south_north=i,west_east=j), ds.HGT.sel(south_north=i,west_east=j).values/6370000.0)
    
    print('Write cells \n')
    for idx in range(points.GetNumberOfPoints()-ds.west_east.size):
        if (idx%ds.west_east.size != 0):
            quad.GetPointIds().SetId(0,idx)
            quad.GetPointIds().SetId(1,idx+1)
            quad.GetPointIds().SetId(2,idx+ds.west_east.size+1)
            quad.GetPointIds().SetId(3,idx+ds.west_east.size)
            cells.InsertNextCell(quad)

    print('Create unstructured grid \n') 
    grid = vtk.vtkUnstructuredGrid()
    grid.SetPoints(points)
    grid.SetCells(vtk.VTK_QUAD, cells)
    
    writer = vtk.vtkXMLUnstructuredGridWriter()
    writer.SetFileName('cosipy.vtu')
    writer.SetInputData(grid)
    writer.Write() 
Example #5
Source File: visualization.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def face_points2actor(fps_df):

    cell_array = vtk.vtkCellArray()
    points = vtk.vtkPoints()
    point_id = 0
    for i in range(fps_df.shape[0]):
        polygon = vtk.vtkPolygon()
        polygon.GetPointIds().SetNumberOfIds(3)
        for n in range(3):
            points.InsertNextPoint(fps_df.ix[i, 0+3*n], fps_df.ix[i, 1+3*n], fps_df.ix[i, 2+3*n])
            polygon.GetPointIds().SetId(n, point_id)
            point_id += 1
        cell_array.InsertNextCell(polygon)
    polydata = vtk.vtkPolyData()
    polydata.SetPoints(points)
    polydata.SetPolys(cell_array)

    # mapper
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(polydata)
    # actor
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    return actor, polydata 
Example #6
Source File: pointobject.py    From Det3D with Apache License 2.0 6 votes vote down vote up
def CreateTriangles(self, pc, triangles):
        "Create a mesh from triangles"

        self.verts = vtk.vtkPoints()
        self.points_npy = pc[:, :3].copy()
        self.verts.SetData(numpy_support.numpy_to_vtk(self.points_npy))

        nTri = len(triangles)
        self.cells = vtk.vtkCellArray()
        self.pd = vtk.vtkPolyData()
        # - Note that the cell array looks like this: [3 vtx0 vtx1 vtx2 3 vtx3 ... ]
        self.cells_npy = np.column_stack(
            [np.full(nTri, 3, dtype=np.int64), triangles.astype(np.int64)]
        ).ravel()
        self.cells.SetCells(nTri, numpy_support.numpy_to_vtkIdTypeArray(self.cells_npy))

        self.pd.SetPoints(self.verts)
        self.pd.SetPolys(self.cells)

        self.SetupPipelineMesh() 
Example #7
Source File: kinect3Dcould.py    From python-urbanPlanning with MIT License 6 votes vote down vote up
def addPoint(self, point,color):
        if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
            pointId = self.vtkPoints.InsertNextPoint(point[:])
            self.vtkDepth.InsertNextValue(point[2])
            self.vtkCells.InsertNextCell(1)
            self.vtkCells.InsertCellPoint(pointId)            
            
        else:
            r = random.randint(0, self.maxNumPoints)
            self.vtkPoints.SetPoint(r, point[:])
        
        self.Colors.InsertNextTuple3(color[0],color[1],color[2]) #设置每一增加点的颜色。
        self.vtkPolyData.GetPointData().SetScalars(self.Colors)
        self.vtkPolyData.Modified()
        
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
        self.vtkDepth.Modified() 
Example #8
Source File: pointobject.py    From Det3D with Apache License 2.0 6 votes vote down vote up
def CreatePolyLine(self, points):
        "Create a 3D line from Nx3 numpy array"
        self.verts = vtk.vtkPoints()
        polyline = vtk.vtkPolyLine()

        polyline_pid = polyline.GetPointIds()
        for i, p in enumerate(points):
            self.verts.InsertNextPoint(*tuple(p))
            polyline_pid.InsertNextId(i)

        polyline_cell = vtk.vtkCellArray()
        polyline_cell.InsertNextCell(polyline)

        self.pd = vtk.vtkPolyData()
        self.pd.SetPoints(self.verts)
        self.pd.SetLines(polyline_cell)

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputData(self.pd)
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetLineStipplePattern(0xF0F0)
        self.actor.GetProperty().SetLineStippleRepeatFactor(1)
        self.actor.GetProperty().SetLineWidth(1.5) 
Example #9
Source File: pointobject.py    From Det3D with Apache License 2.0 6 votes vote down vote up
def CreatePolygon(self, points):
        "Create a 3D plane from Nx3 numpy array"
        self.verts = vtk.vtkPoints()
        polygon = vtk.vtkPolygon()

        polygon_pid = polygon.GetPointIds()
        for i, p in enumerate(points):
            self.verts.InsertNextPoint(*tuple(p))
            polygon_pid.InsertNextId(i)

        polygon_cell = vtk.vtkCellArray()
        polygon_cell.InsertNextCell(polygon)

        self.pd = vtk.vtkPolyData()
        self.pd.SetPoints(self.verts)
        self.pd.SetPolys(polygon_cell)

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputData(self.pd)
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper) 
Example #10
Source File: gui_viewer.py    From voxel-dcgan with MIT License 6 votes vote down vote up
def create_voxel(self):
        numberOfVertices = 8

        points = vtk.vtkPoints()
        points.InsertNextPoint(0, 0, 0)
        points.InsertNextPoint(1, 0, 0)
        points.InsertNextPoint(0, 1, 0)
        points.InsertNextPoint(1, 1, 0)
        points.InsertNextPoint(0, 0, 1)
        points.InsertNextPoint(1, 0, 1)
        points.InsertNextPoint(0, 1, 1)
        points.InsertNextPoint(1, 1, 1)

        voxel = vtk.vtkVoxel()
        for i in range(0, numberOfVertices):
            voxel.GetPointIds().SetId(i, i)

        ugrid = vtk.vtkUnstructuredGrid()
        ugrid.SetPoints(points)
        ugrid.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds())

        gfilter = vtk.vtkGeometryFilter()
        gfilter.SetInput(ugrid)
        gfilter.Update()
        return gfilter 
Example #11
Source File: visualization.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def points2actor(xyz, apoint_size):
    import vtk
    points = vtk.vtkPoints()
    # Create the topology of the point (a vertex)
    vertices = vtk.vtkCellArray()
    # Add points
    for i in range(0, len(xyz)):
        p = xyz.loc[i].values.tolist()
        point_id = points.InsertNextPoint(p)
        vertices.InsertNextCell(1)
        vertices.InsertCellPoint(point_id)
    # Create a poly data object
    polydata = vtk.vtkPolyData()
    # Set the points and vertices we created as the geometry and topology of the polydata
    polydata.SetPoints(points)
    polydata.SetVerts(vertices)
    polydata.Modified()
    # Mapper for points
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(polydata)
    # ACTOR for points
    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetPointSize(apoint_size)
    return actor, polydata 
Example #12
Source File: pointobject.py    From Det3D with Apache License 2.0 6 votes vote down vote up
def AddPoses(self, matrix_list):
        """"Add poses (4x4 NumPy arrays) to the object 
        """
        R_list = [p[:3, :3] for p in matrix_list]  # translation data
        t_list = [p[:3, 3] for p in matrix_list]  # rotation data

        self.points = vtk.vtkPoints()  # where t goes
        self.tensors = vtk.vtkDoubleArray()  # where R goes, column major
        self.tensors.SetNumberOfComponents(9)
        for i, R, t in zip(count(), R_list, t_list):
            self.points.InsertNextPoint(*tuple(t))
            self.tensors.InsertNextTypedTuple(tuple(R.ravel(order="F")))

        self.pose_pd = vtk.vtkPolyData()
        self.pose_pd.SetPoints(self.points)
        self.pose_pd.GetPointData().SetTensors(self.tensors) 
Example #13
Source File: vtkpointcloud.py    From deep-prior with GNU General Public License v3.0 6 votes vote down vote up
def addPoint(self, point):
        """
        Add point to point cloud, if more than maximum points are set, they are randomly subsampled
        :param point: 3D coordinates
        :return: None
        """
        if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
            pointId = self.vtkPoints.InsertNextPoint(point[:])
            self.vtkDepth.InsertNextValue(point[2])
            self.vtkCells.InsertNextCell(1)
            self.vtkCells.InsertCellPoint(pointId)
        else:
            r = numpy.random.randint(0, self.maxNumPoints)
            self.vtkPoints.SetPoint(r, point[:])
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
        self.vtkDepth.Modified() 
Example #14
Source File: gui_viewer.py    From pix2vox with GNU General Public License v3.0 6 votes vote down vote up
def create_voxel(self):
        numberOfVertices = 8

        points = vtk.vtkPoints()
        points.InsertNextPoint(0, 0, 0)
        points.InsertNextPoint(1, 0, 0)
        points.InsertNextPoint(0, 1, 0)
        points.InsertNextPoint(1, 1, 0)
        points.InsertNextPoint(0, 0, 1)
        points.InsertNextPoint(1, 0, 1)
        points.InsertNextPoint(0, 1, 1)
        points.InsertNextPoint(1, 1, 1)

        voxel = vtk.vtkVoxel()
        for i in range(0, numberOfVertices):
            voxel.GetPointIds().SetId(i, i)

        ugrid = vtk.vtkUnstructuredGrid()
        ugrid.SetPoints(points)
        ugrid.InsertNextCell(voxel.GetCellType(), voxel.GetPointIds())

        gfilter = vtk.vtkGeometryFilter()
        gfilter.SetInput(ugrid)
        gfilter.Update()
        return gfilter 
Example #15
Source File: vtkpointcloud.py    From deep-prior-pp with GNU General Public License v3.0 6 votes vote down vote up
def addPoint(self, point):
        """
        Add point to point cloud, if more than maximum points are set, they are randomly subsampled
        :param point: 3D coordinates
        :return: None
        """
        if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
            pointId = self.vtkPoints.InsertNextPoint(point[:])
            if self.color == 'depth':
                self.vtkDepth.InsertNextValue(point[2])
            else:
                import numbers
                assert isinstance(self.color, numbers.Number)
                self.vtkDepth.InsertNextValue(self.color)
            self.vtkCells.InsertNextCell(1)
            self.vtkCells.InsertCellPoint(pointId)
        else:
            r = self.rng.randint(0, self.maxNumPoints)
            self.vtkPoints.SetPoint(r, point[:])
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
        self.vtkDepth.Modified() 
Example #16
Source File: converters.py    From pcloudpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_polydata_from(points, tr_re):

    numberPoints = len(points)
    Points = vtkPoints()
    ntype = get_numpy_array_type(Points.GetDataType())
    points_vtk = numpy_to_vtk(np.asarray(points, order='C',dtype=ntype), deep=1)
    Points.SetNumberOfPoints(numberPoints)
    Points.SetData(points_vtk)

    Triangles = vtkCellArray()
    for item in tr_re:
        Triangle = vtkTriangle()
        Triangle.GetPointIds().SetId(0,item[0])
        Triangle.GetPointIds().SetId(1,item[1])
        Triangle.GetPointIds().SetId(2,item[2])
        Triangles.InsertNextCell(Triangle)

    polydata = vtkPolyData()
    polydata.SetPoints(Points)
    polydata.SetPolys(Triangles)

    polydata.Modified()
    polydata.Update()

    return polydata 
Example #17
Source File: test_common.py    From pyvista with MIT License 6 votes vote down vote up
def test_shallow_copy_back_propagation():
    """Test that the original data object's points get modified after a
    shallow copy.

    Reference: https://github.com/pyvista/pyvista/issues/375#issuecomment-531691483
    """
    # Case 1
    points = vtk.vtkPoints()
    points.InsertNextPoint(0.0, 0.0, 0.0)
    points.InsertNextPoint(1.0, 0.0, 0.0)
    points.InsertNextPoint(2.0, 0.0, 0.0)
    original = vtk.vtkPolyData()
    original.SetPoints(points)
    wrapped = pyvista.PolyData(original, deep=False)
    wrapped.points[:] = 2.8
    orig_points = vtk_to_numpy(original.GetPoints().GetData())
    assert np.allclose(orig_points, wrapped.points)
    # Case 2
    original = vtk.vtkPolyData()
    wrapped = pyvista.PolyData(original, deep=False)
    wrapped.points = np.random.rand(5, 3)
    orig_points = vtk_to_numpy(original.GetPoints().GetData())
    assert np.allclose(orig_points, wrapped.points) 
Example #18
Source File: vtkpointcloud.py    From semi-auto-anno with GNU General Public License v3.0 6 votes vote down vote up
def addPoint(self, point):
        """
        Add point to point cloud, if more than maximum points are set, they are randomly subsampled
        :param point: 3D coordinates
        :return: None
        """
        if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
            pointId = self.vtkPoints.InsertNextPoint(point[:])
            self.vtkDepth.InsertNextValue(point[2])
            self.vtkCells.InsertNextCell(1)
            self.vtkCells.InsertCellPoint(pointId)
        else:
            r = self.rng.randint(0, self.maxNumPoints)
            self.vtkPoints.SetPoint(r, point[:])
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
        self.vtkDepth.Modified() 
Example #19
Source File: synchronizable_deserializer.py    From panel with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def poly_data_builder(state, zf, register):
    instance = vtk.vtkPolyData()
    register.update({state['id']: instance})
    # geometry
    if 'points' in state['properties']:
        points = state['properties']['points']
        vtkpoints = vtk.vtkPoints()
        data_arr = ARRAY_TYPES[points['dataType']]()
        fill_array(data_arr, points, zf)
        vtkpoints.SetData(data_arr)
        instance.SetPoints(vtkpoints)
    for cell_type in ['verts', 'lines', 'polys', 'strips']:
        if cell_type in state['properties']:
            cell_arr = vtk.vtkCellArray()
            fill_array(cell_arr.GetData(), state['properties'][cell_type], zf)
            getattr(instance, 'Set' + capitalize(cell_type))(cell_arr)
    
    # datasets
    fields = state['properties']['fields']
    for dataset in fields:
        data_arr = ARRAY_TYPES[dataset['dataType']]()
        fill_array(data_arr, dataset, zf)
        location = getattr(instance, 'Get' + capitalize(dataset['location']))()
        getattr(location, capitalize(dataset['registration']))(data_arr) 
Example #20
Source File: viz.py    From deep_gcns with MIT License 5 votes vote down vote up
def clear_points(self):
        self.vtkPoints = vtk.vtkPoints()
        self.vtkCells = vtk.vtkCellArray()
        self.vtkDepth = vtk.vtkDoubleArray()
        self.vtkDepth.SetName('DepthArray')
        self.vtkPolyData.SetPoints(self.vtkPoints)
        self.vtkPolyData.SetVerts(self.vtkCells)
        self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
        self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray') 
Example #21
Source File: show_vtk.py    From pyrealsense with Apache License 2.0 5 votes vote down vote up
def __init__(self, nparray):
        super(VTKActorWrapper, self).__init__()

        self.nparray = nparray

        nCoords = nparray.shape[0]
        nElem = nparray.shape[1]

        self.verts = vtk.vtkPoints()
        self.cells = vtk.vtkCellArray()
        self.scalars = None

        self.pd = vtk.vtkPolyData()
        self.verts.SetData(vtk_np.numpy_to_vtk(nparray))
        self.cells_npy = np.vstack([np.ones(nCoords,dtype=np.int64),
                               np.arange(nCoords,dtype=np.int64)]).T.flatten()
        self.cells.SetCells(nCoords,vtk_np.numpy_to_vtkIdTypeArray(self.cells_npy))
        self.pd.SetPoints(self.verts)
        self.pd.SetVerts(self.cells)

        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInputDataObject(self.pd)

        self.actor = vtk.vtkActor()
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetRepresentationToPoints()
        self.actor.GetProperty().SetColor(0.0,1.0,0.0) 
Example #22
Source File: gui_viewer.py    From voxel-dcgan with MIT License 5 votes vote down vote up
def create_actor(self):
        self.points = vtk.vtkPoints()
        self.colors = vtk.vtkUnsignedCharArray()
        self.colors.SetName("colors")
        self.colors.SetNumberOfComponents(4)

        polydata = vtk.vtkPolyData()
        polydata.SetPoints(self.points)
        polydata.GetPointData().SetScalars(self.colors)

        # create cell
        voxel = self.create_voxel()

        self.glyph3D = vtk.vtkGlyph3D()
        self.glyph3D.SetColorModeToColorByScalar()
        self.glyph3D.SetSource(voxel.GetOutput())
        self.glyph3D.SetInput(polydata)
        self.glyph3D.ScalingOff()
        self.glyph3D.Update()

        # mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(self.glyph3D.GetOutput())

        # actor
        self.actor = vtk.vtkActor()
        self.actor.SetMapper(mapper)
        self.actor.GetProperty().SetAmbient(0.15) 
Example #23
Source File: mesh.py    From OpenWARP with Apache License 2.0 5 votes vote down vote up
def _create_vtp_mesh(self):
        '''Internal function to creat a VTP mesh from the imported mesh data
        '''
        if self.VTK_installed is True:

            self.vtp_mesh    = vtk.vtkPolyData()
            points  = vtk.vtkPoints()
            polys   = vtk.vtkCellArray()

            for i in range(self.points.shape[0]):

                points.InsertPoint(i, self.points[i])


            for i in range(self.faces.shape[0]):

                polys.InsertNextCell(_mk_vtk_id_list(self.faces[i]))

            self.vtp_mesh.SetPoints(points)
            self.vtp_mesh.SetPolys(polys)

    # def _collapse(self,plane=2,value=0.0,direction=1):
    #This function is not yet working 100%

    #     '''Collapse points
    #     '''
    #     for face,face_n in xrange(self.faces.shape[0]):
    #
    #         for j in xrange(self.faces[i].size):
    #
    #             p = int(self.faces[i][j])
    #
    #             if self.points[p][plane] > value*direction:
    #
    #                 self.points[p][plane] = value 
Example #24
Source File: util.py    From sanet_relocal_demo with GNU General Public License v3.0 5 votes vote down vote up
def create_pointcloud_polydata(points, colors=None):
    """Creates a vtkPolyData object with the point cloud from numpy arrays

    points: numpy.ndarray
        pointcloud with shape (n,3)

    colors: numpy.ndarray
        uint8 array with colors for each point. shape is (n,3)

    Returns vtkPolyData object
    """
    import vtk
    vpoints = vtk.vtkPoints()
    vpoints.SetNumberOfPoints(points.shape[0])
    for i in range(points.shape[0]):
        vpoints.SetPoint(i, points[i])
    vpoly = vtk.vtkPolyData()
    vpoly.SetPoints(vpoints)

    if not colors is None:
        vcolors = vtk.vtkUnsignedCharArray()
        vcolors.SetNumberOfComponents(3)
        vcolors.SetName("Colors")
        vcolors.SetNumberOfTuples(points.shape[0])
        for i in range(points.shape[0]):
            vcolors.SetTuple3(i ,colors[i,0],colors[i,1], colors[i,2])
        vpoly.GetPointData().SetScalars(vcolors)

    vcells = vtk.vtkCellArray()

    for i in range(points.shape[0]):
        vcells.InsertNextCell(1)
        vcells.InsertCellPoint(i)

    vpoly.SetVerts(vcells)

    return vpoly 
Example #25
Source File: vtk_adaptor.py    From tessagon with Apache License 2.0 5 votes vote down vote up
def create_empty_mesh(self):
        self.pcoords = vtk.vtkFloatArray()
        self.pcoords.SetNumberOfComponents(3)
        self.points = vtk.vtkPoints()
        self.polys = vtk.vtkCellArray()
        self.poly_data = vtk.vtkPolyData() 
Example #26
Source File: vtkpointcloud.py    From semi-auto-anno with GNU General Public License v3.0 5 votes vote down vote up
def clearPoints(self):
        """
        Clear all points from the point cloud
        :return: None
        """
        self.vtkPoints = vtk.vtkPoints()
        self.vtkCells = vtk.vtkCellArray()
        self.vtkDepth = vtk.vtkDoubleArray()
        self.vtkDepth.SetName('DepthArray')
        self.vtkPolyData.SetPoints(self.vtkPoints)
        self.vtkPolyData.SetVerts(self.vtkCells)
        self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
        self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray') 
Example #27
Source File: animate.py    From PVGeo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def RequestData(self, request, inInfo, outInfo):
        from vtk.numpy_interface import dataset_adapter as dsa
        import PVGeo._helpers as inputhelp
        from PVGeo.filters import pointsToTube
        # Get input/output of Proxy
        pdi = self.GetInputData(inInfo, 0, 0)
        pdo = self.GetOutputData(outInfo, 0)
        # Grab input arrays to process from drop down menus
        #- Grab all fields for input arrays:
        fields = []
        for i in range(3):
            fields.append(inputhelp.get_selected_array_field(self, i))
        #- Simply grab the names
        names = []
        for i in range(9):
            names.append(inputhelp.get_selected_array_name(self, i))
        # Pass array names and associations on to process
        # Get the input arrays
        wpdi = dsa.WrapDataObject(pdi)
        arrs = []
        for i in range(9):
            arrs.append(inputhelp.get_array(wpdi, fields[i], names[i]))

        # grab coordinates for each part of boring machine at time idx as row
        executive = self.GetExecutive()
        outInfo = executive.GetOutputInformation(0)
        idx = int(outInfo.Get(executive.UPDATE_TIME_STEP())/self.__dt)
        pts = []
        for i in range(3):
            x = arrs[i*3][idx]
            y = arrs[i*3+1][idx]
            z = arrs[i*3+2][idx]
            pts.append((x,y,z))
        # now exectute a points to tube filter
        vtk_pts = vtk.vtkPoints()
        for i in range(len(pts)):
            vtk_pts.InsertNextPoint(pts[i][0],pts[i][1],pts[i][2])
        poly = vtk.vtkPolyData()
        poly.SetPoints(vtk_pts)
        pointsToTube(poly, radius=self.__diameter/2, numSides=20, nrNbr=False, pdo=pdo)
        return 1 
Example #28
Source File: mesh.py    From OpenWARP with Apache License 2.0 5 votes vote down vote up
def _create_vtp_mesh(self):
        '''Internal function to creat a VTP mesh from the imported mesh data
        '''
        if self.VTK_installed is True:

            self.vtp_mesh    = vtk.vtkPolyData()
            points  = vtk.vtkPoints()
            polys   = vtk.vtkCellArray()

            for i in range(self.points.shape[0]):

                points.InsertPoint(i, self.points[i])


            for i in range(self.faces.shape[0]):

                polys.InsertNextCell(_mk_vtk_id_list(self.faces[i]))

            self.vtp_mesh.SetPoints(points)
            self.vtp_mesh.SetPolys(polys)

    # def _collapse(self,plane=2,value=0.0,direction=1):
    #This function is not yet working 100%

    #     '''Collapse points
    #     '''
    #     for face,face_n in xrange(self.faces.shape[0]):
    #
    #         for j in xrange(self.faces[i].size):
    #
    #             p = int(self.faces[i][j])
    #
    #             if self.points[p][plane] > value*direction:
    #
    #                 self.points[p][plane] = value 
Example #29
Source File: pointset.py    From omfvista with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def point_set_to_vtk(pse):
    """Convert the point set to a :class:`pyvista.PolyData` data object.

    Args:
        pse (:class:`omf.pointset.PointSetElement`): The point set to convert

    Return:
        :class:`pyvista.PolyData`
    """

    points = pse.geometry.vertices
    npoints = pse.geometry.num_nodes

    # Make VTK cells array
    cells = np.hstack((np.ones((npoints, 1)),
                       np.arange(npoints).reshape(-1, 1)))
    cells = np.ascontiguousarray(cells, dtype=np.int64)
    cells = np.reshape(cells, (2*npoints))
    vtkcells = vtk.vtkCellArray()
    vtkcells.SetCells(npoints, nps.numpy_to_vtk(cells, deep=True, array_type=vtk.VTK_ID_TYPE))

    # Convert points to vtk object
    pts = vtk.vtkPoints()
    pts.SetNumberOfPoints(pse.geometry.num_nodes)
    pts.SetData(nps.numpy_to_vtk(points))

    # Create polydata
    output = vtk.vtkPolyData()
    output.SetPoints(pts)
    output.SetVerts(vtkcells)

    # Now add point data:
    add_data(output, pse.data)

    add_textures(output, pse.textures, pse.name)

    return pyvista.wrap(output) 
Example #30
Source File: pc_viz.py    From deep_gcns_torch with MIT License 5 votes vote down vote up
def clear_points(self):
        self.vtkPoints = vtk.vtkPoints()
        self.vtkCells = vtk.vtkCellArray()
        self.vtkDepth = vtk.vtkDoubleArray()
        self.vtkDepth.SetName('DepthArray')
        self.vtkPolyData.SetPoints(self.vtkPoints)
        self.vtkPolyData.SetVerts(self.vtkCells)
        self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
        self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')