Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interpolation of sparse grid using python (preferably scipy)

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.

like image 239
Loccsta Avatar asked Oct 16 '12 21:10

Loccsta


2 Answers

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'
like image 89
nneonneo Avatar answered Sep 23 '22 20:09

nneonneo


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

like image 34
captain_M Avatar answered Sep 21 '22 20:09

captain_M