Reputation: 67
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 that I can do it with numpy.repeat
if for example I have to double the size but lets say I want to convert an array of size (180,150)
to (300,250)
. I know there is not a perfect way to do this but I am looking for the most efficient (minimum loss of information) method!
So far, I was converting the array to an image and resize it accordingly, then convert it to an array again. However, it seems that I cannot convert all types of data to image so I need a general way to do this.
For example, lets say I have an input array of size (2,2)
:
input_array=np.array([[1,2],[3,4]])
If I want to convert it to a (3,3)
array, output may be like:
output_array=np.array([[1,1,2],[1,1,2],[3,3,4]])
Like I said before, I just don't want to tile or fill with zeros, I want to expand the size by repeating some of the elements.
Upvotes: 1
Views: 1895
Reputation: 14167
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]
Upvotes: 3
Reputation: 8933
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:
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.]])
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.
Upvotes: 3