python扩展2d数组并插值缺失的值

2024-09-29 23:21:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

^{pr2}$

其中,将这些“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文件


Tags: infornpscipy数组解决方案arraypts
1条回答
网友
1楼 · 发布于 2024-09-29 23:21:36

虽然interpolate没有用于此特定任务的函数,但您可以轻松地使用内置选项来执行此操作。用你建议的同样的例子

[1 2 3]
[4 5 6]
[7 8 9]

^{pr2}$

我们可以用这个密码

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

或者,作为图像

Original image

Interpolated image

在本例中,我使用了griddata,它将一组点(pts)上定义的集函数(vals)插值到给定的直线网格(由grid_xgrid_y)插值。例如,如果您想对$x$使用nx点,而对$y$使用ny,则可以替换一行

grid_x, grid_y = np.mgrid[0:1:nx*1j, 0:1:ny*1j]

对于nx=20ny=15我们得到了这张图片

enter image description here

您可以在documentation of the function上看到更多示例。在

更新:包括示例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()

生成的图像是: Example 2 ^{5美元

相关问题 更多 >

    热门问题