[英]fill Numpy array with axisymmetric values
I'm trying to find a fast way to fill a Numpy array with rotation symmetric values. 我试图找到一种快速的方法来填充具有旋转对称值的Numpy数组。 Imagine an array of zeros containing a cone shaped area.
想象一下包含锥形区域的零个数组。 I have a 1D array of values and want to rotate it 360° around the center of the array.
我有一维数组,想要围绕数组的中心旋转360°。 There is no 2D function like z=f(x,y), so I can't calculate the 2D values explicitly.
没有像z = f(x,y)这样的2D函数,所以我无法明确地计算2D值。 I have something that works, but the for-loop is too slow for big arrays.
我有一些有用的东西,但for循环对于大型数组来说太慢了。 This should make a circle:
这应该是一个圆圈:
values = np.ones(100)
x = np.arange(values.size)-values.size/2+0.5
y = values.size/2-0.5-np.arange(values.size)
x,y = np.meshgrid(x,y)
grid = np.rint(np.sqrt(x**2+y**2))
arr = np.zeros_like(grid)
for i in np.arange(values.size/2):
arr[grid==i] = values[i+values.size/2]
My 1D array is of course not as simple. 我的1D阵列当然不是那么简单。 Can someone think of a way to get rid of the for-loop?
有人可以想办法摆脱for循环吗?
Update: I want to make a circular filter for convolutional blurring. 更新:我想为卷积模糊制作圆形滤镜。 Before I used
np.outer(values,values)
which gave me a rectangular filter. 在我使用
np.outer(values,values)
给了我一个矩形过滤器。 David's hint allows me to create a circular filter very fast. 大卫的提示允许我非常快速地创建一个圆形过滤器。 See below:
见下文:
You can use fancy indexing to achieve this: 您可以使用花式索引来实现此目的:
values = np.ones(100)
x = np.arange(values.size)-values.size/2+0.5
y = values.size/2-0.5-np.arange(values.size)
x,y = np.meshgrid(x,y)
grid = np.rint(np.sqrt(x**2+y**2)).astype(np.int)
arr = np.zeros_like(grid)
size_half = values.size // 2
inside = (grid < size_half)
arr[inside] = values[grid[inside] + size_half]
Here, inside
select the indices that lie inside the circle, since only these items can be derived from values
. 在这里,
inside
选择位于圆圈inside
的索引,因为只有这些项可以从values
导出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.