计算每个图像块的平均值-Python

时间:2019-12-13 09:32:24

标签: python python-3.x numpy

我有一个像下面的矩阵

c = [[ 1 2 3 4 5 6 7 8 9 1]
     [ 2 3 4 5 6 7 8 9 1 2]
     [ 3 4 5 6 7 8 9 1 2 3]
     [ 4 5 6 7 8 9 1 2 3 4]]

根据本文中给定的SO ANSWERS,我使用它将矩阵分成如下所示的块(2 * 5)

def blockshaped(arr, nrows, ncols):
"""
Return an array of shape (n, nrows, ncols) where
n * nrows * ncols = arr.size

If arr is a 2D array, the returned array should look like n subblocks with
each subblock preserving the "physical" layout of arr.
"""
    h, w = arr.shape
    assert h % nrows == 0, "{} rows is not evenly divisble by {}".format(h, nrows)
    assert w % ncols == 0, "{} cols is not evenly divisble by {}".format(w, ncols)
    return (arr.reshape(h//nrows, nrows, -1, ncols)
           .swapaxes(1,2)
           .reshape(-1, nrows, ncols))


print(blockshaped(c, 2, 5))

Result:

[[[ 1 2 3 4 5 ]
  [ 2 3 4 5 6 ]]

 [[ 6 7 8 9 1 ]
  [ 7 8 9 1 2]]

 [[ 3 4 5 6 7 ]
  [ 4 5 6 7 8 ]]

 [[ 8 9 1 2 3 ]
  [ 9 1 2 3 4]]]

我有4个矩阵块,现在我需要每个块的平均值。如何计算每个块的平均值?

当我尝试使用mean()时,它将计算整个矩阵的平均值,而不是每个块的平均值。

2 个答案:

答案 0 :(得分:1)

1。 列表理解

的半行解决方案
results = blockshaped(c, 2, 5)
block_means = [np.mean(results[block,:,:]) for block in range(results.shape[0])]

print(block_means)
# [3.5, 5.8, 5.5, 4.2]

版本2-较短的代码

results = blockshaped(c, 2, 5)
block_means = [np.mean(block) for block in results]
# [3.5, 5.8, 5.5, 4.2]

In [15]: %timeit [np.mean(results[block,:,:]) for block in range(results.shape[0])]
10000 loops, best of 3: 35.9 µs per loop

In [16]: %timeit [np.mean(block) for block in results]
10000 loops, best of 3: 33.4 µs per loop

P.S:仅当块位于results的第一(0)维中时,第二种解决方案才有效。

答案 1 :(得分:1)

另一种选择是使用map函数:

means = np.round(map(np.mean, r),3)
print(means)

结果为:

  

[3.5 5.8 5.5 4.2]