Apply Zero Padding to an Image

Easy
Computer Vision

Task: Zero Padding for Images

In this task, you will implement a function zero_pad_image(img, pad_width) that adds zero padding around a grayscale image.

Zero padding is a fundamental operation in image processing and convolutional neural networks where layers of zeros are added around the border of an image.

Your Task:

Implement the function zero_pad_image(img, pad_width) to:

  1. Add pad_width rows/columns of zeros on each side of the image (top, bottom, left, right).
  2. Return the padded image as a 2D list with integer values.
  3. Handle edge cases:
    • If the input is not a valid 2D array.
    • If the image has empty dimensions.
    • If pad_width is not a non-negative integer.

For any of these edge cases, the function should return -1.

Examples

Example 1:
Input: img = [[1, 2], [3, 4]] pad_width = 1 print(zero_pad_image(img, pad_width))
Output: [[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]
Explanation: The original 2x2 image gets a border of zeros added on all sides. The new dimensions are (2+2*1) x (2+2*1) = 4x4. The original pixel values remain in the center while zeros fill the border.

Starter Code

import numpy as np

def zero_pad_image(img, pad_width):
    """
    Add zero padding around a grayscale image.
    
    Args:
        img: 2D list or numpy array of pixel values
        pad_width: integer number of pixels to pad on each side
    
    Returns:
        Padded image as 2D list with integer values,
        or -1 if input is invalid
    """
    # Write your code here
    pass
Lines: 1Characters: 0
Ready
The AI Interview - Master AI/ML Interviews