我有一个 2D numpy 数组,它表示来自 CCD 的单色图像,该图像已合并为 3x3(也就是说,数组中的每个值代表物理 CCD 上的 9 个像素 (3x3))。
我想重新缩放它以匹配原始 CCD 布局(这样我就可以轻松地将它与来自同一 CCD 的非合并图像叠加)。
我看到了Resampling a numpy array representing an image ,但这似乎并不能满足我的要求。
假设我有一个数组 g:
import numpy as np
import scipy.ndimage
g = np.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
当我尝试将它缩放 2 倍时:
o = scipy.ndimage.zoom(g, 2, order=0)
我得到的正是我所期望的 - 每个值现在都是 2x2 相同的值:
array([[0, 0, 1, 1, 2, 2],
[0, 0, 1, 1, 2, 2],
[3, 3, 4, 4, 5, 5],
[3, 3, 4, 4, 5, 5],
[6, 6, 7, 7, 8, 8],
[6, 6, 7, 7, 8, 8]])
但是当我尝试按 3 倍缩放时,我得到了这个:
o = scipy.ndimage.zoom(g, 3, order=0)
给我:
array([[0, 0, 1, 1, 1, 1, 2, 2, 2],
[0, 0, 1, 1, 1, 1, 2, 2, 2],
[3, 3, 4, 4, 4, 4, 5, 5, 5],
[3, 3, 4, 4, 4, 4, 5, 5, 5],
[3, 3, 4, 4, 4, 4, 5, 5, 5],
[3, 3, 4, 4, 4, 4, 5, 5, 5],
[6, 6, 7, 7, 7, 7, 8, 8, 8],
[6, 6, 7, 7, 7, 7, 8, 8, 8],
[6, 6, 7, 7, 7, 7, 8, 8, 8]])
我希望原始数组中的每个值都变成一组 3x3 值...这不是我得到的。
我该怎么做? (为什么我会得到这个不直观的结果?)
最佳答案
您可以使用 np.kron
:
In [16]: g
Out[16]:
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
In [17]: np.kron(g, np.ones((3,3), dtype=int))
Out[17]:
array([[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[0, 0, 0, 1, 1, 1, 2, 2, 2],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[3, 3, 3, 4, 4, 4, 5, 5, 5],
[6, 6, 6, 7, 7, 7, 8, 8, 8],
[6, 6, 6, 7, 7, 7, 8, 8, 8],
[6, 6, 6, 7, 7, 7, 8, 8, 8]])
zoom(g, 3, order=0)
的输出有点令人惊讶。考虑第一行:[0, 0, 1, 1, 1, 1, 2, 2, 2]
。为什么有四个 1
?
当 order=0
zoom(有效)计算 np.linspace(0, 2, 9)
时,看起来像
In [80]: np.linspace(0, 2, 9)
Out[80]: array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ])
然后四舍五入这些值。如果你使用 np.round()
,你会得到:
In [71]: np.round(np.linspace(0, 2, 9)).astype(int)
Out[71]: array([0, 0, 0, 1, 1, 1, 2, 2, 2])
注意 np.round(0.5)
给出 0
,但是 np.round(1.5)
给出 2
。 np.round()
使用 "round half to even" tie-breaking rule .显然,在 zoom
代码中完成的舍入使用了 "round half down" rule : 它将 0.5
舍入到 0
并将 1.5
舍入到 1
,如下所示
In [81]: [int(round(x)) for x in np.linspace(0, 2, 9)]
Out[81]: [0, 0, 1, 1, 1, 1, 2, 2, 2]
这就是为什么里面有四个 1
的原因。
关于python - 重新缩放一个 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25676247/