v9.1.1
Menu

2D Convolution

mediumFREELinear FilteringImage ProcessingCV: Image Processing

Implement a 2D convolution operation to filter an image using a given kernel. This process is fundamental in Linear Filtering for image processing, where the goal is to modify or enhance the image by applying a kernel that slides over the entire image, performing an element-wise multiplication at each position.

The concept of 2D convolution is crucial in image processing as it allows for the application of various filters to achieve desired effects such as blurring, sharpening, or edge detection. Mathematically, the 2D convolution operation can be represented as a double summation over the kernel's dimensions.

  1. Initialize the output image with zeros.
  2. Slide the kernel over the input image, calculating the element-wise product at each position.
  3. Sum the products to obtain the output value at each position.
out(y,x)=∑m=0kH−1∑n=0kW−1I(y+m−⌊kH/2⌋, x+n−⌊kW/2⌋)⋅K(m,n)\text{out}(y, x) = \sum_{m=0}^{k_H-1} \sum_{n=0}^{k_W-1} I\big(y + m - \lfloor k_H/2 \rfloor,\ x + n - \lfloor k_W/2 \rfloor\big) \cdot K(m, n)

Here yy is the row and xx the column. The kernel is not flipped, its anchor is cell (⌊kH/2⌋,⌊kW/2⌋)(\lfloor k_H/2 \rfloor, \lfloor k_W/2 \rfloor), and any image position outside the image counts as 0 (zero padding).

This technique is widely used in image processing applications.

Example

Input
image = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]
kernel = [[1, 0],
         [0, -1]]
Output
[[-1, -2, -3], [-4, -4, -4], [-7, -4, -4]]
Reasoning
  • Inputs: image is a 3×33 \times 3 intensity grid; kernel holds the weights K=(100−1)K = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}. Since ⌊2/2⌋=1\lfloor 2/2 \rfloor = 1, the anchor is the kernel's bottom-right cell: K(0,0)K(0,0) lands on the pixel up-and-left of the target, K(1,1)K(1,1) on the target itself.
  • Math: plugging into the formula gives out(y,x)=I(y−1,x−1)−I(y,x)\text{out}(y,x) = I(y-1, x-1) - I(y, x), where anything outside the image is 0.
  • Top row and left column: the up-left neighbour is padding, so only −I(y,x)-I(y,x) survives. Row 0 becomes −1,−2,−3-1, -2, -3; cells (1,0)(1,0) and (2,0)(2,0) become −4-4 and −7-7.
  • Interior: (1,1)(1,1): 1−5=−41 - 5 = -4; (1,2)(1,2): 2−6=−42 - 6 = -4; (2,1)(2,1): 4−8=−44 - 8 = -4; (2,2)(2,2): 5−9=−45 - 9 = -4.
  • Output: a 3×33 \times 3 grid, same size as the input: [[-1, -2, -3], [-4, -4, -4], [-7, -4, -4]].
  • Notice every interior value is −4-4: the image rises by exactly 4 along each down-right diagonal (1→5→91 \to 5 \to 9), which is what this diagonal-difference kernel measures. Flipping the kernel would change these numbers.

Constraints

  • Kernel is a small 2D array (typically 3×3 or 5×5)
  • Use zero-padding
  • Return result with same dimensions as input

Learn this in

More from CV: Image Processing

solution.py

Test results

Sign in to run your code against the test cases.