Sobel Edge Strength From Two Gradients

Computer VisionMedium+15 XP+15

Sobel Edge Strength From Two Gradients

An edge is a place where brightness changes quickly. Sobel finds them by measuring the rate of change in two directions at once, using a pair of fixed 3×3 kernels:

Gx=[−101−202−101],Gy=[−1−2−1000121]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}Gx​=​−1−2−1​000​121​​,Gy​=​−101​−202​−101​​

Gx responds to vertical edges (brightness changing left-to-right) and Gy to horizontal ones. Combine the two into a single strength with Pythagoras:

magnitude=Gx2+Gy2\text{magnitude} = \sqrt{G_x^2 + G_y^2}magnitude=Gx2​+Gy2​​

Task: write sobel_magnitude(image) returning the edge strength at every position where the 3×3 window fits, each rounded to 4 decimal places.

  • Slide the window over the image with no padding, so an H × W image gives an (H-2) × (W-2) result. The output's top-left entry corresponds to the window anchored at the image's top-left.
  • At each position, multiply the nine pixels under the window by the matching kernel entries and add them up — without flipping the kernel. (Strictly that's correlation rather than convolution, and it's what every image-processing library does here.)
  • A flat region gives 0.0 everywhere: the weights in each kernel sum to zero, so constant brightness cancels exactly.

The 2 in the middle of each kernel is the Sobel part. It weights the pixels directly adjacent to the centre more heavily than the diagonal ones, which smooths slightly in the direction along the edge while differentiating across it — the reason Sobel is less noise-sensitive than a bare difference of neighbours.

0.0
?
?
?

Step it across one column at a time, recording a score at each stop.

Examples

image = [[0, 0, 255], [0, 0, 255], [0, 0, 255]]
returns [[1020.0]]
image = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
returns [[0.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run