numpy pad函数的使用

ndarray = numpy.pad(array, pad_width, mode, **kwargs)
  • array: 表示要填充的数组
  • pad_width: 表示填充到每个边缘的数值,如((before_1, after_1), (before_2, after_2),…,(before_n, after_n))表示在每个轴前面填充before个元素,后面填充after个元素。
  • mode:表示填充方式
import numpy as np
import matplotlib.pyplot as plt
a = [1, 2, 3, 4, 5]
# ((2, 3))表示在第一维左边填充两个,第一维右边填充三个
np.pad(a, ((2,3)), 'constant', constant_values=(4, 6))
array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6])
# ((2, 3))可以简写成(2, 3)
np.pad(a, (2,3), 'constant', constant_values=0)
array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0])
a = np.ones((2, 3))
a, a.shape
(array([[1., 1., 1.],
        [1., 1., 1.]]), (2, 3))
print(a.shape)
# ((2,2),(3,3)) 表示在第一维前面和后面填充两个,第二维前面和后面填充三个
data = np.pad(a, ((2,2),(3,3)), 'constant', constant_values=0)
print(data, data.shape)
(2, 3)
[[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. 1. 1. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0.]] (6, 9)
a = np.ones((2, 4, 3))
a
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.]]])
print(a.shape)
# 同理对于图片(一般是三维)可以在第一维(高)上下各填充两行
data = np.pad(a, ((2,2),(0,0),(0,0)), 'constant', constant_values=0)
print(data.shape)
plt.imshow(data)
(2, 4, 3)
(6, 4, 3)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DGbYKGNW-1573883069540)(output_8_2.png)]

print(a.shape)
# 在第二维(宽)左右各填充两行
data = np.pad(a, ((0,0),(3,3),(0,0)), 'constant', constant_values=0)
print(data.shape,)
plt.imshow(data)
(2, 4, 3)
(2, 10, 3)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ma5Ii7jS-1573883069542)(output_9_2.png)]

posted @ 2019-11-16 13:48  mengfu188  阅读(365)  评论(0)    收藏  举报