Given a 2D matrix image of size m x n and a 2D matrix kernel of size km x kn, perform a valid 2D convolution and return the resulting matrix.
The convolution slides the kernel over the image. At each position where the kernel fits entirely within the image, compute the sum of element-wise products between the overlapping region of the image and the kernel.
The output matrix has dimensions (m - km + 1) x (n - kn + 1). This is called valid convolution because no padding is applied to the image.
Function Signature
def convolve_2d(image: list[list[int]], kernel: list[list[int]]) -> list[list[int]]:
Rules
-
Output cell
(i, j)
places the kernel's top-left corner on
image[i][j]
:
out[i][j]=a=0∑km−1b=0∑kn−1image[i+a][j+b]⋅kernel[a][b]
-
The kernel is used as given. Do not flip it before sliding.
-
Return the result as a list of rows, with
m - km + 1
rows of
n - kn + 1
integers each.
Constraints
-
1 <= m, n <= 200
, where
m = len(image)
and
n = len(image[0])
-
1 <= km <= m
and
1 <= kn <= n
, where
km = len(kernel)
and
kn = len(kernel[0])
-
km
and
kn
are odd.
-
-1000 <= image[i][j] <= 1000
-
-1000 <= kernel[i][j] <= 1000
Examples
Input: image = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], kernel = [[1,0,-1],[1,0,-1],[1,0,-1]]
Output: [[-6,-6],[-6,-6]]
The output is 2 x 2. At (0, 0): 1*1 + 2*0 + 3*(-1) + 5*1 + 6*0 + 7*(-1) + 9*1 + 10*0 + 11*(-1) = -6. In every window each row adds its left value and subtracts its right value, which are 2 apart, so all four cells are 3 * (-2) = -6.
Input: image = [[1,2,3],[4,5,6],[7,8,9]], kernel = [[1,1,1],[1,1,1],[1,1,1]]
Output: [[45]]
The kernel is the same size as the image, so the output is 1 x 1 and equals the sum of all image values, 1 + 2 + ... + 9 = 45.
Input: image = [[1,2,3,4],[0,1,0,1]], kernel = [[1,0,2]]
Output: [[7,10],[0,3]]
The output is 2 x 2. Row 0 gives 1*1 + 2*0 + 3*2 = 7 and 2*1 + 3*0 + 4*2 = 10. Row 1 gives 0*1 + 1*0 + 0*2 = 0 and 1*1 + 0*0 + 1*2 = 3. A flipped kernel would give 5 at (0, 0) instead.