使用numpy在边界框内查找点

7
我有来自多个点云文件的数百万个xyz坐标,我将它们存储在一个二维numpy数组中:[[x1, y1, z1], [x2, y2, z2],..., [xn, yn, zn]]
我想过滤所有位于特定边界框内的点,该边界框由4个坐标描述:[[x1, y1], [x2, y2]],即矩形的左下和右上坐标。
我已经找到了以下用于使用numpy过滤坐标的代码,它几乎符合我的要求。唯一的区别是(如果我理解正确的话),我的二维数组还具有z坐标。
import random
import numpy as np

points = [(random.random(), random.random()) for i in range(100)]

bx1, bx2 = sorted([random.random(), random.random()])
by1, by2 = sorted([random.random(), random.random()])

pts = np.array(points)
ll = np.array([bx1, by1])  # lower-left
ur = np.array([bx2, by2])  # upper-right

inidx = np.all(np.logical_and(ll <= pts, pts <= ur), axis=1)
inbox = pts[inidx]
outbox = pts[np.logical_not(inidx)]

我需要修改上述代码以便使用由两个xy坐标描述的边界框筛选xyz坐标。
2个回答

7

我正在编写一个用于处理点云的Python库,我有一个函数认为可以适用于您:

def bounding_box(points, min_x=-np.inf, max_x=np.inf, min_y=-np.inf,
                        max_y=np.inf, min_z=-np.inf, max_z=np.inf):
    """ Compute a bounding_box filter on the given points

    Parameters
    ----------                        
    points: (n,3) array
        The array containing all the points's coordinates. Expected format:
            array([
                [x1,y1,z1],
                ...,
                [xn,yn,zn]])

    min_i, max_i: float
        The bounding box limits for each coordinate. If some limits are missing,
        the default values are -infinite for the min_i and infinite for the max_i.

    Returns
    -------
    bb_filter : boolean array
        The boolean mask indicating wherever a point should be keeped or not.
        The size of the boolean mask will be the same as the number of given points.

    """

    bound_x = np.logical_and(points[:, 0] > min_x, points[:, 0] < max_x)
    bound_y = np.logical_and(points[:, 1] > min_y, points[:, 1] < max_y)
    bound_z = np.logical_and(points[:, 2] > min_z, points[:, 2] < max_z)

    bb_filter = np.logical_and(np.logical_and(bound_x, bound_y), bound_z)

    return bb_filter

这是你所要求的一个示例:
1000万个点:
points = np.random.rand(10000000, 3)

您指定格式的矩形:

rectangle = np.array([[0.2, 0.2],
                     [0.4, 0.4]])

解压矩形:

min_x = rectangle[:,0].min()
max_x = rectangle[:,0].max()
min_y = rectangle[:,1].min()
max_y = rectangle[:,1].max()

获取标记在框内的布尔数组:
%%timeit
inside_box = bounding_box(points, min_x=min_x, max_x=max_x, min_y=min_y, max_y=max_y)
1 loop, best of 3: 247 ms per loop

这样,您就可以按照以下方式使用数组:
points_inside_box = points[inside_box]
points_outside_box = points[~inside_box]

1
我目前正在解决一个类似的问题,我很喜欢你的答案。然而,你的代码似乎只提供了一个与坐标轴平行的边界框。你有没有什么提示或解决方案来获取最小边界框? - dnks23
3D边界框通常有8个坐标。 - Haozhe Xie

6
请选择您的点的X和Y坐标:
xy_pts = pts[:,[0,1]]

现在,在比较中只需使用xy_pts而不是pts即可。
inidx = np.all((ll <= xy_pts) & (xy_pts <= ur), axis=1)

但是这样我会丢失z信息,对吗?我肯定需要保留它们以供后续计算使用。 - conste
@conste 你将使用原始的3D“pts”构建“inbox”。 - DYZ

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接