'resize and pad numpy array with additional dimensions

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)



Solution 1:[1]

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])

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 paime
Solution 2 Zero