Filtering images with convolution

Many image operations replace each pixel by a weighted sum of the pixels around it. The weights form a small grid called a kernel or filter. Sliding the kernel over the image and computing that weighted sum at every position is filtering, usually called convolution. The same operation, with learned kernels, is the core of convolutional neural networks.

Python
def convolve(image, kernel):
    kh, kw = len(kernel), len(kernel[0])
    output = []
    for r in range(len(image) - kh + 1):
        row = []
        for c in range(len(image[0]) - kw + 1):
            row.append(sum(image[r + i][c + j] * kernel[i][j] for i in range(kh) for j in range(kw)))
        output.append(row)
    return output


image = [[0, 0, 90, 90, 90] for _ in range(5)]
box = [[1 / 9] * 3 for _ in range(3)]
identity = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
blurred = convolve(image, box)
print(len(blurred), len(blurred[0]))
print([round(value, 1) for value in blurred[0]])
print(convolve(image, identity)[0])
Read the full lesson