Loading content...
Image Border Padding is a fundamental preprocessing operation in digital image processing and deep learning computer vision pipelines. This technique involves augmenting the boundaries of an image matrix by adding layers of specified values—typically zeros—around its perimeter.
In the context of grayscale images, each pixel is represented as an integer intensity value within a 2D matrix. When we apply border padding, we expand the spatial dimensions of this matrix by surrounding it with additional rows and columns filled with a constant value (zero in this case).
The Transformation: Given an image matrix of dimensions H × W (height × width) and a padding size P, the resulting padded image will have dimensions (H + 2P) × (W + 2P). The original pixel values remain intact in the center, while the newly added border regions are initialized to zero.
Mathematical Representation: For a padded output matrix O with original image I and padding size P:
$$O[i][j] = \begin{cases} I[i-P][j-P] & \text{if } P \leq i < H+P \text{ and } P \leq j < W+P \ 0 & \text{otherwise} \end{cases}$$
Why Zero Padding Matters: Zero padding is extensively utilized in convolutional neural networks (CNNs) to preserve spatial dimensions after convolution operations, prevent information loss at image boundaries, and maintain feature map sizes across network layers.
Your Task: Implement a function that adds zero-value border padding around a grayscale image matrix. Your implementation should:
image = [[1, 2], [3, 4]]
padding_size = 1[[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]The original 2×2 image receives a single layer of zeros around all sides. The transformation expands the dimensions from 2×2 to 4×4 (calculated as (2 + 2×1) × (2 + 2×1)). The original pixel values [1, 2, 3, 4] remain positioned in the center region, while zeros fill the newly created border cells.
image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
padding_size = 1[[0, 0, 0, 0, 0], [0, 1, 2, 3, 0], [0, 4, 5, 6, 0], [0, 7, 8, 9, 0], [0, 0, 0, 0, 0]]A 3×3 grayscale image is expanded to 5×5 dimensions with single-layer padding. Each original row gains a leading and trailing zero, while entirely new zero-filled rows are prepended and appended to the matrix. The center 3×3 region preserves the original intensity values exactly as they appeared in the input.
image = [[10, 20], [30, 40]]
padding_size = 0[[10, 20], [30, 40]]When the padding size is zero, no modification occurs to the image dimensions. The function returns the original image matrix unchanged. This edge case demonstrates that the operation gracefully handles the identity transformation where no padding is requested.
Constraints