边界框内的过滤点数目

2024-06-01 14:20:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

现在我正在处理一个nxn2dnumpy数组中的索引列表,所以我希望这应该是1-2行代码。在


Tags: numpy列表边界x1x2我会yny1
1条回答
网友
1楼 · 发布于 2024-06-01 14:20:30

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

相关问题 更多 >