numpy 使用Python查找属于平面的所有点

91zkwejq  于 12个月前  发布在  Python
关注(0)|答案(3)|浏览(89)

我有一个mx3数组,用于创建一个3d模型。有没有一种快速的方法可以使用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的方法可以让它更快?

nbysray5

nbysray51#

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

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

"""
Points that lie on a plane satisfy Ax + By + Cz + D = 0. 
Here we set values of A, B, C to arbitrary values and 
calculate D so the plane intersects the first point in `p`:
"""
ABC = np.array([3,5,7])
D = -p[0].dot(ABC) 

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

3ks5zfa02#

以下内容是否有帮助?我假设它是快的,因为它没有使用任何for循环。我的答案是基于this

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,:]
mu0hgdu0

mu0hgdu03#

使用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.]]

相关问题