← back

Apply Zero Padding to an Image

#239 · Computer Vision · Easy

⊣ Solve on deep-ml.com

Problem

Apply zero padding to an image by adding a border of zero-valued pixels around the image on all sides.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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

Explanation

  1. Create a new image of size (H + 2*pad, W + 2*pad, C) filled with zeros.
  2. Copy the original image into the center region.
  3. The border of width pad on all four sides contains zero values.
  4. Zero padding is commonly used in CNNs to preserve spatial dimensions after convolution.

Complexity

  • Time: O((H + 2p) (W + 2p) C) where p is the padding size
  • Space: O((H + 2p) (W + 2p) C) for the padded image