Apply zero padding to an image by adding a border of zero-valued pixels around the image on all sides.
def zero_pad(
image: list[list[list[int]]],
pad: int,
) -> list[list[list[int]]]:
"""
image: [H, W, C]
pad: number of pixels to pad on each side
"""
if pad <= 0:
return [row[:] for row in image]
H = len(image)
W = len(image[0])
C = len(image[0][0])
new_H = H + 2 * pad
new_W = W + 2 * pad
# Create padded image filled with zeros
padded = [[[0] * C for _ in range(new_W)] for _ in range(new_H)]
# Copy original image into center
for h in range(H):
for w in range(W):
for c in range(C):
padded[h + pad][w + pad][c] = image[h][w][c]
return padded(H + 2*pad, W + 2*pad, C) filled with zeros.pad on all four sides contains zero values.