使用 python 找到属于一个平面的所有点

finding all the points that belong to a plane using python

我有一个用于创建 3d 模型的 mx3 数组。有没有一种快速的方法可以使用 numpy 或其他 python 函数提取属于给定平面的所有点?该平面将采用 Ax+By+Cz+D=0 形式。我目前正在遍历数组中的所有点以找到满足此方程的点。

plane1=[]
for i in pcd_array:
    if (normal_vector[0]*(i[0]-point1[0])+normal_vector[1]*(i[1]-point1[1])+normal_vector[2]*(i[2]-point1[2]))==0:
        plane1.append(i)

我想知道是否有任何 numpythonic 方法可以让它更快?

矢量化将 快得多。在下面的示例中,下面的所有点都位于 -100 < x,y,z < 100 区域中的整数值上。矩阵 p 包含一百万个点;我们计算位于给定平面上的所有点(几乎是瞬间):

# define 1M points at random:
p = np.random.randint(-100,100, size=(1000000,3))

# A,B,C (c0) are arbitrary values; define D so plane intersects first point:    
c0 = np.array([3,5,7])
D = -p[0].dot(c0) 

# return all points in plane Ax + By + Cz + D = 0
p_in_plane = p[p.dot(c0) + D == 0]

以下有帮助吗?我假设它很快,因为它没有使用任何 for 循环。我的回答是基于

import numpy as np

mat  = np.arange(18).reshape(6,3)
mat[5,:] = [0,1,2]

aa   = 1
bb   = 2
cc   = 3
dd   = -8
mask = mat[:,0]*aa + mat[:,1]*bb + mat[:,2]*cc + dd == 0
selected = mat[mask,:]

使用numpy where查找所有符合条件的点

代码

import numpy as np

def get_planer_indexes(pts, plane):
    '''
        :parm pts    - array of 3D points
        :param plane - coefficient of plane (i.e. A, B, C, D)
        :returns     - indexes of points which are in plance
    '''
    # Compute A*pt[0] + B*pt[1] + C*pt[3] + D for each point pt in pts
    # Checks that abs(...) is below threshold (1e-6) to allow for floating point error
    return np.where(np.abs(points.dot(plane[:3]) + plane[3]) <= 1e-6 )

示例用法

#    Create 3 points which lie in a plane
P1 = [1, -2, 0]
P2 = [3, 1, 4]
P3 = [0, -1, 2]
planar_pts = np.array([P1, P2, P3])

# Plane that P1, P2, P3 lie within
plane = np.array([2, -8, 5, -18]) # i.e. A = 2, B = -8, C = 5, D = -18

# Random 3 D points (100 points)
rand_points = np.random.rand(100, 3)

#    Stack onto planar points
points = np.vstack((planar_pts, rand_points))

#    Shuffle the points (so planar points are in random locations)
np.random.shuffle(points)

#    Find planar points
indexes = get_planer_indexes(points, plane)
print(points[indexes])

输出

[[ 3.  1.  4.]
 [ 0. -1.  2.]
 [ 1. -2.  0.]]