v9.1.1
Menu

2D Image Convolution

easyFREEConvolution and FilteringComputer Vision 2

Implement a 2D image convolution operation in valid mode, which involves sliding a kernel over an image to generate a feature map. This process is fundamental in Computer Vision as it enables the extraction of relevant features from images by applying a set of learnable filters.

The concept of convolution is based on the idea of scanning an image with a smaller matrix, known as a kernel, to compute feature values at each position. The kernel is slid over the entire image, and at each position, the element-wise product between the kernel and the overlapping image region is computed, followed by summation of these products. The resulting feature map has a size of (H−kH+1)×(W−kW+1)(H - kH + 1) \times (W - kW + 1), where HH and WW are the dimensions of the image, and kHkH and kWkW are the dimensions of the kernel.

Here are the steps to perform the convolution:

  1. Initialize an empty output matrix with dimensions (H−kH+1)×(W−kW+1)(H - kH + 1) \times (W - kW + 1).
  2. Slide the kernel over the image, scanning each valid position.
  3. At each position, compute the element-wise product between the kernel and the overlapping image region.
  4. Sum up the products to obtain the feature value at that position.
Output(i,j)=∑x=0kH−1∑y=0kW−1Image(i+x,j+y)×Kernel(x,y)\text{Output}(i, j) = \sum_{x=0}^{kH-1} \sum_{y=0}^{kW-1} \text{Image}(i+x, j+y) \times \text{Kernel}(x, y)

This technique is widely used in image processing and analysis applications.

Example

Input
image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
kernel = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
Output
[[45.0]]
Reasoning
  • image is a 3×33 \times 3 grid of pixel values, and kernel is a 3×33 \times 3 grid of weights, all 11.
  • Output size is (3−3+1)×(3−3+1)=1×1(3 - 3 + 1) \times (3 - 3 + 1) = 1 \times 1: a kernel as large as the image fits in exactly one place, so only (i,j)=(0,0)(i, j) = (0, 0) is valid.
  • There each pixel is multiplied by the weight on it and the products are summed: (1+2+3)+(4+5+6)+(7+8+9)=6+15+24=45(1+2+3) + (4+5+6) + (7+8+9) = 6 + 15 + 24 = 45.
  • Rounded to 4 decimal places, the sum appears as 45.0, in one row of one value: [[45.0]].
  • Notice that an all-ones kernel just totals the pixels under it. The kernel is not flipped: Kernel(x,y)\text{Kernel}(x, y) weights Image(i+x,j+y)\text{Image}(i+x, j+y) directly. A 2×22 \times 2 kernel with 11 in the top-left, −1-1 in the bottom-left and 00 elsewhere gives 1⋅1+4⋅(−1)=−31 \cdot 1 + 4 \cdot (-1) = -3 at (0,0)(0, 0), and −3-3 at all four positions.

Constraints

  • image and kernel are 2D lists of numbers
  • kernel fits within the image
  • Return 2D list of convolution results rounded to 4 decimal places

Learn this in

More from Computer Vision 2

solution.py

Test results

Sign in to run your code against the test cases.