All problems
2D Convolution (Valid)
Problem
Compute the valid-mode 2D convolution of an image with a kernel.
out[i][j] = sum over (a, b) of image[i + a][j + b] * kernel[kh - 1 - a][kw - 1 - b], so the kernel is flipped 180 degrees relative to cross-correlation. The output shape is (H - kh + 1) x (W - kw + 1).
Hint
Same sliding-window code as correlation, but read the kernel backwards.
Test cases
case 1
in: [[[1,2,3],[4,5,6],[7,8,9]],[[1,0],[0,0]]]
expected: [[5,6],[8,9]]
case 2
in: [[[1,2,3],[4,5,6],[7,8,9]],[[0,0,0],[0,1,0],[0,0,0]]]
expected: [[5]]
case 3
in: [[[1,2,3],[4,5,6],[7,8,9]],[[1,2],[3,4]]]
expected: [[23,33],[53,63]]
case 4
in: [[[1,2,3],[4,5,6]],[[1,1],[1,1]]]
expected: [[12,16]]
Starter codePython
def convolve2d(image, kernel):
# Your code here
pass4 test cases · run your code against them in the editor