12

我有一个形状为(103、37、13)的 3d numpy 数组(数据)。我想通过沿每个轴的两个方向几乎相等的零填充来将此 numpy 数组的大小调整为 (250,250,13)。

下面的代码适用于 2d 数组,但我无法使其适用于 3d 数组。

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

1 回答 1

19
data1=np.pad(data, ((73,74), (106,107), (0, 0)), 'constant')

工作正常。需要为第三个轴添加第三组对。

于 2018-04-24T18:52:38.513 回答