Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues with 2D-Interpolation in Scipy

In my application, the data data is sampled on a distorted grid, and I would like to resample it to a nondistorted grid. In order to test this, I wrote this program with examplary distortions and a simple function as data:

from __future__ import division

import numpy as np
import scipy.interpolate as intp
import pylab as plt

# Defining some variables:

quadratic = -3/128
linear = 1/16
pn = np.poly1d([quadratic, linear,0])

pixels_x = 50
pixels_y = 30
frame = np.zeros((pixels_x,pixels_y))

x_width= np.concatenate((np.linspace(8,7.8,57) , np.linspace(7.8,8,pixels_y-57)))

def data(x,y):
    z = y*(np.exp(-(x-5)**2/3) + np.exp(-(x)**2/5) + np.exp(-(x+5)**2))
    return(z)

# Generating grid coordinates

yt = np.arange(380,380+pixels_y*4,4)
xt = np.linspace(-7.8,7.8,pixels_x)
X, Y = np.meshgrid(xt,yt)
Y=Y.T
X=X.T

Y_m = np.zeros((pixels_x,pixels_y))
X_m = np.zeros((pixels_x,pixels_y))

# generating distorted grid coordinates:    

for i in range(pixels_y):
    Y_m[:,i] = Y[:,i] - pn(xt)
    X_m[:,i] = np.linspace(-x_width[i],x_width[i],pixels_x)


# Sample data:
for i in range(pixels_y):
    for j in range(pixels_x):
        frame[j,i] = data(X_m[j,i],Y_m[j,i])


Y_m = Y_m.flatten()
X_m = X_m.flatten()
frame = frame.flatten()
##
Y = Y.flatten()
X = X.flatten()
ipf = intp.interp2d(X_m,Y_m,frame)
interpolated_frame = ipf(xt,yt)

At this point, I have to questions:

  1. The code works, but I get the the following warning:

    Warning: No more knots can be added because the number of B-spline coefficients already exceeds the number of data points m. Probably causes: either s or m too small. (fp>s) kx,ky=1,1 nx,ny=54,31 m=1500 fp=0.000006 s=0.000000

Also, some interpolation artifacts appear, and I assume that they are related to the warning - Do you guys know what I am doing wrong?

  1. For my actual applications, the frames need to be around 500*100, but when doing this, I get a MemoryError - Is there something I can do to help that, apart from splitting the frame into several parts?

Thanks!

like image 306
Dzz Avatar asked Oct 10 '10 09:10

Dzz


2 Answers

This problem is most likely related to the usage of bisplrep and bisplev within interp2d. The docs mention that they use a smooting factor of s=0.0 and that bisplrep and bisplev should be used directly if more control over s is needed. The related docs mention that s should be found between (m-sqrt(2*m),m+sqrt(2*m)) where m is the number of points used to construct the splines. I had a similar problem and found it solved when using bisplrep and bisplev directly, where s is only optional.

like image 99
Andre Avatar answered Nov 05 '22 11:11

Andre


For 2d interpolation, griddata is solid, local, fast. Take a look at problem-with-2d-interpolation-in-scipy-non-rectangular-grid on SO.

like image 1
denis Avatar answered Nov 05 '22 11:11

denis