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

时间:2014-10-06 08:07:10

标签: python interpolation

我有一个大小为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 个答案:

答案 0 :(得分:4)

虽然插值没有针对此特定任务的功能,但您可以轻松使用内置选项来执行此操作。使用您提议的相同示例

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

或,作为图像

Original image

Interpolated image

在这种情况下,我使用griddata将在一组点(vals)上定义的集函数(pts)插值到给定的直线网格(由{{1}给出和grid_x)。例如,如果您想为$ y $使用grid_y点,为$ y $使用nx,则可以替换一行

ny

grid_x, grid_y = np.mgrid[0:1:nx*1j, 0:1:ny*1j] nx=20我们得到了这张图片

enter image description here

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

更新:包括示例2,其中矩阵为

ny=15

以及一个大小为20x30的新数组。代码在

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

生成的图像是: Example 2 Interpolated matrix in example 2