Detect edges with Sobel filters and a magnitude threshold

Sobel filters are hand-made convolution kernels that measure how fast brightness changes horizontally and vertically. The first layer of a trained CNN often learns filters that look a lot like them.

Write sobel_edges(img, thr) for a grayscale image of shape (H, W), H and W at least 3. Use cross-correlation (no kernel flip), no padding, stride 1:
- Kx = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]] and Ky = Kx transposed.
- gx and gy have shape (H-2, W-2). The magnitude is sqrt(gx**2 + gy**2).
Return a tuple (mag, edges) where edges is a boolean array, True where mag >= thr.

Signaturedef sobel_edges(img, thr)

Example

a 3x3 image [[0, 0, 9], [0, 0, 9], [0, 0, 9]] gives gx = 36, gy = 0, so mag is [[36.0]].

Understand the idea

An edge is a place where brightness changes fast. Sobel kernels measure that change: Kx compares the right column with the left column (with the middle row weighted 2), and Ky, its transpose, compares the bottom row with the top row. Slide both over the image without padding, then combine them into one strength. Worked example: a 3x3 patch whose bottom row is [6, 6, 6] and the rest is 0. Ky = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]], so gy = 6 + 12 + 6 = 24, and gx = 0 because the left and right columns match. Magnitude = sqrt(0 + 24^2) = 24. For a diagonal edge with gx = 3 and gy = 4, magnitude is 5, not 7. Rule: at each valid position, gx = sum of Kx times the 3x3 window, gy likewise with Ky (no kernel flip); mag = sqrt(gx^2 + gy^2); edges = mag >= thr. Output is (H - 2, W - 2). Using |gx| + |gy| overstates diagonals. Sobel is a classic preprocessing step and early CNN filters often learn similar shapes.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplesobel_edges([[0, 0, 9], [0, 0, 9], [0, 0, 9]], 10)
  • Sample 2: diagonal edge magnitudesobel_edges(_diag, 10)[0]