5

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.

Warren Weckesser
  • 102,583
  • 19
  • 173
  • 194
Loccsta
  • 81
  • 2
  • 4
  • Perhaps you can find your answer in [this](http://stackoverflow.com/questions/9478347/how-do-i-fill-holes-in-an-image) or [this](http://stackoverflow.com/questions/3242382/interpolation-over-an-irregular-grid) question. – tiago Oct 17 '12 at 03:29
  • For a 2 lignes nearest neighbor interpolation look [there](http://stackoverflow.com/questions/5551286/filling-gaps-in-a-numpy-array/9262129#9262129) – Juh_ Aug 28 '13 at 13:00

3 Answers3

3

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'
nneonneo
  • 162,933
  • 34
  • 285
  • 360
2

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

captain_M
  • 287
  • 1
  • 10
0

You can get nearest neighbor interpolation very simply using the following lines:

from scipy import ndimage as nd

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

where invalid_cell_mask is a boolean mask of the array cells that are undefined and data is the array to be filled.

I posted an answer with full example at Filling gaps in a numpy array.

Community
  • 1
  • 1
Juh_
  • 13,303
  • 7
  • 53
  • 84