5

I have a numpy array which has the following shape: (1, 128, 160, 1).

Now, I have an image which has the shape: (200, 200).

So, I do the following:

orig = np.random.rand(1, 128, 160, 1)
orig = np.squeeze(orig)

Now, what I want to do is take my original array and interpolate it to be of the same size as the input image i.e. (200, 200) using linear interpolation. I think I have to specify the grid on which the numpy array should be evaluated but I am unable to figure out how to do it.

Luca
  • 10,458
  • 24
  • 107
  • 234
  • 2
    If you meant *bilinear* interpolation – [`scipy.interpolate.interp2d`](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.interp2d.html) – meowgoesthedog Mar 27 '19 at 09:41
  • @meowgoesthedog Ahhhh ok, so the sampling grid can just be defined simply as a meshed grid or something? – Luca Mar 27 '19 at 10:53

1 Answers1

6

You can do it with scipy.interpolate.interp2d like this:

from scipy import interpolate

# Make a fake image - you can use yours.
image = np.ones((200,200))

# Make your orig array (skipping the extra dimensions).
orig = np.random.rand(128, 160)

# Make its coordinates; x is horizontal.
x = np.linspace(0, image.shape[1], orig.shape[1])
y = np.linspace(0, image.shape[0], orig.shape[0])

# Make the interpolator function.
f = interpolate.interp2d(x, y, orig, kind='linear')

# Construct the new coordinate arrays.
x_new = np.arange(0, image.shape[1])
y_new = np.arange(0, image.shape[0])

# Do the interpolation.
new_orig = f(x_new, y_new)

Note the -1 adjustment to the coordinate range when forming x and y. This ensures that the image coordinates go from 0 to 199 inclusive.

Matt Hall
  • 7,614
  • 1
  • 23
  • 36