gpt4 book ai didi

python - 根据单元格区域重新排列 numpy 数组

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:54 26 4
gpt4 key购买 nike

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)

我想将一个 numpy 数组 arr 从 6 x 6 大小重新网格化为 3 x 3。为此使用 skimage 函数 block_reduce。

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

给出

-- 编辑:

一个例子:

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

最佳答案

看来您仍在按 block 减少,但是在使用 area_cell 缩放 arr 之后。因此,您只需要在这两个数组之间执行逐元素乘法,并在该乘积数组上使用相同的 block_reduce 代码,就像这样 -

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

或者,我们可以简单地使用 np.mean在 reshape 为产品数组的 4D 版本之后,就像这样 -

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

sample 运行-

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 ]])

关于python - 根据单元格区域重新排列 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39275552/

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