Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python NumPy 2D数组:选择圆中的索引_Python_Arrays_Numpy_Indexing - Fatal编程技术网

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

Python NumPy 2D数组:选择圆中的索引,python,arrays,numpy,indexing,Python,Arrays,Numpy,Indexing,对于某些矩形,我们可以非常有效地选择2D数组中的所有索引: arr[y:y+height, x:x+width] …其中,(x,y)是矩形的左上角,高度和宽度是矩形选择的高度(行数)和宽度(列数) 现在,假设我们想要选择位于给定中心坐标(cx,cy)和半径r的特定圆内的2D数组中的所有索引。是否有numpy功能可以有效地实现这一点 目前,我正在通过一个Python循环手动预计算索引,该循环将索引添加到缓冲区(列表)中。因此,对于大型2D数组来说,这是非常低效的,因为我需要将位于某个圆中的每个整

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

arr[y:y+height, x:x+width]
…其中,
(x,y)
是矩形的左上角,
高度
宽度
是矩形选择的高度(行数)和宽度(列数)

现在,假设我们想要选择位于给定中心坐标
(cx,cy)
和半径
r
的特定圆内的2D数组中的所有索引。是否有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)]
用于x&y索引的缓冲区 索引x=列表() 索引_y=列表() #上下索引范围 下x_,上x_=int(max(cx-r,0)),int(min(cx+r,arr.shape[1]-1)) y_下,y_上=int(max(cy-r,0)),int(min(cy+r,arr.shape[0]-1)) 范围x=范围(x\u较低,x\u较高) 范围y=范围(y较低,y较高) #循环所有索引 对于产品中的y,x(范围y,范围x): #检查点是否位于半径r内 如果(x-cx)**2+(y-cy)**2 如前所述,对于较大的阵列/圆,此过程效率很低。有没有加快速度的想法


如果有更好的方法索引圆,这是否也适用于“任意”二维形状?例如,我是否可以通过某种方式传递一个表示任意形状的点的成员身份的函数,以获得数组的相应numpy索引?

您可以定义一个包含圆的遮罩。下面,我已经演示了一个圆圈,但是您可以在
掩码
赋值中编写任意函数。如果右侧的条件满足,则字段
掩码
的尺寸为
arr
,值为
True
,否则为
False
。此掩码可与索引运算符结合使用,以仅指定一组索引,如
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()
将numpy导入为np
将matplotlib.pyplot作为plt导入
x=np.arange(0,32)
y=np.arange(0,32)
arr=np.零((y.尺寸,x.尺寸))
cx=12。
cy=16。
r=5。
#下面的两行可以合并,但我存储了掩码
#为了代码清晰。
掩码=(x[np.newaxis,:]-cx)**2+(y[:,np.newaxis]-cy)**2
干得好。我在电脑上计时,我必须生成两个坐标
x
y
,才能计算出一个圆。你可以使用任何函数,arange对我来说只是一个方便的选择。