I want to convert a polydata to volume, and my reference code is: https://kitware.github.io/vtk-examples/site/Cxx/PolyData/PolyDataToImageData/.
My polydata is:
But the converted imagedata is:
There is some unexpected connection.
The completed code to reproduce my problem is:
import vtkmodules.all as vtk
import numpy as np
def GenerateMask(poly, origin=None, spacing=[1, 1, 1]):
import vtkmodules.all as vtk
mask = vtk.vtkImageData()
bounds = poly.GetBounds()
# 计算图像有多大
dim = [0, 0, 0]
for i in [0, 1, 2]:
dim[i] = int(
np.ceil((bounds[i * 2 + 1] - bounds[i * 2]) / spacing[i])
)
mask.SetDimensions(dim)
mask.SetSpacing(spacing)
mask.SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1)
if not origin:
origin = [0, 0, 0]
origin[0] = bounds[0] + spacing[0] / 2
origin[1] = bounds[2] + spacing[1] / 2
origin[2] = bounds[4] + spacing[2] / 2
mask.SetOrigin(origin)
mask.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1)
mask.GetPointData().GetScalars().Fill(255)
pol2stenc = vtk.vtkPolyDataToImageStencil()
pol2stenc.SetInputData(poly)
pol2stenc.SetOutputOrigin(mask.GetOrigin())
pol2stenc.SetOutputSpacing(mask.GetSpacing())
pol2stenc.SetOutputWholeExtent(mask.GetExtent())
pol2stenc.Update()
imgStenc = vtk.vtkImageStencil()
imgStenc.SetInputData(mask)
imgStenc.SetStencilConnection(pol2stenc.GetOutputPort())
imgStenc.SetBackgroundValue(0)
imgStenc.SetReverseStencil(False)
imgStenc.Update()
return imgStenc.GetOutput()
reader = vtk.vtkOBJReader()
reader.SetFileName('vessel.obj')
reader.Update()
polydata = reader.GetOutput()
mask = GenerateMask(polydata, spacing=[0.01, 0.01, 0.01])
mapper = vtk.vtkSmartVolumeMapper()
mapper.SetInputData(mask)
mapper.SetBlendModeToMaximumIntensity()
volume = vtk.vtkVolume()
volume.SetMapper(mapper)
renderer = vtk.vtkRenderer()
renderer.AddActor(volume)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(renderer)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
iren.Start()
And the polydata is upload to github: https://github.com/zhang-qiang-github/Test
How to obtain correctly volume from this polydata? Ang suggestion is appreciated~~~