1

I have a feeling this will be really simple, but I seem to be completely stuck on it. I'm trying to take a bounding box, and resample it to MxN. Let's say I'm taking the dog's bounding box, and resampling it to 256x256. It's going to mess up the aspect ratio, but that's ok.

enter image description here

In matlab, I would use interp2. In python, I've tried scipy.interpolate.interp2d and scipy.interpolate.RectBivariateSpline.

I'm getting errors like:

*** ValueError: x dimension of z must have same number of elements as x

but I want x and z to have different numbers of elements. Isn't the whole point of interpolating to increase the number of elements over a given range?

I have tried with both interp2d and RectBivariateSpline, and with linear and meshgrid inputs. Breaking down cropping and interpolating into two separate steps hasn't helped either.

Here's my attempt:

from PIL import Image
import requests
from io import BytesIO

import matplotlib.pyplot as plt
import numpy as np
from scipy import interpolate

url = "https://i.stack.imgur.com/7zYzr.png"
response = requests.get(url)
img = np.array(Image.open(BytesIO(response.content)))

print(img.shape)

plt.figure()
plt.imshow(img)
plt.draw()

bbox = [0, 82, 181, 412]
crop_w = 256
crop_h = 256

x = np.linspace(bbox[0],bbox[2],crop_w)
y = np.linspace(bbox[1],bbox[3],crop_h)
my_crop = np.zeros((crop_w, crop_h, 3))
for RGB in range(3):
    my_crop[:,:,RGB] = interpolate.RectBivariateSpline(x, y, img[:,:,RGB])

plt.figure()
plt.imshow(my_crop)
plt.show()
Cleb
  • 25,102
  • 20
  • 116
  • 151
craq
  • 1,441
  • 2
  • 20
  • 39
  • My answer in the duplicate exactly answers your question also. – Cris Luengo Nov 13 '18 at 14:05
  • @CrisLuengo thanks, that got me there in the end. It seems quite inefficient to crop and then generate a function as an intermediate steps, but anyway, it works now. I was able to swap in `RectBivariateSpline` for `interp2d` just by swapping the `x` and `y` arguments... Should I delete this question since it's a duplicate, or leave it linked to the other question? – craq Nov 13 '18 at 22:55
  • 1
    Please leave the question up. Duplicates are considered good sign posts to direct people to their answer. I'm not sure what `interp2d` and `RectBivariateSpline` do internally, it might not be any less efficient than MATLAB's solution. It's more typing, though. :) – Cris Luengo Nov 13 '18 at 23:08

0 Answers0