Numpy填充数组

使用np.pad

使用方法:

numpy.pad(array, pad_width, mode=’constant’, **kwargs)

array: 是待填充的数组
pad_width: 填充每一个轴填充的宽度
padwidth{sequence, arraylike, int}
Number of values padded to the edges of each axis. ((before_1, after_1), … (before_N, after_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes.
mode: 填充的模式,默认选’constant’

用法:

  1. # 一维
  2. a = [1, 2, 3, 4, 5]
  3. np.pad(a, (2, 3), 'constant', constant_values=(4, 6))
  4. -----------------------------------------------------------------------
  5. # output:
  6. array([4, 4, 1, ..., 6, 6, 6])
  7. -----------------------------------------------------------------------
  8. # 二维
  9. a = [[1, 2], [3, 4]]
  10. np.pad(a, ((3, 2), (2, 3)), 'minimum')
  11. -----------------------------------------------------------------------
  12. output:
  13. array([[1, 1, 1, 2, 1, 1, 1],
  14. [1, 1, 1, 2, 1, 1, 1],
  15. [1, 1, 1, 2, 1, 1, 1],
  16. [1, 1, 1, 2, 1, 1, 1],
  17. [3, 3, 3, 4, 3, 3, 3],
  18. [1, 1, 1, 2, 1, 1, 1],
  19. [1, 1, 1, 2, 1, 1, 1]])

MATLAB填充三维数组

  1. D = padarray(C,[3 3],0,'both')