Reputation: 41
I have around 500 vtk files that need to be converted to stl file. I usually use Paraview to convert them manually, but it takes forever. I wonder if there is a tool to convert vtk files into stl files in Python? I attached a screenshot of my VTK file.
Thanks in advance.
Upvotes: 1
Views: 7857
Reputation: 9792
How about something like the following? Save the code as file_converter.py
and run the script with arguments:
python file_converter.py -h
python file_converter.py <path-to-input-dir> -o <path-to-output-dir>
And here the code for the converter.
#!/usr/bin/env python
import os
import vtk
import argparse
def convertFile(filepath, outdir):
if not os.path.isdir(outdir):
os.makedirs(outdir)
if os.path.isfile(filepath):
basename = os.path.basename(filepath)
print("Copying file:", basename)
basename = os.path.splitext(basename)[0]
outfile = os.path.join(outdir, basename+".stl")
reader = vtk.vtkGenericDataObjectReader()
reader.SetFileName(filepath)
reader.Update()
writer = vtk.vtkSTLWriter()
writer.SetInputConnection(reader.GetOutputPort())
writer.SetFileName(outfile)
return writer.Write()==1
return False
def convertFiles(indir, outdir):
files = os.listdir(indir)
files = [ os.path.join(indir,f) for f in files if f.endswith('.vtk') ]
ret = 0
print("In:", indir)
print("Out:", outdir)
for f in files:
ret += convertFile(f, outdir)
print("Successfully converted %d out of %d files." % (ret, len(files)))
def run(args):
convertFiles(args.indir, args.outdir)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="VTK to STL converter")
parser.add_argument('indir', help="Path to input directory.")
parser.add_argument('--outdir', '-o', default='output', help="Path to output directory.")
parser.set_defaults(func=run)
args = parser.parse_args()
ret = args.func(args)
Upvotes: 3