[英]python3 - get average of n x n array within a 600 x 600 numpy array
I am writing a method which takes 4 arguments: 我正在写一个带有4个参数的方法:
I want to return the average in the nxn grid around the location of [pos_1, pos_2]. 我想在[pos_1,pos_2]位置附近的nxn网格中返回平均值。 Grid_size will be 5, 7 or 9.
Grid_size将为5、7或9。
Eg. 例如。 If grid_size was 5, pos_1 was 20 and pos_2 was 150, I would sum the values in a 5 x 5 grid centred around im[20,150] divided by 25 (5 x 5).
如果grid_size为5,则pos_1为20,而pos_2为150,我将求和以im [20,150]除以25(5 x 5)为中心的5 x 5网格中的值之和。 The current implementation is:
当前的实现是:
def calc_density(im, pos_1, pos_2, grid_size):
grid_sum = 0
if(pos_1 < 600 - (grid_size - 1)/2):
if(pos_1 > (grid_size - 1)/2):
if(pos_2 < 600 - (grid_size - 1)/2):
if(pos_1 > (grid_size - 1)/2):
for i in range(grid_size):
for j in range(grid_size):
grid_sum = grid_sum + im[(pos_1 - (grid_size - 1)/2) + i, (pos_2 - (grid_size - 1)/2) + j]
This method should work for any case where [pos_1, pos_2] does not fall within (grid_size - 1)/2 from the edge of im. 此方法适用于[pos_1,pos_2]不在im的边缘(grid_size-1)/ 2范围内的情况。 If it does then the averaging nxn grid will fall outside of im.
如果这样做,则平均nxn网格将落在im之外。 If this happens then I am hoping to drop those positions which fall out of im and find the average of those which do fall in the nxn grid.
如果发生这种情况,那么我希望删除那些落在im之外的位置,并找到那些落在nxn网格中的平均值。
I can only imagine doing this with a lot of 'if' cases. 我只能想象在很多“如果”的情况下这样做。 Is there a better way to do this?
有一个更好的方法吗?
Use numpy facilities for a more readable and more efficient way: 使用numpy工具以更易读和更有效的方式:
def density(arr,x0,y0,size):
xb=x0-size//2
yb=y0-size//2
return arr[xb:,yb:][:size,:size].mean()
This correctly manages borders in the sense you want : 这可以按照您想要的方式正确管理边界:
In [46]: density(arr,603,603,9)
Out[46]: 743.0
In [47]: arr
Out[47]:
array([[ 73, 197, 311, ..., 952, 477, 138],
[751, 93, 291, ..., 983, 167, 599],
[ 54, 666, 380, ..., 456, 466, 754],
...,
[186, 737, 829, ..., 929, 28, 923],
[136, 408, 193, ..., 844, 649, 927],
[477, 411, 458, ..., 64, 173, 743]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.