![](/img/trans.png)
[英]Replace all elements of Numpy array greater than threshold with average of X adjacent values
[英]numpy replace array elements with average of 2*2 blocks
我在numpy
有一个m*n matrix
。 我想将矩阵分成2 * 2块,然后将每个元素替换为其块中元素的平均值。 例如考虑以下数组:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
]
我想产生这个矩阵:
[
[3.5, 3.5, 5.5, 5.5]
[3.5, 3.5, 5.5, 5.5]
[11.5, 11.5, 13.5, 13.5]
[11.5, 11.5, 13.5, 13.5]
]
最有效的方法是什么? 我应该使用循环吗?
一种方法是重塑形状,将这两个轴分别分成两个,并沿着这两个轴的mean
求mean
,从而得到平均值。 我们将保持尺寸为keepdims=True
,以便以后在最终输出时使用np.repeat
便于沿精简轴进行复制。
因此,一种实现方式是-
b = a.reshape(2,2,2,2).mean((1,3), keepdims=1)
out = np.repeat(np.repeat(b,(2),axis=(1)),(2), axis=3).reshape(4,4)
样品运行-
In [17]: a
Out[17]:
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12],
[13, 14, 15, 16]])
In [18]: b = a.reshape(2,2,2,2).mean((1,3), keepdims=1)
In [19]: np.repeat(np.repeat(b,(2),axis=(1)),(2), axis=3).reshape(4,4)
Out[19]:
array([[ 3.5, 3.5, 5.5, 5.5],
[ 3.5, 3.5, 5.5, 5.5],
[ 11.5, 11.5, 13.5, 13.5],
[ 11.5, 11.5, 13.5, 13.5]])
一般而言,解决方案如下所示-
m,n = a.shape
p,q = (2,2) # Block size
b = a.reshape(m//p,p,n//q,q).mean((1,3), keepdims=1)
out = np.repeat(np.repeat(b,(p),axis=(1)),(q), axis=3).reshape(a.shape)
性能提升
我们可以将复制部分替换为基于初始化的部分,如下所示:
out = np.empty((m//p,p,n//q,q),dtype=float)
out[:] = b
out.shape = a.shape
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.