Convolution: a small window sliding over an image
Each output pixel is the sum of a 3 × 3 patch of input pixels, each multiplied by the matching kernel weight.
Window
×0.900.900.900.900.900.900.900.900.90
Kernel
→−101−202−101
Products
Σ−0.9000.90−1.8001.80−0.9000.90
Sum0
Window positioncolumn 13, row 13
Output at this pixel0
Challenges
0 of 3 complete
- With Vertical edges or Horizontal edges, find a window that sits across an edge of the square yet outputs exactly 0. (not yet)
- Find two windows at least 10 pixels apart that give exactly the same output (not 0). (not yet)
- Choose Custom and build a diagonal edge detector: exactly 0 all along the square's straight edges, but not 0 on the diagonal stripes. (not yet)
Try this
- Compare Vertical edges and Horizontal edges on the square.
- Put the window on a flat area: edge kernels output zero there.
- Choose Custom and make a kernel that detects diagonal edges.
A convolution in a few lines of codePython with NumPy
import numpy as np
# An 8 x 8 dark image (0) with a bright 4 x 4 square (1) in the middle.
image = np.zeros((8, 8))
image[2:6, 2:6] = 1
# The vertical edge kernel (Sobel x): right column minus left column.
kernel = np.array([[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]])
def convolve(image, kernel):
padded = np.pad(image, 1) # a border of zeros keeps the output the same size
out = np.zeros_like(image)
for i in range(image.shape[0]):
for j in range(image.shape[1]):
window = padded[i:i + 3, j:j + 3]
out[i, j] = np.sum(window * kernel) # nine products, added up
return out
# Positive at the square's left edge, negative at its right edge,
# and 0 along its top and bottom edges, where the columns match.
print(convolve(image, kernel).astype(int))[[ 0 0 0 0 0 0 0 0]
[ 0 1 1 0 0 -1 -1 0]
[ 0 3 3 0 0 -3 -3 0]
[ 0 4 4 0 0 -4 -4 0]
[ 0 4 4 0 0 -4 -4 0]
[ 0 3 3 0 0 -3 -3 0]
[ 0 1 1 0 0 -1 -1 0]
[ 0 0 0 0 0 0 0 0]]