我一直在尝试在 Python 中将图像可视化为 VTK 中平面上的部分半透明纹理。
我的方法是使用
vtkThresholdTextureCoords()
根据图像值设置透明度。 但是,我正在努力应用该阈值。 错误消息指出 texture threshold
没有标量数据。
这是代码片段:
from vtkmodules.vtkIOImage import vtkImageReader2Factory
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer,
vtkTexture
)
from vtkmodules.vtkFiltersSources import vtkPlaneSource
from vtkmodules.vtkFiltersTexture import vtkThresholdTextureCoords
from vtkmodules.vtkCommonColor import vtkNamedColors
import vtk
def main():
#fileName = get_program_parameters()
fileName = 'ice.png'
readerFactory = vtkImageReader2Factory()
textureFile = readerFactory.CreateImageReader2(fileName)
textureFile.SetFileName(fileName)
textureFile.Update()
texture = vtkTexture()
texture.SetInputConnection(textureFile.GetOutputPort())
texture.InterpolateOn()
plane = vtkPlaneSource()
plane.SetCenter(0.0,0.0,0.0)
plane.SetNormal(0.0,1.0,0.0)
texturePlane = vtk.vtkTextureMapToPlane()
texturePlane.SetInputConnection(plane.GetOutputPort())
thresh = vtkThresholdTextureCoords()
thresh.SetInputConnection(texturePlane.GetOutputPort())
thresh.ThresholdByUpper(0.1)
planeMapper = vtkPolyDataMapper()
planeMapper.SetInputConnection(thresh.GetOutputPort())
#planeMapper.SetInputConnection(plane.GetOutputPort()) # This does work
planeMapper.SetScalarRange(textureFile.GetOutput().GetScalarRange())
planeActor = vtkActor()
planeActor.SetMapper(planeMapper)
planeActor.SetTexture(texture)
# Create the RenderWindow, Renderer and Interactor.
renderer = vtkRenderer()
renWin = vtkRenderWindow()
renWin.AddRenderer(renderer)
iren = vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer, set the background and size.
renderer.AddActor(planeActor)
colors = vtkNamedColors()
renderer.SetBackground(colors.GetColor3d('DarkSlateGray'))
renWin.SetSize(640, 480)
renWin.SetWindowName('TexturePlane')
# render the image
renWin.Render()
renderer.ResetCamera()
renderer.GetActiveCamera().Elevation(-30)
renderer.GetActiveCamera().Roll(-20)
renderer.ResetCameraClippingRange()
renWin.Render()
iren.Start()
return
我想出了一个方法,通过设置每个像素的第四个标量值(即alpha值)。
reader = vtk.vtkPNGReader()
reader.SetFileName('ice.png')
reader.Update()
img = reader.GetOutput()
ext = img.GetExtent()
for y in range(ext[2],ext[3]):
for x in range(ext[0],ext[1]):
val0 = img.GetScalarComponentAsFloat(x,y,0,0)
val1 = img.GetScalarComponentAsFloat(x,y,0,1)
val2 = img.GetScalarComponentAsFloat(x,y,0,2)
if val0+val1+val2 < 2.:# Apply a threshold.
# In this example, simply
# the sum of the three
# color components
# Setting the 4th (alpha) value to zero
img.SetScalarComponentFromFloat(x,y,0,3,0)
texture = vtkTexture()
texture.SetInputDataObject(img)