我有一个大的像素网格(2000 x 2000),只在某些(x,y)坐标处定义值。例如,这个简化版本看起来像这样:
-5-3--
---0--
-6--4-
-4-5--
---0--
-6--4-
如何进行线性插值或最近邻插值,以便在网格的每个位置都有定义的值。
我有一个大的像素网格(2000 x 2000),只在某些(x,y)坐标处定义值。例如,这个简化版本看起来像这样:
-5-3--
---0--
-6--4-
-4-5--
---0--
-6--4-
如何进行线性插值或最近邻插值,以便在网格的每个位置都有定义的值。
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'
- Devymexoutgrid = griddata(points, values, gridcoords, method='nearest') 回溯(最近的调用): File "<stdin>", line 1, in <module> NameError: 名称 'gridcoords' 未定义
- undefinedoutgrid = griddata(points, values, gridcoords, method='nearest') 回溯(最近的调用最后): File "<stdin>", line 1, in <module> NameError: 名称 'gridcoords' 未定义
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')
使用以下代码行,您可以非常简单地进行最近邻插值:
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中发布了一个带有完整示例的答案。