Search code examples
pythonnumpycoordinatespoint-clouds

Finding points within a bounding box with numpy


I have millions of xyz-coordinates from multiple point cloud files which I am storing inside a 2-dimensional numpy array: [[x1, y1, z1], [x2, y2, z2],..., [xn, yn, zn]].

I want to filter all the points which are inside a specific bounding box described by 4 coordinates [[x1, y1], [x2, y2]] i.e. the lower left and upper right coordinates of a rectangle.

I have already found the following piece of code to filter coordinates with numpy and it's almost what I want. The only difference is (if I'm getting it right) that my 2-dimensional array also has got z-coordinates.

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)]

How would I have to modifiy the code above to make it work with xyz-coordinates to be filtered by a bounding box described with two xy-coordinates?


Solution

  • Select the X and Y coordinates of your points:

    xy_pts = pts[:,[0,1]]
    

    Now, simply use xy_pts instead of pts in the comparisons:

    inidx = np.all((ll <= xy_pts) & (xy_pts <= ur), axis=1)