VTK rendering 2D mesh in python

Tags: , ,



so i’m trying to render a 2D mesh using vtk (in python). I have a list of tuples containing all the points and also a list of tuples containing the points of each cell. Just to experiment, I tried to create a polydata object of a square with 4 elements and render it, but i ended up with this:

square

I would like it to show the lines connecting the nodes (like a wireframe) instead of solid square.. This is the code to produce the image above:

def main2():

    #Array of vectors containing the coordinates of each point
    nodes = np.array([[0, 0, 0], [1, 0, 0], [2, 0, 0], [2, 1, 0], [2, 2, 0], 
                      [1, 2, 0], [0, 2, 0], [0, 1, 0], [1, 1, 0]])

    #Array of tuples containing the nodes correspondent of each element
    elements = np.array([(0, 1, 8, 7), (7, 8, 5, 6), (1, 2, 3, 8), (8, 3, 4, 
                        5)])

    #Make the building blocks of polyData attributes
    Mesh = vtk.vtkPolyData()
    Points = vtk.vtkPoints()
    Cells = vtk.vtkCellArray()  

    #Load the point and cell's attributes
    for i in range(len(nodes)):
        Points.InsertPoint(i, nodes[i])

    for i in range(len(elements)):
        Cells.InsertNextCell(mkVtkIdList(elements[i]))

    #Assign pieces to vtkPolyData
    Mesh.SetPoints(Points)
    Mesh.SetPolys(Cells)

    #Mapping the whole thing
    MeshMapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        MeshMapper.SetInput(Mesh)
    else:
        MeshMapper.SetInputData(Mesh)

    #Create an actor
    MeshActor = vtk.vtkActor()
    MeshActor.SetMapper(MeshMapper)

    #Rendering Stuff
    camera = vtk.vtkCamera()
    camera.SetPosition(1,1,1)
    camera.SetFocalPoint(0,0,0)

    renderer = vtk.vtkRenderer()
    renWin   = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    renderer.AddActor(MeshActor)
    renderer.SetActiveCamera(camera)
    renderer.ResetCamera()
    renderer.SetBackground(1,1,1)

    renWin.SetSize(300,300)

    #Interact with data
    renWin.Render()
    iren.Start()


main2()

I would also like to know if it’s possible to have a gridline as the background of the render window, instead of a black color, just like this:

gridline

Thanks in advance!

Answer

You can use MeshActor.GetProperty().SetRepresentationToWireframe() (https://www.vtk.org/doc/nightly/html/classvtkProperty.html#a2a4bdf2f46dc499ead4011024eddde5c) to render the actor as wireframe, or MeshActor.GetProperty().SetEdgeVisibility(True) to render it as solid with edges rendered as lines.

Regarding the render window background, I don’t know.



Source: stackoverflow