Load and resize multiple STL files in python

Question:

I found the code to read an STL file but I don’t know how to read multiple STL files in one window and resize them.

import vtk

filename = "Stl file"
 
reader = vtk.vtkSTLReader()
reader.SetFileName(filename)
mapper = vtk.vtkPolyDataMapper()
if vtk.VTK_MAJOR_VERSION <= 5:
    mapper.SetInput(reader.GetOutput())
else:
    mapper.SetInputConnection(reader.GetOutputPort())

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

ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
 
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

ren.AddActor(actor)
iren.Initialize()
renWin.Render()
iren.Start()

I want these two stl files together in one window

Asked By: Amir Hossein Zeydi

||

Answers:

I’ve modified your code to make a script loads multiple STL files. I get them from the command line using sys.argv[]

import sys
import vtk

filenames = sys.argv[1:]
print(filenames)

actors = []
for name in filenames:
    reader = vtk.vtkSTLReader()
    reader.SetFileName(name)
    mapper = vtk.vtkPolyDataMapper()
    if vtk.VTK_MAJOR_VERSION <= 5:
        mapper.SetInput(reader.GetOutput())
    else:
        mapper.SetInputConnection(reader.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.SetPosition([0.0, 0.0, 0.0])
    actor.SetScale([1.0, 1.0, 1.0])

    actors.append(actor)

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

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

for actor in actors:
  ren.AddActor(actor)
iren.Initialize()
renWin.Render()
iren.Start()

Basically I loop through each of the file names. For each file there is a reader, mapper and actor. The result is a list of actors, and those are each added to the renderer.

Also note that to scale and position each STL model, I do that by calling SetPosition and SetScale of the STL’s actor. In this case the positions and scales are just for illustration. The values don’t really do anything. You can apply any transformation to a vtkActor.

Answered By: Dave Chen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.