Home > Software engineering >  Python: Increase resolution of 2D Array (As in split the pixels)
Python: Increase resolution of 2D Array (As in split the pixels)

Time:01-06

I want to resize a 2D array of the size (25,180) to size (50,360) with keeping all the values at the same relative place. If it was an image id should still look the same but have 4 times the pixels. So for a smaller array example of (2,3):

 ((1,3,6),
  (4,7,8))

it should look like (4,6):

((1,1,3,3,6,6),
 (1,1,3,3,6,6),
 (4,4,7,7,8,8),
 (4,4,7,7,8,8))

I have tried resize and reshape but none seemed to do the job for me. formulating this question i have found an easy solution using loops:

But I bet theres a clever and/or build in function for something like this right?

I have tried resize and reshape but none seemed to do the job for me. formulating this question i have found an easy solution using loops. But I bet theres a clever and/or build in function for something like this right?

ary = np.array(((1,3,6),(4,7,8)))
aarryy=np.zeros((4,6))
for i in range(len(ary)):
    #print(ary[i])
    for j in range(len(ary[i])):
        #print(ary[i][j])
        aarryy[i*2][j*2]=ary[i][j]
        aarryy[i*2][j*2 1]=ary[i][j]
    aarryy[i*2 1]=aarryy[i*2]

CodePudding user response:

I am pretty sure there are some more elegant numpy magic (indexing is one of my weak point in numpy), and that someone will post one. But in the meantime, here is a one-liner

ary[np.arange(len(ary)*2)//2][:,np.arange(ary.shape[1]*2)//2]

The trick is that np.arange(n*2)//2 is array([0,0,1,1,...,n-1,n-1]. So I use that to index lines, and then same for columns

CodePudding user response:

(First time I post 2 answers instead of editing the 1st one. Hope I am not doing something wrong by doing so, but since the possibility exists, and that my two answers are totally different way to do the same thing, I guess this is appropriate)

Another way is use hstack to duplicate lines. That way

np.hstack([ary,ary]).reshape(len(ary)*2,-1)

is

array([[1, 3, 6],
       [1, 3, 6],
       [4, 7, 8],
       [4, 7, 8]])

You can't directly duplicate columns the same way (lines and columns are not really dual. You can't just do the same with vstack)

But you can do the same operation on the transposed matrix, then transpose the result back

So

ar2=np.hstack([ary,ary]).reshape(len(ary)*2,-1)
resized=np.hstack([ar2.T, ar2.T]).reshape(len(ar2.T)*2, -1).T
  • Related