numpy pad

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

  • array为要填补的数组
  • pad_width是在各维度的各个方向上想要填补的长度,如((1,2),(2,2)),表示在第一个维度上前面padding=1,后面padding=2,在第二个维度上前面padding=2,后面padding=2。如果直接输入一个整数,则说明各个维度和各个方向所填补的长度都一样。
  •  mode为填补类型,即怎样去填补,有“constant”,“edge”等模式,如果为constant模式,就得指定填补的值,如果不指定,则默认填充0。

1D

t1D = np.array([1, 1, 1])

print("1D before: \n", t1D)

t1D = np.pad(t1D, (1, 2),'constant')

print("1D after: \n", t1D)

1D before: 
 [1 1 1]
1D after:
 [0 1 1 1 0 0]

2D 

t2D = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])

print("2D before: \n", t2D)

t2D = np.pad(t2D, ((1, 2), (3, 4)),'constant')

print("2D after: \n", t2D)

2D before:
 [[1 1 1]
 [1 1 1]
 [1 1 1]]

2D after:
 [[0 0 0 0 0 0 0 0 0 0]
 [0 0 0 1 1 1 0 0 0 0]
 [0 0 0 1 1 1 0 0 0 0]
 [0 0 0 1 1 1 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]

3D 

    t3D = np.array([[[1, 1, 1], [1, 1, 1], [1, 1, 1]],

                    [[1, 1, 1], [1, 1, 1], [1, 1, 1]],

                    [[1, 1, 1], [1, 1, 1], [1, 1, 1]]])

    print("3D before: \n", t3D)

    t3D = np.pad(t3D, ((1, 2), (1, 2), (3, 4)),'constant')

    print("3D after: \n", t3D)


3D before:
 [[[1 1 1]
  [1 1 1]
  [1 1 1]]

 [[1 1 1]
  [1 1 1]
  [1 1 1]]

 [[1 1 1]
  [1 1 1]
  [1 1 1]]]
3D after:
 [[[0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]]

 [[0 0 0 0 0 0 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]]

 [[0 0 0 0 0 0 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]]

 [[0 0 0 0 0 0 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 1 1 1 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]]

 [[0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]]

 [[0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]
  [0 0 0 0 0 0 0 0 0 0]]]

猜你喜欢

转载自blog.csdn.net/qq_30460949/article/details/128374921