Zero Padding a 3d Numpy array
Asked Answered
D

1

13

I have a 3d numpy array(data) with shape say (103, 37, 13). I want to resize this numpy array to (250,250,13) by zero padding almost equally in both directions along each axis.

The code below works well for 2d array, but I am not able to make it work for 3d array.

>>> a = np.arange(6)
>>> a = a.reshape((2, 3))
>>> np.lib.pad(a, [(2,3),(1,1)], 'constant', constant_values=[(0, 0),(0,0)])
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 1, 2, 0],
       [0, 3, 4, 5, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]])

>>> zerpads =np.zeros(13)
>>> data1=np.lib.pad(data,[(73,74),(106,107)],'constant',constant_values=[(zerpads, zerpads),(zerpads,zerpads)])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/ayush/anaconda2/lib/python2.7/site-packages/numpy/lib/arraypad.py", line 1295, in pad
    pad_width = _validate_lengths(narray, pad_width)
  File "/home/ayush/anaconda2/lib/python2.7/site-packages/numpy/lib/arraypad.py", line 1080, in _validate_lengths
    normshp = _normalize_shape(narray, number_elements)
  File "/home/ayush/anaconda2/lib/python2.7/site-packages/numpy/lib/arraypad.py", line 1039, in _normalize_shape
    raise ValueError(fmt % (shape,))
ValueError: Unable to create correctly shaped tuple from [(73, 74), (106, 107)]
Dissyllable answered 24/4, 2018 at 18:29 Comment(7)
You need to pass 3 pairs of padding widths. Put (0, 0) if you don't want to pad along an axis. Also, 'constant' mode defaults to 0, so you needn't pass constant_values.Thermo
Used this data1=np.lib.pad(data,[(73,74,0),(106,107,0)],'constant'), but i still get ValueError: Unable to create correctly shaped tuple from [(73, 74, 0), (106, 107, 0)]Dissyllable
I think three pairs, not two triplets.Thermo
It works! thanks a lot @Paul PanzerDissyllable
Should I delete this question then?Dissyllable
This should work: np.pad(a, ((73,74), (106,107), (0, 0)), 'constant').shapeRonel
@ayushgupta I have no strong feelings about this. You can leave it and write an answer yourself. Maybe it will be helpful for others to see an example of the correct syntax. Or you can delete it.Thermo
D
27
data1=np.pad(data, ((73,74), (106,107), (0, 0)), 'constant')

works fine. A 3rd set of pair needs to be added for the third axis.

Dissyllable answered 24/4, 2018 at 18:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.