I have a code to show a image:
from vtk.util.numpy_support import vtk_to_numpy, numpy_to_vtk
import vtk
import numpy as np
def numpyToVTK(data):
flat_data_array = data.transpose(2,1,0).flatten()
vtk_data_array = numpy_to_vtk(flat_data_array)
vtk_data = numpy_to_vtk(num_array=vtk_data_array, deep=True, array_type=vtk.VTK_FLOAT)
img = vtk.vtkImageData()
img.GetPointData().SetScalars(vtk_data)
img.SetDimensions(data.shape)
return img
img = np.zeros(shape=[512,512,1])
img[0:300,0:100,0] = 255
vtkImg = numpyToVTK(img)
vtkImg.SetOrigin(100, 100, 100)
center = vtkImg.GetCenter()
imageActor = vtk.vtkImageActor()
windowLevel = vtk.vtkImageMapToWindowLevelColors()
imageActor.GetMapper().SetInputConnection(windowLevel.GetOutputPort())
windowLevel.SetInputData(vtkImg)
windowLevel.Update()
sphere = vtk.vtkSphereSource()
sphere.SetCenter(center[0], center[1], center[2])
sphere.SetRadius(50)
sphere.Update()
sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputData(sphere.GetOutput())
sphereActor = vtk.vtkActor()
sphereActor.SetMapper(sphereMapper)
ren = vtk.vtkRenderer()
ren.AddActor(imageActor)
ren.AddActor(sphereActor)
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()
and the result is:
The sphere is the center of image. Then, I need to adjust the direction of vtkImageData
as following:
...
vtkImg = numpyToVTK(img)
vtkImg.SetOrigin(100, 100, 100)
x = [0, 0, 1]
y = [0, 1, 0]
z = [1, 0, 0]
vtkImg.SetDirectionMatrix([x[0], y[0], z[0], x[1], y[1], z[1], x[2], y[2], z[2]])
center = vtkImg.GetCenter()
...
Then, the result is:
We can see the sphere is not located on the image. But the sphere is definitely the center of the image: center=vtkImage.GetCenter()
.
What’s wrong with my code?? Or it is a bug of vtk?