Interpolation bilinéaire avec python

Example de comment faire une interpolation lineaire avec python (source) dans le cas ou les données de départs sont déjà placées sur une grille régulière (scipy.interpolate.interp2d):

Interpolation bilinéaire avec python et matplotlib (1/2)
Interpolation bilinéaire avec python et matplotlib (1/2)

Interpolation bilinéaire avec python et matplotlib (2/2)
Interpolation bilinéaire avec python et matplotlib (2/2)

from scipy import interpolate

import numpy as np
import matplotlib.pyplot as plt

#----- Define a function -----#

def f(x,y):
    return (x+y)*np.exp(-5.0*(x**2+y**2))

#----- Grid -----#

x,y = np.mgrid[-1:1:15j, -1:1:15j]

z = f(x,y)

#----- Plot 1 -----#

plt.imshow(z,extent=[-1,1,-1,1])
plt.savefig("BilinearInterpolation01.png")
plt.show()

#----- Define interpolation bilinear -----#

z_interp = interpolate.interp2d(x,y,z, kind='cubic')

#-----Apply -----#

xnew = np.linspace(-1,1,100)
ynew = xnew
z_new = z_interp(xnew,xnew)

#----- Plot 2 -----#

plt.clf()

plt.imshow(z_new,extent=[-1,1,-1,1])
plt.savefig("BilinearInterpolation02.png")
plt.show()

Dans le cas ou les données ne sont pas placées régulièrement il faut passser par scipy.interpolate.griddata

Interpolation bilinéaire avec python (Grille Irrégulière) (1/2)
Interpolation bilinéaire avec python (Grille Irrégulière) (1/2)

Interpolation bilinéaire avec python (Grille Irrégulière) (2/2)
Interpolation bilinéaire avec python (Grille Irrégulière) (2/2)

from scipy.interpolate import griddata
from numpy.random import uniform, seed

import numpy as np
import matplotlib.pyplot as plt

#----- Define a function -----#

def f(x,y):
    return (x+y)*np.exp(-5.0*(x**2+y**2))

seed(1234)

x = uniform(-1,1,400)
y = uniform(-1,1,400)
z = f(x, y)

#----- Plot 1 -----#

x_test, y_test = np.mgrid[-1:1:100j, -1:1:200j]

z_test = f(x_test,y_test)

plt.scatter(x,y,marker='o',c='b',s=5)
plt.imshow(z_test,extent=[-1,1,-1,1])

plt.savefig("BilinearInterpolationIGrid01.png")
plt.show()

#----- Interpolation -----#

xi, yi = np.mgrid[-1:1:300j, -1:1:300j]

zi = griddata((x, y), z, (xi, yi), method='cubic')

#----- Plot 2 -----#

print zi.shape

plt.scatter(x,y,marker='o',c='b',s=5)
plt.imshow(zi,extent=[-1,1,-1,1])

plt.savefig("BilinearInterpolationIGrid02.png")
plt.show()

Recherches associées

Image

of