I have a large (2000 x 2000) pixel grid that have values defined at only certain (x,y) coordinates. For example, a simplified version of this would look like this:
-5-3--
---0--
-6--4-
-4-5--
---0--
-6--4-
How can I do linear interpolation or nearest neighbor interpolation so that I can have a defined value at every location in the grid.
Using a Scipy function:
import numpy as np
from scipy.interpolate import griddata # not quite the same as `matplotlib.mlab.griddata`
grid = np.random.random((10, 10))
mask = np.random.random((10, 10)) < 0.2
points = mask.nonzero()
values = grid[points]
gridcoords = np.meshgrid[:grid.shape(0), :grid.shape(1)]
outgrid = griddata(points, values, gridcoords, method='nearest') # or method='linear', method='cubic'
Here is my stab at it.
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')
This is how I go about interpolating unevenly distributed points to a regular grid. I have not tried any other type of interpolation method(ie. linear).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With