AndFantasy
AndFantasy

Reputation: 73

numpy array - use np.concatenate or np.insert to prepend and append rows of zeros to ndarray

I am fairly new to numpy and I very well may be asking a stupid question, so I apologize in advance if this not a good question or if the question needs more clarifications.

The task

For example, I have an image represented as an ndarray of size (10,20,3) and I am trying to change the size of the array to (12,20,3) by inserting 1px at the beginning and at the end of the image. Essentially, I am trying to achieve image resize with padding only on the top and bottom of the image.

This is basically what I am trying to achieve, represented with arrays of smaller dimensions.

Original array

[ [[255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]]

 [[255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]]]

Modified array

[[[  0.   0.   0.]
  [  0.   0.   0.]
  [  0.   0.   0.]
  [  0.   0.   0.]]

 [[255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]]

 [[255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]]

 [[  0.   0.   0.]
  [  0.   0.   0.]
  [  0.   0.   0.]
  [  0.   0.   0.]]]

My plan is to use numpy.concatenate using the following steps.

#1 Create an array of 0's with this dimension (1,4,3)

#2 Concatenate the original array to the array from step 1. This will create a new array like this

[[[  0.   0.   0.]
  [  0.   0.   0.]
  [  0.   0.   0.]
  [  0.   0.   0.]]

 [[255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]]

 [[255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]
  [255. 255. 255.]]]

#3 Use the array from step 1 and append it to the array that was created in part 2 and this will finally give me the result I want.

However, I also wonder if there is a way to use numpy.insert and just insert (1,4,3) to the beginning and end of the array without complicating this with concatenate. I would appreciate any input on this.

Upvotes: 1

Views: 2864

Answers (1)

miradulo
miradulo

Reputation: 29690

Using numpy.concatenate, you can create a zero array to concatenate on either side.

zs = np.zeros((1,) + arr.shape[1:])
np.concatenate((zs, arr, zs))

Another option - create a zero array of the new size, and set the interior to be your original array.

padded_arr = np.zeros((arr.shape[0]+2,) + arr.shape[1:])
padded_arr[1:-1, ...] = arr

Lastly you can achieve this with numpy.pad, specifying a pad width for each axis.

np.pad(arr, ((1,), (0,), (0,)), 'constant')

Upvotes: 1

Related Questions