np.pad(array,pad_width,mode,**kwargs) # 返回填充后的numpy数组
array:要填充的numpy数组【要对谁进行填充】
pad_width:每个轴要填充的数据的数目【每个维度前、后各要填充多少个数据】
mode:填充的方式【采用哪种方式填充】
import numpy as np # 一维 a = np.array([1, 2, 3, 4, 5]) print("a.shape", a.shape) b = np.pad(a, 1, 'constant') print("b = ", b) c = np.pad(a, (1, 2), 'constant') print("c.shape", c.shape) print("c = ", c) print("----------------------------------") # 二维 d = np.array([[1, 2], [3, 4]]) print("d.shape", d.shape) e = np.pad(d, (1, 2), 'constant') print("e = ") print(e) f = np.pad(d, ((1, 2), (3, 4)), 'constant') print("f = ") print(f) print("----------------------------------") # 三维 arr = np.array([[[1, 2, 3], [4, 5, 6], [7, 8, 9]]]) arr_pad = np.pad(arr, ((1, 1), (1, 2), (3, 4)), 'constant') print("arr.shape", arr.shape) print(arr_pad) print("----------------------------------") # 四维 img = np.array([[[[1, 2], [5, 6], [9, 10], [13,14]]]]) pad = 1 print("img.shape", img.shape) img_pad = np.pad(img, [(1,1), (1,1), (pad, pad), (pad, pad)], "constant") print(img_pad)
a.shape (5,) b = [0 1 2 3 4 5 0] c.shape (8,) c = [0 1 2 3 4 5 0 0] ---------------------------------- d.shape (2, 2) e = [[0 0 0 0 0] [0 1 2 0 0] [0 3 4 0 0] [0 0 0 0 0] [0 0 0 0 0]] f = [[0 0 0 0 0 0 0 0 0] [0 0 0 1 2 0 0 0 0] [0 0 0 3 4 0 0 0 0] [0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0]] ---------------------------------- arr.shape (1, 3, 3) [[[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 2 3 0 0 0 0] [0 0 0 4 5 6 0 0 0 0] [0 0 0 7 8 9 0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