#142Sobel edge magnitudeMedium

Sobel edge magnitude

Background

Classic Sobel filters approximate image derivatives. The vertical-edge (GxG_x) and horizontal-edge (GyG_y) kernels are

Gx=[101202101],Gy=[121000121].G_x = \begin{bmatrix}-1&0&1\\-2&0&2\\-1&0&1\end{bmatrix}, \qquad G_y = \begin{bmatrix}-1&-2&-1\\0&0&0\\1&2&1\end{bmatrix}.

Convolve the image with each (valid, stride 1), then combine into an edge magnitude:

Mij=gx,ij2+gy,ij2.M_{ij} = \sqrt{g_{x,ij}^2 + g_{y,ij}^2}.

Problem statement

Implement sobel_magnitude(img) returning the Sobel gradient-magnitude map of a grayscale image.

Input

  • img — array-like of shape (H, W), H, W ≥ 3.

Output

Returns an np.ndarray of shape (H - 2, W - 2): gx2+gy2\sqrt{g_x^2 + g_y^2} at each valid position.

Examples

Example 1 — a flat image has no edges

Input:  img = 4×4 of all 7s
Output: 2×2 of all 0.0

Example 2 — a vertical edge lights up

Input:  img = [[0,0,9,9],[0,0,9,9],[0,0,9,9]]
Output: [[36. 36.]]

Explanation: GxG_x responds strongly to the 0→9 column transition; GyG_y is 0; magnitude =362+02=36=\sqrt{36^2+0^2}=36.

Constraints

  • Use valid (no-padding) 3×3 cross-correlation for both kernels.
  • Output shape is (H-2, W-2).
  • Combine as sqrt(gx**2 + gy**2).

Notes

  • Sobel is a hand-designed edge detector; a CNN's first layer learns a whole bank of such filters from data instead of using these fixed ones.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • Flat image example -> no edges
  • Vertical edge reference
  • Sample tiled 5x5 image