方法一: 用for循环
import numpy as np
"""
input:
[
[1, 2, 3, 4, 5],
[4, 5, 6, 7, 8],
[9, 8, 7, 6, 5],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6]
] output:
[
[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. 4. 5. 0. 0. 0.]
[0. 0. 0. 4. 5. 6. 7. 8. 0. 0. 0.]
[0. 0. 0. 9. 8. 7. 6. 5. 0. 0. 0.]
[0. 0. 0. 1. 2. 3. 4. 5. 0. 0. 0.]
[0. 0. 0. 2. 3. 4. 5. 6. 0. 0. 0.]
[0. 0. 0. 2. 3. 4. 5. 6. 0. 0. 0.]
[0. 0. 0. 2. 3. 4. 5. 6. 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.]
]
"""
X = np.array([
[1, 2, 3, 4, 5],
[4, 5, 6, 7, 8],
[9, 8, 7, 6, 5],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6]
])
def zero_padding(in_array, padding_size=0):
h, w = in_array.shape
padding_array = np.zeros([h + 2 * padding_size, w + 2 * padding_size])
for xx in range(h):
for yy in range(w):
padding_array[xx + padding_size, yy + padding_size] = in_array[xx, yy]
return padding_array
def zero_multi_padding(in_array, padding_size=0):
h, w, in_channels = in_array.shape
padding_array = np.zeros([h + 2 * padding_size, w + 2 * padding_size, in_channels])
for i in range(in_channels):
for xx in range(h):
for yy in range(w):
padding_array[xx + padding_size, yy + padding_size, i] = in_array[xx, yy, i]
return padding_array
if __name__ == '__main__':
Y = zero_padding(X, 3)
print(Y)
方法二: 直接根据numpy赋值即可
import numpy as np
"""
input:
[
[1, 2, 3, 4, 5],
[4, 5, 6, 7, 8],
[9, 8, 7, 6, 5],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6]
] output:
[
[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. 4. 5. 0. 0. 0.]
[0. 0. 0. 4. 5. 6. 7. 8. 0. 0. 0.]
[0. 0. 0. 9. 8. 7. 6. 5. 0. 0. 0.]
[0. 0. 0. 1. 2. 3. 4. 5. 0. 0. 0.]
[0. 0. 0. 2. 3. 4. 5. 6. 0. 0. 0.]
[0. 0. 0. 2. 3. 4. 5. 6. 0. 0. 0.]
[0. 0. 0. 2. 3. 4. 5. 6. 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.]
]
"""
X = np.array([
[1, 2, 3, 4, 5],
[4, 5, 6, 7, 8],
[9, 8, 7, 6, 5],
[1, 2, 3, 4, 5],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6],
[2, 3, 4, 5, 6]
])
def zero_padding(in_array, padding_size=0):
rows, cols = in_array.shape
padding_array = np.zeros([rows + 2 * padding_size, cols + 2 * padding_size])
padding_array[padding_size:rows + padding_size, padding_size:cols + padding_size] = in_array
return padding_array
if __name__ == '__main__':
Y = zero_padding(X, 3)
print(Y)