Convert STL object to VTK geometry in python

Question:

I am wanting to do Boolean operations on STL files with geometric primitives from the VTK library.

My problem is converting the STL geometry to something that the VTK Boolean objects will except.

I tried the following…

import vtk

filename = 'gyroid.stl' 
reader = vtk.vtkSTLReader()
reader.SetFileName(filename)
mapper = vtk.vtkPolyDataMapper()
mapper.SetInputConnection(reader.GetOutputPort())
gyroid = vtk.vtkActor()
gyroid.SetMapper(mapper)

sphere = vtk.vtkSphere()
sphere.SetRadius(30)
sphere.SetCenter(0, 0, 0)

boolean = vtk.vtkImplicitBoolean()
boolean.SetOperationTypeToIntersection()
boolean.AddFunction(gyroid)
boolean.AddFunction(sphere)

But get the following error…

File "D:Python codesVTKuntitled8.py", line 29, in <module>
    boolean.AddFunction(gyroid)

TypeError: AddFunction argument %Id: %V

It throws the same error if I replace gyroid with mapper

How do I convert the STL mesh into something useable by VTK? Or cant I do this & need to look elsewhere?

Asked By: DrBwts

||

Answers:

The problem is not about converting STL in VTK but about how to use VTK API 🙂

vtkImplicitBoolean works on implicits function, i.e. classes that can generate data, such as the vtkSphere. See here for doc
and here for usage

As you have a loaded dataset, you cannot use this. Instead, use vtkBooleanOperationPolyDataFilter and generate a sphere with the vtkSphereSource. Here and here
for examples.

Example

sphere = vtk.vtkSphereSource()
booleanOperation = vtk.vtkBooleanOperationPolyDataFilter()
booleanOperation.SetOperationToIntersection()
booleanOperation.SetInputConnection(0, reader.GetOutputPort())
booleanOperation.SetInputConnection(1, sphere.GetOutputPort())
Answered By: Nico Vuaille

Code to convert from .stl to .vtk format. Install vtk for this using pip install vtk.

import sys
import vtk

# Read the .stl file
filename = sys.argv[1] 
a = vtk.vtkSTLReader()
a.SetFileName(filename)
a.Update()
a = a.GetOutput()

# Write the .vtk file
filename = filename.replace('.stl', '.vtk')
b = vtk.vtkPolyDataWriter()
b.SetFileName(filename)
b.SetInputData(a)
b.Update()
Answered By: Pranjal Sahu
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.