python – 基于单元格区域的Regrid numpy数组

import numpy as np
from skimage.measure import block_reduce

arr = np.random.random((6, 6))
area_cell = np.random.random((6, 6))

block_reduce(arr, block_size=(2, 2), func=np.ma.mean)

我想重新调整一个从6 x 6大小到3 x 3的numpy数组arr.使用skimage函数block_reduce.

但是,block_reduce假设每个网格单元具有相同的大小.当每个网格单元具有不同的大小时,如何解决此问题?在这种情况下,每个网格单元的大小由numpy数组area_cell给出

– 编辑:

一个例子:

ARR

0.25    0.58    0.69    0.74
0.49    0.11    0.10    0.41
0.43    0.76    0.65    0.79
0.72    0.97    0.92    0.09

如果area_cell的所有元素都是1,我们将4 x 4 arr转换为2 x 2,结果将是:

0.36    0.48
0.72    0.61

但是,如果area_cell如下:

0.00    1.00    1.00    0.00
0.00    1.00    0.00    0.50
0.20    1.00    0.80    0.80
0.00    0.00    1.00    1.00

然后,结果变为:

0.17    0.22
0.21    0.54

最佳答案 看起来你仍在减少块数,但在使用area_cell缩放之后.所以,你只需要在这两个数组之间执行逐元素乘法,并在该产品数组上使用相同的block_reduce代码,就像这样 –

block_reduce(arr*area_cell, block_size=(2, 2), func=np.ma.mean)

或者,我们可以在重新塑造到产品阵列的4D版本之后简单地使用np.mean,就像这样 –

m,n = arr.shape
out = (arr*area_cell).reshape(m//2,2,n//2,2).mean(axis=(1,3))

样品运行 –

In [21]: arr
Out[21]: 
array([[ 0.25,  0.58,  0.69,  0.74],
       [ 0.49,  0.11,  0.1 ,  0.41],
       [ 0.43,  0.76,  0.65,  0.79],
       [ 0.72,  0.97,  0.92,  0.09]])

In [22]: area_cell
Out[22]: 
array([[ 0. ,  1. ,  1. ,  0. ],
       [ 0. ,  1. ,  0. ,  0.5],
       [ 0.2,  1. ,  0.8,  0.8],
       [ 0. ,  0. ,  1. ,  1. ]])

In [23]: block_reduce(arr*area_cell, block_size=(2, 2), func=np.ma.mean)
Out[23]: 
array([[ 0.1725 ,  0.22375],
       [ 0.2115 ,  0.5405 ]])

In [24]: m,n = arr.shape

In [25]: (arr*area_cell).reshape(m//2,2,n//2,2).mean(axis=(1,3))
Out[25]: 
array([[ 0.1725 ,  0.22375],
       [ 0.2115 ,  0.5405 ]])
点赞