1

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 codes\VTK\untitled8.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?

273K
  • 29,503
  • 10
  • 41
  • 64
DrBwts
  • 3,470
  • 6
  • 38
  • 62

2 Answers2

2

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()
Pranjal Sahu
  • 1,469
  • 3
  • 18
  • 27
1

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())
DrBwts
  • 3,470
  • 6
  • 38
  • 62
Nico Vuaille
  • 2,310
  • 1
  • 6
  • 14
  • this works but only if the cropping sphere's radius = 30, all other values lead to an empty set – DrBwts Dec 03 '20 at 15:18
  • in fact none of the BooleanOperators are working properly! – DrBwts Dec 03 '20 at 15:34
  • 1
    After some investigation, it is not the better part of VTK ... [A VTK forum post](https://discourse.vtk.org/t/adding-roemers-boolean-filter-as-a-remote-module/1635) about using [this repo](https://github.com/zippy84/vtkbool) in VTK. – Nico Vuaille Dec 03 '20 at 16:13
  • Thanks Nico I have opened up a new question about this [here](https://stackoverflow.com/questions/65129906/vtk-boolean-operations-on-poly-data-producing-empty-sets) – DrBwts Dec 03 '20 at 16:22