我有一个表示空间数据的二维 numpy 数组。我需要提高它的分辨率。我还需要在空间中均匀分布值。例如,值为
5
会变成:
1.25 1.25
1.25 1.25
我看过 imresize,但我认为插值选项对此不起作用。也许还有另一种方法?如果可以的话,我想避免迭代行和列。任何帮助将不胜感激!谢谢!
最佳答案
简单地除以由其高度和宽度定义的 block 中的元素数,然后复制/扩展。要复制,我们可以使用 np.repeat
或 np.lib.stride_tricks.as_strided
。
与 np.repeat
-
def upscale_repeat(a, h, w):
return (a/float(h*w)).repeat(h, axis=0).repeat(h, axis=1)
与 np.lib.stride_tricks.as_strided
使用 tile_array
-
def upscale_strided(a, h, w):
return tile_array(a/float(h*w), h, w)
sample 运行-
In [140]: a
Out[140]:
array([[ 7, 6, 9],
[ 6, 6, 10]])
In [141]: upscale_repeat(a, 2, 2)
Out[141]:
array([[ 1.75, 1.75, 1.5 , 1.5 , 2.25, 2.25],
[ 1.75, 1.75, 1.5 , 1.5 , 2.25, 2.25],
[ 1.5 , 1.5 , 1.5 , 1.5 , 2.5 , 2.5 ],
[ 1.5 , 1.5 , 1.5 , 1.5 , 2.5 , 2.5 ]])
In [142]: upscale_repeat(a, 2, 3)
Out[142]:
array([[ 1.17, 1.17, 1.17, 1. , 1. , 1. , 1.5 , 1.5 , 1.5 ],
[ 1.17, 1.17, 1.17, 1. , 1. , 1. , 1.5 , 1.5 , 1.5 ],
[ 1. , 1. , 1. , 1. , 1. , 1. , 1.67, 1.67, 1.67],
[ 1. , 1. , 1. , 1. , 1. , 1. , 1.67, 1.67, 1.67]])
关于python - 升级 numpy 数组并均匀分布值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46215414/