NumPy 2D数组:在圆中选择索引

daniel451:

对于某些矩形,我们可以非常有效地选择2D数组中的所有索引:

arr[y:y+height, x:x+width]

...其中(x, y)是矩形和的左上角heightwidth矩形选择的高度(行数)和宽度(列数)。

现在,假设要在给定中心坐标(cx, cy)和radius 的特定圆中选择2D数组中的所有索引r是否有一个numpy函数来有效地实现这一目标?

目前,我正在通过具有将索引添加到缓冲区(列表)中的Python循环来手动预先计算索引。因此,这对于大型2D数组而言效率很低,因为我需要排队每个圆圈中的每个整数。

# 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索引吗?

Chiel:

您可以定义一个包含圆的蒙版。下面,我已经演示了一个圆圈,但是您可以在mask赋值中编写任意函数如果满足右侧条件,则该字段mask的尺寸为arr,并且值为TrueFalse否则为。该掩码可以与索引运算符结合使用,以仅分配给索引选择,如该行arr[mask] = 123.所示。

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 32)
y = np.arange(0, 32)
arr = np.zeros((y.size, x.size))

cx = 12.
cy = 16.
r = 5.

# The two lines below could be merged, but I stored the mask
# for code clarity.
mask = (x[np.newaxis,:]-cx)**2 + (y[:,np.newaxis]-cy)**2 < r**2
arr[mask] = 123.

# This plot shows that only within the circle the value is set to 123.
plt.figure(figsize=(6, 6))
plt.pcolormesh(x, y, arr)
plt.colorbar()
plt.show()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章