边界框内的numpy过滤点

时间:2015-10-10 06:57:41

标签: python numpy coordinates bounding-box

我在numpy中有一个2d点[(x1,y1),(x2,y2),...,(xn,yn)]的列表,如何获得角((bx1,by1),(bx2,by2))指定的边界框内的点列表?

如果这是C ++,我会使用OGC "within" specification in boost geometry来过滤列表。

现在我只是处理一个NxN 2d numpy数组中的索引列表,所以我希望这只是1-2行代码和numpy。

1 个答案:

答案 0 :(得分:11)

使用alllogical_and<=运算符的组合,一个 可以用一行表达主要思想。

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