11

I have a list of 2d points [(x1,y1),(x2,y2),...,(xn,yn)] in numpy, how do I get a list of points within the bounding box specified by the corners ((bx1,by1),(bx2,by2))?

If this were C++ I would use the OGC "within" specification in boost geometry to filter the list.

Right now I'm just dealing with a list of indexes into an NxN 2d numpy array, so I expect this should just be 1-2 lines of code with numpy.

Andrew Hundt
  • 2,551
  • 2
  • 32
  • 64
  • Meaby you'll find this helpful: http://stackoverflow.com/questions/1897779/test-if-point-is-in-some-rectangle – grael Oct 10 '15 at 07:05
  • Also http://stackoverflow.com/questions/21612976/point-inside-polygon – grael Oct 10 '15 at 07:10

1 Answers1

25

Using a combination of all, logical_and and the <= operator, one can express the main idea in 1 line.

import random
import numpy as np
from matplotlib import pyplot

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

# this is just for drawing
rect = np.array([[bx1, by1], [bx1, by2], [bx2, by2], [bx2, by1], [bx1, by1]])

pyplot.plot(inbox[:, 0], inbox[:, 1], 'rx',
            outbox[:, 0], outbox[:, 1], 'bo',
            rect[:, 0], rect[:, 1], 'g-')
pyplot.show()

Illustration of bounding box result

Andrew Hundt
  • 2,551
  • 2
  • 32
  • 64
Rory Yorke
  • 2,166
  • 13
  • 13