gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:16:11 24 4
gpt4 key购买 nike

我有一个如下所示的矩阵

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在这篇文章中,我用它把矩阵分成 block (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 个矩阵 block ,现在我需要每个 block 的平均值。如何计算每个 block 的平均值?

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

最佳答案

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:仅当 block 位于结果的第一个 (0) 维度时,第二种解决方案才有效。

关于python - 计算每个图像 block 的平均值 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59319669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com