在 python 中的网格内插值

Interpolating within a grid in python

我在一个网格中有许多高度值,在一系列列表中指定:

[3, 1, -2, -3, -3] # x = 0m 
[2, -7, -14, -30, -39] # x = 10m
[46, 22, 5, -2, -8] # x = 20m

上面的示例显示了一个 40m x 20m 的网格,格式为

[x=0y=0, x=0y=10...][x=10y=0, x=10y=10...] etc.

我需要计算特定 x,y 坐标处的高度。我查看了各种插值函数和示例,但无法理解它们 - 请帮忙!

一个例子是上面网格中 x = 5m、y = 5m 处的高度,它位于值 3、1、2 和 -7(-1ish?)的中间

谢谢

解法:转化为二维数组

import numpy as np

a = [3, 1, -2, -3, -3] # x = 0m 
b = [2, -7, -14, -30, -39] # x = 10m
c = [46, 22, 5, -2, -8] # x = 20m

all_lists = [a,b,c]


grid = np.vstack(all_lists) # Edit: thanks @jochen for better code

>>print(grid.shape)
(3, 5)

现在您可以通过 x,y 坐标访问网格

grid[1,1] 等等

基于此,您可以创建逻辑。

如果x = 5, y = 5,那么你可以这样创建方角索引:

indexes: x/5 +0, x/5+1, y/5,y/5+1 ---> 通过组合它们你得到 [0,0] ,[0,1],[1,0],[1,1]

最后你只需将这些索引输入网格

SUM = grid[0,0] + grid[0,1] + grid[1,0] + grid[1,1]

您可以使用 scipy.interpolate.interp2d。下面的代码应该可以完成这项工作:

import numpy as np
from scipy.interpolate import interp2d

# Original data (e.g. measurements)
a = [3, 1, -2, -3, -3]
b = [2, -7, -14, -30, -39]
c = [46, 22, 5, -2, -8]

x = [0, 10, 20]             # x-coordinates
y = [0, 10, 20, 30, 40]     # y-coordinates

# Organise data in matrix
z = np.vstack([a, b, c]).T

# Create interpolation function
f_z = interp2d(x, y, z)

# Desired x/y values
x_interp = 5
y_interp = 5

# Collect interpolated z-value
z_interp = f_z(x_interp, y_interp)
print(z_interp)  # (result: [-0.25])

您可以通过 interpolate.gridddata function from scipy 实现。

使用下面的代码,您可以从网格中获得您想要的任何插值。

import itertools
import numpy as np
from scipy.interpolate import griddata

dataX0 = [3, 1, -2, -3, -3] # x = 0m
dataX10 = [2, -7, -14, -30, -39] # x = 10m
dataX20 = [46, 22, 5, -2, -8] # x = 20m
data = dataX0 + dataX10 + dataX20
points = list(itertools.product(range(0,30,10),range(0,50,10)))

outputPoint = (5,5)
outputValue = griddata(points=points,values=data, xi=outputPoint, method="cubic")
print outputValue

上面的示例为您提供了 ouputPoint (5,5) 处的插值。输出将给出:

>>> 
-2.78976054957