Home > Back-end >  resize and pad numpy array with additional dimensions
resize and pad numpy array with additional dimensions

Time:05-03

I have an np array with shape (100,28,28)

I would like to turn it to (100,32,32,3)

by padding with zero's and adding dimensions

I tried np.newaxis which got me as far as (100,28,28,1)

CodePudding user response:

You can try the resize function on your array. This is the code I tried.

arr = np.ones((100,28,28))
arr.resize((100, 32, 32, 3))
print(arr)

The newly added items are all 0s.

CodePudding user response:

There is not enough information about how you want the padding to be done, so I'll suppose an image processing setup:

  1. Padding on both edges of the array
  2. Array must be replicated along the newly added dimension

Setup

import numpy as np

N, H, W, C = 100, 28, 28, 3
x = np.ones((N, H, W))

1. Padding

# (before, after)
padN = (0, 0)
padH = (2, 2)
padW = (2, 2)

x_pad = np.pad(x, (padN, padH, padW))

assert x_pad.shape == (N   sum(padN), H   sum(padH), W   sum(padW))

2. Replicate along a new dimensions

x_newd = np.repeat(x_pad[..., None], repeats=C, axis=-1)

assert x_newd.shape == (*x_pad.shape, C)
assert np.all(x_newd[..., 0] == x_newd[..., 1])
assert np.all(x_newd[..., 1] == x_newd[..., 2])
  • Related