Problems
Loading...
1 / 1

2D Convolution (Image Filtering)

Computer Vision
Medium

2D convolution is the core operation in convolutional neural networks and classical image processing. A small kernel slides over an image, computing a weighted sum at each position to produce a filtered output.

Given a single-channel 2D image, a kernel, a stride, and a padding amount, compute the convolution output.

Operation

  1. Pad the image with zeros on all sides by the padding amount.
  2. Slide the kernel over the padded image with the given stride.
  3. At each position, compute the element-wise product of the kernel and the image patch, then sum all values.
output[i][j]=m=0kh1n=0kw1padded[is+m][js+n]kernel[m][n]\text{output}[i][j] = \sum_{m=0}^{k_h-1} \sum_{n=0}^{k_w-1} \text{padded}[i \cdot s + m][j \cdot s + n] \cdot \text{kernel}[m][n]

The output dimensions are:

Hout=H+2pkhs+1Wout=W+2pkws+1H_{out} = \left\lfloor \frac{H + 2p - k_h}{s} \right\rfloor + 1 \qquad W_{out} = \left\lfloor \frac{W + 2p - k_w}{s} \right\rfloor + 1

Return the output as a 2D list of floats.

Loading visualization...

Examples

Input:

image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] kernel = [[1, 0], [0, 1]] stride = 1, padding = 0

Output:

[[6, 8], [12, 14]]

The 2x2 kernel acts as a diagonal sum filter. At position (0,0): 11 + 20 + 40 + 51 = 6.

Input:

image = [[1, 2], [3, 4]] kernel = [[1, 1], [1, 1]] stride = 1, padding = 1

Output:

[[1, 3, 2], [4, 10, 6], [3, 7, 4]]

The image is padded with zeros, making it 4x4. The kernel sums a 2x2 neighborhood. Padding preserves spatial dimensions.

Hint 1

Build the padded image first as a separate 2D array, then iterate over valid kernel positions.

Hint 2

The output position (i, j) reads from padded image starting at row istride, column jstride.

Requirements

  • Apply zero-padding to the image before convolution
  • Slide the kernel with the given stride
  • Compute the correct output dimensions
  • Support non-square images and kernels

Constraints

  • 1 <= image height, width <= 100
  • 1 <= kernel height, width <= image dimensions
  • 1 <= stride <= 5
  • 0 <= padding <= 5
  • Time limit: 300 ms
Try Similar Problems