[英]Numpy array to vtk table
我有以下問題。 我有一個像這樣的numpy數組:
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.]])
現在我想將它轉換為vtk表。 這可能嗎?
最好的祝福!
我認為可以通過以下方法實現:
# 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)
我試圖避免使用不必要的值副本,這就是我使用SetVoidArray()
的原因。 所以基本上,它的第一個參數是數組本身,第二個參數是數組中元素的總數,最后一個參數告訴你是否希望vtkTable
對象解除分配原始數據(在這種情況下,它會)。
另一種方法是使用vtk的numpy_support模塊:
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)
注意:在內部,numpy_to_vtk似乎也使用SetVoidArray()。
如果你像我一樣來到這里復制多維數據,可以使用arr.ravel()展平它們,然后使用numpy_to_vtk將它們轉換為vtkArray,然后使用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 )
有關詳細信息,請參閱此博客文章 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.