[英]Find cells from vertices in pyvista PolyData mesh
我有一個 PolyData 網格,我正在嘗試為一些包含給定頂點的單元格着色。 但是,我需要一種有效的方法來解決這個問題。
例如,這可行,但對於大型網格來說太慢了:
import pyvista as pv
import numpy as np
mesh = pv.Sphere()
# Scalars are zero everywhere
data = [0] * mesh.n_cells
# I want to color the cells which contain these vertices
point_indexes = np.random.randint(0,mesh.n_points,100)
# Loop over all vertices
for point in point_indexes:
# This next part is inefficient in a large mesh:
# I extract the 3D coordinates of the point and look for
# a containing cell. I think I should look for a cell containing
# the vertex from its index...but I can't find a way to do it!
point_idx = mesh.points[point]
cell_idx = mesh.find_containing_cell(point_idx)
# Change the scalar
data [cell_idx] = 1
# Color the cells touching the vertices
mesh.cell_data['data'] = data
mesh.plot()
這就是我得到的,這很好......我只需要做得更快!
如果您有點索引並且想要提取包含這些點中的任何一個的每個單元格,您可以使用extract_points()
過濾器,其默認的adjacent_cells=True, include_cells=True
參數意味着提取您的點(一次全部)也將提取每個它們是細胞的一部分。
然后剩下的就是使用稱為'vtkOriginalCellIds'
的單元標量並使用這些索引來更改原始網格中的標量。 我在代碼中清理了一些風格的東西:
import numpy as np
import pyvista as pv
mesh = pv.Sphere()
# start from zero scalars
data = np.zeros(mesh.n_cells)
# point indices to use
rng = np.random.default_rng()
point_indices = rng.integers(0, mesh.n_points, 100)
# extract cells along with the points, assign 1 scalar to cells
extracted = mesh.extract_points(point_indices)
data[extracted.cell_data['vtkOriginalCellIds']] = 1
# assign to cell scalas and plot
mesh.cell_data['data'] = data
plotter = pv.Plotter()
plotter.add_mesh(mesh)
plotter.add_points(mesh.points[point_indices, :], color='forestgreen',
point_size=10, render_points_as_spheres=True)
plotter.show()
如您所見,通過這種方法,您確實可以得到每個包含特殊點的單元格,從而導致每個點周圍出現單元格島。 根據您的描述,這是我所期望的。 我懷疑您原來的 output 沒有反映這一點的原因是因為通過 3d 點坐標查找點容易出現浮點錯誤,這使得 VTK 錯過了大部分周圍的單元格。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.