How To Upsample An Array To Arbitrary Sizes?
I am trying to resize an array to a larger size in Python by repeating each element proportionally to the new size. However, I want to be able to resize to arbitrary sizes. I know
Solution 1:
Without a clear idea about the final result you would like to achieve, your question opens multiple paths and solutions. Just to name a few:
- Using
numpy.resize
:
import numpy as np
input_array=np.array([[1.,2],[3,4]])
np.resize(input_array, (3,3))
you get:
array([[1., 2., 3.],
[4., 1., 2.],
[3., 4., 1.]])
- Using
cv2.resize
:
import cv2
import numpy as np
input_array=np.array([[1.,2],[3,4]])
cv2.resize(input_array,
(3,3),
interpolation=cv2.INTER_NEAREST)
you get:
array([[1., 1., 2.],
[1., 1., 2.],
[3., 3., 4.]])
Depending on your objective, you can use different interpolation methods.
Solution 2:
If you look for pure numpy solution then you can try to use fancy indexing:
outshape = 3,3
rows = np.linspace(0, input_array.shape[0], endpoint=False, num=outshape[0], dtype=int)
cols = np.linspace(0, input_array.shape[1], endpoint=False, num=outshape[1], dtype=int)
# Extract result using compute indices
output_array=input_array[rows,:][:,cols]
Post a Comment for "How To Upsample An Array To Arbitrary Sizes?"