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]
np.pad(a, ((2,3)), 'constant', constant_values=(4, 6))
array([4, 4, 1, 2, 3, 4, 5, 6, 6, 6])
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)
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)]](https://i-blog.csdnimg.cn/blog_migrate/3877cb289c454f850de8283fbe145f77.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)]](https://i-blog.csdnimg.cn/blog_migrate/4a921bef13af9eb541a550217b9face4.png)