使用Python(最好是Scipy)进行稀疏网格插值

5

我有一个大的像素网格(2000 x 2000),只在某些(x,y)坐标处定义值。例如,这个简化版本看起来像这样:

-5-3--
---0--
-6--4-
-4-5--
---0--
-6--4-

如何进行线性插值或最近邻插值,以便在网格的每个位置都有定义的值。


也许你可以在这个或者这个问题中找到答案。 - tiago
对于2行最近邻插值,请查看此处 - Juh_
3个回答

3
使用Scipy函数:
import numpy as np
from scipy.interpolate import griddata # not quite the same as `matplotlib.mlab.griddata`

# a grid of data
grid = np.random.random((10, 10))
# a mask defining where the data is valid
mask = np.random.random((10, 10)) < 0.2

# locations and values of the valid data points
points = mask.nonzero()
values = grid[points]
gridx, gridy = np.mgrid[:grid.shape[0], :grid.shape[1]]

outgrid = griddata(points, values, (gridx, gridy), method='nearest') # or method='linear', method='cubic'

运行时错误:>>> gridcoords = np.meshgrid[:grid.shape(0), :grid.shape(1)] 回溯(最近的调用): File "<stdin>", line 1, in <module> TypeError: 'tuple' 对象不可调用
outgrid = griddata(points, values, gridcoords, method='nearest') 回溯(最近的调用): File "<stdin>", line 1, in <module> NameError: 名称 'gridcoords' 未定义
- Devymex
运行时错误:>>> gridcoords = np.meshgrid[:grid.shape(0), :grid.shape(1)] 回溯(最近的调用最后): File "<stdin>", line 1, in <module> TypeError: 'tuple' 对象不可调用
outgrid = griddata(points, values, gridcoords, method='nearest') 回溯(最近的调用最后): File "<stdin>", line 1, in <module> NameError: 名称 'gridcoords' 未定义
- undefined
@Devymex 感谢你的报告 - 看来在发布之前我没有好好测试这个。真让人惊讶,居然花了10年才有人注意到!现在已经修复了。 - nneonneo
@Devymex 谢谢你的报告 - 看来我在发布之前没有好好测试这个。很惊讶竟然花了10年才有人注意到!现在已经修复了。 - undefined

2
这是我的尝试。
import numpy as np
from matplotlib.mlab import griddata

##Generate a random sparse grid
grid = np.random.random((6,6))*10
grid[grid>5] = np.nan

## Create Boolean array of missing values
mask = np.isfinite(grid)

## Get all of the finite values from the grid
values = grid[mask].flatten()

## Find indecies of finite values
index = np.where(mask==True)

x,y = index[0],index[1]

##Create regular grid of points
xi = np.arange(0,len(grid[0,:]),1)
yi = np.arange(0,len(grid[:,0]),1)

## Grid irregular points to regular grid using delaunay triangulation
ivals = griddata(x,y,values,xi,yi,interp='nn')

这是我如何将不均匀分布的点插值为正则网格。 我没有尝试过其他类型的插值方法(例如线性插值)。

是的,我从来没有成功地使用过'scipy.interpolate'。顺便说一句,谢谢你。 - captain_M

0

使用以下代码行,您可以非常简单地进行最近邻插值:

from scipy import ndimage as nd

indices = nd.distance_transform_edt(invalid_cell_mask, return_distances=False, return_indices=True)
data = data[tuple(ind)]

invalid_cell_mask是一个布尔掩码数组,表示未定义的数组单元格,data是要填充的数组。

我在Filling gaps in a numpy array中发布了一个带有完整示例的答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接