Convert STL to Voxel mesh using Python VTK

Introduction

Create a Voxel mesh from STL CAD data using the Signed Distance Function (SDF). The library used is Python's VTK. In addition, the code was entirely based on the following article.

environment

Windows 10 home

Anaconda(Python 3.7.6)

VTK 8.2

Paraview 5.4.1 (used to display STL and voxel mesh)

CAD data (STL data)

Stanford Dragon.

stanford_dragon_original.png

Source code

import vtk

filename = "./dragon.stl"
#Read stl file
reader = vtk.vtkSTLReader()
reader.SetFileName(filename)
reader.Update()

#Extract Poly data
poly_data = reader.GetOutput()

#Determine the mesh size
cell_dims = [50, 50, 50]#x, y, z

#Create a mesh grid
#x_min:0 x_max:1, y_min:2,y_max:3,z_min:4,z_max:5
bounds = poly_data.GetBounds()
mesh_pitch = [(bounds[1] - bounds[0])/cell_dims[0],
              (bounds[3] - bounds[2])/cell_dims[1],
              (bounds[5] - bounds[4])/cell_dims[2]]
mins = [bounds[0], bounds[2], bounds[4]]

points = vtk.vtkPoints()
for ix in range(cell_dims[0]+1):
    for iy in range(cell_dims[1]+1):
        for iz in range(cell_dims[2]+1):
            x = ix * mesh_pitch[0] + mins[0]
            y = iy * mesh_pitch[1] + mins[1]
            z = iz * mesh_pitch[2] + mins[2]
            points.InsertNextPoint(x,y,z)
structured_base_mesh = vtk.vtkStructuredGrid()
structured_base_mesh.SetExtent(0, cell_dims[0], 0, cell_dims[1], 0, cell_dims[2])
structured_base_mesh.SetPoints(points)

#Convert structured grid data to unstructured grid data
append = vtk.vtkAppendFilter()
append.AddInputData(structured_base_mesh)
append.Update()
base_mesh = append.GetOutput()

#Find the coordinates of the center of Voxel
cell_centers = vtk.vtkCellCenters()
cell_centers.SetInputData(base_mesh)
cell_centers.Update()

#Create a Voxel mesh from STL
center_points = cell_centers.GetOutput().GetPoints()
cell_list = vtk.vtkIdList()
sdf = vtk.vtkImplicitPolyDataDistance()
sdf.SetInput(poly_data)
distance_sdf = vtk.vtkDoubleArray()
distance_sdf.SetName("sdf")
for idx in range(center_points.GetNumberOfPoints()):
    current_center = center_points.GetPoint(idx)
    distance = sdf.FunctionValue(current_center)
    distance_sdf.InsertNextValue(distance)
    if distance <= 0:
        cell_list.InsertNextId(idx)

base_mesh.GetCellData().SetScalars(distance_sdf)#Add SDF value

extract_cells = vtk.vtkExtractCells()
extract_cells.SetInputData(base_mesh)
extract_cells.SetCellList(cell_list)
extract_cells.Update()

#Output Voxel data as VTK file
writer = vtk.vtkXMLDataSetWriter()
writer.SetFileName("closed_voxel.vtu")
writer.SetInputData(extract_cells.GetOutput())
writer.Update()

#Output the grid data with the SDF value input as a VTK file
#writer = vtk.vtkXMLDataSetWriter()
#writer.SetFileName("all_voxel.vtu")
#writer.SetInputData(base_mesh)
#writer.Update()

stanford_dragon_voxel.png

Recommended Posts

Convert STL to Voxel mesh using Python VTK
Python code to convert region mesh code to latitude / longitude
Python script to convert latitude / longitude to mesh code
Convert cubic mesh code to WKT in Python
[python] Convert date to string
Convert numpy int64 to python int
[Python] Convert list to Pandas [Pandas]
Post to Twitter using Python
Start to Selenium using python
Convert Scratch project to Python
Convert python 3.x code to python 2.x
Convert from Pandas DataFrame to System.Data.DataTable using Python for .NET
Convert markdown to PDF in Python
Workflow to convert formula (image) to python
Convert list to DataFrame with python
Python> list> Convert double list to single list
[Python] Convert natural numbers to ordinal numbers
Convert decimal numbers to n-ary numbers [python]
Python> tuple> Convert double tuple to single tuple
Create a command line tool to convert dollars to yen using Python
[Python] How to convert db file to csv
From Python to using MeCab (and CaboCha)
Convert Python> two value sequence to dictionary
[Python] How to convert a 2D list to a 1D list
How to convert Python to an exe file
[Python] Convert csv file delimiters to tab delimiters
Convert XML document stored in XML database (BaseX) to CSV format (using Python)
Convert psd file to png in Python
Convert Excel data to JSON with python
Convert Hiragana to Romaji with Python (Beta)
Convert from katakana to vowel kana [python]
Log in to Slack using requests in Python
Convert FX 1-minute data to 5-minute data with Python
python> Convert tuple to list> aList = list (pi_tuple)
Try to operate Excel using Python (Xlwings)
Dump BigQuery tables to GCS using Python
Convert Python date types to RFC822 format
Introduction to Discrete Event Simulation Using Python # 2
Convert HEIC files to PNG files with Python
Convert Chinese numerals to Arabic numerals with Python
Convert from Markdown to HTML in Python
Convert absolute URLs to relative URLs in Python
Sample to convert image to Wavelet with Python
I tried using the Python library "pykakasi" that can convert kanji to romaji.
Convert the cURL API to a Python script (using IBM Cloud object storage)
Convert FBX files to ASCII <-> BINARY in Python
Convert PDF to image (JPEG / PNG) with Python
Convert "number" of excel date to python datetime
#Monte Carlo method to find pi using Python
Convert PDFs to images in bulk with Python
Introducing 4 ways to monitor Python applications using Prometheus
I want to email from Gmail using Python.
Convert svg file to png / ico with Python
Convert Windows epoch values to date with python
How to convert SVG to PDF and PNG [Python]
Convert json format data to txt (using yolo)
Convert exponential notation float to str in Python
Convert strings to character-by-character list format with python
[Python] Convert time display (str type) using "" "and"'" to seconds (float type) with datetime and timedelta
Updated to Python 2.7.9
Convert to HSV