[英]python - Extend 2-d array and interpolate the missing values
我有一个大小为48x80的数组,现在我想将数组扩展为一个大小为117x192的新数组。
我读过有关scipy.interpolate的内容 ,但没有提到有关扩展的内容。
如何扩展数组并将值放入新数组?
例如:给定数组A [[1,2,3],[4,5,6],[7,8,9]]
[1 2 3]
[4 5 6]
[7 8 9]
现在我想将数组A扩展到数组B大小为5x7
1 x 2 x 3
x x x x x
x x x x x
4 x 5 x 6
x x x x x
x x x x x
7 x 8 x 9
其中,用插值替换这些'x'。
例2:更一般的数组
[4 2 6 4]
[4 34 6 2]
[2 11 3 4]
[2 4 22 4]
[2 1 35 255]
[1 3 4 54]
[22 1 4 5]
如果我想要一个大小为20x30的新阵列,我该怎么办?
更新:我发现有一个区别让@nicoguaro的答案在我的情况下不起作用:
他的解决方案
pts = np.array([[i,j] for i in np.linspace(0,1,n) for j in np.linspace(0,1,m)] )
grid_x, grid_y = np.mgrid[0:1:m*2j, 0:1:n*2j]
我的解决方案
pts = np.array([[i,j] for i in np.linspace(0,2*m-1,m) for j in np.linspace(0,2*n-1,n)] )
grid_x, grid_y = np.mgrid[0:m*2, 0:n*2]
这会导致不同的结果。 事实上,他的解决方案适用于大多数情况,但我认为是TIFF文件
虽然插值没有针对此特定任务的功能,但您可以轻松使用内置选项来执行此操作。 使用您建议的相同示例
[1 2 3]
[4 5 6]
[7 8 9]
至
1 x 2 x 3
x x x x x
x x x x x
4 x 5 x 6
x x x x x
x x x x x
7 x 8 x 9
我们可以使用这段代码
import numpy as np
import scipy.interpolate as inter
import matplotlib.pyplot as plt
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
vals = np.reshape(A, (9))
pts = np.array([[i,j] for i in [0.0, 0.5, 1.0] for j in [0.0, 0.5, 1.0]] )
grid_x, grid_y = np.mgrid[0:1:7j, 0:1:5j]
grid_z = inter.griddata(pts, vals, (grid_x, grid_y), method='linear')
这就是结果
array([[ 1. , 1.5, 2. , 2.5, 3. ],
[ 2. , 2.5, 3. , 3.5, 4. ],
[ 3. , 3.5, 4. , 4.5, 5. ],
[ 4. , 4.5, 5. , 5.5, 6. ],
[ 5. , 5.5, 6. , 6.5, 7. ],
[ 6. , 6.5, 7. , 7.5, 8. ],
[ 7. , 7.5, 8. , 8.5, 9. ]])
或者,作为图像
在这种情况下,我使用griddata
将一组点( pts
)上定义的集合函数( vals
)插值到给定的直线网格(由grid_x
和grid_y
)。 例如,如果要为$ x $使用nx
点,为$ y $使用ny
,则可以替换一行
grid_x, grid_y = np.mgrid[0:1:nx*1j, 0:1:ny*1j]
对于nx=20
和ny=15
我们得到了这个图像
更新:包括示例2,矩阵在哪里
A = np.array([[4, 2, 6, 4],
[4, 34, 6, 2],
[2, 11, 3, 4],
[2, 4, 22, 4],
[2, 1, 35, 255],
[1, 3, 4, 54],
[22, 1, 4, 5]])
以及一个大小为20x30的新阵列。 代码如下
import numpy as np
import scipy.interpolate as inter
import matplotlib.pyplot as plt
A = np.array([[4, 2, 6, 4],
[4, 34, 6, 2],
[2, 11, 3, 4],
[2, 4, 22, 4],
[2, 1, 35, 255],
[1, 3, 4, 54],
[22, 1, 4, 5]])
vals = np.reshape(A, (28))
pts = np.array([[i,j] for i in np.linspace(0,1,4) for j in np.linspace(0,1,7)] )
grid_x, grid_y = np.mgrid[0:1:20j, 0:1:30j]
grid_z = inter.griddata(pts, vals, (grid_x, grid_y), method='linear')
plt.matshow(A)
plt.matshow(grid_z)
plt.show()
生成的图像是:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.