i have the following problem. I have a numpy array like this :
arr = np.array([[ 1. , 1. , 4. , 3. , 6. , 12. , -1. , 1.],
[ 1. , 2. , 2., 2., 10. , 6. , -2. , 2.],
[ 1. , 2. , 3. , 4. , 4. , 11. , -2. , 3.],
[ 1. , 2. , 3. , 6., 8. , 9. , 1. , 4.],
[ 1. , 2. , 6. , 7. , 4., 14. , 1. , 5.],
[ 1. , 2. , 7. , 4. , 2. , 17. , -0. , 6.],
[ 1. , 3. , 2. , 6. , 7. , 3. , -1. , 7.],
[ 1. , 3. , 4. , 1. , 3. , 14. , 0. , 8.],
[ 1. , 3. , 5. , 5. , 1. , 16. , -1. , 9.],
[ 1. , 3. , 6. , 2. , 9. , 19. , 1. , 10.],
[ 1. , 4. , 3. , 1. , 1. , 7. , -1. , 11.],
[ 1. , 4. , 4. , 5. , 9. , 10. , 2. , 12.],
[ 1. , 4. , 5. , 3. , 6. , 18. , 0. , 13.],
[ 1. , 4. , 6. , 6. , 5. , 2. , -1. , 14.],
[ 1. , 5. , 1. , 4. , 3. , 5. , 1. , 15.],
[ 2. , 1. , 2. , 7. , 2. , 19. , -1. , 16.],
[ 2. , 1. , 3. , 2. , 3. , 16. , -2. , 17.]])
Now i want to convert it to a vtk Table. Is this possible?
Best regards!
I think that it could be possible to do that with the following method:
# create the vtkTable object
tab = vtk.vtkTable()
# create a vtkDataArray with arr values
vtkarr = vtk.vtkDoubleArray()
vtkarr.SetNumberOfComponents(arr.shape[1])
vtkarr.SetNumberOfTuples(arr.shape[0])
vtkarr.SetVoidArray(arr, arr.size, 0)
# finally assign the values to the vtkTable
tab.GetRowData().AddArray(vtkarr)
I tried to avoid unnecessary copies of the values that's why I used SetVoidArray()
. So basically, its first argument is the array itself, the second is the total number of elements in the array and the last tells whether you want the vtkTable
object to deallocate the raw data or not (in this case, it will).
An alternative method is to use vtk's numpy_support module:
import numpy as np
import vtk
from vtk.util import numpy_support
arr = np.array([[ ... ]])
vtkarr = numpy_support.numpy_to_vtk( arr, deep=True, array_type=vtk.VTK_DOUBLE )
# create the vtkTable object
tab = vtk.vtkTable()
tab.GetRowData().AddArray(vtkarr)
Note: Internally, numpy_to_vtk seems to use SetVoidArray() as well.
If you came here, like me, to copy multi-dimensionsional data, you can flatten them using arr.ravel(), then convert them to a vtkArray using numpy_to_vtk and then "fix" the number of components per tuple using vtkArray.SetNumberOfComponents():
# arr is a 3xNxNxN array
# Make sure the dimension which you want to make up the tuples is at the end.
# In our case, dimension 0 (the 3) is what we want to be in each tuple,
# so we move it to the end:
arr = numpy.transpose( arr, (1,2,3,0) )
# Convert the array to vtk. ravel() flattens the array and makes sure
# it's contiguous:
vtkarr = numpy_support.numpy_to_vtk( arr.ravel(), deep=True, array_type=vtk.VTK_DOUBLE )
# "Fix" the number of components:
vtkarr.SetNumberOfComponents( 3 )
vtkarr.SetNumberOfTuples( N*N*N )
vtkarr.SetName("DisplacementField")
cellData.AddArray( vtkarr )
See this blog post for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With