Before you start
Detect edges in a grayscale image with the Sobel operator.
An edge is a place where brightness changes quickly. The Sobel operator
estimates the horizontal and vertical brightness gradients with two 3 x 3
kernels, each a smoothed finite difference:
Gx = [[-1, 0, 1], Gy = [[-1, -2, -1],
[-2, 0, 2], [ 0, 0, 0],
[-1, 0, 1]] [ 1, 2, 1]]
Slide each kernel over the image without padding (valid mode). At each
position, multiply the kernel with the 3 x 3 patch under it and sum. This is
cross-correlation, the same operation deep learning calls convolution, so do
not flip the kernels. The edge strength is sqrt(gx^2 + gy^2).
The first layers of a trained CNN often learn filters that look much like these.
def sobel_magnitude(img):
Input
img = np.array([[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1],
[0, 0, 1, 1]], dtype=float)
sobel_magnitude(img)
Output
array([[4., 4.],
[4., 4.]])
Reasoning
There is a vertical edge between columns 1 and 2. Every 3 x 3 patch has a
left column darker than its right column by 1, so gx = 1 + 2 + 1 = 4. The
rows are all the same, so gy = 0. The magnitude is 4 everywhere.
img has shape (H, W) with H, W >= 3.(H - 2, W - 2).Check runs the visible cases against a fresh kernel. Submit runs the hidden ones too.
⇧↵run cell