在 3d numpy 数组中找到 k 个最近的邻居

问题描述

所以我试图从示例网格中找到 pyvista numpy 数组中的 k 个最近邻居。收到邻居后,我想在我的 3d 模型中实现一些区域的增长。

但不幸的是,我收到了一些奇怪的输出,您可以在下图中看到。 我似乎在 KDTree 实现中遗漏了一些东西。我正在关注类似问题的答案:https://stackoverflow.com/a/2486341/9812286

import numpy as np 
from sklearn.neighbors import KDTree

import pyvista as pv

from pyvista import examples

# Example dataset with normals
mesh = examples.load_random_hills()

smooth = mesh

NDIM = 3
X = smooth.points
point = X[5000]

tree = KDTree(X,leaf_size=X.shape[0]+1)
# ind = tree.query_radius([point],r=10) # indices of neighbors within distance 0.3
distances,ind = tree.query([point],k=1000)

p = pv.Plotter()
p.add_mesh(smooth)

ids = np.arange(smooth.n_points)[ind[0]]
top = smooth.extract_cells(ids)
random_color = np.random.random(3)
p.add_mesh(top,color=random_color)

p.show()

3d plot of a surface with two elongated patches coloured differently

解决方法

大功告成:) 问题在于您使用网格中的来构建树,然后提取单元。当然,这些是无关的,因为点的索引在用作单元格索引时会给您带来废话。

要么你必须extract_points

import numpy as np 
from sklearn.neighbors import KDTree

import pyvista as pv

from pyvista import examples

# Example dataset with normals
mesh = examples.load_random_hills()

smooth = mesh

NDIM = 3
X = smooth.points
point = X[5000]

tree = KDTree(X,leaf_size=X.shape[0]+1)
# ind = tree.query_radius([point],r=10) # indices of neighbors within distance 0.3
distances,ind = tree.query([point],k=1000)

p = pv.Plotter()
p.add_mesh(smooth)

ids = np.arange(smooth.n_points)[ind[0]]
top = smooth.extract_points(ids)  # changed here!
random_color = np.random.random(3)
p.add_mesh(top,color=random_color)

p.show()

plot with circular region coloured near one edge

或者您必须首先与细胞中心合作:

import numpy as np 
from sklearn.neighbors import KDTree

import pyvista as pv

from pyvista import examples

# Example dataset with normals
mesh = examples.load_random_hills()

smooth = mesh

NDIM = 3
X = smooth.cell_centers().points  # changed here!
point = X[5000]

tree = KDTree(X,k=1000)

p = pv.Plotter()
p.add_mesh(smooth)

ids = np.arange(smooth.n_points)[ind[0]]
top = smooth.extract_cells(ids)
random_color = np.random.random(3)
p.add_mesh(top,color=random_color)

p.show()

figure with circular region coloured somewhere in the middle

如您所见,这两个结果不同,因为索引 5000(我们用于参考点)在索引点或索引单元格时表示其他含义。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...