【发布时间】:2018-08-26 01:43:36
【问题描述】:
对于一些矩形,我们可以非常有效地选择二维数组中的所有索引:
arr[y:y+height, x:x+width]
...其中(x, y) 是矩形的左上角,height 和width 是矩形选择的高度(行数)和宽度(列数)。
现在,假设我们要在给定中心坐标(cx, cy) 和半径r 的特定圆中选择二维数组中的所有索引。是否有一个 numpy 函数可以有效地实现这一点?
目前,我正在通过一个 Python 循环手动预先计算索引,该循环将索引添加到缓冲区(列表)中。因此,这对于大型二维数组来说效率很低,因为我需要将位于某个圆圈中的每个整数排队。
# buffer for x & y indices
indices_x = list()
indices_y = list()
# lower and upper index range
x_lower, x_upper = int(max(cx-r, 0)), int(min(cx+r, arr.shape[1]-1))
y_lower, y_upper = int(max(cy-r, 0)), int(min(cy+r, arr.shape[0]-1))
range_x = range(x_lower, x_upper)
range_y = range(y_lower, y_upper)
# loop over all indices
for y, x in product(range_y, range_x):
# check if point lies within radius r
if (x-cx)**2 + (y-cy)**2 < r**2:
indices_y.append(y)
indices_x.append(x)
# circle indexing
arr[(indices_y, indices_x)]
如前所述,此过程对于较大的数组/圆非常低效。有什么加快速度的想法吗?
如果有更好的方法来索引圆,这是否也适用于“任意”2D 形状?例如,我能否以某种方式传递一个表示任意形状的点的成员资格的函数来获取数组的相应 numpy 索引?
【问题讨论】:
标签: python arrays numpy indexing