【问题标题】:Finding k nearest neighbors in 3d numpy array在 3d numpy 数组中查找 k 个最近的邻居
【发布时间】:2021-04-29 15:15:39
【问题描述】:

所以我试图从示例网格中找到 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()

【问题讨论】:

    标签: python numpy kdtree pyvista


    【解决方案1】:

    你快到了 :) 问题是你使用网格中的 points 来构建树,然后提取 cells。当然,这些是无关的,因为点的索引在用作单元格的索引时会给你带来废话。

    要么你必须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()
    

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

    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, 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()
    

    如您所见,这两个结果不同,因为索引 5000(我们用于参考点)在索引点或索引单元格时意味着其他东西。

    【讨论】:

    • 非常感谢您的快速响应,现在我可以开始解决真正的问题了;)
    猜你喜欢
    • 2018-06-26
    • 2019-11-28
    • 1970-01-01
    • 2020-11-05
    • 2019-06-05
    • 1970-01-01
    • 2011-02-01
    • 2015-03-27
    • 1970-01-01
    相关资源
    最近更新 更多