I need to blend a gray and rgb image, and my code is:
import vtk
import numpy as np
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
def numpyToVTK(data, multi_component=False):
if multi_component == False:
if len(data.shape) == 2:
data = data[:, :, np.newaxis]
flat_data_array = data.transpose(2,1,0).flatten()
vtk_data = numpy_to_vtk(num_array=flat_data_array, deep=True, array_type=vtk.VTK_FLOAT)
else:
assert len(data.shape)==3, 'only test for 2D RGB'
flat_data_array = data.transpose(1, 0, 2)
flat_data_array = np.reshape(flat_data_array, newshape=[-1, data.shape[2]])
vtk_data = numpy_to_vtk(num_array=flat_data_array, deep=True, array_type=vtk.VTK_FLOAT)
img = vtk.vtkImageData()
img.GetPointData().SetScalars(vtk_data)
img.SetDimensions(data.shape[0], data.shape[1], 1)
return img
x = np.linspace(start=-1000, stop=500, num=256)
y = np.linspace(start=-1000, stop=500, num=256)
xx, yy = np.meshgrid(x, y) # 为一维的矩阵
img = xx
rgb = np.zeros(shape=[256, 256, 3])
rgb[100:150, 100:150, 0] = 255
gray = numpyToVTK(img)
rgb = numpyToVTK(rgb, multi_component=True)
windowLevelColor = vtk.vtkImageMapToWindowLevelColors()
windowLevelColor.SetInputData(gray)
# windowLevelColor.SetWindow(400)
# windowLevelColor.SetLevel(0)
windowLevelColor.Update()
image_blender = vtk.vtkImageBlend()
image_blender.AddInputData(rgb)
image_blender.AddInputData(windowLevelColor.GetOutput())
image_blender.SetOpacity(0, 0.5)
image_blender.SetOpacity(1, 0.5)
image_blender.Update()
imageActor = vtk.vtkImageActor()
imageActor.GetMapper().SetInputData(image_blender.GetOutput())
# imageActor.GetMapper().SetInputData(gray)
# imageActor.GetMapper().SetInputData(windowLevelColor.GetOutput())
# imageActor.GetMapper().SetInputData(rgb)
ren = vtk.vtkRenderer()
ren.AddActor(imageActor)
ren.SetBackground(0.1, 0.2, 0.4)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetSize(400, 400)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
renWin.Render()
iren.Start()
I have tested that gray/rgb is OK:
# imageActor.GetMapper().SetInputData(gray)
# imageActor.GetMapper().SetInputData(windowLevelColor.GetOutput())
# imageActor.GetMapper().SetInputData(rgb)
The windlwLevelColor.GetOutput
is:
The rgb
is:
Unfortunately, the image_blender.GetOutput()
is:
Is there anything wrong with my code? How can I blend the gray and rgb image? Any suggestion is appreciated!