I want to create a binary mask from some ordered points.
For example, for the points:
ps = [
[64, 64, 0],
[128, 64, 0],
[128, 128, 0],
[64, 128, 0],
]
I hope it can create a binary mask which is agree with:
import numpy as np
img = np.zeros(shape=[256, 256])
img[64:128, 64:128] = 1
I find vtkPolyDataToImageStencil
&vtkImageStencilToImage
may be the solution. And my code is:
import vtkmodules.all as vtk
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
ps = [
[64, 64, 0],
[128, 64, 0],
[128, 128, 0],
[64, 128, 0],
]
polydata = vtk.vtkPolyData()
points = vtk.vtkPoints()
polygon = vtk.vtkPolygon()
polygon.GetPointIds().SetNumberOfIds(len(ps))
for idx, p in enumerate(ps):
points.InsertNextPoint(p[0], p[1], p[2])
polygon.GetPointIds().SetId(idx, idx)
polygons = vtk.vtkCellArray()
polygons.InsertNextCell(polygon)
polydata.SetPoints(points)
polydata.SetPolys(polygons)
polyDataToImageStencil = vtk.vtkPolyDataToImageStencil()
polyDataToImageStencil.SetInputData(polydata)
polyDataToImageStencil.SetOutputOrigin(0, 0, 0)
polyDataToImageStencil.SetOutputSpacing([1, 1, 1])
polyDataToImageStencil.SetOutputWholeExtent([0, 255, 0, 255, 0, 0])
polyDataToImageStencil.Update()
imgStencilToImage = vtk.vtkImageStencilToImage()
imgStencilToImage.SetInputConnection(polyDataToImageStencil.GetOutputPort())
imgStencilToImage.SetInsideValue(1)
imgStencilToImage.SetOutsideValue(0)
imgStencilToImage.Update()
vtkMask = imgStencilToImage.GetOutput()
mask = vtk_to_numpy(vtkMask.GetPointData().GetScalars())
print(mask.sum())
However, the final mask is all 0.
What’s wrong with my code? Any suggestion is appreciated~~~