v9.1.1
Menu

Sobel Edge Magnitude and Direction

mediumFREEEdge DetectionComputer Vision 2

Given a 2D grayscale image, compute both the X and Y Sobel gradients, then derive the gradient magnitude and direction at each pixel.

The Sobel kernels are: Gx=[−101−202−101],Gy=[−1−2−1000121]G_x = \begin{bmatrix} -1 & 0 & 1 \\ -2 & 0 & 2 \\ -1 & 0 & 1 \end{bmatrix}, \quad G_y = \begin{bmatrix} -1 & -2 & -1 \\ 0 & 0 & 0 \\ 1 & 2 & 1 \end{bmatrix}

For each valid position compute:

  • Magnitude: M=Gx2+Gy2M = \sqrt{G_x^2 + G_y^2}
  • Direction: θ=atan2(Gy,Gx)\theta = \text{atan2}(G_y, G_x) in degrees

Return a tuple (magnitude_matrix, direction_matrix), both rounded to 2 decimal places.

Example

Input
image = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Output
([[25.3]], [[71.57]])
Reasoning
  • image is a 3×33 \times 3 grid of intensities that rise by 1 left to right and by 3 top to bottom. A 3×33 \times 3 kernel fits fully inside it at exactly one spot (centred on the 5), so both output grids are 1×11 \times 1; an H×WH \times W image gives (H−2)×(W−2)(H-2) \times (W-2).
  • Overlay GxG_x on the whole window: it weights the right column minus the left column, rows weighted 1,2,11, 2, 1: Gx=(3−1)+2(6−4)+(9−7)=8G_x = (3-1) + 2(6-4) + (9-7) = 8.
  • Overlay GyG_y: bottom row minus top row, columns weighted 1,2,11, 2, 1: Gy=(7+16+9)−(1+4+3)=24G_y = (7 + 16 + 9) - (1 + 4 + 3) = 24.
  • Magnitude: M=82+242=640≈25.298M = \sqrt{8^2 + 24^2} = \sqrt{640} \approx 25.298, rounded to 2 decimal places: 25.3.
  • Direction: θ=atan2(24,8)\theta = \text{atan2}(24, 8) (tangent 33) is about 71.565∘71.565^\circ, giving 71.57.
  • Notice the vertical gradient is three times the horizontal one, matching the image rising 3 per row versus 1 per column. A flat image gives 0.0 for both.

Constraints

  • Input image is a 2D list (at least 3x3)
  • Use math.sqrt and math.atan2, math.degrees
  • Return tuple of two 2D lists, each rounded to 2 decimal places

Learn this in

More from Computer Vision 2

solution.py

Test results

Sign in to run your code against the test cases.